From 1cfc367b83bc807f0289e218c83966ac8725efb0 Mon Sep 17 00:00:00 2001 From: "Can H. Tartanoglu" Date: Tue, 17 Nov 2026 13:25:48 +0100 Subject: [PATCH] feat(secrets): request_secret can store a value straight into agenix An agent that needed a persistent secret asked with `delivery: "file"`, and a second tool moved the file into agenix. On 2026-11-17 T3 swept its secret files before that second step ran, the token was lost, and the user had to create and paste it again. `delivery: "agenix"` with an `agenix` target (user, root module or host, name, env or bare, category, expiry, custodian, project, verify URL) keeps the card as the entry surface but removes the second step. The card shows where the value will go. On save the server runs the `agenixSecretCommand` setting (default `canix secret store`, settings.json only) with the target as `--flag=value` arguments and the value on stdin only. T3 writes nothing: no ref, no file, no argv or env, and a secret-provider read no longer stays in the resolver cache. The agent gets only the command's JSON result (path, commit, verify and rekey state); a failure shows on the card, which stays open to retry or decline. An empty command refuses the mode at request time. Closes #9 --- .../features/threads/SecretRequestCard.tsx | 6 + .../OrchestratorMcpService.activity.test.ts | 91 ++++++++++ apps/server/src/mcp/OrchestratorMcpService.ts | 45 ++++- ...OrchestratorMcpToolkit.integration.test.ts | 3 + .../src/mcp/toolkits/orchestrator/tools.ts | 2 +- .../src/orchestration-v2/Orchestrator.ts | 2 + .../src/orchestration-v2/runtimeLayer.ts | 3 +- .../src/provider/agentContextBudget.json | 2 +- .../server/src/secrets/SecretRequests.test.ts | 163 ++++++++++++++++-- apps/server/src/secrets/SecretRequests.ts | 120 ++++++++++++- .../src/components/chat/SecretRequestCard.tsx | 6 + docs/user/secrets.md | 15 ++ packages/client-runtime/src/secretRequest.ts | 41 ++++- packages/contracts/src/orchestrationV2.ts | 12 +- packages/contracts/src/orchestratorMcp.ts | 12 +- packages/contracts/src/secretRequest.ts | 48 +++++- packages/contracts/src/settings.ts | 4 + 17 files changed, 539 insertions(+), 36 deletions(-) diff --git a/apps/mobile/src/features/threads/SecretRequestCard.tsx b/apps/mobile/src/features/threads/SecretRequestCard.tsx index 4d4234075a596..c8312ad2f600b 100644 --- a/apps/mobile/src/features/threads/SecretRequestCard.tsx +++ b/apps/mobile/src/features/threads/SecretRequestCard.tsx @@ -1,6 +1,7 @@ import { pipe } from "effect/Function"; import { SECRET_REQUEST_DEFAULT_PLACEHOLDER, + secretRequestAgenixDestination, secretRequestAnswerInput, secretRequestDisplay, secretRequestFailureMessage, @@ -129,6 +130,11 @@ function PendingSecretRequestForm(props: { {item.reason} ) : null} + {secretRequestAgenixDestination(item).map((line) => ( + + {line} + + ))} {sources.length > 0 ? ( diff --git a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts index c35b605dca4fb..59ac61bc6b588 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts @@ -841,3 +841,94 @@ it("requestSecret returns the unsaved note for a declined, cancelled or timed-ou { status: "timed_out", note: SECRET_REQUEST_UNSAVED_NOTE.timed_out }, ]); }); + +it("requestSecret refuses an incomplete or unconfigured agenix request and returns only the store result", async () => { + const agenixResult = { + path: "age/can/x.age", + committed_sha: "abc123", + verify: "pass", + rekey: "queued", + rops_id: "r1", + }; + const agenix = { user: "can", name: "x" }; + const run = (command: ReadonlyArray, input: Record) => { + const dispatched: Array<{ readonly type: string; readonly turnItemId?: string }> = []; + const projection = () => { + const card = dispatched.find((command) => command.type === "secret_request.record"); + return { + thread: baseThread({ + threadId: parentThreadId, + title: "Parent", + instanceId: parentInstanceId, + model: "gpt-5.4", + }), + runs: [ + { ...makeRun({ id: activeRunId, ordinal: 1, status: "running" }), rootNodeId: taskId }, + ], + visibleTurnItems: [], + turnItems: + card === undefined + ? [] + : [ + { + type: "secret_request", + id: card.turnItemId, + secretStatus: "saved", + agenixResult, + }, + ], + runtimeRequests: [], + messages: [], + contextTransfers: [], + subagents: [], + updatedAt: now, + } as unknown as OrchestrationV2ThreadProjection; + }; + const layer = layerOrchestratorService.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: () => Effect.sync(projection), + getThreadShell: () => + Effect.sync(() => projection().thread as unknown as OrchestrationV2ThreadShell), + dispatch: (command) => Effect.sync(() => void dispatched.push(command) as never), + } satisfies Partial), + ServerSettings.layerTest({ agenixSecretCommand: [...command] }), + Layer.mock(ProviderRegistry.ProviderRegistry)({ + getProviders: Effect.succeed([]), + } satisfies Partial), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({}), + NodeCrypto.layer, + ), + ), + ); + return Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + const result = yield* service + .requestSecret(makeScope(), { label: "Token", reason: "CI.", ...input } as never) + .pipe(Effect.result); + return { result, dispatched }; + }).pipe(Effect.provide(layer)); + }; + const canix = ["canix", "secret", "store"]; + const outcomes = await Effect.all([ + run(canix, { delivery: "agenix" }), + run(canix, { agenix }), + run(canix, { delivery: "agenix", agenix, value: "pasted" }), + run([], { delivery: "agenix", agenix }), + run(canix, { delivery: "agenix", agenix }), + ]).pipe(Effect.runPromise); + for (const { result, dispatched } of outcomes.slice(0, 4)) { + expect(result._tag).toBe("Failure"); + expect(dispatched).toEqual([]); + } + expect(JSON.stringify(outcomes[3]!.result)).toContain("agenixSecretCommand"); + const saved = outcomes[4]!; + expect(saved.result._tag).toBe("Success"); + expect(saved.result).toMatchObject({ success: { status: "saved", agenix: agenixResult } }); + expect(saved.dispatched[0]).toMatchObject({ delivery: "agenix", agenix }); +}); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 9d15408483a3e..7d772017dbe67 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -65,6 +65,7 @@ import { isOrchestrationV2WorkActive, resolveProjectProviderInstanceEnabled, SECRET_REQUEST_UNSAVED_NOTE, + SecretRequestError, } from "@t3tools/contracts"; import { getProviderOptionCurrentValue, withLegacyUltracodeEffort } from "@t3tools/shared/model"; import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; @@ -2170,6 +2171,29 @@ const make = Effect.gen(function* () { "Asking for a secret requires an active run owned by this MCP provider session.", ); } + if ((input.delivery === "agenix") !== (input.agenix !== undefined)) { + return yield* failure( + "invalid_request", + '`delivery: "agenix"` and `agenix` go together: pass both or neither.', + ); + } + if (input.delivery === "agenix") { + if (input.value !== undefined) { + return yield* failure( + "invalid_request", + "A pasted `value` is already in the transcript. Ask the user to enter it on an agenix card instead.", + ); + } + const settings = yield* serverSettings.getSettings.pipe( + Effect.mapError(() => failure("orchestration_error", "Unable to read server settings.")), + ); + if (settings.agenixSecretCommand.length === 0) { + return yield* failure( + "invalid_request", + new SecretRequestError({ reason: "agenix_not_configured" }).message, + ); + } + } // A secret the user already pasted needs no card: it goes straight to a file. if (input.value !== undefined) { if (input.delivery === "secretRef") { @@ -2212,7 +2236,10 @@ const make = Effect.gen(function* () { label: input.label, reason: input.reason, ...(input.placeholder === undefined ? {} : { placeholder: input.placeholder }), - ...(input.delivery === "file" ? { delivery: "file" as const } : {}), + ...(input.delivery === "file" || input.delivery === "agenix" + ? { delivery: input.delivery } + : {}), + ...(input.agenix === undefined ? {} : { agenix: input.agenix }), secretStatus, }) .pipe( @@ -2291,6 +2318,22 @@ const make = Effect.gen(function* () { yield* Effect.annotateCurrentSpan({ "secret_request.status": status }); yield* Metrics.increment(Metrics.secretRequestsTotal, { status }); if (status !== "saved") return { status, note: SECRET_REQUEST_UNSAVED_NOTE[status] }; + if (input.delivery === "agenix") { + const records = yield* threadManagement + .getThreadRecords(threadId, ["turnItems"], { + turnItemTypes: ["secret_request"], + messageRoles: [], + }) + .pipe(Effect.orElseSucceed(() => undefined)); + const item = records?.turnItems.find((candidate) => candidate.id === turnItemId); + if (item?.type !== "secret_request" || item.agenixResult === undefined) { + return yield* failure( + "orchestration_error", + "The user stored the secret, but its result could not be read. Do not ask again; ask the user to check agenix.", + ); + } + return { status, agenix: item.agenixResult }; + } if (input.delivery === "file") { const file = yield* secretRequests .saveToFile({ threadId, turnItemId }) diff --git a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts index 5ec8dfd49a17a..d52a721069b01 100644 --- a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts @@ -34,6 +34,7 @@ import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import * as ServerSettings from "../serverSettings.ts"; +import * as ProcessRunner from "../processRunner.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; @@ -250,6 +251,8 @@ describe("orchestrator MCP toolkit", () => { Layer.provide(Layer.mock(ProjectService.ProjectService)({})), Layer.provideMerge( SecretRequests.layer.pipe( + Layer.provide(ServerSettings.layerTest()), + Layer.provide(ProcessRunner.layer), Layer.provide(layerMemorySecretStore), Layer.provide(Layer.mock(SecretResolver.SecretResolver)({})), Layer.provide(layerOrchestration), diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index f0affbf6dec8c..4c1fcfb9de27e 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -197,7 +197,7 @@ const DeleteScheduledTaskTool = Tool.make("delete_scheduled_task", { const RequestSecretTool = Tool.make("request_secret", { description: - 'Ask for one secret per single-line card; never combine values. Open it, don\'t offer it. Returns one-use `secretRef`, or `delivery: "file"` a file read only in its command, e.g. `adb pair "$(cat )"`. Asked how: call now. Pasted secret for child/script: `value`. Never from an old thread.', + 'Ask for one secret per single-line card; never combine values. Open it, don\'t offer it. A secret to keep (token, key): `delivery: "agenix"` with an `agenix` target; it goes straight into agenix and you get only its path and commit. Otherwise one-use `secretRef`, or `delivery: "file"` a file read only in its command, e.g. `adb pair "$(cat )"`. Asked how: call now. Pasted secret for child/script: `value`. Never from an old thread.', 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 5d3c4391b1fe8..02e75c8953f19 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -9034,6 +9034,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio reason: command.reason, ...(command.placeholder === undefined ? {} : { placeholder: command.placeholder }), ...(command.delivery === undefined ? {} : { delivery: command.delivery }), + ...(command.agenix === undefined ? {} : { agenix: command.agenix }), + ...(command.agenixResult === undefined ? {} : { agenixResult: command.agenixResult }), secretStatus: command.secretStatus, }; if ( diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index ba1dadad1864c..37c2842349fe7 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -1,3 +1,4 @@ +import * as ProcessRunner from "../processRunner.ts"; import * as WorktreeBranchSync from "./WorktreeBranchSync.ts"; import * as GuestShareService from "../guest/GuestShareService.ts"; import * as UsageLimitRecoveryWorker from "./UsageLimitRecoveryWorker.ts"; @@ -279,7 +280,7 @@ const layerThreadLaunchProvided = ThreadLaunchService.layer.pipe( ), ); const layerSecretRequestsProvided = SecretRequests.layer.pipe( - Layer.provide(layerThreadManagementProvided), + Layer.provide(Layer.mergeAll(layerThreadManagementProvided, ProcessRunner.layer)), ); const layerScheduledTaskProvided = ScheduledTaskService.layer.pipe( Layer.provide( diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 0d9f26d44c40a..d524e676d599d 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 5366, "codexAdditionalContextBytes": 7096, - "mcpToolListJsonBytes": 48119 + "mcpToolListJsonBytes": 48764 } diff --git a/apps/server/src/secrets/SecretRequests.test.ts b/apps/server/src/secrets/SecretRequests.test.ts index f5f50c5a09a1a..86e9e8bd96d8e 100644 --- a/apps/server/src/secrets/SecretRequests.test.ts +++ b/apps/server/src/secrets/SecretRequests.test.ts @@ -11,10 +11,12 @@ import { SecretRef, ThreadId, TurnItemId, + type SecretAgenixTarget, } from "@t3tools/contracts"; import { defineSecretProviderDriver } from "@t3tools/secret-provider-core/server/driver"; import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; import { defineSecretProvider } from "@t3tools/secret-provider-core/shared/definition"; +import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; @@ -28,6 +30,8 @@ import * as Schema from "effect/Schema"; import * as TestClock from "effect/testing/TestClock"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import * as ProcessRunner from "../processRunner.ts"; +import * as ServerSettings from "../serverSettings.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import * as SecretRequests from "./SecretRequests.ts"; @@ -74,7 +78,9 @@ const withService = ( }) => Effect.Effect, options: { readonly threadId?: ThreadId; - readonly delivery?: "file"; + readonly delivery?: "file" | "agenix"; + readonly agenix?: SecretAgenixTarget; + readonly agenixCommand?: ReadonlyArray; readonly directory?: string; readonly runStatus?: string; readonly removeFails?: boolean; @@ -93,6 +99,8 @@ const withService = ( NodeCrypto.layer, NodeServices.layer, options.resolver ?? fakeVault().layer, + ServerSettings.layerTest({ agenixSecretCommand: [...(options.agenixCommand ?? [])] }), + ProcessRunner.layer.pipe(Layer.provide(NodeServices.layer)), Layer.succeed( ServerSecretStore.ServerSecretStore, ServerSecretStore.ServerSecretStore.of({ @@ -148,6 +156,7 @@ const withService = ( label: "GitHub token", reason: "Used as GH_TOKEN.", ...(options.delivery === undefined ? {} : { delivery: options.delivery }), + ...(options.agenix === undefined ? {} : { agenix: options.agenix }), secretStatus, }, ], @@ -205,22 +214,26 @@ it.effect("a saved answer becomes a one-use ref, and the thread only learns it w ); it.effect("a secret provider reference is read once and saved like a typed value", () => - withService(({ service, dispatched }) => - Effect.gen(function* () { - yield* service.answer({ - threadId, - turnItemId, - answer: { - type: "reference", - reference: { provider: vault, reference: "fake://github/token" }, - }, - }); - assert.include(dispatched[0] as object, { secretStatus: "saved" }); - assert.notInclude(JSON.stringify(dispatched), "fake://"); - const ref = Option.getOrThrow(yield* service.savedRef({ threadId, turnItemId })); - assert.equal(yield* service.consume({ ref, projectId }), "ghp_from_vault"); - }), - ), + Effect.gen(function* () { + const { state, layer } = fakeVault(); + const context = yield* Layer.build(layer); + const reference = { provider: vault, reference: "fake://github/token" }; + yield* withService( + ({ service, dispatched }) => + Effect.gen(function* () { + yield* service.answer({ threadId, turnItemId, answer: { type: "reference", reference } }); + assert.include(dispatched[0] as object, { secretStatus: "saved" }); + assert.notInclude(JSON.stringify(dispatched), "fake://"); + const ref = Option.getOrThrow(yield* service.savedRef({ threadId, turnItemId })); + assert.equal(yield* service.consume({ ref, projectId }), "ghp_from_vault"); + }), + { resolver: Layer.succeedContext(context) }, + ); + // Nothing stays in the resolver's cache once the answer is read. + state.unlocked = false; + const resolver = Context.get(context, SecretResolver.SecretResolver); + assert.deepEqual(yield* resolver.read([reference]), [undefined]); + }), ); it.effect( @@ -694,3 +707,119 @@ it.effect("a pasted secret is refused without a secrets directory", () => }), ), ); + +const agenixTarget: SecretAgenixTarget = { + user: "can", + name: "--host=evil", + expires: "never", + verifyUrl: "https://api.example.com/verify", +}; + +/** A fake `canix secret store` that records what it was given and answers like the real one. */ +const fakeStoreCommand = Effect.fn("fakeStoreCommand")(function* (directory: string, mode: string) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const script = path.join(directory, "fake-store.cjs"); + const seen = path.join(directory, "seen.json"); + yield* fs.writeFileString( + script, + `const fs = require("node:fs"); +const [, , seen, mode, ...flags] = process.argv; +const stdin = fs.readFileSync(0, "utf8"); +fs.writeFileSync(seen, JSON.stringify({ flags, env: process.env, stdin })); +if (mode === "fail") { + process.stdout.write(JSON.stringify({ error: { code: "verify_failed", message: "The token did not verify." } })); + process.exit(1); +} +if (mode === "stderr") { + process.stderr.write("error: unexpected argument '--x' found\\n\\nUsage: canix secret store\\n\\nFor more information, try '--help'.\\n"); + process.exit(2); +} +process.stdout.write(JSON.stringify({ path: "age/can/x.age", committed_sha: "abc123", verify: "pass", rekey: "not-needed", extra: "dropped" })); +`, + ); + return { command: [process.execPath, script, seen, mode], seen }; +}); + +it.live("an agenix answer goes to the store command on stdin only, and T3 keeps nothing", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "secret-agenix-test-" }); + const store = yield* fakeStoreCommand(directory, "ok"); + const value = "cf_token'$(id)"; + yield* withService( + ({ service, stored, dispatched }) => + Effect.gen(function* () { + yield* service.answer({ threadId, turnItemId, answer: { type: "save", secret: value } }); + const seen = JSON.parse(yield* fs.readFileString(store.seen)); + assert.equal(seen.stdin, value); + assert.deepEqual(seen.flags, [ + "--user=can", + "--name=--host=evil", + "--expires=never", + "--verify-url=https://api.example.com/verify", + "--bare", + ]); + assert.notInclude(JSON.stringify(seen.env), "cf_token"); + assert.deepEqual(valuesOf(stored), []); + assert.isFalse(yield* fs.exists(path.join(directory, "files"))); + assert.include(dispatched[0] as object, { secretStatus: "saved", delivery: "agenix" }); + assert.deepEqual((dispatched[0] as { agenixResult?: unknown }).agenixResult, { + path: "age/can/x.age", + committed_sha: "abc123", + verify: "pass", + rekey: "not-needed", + }); + assert.notInclude(JSON.stringify(dispatched), "cf_token"); + }), + { delivery: "agenix", agenix: agenixTarget, agenixCommand: store.command, directory }, + ); + }).pipe(Effect.provide(NodeServices.layer)), +); + +it.live("a failed or missing store command leaves the card open and keeps nothing", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "secret-agenix-test-" }); + const cases = [ + { mode: "fail", message: "The token did not verify. (verify_failed)" }, + { mode: "stderr", message: "error: unexpected argument '--x' found" }, + { mode: "none", message: "no agenix store command" }, + ]; + for (const { mode, message } of cases) { + const store = yield* fakeStoreCommand(directory, mode); + yield* withService( + ({ service, stored, dispatched }) => + Effect.gen(function* () { + const failed = yield* service + .answer({ threadId, turnItemId, answer: { type: "save", secret: "cf_token" } }) + .pipe(Effect.flip); + assert.include(failed.message, message); + assert.notInclude(failed.message, "cf_token"); + assert.deepEqual(dispatched, []); + assert.deepEqual(valuesOf(stored), []); + }), + { + delivery: "agenix", + agenix: agenixTarget, + agenixCommand: mode === "none" ? [] : store.command, + directory, + }, + ); + } + }).pipe(Effect.provide(NodeServices.layer)), +); + +it.effect("an agenix target names exactly one owner", () => + Effect.sync(() => { + const decode = (agenix: object) => + decodeSecretInputExit({ label: "Token", reason: "CI.", delivery: "agenix", agenix }); + assert.isTrue(Exit.isSuccess(decode({ host: "atlas", name: "x" }))); + assert.isTrue(Exit.isFailure(decode({ name: "x" }))); + assert.isTrue(Exit.isFailure(decode({ user: "can", host: "atlas", name: "x" }))); + assert.isTrue(Exit.isFailure(decode({ user: "can", name: "x", expires: "soon" }))); + assert.isTrue(Exit.isFailure(decode({ user: "can", name: "x", verifyUrl: "http://a" }))); + assert.isTrue(Exit.isFailure(decode({ user: "can", name: "x", env: ["CF-TOKEN"] }))); + }), +); diff --git a/apps/server/src/secrets/SecretRequests.ts b/apps/server/src/secrets/SecretRequests.ts index 8fcea2308568a..78a63c42774b0 100644 --- a/apps/server/src/secrets/SecretRequests.ts +++ b/apps/server/src/secrets/SecretRequests.ts @@ -1,12 +1,14 @@ // 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. -// A secret the user pasted in chat goes straight to such a file, with no card. +// A `file` request instead moves its value to an owner-only file for the agent's own shell, as +// does a secret pasted in chat. An `agenix` request hands its value to the configured store +// command on stdin and keeps nothing. import { CommandId, + SecretAgenixResult, SecretRef, SecretRequestError, type ProjectId, + type SecretAgenixTarget, type SecretReference, type SecretRequestAnswerInput, type ThreadId, @@ -28,6 +30,8 @@ import * as Semaphore from "effect/Semaphore"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; import * as Metrics from "../observability/Metrics.ts"; +import * as ProcessRunner from "../processRunner.ts"; +import * as ServerSettings from "../serverSettings.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; const SECRET_REF_PREFIX = "secret-ref:"; @@ -43,6 +47,38 @@ const StoredSecret = Schema.fromJsonString( const encodeStored = Schema.encodeEffect(StoredSecret); const decodeStored = Schema.decodeUnknownOption(StoredSecret); +const decodeAgenixResult = Schema.decodeUnknownOption(Schema.fromJsonString(SecretAgenixResult)); +const decodeAgenixError = Schema.decodeUnknownOption( + Schema.fromJsonString( + Schema.Struct({ + error: Schema.Struct({ + code: Schema.String, + message: Schema.String, + path: Schema.optional(Schema.String), + }), + }), + ), +); +const AGENIX_FLAGS = [ + ["user", "--user"], + ["rootModule", "--root-module"], + ["host", "--host"], + ["name", "--name"], + ["category", "--category"], + ["expires", "--expires"], + ["custodian", "--custodian"], + ["project", "--project"], + ["verifyUrl", "--verify-url"], +] as const; +// `--flag=value` so a value starting with `-` is never read as another flag. +const agenixStoreArgs = (target: SecretAgenixTarget) => [ + ...AGENIX_FLAGS.flatMap(([key, flag]) => { + const value = target[key]; + return value === undefined ? [] : [`${flag}=${value}`]; + }), + ...(target.env === undefined ? ["--bare"] : target.env.map((name) => `--env=${name}`)), +]; + export class SecretRequests extends Context.Service< SecretRequests, { @@ -77,6 +113,8 @@ const make = Effect.gen(function* () { const path = yield* Path.Path; const threadManagement = yield* ThreadManagementService.ThreadManagementService; const resolver = yield* SecretResolver.SecretResolver; + const serverSettings = yield* ServerSettings.ServerSettingsService; + const processRunner = yield* ProcessRunner.ProcessRunner; // 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"); @@ -99,7 +137,10 @@ const make = Effect.gen(function* () { ) { // The resolver keeps failed reads for the server's life; a retry after unlocking must re-read. yield* resolver.invalidate([reference]); - const [value] = yield* resolver.read([reference]); + // Read once: the value must not stay in the resolver's server-lifetime cache. + const [value] = yield* resolver + .read([reference]) + .pipe(Effect.ensuring(resolver.invalidate([reference]))); if (value === undefined || value.trim() === "") { return yield* new SecretRequestError({ reason: "reference_unreadable", @@ -109,6 +150,52 @@ const make = Effect.gen(function* () { return value; }); + // The value goes to the command on stdin only: never argv, env, a file or a log. + const storeInAgenix = Effect.fn("SecretRequests.storeInAgenix")(function* ( + target: SecretAgenixTarget | undefined, + value: string, + ) { + const settings = yield* serverSettings.getSettings.pipe( + Effect.mapError((cause) => new SecretRequestError({ reason: "load_failed", cause })), + ); + const [command, ...prefix] = settings.agenixSecretCommand; + if (command === undefined || target === undefined) { + return yield* new SecretRequestError({ reason: "agenix_not_configured" }); + } + const output = yield* processRunner + .run({ + command, + args: [...prefix, ...agenixStoreArgs(target)], + stdin: value, + timeout: "5 minutes", + maxOutputBytes: 64 * 1024, + outputMode: "truncate", + }) + .pipe( + Effect.mapError( + (cause) => new SecretRequestError({ reason: "agenix_failed", detail: cause.message }), + ), + ); + if (output.code === 0) { + const result = decodeAgenixResult(output.stdout.trim()); + if (Option.isSome(result)) return result.value; + return yield* new SecretRequestError({ + reason: "agenix_failed", + detail: "The store command exited 0 without a result; check whether it stored the value.", + }); + } + const failed = decodeAgenixError(output.stdout.trim()); + // Usage errors (clap) lead with `error:`; anything else ends with its reason. + const lines = output.stderr.trim().split("\n"); + const stderr = lines.find((line) => line.startsWith("error:")) ?? lines.at(-1); + return yield* new SecretRequestError({ + reason: "agenix_failed", + detail: Option.isSome(failed) + ? `${failed.value.error.message} (${failed.value.error.code})` + : stderr || `The store command exited with code ${output.code ?? "unknown"}.`, + }); + }); + const answer: SecretRequests["Service"]["answer"] = Effect.fn("SecretRequests.answer")( function* (input) { yield* Effect.annotateCurrentSpan({ @@ -138,9 +225,16 @@ const make = Effect.gen(function* () { : input.answer.type === "reference" ? yield* readReference(input.answer.reference) : undefined; + const agenix = item.delivery === "agenix"; + const agenixResult = + agenix && secret !== undefined ? yield* storeInAgenix(item.agenix, secret) : undefined; + const stored = + agenixResult === undefined + ? "" + : ` Stored at ${agenixResult.path} in ${agenixResult.committed_sha}.`; // Create before recording so racing answers cannot overwrite values or show saved before storage. // Existing values on pending cards finish earlier saves whose recording failed. - if (secret !== undefined) { + if (secret !== undefined && !agenix) { const encoded = yield* encodeStored({ projectId: records.thread.projectId, value: secret, @@ -171,13 +265,22 @@ const make = Effect.gen(function* () { reason: item.reason, ...(item.placeholder === undefined ? {} : { placeholder: item.placeholder }), ...(item.delivery === undefined ? {} : { delivery: item.delivery }), + ...(item.agenix === undefined ? {} : { agenix: item.agenix }), + ...(agenixResult === undefined ? {} : { agenixResult }), secretStatus, }) .pipe( - Effect.mapError((cause) => new SecretRequestError({ reason: "record_failed", cause })), + Effect.mapError( + (cause) => + new SecretRequestError({ + reason: "record_failed", + cause, + ...(stored === "" ? {} : { detail: stored.trim() }), + }), + ), // Clear failed saves so the pending card can be answered again. Effect.tapError(() => - secret !== undefined + secret !== undefined && !agenix ? refFor(input.threadId, item.id).pipe( Effect.flatMap((ref) => removeLogged(storeName(ref))), ) @@ -196,6 +299,9 @@ const make = Effect.gen(function* () { ); const card = recorded.turnItems.find((candidate) => candidate.id === item.id); if (card?.type === "secret_request" && card.secretStatus !== "saved") { + if (agenix) { + return yield* new SecretRequestError({ reason: "agent_stopped", detail: stored.trim() }); + } yield* removeLogged(storeName(yield* refFor(input.threadId, item.id))); return yield* new SecretRequestError({ reason: "agent_stopped" }); } diff --git a/apps/web/src/components/chat/SecretRequestCard.tsx b/apps/web/src/components/chat/SecretRequestCard.tsx index 6a78a7415575f..0445c8114855c 100644 --- a/apps/web/src/components/chat/SecretRequestCard.tsx +++ b/apps/web/src/components/chat/SecretRequestCard.tsx @@ -1,6 +1,7 @@ import { pipe } from "effect/Function"; import { SECRET_REQUEST_DEFAULT_PLACEHOLDER, + secretRequestAgenixDestination, secretRequestAnswerInput, secretRequestDisplay, secretRequestFailureMessage, @@ -150,6 +151,11 @@ function PendingSecretRequestForm(props: { {item.reason.trim() ? (

{item.reason}

) : null} + {secretRequestAgenixDestination(item).map((line) => ( +

+ {line} +

+ ))}
{sources.length > 0 ? ( diff --git a/docs/user/secrets.md b/docs/user/secrets.md index a1e793bba38aa..e6f9d8c8ca08b 100644 --- a/docs/user/secrets.md +++ b/docs/user/secrets.md @@ -61,3 +61,18 @@ The value never appears in the conversation. Most requests keep it from the agen passes it to the tool that needs it. When an agent has to run a command with the value, the card says so instead: the value goes into a private file that the agent's commands can read for about 24 hours. + +## Store a secret in agenix + +On a machine whose secrets live in agenix, an agent asking for a secret to keep, such as an API +token, should use an agenix card. The card shows where the value will go: the user, root module or +host, the secret's name, whether it is bare or wired to environment variables, and its expiry. If +it names a verify URL, that address receives the value as a Bearer token before anything is stored. + +When you save, T3 Code hands the value to the store command on its standard input and keeps no +copy. The agent learns only the stored path and commit. If the command fails, for example because +the token did not verify, the card shows why and stays open: fix the value and save again, or +decline. + +The command is `canix secret store` unless `settings.json` sets `agenixSecretCommand` to another +argument list. An empty list turns agenix cards off. diff --git a/packages/client-runtime/src/secretRequest.ts b/packages/client-runtime/src/secretRequest.ts index 26a32e735bcfb..024595e64497c 100644 --- a/packages/client-runtime/src/secretRequest.ts +++ b/packages/client-runtime/src/secretRequest.ts @@ -19,7 +19,36 @@ export type SecretRequestItem = Extract< export const secretRequestPrivacyNote = (item: Pick) => 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"; + : item.delivery === "agenix" + ? "Sent straight to agenix; T3 keeps no copy and the agent sees only where it went" + : "Stored securely, never shown to the agent"; + +/** Where an `agenix` card stores its value, so the user can check it before saving. */ +export function secretRequestAgenixDestination( + item: Pick, +): ReadonlyArray { + const target = item.agenix; + if (target === undefined) return []; + const owner = + target.user !== undefined + ? `user ${target.user}` + : target.rootModule !== undefined + ? `root module ${target.rootModule}` + : `host ${target.host}`; + const details = [ + target.category === undefined ? null : `category ${target.category}`, + target.expires === undefined ? null : `expires ${target.expires}`, + target.custodian === undefined ? null : `custodian ${target.custodian}`, + target.project === undefined ? null : `project ${target.project}`, + ].filter((detail) => detail !== null); + return [ + `Stores ${target.name} for ${owner}, ${target.env === undefined ? "bare" : `as ${target.env.join(", ")}`}`, + ...(details.length === 0 ? [] : [details.join(" ยท ")]), + ...(target.verifyUrl === undefined + ? [] + : [`Checked first at ${target.verifyUrl}, which receives the value as a Bearer token`]), + ]; +} export const SECRET_REQUEST_DEFAULT_PLACEHOLDER = "Paste the secret"; export type SecretRequestDisplay = @@ -57,14 +86,20 @@ const PENDING_ELSEWHERE_DISPLAY: SecretRequestDisplay = { * thread (a fork) can only be answered where it was asked. */ export function secretRequestDisplay( - item: Pick, + item: Pick, visibility: "local" | "inherited" | "synthetic", ): SecretRequestDisplay { switch (item.secretStatus) { case "pending": return visibility === "local" ? PENDING_DISPLAY : PENDING_ELSEWHERE_DISPLAY; case "saved": - return SAVED_DISPLAY; + return item.agenixResult === undefined + ? SAVED_DISPLAY + : { + kind: "answered", + outcome: "saved", + label: `Stored in agenix at ${item.agenixResult.path}`, + }; case "declined": return DECLINED_DISPLAY; case "cancelled": diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 5c430ef75581a..dbccee5eae6e8 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1,5 +1,6 @@ import { OrchestrationMessageContext } from "./composerContext.ts"; import { withRecordIdTable } from "./orchestrationV2IdTable.ts"; +import { SecretAgenixResult, SecretAgenixTarget } from "./secretRequest.ts"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; @@ -1555,8 +1556,11 @@ 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"); +/** + * `file`: the value goes to an owner-only file the agent's shell commands can read. + * `agenix`: the value goes straight to the configured store command; T3 keeps nothing. + */ +export const OrchestrationV2SecretRequestDelivery = Schema.Literals(["file", "agenix"]); const OrchestrationV2SecretRequestFields = { type: Schema.Literal("secret_request"), @@ -1564,6 +1568,8 @@ const OrchestrationV2SecretRequestFields = { reason: Schema.String, placeholder: Schema.optional(Schema.String), delivery: Schema.optional(OrchestrationV2SecretRequestDelivery), + agenix: Schema.optional(SecretAgenixTarget), + agenixResult: Schema.optional(SecretAgenixResult), secretStatus: OrchestrationV2SecretRequestStatus, } as const; @@ -3549,6 +3555,8 @@ const OrchestrationV2InternalCommand = Schema.Union([ reason: Schema.String, placeholder: Schema.optional(Schema.String), delivery: Schema.optional(OrchestrationV2SecretRequestDelivery), + agenix: Schema.optional(SecretAgenixTarget), + agenixResult: Schema.optional(SecretAgenixResult), secretStatus: OrchestrationV2SecretRequestStatus, }), /** diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index c73bbd48e26f5..c548b2d6e0c7a 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -41,6 +41,7 @@ import { OrchestrationV2TurnItemStatus, } from "./orchestrationV2.ts"; import { ProviderOptionSelection, ProviderOptionSelectionValue } from "./model.ts"; +import { SecretAgenixResult, SecretAgenixTarget } from "./secretRequest.ts"; import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts"; const OrchestratorMcpPrompt = TrimmedNonEmptyString.check(Schema.isMaxLength(120_000)); @@ -755,8 +756,11 @@ export const OrchestratorMcpRequestSecretInput = Schema.Struct({ description: "What it is for and where to get it.", }), placeholder: Schema.optional(TrimmedNonEmptyString), - delivery: Schema.optional(Schema.Literals(["secretRef", "file"])).annotate({ - description: "secretRef (default) for a T3 tool; file for a command.", + delivery: Schema.optional(Schema.Literals(["secretRef", "file", "agenix"])).annotate({ + description: "agenix: a secret to keep. secretRef (default): a T3 tool. file: a command.", + }), + agenix: Schema.optional(SecretAgenixTarget).annotate({ + description: "One of user/rootModule/host. env omitted: bare. verifyUrl gets it as Bearer.", }), value: Schema.optional(PastedSecretValue).annotate({ description: "Pasted in this thread; no card.", @@ -785,6 +789,10 @@ export const OrchestratorMcpRequestSecretResult = Schema.Union([ "Owner-only file with the value. Read it inside commands and never print it. Deleted after 24 hours.", }), }), + Schema.Struct({ + status: Schema.Literal("saved").annotate({ description: "Stored and committed in agenix." }), + agenix: SecretAgenixResult, + }), 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 4c74e9fcca3e7..0765304a18747 100644 --- a/packages/contracts/src/secretRequest.ts +++ b/packages/contracts/src/secretRequest.ts @@ -3,6 +3,46 @@ import * as Schema from "effect/Schema"; import { ThreadId, TrimmedNonEmptyString, TurnItemId } from "./baseSchemas.ts"; import { SecretReference } from "./secretReference.ts"; +const AgenixName = TrimmedNonEmptyString.check(Schema.isMaxLength(200)); + +/** Where `delivery: "agenix"` stores a value; becomes the store command's flags. */ +export const SecretAgenixTarget = Schema.Struct({ + user: Schema.optional(AgenixName), + rootModule: Schema.optional(AgenixName), + host: Schema.optional(AgenixName), + name: AgenixName, + /** Environment variables the secret is wired to; leave out for a bare secret. */ + env: Schema.optional( + Schema.Array(Schema.String.check(Schema.isPattern(/^[A-Za-z_][A-Za-z0-9_]*$/))).check( + Schema.isMinLength(1), + ), + ), + category: Schema.optional(AgenixName), + expires: Schema.optional(Schema.String.check(Schema.isPattern(/^(?:\d{4}-\d{2}-\d{2}|never)$/))), + custodian: Schema.optional(AgenixName), + project: Schema.optional(AgenixName), + /** Called with the value as a Bearer token before it is stored; pass/fail only. */ + verifyUrl: Schema.optional(TrimmedNonEmptyString.check(Schema.isPattern(/^https:\/\//))), +}).check( + Schema.makeFilter( + (target) => + [target.user, target.rootModule, target.host].filter((owner) => owner !== undefined) + .length === 1, + { expected: "exactly one of user, rootModule or host" }, + ), +); +export type SecretAgenixTarget = typeof SecretAgenixTarget.Type; + +/** The store command's result: metadata only, never the value. */ +export const SecretAgenixResult = Schema.Struct({ + path: Schema.String, + committed_sha: Schema.String, + verify: Schema.String, + rekey: Schema.String, + rops_id: Schema.optional(Schema.String), +}); +export type SecretAgenixResult = typeof SecretAgenixResult.Type; + /** Server stores the value under a one-use SecretRef; the thread learns only status. */ export const SecretRequestAnswerInput = Schema.Struct({ threadId: ThreadId, @@ -42,6 +82,9 @@ const SECRET_REQUEST_FAILURE_MESSAGES = { 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".', + agenix_not_configured: + 'This T3 server has no agenix store command (setting "agenixSecretCommand"). Ask with another delivery.', + agenix_failed: "Could not store the secret in agenix.", } as const; export const SecretRequestFailureReason = Schema.Literals( @@ -57,6 +100,8 @@ export class SecretRequestError extends Schema.TaggedError() reason: SecretRequestFailureReason, /** The secret provider a `reference_unreadable` answer named. */ provider: Schema.optionalKey(Schema.String), + /** Shown after the message; never holds the value. */ + detail: Schema.optionalKey(Schema.String), cause: Schema.optionalKey(Schema.Defect()), }, ) { @@ -64,6 +109,7 @@ export class SecretRequestError extends Schema.TaggedError() if (this.reason === "reference_unreadable" && this.provider !== undefined) { return `Could not read the secret from the secret provider "${this.provider}". Unlock it and try again, or enter the value.`; } - return SECRET_REQUEST_FAILURE_MESSAGES[this.reason]; + const message = SECRET_REQUEST_FAILURE_MESSAGES[this.reason]; + return this.detail === undefined ? message : `${message} ${this.detail}`; } } diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index f6409a87074fd..ac67daff4689d 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1449,6 +1449,10 @@ export const ServerSettings = Schema.Struct({ secretProviders: Schema.Record(SecretProviderId, SecretProviderConfig).pipe( Schema.withDecodingDefault(Effect.succeed({})), ), + /** argv `request_secret` runs for `delivery: "agenix"`, value on stdin; empty refuses it. Edit in settings.json. */ + agenixSecretCommand: Schema.Array(Schema.String).pipe( + Schema.withDecodingDefault(Effect.succeed(["canix", "secret", "store"])), + ), usagePriceOverrides: Schema.Record(TrimmedNonEmptyString, UsageModelPriceOverride).pipe( Schema.withDecodingDefault(Effect.succeed({})),