feat: agents ask the user for a secret through a private card (#15907)

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Opus 5.5 authored and GitHub committed 2026-10-05 16:14:12 -07:00
1 parent 25d5c7cacb
commit 9f61ba6741
49 files changed
+2250 -27

No files matched your search

+4
View File
@@ -35,6 +35,10 @@
"types": "./src/userMessage.ts",
"default": "./src/userMessage.ts"
},
"./secret-request": {
"types": "./src/secretRequest.ts",
"default": "./src/secretRequest.ts"
},
"./scheduled-task-webhook": {
"types": "./src/scheduledTaskWebhook.ts",
"default": "./src/scheduledTaskWebhook.ts"
@@ -0,0 +1,75 @@
import { SecretRequestError, ThreadId, TurnItemId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import {
secretRequestAnswerInput,
secretRequestDisplay,
secretRequestFailureMessage,
type SecretRequestItem,
} from "./secretRequest.ts";
const item = {
id: TurnItemId.make("turn-item:secret-request:1"),
threadId: ThreadId.make("thread-1"),
};
describe("secretRequestDisplay", () => {
it("shows the form only while pending and maps every answer to its outcome copy", () => {
const display = (secretStatus: SecretRequestItem["secretStatus"]) =>
secretRequestDisplay({ secretStatus }, "local");
expect(display("pending")).toEqual({ kind: "pending" });
expect(display("saved")).toEqual({
kind: "answered",
outcome: "saved",
label: "Saved securely and kept private",
});
expect(display("declined")).toEqual({
kind: "answered",
outcome: "declined",
label: "Declined",
});
expect(display("cancelled")).toEqual({
kind: "answered",
outcome: "ended",
label: "Request ended",
});
});
it("never offers the form for a request inherited from another thread", () => {
expect(secretRequestDisplay({ secretStatus: "pending" }, "inherited")).toEqual({
kind: "pending-elsewhere",
label: "Waiting for an answer in the original thread",
});
expect(secretRequestDisplay({ secretStatus: "saved" }, "inherited")).toMatchObject({
outcome: "saved",
});
});
});
describe("secretRequestAnswerInput", () => {
it("refuses a blank save and trims the value the server will store", () => {
expect(secretRequestAnswerInput(item, { type: "save", secret: " " })).toBeNull();
expect(secretRequestAnswerInput(item, { type: "save", secret: " whsec_1 " })).toEqual({
threadId: item.threadId,
turnItemId: item.id,
answer: { type: "save", secret: "whsec_1" },
});
expect(secretRequestAnswerInput(item, { type: "decline" })).toEqual({
threadId: item.threadId,
turnItemId: item.id,
answer: { type: "decline" },
});
});
});
describe("secretRequestFailureMessage", () => {
it("passes through server errors but hides anything that could echo the payload", () => {
expect(
secretRequestFailureMessage(new SecretRequestError({ reason: "already_answered" })),
).toBe("This secret request was already answered.");
expect(secretRequestFailureMessage(new Error('Expected string, got "whsec_1"'))).toBe(
"Could not answer the request. Try again.",
);
expect(secretRequestFailureMessage(undefined)).toBe("Could not answer the request. Try again.");
});
});
@@ -0,0 +1,101 @@
import type { OrchestrationV2TurnItem, SecretRequestAnswerInput } from "@t3tools/contracts";
export type SecretRequestItem = Extract<
OrchestrationV2TurnItem,
{ readonly type: "secret_request" }
>;
/** Shown under the field: the one promise the card makes about the value. */
export const SECRET_REQUEST_PRIVACY_NOTE = "Stored securely, never shown to the agent";
export const SECRET_REQUEST_DEFAULT_PLACEHOLDER = "Paste the secret";
/** What a secret request card shows: the form while pending, otherwise a one-line outcome. */
export type SecretRequestDisplay =
| { readonly kind: "pending" }
| { readonly kind: "pending-elsewhere"; readonly label: string }
| {
readonly kind: "answered";
readonly outcome: "saved" | "declined" | "ended";
readonly label: string;
};
const SAVED_DISPLAY: SecretRequestDisplay = {
kind: "answered",
outcome: "saved",
label: "Saved securely and kept private",
};
const DECLINED_DISPLAY: SecretRequestDisplay = {
kind: "answered",
outcome: "declined",
label: "Declined",
};
const ENDED_DISPLAY: SecretRequestDisplay = {
kind: "answered",
outcome: "ended",
label: "Request ended",
};
const PENDING_DISPLAY: SecretRequestDisplay = { kind: "pending" };
const PENDING_ELSEWHERE_DISPLAY: SecretRequestDisplay = {
kind: "pending-elsewhere",
label: "Waiting for an answer in the original thread",
};
/**
* `visibility` is the projected row's: a request inherited from another
* thread (a fork) can only be answered where it was asked.
*/
export function secretRequestDisplay(
item: Pick<SecretRequestItem, "secretStatus">,
visibility: "local" | "inherited" | "synthetic",
): SecretRequestDisplay {
switch (item.secretStatus) {
case "pending":
return visibility === "local" ? PENDING_DISPLAY : PENDING_ELSEWHERE_DISPLAY;
case "saved":
return SAVED_DISPLAY;
case "declined":
return DECLINED_DISPLAY;
case "cancelled":
return ENDED_DISPLAY;
}
}
/**
* Builds the RPC payload for an answer. A save with a blank value returns null,
* since the server rejects it; callers keep Save disabled instead.
*/
export function secretRequestAnswerInput(
item: Pick<SecretRequestItem, "id" | "threadId">,
answer: { readonly type: "save"; readonly secret: string } | { readonly type: "decline" },
): SecretRequestAnswerInput | null {
if (answer.type === "decline") {
return { threadId: item.threadId, turnItemId: item.id, answer: { type: "decline" } };
}
const secret = answer.secret.trim();
if (secret.length === 0) return null;
return { threadId: item.threadId, turnItemId: item.id, answer: { type: "save", secret } };
}
/** Failures whose message is written for the user and never echoes the request payload. */
const USER_FACING_FAILURE_TAGS = new Set(["SecretRequestError", "EnvironmentAuthorizationError"]);
/**
* Inline error copy for a failed answer. Only known server errors pass their
* message through: anything else (transport or encoding failures) gets the
* generic copy, so the typed value can never surface in the UI.
*/
export function secretRequestFailureMessage(failure: unknown): string {
if (
typeof failure === "object" &&
failure !== null &&
"_tag" in failure &&
typeof failure._tag === "string" &&
USER_FACING_FAILURE_TAGS.has(failure._tag) &&
"message" in failure &&
typeof failure.message === "string" &&
failure.message.trim().length > 0
) {
return failure.message;
}
return "Could not answer the request. Try again.";
}
@@ -1299,6 +1299,17 @@ export function createServerEnvironmentAtoms<R, E>(
scheduler: configScheduler,
concurrency: configConcurrency,
}),
// Off the config lane: answering a card must not queue behind settings
// edits. One answer per card at a time.
answerSecretRequest: createEnvironmentRpcCommand(runtime, {
label: "environment-data:server:secrets:answer-request",
tag: WS_METHODS.secretsAnswerRequest,
concurrency: {
mode: "singleFlight",
key: ({ environmentId, input }) =>
JSON.stringify([environmentId, input.threadId, input.turnItemId]),
},
}),
refreshUsageRates: createEnvironmentRpcCommand(runtime, {
label: "environment-data:server:refresh-usage-rates",
tag: WS_METHODS.serverRefreshUsageRates,
@@ -285,6 +285,9 @@ export function summarizeT3ToolCalls(
quantity(countEntities(entityIds("requestId")), "pending question request"),
);
break;
case "secret-request":
label = phrase("Asked for", "ask for", quantity(selected.length, "secret"));
break;
case "worktree-handoff":
label = phrase(
"Handed off to",
+3
View File
@@ -349,6 +349,9 @@ export type RuntimeRequestId = typeof RuntimeRequestId.Type;
export const RuntimeTaskId = makeEntityId("RuntimeTaskId");
export type RuntimeTaskId = typeof RuntimeTaskId.Type;
export const ScheduledTaskId = makeEntityId("ScheduledTaskId");
/** A one-use handle to a secret the user entered for an agent; the agent never sees the value. */
export const SecretRef = makeEntityId("SecretRef");
export type SecretRef = typeof SecretRef.Type;
export type ScheduledTaskId = typeof ScheduledTaskId.Type;
export const ApprovalRequestId = makeEntityId("ApprovalRequestId");
export type ApprovalRequestId = typeof ApprovalRequestId.Type;
+1
View File
@@ -60,3 +60,4 @@ export * from "./worktreeMcp.ts";
export * from "./resourceTelemetry.ts";
export * from "./rpc.ts";
export * from "./worktreeSetup.ts";
export * from "./secretRequest.ts";
@@ -205,7 +205,7 @@ describe("orchestration V2 contracts", () => {
});
const known = item("item-known", "system_notice", { message: "Hello" });
// A type no build of this client knows, standing in for a newer server's item.
const future = item("item-future", "secret_request", { secretRef: "ref-1" });
const future = item("item-future", "hologram", { beam: "ref-1" });
const projected = (position: number, turnItem: { readonly id: string }) => ({
position,
visibility: "local",
+45
View File
@@ -1346,6 +1346,26 @@ export const OrchestrationV2WebSearchResult = Schema.Struct({
});
export type OrchestrationV2WebSearchResult = typeof OrchestrationV2WebSearchResult.Type;
export const OrchestrationV2SecretRequestStatus = Schema.Literals([
"pending",
"saved",
"declined",
"cancelled",
]);
export type OrchestrationV2SecretRequestStatus = typeof OrchestrationV2SecretRequestStatus.Type;
/**
* A secret an agent asked the user for. The value never passes through
* orchestration: the item carries only what was asked and how it was answered.
*/
const OrchestrationV2SecretRequestFields = {
type: Schema.Literal("secret_request"),
label: TrimmedNonEmptyString,
reason: Schema.String,
placeholder: Schema.optional(Schema.String),
secretStatus: OrchestrationV2SecretRequestStatus,
} as const;
export const OrchestrationV2TurnItem = Schema.Union([
Schema.Struct({
...OrchestrationV2TurnItemBaseFields,
@@ -1525,6 +1545,10 @@ export const OrchestrationV2TurnItem = Schema.Union([
targetProviderInstanceId: ProviderInstanceId,
targetModel: TrimmedNonEmptyString,
}),
Schema.Struct({
...OrchestrationV2TurnItemBaseFields,
...OrchestrationV2SecretRequestFields,
}),
Schema.Struct({
...OrchestrationV2TurnItemBaseFields,
type: Schema.Literal("subagent"),
@@ -2296,6 +2320,10 @@ export const OrchestrationV2TurnItemJson = Schema.Union([
targetProviderInstanceId: ProviderInstanceId,
targetModel: TrimmedNonEmptyString,
}),
Schema.Struct({
...OrchestrationV2TurnItemJsonBaseFields,
...OrchestrationV2SecretRequestFields,
}),
Schema.Struct({
...OrchestrationV2TurnItemJsonBaseFields,
type: Schema.Literal("subagent"),
@@ -3013,6 +3041,7 @@ export const OrchestrationV2Command = Schema.Union([
targetThreadId: ThreadId,
targetRunId: Schema.NullOr(RunId),
}),
Schema.Struct({
type: Schema.Literal("provider.switch"),
commandId: CommandId,
@@ -3081,6 +3110,22 @@ const OrchestrationV2InternalCommand = Schema.Union([
threadId: ThreadId,
reason: Schema.optional(Schema.String),
}),
/**
* Records or updates a secret an agent asked the user for. Internal so no
* client can mark a request saved without the value being stored.
*/
Schema.Struct({
type: Schema.Literal("secret_request.record"),
commandId: CommandId,
threadId: ThreadId,
runId: RunId,
nodeId: NodeId,
turnItemId: TurnItemId,
label: TrimmedNonEmptyString,
reason: Schema.String,
placeholder: Schema.optional(Schema.String),
secretStatus: OrchestrationV2SecretRequestStatus,
}),
]);
export type OrchestrationV2InternalCommand = typeof OrchestrationV2InternalCommand.Type;
+47 -2
View File
@@ -12,6 +12,7 @@ import {
ProjectId,
RunId,
ScheduledTaskId,
SecretRef,
ThreadId,
TrimmedNonEmptyString,
TurnItemId,
@@ -541,8 +542,14 @@ export const OrchestratorMcpScheduledTask = Schema.Struct({
schedule: ScheduledTaskSchedule,
nextRunAt: Schema.NullOr(IsoDateTime),
lastRunStatus: ScheduledTaskRunStatus,
/** For webhook tasks: the public T3 Connect URL, or the environment-relative path when the environment is not linked. */
webhookUrl: Schema.optional(Schema.String),
/** For webhook tasks: the public T3 Connect URL. Absent when this environment has no managed tunnel. */
webhookUrl: Schema.optional(Schema.String).annotate({
description:
"Public URL to give the sender. Absent when this environment has no T3 Connect managed tunnel; the user must enable T3 Connect remote access first.",
}),
webhookSignature: Schema.optional(Schema.Literals(["none", "set"])).annotate({
description: "Whether requests must carry a valid signature.",
}),
});
export type OrchestratorMcpScheduledTask = typeof OrchestratorMcpScheduledTask.Type;
@@ -577,6 +584,44 @@ export const OrchestratorMcpUpdateScheduledTaskInput = Schema.Struct({
export type OrchestratorMcpUpdateScheduledTaskInput =
typeof OrchestratorMcpUpdateScheduledTaskInput.Type;
export const OrchestratorMcpRequestSecretInput = Schema.Struct({
label: TrimmedNonEmptyString.annotate({
description: "What you need, shown as the card's title, e.g. 'GitHub webhook secret'.",
}),
reason: TrimmedNonEmptyString.annotate({
description:
"One or two sentences on what it is for and where the user gets or also enters it.",
}),
placeholder: Schema.optional(TrimmedNonEmptyString).annotate({
description: "Hint inside the input, e.g. 'Paste your GitHub token'.",
}),
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." }),
clientRequestId: Schema.optional(OrchestratorMcpClientRequestId).annotate({
description:
"Reuse when retrying a call that lost its result, so the user sees one card and its answer is returned again. Use a new id to ask again after timed_out or cancelled.",
}),
});
export type OrchestratorMcpRequestSecretInput = typeof OrchestratorMcpRequestSecretInput.Type;
export const OrchestratorMcpRequestSecretResult = Schema.Union([
Schema.Struct({
status: Schema.Literal("saved").annotate({ description: "secretRef holds the value." }),
secretRef: SecretRef.annotate({
description:
"Pass it to a tool that accepts a secretRef; it works once, and you never see the value.",
}),
}),
Schema.Struct({
status: Schema.Literals(["declined", "cancelled", "timed_out"]).annotate({
description:
"declined: the user chose not to. cancelled: the request ended with the run. timed_out: the user did not answer in time; the card is closed, so ask again with a new clientRequestId if still needed.",
}),
}),
]);
export type OrchestratorMcpRequestSecretResult = typeof OrchestratorMcpRequestSecretResult.Type;
export const OrchestratorMcpDeleteScheduledTaskInput = Schema.Struct({
scheduledTaskId: ScheduledTaskId,
});
+8
View File
@@ -320,6 +320,7 @@ import {
ScheduledTaskUpsertInput,
ScheduledTaskMutationResult,
} from "./scheduledTask.ts";
import { SecretRequestAnswerInput, SecretRequestError } from "./secretRequest.ts";
import {
ProjectCloneActionInput,
ProjectCloneActionResult,
@@ -480,6 +481,7 @@ export const WS_METHODS = {
scheduledTasksDelete: "scheduledTasks.delete",
scheduledTasksRunNow: "scheduledTasks.runNow",
scheduledTasksRotateWebhookToken: "scheduledTasks.rotateWebhookToken",
secretsAnswerRequest: "secrets.answerRequest",
scheduledTasksListWebhookDeliveries: "scheduledTasks.listWebhookDeliveries",
scheduledTasksGetWebhookDelivery: "scheduledTasks.getWebhookDelivery",
@@ -1685,6 +1687,11 @@ const WsScheduledTasksRotateWebhookTokenRpc = Rpc.make(
},
);
const WsSecretsAnswerRequestRpc = Rpc.make(WS_METHODS.secretsAnswerRequest, {
payload: SecretRequestAnswerInput,
error: Schema.Union([SecretRequestError, EnvironmentAuthorizationError]),
});
const WsScheduledTasksListWebhookDeliveriesRpc = Rpc.make(
WS_METHODS.scheduledTasksListWebhookDeliveries,
{
@@ -1789,6 +1796,7 @@ export const WsRpcGroup = RpcGroup.make(
WsScheduledTasksDeleteRpc,
WsScheduledTasksRunNowRpc,
WsScheduledTasksRotateWebhookTokenRpc,
WsSecretsAnswerRequestRpc,
WsScheduledTasksListWebhookDeliveriesRpc,
WsScheduledTasksGetWebhookDeliveryRpc,
WsServerReportClientActivityRpc,
+5
View File
@@ -6,6 +6,7 @@ import {
IsoDateTime,
ProjectId,
ScheduledTaskId,
SecretRef,
ThreadId,
TrimmedNonEmptyString,
} from "./baseSchemas.ts";
@@ -106,6 +107,10 @@ const ScheduledTaskUpsertWebhookSchedule = Schema.Struct({
secret: Schema.optional(TrimmedNonEmptyString).annotate({
description: "Shared signing secret. Omit to keep the stored secret.",
}),
secretRef: Schema.optional(SecretRef).annotate({
description:
"A secret the user entered through request_secret, used instead of secret. It is consumed by this save.",
}),
}),
),
).annotate({
+52
View File
@@ -0,0 +1,52 @@
import * as Schema from "effect/Schema";
import { ThreadId, TrimmedNonEmptyString, TurnItemId } from "./baseSchemas.ts";
/**
* The user's answer to an agent's request for a secret. A saved value is kept
* by the server under a one-use SecretRef; the thread learns only the status.
*/
export const SecretRequestAnswerInput = Schema.Struct({
threadId: ThreadId,
turnItemId: TurnItemId,
answer: Schema.Union([
Schema.Struct({ type: Schema.Literal("save"), secret: TrimmedNonEmptyString }),
Schema.Struct({ type: Schema.Literal("decline") }),
]),
});
export type SecretRequestAnswerInput = typeof SecretRequestAnswerInput.Type;
const SECRET_REQUEST_FAILURE_MESSAGES = {
load_failed: "Could not load the secret request.",
not_found: "This secret request no longer exists.",
already_answered: "This secret request was already answered.",
agent_stopped: "The agent that asked has stopped, so this secret can't be used.",
store_failed: "Could not store the secret.",
record_failed: "Saved the secret, but could not update the request.",
invalid_ref: "That secretRef is not valid.",
read_failed: "Could not read the secret.",
ref_unavailable:
"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.",
} as const;
export const SecretRequestFailureReason = Schema.Literals(
Object.keys(SECRET_REQUEST_FAILURE_MESSAGES) as Array<
keyof typeof SECRET_REQUEST_FAILURE_MESSAGES
>,
);
export type SecretRequestFailureReason = typeof SecretRequestFailureReason.Type;
/** Answering a request or using its ref failed; the message is shown to users and agents. */
export class SecretRequestError extends Schema.TaggedError<SecretRequestError>()(
"SecretRequestError",
{
reason: SecretRequestFailureReason,
cause: Schema.optionalKey(Schema.Defect()),
},
) {
override get message(): string {
return SECRET_REQUEST_FAILURE_MESSAGES[this.reason];
}
}
@@ -38,6 +38,7 @@ export type T3McpToolSummaryAction =
| "question-list"
| "question-read"
| "question-respond"
| "secret-request"
| "worktree-handoff"
| "worktree-list"
| "worktree-status"
@@ -130,6 +131,7 @@ const T3_MCP_TOOLS: Readonly<Record<string, T3McpToolDefinition>> = {
["Delete", "Deleting", "Requested deletion of", "a scheduled task"],
"schedule-delete",
),
request_secret: tool(["Ask for", "Asking for", "Asked for", "a secret"], "secret-request"),
create_threads: tool(["Create", "Creating", "Created", "T3 threads"], "thread-create"),
t3_thread_start: tool(["Start", "Starting", "Started", "a T3 thread"], "thread-create"),
t3_thread_list: tool(["List", "Listing", "Listed", "T3 threads"], "thread-list"),