The best way to control Claude Code, Codex and more from any computer or phone
feat(server): agents ask for secrets through request_secret instead of chat (#30257)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Gabriel De Andrade committed
Nov 4, 2026 at 09:50 UTC
9e85538535c8553901351112ab02dd1dd62db5ee
10 files changed
+437
-36
apps/server/src/mcp/OrchestratorMcpService.activity.test.ts
+186
@@ -8,12 +8,16 @@ import {
8
ProviderInstanceId,
9
RunId,
10
ScheduledTaskId,
11
+ SECRET_REQUEST_UNSAVED_NOTE,
12
ThreadId,
13
TurnItemId,
14
} from "@t3tools/contracts";
15
import * as DateTime from "effect/DateTime";
16
import * as Effect from "effect/Effect";
17
+import * as Fiber from "effect/Fiber";
18
import * as Layer from "effect/Layer";
19
+import * as Metric from "effect/Metric";
20
+import * as TestClock from "effect/testing/TestClock";
21
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
22
import { expect, it } from "vite-plus/test";
23
@@ -655,3 +659,185 @@ it("readThread and sendToThread reach threads in other projects", async () => {
659
expect(stopped.code).toBe("parent_not_active");
660
}).pipe(Effect.provide(layer), Effect.runPromise);
661
});
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
+22
-1
@@ -63,6 +63,7 @@ import {
63
ThreadId,
64
isOrchestrationV2WorkActive,
65
resolveProjectProviderInstanceEnabled,
66
+ SECRET_REQUEST_UNSAVED_NOTE,
67
} from "@t3tools/contracts";
68
import { getProviderOptionCurrentValue } from "@t3tools/shared/model";
69
import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
@@ -2135,6 +2136,26 @@ const make = Effect.gen(function* () {
2136
"Asking for a secret requires an active run owned by this MCP provider session.",
2137
);
2138
}
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
+ }
2159
const runId = run.id;
2160
const nodeId = run.rootNodeId;
2161
const key = yield* requestKey(input.clientRequestId);
@@ -2235,7 +2256,7 @@ const make = Effect.gen(function* () {
2256
);
2257
yield* Effect.annotateCurrentSpan({ "secret_request.status": status });
2258
yield* Metrics.increment(Metrics.secretRequestsTotal, { status });
2238
- if (status !== "saved") return { status };
2259
+ if (status !== "saved") return { status, note: SECRET_REQUEST_UNSAVED_NOTE[status] };
2260
if (input.delivery === "file") {
2261
const file = yield* secretRequests
2262
.saveToFile({ threadId, turnItemId })
apps/server/src/mcp/toolkits/orchestrator/tools.ts
+5
-3
@@ -85,7 +85,7 @@ const OrchestratorCapabilitiesTool = Tool.make("orchestrator_capabilities", {
85
86
const DelegateTaskTool = Tool.make("delegate_task", {
87
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`.",
89
parameters: OrchestratorMcpDelegateTaskInput,
90
success: OrchestratorMcpDelegateTaskResult,
91
failure: OrchestratorMcpFailure,
@@ -197,7 +197,7 @@ const DeleteScheduledTaskTool = Tool.make("delete_scheduled_task", {
197
198
const RequestSecretTool = Tool.make("request_secret", {
199
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.',
201
parameters: OrchestratorMcpRequestSecretInput,
202
success: OrchestratorMcpRequestSecretResult,
203
failure: OrchestratorMcpFailure,
@@ -205,7 +205,9 @@ const RequestSecretTool = Tool.make("request_secret", {
205
dependencies,
206
})
207
.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 });
211
212
const CreateThreadsTool = Tool.make("create_threads", {
213
description:
apps/server/src/provider/AgentContextBudget.test.ts
+17
-8
@@ -106,6 +106,22 @@ const codexAdditionalContext = () =>
106
.map((entry) => entry.value)
107
.join("");
108
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
+
125
// CI rejects a PR that raises any value above main's agentContextBudget.json, so growth
126
// needs the agent-context-increase label. Lower the values when the text shrinks.
127
it.effect("agent context matches the committed budget", () =>
@@ -130,12 +146,5 @@ it.effect("agent context matches the committed budget", () =>
146
measured,
147
"Set agentContextBudget.json to the measured values. Before you cut text to fit, run the evals that cover it (evals/README.md).",
148
).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)),
150
);
apps/server/src/provider/agentContextBudget.json
+3
-3
@@ -1,5 +1,5 @@
1
{
2
- "claudeSystemAppendBytes": 5153,
3
- "codexAdditionalContextBytes": 6883,
4
- "mcpToolListJsonBytes": 47538
2
+ "claudeSystemAppendBytes": 5133,
3
+ "codexAdditionalContextBytes": 6863,
4
+ "mcpToolListJsonBytes": 47498
5
}
apps/server/src/secrets/SecretRequests.test.ts
+132
@@ -3,6 +3,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
3
import { assert, it } from "@effect/vitest";
4
import * as HostProcess from "@t3tools/shared/HostProcess";
5
import {
6
+ OrchestratorMcpRequestSecretInput,
7
ProjectId,
8
type OrchestrationV2ServerCommand,
9
SecretRef,
@@ -10,6 +11,7 @@ import {
11
TurnItemId,
12
} from "@t3tools/contracts";
13
import * as Effect from "effect/Effect";
14
+import * as Exit from "effect/Exit";
15
import * as FileSystem from "effect/FileSystem";
16
import * as Layer from "effect/Layer";
17
import * as Metric from "effect/Metric";
@@ -17,6 +19,7 @@ import * as Tracer from "effect/Tracer";
19
import * as Option from "effect/Option";
20
import * as Path from "effect/Path";
21
import * as PlatformError from "effect/PlatformError";
22
+import * as Schema from "effect/Schema";
23
import * as TestClock from "effect/testing/TestClock";
24
25
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
@@ -26,6 +29,8 @@ import * as SecretRequests from "./SecretRequests.ts";
29
const threadId = ThreadId.make("thread-orchestrator");
30
const turnItemId = TurnItemId.make("turn-item:secret-request:1");
31
const projectId = ProjectId.make("project-1");
32
+const decodeSecretInput = Schema.decodeUnknownEffect(OrchestratorMcpRequestSecretInput);
33
+const decodeSecretInputExit = Schema.decodeUnknownExit(OrchestratorMcpRequestSecretInput);
34
35
const withService = <A, E>(
36
body: (input: {
@@ -456,3 +461,130 @@ it.effect("a secret the card promised to keep from the agent is never written to
461
}),
462
),
463
);
464
+
465
+it.effect("a pasted secret goes straight to an owner-only file, with no card", () =>
466
+ Effect.gen(function* () {
467
+ const fs = yield* FileSystem.FileSystem;
468
+ const path = yield* Path.Path;
469
+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "secret-files-test-" });
470
+ const spans: Array<Tracer.NativeSpan> = [];
471
+ const tracer = Tracer.make({
472
+ span: (options) => {
473
+ const span = new Tracer.NativeSpan(options);
474
+ spans.push(span);
475
+ return span;
476
+ },
477
+ });
478
+ const pasted = "4829'$(id) 16";
479
+ const file = yield* withService(
480
+ ({ service, stored, dispatched }) =>
481
+ Effect.gen(function* () {
482
+ const file = yield* service.savePasted({
483
+ threadId,
484
+ requestNamespace: "session-a",
485
+ requestKey: "key-1",
486
+ value: pasted,
487
+ });
488
+ assert.equal(path.dirname(file), path.join(directory, "files"));
489
+ assert.match(path.basename(file), /^[0-9a-f]{32}$/);
490
+ assert.equal(yield* fs.readFileString(file), pasted);
491
+ if ((yield* HostProcess.Platform) !== "win32") {
492
+ assert.equal((yield* fs.stat(file)).mode & 0o777, 0o600);
493
+ assert.equal((yield* fs.stat(path.dirname(file))).mode & 0o777, 0o700);
494
+ }
495
+ // No card and no stored copy: the thread never hears of it.
496
+ assert.deepEqual(dispatched, []);
497
+ assert.deepEqual(valuesOf(stored), []);
498
+ // A retry with the same key gets the same file, unchanged even if the value differs.
499
+ assert.equal(
500
+ yield* service.savePasted({
501
+ threadId,
502
+ requestNamespace: "session-a",
503
+ requestKey: "key-1",
504
+ value: "other",
505
+ }),
506
+ file,
507
+ );
508
+ assert.equal(yield* fs.readFileString(file), pasted);
509
+ // Another key, or the same key from another provider session, gets its own file.
510
+ const other = yield* service.savePasted({
511
+ threadId,
512
+ requestNamespace: "session-a",
513
+ requestKey: "key-2",
514
+ value: "x",
515
+ });
516
+ assert.notEqual(other, file);
517
+ const otherSession = yield* service.savePasted({
518
+ threadId,
519
+ requestNamespace: "session-b",
520
+ requestKey: "key-1",
521
+ value: "y",
522
+ });
523
+ assert.notEqual(otherSession, file);
524
+ assert.equal(yield* fs.readFileString(file), pasted);
525
+ // Its name is not a ref to the value.
526
+ const ref = SecretRef.make(`secret-ref:${path.basename(file)}`);
527
+ const reused = yield* service.consume({ ref, projectId }).pipe(Effect.flip);
528
+ assert.equal(reused.reason, "ref_unavailable");
529
+ return file;
530
+ }).pipe(Effect.withTracer(tracer)),
531
+ { directory },
532
+ );
533
+ const recorded = spans.flatMap((span) => [
534
+ span.name,
535
+ ...Array.from(span.attributes.values(), String),
536
+ ]);
537
+ assert.include(recorded, "SecretRequests.savePasted");
538
+ assert.isFalse(recorded.some((value) => value.includes("4829")));
539
+
540
+ const { mtime } = yield* fs.stat(file);
541
+ yield* TestClock.setTime(Option.getOrThrow(mtime).getTime() + SECRET_FILE_TTL_MS);
542
+ yield* withService(() => Effect.void, { directory });
543
+ assert.isTrue(yield* fs.exists(file));
544
+ yield* TestClock.setTime(Option.getOrThrow(mtime).getTime() + SECRET_FILE_TTL_MS + 1);
545
+ yield* withService(() => Effect.void, { directory });
546
+ assert.isFalse(yield* fs.exists(file));
547
+ }).pipe(Effect.provide(NodeServices.layer)),
548
+);
549
+
550
+it.effect("a pasted secret keeps its exact bytes from the tool input to the file", () =>
551
+ Effect.gen(function* () {
552
+ const fs = yield* FileSystem.FileSystem;
553
+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "secret-files-test-" });
554
+ const pasted = " pa ss\tword\t ";
555
+ const input = yield* decodeSecretInput({
556
+ label: "Staging password",
557
+ reason: "Signs in the QA account.",
558
+ value: pasted,
559
+ });
560
+ assert.equal(input.value, pasted);
561
+ const empty = decodeSecretInputExit({
562
+ label: "Staging password",
563
+ reason: "Signs in the QA account.",
564
+ value: "",
565
+ });
566
+ assert.isTrue(Exit.isFailure(empty));
567
+ const file = yield* withService(
568
+ ({ service }) =>
569
+ service.savePasted({
570
+ threadId,
571
+ requestNamespace: "session-a",
572
+ requestKey: "key-1",
573
+ value: input.value!,
574
+ }),
575
+ { directory },
576
+ );
577
+ assert.equal(yield* fs.readFileString(file), pasted);
578
+ }).pipe(Effect.provide(NodeServices.layer)),
579
+);
580
+
581
+it.effect("a pasted secret is refused without a secrets directory", () =>
582
+ withService(({ service }) =>
583
+ Effect.gen(function* () {
584
+ const failed = yield* service
585
+ .savePasted({ threadId, requestNamespace: "session-a", requestKey: "key-1", value: "4829" })
586
+ .pipe(Effect.flip);
587
+ assert.equal(failed.reason, "store_failed");
588
+ }),
589
+ ),
590
+);
apps/server/src/secrets/SecretRequests.ts
+47
-15
@@ -1,6 +1,7 @@
1
// Answers stay in the secret store behind one-use refs; orchestration records only request status.
2
// Consuming tools keep values out of transcripts, projections, clients and model context.
3
// A `file` request instead moves its value to an owner-only file for the agent's own shell.
4
+// A secret the user pasted in chat goes straight to such a file, with no card.
5
import { pipe } from "effect/Function";
6
import {
7
CommandId,
@@ -66,6 +67,14 @@ export class SecretRequests extends Context.Service<
67
readonly threadId: ThreadId;
68
readonly turnItemId: string;
69
}) => Effect.Effect<string, SecretRequestError>;
70
+ /** Writes a secret the user pasted in chat to an owner-only file and returns its path. */
71
+ readonly savePasted: (input: {
72
+ readonly threadId: ThreadId;
73
+ /** The provider session's namespace, so two sessions' keys never share a file. */
74
+ readonly requestNamespace: string;
75
+ readonly requestKey: string;
76
+ readonly value: string;
77
+ }) => Effect.Effect<string, SecretRequestError>;
78
}
79
>()("t3/secrets/SecretRequests") {}
80
@@ -232,6 +241,23 @@ const make = Effect.gen(function* () {
241
return value;
242
});
243
244
+ const writeSecretFile = (dir: string, file: string, value: string) => {
245
+ const partial = `${file}.partial`;
246
+ return fileSystem.makeDirectory(dir, { recursive: true, mode: 0o700 }).pipe(
247
+ Effect.andThen(fileSystem.chmod(dir, 0o700)),
248
+ Effect.andThen(fileSystem.remove(partial, { force: true })),
249
+ // `wx` never follows or replaces an existing path.
250
+ Effect.andThen(
251
+ fileSystem.writeFile(partial, new TextEncoder().encode(value), {
252
+ flag: "wx",
253
+ mode: 0o600,
254
+ }),
255
+ ),
256
+ Effect.andThen(fileSystem.rename(partial, file)),
257
+ Effect.mapError((cause) => new SecretRequestError({ reason: "store_failed", cause })),
258
+ );
259
+ };
260
+
261
const saveToFile: SecretRequests["Service"]["saveToFile"] = Effect.fn(
262
"SecretRequests.saveToFile",
263
)(function* (input) {
@@ -266,24 +292,30 @@ const make = Effect.gen(function* () {
292
}
293
// The stored value goes only after the file is complete, so a failed write can retry.
294
const value = yield* readRef({ ref, projectId: records.thread.projectId });
269
- const partial = `${file}.partial`;
270
- yield* fileSystem.makeDirectory(filesDir, { recursive: true, mode: 0o700 }).pipe(
271
- Effect.andThen(fileSystem.chmod(filesDir, 0o700)),
272
- Effect.andThen(fileSystem.remove(partial, { force: true })),
273
- // `wx` never follows or replaces an existing path.
274
- Effect.andThen(
275
- fileSystem.writeFile(partial, new TextEncoder().encode(value), {
276
- flag: "wx",
277
- mode: 0o600,
278
- }),
279
- ),
280
- Effect.andThen(fileSystem.rename(partial, file)),
281
- Effect.mapError((cause) => new SecretRequestError({ reason: "store_failed", cause })),
282
- );
295
+ yield* writeSecretFile(filesDir, file, value);
296
return yield* removeStored;
297
}).pipe(consumeLock.withPermits(1));
298
});
299
300
+ const savePasted: SecretRequests["Service"]["savePasted"] = Effect.fn(
301
+ "SecretRequests.savePasted",
302
+ )(function* (input) {
303
+ if (filesDir === undefined) return yield* new SecretRequestError({ reason: "store_failed" });
304
+ const ref = refFor(
305
+ salt,
306
+ input.threadId,
307
+ `pasted\u0000${input.requestNamespace}\u0000${input.requestKey}`,
308
+ );
309
+ const file = path.join(filesDir, ref.slice(SECRET_REF_PREFIX.length));
310
+ // A retry with the same clientRequestId gets the file the first call wrote, unchanged, so a
311
+ // command already holding that path never reads another value.
312
+ return yield* Effect.gen(function* () {
313
+ if (yield* fileSystem.exists(file).pipe(Effect.orElseSucceed(() => false))) return file;
314
+ yield* writeSecretFile(filesDir, file, input.value);
315
+ return file;
316
+ }).pipe(consumeLock.withPermits(1));
317
+ });
318
+
319
const sweepExpired = Effect.gen(function* () {
320
if (store.directory === undefined) return;
321
const now = yield* Clock.currentTimeMillis;
@@ -330,7 +362,7 @@ const make = Effect.gen(function* () {
362
Effect.forkScoped,
363
);
364
333
- return SecretRequests.of({ answer, savedRef, consume, saveToFile });
365
+ return SecretRequests.of({ answer, savedRef, consume, saveToFile, savePasted });
366
});
367
368
export const layer = Layer.effect(SecretRequests, make);
packages/contracts/src/orchestratorMcp.ts
+14
-5
@@ -728,6 +728,11 @@ export const OrchestratorMcpUpdateScheduledTaskInput = Schema.Struct({
728
export type OrchestratorMcpUpdateScheduledTaskInput =
729
typeof OrchestratorMcpUpdateScheduledTaskInput.Type;
730
731
+// Not trimmed: whitespace in a password matters. The check stays out of the advertised schema.
732
+const PastedSecretValue = Schema.String.check(
733
+ Schema.makeFilter((value: string) => value.length > 0, { expected: "a non-empty string" }),
734
+);
735
+
736
export const OrchestratorMcpRequestSecretInput = Schema.Struct({
737
label: TrimmedNonEmptyString.annotate({
738
description: "Card title, such as 'GitHub webhook secret'.",
@@ -737,14 +742,17 @@ export const OrchestratorMcpRequestSecretInput = Schema.Struct({
742
}),
743
placeholder: Schema.optional(TrimmedNonEmptyString),
744
delivery: Schema.optional(Schema.Literals(["secretRef", "file"])).annotate({
740
- description:
741
- 'secretRef (default) for a T3 tool. file for a shell CLI: read the path in your command, e.g. TOKEN="$(cat <file>)" wrangler whoami.',
745
+ description: "secretRef (default) for a T3 tool; file for a command.",
746
}),
747
+ value: Schema.optional(PastedSecretValue).annotate({
748
+ description: "Pasted in this thread; no card.",
749
+ }),
750
+ /** Default 10 minutes. */
751
timeoutMs: Schema.optional(
752
Schema.Int.check(Schema.isBetween({ minimum: 1_000, maximum: 60 * 60 * 1_000 })),
745
- ).annotate({ description: "Default 10 min." }),
753
+ ),
754
clientRequestId: Schema.optional(OrchestratorMcpClientRequestId).annotate({
747
- description: "Retry key for this ask. New key after a timeout or cancel.",
755
+ description: "Retry key.",
756
}),
757
});
758
export type OrchestratorMcpRequestSecretInput = typeof OrchestratorMcpRequestSecretInput.Type;
@@ -766,8 +774,9 @@ export const OrchestratorMcpRequestSecretResult = Schema.Union([
774
Schema.Struct({
775
status: Schema.Literals(["declined", "cancelled", "timed_out"]).annotate({
776
description:
769
- "declined: user chose not to. cancelled: ended with the run. timed_out: no answer in time. Ask again with a new `clientRequestId` if still needed.",
777
+ "declined: user chose not to; don't ask again. cancelled: ended with the run. timed_out: no answer in time. After cancelled or timed_out, ask again with a new `clientRequestId` only if still needed.",
778
}),
779
+ note: Schema.optional(Schema.String).annotate({ description: "What to do next." }),
780
}),
781
]);
782
export type OrchestratorMcpRequestSecretResult = typeof OrchestratorMcpRequestSecretResult.Type;
packages/contracts/src/secretRequest.ts
+10
@@ -13,6 +13,16 @@ export const SecretRequestAnswerInput = Schema.Struct({
13
});
14
export type SecretRequestAnswerInput = typeof SecretRequestAnswerInput.Type;
15
16
+/** What the agent reads when its card ends without a secret. */
17
+export const SECRET_REQUEST_UNSAVED_NOTE = {
18
+ declined:
19
+ "The user declined. Don't ask for it in chat or another way; say what's blocked and go on without it.",
20
+ cancelled:
21
+ "The card closed with the run. Ask again with a new clientRequestId only if the secret is still needed.",
22
+ timed_out:
23
+ "No answer in time. Don't ask in chat; ask again with a new clientRequestId only if it is still needed.",
24
+} as const;
25
+
26
const SECRET_REQUEST_FAILURE_MESSAGES = {
27
load_failed: "Could not load the secret request.",
28
not_found: "This secret request no longer exists.",
packages/provider-core/src/server/orchestrationInstructions.ts
+1
-1
@@ -16,7 +16,7 @@ Ordinary coding tasks need no T3 tools.
16
- Another machine: \`t3_environment_links\` lists linked ones. Pass its \`environmentId\` to a T3 tool to act there. Ids are then that machine's, so pass \`threadId\`.
17
- A machine the user names that is not linked ("delegate this to my vps"): call \`t3_environment_link\` with a \`hint\` from their words. Never ask for a pairing code in chat.
18
- In your reply, mention a thread by its \`link\`, verbatim. Never a plain title or bare id.
19
-- A secret: call \`request_secret\` yourself. Pass its \`secretRef\` to a T3 tool, or use \`delivery: "file"\` for a shell command. Never ask in chat or invent one. When asked only to schedule, \`schedule_task\` without running its prompt.
19
+- A login, token, PIN or pairing code only the user can give: call \`request_secret\`, not a chat ask or a handoff. Not for access you have. When asked only to schedule, \`schedule_task\` without running its prompt.
20
- T3 tools may load late. Try the name once before you call it absent.`,
21
`### Visuals and preview
22