Skip to content

Commit f9c65b6

Browse files
Merge remote-tracking branch 'origin/main' into fix/issue-30850
2 parents a3e4564 + 9e85538 commit f9c65b6

20 files changed

Lines changed: 6041 additions & 74 deletions

‎apps/server/src/mcp/OrchestratorMcpService.activity.test.ts‎

Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,16 @@ import {
88
ProviderInstanceId,
99
RunId,
1010
ScheduledTaskId,
11+
SECRET_REQUEST_UNSAVED_NOTE,
1112
ThreadId,
1213
TurnItemId,
1314
} from "@t3tools/contracts";
1415
import * as DateTime from "effect/DateTime";
1516
import * as Effect from "effect/Effect";
17+
import * as Fiber from "effect/Fiber";
1618
import * as Layer from "effect/Layer";
19+
import * as Metric from "effect/Metric";
20+
import * as TestClock from "effect/testing/TestClock";
1721
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
1822
import { expect, it } from "vite-plus/test";
1923

@@ -655,3 +659,185 @@ it("readThread and sendToThread reach threads in other projects", async () => {
655659
expect(stopped.code).toBe("parent_not_active");
656660
}).pipe(Effect.provide(layer), Effect.runPromise);
657661
});
662+
663+
it("requestSecret saves a pasted value to a file without opening a card", async () => {
664+
const projection = {
665+
thread: baseThread({
666+
threadId: parentThreadId,
667+
title: "Parent",
668+
instanceId: parentInstanceId,
669+
model: "gpt-5.4",
670+
}),
671+
runs: [{ ...makeRun({ id: activeRunId, ordinal: 1, status: "running" }), rootNodeId: taskId }],
672+
visibleTurnItems: [],
673+
runtimeRequests: [],
674+
messages: [],
675+
contextTransfers: [],
676+
subagents: [],
677+
updatedAt: now,
678+
} as unknown as OrchestrationV2ThreadProjection;
679+
const dispatched: Array<unknown> = [];
680+
const saved: Array<{
681+
readonly requestNamespace: string;
682+
readonly requestKey: string;
683+
readonly value: string;
684+
}> = [];
685+
const file = "/home/user/.t3/userdata/secrets/files/0123456789abcdef0123456789abcdef";
686+
687+
const layer = layerOrchestratorService.pipe(
688+
Layer.provide(
689+
Layer.mergeAll(
690+
Layer.mock(ThreadManagementService.ThreadManagementService)({
691+
getThreadRecords: (threadId) =>
692+
threadId === parentThreadId
693+
? Effect.succeed(projection)
694+
: Effect.die(`unexpected thread ${threadId}`),
695+
getThreadShell: (threadId) =>
696+
Effect.succeed(
697+
threadId === parentThreadId
698+
? (projection.thread as unknown as OrchestrationV2ThreadShell)
699+
: null,
700+
),
701+
dispatch: (command) => Effect.sync(() => void dispatched.push(command) as never),
702+
} satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
703+
ServerSettings.layerTest(),
704+
Layer.mock(ProviderRegistry.ProviderRegistry)({
705+
getProviders: Effect.succeed([]),
706+
} satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
707+
Layer.mock(ProjectService.ProjectService)({}),
708+
Layer.mock(SecretRequests.SecretRequests)({
709+
savePasted: (input) =>
710+
Effect.sync(() => {
711+
saved.push({
712+
requestNamespace: input.requestNamespace,
713+
requestKey: input.requestKey,
714+
value: input.value,
715+
});
716+
return file;
717+
}),
718+
}),
719+
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
720+
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
721+
Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({}),
722+
NodeCrypto.layer,
723+
),
724+
),
725+
);
726+
const counted = Metric.snapshot.pipe(
727+
Effect.map((snapshots) => {
728+
const found = snapshots.find(
729+
(snapshot) =>
730+
snapshot.id === "t3_secret_requests_total" &&
731+
snapshot.attributes?.status === "saved_pasted",
732+
);
733+
return found?.type === "Counter" ? Number(found.state.count) : 0;
734+
}),
735+
);
736+
737+
await Effect.gen(function* () {
738+
const service = yield* OrchestratorMcpService.OrchestratorMcpService;
739+
const before = yield* counted;
740+
const result = yield* service.requestSecret(makeScope(), {
741+
label: "Pixel PIN",
742+
reason: "Unlocks the test phone.",
743+
value: "482916",
744+
clientRequestId: "pin-1",
745+
});
746+
expect(result).toEqual({ status: "saved", file });
747+
expect(JSON.stringify(result)).not.toContain("482916");
748+
expect(saved).toEqual([
749+
{
750+
requestNamespace: "provider-session-mcp-orchestrator-detail",
751+
requestKey: "pin-1",
752+
value: "482916",
753+
},
754+
]);
755+
expect(dispatched).toEqual([]);
756+
expect((yield* counted) - before).toBe(1);
757+
758+
const asRef = yield* service
759+
.requestSecret(makeScope(), {
760+
label: "Pixel PIN",
761+
reason: "Unlocks the test phone.",
762+
value: "482916",
763+
delivery: "secretRef",
764+
})
765+
.pipe(Effect.flip);
766+
expect(asRef.code).toBe("invalid_request");
767+
expect(asRef.message).not.toContain("482916");
768+
expect(saved).toHaveLength(1);
769+
expect(dispatched).toEqual([]);
770+
}).pipe(Effect.provide(layer), Effect.runPromise);
771+
});
772+
773+
it("requestSecret returns the unsaved note for a declined, cancelled or timed-out card", async () => {
774+
const outcomes = ["declined", "cancelled", "pending"] as const;
775+
const results = await Effect.forEach(outcomes, (outcome) => {
776+
const dispatched: Array<{ readonly type: string; readonly turnItemId?: string }> = [];
777+
const projection = () => {
778+
const card = dispatched.find((command) => command.type === "secret_request.record");
779+
return {
780+
thread: baseThread({
781+
threadId: parentThreadId,
782+
title: "Parent",
783+
instanceId: parentInstanceId,
784+
model: "gpt-5.4",
785+
}),
786+
runs: [
787+
{ ...makeRun({ id: activeRunId, ordinal: 1, status: "running" }), rootNodeId: taskId },
788+
],
789+
visibleTurnItems: [],
790+
turnItems:
791+
card === undefined
792+
? []
793+
: [{ type: "secret_request", id: card.turnItemId, secretStatus: outcome }],
794+
runtimeRequests: [],
795+
messages: [],
796+
contextTransfers: [],
797+
subagents: [],
798+
updatedAt: now,
799+
} as unknown as OrchestrationV2ThreadProjection;
800+
};
801+
const layer = layerOrchestratorService.pipe(
802+
Layer.provide(
803+
Layer.mergeAll(
804+
Layer.mock(ThreadManagementService.ThreadManagementService)({
805+
getThreadRecords: () => Effect.sync(projection),
806+
getThreadShell: () =>
807+
Effect.sync(() => projection().thread as unknown as OrchestrationV2ThreadShell),
808+
dispatch: (command) => Effect.sync(() => void dispatched.push(command) as never),
809+
} satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
810+
ServerSettings.layerTest(),
811+
Layer.mock(ProviderRegistry.ProviderRegistry)({
812+
getProviders: Effect.succeed([]),
813+
} satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
814+
Layer.mock(ProjectService.ProjectService)({}),
815+
Layer.mock(SecretRequests.SecretRequests)({}),
816+
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
817+
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
818+
Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({}),
819+
NodeCrypto.layer,
820+
),
821+
),
822+
);
823+
return Effect.gen(function* () {
824+
const service = yield* OrchestratorMcpService.OrchestratorMcpService;
825+
const request = yield* service
826+
.requestSecret(makeScope(), {
827+
label: "Staging password",
828+
reason: "Signs in the QA account.",
829+
delivery: "file",
830+
timeoutMs: 1_000,
831+
})
832+
.pipe(Effect.forkChild({ startImmediately: true }));
833+
yield* TestClock.adjust("2 seconds");
834+
return yield* Fiber.join(request);
835+
}).pipe(Effect.provide(Layer.merge(layer, TestClock.layer())));
836+
}).pipe(Effect.runPromise);
837+
838+
expect(results).toEqual([
839+
{ status: "declined", note: SECRET_REQUEST_UNSAVED_NOTE.declined },
840+
{ status: "cancelled", note: SECRET_REQUEST_UNSAVED_NOTE.cancelled },
841+
{ status: "timed_out", note: SECRET_REQUEST_UNSAVED_NOTE.timed_out },
842+
]);
843+
});

‎apps/server/src/mcp/OrchestratorMcpService.ts‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ import {
6363
ThreadId,
6464
isOrchestrationV2WorkActive,
6565
resolveProjectProviderInstanceEnabled,
66+
SECRET_REQUEST_UNSAVED_NOTE,
6667
} from "@t3tools/contracts";
6768
import { getProviderOptionCurrentValue } from "@t3tools/shared/model";
6869
import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
@@ -2135,6 +2136,26 @@ const make = Effect.gen(function* () {
21352136
"Asking for a secret requires an active run owned by this MCP provider session.",
21362137
);
21372138
}
2139+
// A secret the user already pasted needs no card: it goes straight to a file.
2140+
if (input.value !== undefined) {
2141+
if (input.delivery === "secretRef") {
2142+
return yield* failure(
2143+
"invalid_request",
2144+
'A pasted `value` is saved as a file. Leave out `delivery: "secretRef"`.',
2145+
);
2146+
}
2147+
const file = yield* secretRequests
2148+
.savePasted({
2149+
threadId,
2150+
requestNamespace: scope.requestNamespace,
2151+
requestKey: yield* requestKey(input.clientRequestId),
2152+
value: input.value,
2153+
})
2154+
.pipe(Effect.mapError((error) => failure("orchestration_error", error.message)));
2155+
yield* Effect.annotateCurrentSpan({ "secret_request.status": "saved_pasted" });
2156+
yield* Metrics.increment(Metrics.secretRequestsTotal, { status: "saved_pasted" });
2157+
return { status: "saved" as const, file };
2158+
}
21382159
const runId = run.id;
21392160
const nodeId = run.rootNodeId;
21402161
const key = yield* requestKey(input.clientRequestId);
@@ -2235,7 +2256,7 @@ const make = Effect.gen(function* () {
22352256
);
22362257
yield* Effect.annotateCurrentSpan({ "secret_request.status": status });
22372258
yield* Metrics.increment(Metrics.secretRequestsTotal, { status });
2238-
if (status !== "saved") return { status };
2259+
if (status !== "saved") return { status, note: SECRET_REQUEST_UNSAVED_NOTE[status] };
22392260
if (input.delivery === "file") {
22402261
const file = yield* secretRequests
22412262
.saveToFile({ threadId, turnItemId })

‎apps/server/src/mcp/toolkits/orchestrator/tools.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ const OrchestratorCapabilitiesTool = Tool.make("orchestrator_capabilities", {
8585

8686
const DelegateTaskTool = Tool.make("delegate_task", {
8787
description:
88-
"Start one child agent with only `task`. No parent history. Separate checkout or PR per child: `isolation:'worktree'`. Keep `taskId` for `task_status` and `task_cancel`.",
88+
"Start one child agent with only `task`. No parent history. Separate checkout or PR per child: `isolation:'worktree'`. Keep `taskId` for `task_status` and `task_cancel`. No secrets in `task`.",
8989
parameters: OrchestratorMcpDelegateTaskInput,
9090
success: OrchestratorMcpDelegateTaskResult,
9191
failure: OrchestratorMcpFailure,
@@ -197,15 +197,17 @@ const DeleteScheduledTaskTool = Tool.make("delete_scheduled_task", {
197197

198198
const RequestSecretTool = Tool.make("request_secret", {
199199
description:
200-
'Ask the user to enter a secret in a private card and wait. You never see the value. Returns a one-use `secretRef` for a tool that accepts it, or with `delivery: "file"` a private file path to read inside a shell command. Asked how to provide a secret: call this now, do not explain instead.',
200+
'Ask for a secret in a private card and wait; open it, don\'t offer it. Returns a one-use `secretRef`, or with `delivery: "file"` a file to read only in its command, e.g. `adb pair <ip:port> "$(cat <file>)"`. Asked how to give one: call now. Pasted secret for child or script: `value`. Not one from an old thread.',
201201
parameters: OrchestratorMcpRequestSecretInput,
202202
success: OrchestratorMcpRequestSecretResult,
203203
failure: OrchestratorMcpFailure,
204204
failureMode: "return",
205205
dependencies,
206206
})
207207
.annotate(Tool.Title, "Request a secret from the user")
208-
.annotate(Tool.Destructive, false);
208+
.annotate(Tool.Destructive, false)
209+
// Claude Code defers MCP tools behind ToolSearch; agents that never load this one ask in chat.
210+
.annotate(Tool.Meta, { "anthropic/alwaysLoad": true });
209211

210212
const CreateThreadsTool = Tool.make("create_threads", {
211213
description:

‎apps/server/src/provider/AgentContextBudget.test.ts‎

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,22 @@ const codexAdditionalContext = () =>
106106
.map((entry) => entry.value)
107107
.join("");
108108

109+
const layerAdvertisedTools = McpHttpServer.layerTools.pipe(
110+
Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
111+
Layer.provide(toolHandlerServices),
112+
);
113+
114+
// Claude Code loads these tools up front instead of behind ToolSearch, outside this budget.
115+
it.effect("only request_secret asks Claude Code to load it up front", () =>
116+
Effect.gen(function* () {
117+
const mcp = yield* McpServer.McpServer;
118+
const alwaysLoad = mcp.tools
119+
.filter(({ tool }) => tool._meta?.["anthropic/alwaysLoad"] !== undefined)
120+
.map(({ tool }) => [tool.name, tool._meta]);
121+
expect(alwaysLoad).toEqual([["request_secret", { "anthropic/alwaysLoad": true }]]);
122+
}).pipe(Effect.provide(layerAdvertisedTools)),
123+
);
124+
109125
// CI rejects a PR that raises any value above main's agentContextBudget.json, so growth
110126
// needs the agent-context-increase label. Lower the values when the text shrinks.
111127
it.effect("agent context matches the committed budget", () =>
@@ -130,12 +146,5 @@ it.effect("agent context matches the committed budget", () =>
130146
measured,
131147
"Set agentContextBudget.json to the measured values. Before you cut text to fit, run the evals that cover it (evals/README.md).",
132148
).toEqual(budget);
133-
}).pipe(
134-
Effect.provide(
135-
McpHttpServer.layerTools.pipe(
136-
Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
137-
Layer.provide(toolHandlerServices),
138-
),
139-
),
140-
),
149+
}).pipe(Effect.provide(layerAdvertisedTools)),
141150
);
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
2-
"claudeSystemAppendBytes": 5153,
3-
"codexAdditionalContextBytes": 6883,
4-
"mcpToolListJsonBytes": 47538
2+
"claudeSystemAppendBytes": 5133,
3+
"codexAdditionalContextBytes": 6863,
4+
"mcpToolListJsonBytes": 47498
55
}

0 commit comments

Comments
 (0)