feat: agents ask the user for a secret through a private card #15907
Mergedjuliusmarmingemerged 22 commits into
main fromrefs/pull/15907/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
juliusmarminge added labelsmacroscope-review
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- packages/client-runtime/src/state/server.ts line 1309OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1299,3 +1299,11 @@12991299 scheduler: configScheduler,13001300 concurrency: configConcurrency,13011301 }),1302+ // Off the config lane like run-now: answering a card must not queue1303+ // behind settings edits. One answer per card at a time.1304+ answerScheduledTaskSecretRequest: createEnvironmentRpcCommand(runtime, {1305+ label: "environment-data:server:scheduled-task:answer-secret-request",1306+ tag: WS_METHODS.scheduledTasksAnswerSecretRequest,1307+ concurrency: {1308+ mode: "singleFlight",1309+ key: ({ environmentId, input }) => `${environmentId}:${input.threadId}:${input.turnItemId}`,apps/server/src/orchestration-v2/Orchestrator.ts line 6850OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -6809,0 +6830,21 @@6830+ (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),6831+ ),6832+ );6833+ const run = projection.runs.find((candidate) => candidate.id === command.runId);6834+ if (run === undefined || run.rootNodeId !== command.nodeId) {6835+ return yield* new OrchestratorDispatchError({6836+ commandId: command.commandId,6837+ commandType: command.type,6838+ cause: `Node ${command.nodeId} is not the root of run ${command.runId}.`,6839+ });6840+ }6841+ const existing = projection.turnItems.find((item) => item.id === command.turnItemId);6842+ if (existing !== undefined && existing.type !== "secret_request") {6843+ return yield* new OrchestratorDispatchError({6844+ commandId: command.commandId,6845+ commandType: command.type,6846+ cause: `Turn item ${command.turnItemId} is not a secret request.`,6847+ });6848+ }6849+ // A request is answered once; later updates cannot reopen or change it.6850+ if (existing !== undefined && existing.secretStatus !== "pending") return;apps/server/src/scheduledTasks/ScheduledTaskService.ts line 1208OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1153,0 +1188,21 @@1188+ return yield* taskError("Schedule task was deleted or replaced.", { taskId: input.id });1189+ }1190+ yield* notifyChanged;1191+ return { task: yield* loadTask(input.id) };1192+ });1193+1194+ const answerSecretRequest: ScheduledTaskService["Service"]["answerSecretRequest"] = (input) =>1195+ Effect.gen(function* () {1196+ const records = yield* threadManagement1197+ .getThreadRecords(input.threadId, ["turnItems"], {1198+ turnItemTypes: ["secret_request"],1199+ messageRoles: [],1200+ })1201+ .pipe(1202+ Effect.mapError((cause) => taskError("Could not load the secret request.", { cause })),1203+ );1204+ const item = records.turnItems.find((candidate) => candidate.id === input.turnItemId);1205+ if (item?.type !== "secret_request" || item.runId === null || item.nodeId === null) {1206+ return yield* taskError("This secret request no longer exists.");1207+ }1208+ if (item.secretStatus !== "pending") {apps/server/src/mcp/OrchestratorMcpService.ts line 1632Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1323,0 +1414,21 @@1414+ failure(1415+ "orchestration_error",1416+ `Unable to read the secret request: ${errorMessage(error)}`,1417+ ),1418+ ),1419+ );1420+ const item = projection.turnItems.find((candidate) => candidate.id === turnItemId);1421+ if (item?.type === "secret_request" && item.secretStatus !== "pending") {1422+ return item.secretStatus;1423+ }1424+ const current = projection.runs.find((candidate) => candidate.id === runId);1425+ if (1426+ current === undefined ||1427+ ThreadManagementService.isTerminalRunStatus(current.status)1428+ ) {1429+ yield* record("cancelled");1430+ return "cancelled" as const;1431+ }1432+ yield* Effect.sleep(Duration.millis(SECRET_REQUEST_POLL_INTERVAL_MS));1433+ }1434+ }).pipe(
juliusmarminge changed the title
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- packages/contracts/src/scheduledTask.ts line 110Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -106,3 +107,4 @@106107 secret: Schema.optional(TrimmedNonEmptyString).annotate({107108 description: "Shared signing secret. Omit to keep the stored secret.",108109 }),110+ secretRef: Schema.optional(SecretRef).annotate({apps/server/src/secrets/SecretRequests.ts line 105OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +85,21 @@85+ const records = yield* threadManagement86+ .getThreadRecords(input.threadId, ["turnItems"], {87+ turnItemTypes: ["secret_request"],88+ messageRoles: [],89+ })90+ .pipe(Effect.mapError(() => fail("Could not load the secret request.")));91+ const item = records.turnItems.find((candidate) => candidate.id === input.turnItemId);92+ if (item?.type !== "secret_request" || item.runId === null || item.nodeId === null) {93+ return yield* fail("This secret request no longer exists.");94+ }95+ if (item.secretStatus !== "pending") {96+ return yield* fail("This secret request was already answered.");97+ }98+ // Store first: the card only says saved once the value is kept.99+ if (input.answer.type === "save") {100+ const ref = yield* newRef;101+ const encoded = yield* encodeStored({102+ projectId: records.thread.projectId,103+ value: input.answer.secret,104+ }).pipe(Effect.orDie);105+ yield* Effect.all([apps/server/src/secrets/SecretRequests.ts line 130OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +110,21 @@110+ const secretStatus = input.answer.type === "save" ? "saved" : "declined";111+ yield* threadManagement112+ .dispatch({113+ type: "secret_request.record",114+ commandId: CommandId.make(`secret-request:${item.id}:${secretStatus}`),115+ threadId: input.threadId,116+ runId: item.runId,117+ nodeId: item.nodeId,118+ turnItemId: item.id,119+ label: item.label,120+ reason: item.reason,121+ ...(item.placeholder === undefined ? {} : { placeholder: item.placeholder }),122+ secretStatus,123+ })124+ .pipe(Effect.mapError(() => fail("Saved the secret, but could not update the request.")));125+ });126+127+ const savedRef: SecretRequests["Service"]["savedRef"] = (input) =>128+ store.get(refForRequest(input.threadId, input.turnItemId)).pipe(129+ Effect.map(Option.map((bytes) => SecretRef.make(new TextDecoder().decode(bytes)))),130+ Effect.orElseSucceed(() => Option.none()),packages/client-runtime/src/secretRequest.ts lines 74 to 76Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +56,21 @@56+ case "declined":57+ return DECLINED_DISPLAY;58+ case "cancelled":59+ return ENDED_DISPLAY;60+ }61+}62+63+/**64+ * Builds the RPC payload for an answer. A save with a blank value returns null,65+ * since the server rejects it; callers keep Save disabled instead.66+ */67+export function secretRequestAnswerInput(68+ item: Pick<SecretRequestItem, "id" | "threadId">,69+ answer: { readonly type: "save"; readonly secret: string } | { readonly type: "decline" },70+): SecretRequestAnswerInput | null {71+ if (answer.type === "decline") {72+ return { threadId: item.threadId, turnItemId: item.id, answer: { type: "decline" } };73+ }74+ const secret = answer.secret.trim();75+ if (secret.length === 0) return null;76+ return { threadId: item.threadId, turnItemId: item.id, answer: { type: "save", secret } };packages/contracts/src/scheduledTask.ts line 110Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -106,3 +107,4 @@106107 secret: Schema.optional(TrimmedNonEmptyString).annotate({107108 description: "Shared signing secret. Omit to keep the stored secret.",108109 }),110+ secretRef: Schema.optional(SecretRef).annotate({
- apps/server/src/secrets/SecretRequests.ts line 230Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +167,21 @@167+ Effect.tapError(() =>168+ Metrics.increment(Metrics.secretRefsConsumedTotal, { result: "rejected" }),169+ ),170+ Effect.withSpan("SecretRequests.consume"),171+ );172+173+ const consumeRef = (input: { readonly ref: SecretRef; readonly projectId: ProjectId }) =>174+ Effect.gen(function* () {175+ if (!REF_PATTERN.test(input.ref)) return yield* fail("That secretRef is not valid.");176+ const stored = yield* store177+ .get(storeName(input.ref))178+ .pipe(Effect.mapError(() => fail("Could not read the secret.")));179+ const decoded = Option.flatMap(stored, (bytes) =>180+ decodeStored(new TextDecoder().decode(bytes)),181+ );182+ if (Option.isNone(decoded) || decoded.value.projectId !== input.projectId) {183+ return yield* fail(184+ "That secretRef was already used or does not exist. Ask the user again with request_secret.",185+ );186+ }187+ if ((yield* Clock.currentTimeMillis) - decoded.value.savedAt > SECRET_REF_TTL_MS) {
- apps/server/src/mcp/OrchestratorMcpService.ts line 1535OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1459,0 +1515,21 @@1515+ threadId: threadId,1516+ runId,1517+ nodeId,1518+ turnItemId,1519+ label: input.label,1520+ reason: input.reason,1521+ ...(input.placeholder === undefined ? {} : { placeholder: input.placeholder }),1522+ secretStatus,1523+ })1524+ .pipe(1525+ Effect.mapError((error) =>1526+ failure(1527+ "orchestration_error",1528+ `Could not record the secret request: ${errorMessage(error)}`,1529+ ),1530+ ),1531+ );1532+ yield* record("pending");1533+ // Only this call can hand the agent its ref, so the card must not1534+ // outlive it: a timeout or an aborted call closes it as cancelled.1535+ const closeCard = record("cancelled").pipe(Effect.ignore);apps/server/src/orchestration-v2/Orchestrator.ts line 6865OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -6810,0 +6845,21 @@6845+ commandId: command.commandId,6846+ commandType: command.type,6847+ cause: `Turn item ${command.turnItemId} is not a secret request.`,6848+ });6849+ }6850+ // A request is answered once; later updates cannot reopen or change it.6851+ if (existing !== undefined && existing.secretStatus !== "pending") return;6852+6853+ const now = yield* DateTime.now;6854+ const pending = command.secretStatus === "pending";6855+ const turnItem: OrchestrationV2TurnItem = {6856+ id: command.turnItemId,6857+ threadId: command.threadId,6858+ runId: command.runId,6859+ nodeId: command.nodeId,6860+ providerThreadId: run.providerThreadId,6861+ providerTurnId: providerTurnForRun(projection, run)?.id ?? null,6862+ nativeItemRef: null,6863+ parentItemId: null,6864+ ordinal: existing?.ordinal ?? (yield* nextTurnItemOrdinal(projection)),6865+ status: pending ? "waiting" : command.secretStatus === "saved" ? "completed" : "cancelled",apps/server/src/secrets/SecretRequests.ts line 221Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +156,21 @@156+157+ const savedRef: SecretRequests["Service"]["savedRef"] = (input) =>158+ Effect.gen(function* () {159+ const ref = refFor(salt, input.threadId, input.turnItemId);160+ const stored = yield* store.get(storeName(ref)).pipe(Effect.orElseSucceed(Option.none));161+ return Option.map(stored, () => ref);162+ });163+164+ const consume: SecretRequests["Service"]["consume"] = (input) =>165+ consumeRef(input).pipe(166+ Effect.tap(() => Metrics.increment(Metrics.secretRefsConsumedTotal, { result: "used" })),167+ Effect.tapError(() =>168+ Metrics.increment(Metrics.secretRefsConsumedTotal, { result: "rejected" }),169+ ),170+ Effect.withSpan("SecretRequests.consume"),171+ );172+173+ const consumeRef = (input: { readonly ref: SecretRef; readonly projectId: ProjectId }) =>174+ Effect.gen(function* () {175+ if (!REF_PATTERN.test(input.ref)) return yield* fail("That secretRef is not valid.");176+ const stored = yield* store
- apps/server/src/scheduledTasks/ScheduledTaskService.ts line 1038OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1018,4 +1020,19 @@10181020 const signature =10191021 input.schedule.type === "webhook" ? input.schedule.signature : null;1020- const secret =1021- signature == null ? null : (signature.secret ?? existing?.secret ?? null);1022+ // A secretRef is a value the user entered for an agent; this1023+ // save consumes it, so it cannot be used again. A replay of a1024+ // save that already used it keeps the secret that save stored.1025+ const replay = input.commandId !== undefined && existing?.secret != null;1026+ const fromRef =1027+ signature?.secretRef === undefined1028+ ? undefined1029+ : yield* secretRequests1030+ .consume({ ref: signature.secretRef, projectId: input.projectId })1031+ .pipe(1032+ Effect.catch((error) =>1033+ replay1034+ ? Effect.succeed(undefined)1035+ : Effect.fail(taskError(error.message, { taskId: id })),1036+ ),1037+ );1038+ const provided = fromRef ?? signature?.secret;apps/server/src/orchestration-v2/Orchestrator.ts line 6855OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -6810,0 +6835,21 @@6835+ if (run === undefined || run.rootNodeId !== command.nodeId) {6836+ return yield* new OrchestratorDispatchError({6837+ commandId: command.commandId,6838+ commandType: command.type,6839+ cause: `Node ${command.nodeId} is not the root of run ${command.runId}.`,6840+ });6841+ }6842+ const existing = projection.turnItems.find((item) => item.id === command.turnItemId);6843+ if (existing !== undefined && existing.type !== "secret_request") {6844+ return yield* new OrchestratorDispatchError({6845+ commandId: command.commandId,6846+ commandType: command.type,6847+ cause: `Turn item ${command.turnItemId} is not a secret request.`,6848+ });6849+ }6850+ // A request is answered once; later updates cannot reopen or change it.6851+ if (existing !== undefined && existing.secretStatus !== "pending") return;6852+6853+ const now = yield* DateTime.now;6854+ const pending = command.secretStatus === "pending";6855+ const turnItem: OrchestrationV2TurnItem = {apps/server/src/secrets/SecretRequests.ts line 192OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +172,21 @@172+ Metrics.increment(Metrics.secretRefsConsumedTotal, { result: "rejected" }),173+ ),174+ Effect.withSpan("SecretRequests.consume"),175+ );176+177+ const consumeRef = (input: { readonly ref: SecretRef; readonly projectId: ProjectId }) =>178+ Effect.gen(function* () {179+ if (!REF_PATTERN.test(input.ref)) return yield* fail("That secretRef is not valid.");180+ const stored = yield* store181+ .get(storeName(input.ref))182+ .pipe(Effect.mapError(() => fail("Could not read the secret.")));183+ const decoded = Option.flatMap(stored, (bytes) =>184+ decodeStored(new TextDecoder().decode(bytes)),185+ );186+ if (Option.isNone(decoded) || decoded.value.projectId !== input.projectId) {187+ return yield* fail(188+ "That secretRef was already used or does not exist. Ask the user again with request_secret.",189+ );190+ }191+ if ((yield* Clock.currentTimeMillis) - decoded.value.savedAt > SECRET_REF_TTL_MS) {192+ yield* store.remove(storeName(input.ref)).pipe(Effect.ignore);
- apps/server/src/mcp/OrchestratorMcpService.ts lines 1588 to 1591OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1459,0 +1571,21 @@1571+ Math.min(input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS, MAX_WAIT_TIMEOUT_MS),1572+ ),1573+ ),1574+ Effect.onInterrupt(() => closeCard),1575+ );1576+ if (Option.isNone(answered)) yield* closeCard;1577+ // A save that raced the timeout still wins: the card is answered once.1578+ const status = Option.isSome(answered)1579+ ? answered.value1580+ : yield* threadManagement1581+ .getThreadRecords(threadId, ["turnItems"], {1582+ turnItemTypes: ["secret_request"],1583+ messageRoles: [],1584+ })1585+ .pipe(1586+ Effect.map((records) => {1587+ const item = records.turnItems.find((candidate) => candidate.id === turnItemId);1588+ return item?.type === "secret_request" && item.secretStatus === "saved"1589+ ? ("saved" as const)1590+ : ("timed_out" as const);1591+ }),
- apps/server/src/orchestration-v2/runtimeLayer.ts line 54OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -51,3 +51,4 @@5151 import { layer as threadForkServiceLayer } from "./ThreadForkService.ts";5252 import { layer as turnItemPositionStoreLayer } from "./TurnItemPositionStore.ts";5353 import { layer as scheduledTaskServiceLayer } from "../scheduledTasks/ScheduledTaskService.ts";54+import { layer as secretRequestsLayer } from "../secrets/SecretRequests.ts";
- apps/server/src/mcp/OrchestratorMcpService.ts lines 1532 to 1535OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1459,0 +1515,21 @@1515+ threadId: threadId,1516+ runId,1517+ nodeId,1518+ turnItemId,1519+ label: input.label,1520+ reason: input.reason,1521+ ...(input.placeholder === undefined ? {} : { placeholder: input.placeholder }),1522+ secretStatus,1523+ })1524+ .pipe(1525+ Effect.mapError((error) =>1526+ failure(1527+ "orchestration_error",1528+ `Could not record the secret request: ${errorMessage(error)}`,1529+ ),1530+ ),1531+ );1532+ yield* record("pending");1533+ // Only this call can hand the agent its ref, so the card must not1534+ // outlive it: a timeout or an aborted call closes it as cancelled.1535+ const closeCard = record("cancelled").pipe(Effect.ignore);apps/server/src/secrets/SecretRequests.ts lines 136 to 179OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +141,21 @@141+ ServerSecretStore.isSecretAlreadyExistsError(error)142+ ? fail("already_answered", error)143+ : fail("store_failed", error),144+ ),145+ );146+ }147+ const secretStatus = input.answer.type === "save" ? "saved" : "declined";148+ yield* threadManagement149+ .dispatch({150+ type: "secret_request.record",151+ commandId: CommandId.make(`secret-request:${item.id}:${secretStatus}`),152+ threadId: input.threadId,153+ runId: item.runId,154+ nodeId: item.nodeId,155+ turnItemId: item.id,156+ label: item.label,157+ reason: item.reason,158+ ...(item.placeholder === undefined ? {} : { placeholder: item.placeholder }),159+ secretStatus,160+ })161+ .pipe(Effect.mapError((cause) => fail("record_failed", cause)));
- apps/server/src/secrets/SecretRequests.ts line 141OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +121,21 @@121+ // nobody will ever receive the ref, so a value saved now would be lost.122+ const run = records.runs.find((candidate) => candidate.id === item.runId);123+ if (run === undefined || ThreadManagementService.isTerminalRunStatus(run.status)) {124+ return yield* fail("agent_stopped");125+ }126+ // Store first: the card only says saved once the value is kept. Create,127+ // not set: a second answer racing this one must not replace the value.128+ if (input.answer.type === "save") {129+ const encoded = yield* encodeStored({130+ projectId: records.thread.projectId,131+ value: input.answer.secret,132+ savedAt: yield* Clock.currentTimeMillis,133+ }).pipe(Effect.orDie);134+ yield* store135+ .create(136+ storeName(refFor(salt, input.threadId, item.id)),137+ new TextEncoder().encode(encoded),138+ )139+ .pipe(140+ Effect.mapError((error) =>141+ ServerSecretStore.isSecretAlreadyExistsError(error)
- apps/web/src/components/chat/SecretRequestCard.tsx lines 132 to 132Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +112,21 @@112+ // A click anywhere on the card targets its field, so a paste that113+ // follows lands here rather than with the composer.114+ onPointerDown={(event) => {115+ if (!(event.target instanceof HTMLElement)) return;116+ if (event.target.closest("input, button, a")) return;117+ document.getElementById(inputId)?.focus();118+ }}119+ >120+ <div className="flex min-w-0 flex-col gap-1">121+ <label htmlFor={inputId} className="text-sm font-medium text-foreground">122+ {item.label}123+ </label>124+ {item.reason.trim() ? <p className="text-sm text-muted-foreground">{item.reason}</p> : null}125+ </div>126+ <div className="flex min-w-0 items-center gap-2">127+ <div className="min-w-0 flex-1">128+ <Input129+ id={inputId}130+ // Masked text rather than a password field: browsers offer to131+ // save any submitted password, and this is not a login.132+ type="text"packages/contracts/src/orchestratorMcp.ts line 613OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -579,0 +593,21 @@593+ "One or two sentences on what it is for and where the user gets or also enters it.",594+ }),595+ placeholder: Schema.optional(TrimmedNonEmptyString).annotate({596+ description: "Hint inside the input, e.g. 'Paste your GitHub token'.",597+ }),598+ timeoutMs: Schema.optional(599+ Schema.Int.check(Schema.isBetween({ minimum: 1_000, maximum: 60 * 60 * 1_000 })),600+ ).annotate({ description: "How long to wait for the user. Default 10 minutes." }),601+ clientRequestId: Schema.optional(OrchestratorMcpClientRequestId).annotate({602+ description:603+ "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.",604+ }),605+});606+export type OrchestratorMcpRequestSecretInput = typeof OrchestratorMcpRequestSecretInput.Type;607+608+export const OrchestratorMcpRequestSecretResult = Schema.Struct({609+ status: Schema.Literals(["saved", "declined", "cancelled", "timed_out"]).annotate({610+ description:611+ "saved: secretRef holds the value. 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.",612+ }),613+ secretRef: Schema.optional(SecretRef).annotate({
juliusmarminge merged this9f61ba6
juliusmarminge closed this
Sign in to join this conversation.




macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed