Skip to content
TypeScript

feat(server): request_secret can save a CLI token to a private file (#24809)

Theo Brownee0b194021b15
diff --git a/apps/mobile/src/features/threads/SecretRequestCard.tsx b/apps/mobile/src/features/threads/SecretRequestCard.tsx
index 02d773c13f1..0112257fec7 100644
--- a/apps/mobile/src/features/threads/SecretRequestCard.tsx
+++ b/apps/mobile/src/features/threads/SecretRequestCard.tsx
@@ -1,9 +1,9 @@
import {
SECRET_REQUEST_DEFAULT_PLACEHOLDER,
- SECRET_REQUEST_PRIVACY_NOTE,
secretRequestAnswerInput,
secretRequestDisplay,
secretRequestFailureMessage,
+ secretRequestPrivacyNote,
type SecretRequestItem,
} from "@t3tools/client-runtime/secret-request";
import {
@@ -144,7 +144,7 @@ function PendingSecretRequestForm(props: {
type="monochrome"
/>
<Text className="flex-1 font-sans text-xs text-foreground-muted">
- {SECRET_REQUEST_PRIVACY_NOTE}
+ {secretRequestPrivacyNote(item)}
</Text>
</View>
<Button
diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts
index 0df296db5bc..d69a8649d13 100644
--- a/apps/server/src/mcp/OrchestratorMcpService.ts
+++ b/apps/server/src/mcp/OrchestratorMcpService.ts
@@ -1969,6 +1969,7 @@ const make = Effect.gen(function* () {
label: input.label,
reason: input.reason,
...(input.placeholder === undefined ? {} : { placeholder: input.placeholder }),
+ ...(input.delivery === "file" ? { delivery: "file" as const } : {}),
secretStatus,
})
.pipe(
@@ -2047,6 +2048,12 @@ const make = Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({ "secret_request.status": status });
yield* Metrics.increment(Metrics.secretRequestsTotal, { status });
if (status !== "saved") return { status };
+ if (input.delivery === "file") {
+ const file = yield* secretRequests
+ .saveToFile({ threadId, turnItemId })
+ .pipe(Effect.mapError((error) => failure("orchestration_error", error.message)));
+ return { status, file };
+ }
const secretRef = yield* secretRequests.savedRef({ threadId: threadId, turnItemId });
if (Option.isNone(secretRef)) {
return yield* failure(
diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts
index c193a0afb15..2b56e12b025 100644
--- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts
+++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts
@@ -189,7 +189,7 @@ const DeleteScheduledTaskTool = Tool.make("delete_scheduled_task", {
const RequestSecretTool = Tool.make("request_secret", {
description:
- "Ask the user for a secret (a token, API key, signing secret, password) through a private card in this thread, and wait for them to answer. The value is kept by the app and NEVER returned to you or shown in the transcript. When saved, the result carries a secretRef: pass it to a tool that accepts one (e.g. schedule_task's signature.secretRef). It works once. Never ask for secrets in chat, and never invent one.",
+ "Ask the user for a secret (a token, API key, signing secret, password) through a private card in this thread, and wait for them to answer. The value is NEVER returned to you or shown in the transcript. By default the result carries a one-use secretRef for a tool that accepts one (e.g. schedule_task's signature.secretRef). For a shell CLI token, set delivery to file. Never ask for secrets in chat, and never invent one.",
parameters: OrchestratorMcpRequestSecretInput,
success: OrchestratorMcpRequestSecretResult,
failure: OrchestratorMcpFailure,
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index 13ae0a48fa1..8087cb4781e 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -7749,6 +7749,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
label: command.label,
reason: command.reason,
...(command.placeholder === undefined ? {} : { placeholder: command.placeholder }),
+ ...(command.delivery === undefined ? {} : { delivery: command.delivery }),
secretStatus: command.secretStatus,
};
yield* emit(
diff --git a/apps/server/src/secrets/SecretRequests.test.ts b/apps/server/src/secrets/SecretRequests.test.ts
index ffb8cd314d8..f9bb937f7bd 100644
--- a/apps/server/src/secrets/SecretRequests.test.ts
+++ b/apps/server/src/secrets/SecretRequests.test.ts
@@ -1,18 +1,23 @@
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
+import * as HostProcess from "@t3tools/shared/HostProcess";
import {
ProjectId,
type OrchestrationV2ServerCommand,
+ SecretRef,
ThreadId,
TurnItemId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Metric from "effect/Metric";
import * as Tracer from "effect/Tracer";
import * as Option from "effect/Option";
+import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
+import * as TestClock from "effect/testing/TestClock";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
@@ -30,6 +35,8 @@ const withService = <A, E>(
}) => Effect.Effect<A, E>,
options: {
readonly threadId?: ThreadId;
+ readonly delivery?: "file";
+ readonly directory?: string;
readonly runStatus?: string;
readonly removeFails?: boolean;
readonly closedFirst?: boolean;
@@ -48,6 +55,7 @@ const withService = <A, E>(
Layer.succeed(
ServerSecretStore.ServerSecretStore,
ServerSecretStore.ServerSecretStore.of({
+ ...(options.directory === undefined ? {} : { directory: options.directory }),
get: (name) => Effect.yieldNow.pipe(Effect.as(Option.fromNullishOr(stored.get(name)))),
set: (name, value) => Effect.sync(() => void stored.set(name, value)),
create: (name, value) =>
@@ -98,6 +106,7 @@ const withService = <A, E>(
type: "secret_request",
label: "GitHub token",
reason: "Used as GH_TOKEN.",
+ ...(options.delivery === undefined ? {} : { delivery: options.delivery }),
secretStatus,
},
],
@@ -338,3 +347,113 @@ it.effect("a used value that cannot be deleted is not handed out", () =>
{ removeFails: true },
),
);
+
+const SECRET_FILE_TTL_MS = 24 * 60 * 60 * 1000;
+
+it.effect("a file request moves its value to an owner-only file, once", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "secret-files-test-" });
+ const file = yield* withService(
+ ({ service, stored, dispatched }) =>
+ Effect.gen(function* () {
+ yield* service.answer({
+ threadId,
+ turnItemId,
+ answer: { type: "save", secret: "cf_token'$(id)" },
+ });
+ assert.include(dispatched[0] as object, { secretStatus: "saved", delivery: "file" });
+ const file = yield* service.saveToFile({ threadId, turnItemId });
+ assert.equal(yield* fs.readFileString(file), "cf_token'$(id)");
+ assert.deepEqual(valuesOf(stored), []);
+ if ((yield* HostProcess.Platform) !== "win32") {
+ assert.equal((yield* fs.stat(file)).mode & 0o777, 0o600);
+ assert.equal((yield* fs.stat(path.dirname(file))).mode & 0o777, 0o700);
+ }
+ // A retried request_secret gets the same file; the value is never a ref again.
+ assert.equal(yield* service.saveToFile({ threadId, turnItemId }), file);
+ const ref = SecretRef.make(`secret-ref:${path.basename(file)}`);
+ const reused = yield* service.consume({ ref, projectId }).pipe(Effect.flip);
+ assert.equal(reused.reason, "ref_unavailable");
+ return file;
+ }),
+ { delivery: "file", directory },
+ );
+
+ const { mtime } = yield* fs.stat(file);
+ yield* TestClock.setTime(Option.getOrThrow(mtime).getTime() + SECRET_FILE_TTL_MS);
+ yield* withService(() => Effect.void, { directory });
+ assert.isTrue(yield* fs.exists(file));
+ yield* TestClock.setTime(Option.getOrThrow(mtime).getTime() + SECRET_FILE_TTL_MS + 1);
+ yield* withService(() => Effect.void, { directory });
+ assert.isFalse(yield* fs.exists(file));
+ }).pipe(Effect.provide(NodeServices.layer)),
+);
+
+it.effect("a failed file write keeps the value, so the request can retry", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "secret-files-test-" });
+ yield* withService(
+ ({ service }) =>
+ Effect.gen(function* () {
+ yield* service.answer({
+ threadId,
+ turnItemId,
+ answer: { type: "save", secret: "cf_token" },
+ });
+ const ref = Option.getOrThrow(yield* service.savedRef({ threadId, turnItemId }));
+ const name = ref.slice("secret-ref:".length);
+ // A non-empty directory where the partial file goes makes the write fail.
+ const partial = path.join(directory, "files", `${name}.partial`);
+ yield* fs.makeDirectory(path.join(partial, "block"), { recursive: true });
+ const failed = yield* service.saveToFile({ threadId, turnItemId }).pipe(Effect.flip);
+ assert.equal(failed.reason, "store_failed");
+ yield* fs.remove(partial, { recursive: true });
+ const file = yield* service.saveToFile({ threadId, turnItemId });
+ assert.equal(yield* fs.readFileString(file), "cf_token");
+ }),
+ { delivery: "file", directory },
+ );
+ }).pipe(Effect.provide(NodeServices.layer)),
+);
+
+it.effect("a file is not delivered while its stored copy cannot be removed", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "secret-files-test-" });
+ yield* withService(
+ ({ service }) =>
+ Effect.gen(function* () {
+ yield* service.answer({
+ threadId,
+ turnItemId,
+ answer: { type: "save", secret: "cf_token" },
+ });
+ const first = yield* service.saveToFile({ threadId, turnItemId }).pipe(Effect.flip);
+ assert.equal(first.reason, "consume_failed");
+ // A retry finds the file but still will not hand it out until the removal works.
+ const retried = yield* service.saveToFile({ threadId, turnItemId }).pipe(Effect.flip);
+ assert.equal(retried.reason, "consume_failed");
+ }),
+ { delivery: "file", directory, removeFails: true },
+ );
+ }).pipe(Effect.provide(NodeServices.layer)),
+);
+
+it.effect("a secret the card promised to keep from the agent is never written to a file", () =>
+ withService(({ service, stored }) =>
+ Effect.gen(function* () {
+ yield* service.answer({
+ threadId,
+ turnItemId,
+ answer: { type: "save", secret: "ghp_secret" },
+ });
+ const refused = yield* service.saveToFile({ threadId, turnItemId }).pipe(Effect.flip);
+ assert.equal(refused.reason, "not_a_file_request");
+ assert.isTrue(valuesOf(stored).some((value) => value.includes("ghp_secret")));
+ }),
+ ),
+);
diff --git a/apps/server/src/secrets/SecretRequests.ts b/apps/server/src/secrets/SecretRequests.ts
index 80960bbee53..7c8e961dbd2 100644
--- a/apps/server/src/secrets/SecretRequests.ts
+++ b/apps/server/src/secrets/SecretRequests.ts
@@ -1,5 +1,6 @@
// Answers stay in the secret store behind one-use refs; orchestration records only request status.
// Consuming tools keep values out of transcripts, projections, clients and model context.
+// A `file` request instead moves its value to an owner-only file for the agent's own shell.
import {
CommandId,
SecretRef,
@@ -17,6 +18,7 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
+import * as Path from "effect/Path";
import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
@@ -30,6 +32,7 @@ const storeName = (ref: SecretRef) => `secret-request-${ref.slice(SECRET_REF_PRE
const REF_PATTERN = /^secret-ref:[0-9a-f]{32}$/;
const SECRET_REF_TTL_MS = 24 * 60 * 60 * 1000;
const STORE_NAME_PATTERN = /^(secret-request-[0-9a-f]{32})\.bin$/;
+const FILE_NAME_PATTERN = /^[0-9a-f]{32}(\.partial)?$/;
const refFor = (salt: string, threadId: ThreadId, turnItemId: string) =>
SecretRef.make(
@@ -57,13 +60,21 @@ export class SecretRequests extends Context.Service<
readonly ref: SecretRef;
readonly projectId: ProjectId;
}) => Effect.Effect<string, SecretRequestError>;
+ /** Moves a saved `file` request's value to an owner-only file and returns its path. */
+ readonly saveToFile: (input: {
+ readonly threadId: ThreadId;
+ readonly turnItemId: string;
+ }) => Effect.Effect<string, SecretRequestError>;
}
>()("t3/secrets/SecretRequests") {}
const make = Effect.gen(function* () {
const store = yield* ServerSecretStore.ServerSecretStore;
const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
const threadManagement = yield* ThreadManagementService.ThreadManagementService;
+ // Beside the store's own files so the same owner-only directory and cleanup rules apply.
+ const filesDir = store.directory === undefined ? undefined : path.join(store.directory, "files");
const salt = Buffer.from(
yield* store.getOrCreateRandom("secret-request-salt", 32).pipe(Effect.orDie),
@@ -124,6 +135,7 @@ const make = Effect.gen(function* () {
label: item.label,
reason: item.reason,
...(item.placeholder === undefined ? {} : { placeholder: item.placeholder }),
+ ...(item.delivery === undefined ? {} : { delivery: item.delivery }),
secretStatus,
})
.pipe(
@@ -183,7 +195,8 @@ const make = Effect.gen(function* () {
Effect.withSpan("SecretRequests.consume"),
);
- const consumeRef = Effect.fn("SecretRequests.consumeRef")(function* (input: {
+ /** A live ref's value, left in the store. */
+ const readRef = Effect.fn("SecretRequests.readRef")(function* (input: {
readonly ref: SecretRef;
readonly projectId: ProjectId;
}) {
@@ -202,12 +215,72 @@ const make = Effect.gen(function* () {
yield* removeLogged(storeName(input.ref));
return yield* new SecretRequestError({ reason: "ref_expired" });
}
+ return decoded.value.value;
+ });
+
+ const consumeRef = Effect.fn("SecretRequests.consumeRef")(function* (input: {
+ readonly ref: SecretRef;
+ readonly projectId: ProjectId;
+ }) {
+ const value = yield* readRef(input);
// One use: the value moves into whatever consumed it. If it cannot be
// deleted, it is not handed out, so a ref is never used twice.
if (!(yield* removeLogged(storeName(input.ref)))) {
return yield* new SecretRequestError({ reason: "consume_failed" });
}
- return decoded.value.value;
+ return value;
+ });
+
+ const saveToFile: SecretRequests["Service"]["saveToFile"] = Effect.fn(
+ "SecretRequests.saveToFile",
+ )(function* (input) {
+ const records = yield* threadManagement
+ .getThreadRecords(input.threadId, ["turnItems"], {
+ turnItemTypes: ["secret_request"],
+ messageRoles: [],
+ })
+ .pipe(Effect.mapError((cause) => new SecretRequestError({ reason: "load_failed", cause })));
+ const item = records.turnItems.find((candidate) => candidate.id === input.turnItemId);
+ // Only a card that told the user the agent's commands can read the value may write it out.
+ if (
+ item?.type !== "secret_request" ||
+ item.secretStatus !== "saved" ||
+ item.delivery !== "file"
+ ) {
+ return yield* new SecretRequestError({ reason: "not_a_file_request" });
+ }
+ if (filesDir === undefined) return yield* new SecretRequestError({ reason: "store_failed" });
+ const ref = refFor(salt, input.threadId, item.id);
+ const file = path.join(filesDir, ref.slice(SECRET_REF_PREFIX.length));
+ return yield* Effect.gen(function* () {
+ // One use: the file counts as delivered only once the stored copy is gone. A retry with the
+ // same clientRequestId gets the file the first call wrote and finishes that removal.
+ const removeStored = removeLogged(storeName(ref)).pipe(
+ Effect.flatMap((removed) =>
+ removed ? Effect.succeed(file) : new SecretRequestError({ reason: "consume_failed" }),
+ ),
+ );
+ if (yield* fileSystem.exists(file).pipe(Effect.orElseSucceed(() => false))) {
+ return yield* removeStored;
+ }
+ // The stored value goes only after the file is complete, so a failed write can retry.
+ const value = yield* readRef({ ref, projectId: records.thread.projectId });
+ const partial = `${file}.partial`;
+ yield* fileSystem.makeDirectory(filesDir, { recursive: true, mode: 0o700 }).pipe(
+ Effect.andThen(fileSystem.chmod(filesDir, 0o700)),
+ Effect.andThen(fileSystem.remove(partial, { force: true })),
+ // `wx` never follows or replaces an existing path.
+ Effect.andThen(
+ fileSystem.writeFile(partial, new TextEncoder().encode(value), {
+ flag: "wx",
+ mode: 0o600,
+ }),
+ ),
+ Effect.andThen(fileSystem.rename(partial, file)),
+ Effect.mapError((cause) => new SecretRequestError({ reason: "store_failed", cause })),
+ );
+ return yield* removeStored;
+ }).pipe(consumeLock.withPermits(1));
});
const sweepExpired = Effect.gen(function* () {
@@ -231,14 +304,32 @@ const make = Effect.gen(function* () {
Effect.catchCause((cause) => Effect.logWarning("Could not sweep expired secret refs", cause)),
Effect.withSpan("SecretRequests.sweepExpired"),
);
- yield* sweepExpired;
- yield* sweepExpired.pipe(
+ const sweepExpiredFiles = Effect.gen(function* () {
+ if (filesDir === undefined || !(yield* fileSystem.exists(filesDir))) return;
+ const now = yield* Clock.currentTimeMillis;
+ let removed = 0;
+ for (const name of yield* fileSystem.readDirectory(filesDir)) {
+ if (!FILE_NAME_PATTERN.test(name)) continue;
+ const file = path.join(filesDir, name);
+ const { mtime } = yield* fileSystem.stat(file);
+ if (Option.exists(mtime, (time) => now - time.getTime() <= SECRET_REF_TTL_MS)) continue;
+ yield* fileSystem.remove(file);
+ removed += 1;
+ }
+ yield* Effect.annotateCurrentSpan({ "secret_request.expired_files_removed": removed });
+ }).pipe(
+ Effect.catchCause((cause) => Effect.logWarning("Could not sweep expired secret files", cause)),
+ Effect.withSpan("SecretRequests.sweepExpiredFiles"),
+ );
+ const sweep = Effect.andThen(sweepExpired, sweepExpiredFiles);
+ yield* sweep;
+ yield* sweep.pipe(
Effect.delay("1 hour"),
Effect.repeat(Schedule.spaced("1 hour")),
Effect.forkScoped,
);
- return SecretRequests.of({ answer, savedRef, consume });
+ return SecretRequests.of({ answer, savedRef, consume, saveToFile });
});
export const layer = Layer.effect(SecretRequests, make);
diff --git a/apps/web/src/components/chat/SecretRequestCard.tsx b/apps/web/src/components/chat/SecretRequestCard.tsx
index ca980b902fd..f8dc7579adc 100644
--- a/apps/web/src/components/chat/SecretRequestCard.tsx
+++ b/apps/web/src/components/chat/SecretRequestCard.tsx
@@ -1,9 +1,9 @@
import {
SECRET_REQUEST_DEFAULT_PLACEHOLDER,
- SECRET_REQUEST_PRIVACY_NOTE,
secretRequestAnswerInput,
secretRequestDisplay,
secretRequestFailureMessage,
+ secretRequestPrivacyNote,
type SecretRequestItem,
} from "@t3tools/client-runtime/secret-request";
import {
@@ -150,7 +150,7 @@ function PendingSecretRequestForm(props: {
className="flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground"
>
<ShieldCheckIcon className="size-3.5 shrink-0" aria-hidden />
- {SECRET_REQUEST_PRIVACY_NOTE}
+ {secretRequestPrivacyNote(item)}
</p>
<Button
type="button"
diff --git a/packages/client-runtime/src/secretRequest.test.ts b/packages/client-runtime/src/secretRequest.test.ts
index 08db52bb644..57d4c4f49a8 100644
--- a/packages/client-runtime/src/secretRequest.test.ts
+++ b/packages/client-runtime/src/secretRequest.test.ts
@@ -1,7 +1,11 @@
import { SecretRequestError } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
-import { secretRequestDisplay, secretRequestFailureMessage } from "./secretRequest.ts";
+import {
+ secretRequestDisplay,
+ secretRequestFailureMessage,
+ secretRequestPrivacyNote,
+} from "./secretRequest.ts";
describe("secretRequestDisplay", () => {
it("never offers the form for a request inherited from another thread", () => {
@@ -15,6 +19,13 @@ describe("secretRequestDisplay", () => {
});
});
+describe("secretRequestPrivacyNote", () => {
+ it("does not promise to hide a value that the agent's commands can read", () => {
+ expect(secretRequestPrivacyNote({})).toBe("Stored securely, never shown to the agent");
+ expect(secretRequestPrivacyNote({ delivery: "file" })).not.toContain("never shown");
+ });
+});
+
describe("secretRequestFailureMessage", () => {
it("passes through server errors but hides anything that could echo the payload", () => {
expect(
diff --git a/packages/client-runtime/src/secretRequest.ts b/packages/client-runtime/src/secretRequest.ts
index 91640c0958c..c6ec7ce95f2 100644
--- a/packages/client-runtime/src/secretRequest.ts
+++ b/packages/client-runtime/src/secretRequest.ts
@@ -5,7 +5,11 @@ export type SecretRequestItem = Extract<
{ readonly type: "secret_request" }
>;
-export const SECRET_REQUEST_PRIVACY_NOTE = "Stored securely, never shown to the agent";
+/** A `file` request lets the agent's commands read the value, so its card must not promise more. */
+export const secretRequestPrivacyNote = (item: Pick<SecretRequestItem, "delivery">) =>
+ item.delivery === "file"
+ ? "Kept out of chat, in a private file this agent's commands can read for 24 hours"
+ : "Stored securely, never shown to the agent";
export const SECRET_REQUEST_DEFAULT_PLACEHOLDER = "Paste the secret";
export type SecretRequestDisplay =
diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts
index 6aa4ea7bbe6..b4a6f4abc0a 100644
--- a/packages/contracts/src/orchestrationV2.ts
+++ b/packages/contracts/src/orchestrationV2.ts
@@ -1391,11 +1391,15 @@ export const OrchestrationV2SecretRequestStatus = Schema.Literals([
]);
export type OrchestrationV2SecretRequestStatus = typeof OrchestrationV2SecretRequestStatus.Type;
+/** `file`: the value goes to an owner-only file the agent's shell commands can read. */
+export const OrchestrationV2SecretRequestDelivery = Schema.Literal("file");
+
const OrchestrationV2SecretRequestFields = {
type: Schema.Literal("secret_request"),
label: TrimmedNonEmptyString,
reason: Schema.String,
placeholder: Schema.optional(Schema.String),
+ delivery: Schema.optional(OrchestrationV2SecretRequestDelivery),
secretStatus: OrchestrationV2SecretRequestStatus,
} as const;
@@ -3230,6 +3234,7 @@ const OrchestrationV2InternalCommand = Schema.Union([
label: TrimmedNonEmptyString,
reason: Schema.String,
placeholder: Schema.optional(Schema.String),
+ delivery: Schema.optional(OrchestrationV2SecretRequestDelivery),
secretStatus: OrchestrationV2SecretRequestStatus,
}),
]);
diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts
index 49924b06867..2c0cc5693b3 100644
--- a/packages/contracts/src/orchestratorMcp.ts
+++ b/packages/contracts/src/orchestratorMcp.ts
@@ -670,6 +670,10 @@ export const OrchestratorMcpRequestSecretInput = Schema.Struct({
placeholder: Schema.optional(TrimmedNonEmptyString).annotate({
description: "Hint inside the input, e.g. 'Paste your GitHub token'.",
}),
+ delivery: Schema.optional(Schema.Literals(["secretRef", "file"])).annotate({
+ description:
+ 'secretRef (default): for a T3 tool that takes one. file: for a shell CLI; the result is a private file path to read inside your command, e.g. CLOUDFLARE_API_TOKEN="$(cat <file>)" wrangler whoami.',
+ }),
timeoutMs: Schema.optional(
Schema.Int.check(Schema.isBetween({ minimum: 1_000, maximum: 60 * 60 * 1_000 })),
).annotate({ description: "How long to wait for the user. Default 10 minutes." }),
@@ -688,6 +692,13 @@ export const OrchestratorMcpRequestSecretResult = Schema.Union([
"Pass it to a tool that accepts a secretRef; it works once, and you never see the value.",
}),
}),
+ Schema.Struct({
+ status: Schema.Literal("saved").annotate({ description: "file holds the value." }),
+ file: Schema.String.annotate({
+ description:
+ "Owner-only file with the value. Read it inside commands and never print it. Deleted after 24 hours.",
+ }),
+ }),
Schema.Struct({
status: Schema.Literals(["declined", "cancelled", "timed_out"]).annotate({
description:
diff --git a/packages/contracts/src/secretRequest.ts b/packages/contracts/src/secretRequest.ts
index 9f490383542..2506d064b53 100644
--- a/packages/contracts/src/secretRequest.ts
+++ b/packages/contracts/src/secretRequest.ts
@@ -26,6 +26,8 @@ const SECRET_REQUEST_FAILURE_MESSAGES = {
"That secretRef was already used or does not exist. Ask the user again with request_secret.",
ref_expired: "That secretRef expired. Ask the user again with request_secret.",
consume_failed: "Could not use that secretRef. Try again.",
+ not_a_file_request:
+ 'The user did not save this secret for shell use. Ask again with request_secret and delivery: "file".',
} as const;
export const SecretRequestFailureReason = Schema.Literals(
diff --git a/packages/provider-core/src/server/orchestrationInstructions.ts b/packages/provider-core/src/server/orchestrationInstructions.ts
index e5c555af38f..91235b5ec92 100644
--- a/packages/provider-core/src/server/orchestrationInstructions.ts
+++ b/packages/provider-core/src/server/orchestrationInstructions.ts
@@ -10,7 +10,7 @@ The \`t3-code\` MCP server provides app-owned orchestration. Treat these concept
- \`t3_thread_launch\` and \`create_threads\` create ordinary top-level T3 conversations. Use them only when the user explicitly asks for separate/new/top-level threads or conversations. Never use them merely because the user said "subagent" or requested parallel delegated work.
- For independent T3 delegated review rounds, call \`delegate_task\` again. Include the original brief, prior findings, responses, and unresolved objections in each new task prompt. Track each round by its own \`taskId\`. Use a distinct \`clientRequestId\` per round, stable across retries of that round. For a follow-up that needs the same child's conversation, use \`t3_thread_send\` on its \`childThreadId\`.`,
`- \`schedule_task\` creates persistent recurring work in the app scheduler. Pass \`schedule\` as a structured object, never as JSON text: \`{"type":"interval","everyMs":3600000}\` for an interval, or \`{"type":"fixed_time","timeOfDay":"09:00","weekdays":[1,2,3,4,5]}\` for a wall-clock schedule, or \`{"type":"webhook"}\` to run on each request to the returned \`webhookUrl\` (the run sees the request only through \`{{body.path}}\`-style placeholders in the prompt). By default runs return to the current thread, which suits orchestrating: each trigger arrives here and you delegate or dedupe; set \`bindToCurrentThread=false\` only when the user wants a fresh thread for every run. After scheduling a timer, report the returned cadence and next run time; for a webhook, report its \`webhookUrl\`, or say T3 Connect remote access is needed if it is missing.
-- When you need a secret from the user (a token, API key, or webhook signing secret), call \`request_secret\` so they enter it privately, then pass the returned \`secretRef\` to the tool that needs it, e.g. \`signature.secretRef\` on a webhook task for a sender that signs requests such as GitHub. A \`secretRef\` works once. Never ask for a secret in chat, never invent one, and never repeat one.
+- When you need a secret from the user (a token, API key, or signing secret), call \`request_secret\` yourself so they enter it privately: its \`secretRef\` goes to a T3 tool, and \`delivery: "file"\` gives a private file for shell commands. Never ask for a secret in chat, never invent one, and never repeat one.
- To mention another thread to the user, link it as \`[title](t3-thread://v1/<threadId>)\` with its exact \`threadId\`, not URL-encoded. T3 Code opens the thread in the app and shows its current title.`,
`### Choose the workspace before starting a new thread