From f61e9816c141744ef673d49833c7130cee078e72 Mon Sep 17 00:00:00 2001 From: Codeping223 Date: Sun, 25 Oct 2026 16:12:19 +0900 Subject: [PATCH 1/4] feat(cli): expose scoped native approval and question requests --- docs/readme/agent-requests-cli.md | 127 ++++++++ src/cli/agent-request-answer-file.ts | 96 ++++++ src/cli/agent-request-answer.test.ts | 308 ++++++++++++++++++ src/cli/agent-request-answer.ts | 244 ++++++++++++++ src/cli/agent-request-capabilities.ts | 13 + src/cli/agent-request-handlers.test.ts | 121 +++++++ src/cli/agent-request-inventory.test.ts | 179 ++++++++++ src/cli/agent-request-inventory.ts | 257 +++++++++++++++ src/cli/agent-request-test-fixtures.ts | 126 +++++++ src/cli/agent-request-transport.test.ts | 33 ++ src/cli/handler-group-manifest.ts | 5 + src/cli/handlers/agent-requests.ts | 69 ++++ src/cli/root-help-text-primary.ts | 1 + src/cli/runtime/client.ts | 50 +-- src/cli/runtime/remote-runtime-compat-gate.ts | 12 +- src/cli/runtime/runtime-source-fence.test.ts | 44 ++- src/cli/runtime/runtime-source-fence.ts | 21 ++ src/cli/runtime/status.ts | 37 +++ src/cli/runtime/websocket-transport.test.ts | 46 ++- src/cli/runtime/websocket-transport.ts | 24 +- src/cli/specs/agent-requests.ts | 42 +++ src/cli/specs/index.ts | 2 + src/shared/remote-runtime-client.test.ts | 36 ++ src/shared/remote-runtime-client.ts | 18 +- src/shared/remote-runtime-memory-limits.ts | 4 +- .../requests/remote-runtime-request-socket.ts | 12 +- 26 files changed, 1868 insertions(+), 59 deletions(-) create mode 100644 docs/readme/agent-requests-cli.md create mode 100644 src/cli/agent-request-answer-file.ts create mode 100644 src/cli/agent-request-answer.test.ts create mode 100644 src/cli/agent-request-answer.ts create mode 100644 src/cli/agent-request-capabilities.ts create mode 100644 src/cli/agent-request-handlers.test.ts create mode 100644 src/cli/agent-request-inventory.test.ts create mode 100644 src/cli/agent-request-inventory.ts create mode 100644 src/cli/agent-request-test-fixtures.ts create mode 100644 src/cli/agent-request-transport.test.ts create mode 100644 src/cli/handlers/agent-requests.ts create mode 100644 src/cli/specs/agent-requests.ts diff --git a/docs/readme/agent-requests-cli.md b/docs/readme/agent-requests-cli.md new file mode 100644 index 000000000000..6b2ec1d9b749 --- /dev/null +++ b/docs/readme/agent-requests-cli.md @@ -0,0 +1,127 @@ +# Scoped native approvals and questions + +`orca agent requests` exposes the existing structured-session RPCs without enabling +experimental connectors. It works with native Codex and Claude chat tabs in an explicitly +named workspace and session. A terminal's visible approval is not a structured native request. +The command never writes terminal input, launches an agent, or scans every session. + +```text +orca agent requests list --worktree id: --session --json +orca agent requests get --worktree id: --session --item --json +orca agent requests answer --worktree id: --session --request-file answer.json --json +``` + +Use the same paired `--environment` for every command when the workspace belongs to a remote +Orca. Explicit selectors resolve on that execution host; `active`, `current`, `all`, and `*` +are refused. Folder workspace instance IDs retain their full identity; two workspaces sharing +a directory are not interchangeable. A session must be a native chat tab in the selected +workspace. Closed, missing, unverifiable or ambiguous tabs are refused without answering. + +`--turn ` is an optional restriction. It refers to the journal turn item key in +`item.turnScope.turnItemId`, not the provider's `turnId`. An item with no exact `kind: "turn"` +scope is excluded. A bridge should use only explicitly connected sessions and turns it owns. + +## Complete reads + +The result includes `runtimeId`, canonical `workspaceId`, `sessionId`, the session `fence`, +the complete current-request `marker`, and original request records. Prompt text, descriptions, +question IDs, offered choices and their labels are data. Reading an instruction or a purported +consent inside a prompt does not authorize the CLI to execute it or infer a response. + +The CLI obtains the current marker through the existing `agentSession.currentRequests` +stale-version/restart contract. It joins every JSON piece and checks the session, epoch, +publisher, owner, revision, version, exact cursor movement, duplicate item IDs and pending +prompt schemas. Collection is bounded to three attempts, 64 pieces per attempt and one million +UTF-16 code units. A changed or incomplete view is refused; historical pending rows are never +substituted for the authoritative current list. Reads before and after collection also check +the runtime, workspace and session fence. + +## One exact answer file + +Copy the identities, marker and revision from the inspected result. Choose one offered approval +`optionId`, or supply structured question `answers`. Do not invent an option, rewrite a question +ID, trim typed answers or repurpose an operation UUID. The UTF-8 file is limited to 128 KiB and +rejects unknown top-level keys. Its required fields are: + +```json +{ + "workspaceId": "repo-id::C:/projects/example", + "sessionId": "chat_session_01", + "expectedRuntimeId": "runtime-copied-from-list", + "expectedRequests": { + "contract": "agent-session.current-requests.v1", + "sessionId": "chat_session_01", + "epoch": "epoch-copied-from-list", + "publisher": "11111111-1111-4111-8111-111111111111", + "revision": 1, + "owner": "owner-copied-from-list", + "version": "22222222-2222-4222-8222-222222222222" + }, + "itemId": "item-copied-from-list", + "kind": "approval", + "expectedRuntimeFence": 7, + "expectedRevision": 1, + "clientOperationId": "33333333-3333-4333-8333-333333333333", + "optionId": "exact-offered-id" +} +``` + +For a question use `"kind": "question"` and replace `optionId` with: + +```json +{ + "answers": [ + { + "questionId": "exact-question-id", + "optionIds": ["exact-offered-id"], + "other": "An exact typed answer, only when that question permits one.\nNewlines are preserved." + } + ] +} +``` + +The shared native question schema and host validation decide which selections and free text +are permitted. Optional `turnItemId` binds the file to one journal turn. If `--turn` is also +passed, the values must match. All provider-offered options retain their original meaning, +including any broader scope described by a provider. The CLI adds no approve-all flags or +automatic approval policy. A UI relaying an option must disclose its actual scope to its user. + +On an initial answer the CLI compares the runtime, workspace, session, complete marker, fence, +item revision, kind, and any turn restriction again. It computes `payloadFingerprint` with the +existing shared canonical fingerprint function. The host performs its existing lease, +current-provider ownership, question/option and revision checks. Newer hosts do not independently +enforce the envelope's expected fence: the CLI's initial comparison is distinct from those +host checks. + +Answering also requires `runtime-source-fence.v1` and a host installation identity. The inspected +runtime and installation are carried in the existing `expectedRuntimeSource` wire field, which +the host checks before invoking any handler. This works on local sockets and paired sockets. +The pin is a separate transport argument, not part of the orchestration forwarding envelope. +Ordinary terminal/orchestration calls retain their existing behavior. Older hosts that would +ignore the pin are refused without mutation. + +## Receipts, retries and unknown outcomes + +A successful result says `outcome: "accepted"`, preserves the host receipt and its `replayed` +flag, and explicitly says `resumed: "unverified"`. It verifies the returned item, resolved +selection or exact answers, and revision before reporting acceptance. A durable answer may have +been committed before the provider connection failed. Acceptance is therefore not proof of +provider resumption or task completion; follow subsequent authoritative status separately. + +After a lost response, inspect the session first. If deliberately replaying the same operation, +reuse the exact original file and pass its UUID: + +```text +orca agent requests answer --worktree id: --session --request-file answer.json --retry --json +``` + +`--retry` must equal the file UUID. It sends that same native operation once and allows the +host's existing receipt-first replay even when the original prompt is no longer pending, its +marker changed or its fence advanced. Runtime, session and workspace must still match. The CLI +does not generate a fresh operation, retry automatically, choose another pending question or +claim that an unknown outcome failed. Explicit host refusals retain their code; uncertain +transport or mismatched receipts remain unknown. A closed tab whose workspace identity can no +longer be proved is refused even for replay. + +No permission rejection, human-only platform requirement or unsupported native workflow is +bypassed by these commands. Update the execution host when its native contracts are missing. diff --git a/src/cli/agent-request-answer-file.ts b/src/cli/agent-request-answer-file.ts new file mode 100644 index 000000000000..d60143f82250 --- /dev/null +++ b/src/cli/agent-request-answer-file.ts @@ -0,0 +1,96 @@ +import { readFile, stat } from 'node:fs/promises' +import { z } from 'zod' +import { RuntimeClientError } from './runtime/types' +import { AgentRequestMarkerSchema } from './agent-request-inventory' +import { + RespondParams, + RespondToQuestionParams +} from '../shared/rpc-contract/structured-agent-session-params' +import { structuredAgentSessionPayloadFingerprint } from '../shared/structured-agent-session-mutation' + +const AnswerFile = z + .object({ + workspaceId: z.string().min(1), + sessionId: z.string().min(1), + expectedRuntimeId: z.string().min(1), + expectedRequests: AgentRequestMarkerSchema, + itemId: z.string().min(1), + kind: z.enum(['approval', 'question']), + expectedRuntimeFence: z.number().int().positive(), + expectedRevision: z.number().int().positive(), + clientOperationId: z.string().uuid(), + turnItemId: z.string().min(1).optional(), + optionId: z.string().optional(), + answers: z.unknown().optional() + }) + .strict() +export type AgentRequestAnswerFile = z.infer + +export async function readAgentRequestAnswerFile(path: string): Promise { + try { + const info = await stat(path) + if (!info.isFile() || info.size > 128 * 1024) { + throw new Error('size') + } + const content = await readFile(path, 'utf8') + if (Buffer.byteLength(content, 'utf8') > 128 * 1024) { + throw new Error('size') + } + return parseAgentRequestAnswerFile(JSON.parse(content.replace(/^\uFEFF/, ''))) + } catch { + throw new RuntimeClientError( + 'invalid_argument', + 'The request file is not a valid bounded native answer JSON file.' + ) + } +} + +export function parseAgentRequestAnswerFile(value: unknown): AgentRequestAnswerFile { + const parsed = AnswerFile.safeParse(value) + if (!parsed.success || parsed.data.expectedRequests.sessionId !== parsed.data.sessionId) { + throw new RuntimeClientError( + 'invalid_argument', + 'The request file has an invalid native request identity.' + ) + } + // The existing host schema preserves question ids, selected ids and UTF-8 typed answers verbatim. + nativeAnswerParams(parsed.data) + return parsed.data +} + +export function nativeAnswerParams(input: AgentRequestAnswerFile) { + const envelope = { + sessionId: input.sessionId, + clientOperationId: input.clientOperationId, + expectedRuntimeFence: input.expectedRuntimeFence, + payloadFingerprint: '0'.repeat(64) + } + const fields = { + itemId: input.itemId, + expectedRevision: input.expectedRevision, + ...(input.optionId === undefined ? {} : { optionId: input.optionId }), + ...(input.answers === undefined ? {} : { answers: input.answers }) + } + const parsed = + input.kind === 'approval' + ? RespondParams.safeParse({ envelope, ...fields }) + : RespondToQuestionParams.safeParse({ envelope, ...fields }) + if (!parsed.success) { + throw new RuntimeClientError( + 'invalid_argument', + 'The answer does not match the native approval/question schema.' + ) + } + const { envelope: _envelope, ...answerFields } = parsed.data + return { + ...answerFields, + envelope: { + ...envelope, + payloadFingerprint: structuredAgentSessionPayloadFingerprint({ + method: `agentSession.respondTo:${input.kind}`, + sessionId: input.sessionId, + fields: answerFields + }) + } + } +} diff --git a/src/cli/agent-request-answer.test.ts b/src/cli/agent-request-answer.test.ts new file mode 100644 index 000000000000..d1b6be231f9f --- /dev/null +++ b/src/cli/agent-request-answer.test.ts @@ -0,0 +1,308 @@ +import { describe, expect, it } from 'vitest' +import { answerAgentRequest } from './agent-request-answer' +import { nativeAnswerParams, parseAgentRequestAnswerFile } from './agent-request-answer-file' +import { + REQUEST_MARKER, + REQUEST_PROMPT, + REQUEST_RUNTIME, + REQUEST_SESSION, + REQUEST_SOURCE, + REQUEST_WORKSPACE, + answerFile, + requestFixtureClient +} from './agent-request-test-fixtures' +import { RuntimeRpcFailureError } from './runtime/types' +import { computeAgentSessionPayloadFingerprint } from '../shared/agent-session-mutation-envelope' +import { AGENT_REQUEST_CLI_CAPABILITIES } from './agent-request-capabilities' + +const scope = { worktree: `id:${REQUEST_WORKSPACE}`, sessionId: REQUEST_SESSION } +const ok = (result: unknown) => ({ + id: 'test', + ok: true, + _meta: { runtimeId: REQUEST_RUNTIME }, + result +}) +const isMutation = (method: string) => method.startsWith('agentSession.respondTo') + +describe('native answer JSON and admission', () => { + it('preserves exact grouped question ids, choices, newlines and UTF-8 answer text', () => { + const input = answerFile() + const { optionId: _option, ...base } = input + const answers = [ + { + questionId: ' 원문 질문 / 1 ', + optionIds: ['option:%20한글'], + other: '첫 줄\n둘째 줄 "인용" C:\\경로\\파일' + } + ] + const parsed = parseAgentRequestAnswerFile({ ...base, kind: 'question', answers }) + const params = nativeAnswerParams(parsed) + expect('answers' in params && params.answers).toEqual(answers) + const { envelope, ...fields } = params + expect(envelope.payloadFingerprint).toBe( + computeAgentSessionPayloadFingerprint({ + method: 'agentSession.respondTo:question', + sessionId: REQUEST_SESSION, + fields + }) + ) + }) + + it.each([ + { clientOperationId: 'not-a-uuid' }, + { kind: 'approve-all' }, + { expectedRuntimeFence: 0 }, + { expectedRevision: 0 }, + { extra: 'ignored?' }, + { expectedRequests: [] }, + { optionId: undefined }, + { answers: [] } + ])('rejects malformed input without silently changing its meaning: %j', (change) => { + expect(() => parseAgentRequestAnswerFile({ ...answerFile(), ...change })).toThrow() + }) + + it('sends one host-fenced exact answer and distinguishes acceptance from resumption', async () => { + const { client, call } = requestFixtureClient() + const input = parseAgentRequestAnswerFile(answerFile()) + const result = await answerAgentRequest(client, scope, input) + expect(result.result).toMatchObject({ + outcome: 'accepted', + resumed: 'unverified', + clientOperationId: input.clientOperationId, + result: { replayed: false } + }) + const calls = call.mock.calls.filter(([method]) => isMutation(method)) + expect(calls).toHaveLength(1) + expect(calls[0]?.[2]).toEqual({ + expectedRuntimeSource: { sourceId: REQUEST_SOURCE, runtimeId: REQUEST_RUNTIME } + }) + expect(calls[0]?.[1]).toEqual(nativeAnswerParams(input)) + }) + + it('delivers a grouped typed question answer and verifies its exact receipt', async () => { + const answers = [ + { questionId: ' 원문 질문 ID ', optionIds: [], other: ' 첫 줄\n둘째 줄 한글 ' } + ] + const question = { + ...REQUEST_PROMPT, + body: { + kind: 'question', + question: '원문 질문', + options: [], + questions: [ + { + id: answers[0].questionId, + question: '원문 질문', + options: [], + multiSelect: false, + freeTextQuestionId: 'typed-answer', + freeTextInput: { multiline: true } + } + ], + resolution: { state: 'pending', selectedOptionId: null, resolvedBy: null, resolvedAt: null } + } + } + const { client, call } = requestFixtureClient((method, params) => { + if ( + method === 'agentSession.currentRequests' && + typeof params === 'object' && + params !== null && + 'version' in params && + params.version === REQUEST_MARKER.version + ) { + return ok({ marker: REQUEST_MARKER, json: JSON.stringify([question]), nextCursor: null }) + } + if (method === 'agentSession.respondToQuestion') { + return ok({ + ok: true, + replayed: false, + fence: 7, + cursor: { epoch: REQUEST_MARKER.epoch, sequence: 2 }, + value: { + itemId: REQUEST_PROMPT.itemId, + revision: 2, + resolution: { + state: 'resolved', + selectedOptionId: 'question-group:recorded', + answers, + resolvedBy: 'caller', + resolvedAt: 100 + } + } + }) + } + return undefined + }) + const { optionId: _option, ...base } = answerFile() + const input = parseAgentRequestAnswerFile({ ...base, kind: 'question', answers }) + const result = await answerAgentRequest(client, scope, input) + expect(result.result.outcome).toBe('accepted') + expect(result.result.result.value.resolution.answers).toEqual(answers) + const mutation = call.mock.calls.filter(([method]) => isMutation(method)) + expect(mutation).toHaveLength(1) + expect(mutation[0]?.[0]).toBe('agentSession.respondToQuestion') + expect(mutation[0]?.[1]).toEqual(nativeAnswerParams(input)) + }) + + it.each(['runtime', 'workspace', 'marker', 'fence', 'turn'])( + 'refuses changed %s before mutation', + async (kind) => { + const { client, call } = requestFixtureClient() + const input = parseAgentRequestAnswerFile({ + ...answerFile(), + ...(kind === 'runtime' ? { expectedRuntimeId: 'different-runtime' } : {}), + ...(kind === 'workspace' ? { workspaceId: 'different::/workspace' } : {}), + ...(kind === 'marker' + ? { expectedRequests: { ...REQUEST_MARKER, owner: 'different-owner' } } + : {}), + ...(kind === 'fence' ? { expectedRuntimeFence: 99 } : {}), + ...(kind === 'turn' ? { turnItemId: 'different-turn' } : {}) + }) + await expect(answerAgentRequest(client, scope, input)).rejects.toMatchObject({ + code: 'agent_request_unverifiable' + }) + expect(call.mock.calls.filter(([method]) => isMutation(method))).toHaveLength(0) + } + ) + + it('rechecks workspace identity after collecting the current requests', async () => { + let reads = 0 + const { client, call } = requestFixtureClient((method) => { + if (method !== 'session.tabs.list') { + return + } + reads += 1 + return ok({ + worktree: reads === 1 ? REQUEST_WORKSPACE : 'other::/workspace', + tabs: [{ type: 'agent-session', id: 'tab', sessionId: REQUEST_SESSION, agent: 'codex' }] + }) + }) + await expect( + answerAgentRequest(client, scope, parseAgentRequestAnswerFile(answerFile())) + ).rejects.toMatchObject({ code: 'agent_request_unverifiable' }) + expect(call.mock.calls.filter(([method]) => isMutation(method))).toHaveLength(0) + }) + + it('requires host atomic-source-fence capability before sending', async () => { + const { client, call } = requestFixtureClient((method) => + method === 'status.get' + ? ok({ + runtimeId: REQUEST_RUNTIME, + capabilities: AGENT_REQUEST_CLI_CAPABILITIES, + hostDescriptor: { installationId: REQUEST_SOURCE } + }) + : undefined + ) + await expect( + answerAgentRequest(client, scope, parseAgentRequestAnswerFile(answerFile())) + ).rejects.toMatchObject({ code: 'incompatible_runtime' }) + expect(call.mock.calls.filter(([method]) => isMutation(method))).toHaveLength(0) + }) + + it('replays the same operation without requiring a still-pending prompt or current fence', async () => { + const { client, call } = requestFixtureClient((method) => { + if (method === 'agentSession.currentRequests') { + throw new Error('must not select a new prompt') + } + if (isMutation(method)) { + return ok({ + ok: true, + replayed: true, + fence: 88, + cursor: { epoch: 'epoch-later', sequence: 100 }, + value: { + itemId: answerFile().itemId, + revision: 2, + resolution: { + state: 'resolved', + selectedOptionId: 'approve', + resolvedBy: 'caller', + resolvedAt: 100 + } + } + }) + } + return undefined + }) + const input = parseAgentRequestAnswerFile({ ...answerFile(), expectedRuntimeFence: 6 }) + const result = await answerAgentRequest(client, scope, input, input.clientOperationId) + expect(result.result.result.replayed).toBe(true) + expect( + call.mock.calls.filter(([method]) => method === 'agentSession.currentRequests') + ).toHaveLength(0) + expect(call.mock.calls.filter(([method]) => isMutation(method))).toHaveLength(1) + await expect( + answerAgentRequest(client, scope, input, '44444444-4444-4444-8444-444444444444') + ).rejects.toMatchObject({ code: 'invalid_argument' }) + }) + + it('retains a definitive permission refusal instead of calling it a timeout', async () => { + const { client } = requestFixtureClient((method) => { + if (isMutation(method)) { + throw new RuntimeRpcFailureError({ + id: 'refused', + ok: false, + error: { code: 'forbidden', message: 'Host permission denied' }, + _meta: { runtimeId: REQUEST_RUNTIME } + }) + } + }) + await expect( + answerAgentRequest(client, scope, parseAgentRequestAnswerFile(answerFile())) + ).rejects.toMatchObject({ + code: 'forbidden', + data: { outcome: 'refused', resumed: 'unverified' } + }) + }) + + it('never automatically retries an uncertain transport result', async () => { + const { client, call } = requestFixtureClient((method) => { + if (isMutation(method)) { + throw new Error('response lost after acceptance') + } + }) + await expect( + answerAgentRequest(client, scope, parseAgentRequestAnswerFile(answerFile())) + ).rejects.toMatchObject({ + code: 'agent_session_operation_unknown', + data: { + outcome: 'unknown', + clientOperationId: answerFile().clientOperationId + } + }) + expect(call.mock.calls.filter(([method]) => isMutation(method))).toHaveLength(1) + }) + + it.each(['item', 'choice', 'revision', 'malformed'])( + 'does not label a mismatched %s receipt accepted', + async (kind) => { + const { client } = requestFixtureClient((method) => { + if (!isMutation(method)) { + return + } + if (kind === 'malformed') { + return ok({ ok: true }) + } + return ok({ + ok: true, + replayed: false, + fence: 7, + cursor: { epoch: REQUEST_MARKER.epoch, sequence: 2 }, + value: { + itemId: kind === 'item' ? 'different-item' : answerFile().itemId, + revision: kind === 'revision' ? 0 : 2, + resolution: { + state: 'resolved', + selectedOptionId: kind === 'choice' ? 'deny' : 'approve', + resolvedBy: 'caller', + resolvedAt: 100 + } + } + }) + }) + await expect( + answerAgentRequest(client, scope, parseAgentRequestAnswerFile(answerFile())) + ).rejects.toMatchObject({ code: 'agent_session_operation_unknown' }) + } + ) +}) diff --git a/src/cli/agent-request-answer.ts b/src/cli/agent-request-answer.ts new file mode 100644 index 000000000000..c0b8f83710f7 --- /dev/null +++ b/src/cli/agent-request-answer.ts @@ -0,0 +1,244 @@ +import { nativeAnswerParams, type AgentRequestAnswerFile } from './agent-request-answer-file' +import { z } from 'zod' +import { RuntimeClientError, RuntimeRpcFailureError } from './runtime/types' +import type { RuntimeRpcSuccess } from './runtime-client' +import { + listAgentRequests, + readRequestHost, + requireSameRuntime, + sameRequestMarker, + verifyRequestWorkspace, + type AgentRequestClient, + type AgentRequestScope +} from './agent-request-inventory' +import { structuredAgentSessionPayloadFingerprint } from '../shared/structured-agent-session-mutation' +import { + agentSessionPromptQuestions, + isValidAgentSessionQuestionAnswers +} from '../shared/agent-session-question-answer' +import type { + AgentSessionMutationResult, + AgentSessionPromptResult +} from '../shared/agent-session-wire' +import { AGENT_SESSION_QUESTION_ANSWERS_RUNTIME_CAPABILITY } from '../shared/protocol-version' +import { RUNTIME_SOURCE_FENCE_RUNTIME_CAPABILITY } from '../shared/host-runtime-capabilities' +import { isAgentJournalResolution } from '../shared/agent-session-journal-schemas' +import type { AgentJournalResolution } from '../shared/agent-session-journal-types' +import type { RuntimeStatus } from '../shared/runtime-types' +import { worktreeIdsEqual } from '../shared/worktree/id' + +const AcceptedAnswer = z.object({ + ok: z.literal(true), + replayed: z.boolean(), + fence: z.number().int().positive(), + cursor: z.object({ epoch: z.string().min(1), sequence: z.number().int().nonnegative() }), + value: z.object({ + itemId: z.string().min(1), + revision: z.number().int().positive(), + resolution: z.custom(isAgentJournalResolution) + }) +}) +const RefusedAnswer = z.object({ + ok: z.literal(false), + refusal: z.object({ code: z.string().min(1), details: z.unknown().optional() }) +}) +export async function answerAgentRequest( + client: AgentRequestClient, + scope: AgentRequestScope, + input: AgentRequestAnswerFile, + retryOperationId?: string +): Promise< + RuntimeRpcSuccess<{ + runtimeId: string + workspaceId: string + sessionId: string + clientOperationId: string + outcome: 'accepted' + resumed: 'unverified' + result: Extract, { ok: true }> + }> +> { + if ( + input.sessionId !== scope.sessionId || + (scope.turnItemId !== undefined && input.turnItemId !== scope.turnItemId) || + (retryOperationId !== undefined && retryOperationId !== input.clientOperationId) + ) { + throw new RuntimeClientError( + 'invalid_argument', + 'CLI scope and answer-file identity/retry operation must match exactly.' + ) + } + const constrainedScope = { + ...scope, + ...(input.turnItemId ? { turnItemId: input.turnItemId } : {}) + } + const runtimeId = await readRequestHost(client) + if (runtimeId !== input.expectedRuntimeId) { + throw new RuntimeClientError( + 'agent_request_unverifiable', + 'The execution runtime differs from the inspected request.' + ) + } + const workspaceId = await verifyRequestWorkspace(client, constrainedScope, runtimeId) + if (!worktreeIdsEqual(workspaceId, input.workspaceId)) { + throw new RuntimeClientError( + 'agent_request_unverifiable', + 'The answer file belongs to a different workspace.' + ) + } + const params = nativeAnswerParams(input) + if (input.kind === 'question' && input.answers !== undefined) { + const status = await client.call('status.get') + requireSameRuntime(status, runtimeId) + if (!status.result.capabilities?.includes(AGENT_SESSION_QUESTION_ANSWERS_RUNTIME_CAPABILITY)) { + throw new RuntimeClientError( + 'incompatible_runtime', + 'This host cannot accept structured question answers. Update the execution host.' + ) + } + } + if (retryOperationId === undefined) { + const inventory = await listAgentRequests(client, constrainedScope, runtimeId) + const prompt = inventory.requests.find((request) => request.itemId === input.itemId) + if ( + !worktreeIdsEqual(inventory.workspaceId, input.workspaceId) || + inventory.fence !== input.expectedRuntimeFence || + !sameRequestMarker(inventory.marker, input.expectedRequests) || + !prompt || + prompt.revision !== input.expectedRevision || + prompt.body.kind !== input.kind + ) { + throw new RuntimeClientError( + 'agent_request_unverifiable', + 'The inspected request changed. Read it again before answering.' + ) + } + if (prompt.body.kind === 'approval') { + if (!prompt.body.options.some((option) => option.id === input.optionId)) { + throw new RuntimeClientError( + 'invalid_argument', + 'The selected approval option was not offered.' + ) + } + } else if ( + 'answers' in params && + params.answers !== undefined && + !isValidAgentSessionQuestionAnswers(agentSessionPromptQuestions(prompt.body), params.answers) + ) { + throw new RuntimeClientError( + 'invalid_argument', + 'The answers do not match the exact questions/options.' + ) + } + } + const pinStatus = await client.call('status.get') + requireSameRuntime(pinStatus, runtimeId) + const sourceId = pinStatus.result.hostDescriptor?.installationId + if ( + !sourceId || + !pinStatus.result.capabilities?.includes(RUNTIME_SOURCE_FENCE_RUNTIME_CAPABILITY) + ) { + throw new RuntimeClientError( + 'incompatible_runtime', + 'This host cannot atomically fence native answers to the inspected runtime. Nothing was sent.' + ) + } + const recovery = { + clientOperationId: input.clientOperationId, + expectedRuntimeId: runtimeId, + sessionId: input.sessionId, + workspaceId, + resumed: 'unverified' as const + } + let response: RuntimeRpcSuccess + try { + response = await client.call( + input.kind === 'approval' + ? 'agentSession.respondToApproval' + : 'agentSession.respondToQuestion', + params, + { expectedRuntimeSource: { sourceId, runtimeId } } + ) + requireSameRuntime(response, runtimeId) + } catch (error) { + if ( + (error instanceof RuntimeRpcFailureError && error.code !== 'internal_error') || + (error instanceof RuntimeClientError && + ['runtime_source_mismatch', 'runtime_source_unverifiable', 'incompatible_runtime'].includes( + error.code + )) + ) { + throw new RuntimeClientError(error.code, 'The execution host refused the native answer.', { + ...recovery, + outcome: error.code === 'agent_session_operation_unknown' ? 'unknown' : 'refused' + }) + } + throw new RuntimeClientError( + 'agent_session_operation_unknown', + 'Native answer outcome is unknown. Do not create a new operation or automatically resend it.', + { + ...recovery, + outcome: 'unknown' + } + ) + } + const refused = RefusedAnswer.safeParse(response.result) + if (refused.success) { + throw new RuntimeClientError( + refused.data.refusal.code, + 'The native answer was refused. No provider resumption is confirmed.', + { + ...recovery, + refusal: refused.data.refusal, + outcome: + refused.data.refusal.code === 'agent_session_operation_unknown' ? 'unknown' : 'refused' + } + ) + } + const accepted = AcceptedAnswer.safeParse(response.result) + if (!accepted.success) { + throw new RuntimeClientError( + 'agent_session_operation_unknown', + 'The native answer response is invalid; acceptance is unknown.', + { ...recovery, outcome: 'unknown' } + ) + } + const resolution = accepted.data.value.resolution + const sameChoice = + resolution.state === 'resolved' && + ('answers' in params && params.answers !== undefined + ? structuredAgentSessionPayloadFingerprint({ + method: 'answer-value', + sessionId: input.sessionId, + fields: { answers: params.answers } + }) === + structuredAgentSessionPayloadFingerprint({ + method: 'answer-value', + sessionId: input.sessionId, + fields: { answers: resolution.answers } + }) + : resolution.selectedOptionId === input.optionId) + if ( + accepted.data.value.itemId !== input.itemId || + accepted.data.value.revision < input.expectedRevision || + !sameChoice + ) { + throw new RuntimeClientError( + 'agent_session_operation_unknown', + 'The native answer receipt does not match this exact response.', + { ...recovery, outcome: 'unknown' } + ) + } + return { + ...response, + result: { + runtimeId, + workspaceId, + sessionId: input.sessionId, + clientOperationId: input.clientOperationId, + outcome: 'accepted', + resumed: 'unverified', + result: accepted.data + } + } +} diff --git a/src/cli/agent-request-capabilities.ts b/src/cli/agent-request-capabilities.ts new file mode 100644 index 000000000000..a0afaaa8d7cf --- /dev/null +++ b/src/cli/agent-request-capabilities.ts @@ -0,0 +1,13 @@ +import { + AGENT_SESSION_QUESTION_ANSWERS_RUNTIME_CAPABILITY, + CLAUDE_STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY, + STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY +} from '../shared/protocol-version' +import { AGENT_SESSION_CURRENT_REQUESTS_CLIENT_CAPABILITY } from '../shared/agent-session-current-requests-capability' + +export const AGENT_REQUEST_CLI_CAPABILITIES = [ + STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY, + CLAUDE_STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY, + AGENT_SESSION_CURRENT_REQUESTS_CLIENT_CAPABILITY, + AGENT_SESSION_QUESTION_ANSWERS_RUNTIME_CAPABILITY +] as const diff --git a/src/cli/agent-request-handlers.test.ts b/src/cli/agent-request-handlers.test.ts new file mode 100644 index 000000000000..3c85c6e733ce --- /dev/null +++ b/src/cli/agent-request-handlers.test.ts @@ -0,0 +1,121 @@ +import { describe, expect, it, vi } from 'vitest' +import { parseArgs, specPaths, validateCommandAndFlags } from './args' +import { AGENT_REQUEST_COMMAND_SPECS } from './specs/agent-requests' +import { AGENT_REQUEST_HANDLERS } from './handlers/agent-requests' +import type { HandlerContext } from './dispatch' +import type { RuntimeClient } from './runtime-client' +import { + REQUEST_SESSION, + REQUEST_WORKSPACE, + requestFixtureClient +} from './agent-request-test-fixtures' + +function context(entries: [string, string | boolean][]) { + const { client, call } = requestFixtureClient() + // SAFETY: these handlers consume only call; the test supplies that exact checked fake interface. + const runtimeClient = client as RuntimeClient + const value: HandlerContext = { + flags: new Map(entries), + client: runtimeClient, + cwd: '/unused', + json: true + } + return { value, call } +} + +async function handler(key: string, input: HandlerContext) { + const selected = AGENT_REQUEST_HANDLERS[key] + if (!selected) { + throw new Error('Missing test handler') + } + await selected(input) +} + +describe('public scoped native-request commands', () => { + it('parses the three-level command and a valued same-operation retry', () => { + const argv = [ + 'agent', + 'requests', + 'answer', + '--worktree', + `id:${REQUEST_WORKSPACE}`, + '--session', + REQUEST_SESSION, + '--request-file', + 'answer.json', + '--retry', + '33333333-3333-4333-8333-333333333333', + '--json' + ] + const parsed = parseArgs( + argv, + AGENT_REQUEST_COMMAND_SPECS.flatMap(specPaths), + AGENT_REQUEST_COMMAND_SPECS + ) + validateCommandAndFlags(AGENT_REQUEST_COMMAND_SPECS, parsed) + expect(parsed.commandPath).toEqual(['agent', 'requests', 'answer']) + expect(parsed.flags.get('retry')).toBe('33333333-3333-4333-8333-333333333333') + }) + + it.each(['--yes', '--all', '--force', '--text', '--approve-all'])( + 'does not offer a blanket or inline-body flag: %s', + (flag) => { + const parsed = parseArgs( + ['agent', 'requests', 'answer', flag], + AGENT_REQUEST_COMMAND_SPECS.flatMap(specPaths), + AGENT_REQUEST_COMMAND_SPECS + ) + expect(() => validateCommandAndFlags(AGENT_REQUEST_COMMAND_SPECS, parsed)).toThrow() + } + ) + + it.each(['active', 'current', 'all', '*'])( + 'refuses ambient workspace %s before RPC', + async (worktree) => { + const { value, call } = context([ + ['worktree', worktree], + ['session', REQUEST_SESSION] + ]) + await expect(handler('agent requests list', value)).rejects.toMatchObject({ + code: 'invalid_argument' + }) + expect(call).not.toHaveBeenCalled() + } + ) + + it('requires a session and get item without touching the runtime', async () => { + const missingSession = context([['worktree', `id:${REQUEST_WORKSPACE}`]]) + await expect(handler('agent requests list', missingSession.value)).rejects.toMatchObject({ + code: 'invalid_argument' + }) + expect(missingSession.call).not.toHaveBeenCalled() + const missingItem = context([ + ['worktree', `id:${REQUEST_WORKSPACE}`], + ['session', REQUEST_SESSION] + ]) + await expect(handler('agent requests get', missingItem.value)).rejects.toMatchObject({ + code: 'invalid_argument' + }) + expect(missingItem.call).not.toHaveBeenCalled() + }) + + it('prints the complete scoped result with host identity, rather than an approval command', async () => { + const { value } = context([ + ['worktree', `id:${REQUEST_WORKSPACE}`], + ['session', REQUEST_SESSION] + ]) + const output = vi.spyOn(console, 'log').mockImplementation(() => {}) + try { + await handler('agent requests list', value) + const response = JSON.parse(String(output.mock.calls[0]?.[0])) + expect(response.result).toMatchObject({ + workspaceId: REQUEST_WORKSPACE, + sessionId: REQUEST_SESSION, + resumed: 'unverified' + }) + expect(response.result.requests).toHaveLength(1) + } finally { + output.mockRestore() + } + }) +}) diff --git a/src/cli/agent-request-inventory.test.ts b/src/cli/agent-request-inventory.test.ts new file mode 100644 index 000000000000..9a184c66167c --- /dev/null +++ b/src/cli/agent-request-inventory.test.ts @@ -0,0 +1,179 @@ +import { describe, expect, it } from 'vitest' +import { listAgentRequests } from './agent-request-inventory' +import { + REQUEST_MARKER, + REQUEST_PROMPT, + REQUEST_RUNTIME, + REQUEST_SESSION, + REQUEST_WORKSPACE, + requestFixtureClient +} from './agent-request-test-fixtures' +import { STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY } from '../shared/protocol-version' + +const scope = { worktree: `id:${REQUEST_WORKSPACE}`, sessionId: REQUEST_SESSION } +const response = (result: unknown) => ({ + id: 'test', + ok: true, + _meta: { runtimeId: REQUEST_RUNTIME }, + result +}) + +describe('explicit native request inventory', () => { + it('reads complete authoritative prompts without starting, subscribing or listing all sessions', async () => { + const { client, call } = requestFixtureClient() + const result = await listAgentRequests(client, { ...scope, turnItemId: 'provider:turn-1' }) + expect(result).toMatchObject({ + runtimeId: REQUEST_RUNTIME, + workspaceId: REQUEST_WORKSPACE, + fence: 7, + marker: REQUEST_MARKER, + requests: [REQUEST_PROMPT] + }) + expect( + call.mock.calls.every(([method]) => + [ + 'status.get', + 'session.tabs.list', + 'agentSession.history', + 'agentSession.currentRequests' + ].includes(method) + ) + ).toBe(true) + expect( + call.mock.calls + .filter(([method]) => method === 'session.tabs.list') + .every( + ([, params]) => JSON.stringify(params) === JSON.stringify({ worktree: scope.worktree }) + ) + ).toBe(true) + expect( + (await listAgentRequests(client, { ...scope, turnItemId: 'provider:another-turn' })).requests + ).toEqual([]) + }) + + it('reassembles UTF-16 chunks including exact question text, rather than filtering malformed rows', async () => { + const prompt = { + ...REQUEST_PROMPT, + body: { ...REQUEST_PROMPT.body, title: '한글과 🙂 그대로' } + } + const json = JSON.stringify([prompt]) + const { client } = requestFixtureClient((method, params) => { + if ( + method !== 'agentSession.currentRequests' || + typeof params !== 'object' || + params === null || + !('version' in params) + ) { + return + } + if (params.version !== REQUEST_MARKER.version) { + return response({ marker: REQUEST_MARKER, json: '', nextCursor: 0, restart: true }) + } + const cursor = 'cursor' in params && typeof params.cursor === 'number' ? params.cursor : 0 + const end = Math.min(cursor + 19, json.length) + return response({ + marker: REQUEST_MARKER, + json: json.slice(cursor, end), + nextCursor: end === json.length ? null : end + }) + }) + expect((await listAgentRequests(client, scope)).requests[0]?.body).toEqual(prompt.body) + }) + + it.each(['owner', 'epoch', 'publisher', 'revision', 'version'])( + 'never completes from mixed %s markers', + async (field) => { + const { client } = requestFixtureClient((method, params) => { + if ( + method !== 'agentSession.currentRequests' || + typeof params !== 'object' || + params === null || + !('version' in params) || + params.version !== REQUEST_MARKER.version + ) { + return + } + const changed = { + ...REQUEST_MARKER, + [field]: + field === 'revision' + ? 2 + : field === 'publisher' || field === 'version' + ? '44444444-4444-4444-8444-444444444444' + : 'changed' + } + return response({ + marker: changed, + json: JSON.stringify([REQUEST_PROMPT]), + nextCursor: null + }) + }) + await expect(listAgentRequests(client, scope)).rejects.toMatchObject({ + code: 'agent_request_unverifiable' + }) + } + ) + + it.each(['bad-cursor', 'foreign-row', 'duplicate', 'shortened', 'too-many-pages'])( + 'refuses %s without claiming a partial inventory', + async (mode) => { + const { client } = requestFixtureClient((method, params) => { + if ( + method !== 'agentSession.currentRequests' || + typeof params !== 'object' || + params === null || + !('version' in params) || + params.version !== REQUEST_MARKER.version + ) { + return + } + const cursor = 'cursor' in params && typeof params.cursor === 'number' ? params.cursor : 0 + const values = + mode === 'foreign-row' + ? [{ ...REQUEST_PROMPT, body: { kind: 'message' } }] + : mode === 'duplicate' + ? [REQUEST_PROMPT, REQUEST_PROMPT] + : mode === 'shortened' + ? [{ ...REQUEST_PROMPT, shortened: true }] + : [REQUEST_PROMPT] + return response({ + marker: REQUEST_MARKER, + json: mode === 'too-many-pages' ? '[' : JSON.stringify(values), + nextCursor: mode === 'bad-cursor' ? 1 : mode === 'too-many-pages' ? cursor + 1 : null + }) + }) + await expect(listAgentRequests(client, scope)).rejects.toMatchObject({ + code: 'agent_request_unverifiable' + }) + } + ) + + it('refuses a workspace that cannot prove the named session', async () => { + const { client, call } = requestFixtureClient((method) => + method === 'session.tabs.list' + ? response({ worktree: REQUEST_WORKSPACE, tabs: [] }) + : undefined + ) + await expect(listAgentRequests(client, scope)).rejects.toMatchObject({ + code: 'agent_request_unverifiable' + }) + expect(call.mock.calls.some(([method]) => method === 'agentSession.currentRequests')).toBe( + false + ) + }) + + it('refuses a host without authoritative current-request support before reading transcripts', async () => { + const { client, call } = requestFixtureClient((method) => + method === 'status.get' + ? response({ + runtimeId: REQUEST_RUNTIME, + capabilities: [STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY] + }) + : undefined + ) + await expect(listAgentRequests(client, scope)).rejects.toMatchObject({ + code: 'incompatible_runtime' + }) + expect(call.mock.calls.map(([method]) => method)).toEqual(['status.get']) + }) +}) diff --git a/src/cli/agent-request-inventory.ts b/src/cli/agent-request-inventory.ts new file mode 100644 index 000000000000..2f527439c530 --- /dev/null +++ b/src/cli/agent-request-inventory.ts @@ -0,0 +1,257 @@ +import { randomUUID } from 'node:crypto' +import { z } from 'zod' +import type { RuntimeClient, RuntimeRpcSuccess } from './runtime-client' +import { RuntimeClientError } from './runtime/types' +import type { RuntimeStatus, RuntimeMobileSessionTabsResult } from '../shared/runtime-types' +import type { AgentSessionHistoryResult } from '../shared/agent-session-wire' +import type { AgentSessionCurrentRequest } from '../shared/agent-session-current-requests' +import { isAdmissibleAgentJournalRenderItem } from '../shared/agent-session-journal-schemas' +import { AGENT_SESSION_CURRENT_REQUESTS_CLIENT_CAPABILITY } from '../shared/agent-session-current-requests-capability' +import { STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY } from '../shared/protocol-version' +import { worktreeIdsEqual } from '../shared/worktree/id' + +export type AgentRequestClient = Pick +export type AgentRequestScope = { worktree: string; sessionId: string; turnItemId?: string } + +export const AgentRequestMarkerSchema = z.object({ + contract: z.literal(AGENT_SESSION_CURRENT_REQUESTS_CLIENT_CAPABILITY), + sessionId: z.string().min(1), + epoch: z.string().min(1), + publisher: z.string().uuid(), + revision: z.number().int().positive(), + owner: z.string().min(1), + version: z.string().uuid() +}) +const Piece = z.object({ + marker: AgentRequestMarkerSchema, + json: z.string().max(24 * 1024), + nextCursor: z.number().int().nonnegative().nullable(), + restart: z.literal(true).optional() +}) +type RequestMarker = z.infer +export type AgentRequestInventory = { + runtimeId: string + workspaceId: string + sessionId: string + fence: number + marker: RequestMarker + turnItemId?: string + requests: AgentSessionCurrentRequest[] +} + +export function requestRefusal(message: string): never { + throw new RuntimeClientError('agent_request_unverifiable', message) +} + +export function requireSameRuntime(response: RuntimeRpcSuccess, runtimeId: string): void { + if (response._meta.runtimeId !== runtimeId) { + requestRefusal( + 'The execution runtime changed. Inspect the scoped request again; do not answer it.' + ) + } +} + +export async function readRequestHost(client: AgentRequestClient): Promise { + const response = await client.call('status.get') + const capabilities = response.result.capabilities ?? [] + if ( + response.result.runtimeId !== response._meta.runtimeId || + !capabilities.includes(STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY) || + !capabilities.includes(AGENT_SESSION_CURRENT_REQUESTS_CLIENT_CAPABILITY) + ) { + throw new RuntimeClientError( + 'incompatible_runtime', + 'This host cannot authoritatively list native requests. Update Orca on the execution host.' + ) + } + return response._meta.runtimeId +} + +export async function verifyRequestWorkspace( + client: AgentRequestClient, + scope: AgentRequestScope, + runtimeId: string +): Promise { + const response = await client.call('session.tabs.list', { + worktree: scope.worktree + }) + requireSameRuntime(response, runtimeId) + const snapshot = response.result + if ( + snapshot.agentSessionsUnverifiable || + typeof snapshot.worktree !== 'string' || + !Array.isArray(snapshot.tabs) + ) { + requestRefusal('The host cannot verify this workspace and native session.') + } + const matches = snapshot.tabs.filter( + (tab) => tab.type === 'agent-session' && tab.sessionId === scope.sessionId + ) + if (matches.length !== 1) { + requestRefusal('The named native session is not uniquely present in the explicit workspace.') + } + return snapshot.worktree +} + +async function readFence( + client: AgentRequestClient, + sessionId: string, + runtimeId: string +): Promise<{ fence: number; epoch: string }> { + const response = await client.call('agentSession.history', { + sessionId, + direction: 'tail', + limit: 1 + }) + requireSameRuntime(response, runtimeId) + const page = response.result.page + if ( + !response.result.ok || + page.sessionId !== sessionId || + !Number.isSafeInteger(page.fence) || + page.fence === undefined || + page.fence <= 0 || + typeof page.epoch !== 'string' + ) { + requestRefusal('A current native-session fence and journal epoch could not be established.') + } + return { fence: page.fence, epoch: page.epoch } +} + +export function sameRequestMarker(left: RequestMarker, right: RequestMarker): boolean { + return ( + left.contract === right.contract && + left.sessionId === right.sessionId && + left.epoch === right.epoch && + left.publisher === right.publisher && + left.revision === right.revision && + left.owner === right.owner && + left.version === right.version + ) +} + +async function piece( + client: AgentRequestClient, + sessionId: string, + runtimeId: string, + version: string, + cursor?: number +) { + const response = await client.call('agentSession.currentRequests', { + sessionId, + version, + ...(cursor === undefined ? {} : { cursor }) + }) + requireSameRuntime(response, runtimeId) + const parsed = Piece.safeParse(response.result) + if (!parsed.success || parsed.data.marker.sessionId !== sessionId) { + requestRefusal('The host returned an invalid current-request page.') + } + return parsed.data +} + +function pendingRequests(value: unknown): AgentSessionCurrentRequest[] { + if (!Array.isArray(value)) { + requestRefusal('The current-request snapshot is not a complete array.') + } + const result: AgentSessionCurrentRequest[] = [] + const ids = new Set() + for (const entry of value) { + if ( + !isAdmissibleAgentJournalRenderItem(entry) || + (entry.body.kind !== 'approval' && entry.body.kind !== 'question') || + entry.body.resolution.state !== 'pending' || + entry.revision <= 0 || + entry.shortened || + ids.has(entry.itemId) + ) { + requestRefusal('The current-request snapshot contains an invalid or duplicate prompt.') + } + ids.add(entry.itemId) + result.push({ ...entry, body: entry.body }) + } + return result +} + +export async function listAgentRequests( + client: AgentRequestClient, + scope: AgentRequestScope, + expectedRuntimeId?: string +): Promise { + const runtimeId = await readRequestHost(client) + if (expectedRuntimeId !== undefined && runtimeId !== expectedRuntimeId) { + requestRefusal('The request file names a different execution runtime.') + } + const workspaceId = await verifyRequestWorkspace(client, scope, runtimeId) + for (let attempt = 0; attempt < 3; attempt += 1) { + const before = await readFence(client, scope.sessionId, runtimeId) + // A deliberately stale version obtains the host's current marker without a subscription. + const bootstrap = await piece(client, scope.sessionId, runtimeId, randomUUID()) + const marker = bootstrap.marker + if (marker.epoch !== before.epoch) { + continue + } + let cursor = 0 + let json = '' + let complete = false + for (let page = 0; page < 64; page += 1) { + const next = await piece(client, scope.sessionId, runtimeId, marker.version, cursor) + if (next.restart || !sameRequestMarker(marker, next.marker)) { + break + } + json += next.json + if (json.length > 1024 * 1024) { + requestRefusal('The current-request snapshot exceeds the CLI limit.') + } + if (next.nextCursor === null) { + complete = true + break + } + if (next.json.length === 0 || next.nextCursor !== cursor + next.json.length) { + requestRefusal('The current-request cursor did not advance exactly.') + } + cursor = next.nextCursor + } + if (!complete) { + continue + } + let decoded: unknown + try { + decoded = JSON.parse(json) + } catch { + requestRefusal('The current-request snapshot is incomplete JSON.') + } + const requests = pendingRequests(decoded) + const after = await readFence(client, scope.sessionId, runtimeId) + const confirmed = await piece(client, scope.sessionId, runtimeId, marker.version, 0) + const workspaceAfter = await verifyRequestWorkspace(client, scope, runtimeId) + if (!worktreeIdsEqual(workspaceAfter, workspaceId)) { + requestRefusal('The native session changed workspace while its requests were read.') + } + if ( + before.fence !== after.fence || + before.epoch !== after.epoch || + confirmed.restart || + !sameRequestMarker(marker, confirmed.marker) + ) { + continue + } + return { + runtimeId, + workspaceId, + sessionId: scope.sessionId, + fence: after.fence, + marker, + ...(scope.turnItemId === undefined ? {} : { turnItemId: scope.turnItemId }), + requests: + scope.turnItemId === undefined + ? requests + : requests.filter( + (request) => + request.turnScope?.kind === 'turn' && + request.turnScope.turnItemId === scope.turnItemId + ) + } + } + requestRefusal('The request owner, revision or journal changed during collection. Read it again.') +} diff --git a/src/cli/agent-request-test-fixtures.ts b/src/cli/agent-request-test-fixtures.ts new file mode 100644 index 000000000000..cd762e2f6213 --- /dev/null +++ b/src/cli/agent-request-test-fixtures.ts @@ -0,0 +1,126 @@ +import { vi } from 'vitest' +import type { RuntimeRpcSuccess } from './runtime-client' +import type { AgentRequestClient } from './agent-request-inventory' +import { AGENT_REQUEST_CLI_CAPABILITIES } from './agent-request-capabilities' +import { RUNTIME_SOURCE_FENCE_RUNTIME_CAPABILITY } from '../shared/host-runtime-capabilities' + +export const REQUEST_SESSION = 'chat_session_01' +export const REQUEST_WORKSPACE = 'repo-id::C:/projects/example' +export const REQUEST_RUNTIME = 'runtime-test' +export const REQUEST_SOURCE = 'installation-test' +export const REQUEST_MARKER = { + contract: 'agent-session.current-requests.v1' as const, + sessionId: REQUEST_SESSION, + epoch: 'epoch-test', + publisher: '11111111-1111-4111-8111-111111111111', + revision: 1, + owner: 'publisher:current-owner', + version: '22222222-2222-4222-8222-222222222222' +} +export const REQUEST_PROMPT = { + itemId: 'provider:prompt-1', + revision: 1, + sequence: 1, + observedAt: 100, + turnScope: { kind: 'turn' as const, turnItemId: 'provider:turn-1' }, + body: { + kind: 'approval' as const, + title: 'Inspect one command', + detail: 'Literal prompt data', + options: [ + { id: 'approve', label: 'Approve' }, + { id: 'deny', label: 'Deny' } + ], + resolution: { + state: 'pending' as const, + selectedOptionId: null, + resolvedBy: null, + resolvedAt: null + } + } +} +export function answerFile() { + return { + workspaceId: REQUEST_WORKSPACE, + sessionId: REQUEST_SESSION, + expectedRuntimeId: REQUEST_RUNTIME, + expectedRequests: REQUEST_MARKER, + itemId: REQUEST_PROMPT.itemId, + kind: 'approval' as const, + expectedRuntimeFence: 7, + expectedRevision: 1, + clientOperationId: '33333333-3333-4333-8333-333333333333', + optionId: 'approve' + } +} + +export function requestFixtureClient( + override?: (method: string, params: unknown, options: unknown) => unknown +) { + const call = vi.fn(async (method: string, params: unknown, options: unknown) => { + const supplied = override?.(method, params, options) + if (supplied !== undefined) { + return supplied + } + let result: unknown + if (method === 'status.get') { + result = { + runtimeId: REQUEST_RUNTIME, + capabilities: [...AGENT_REQUEST_CLI_CAPABILITIES, RUNTIME_SOURCE_FENCE_RUNTIME_CAPABILITY], + hostDescriptor: { installationId: REQUEST_SOURCE } + } + } else if (method === 'session.tabs.list') { + result = { + worktree: REQUEST_WORKSPACE, + tabs: [{ type: 'agent-session', id: 'tab-1', sessionId: REQUEST_SESSION, agent: 'codex' }] + } + } else if (method === 'agentSession.history') { + result = { + ok: true, + page: { sessionId: REQUEST_SESSION, epoch: REQUEST_MARKER.epoch, fence: 7 } + } + } else if (method === 'agentSession.currentRequests') { + const json = JSON.stringify([REQUEST_PROMPT]) + const version = + typeof params === 'object' && params !== null && 'version' in params ? params.version : null + result = + version === REQUEST_MARKER.version + ? { marker: REQUEST_MARKER, json, nextCursor: null } + : { marker: REQUEST_MARKER, json: '', nextCursor: 0, restart: true } + } else if ( + method === 'agentSession.respondToApproval' || + method === 'agentSession.respondToQuestion' + ) { + result = { + ok: true, + replayed: false, + fence: 7, + cursor: { epoch: REQUEST_MARKER.epoch, sequence: 2 }, + value: { + itemId: REQUEST_PROMPT.itemId, + revision: 2, + resolution: { + state: 'resolved', + selectedOptionId: 'approve', + resolvedBy: 'caller', + resolvedAt: 100 + } + } + } + } else { + throw new Error(`Unexpected fake RPC: ${method}`) + } + return { id: 'test-request', ok: true, _meta: { runtimeId: REQUEST_RUNTIME }, result } + }) + const client: AgentRequestClient = { + async call( + method: string, + params?: unknown, + options?: Parameters[2] + ) { + // SAFETY: this test-only adapter stamps the fixture value for the generic RPC interface under test. + return (await call(method, params, options)) as RuntimeRpcSuccess + } + } + return { client, call } +} diff --git a/src/cli/agent-request-transport.test.ts b/src/cli/agent-request-transport.test.ts new file mode 100644 index 000000000000..f470af658121 --- /dev/null +++ b/src/cli/agent-request-transport.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from 'vitest' +import { serializeRemoteRuntimeRpcRequest } from '../shared/remote-runtime-memory-limits' + +describe('native answer pin is a transport-local field', () => { + it('carries a supplied host pin without adding it to the orchestration forwarding envelope', () => { + const envelope = { orchestrationRequestId: 'existing-operation' } + const expectedRuntimeSource = { sourceId: 'profile', runtimeId: 'runtime-inspected' } + const request = JSON.parse( + serializeRemoteRuntimeRpcRequest({ + requestId: 'request', + deviceToken: 'test-token', + method: 'agentSession.respondToApproval', + params: { exact: true }, + envelope, + expectedRuntimeSource + }) + ) + expect(request.expectedRuntimeSource).toEqual(expectedRuntimeSource) + expect(request.orchestrationRequestId).toBe('existing-operation') + expect(envelope).not.toHaveProperty('expectedRuntimeSource') + const ordinary = JSON.parse( + serializeRemoteRuntimeRpcRequest({ + requestId: 'ordinary', + deviceToken: 'test-token', + method: 'orchestration.reply', + params: { exact: true }, + envelope + }) + ) + expect(ordinary).not.toHaveProperty('expectedRuntimeSource') + expect(ordinary.orchestrationRequestId).toBe('existing-operation') + }) +}) diff --git a/src/cli/handler-group-manifest.ts b/src/cli/handler-group-manifest.ts index 655d111eb42a..859dd8981b37 100644 --- a/src/cli/handler-group-manifest.ts +++ b/src/cli/handler-group-manifest.ts @@ -210,6 +210,11 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ keys: ['agent launch'], load: async () => (await import('./handlers/agent-launch.js')).AGENT_LAUNCH_HANDLERS }, + { + name: 'agent-requests', + keys: ['agent requests list', 'agent requests get', 'agent requests answer'], + load: async () => (await import('./handlers/agent-requests.js')).AGENT_REQUEST_HANDLERS + }, { name: 'connector', keys: [ diff --git a/src/cli/handlers/agent-requests.ts b/src/cli/handlers/agent-requests.ts new file mode 100644 index 000000000000..f3544aa3328e --- /dev/null +++ b/src/cli/handlers/agent-requests.ts @@ -0,0 +1,69 @@ +import type { CommandHandler, HandlerContext } from '../dispatch' +import { getOptionalStringFlag, getRequiredStringFlag } from '../flags' +import { printResult } from '../format' +import { RuntimeClientError } from '../runtime/types' +import { listAgentRequests, type AgentRequestScope } from '../agent-request-inventory' +import { answerAgentRequest } from '../agent-request-answer' +import { readAgentRequestAnswerFile } from '../agent-request-answer-file' + +function scope({ flags }: HandlerContext): AgentRequestScope { + const worktree = getRequiredStringFlag(flags, 'worktree') + if (['active', 'current', 'all', '*'].includes(worktree)) { + throw new RuntimeClientError( + 'invalid_argument', + 'Native requests require an explicit workspace; focus and all-workspace selectors are refused.' + ) + } + return { + worktree, + sessionId: getRequiredStringFlag(flags, 'session'), + ...(flags.has('turn') ? { turnItemId: getRequiredStringFlag(flags, 'turn') } : {}) + } +} + +const read: CommandHandler = async (context) => { + const target = scope(context) + const inventory = await listAgentRequests(context.client, target) + const itemId = getOptionalStringFlag(context.flags, 'item') + const requests = + itemId === undefined + ? inventory.requests + : inventory.requests.filter((request) => request.itemId === itemId) + if (itemId !== undefined && requests.length !== 1) { + throw new RuntimeClientError( + 'agent_request_not_current', + 'This item is not a current request in the explicit session/workspace/turn.' + ) + } + printResult( + { + id: 'agent-requests', + ok: true, + _meta: { runtimeId: inventory.runtimeId }, + result: { ...inventory, requests, resumed: 'unverified' } + }, + context.json, + (value) => JSON.stringify(value, null, 2) + ) +} + +export const AGENT_REQUEST_HANDLERS: Record = { + 'agent requests list': read, + 'agent requests get': async (context) => { + getRequiredStringFlag(context.flags, 'item') + await read(context) + }, + 'agent requests answer': async (context) => { + const target = scope(context) + const input = await readAgentRequestAnswerFile( + getRequiredStringFlag(context.flags, 'request-file') + ) + const response = await answerAgentRequest( + context.client, + target, + input, + getOptionalStringFlag(context.flags, 'retry') + ) + printResult(response, context.json, (value) => JSON.stringify(value, null, 2)) + } +} diff --git a/src/cli/root-help-text-primary.ts b/src/cli/root-help-text-primary.ts index 8a15f9491e0b..c03449e64204 100644 --- a/src/cli/root-help-text-primary.ts +++ b/src/cli/root-help-text-primary.ts @@ -87,6 +87,7 @@ export const ROOT_HELP_TEXT_PRIMARY = [ '', 'Agents:', ' agent launch Start an agent in a worktree, as a chat or terminal per your settings', + ' agent requests list|get|answer Inspect or answer one explicitly scoped native session', '', 'Files:', ' file open Open a file as a tab, view stays put (--focus brings you to it)', diff --git a/src/cli/runtime/client.ts b/src/cli/runtime/client.ts index cddf11bb2150..02ed77ef6bb7 100644 --- a/src/cli/runtime/client.ts +++ b/src/cli/runtime/client.ts @@ -1,7 +1,9 @@ import { randomUUID } from 'node:crypto' import type { CliStatusResult, RuntimeStatus } from '../../shared/runtime-types' -import { runtimeHostConnectionState } from '../../shared/runtime-host-connection-state' -import type { RuntimeOrchestrationEnvelope } from '../../shared/runtime-rpc-envelope' +import type { + ExpectedRuntimeSource, + RuntimeOrchestrationEnvelope +} from '../../shared/runtime-rpc-envelope' import { isDurableMutation, isOrchestrationMutation, @@ -11,7 +13,7 @@ import { import type { PairedRuntimeConnection } from '../../shared/paired-runtime-connection' import { launchOrcaApp } from './launch' import { getDefaultUserDataPath, readMetadata } from './metadata' -import { getCliStatus, projectRemoteAppStatus } from './status' +import { getCliStatus, projectRemoteCliStatus } from './status' import { sendRequest } from './transport' import { RuntimeClientError, RuntimeRpcFailureError, type RuntimeRpcSuccess } from './types' import { @@ -89,6 +91,7 @@ export class RuntimeClient { timeoutMs?: number legacyTerminalPrompt?: true terminalPromptPreflight?: { runtimeId: string | null } + expectedRuntimeSource?: ExpectedRuntimeSource } & RuntimeOrchestrationEnvelope ): Promise> { const effectiveTimeoutMs = options?.timeoutMs ?? this.resolveMethodTimeoutMs(method, params) @@ -147,7 +150,8 @@ export class RuntimeClient { method, params, timeoutMs: effectiveTimeoutMs, - envelope + envelope, + expectedRuntimeSource: options?.expectedRuntimeSource }) } catch (error) { throw recover(error, null) @@ -164,7 +168,11 @@ export class RuntimeClient { } const metadata = readMetadata(this.userDataPath) // Refusal precedes sending, so there is no request to recover. - const expectedRuntimeSource = await this.runtimeSourceFence.check(metadata, method) + const expectedRuntimeSource = await this.runtimeSourceFence.check( + metadata, + method, + options?.expectedRuntimeSource + ) let response try { response = await sendRequest( @@ -214,37 +222,7 @@ export class RuntimeClient { if (this.remote) { const response = await this.call('status.get') this.remoteCompat.noteVerifiedStatus(response.result) - const graphState = response.result.graphStatus - return { - id: response.id, - ok: true, - result: { - target: { - kind: 'environment', - environment: this.environmentSelector ?? 'pairing-code' - }, - app: projectRemoteAppStatus(response.result), - runtime: { - state: graphState === 'ready' ? 'ready' : 'graph_not_ready', - reachable: true, - connectionState: runtimeHostConnectionState({ - hasStatusEntry: true, - status: response.result - }), - runtimeId: response.result.runtimeId, - ...(response.result.appVersion ? { appVersion: response.result.appVersion } : {}), - ...(response.result.remoteUpdateSupport - ? { remoteUpdateSupport: response.result.remoteUpdateSupport } - : {}), - ...(response.result.capabilities ? { capabilities: response.result.capabilities } : {}), - ...(response.result.degradations ? { degradations: response.result.degradations } : {}) - }, - graph: { - state: graphState - } - }, - _meta: response._meta - } + return projectRemoteCliStatus(response, this.environmentSelector) } return getCliStatus(this.userDataPath) } diff --git a/src/cli/runtime/remote-runtime-compat-gate.ts b/src/cli/runtime/remote-runtime-compat-gate.ts index 0efe1d825b42..ec86873c2ebd 100644 --- a/src/cli/runtime/remote-runtime-compat-gate.ts +++ b/src/cli/runtime/remote-runtime-compat-gate.ts @@ -4,7 +4,10 @@ import { MIN_COMPATIBLE_RUNTIME_SERVER_VERSION, RUNTIME_PROTOCOL_VERSION } from '../../shared/protocol-version' -import type { RuntimeOrchestrationEnvelope } from '../../shared/runtime-rpc-envelope' +import type { + ExpectedRuntimeSource, + RuntimeOrchestrationEnvelope +} from '../../shared/runtime-rpc-envelope' import type { RuntimeStatus } from '../../shared/runtime-types' import { markEnvironmentUsed } from './environments' import { RuntimeClientError, RuntimeRpcFailureError, type RuntimeRpcResponse } from './types' @@ -33,6 +36,7 @@ export class RemoteRuntimeCompatGate { params: unknown timeoutMs: number envelope?: RuntimeOrchestrationEnvelope + expectedRuntimeSource?: ExpectedRuntimeSource }): Promise> { if (this.checked || args.method === 'status.get') { return args.transport.sendWebSocketRequest( @@ -40,7 +44,8 @@ export class RemoteRuntimeCompatGate { args.method, args.params, args.timeoutMs, - args.envelope + args.envelope, + args.expectedRuntimeSource ) } return args.transport.sendWebSocketRequestWithStatusPreflight( @@ -59,7 +64,8 @@ export class RemoteRuntimeCompatGate { }) } }, - args.envelope + args.envelope, + args.expectedRuntimeSource ) } diff --git a/src/cli/runtime/runtime-source-fence.test.ts b/src/cli/runtime/runtime-source-fence.test.ts index a3841e632909..5a49a533d5ff 100644 --- a/src/cli/runtime/runtime-source-fence.test.ts +++ b/src/cli/runtime/runtime-source-fence.test.ts @@ -1,6 +1,6 @@ import { createServer, type Server } from 'node:net' import { randomUUID } from 'node:crypto' -import { mkdtempSync, writeFileSync } from 'node:fs' +import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' @@ -112,6 +112,48 @@ async function expectRefusal(promise: Promise, code: string): Promise { + it('refuses an explicit request pin after metadata is replaced before send', async () => { + const original = await startRuntime({ runtimeId: 'runtime-original', installationId: SOURCE_A }) + const replacement = await startRuntime({ + runtimeId: 'runtime-replacement', + installationId: SOURCE_A + }) + launchedBy(SOURCE_A, 'runtime-original') + const client = new RuntimeClient(original.userDataPath, 2_000, null, null, 'orca') + await client.call('status.get') + writeFileSync( + join(original.userDataPath, 'orca-runtime.json'), + readFileSync(join(replacement.userDataPath, 'orca-runtime.json')) + ) + await expectRefusal( + client.call( + 'agentSession.respondToApproval', + { sessionId: 'session', itemId: 'approval' }, + { + expectedRuntimeSource: { sourceId: SOURCE_A, runtimeId: 'runtime-original' } + } + ), + 'runtime_source_mismatch' + ) + expect(original.methods).toEqual(['status.get']) + expect(replacement.methods).toEqual([]) + }) + + it('puts an explicit request pin on the actual local answer wire', async () => { + const runtime = await startRuntime({ runtimeId: 'runtime-answer', installationId: SOURCE_A }) + delete process.env[RUNTIME_SOURCE_ID_ENV] + delete process.env[RUNTIME_SOURCE_INCARNATION_ENV] + const client = new RuntimeClient(runtime.userDataPath, 2_000, null, null, 'orca') + const pin = { sourceId: SOURCE_A, runtimeId: 'runtime-answer' } + await client.call( + 'agentSession.respondToQuestion', + { sessionId: 'session', itemId: 'question' }, + { expectedRuntimeSource: pin } + ) + expect(runtime.methods).toEqual(['agentSession.respondToQuestion']) + expect(runtime.expectations).toEqual([pin]) + }) + it('refuses another live runtime before the request reaches it', async () => { const runtime = await startRuntime({ runtimeId: 'runtime-b', installationId: SOURCE_B }) launchedBy(SOURCE_A, 'runtime-a') diff --git a/src/cli/runtime/runtime-source-fence.ts b/src/cli/runtime/runtime-source-fence.ts index 5b173611448d..e86f14e87da5 100644 --- a/src/cli/runtime/runtime-source-fence.ts +++ b/src/cli/runtime/runtime-source-fence.ts @@ -38,6 +38,27 @@ export class RuntimeSourceFence { } async check( + metadata: RuntimeMetadata, + method: string, + pinnedSource?: ExpectedRuntimeSource + ): Promise { + if (pinnedSource && metadata.runtimeId !== pinnedSource.runtimeId) { + throw new RuntimeClientError( + 'runtime_source_mismatch', + 'The pinned runtime changed. Nothing was sent.' + ) + } + const inheritedSource = await this.checkLaunchingSource(metadata, method) + if (pinnedSource && inheritedSource && pinnedSource.sourceId !== inheritedSource.sourceId) { + throw new RuntimeClientError( + 'runtime_source_mismatch', + 'The pinned profile differs from the launching profile. Nothing was sent.' + ) + } + return pinnedSource ?? inheritedSource + } + + private async checkLaunchingSource( metadata: RuntimeMetadata, method: string ): Promise { diff --git a/src/cli/runtime/status.ts b/src/cli/runtime/status.ts index b49cb7abc598..1011d5f02ce1 100644 --- a/src/cli/runtime/status.ts +++ b/src/cli/runtime/status.ts @@ -101,3 +101,40 @@ function buildCliStatusResponse(result: CliStatusResult): RuntimeRpcSuccess, + environmentSelector: string | null +): RuntimeRpcSuccess { + const graphState = response.result.graphStatus + return { + id: response.id, + ok: true, + result: { + target: { + kind: 'environment', + environment: environmentSelector ?? 'pairing-code' + }, + app: projectRemoteAppStatus(response.result), + runtime: { + state: graphState === 'ready' ? 'ready' : 'graph_not_ready', + reachable: true, + connectionState: runtimeHostConnectionState({ + hasStatusEntry: true, + status: response.result + }), + runtimeId: response.result.runtimeId, + ...(response.result.appVersion ? { appVersion: response.result.appVersion } : {}), + ...(response.result.remoteUpdateSupport + ? { remoteUpdateSupport: response.result.remoteUpdateSupport } + : {}), + ...(response.result.capabilities ? { capabilities: response.result.capabilities } : {}), + ...(response.result.degradations ? { degradations: response.result.degradations } : {}) + }, + graph: { + state: graphState + } + }, + _meta: response._meta + } +} diff --git a/src/cli/runtime/websocket-transport.test.ts b/src/cli/runtime/websocket-transport.test.ts index aa027240a8bf..ca90b0f69f4d 100644 --- a/src/cli/runtime/websocket-transport.test.ts +++ b/src/cli/runtime/websocket-transport.test.ts @@ -19,6 +19,7 @@ import { RuntimeClient } from './client' import { launchOrcaApp } from './launch' import { addEnvironmentFromPairingCode } from './environments' import { RuntimeClientError } from './types' +import { AGENT_REQUEST_CLI_CAPABILITIES } from '../agent-request-capabilities' import { AGENT_SESSION_BACKGROUND_TASK_ROW_STOP_CAPABILITY, AGENT_SESSION_TURN_ITEM_CAPABILITY, @@ -50,6 +51,7 @@ type TestRuntime = { deviceToken: string authFrames: Record[] requestMethods: string[] + requests: Record[] connectionCount: () => number close: () => Promise } @@ -79,7 +81,7 @@ describe('CLI remote WebSocket transport', () => { expect(response.result.runtimeId).toBe('runtime-ws-1') expect(runtime.authFrames).toContainEqual( expect.objectContaining({ - clientCapabilities: [ + clientCapabilities: expect.arrayContaining([ AGENT_SESSION_BACKGROUND_TASK_STOP_CAPABILITY, AGENT_SESSION_BACKGROUND_TASK_ROW_STOP_CAPABILITY, AGENT_SESSION_BACKGROUND_TASK_CHILD_VIEWS_CAPABILITY, @@ -95,8 +97,9 @@ describe('CLI remote WebSocket transport', () => { REPO_SEARCH_QUALIFIED_REFS_RUNTIME_CAPABILITY, TERMINAL_QUICK_COMMAND_LONG_PROMPTS_RUNTIME_CAPABILITY, TERMINAL_QUICK_COMMAND_LARGE_LISTS_RUNTIME_CAPABILITY, - AGENT_LAUNCH_RUNTIME_CAPABILITY - ] + AGENT_LAUNCH_RUNTIME_CAPABILITY, + ...AGENT_REQUEST_CLI_CAPABILITIES + ]) }) ) }) @@ -107,6 +110,37 @@ describe('CLI remote WebSocket transport', () => { ) }) + it('carries the caller request pin through RuntimeClient to the encrypted remote wire', async () => { + const runtime = await startTestRuntime('runtime-pinned') + servers.push(runtime) + const client = new RuntimeClient( + '/tmp/unused', + 5_000, + encodePairingOffer({ + v: 2, + endpoint: runtime.endpoint, + deviceToken: runtime.deviceToken, + publicKeyB64: runtime.publicKeyB64 + }) + ) + const expectedRuntimeSource = { + sourceId: '11111111-1111-4111-8111-111111111111', + runtimeId: 'runtime-pinned' + } + await expect( + client.call( + 'agentSession.respondToQuestion', + { sessionId: 'session' }, + { expectedRuntimeSource } + ) + ).rejects.toMatchObject({ code: 'method_not_found' }) + expect( + runtime.requests.filter((row) => row.method === 'agentSession.respondToQuestion') + ).toEqual([ + expect.objectContaining({ expectedRuntimeSource, params: { sessionId: 'session' } }) + ]) + }) + it('accepts a bare pairing payload as well as the orca URL wrapper', async () => { const runtime = await startTestRuntime('runtime-ws-2', { appVersion: '1.5.0', @@ -285,6 +319,7 @@ async function startTestRuntime( const wss = new WebSocketServer({ server: httpServer }) const authFrames: Record[] = [] const requestMethods: string[] = [] + const requests: Record[] = [] let connectionCount = 0 wss.on('connection', (ws) => { @@ -326,8 +361,10 @@ async function startTestRuntime( return } - const request = JSON.parse(plaintext) as { id: string; method: string } + const request: { id: string; method: string } & Record = + JSON.parse(plaintext) requestMethods.push(request.method) + requests.push(request) const response = request.method === 'status.get' ? { @@ -375,6 +412,7 @@ async function startTestRuntime( deviceToken, authFrames, requestMethods, + requests, connectionCount: () => connectionCount, close: async () => { await new Promise((resolve) => { diff --git a/src/cli/runtime/websocket-transport.ts b/src/cli/runtime/websocket-transport.ts index a0b26c230a51..54fd450350e9 100644 --- a/src/cli/runtime/websocket-transport.ts +++ b/src/cli/runtime/websocket-transport.ts @@ -1,5 +1,8 @@ import type { PairedRuntimeConnection } from '../../shared/paired-runtime-connection' -import type { RuntimeOrchestrationEnvelope } from '../../shared/runtime-rpc-envelope' +import type { + ExpectedRuntimeSource, + RuntimeOrchestrationEnvelope +} from '../../shared/runtime-rpc-envelope' import { RemoteRuntimeClientError } from '../../shared/remote-runtime-client-error' import { AGENT_LAUNCH_RUNTIME_CAPABILITY } from '../../shared/agent-launch-runtime-capability' import { @@ -8,16 +11,21 @@ import { } from '../../shared/remote-runtime-client' import type { RuntimeStatus } from '../../shared/runtime-types' import { RuntimeClientError, type RuntimeRpcResponse } from './types' +import { AGENT_REQUEST_CLI_CAPABILITIES } from '../agent-request-capabilities' // Paired CLI callers are not exempt from the host's agent.launch gate like the local socket is. -const CLI_CLIENT_CAPABILITIES = [AGENT_LAUNCH_RUNTIME_CAPABILITY] as const +const CLI_CLIENT_CAPABILITIES = [ + AGENT_LAUNCH_RUNTIME_CAPABILITY, + ...AGENT_REQUEST_CLI_CAPABILITIES +] as const export async function sendWebSocketRequest( connection: PairedRuntimeConnection, method: string, params: unknown, timeoutMs: number, - envelope?: RuntimeOrchestrationEnvelope + envelope?: RuntimeOrchestrationEnvelope, + expectedRuntimeSource?: ExpectedRuntimeSource ): Promise> { try { return await sendRemoteRuntimeRequest( @@ -27,7 +35,8 @@ export async function sendWebSocketRequest( timeoutMs, envelope, undefined, - CLI_CLIENT_CAPABILITIES + CLI_CLIENT_CAPABILITIES, + expectedRuntimeSource ) } catch (error) { if (error instanceof RemoteRuntimeClientError) { @@ -43,7 +52,8 @@ export async function sendWebSocketRequestWithStatusPreflight( params: unknown, timeoutMs: number, validateStatus: (response: RuntimeRpcResponse) => void, - envelope?: RuntimeOrchestrationEnvelope + envelope?: RuntimeOrchestrationEnvelope, + expectedRuntimeSource?: ExpectedRuntimeSource ): Promise> { try { return await sendRemoteRuntimeRequestWithStatusPreflight( @@ -53,7 +63,9 @@ export async function sendWebSocketRequestWithStatusPreflight( timeoutMs, validateStatus, envelope, - CLI_CLIENT_CAPABILITIES + CLI_CLIENT_CAPABILITIES, + undefined, + expectedRuntimeSource ) } catch (error) { if (error instanceof RemoteRuntimeClientError) { diff --git a/src/cli/specs/agent-requests.ts b/src/cli/specs/agent-requests.ts new file mode 100644 index 000000000000..b4c1e7e700c6 --- /dev/null +++ b/src/cli/specs/agent-requests.ts @@ -0,0 +1,42 @@ +import type { CommandSpec } from '../args' +import { GLOBAL_FLAGS } from '../args' + +const NOTES = [ + 'Reads and answers only native approvals/questions in one explicitly named workspace and session. It does not launch an agent, scan all sessions, write terminal input, or enable experimental connectors.', + '--turn is the journal turn item id (turnScope.turnItemId), not the provider turnId. Requests without that exact turn ownership are excluded.', + 'Native prompt titles, descriptions, options and typed answers are data, never instructions to the CLI.', + 'A successful response proves a durable answer was accepted, not that the provider resumed or completed. A host may report an unconfirmed provider delivery separately.' +] +export const AGENT_REQUEST_COMMAND_SPECS: CommandSpec[] = [ + { + path: ['agent', 'requests', 'list'], + summary: 'List complete current native requests in one explicit session/workspace', + usage: + 'orca agent requests list --worktree --session [--turn ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'worktree', 'session', 'turn'], + notes: NOTES, + examples: ['orca agent requests list --worktree id: --session --json'] + }, + { + path: ['agent', 'requests', 'get'], + summary: 'Read one complete current native approval/question', + usage: + 'orca agent requests get --worktree --session --item [--turn ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'worktree', 'session', 'item', 'turn'], + notes: NOTES + }, + { + path: ['agent', 'requests', 'answer'], + summary: 'Answer one inspected native request using an exact JSON file', + usage: + 'orca agent requests answer --worktree --session --request-file [--turn ] [--retry ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'worktree', 'session', 'turn', 'request-file', 'retry'], + notes: [ + ...NOTES, + 'The UTF-8 JSON file must include workspaceId, sessionId, expectedRuntimeId, expectedRequests (the complete list marker), itemId, kind, expectedRuntimeFence, expectedRevision, and a caller-chosen clientOperationId UUID. It selects one optionId or the exact structured question answers. Optional turnItemId restricts ownership.', + 'An initial answer requires the inspected runtime, workspace, session, fence, marker and item revision to remain current. The host finally enforces its existing lease, item revision and current provider ownership rules; newer hosts do not enforce the envelope fence themselves.', + '--retry must equal the file UUID and resends only that same operation and payload once, allowing the host to replay its receipt even when the prompt is no longer pending. Never replace an unknown operation with a fresh UUID or retry automatically.', + 'A session no longer identifiable in this explicit workspace is refused even for replay. Older hosts lacking the native current-request contract are refused without mutation.' + ] + } +] diff --git a/src/cli/specs/index.ts b/src/cli/specs/index.ts index c17bf1bac62c..91b73548c4a2 100644 --- a/src/cli/specs/index.ts +++ b/src/cli/specs/index.ts @@ -12,6 +12,7 @@ import { ENVIRONMENT_COMMAND_SPECS } from './environment' import { MANAGED_SERVER_COMMAND_SPECS } from './managed-server' import { AGENT_HOOK_COMMAND_SPECS } from './agent-hooks' import { AGENT_LAUNCH_COMMAND_SPECS } from './agent-launch' +import { AGENT_REQUEST_COMMAND_SPECS } from './agent-requests' import { CONNECTOR_COMMAND_SPECS } from './connector' import { DIAGNOSTICS_COMMAND_SPECS } from './diagnostics' import { SPEECH_COMMAND_SPECS } from './speech' @@ -42,6 +43,7 @@ export const COMMAND_SPECS: CommandSpec[] = [ ...COMPUTER_COMMAND_SPECS, ...AGENT_HOOK_COMMAND_SPECS, ...AGENT_LAUNCH_COMMAND_SPECS, + ...AGENT_REQUEST_COMMAND_SPECS, ...CONNECTOR_COMMAND_SPECS, ...DIAGNOSTICS_COMMAND_SPECS, ...SPEECH_COMMAND_SPECS, diff --git a/src/shared/remote-runtime-client.test.ts b/src/shared/remote-runtime-client.test.ts index 6376928c43f6..2241e3c8115d 100644 --- a/src/shared/remote-runtime-client.test.ts +++ b/src/shared/remote-runtime-client.test.ts @@ -458,6 +458,41 @@ describe('sendRemoteRuntimeRequest', () => { }) }) + it('sends the request runtime pin without changing orchestration fields over encryption', async () => { + const observed = vi.fn() + const server = await createOneShotServer({ onRequest: observed }) + const envelope = { + orchestrationCapability: 'capability', + orchestrationContractVersion: 1, + orchestrationRequestId: 'mutation_1' + } + const pin = { sourceId: '11111111-1111-4111-8111-111111111111', runtimeId: 'runtime-test' } + await sendRemoteRuntimeRequest( + server.pairing, + 'agentSession.respondToQuestion', + { sessionId: 'session' }, + 1000, + envelope, + undefined, + [], + pin + ) + expect(observed).toHaveBeenCalledOnce() + expect(observed).toHaveBeenCalledWith( + expect.objectContaining({ + method: 'agentSession.respondToQuestion', + params: { sessionId: 'session' }, + expectedRuntimeSource: pin, + ...envelope + }) + ) + expect(envelope).toEqual({ + orchestrationCapability: 'capability', + orchestrationContractVersion: 1, + orchestrationRequestId: 'mutation_1' + }) + }) + it('sends orchestration authentication fields in the admitted encrypted request', async () => { let receivedRequest: Record | null = null const server = await createOneShotServer({ @@ -505,6 +540,7 @@ describe('sendRemoteRuntimeRequest', () => { expect(receivedRequest).not.toHaveProperty('orchestrationCapability') expect(receivedRequest).not.toHaveProperty('orchestrationContractVersion') expect(receivedRequest).not.toHaveProperty('orchestrationRequestId') + expect(receivedRequest).not.toHaveProperty('expectedRuntimeSource') }) it('detaches one-shot socket listeners after a successful response', async () => { diff --git a/src/shared/remote-runtime-client.ts b/src/shared/remote-runtime-client.ts index 459ee6a9b53a..33d4f4a2b82f 100644 --- a/src/shared/remote-runtime-client.ts +++ b/src/shared/remote-runtime-client.ts @@ -7,7 +7,11 @@ import type { RemoteRuntimeSubscriptionOptions, RemoteRuntimeTransportSubscriptionCallbacks } from './remote-runtime/requests/remote-runtime-subscription-contract' -import type { RuntimeOrchestrationEnvelope, RuntimeRpcResponse } from './runtime-rpc-envelope' +import type { + ExpectedRuntimeSource, + RuntimeOrchestrationEnvelope, + RuntimeRpcResponse +} from './runtime-rpc-envelope' import type { RuntimeStatus } from './runtime-types' export type RemoteRuntimeSubscription = { @@ -35,7 +39,8 @@ export function sendRemoteRuntimeRequest( timeoutMs: number, envelope?: RuntimeOrchestrationEnvelope, signal?: AbortSignal, - clientCapabilities: readonly RuntimeCapability[] = [] + clientCapabilities: readonly RuntimeCapability[] = [], + expectedRuntimeSource?: ExpectedRuntimeSource ): Promise> { return sendRemoteRuntimeRequestOnSocket( connection, @@ -45,7 +50,8 @@ export function sendRemoteRuntimeRequest( envelope, undefined, signal, - clientCapabilities + clientCapabilities, + expectedRuntimeSource ) } @@ -57,7 +63,8 @@ export function sendRemoteRuntimeRequestWithStatusPreflight( validateStatus: (response: RuntimeRpcResponse) => void, envelope?: RuntimeOrchestrationEnvelope, clientCapabilities: readonly RuntimeCapability[] = [], - signal?: AbortSignal + signal?: AbortSignal, + expectedRuntimeSource?: ExpectedRuntimeSource ): Promise> { return sendRemoteRuntimeRequestOnSocket( connection, @@ -67,7 +74,8 @@ export function sendRemoteRuntimeRequestWithStatusPreflight( envelope, validateStatus, signal, - clientCapabilities + clientCapabilities, + expectedRuntimeSource ) } diff --git a/src/shared/remote-runtime-memory-limits.ts b/src/shared/remote-runtime-memory-limits.ts index b70795ca2ca5..7a525af07855 100644 --- a/src/shared/remote-runtime-memory-limits.ts +++ b/src/shared/remote-runtime-memory-limits.ts @@ -3,7 +3,7 @@ import { stringifyJsonWithinByteLimit } from './node-bounded-json-stringify' import { RemoteRuntimeClientError } from './remote-runtime-client-error' -import type { RuntimeOrchestrationEnvelope } from './runtime-rpc-envelope' +import type { ExpectedRuntimeSource, RuntimeOrchestrationEnvelope } from './runtime-rpc-envelope' export const REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES = 4 * 1024 * 1024 // Why: a host refuses a larger client frame by closing the socket (1009), failing every call on it. @@ -75,12 +75,14 @@ export function serializeRemoteRuntimeRpcRequest(args: { method: string params: unknown envelope?: RuntimeOrchestrationEnvelope + expectedRuntimeSource?: ExpectedRuntimeSource }): string { return serializeRemoteRuntimePayload({ id: args.requestId, deviceToken: args.deviceToken, method: args.method, params: args.params, + expectedRuntimeSource: args.expectedRuntimeSource, orchestrationCapability: args.envelope?.orchestrationCapability, orchestrationContractVersion: args.envelope?.orchestrationContractVersion, orchestrationRequestId: args.envelope?.orchestrationRequestId, diff --git a/src/shared/remote-runtime/requests/remote-runtime-request-socket.ts b/src/shared/remote-runtime/requests/remote-runtime-request-socket.ts index e91745504531..8791e55ea069 100644 --- a/src/shared/remote-runtime/requests/remote-runtime-request-socket.ts +++ b/src/shared/remote-runtime/requests/remote-runtime-request-socket.ts @@ -25,7 +25,11 @@ import { takeRemoteRuntimePreparedRequest } from './remote-runtime-prepared-request-admission' import { RemoteRuntimeRequestResponseRouter } from './remote-runtime-request-response-router' -import type { RuntimeOrchestrationEnvelope, RuntimeRpcResponse } from '../../runtime-rpc-envelope' +import type { + ExpectedRuntimeSource, + RuntimeOrchestrationEnvelope, + RuntimeRpcResponse +} from '../../runtime-rpc-envelope' import type { RuntimeStatus } from '../../runtime-types' import { isSafeTimerDelayMs, MAX_TIMER_DELAY_MS } from '../../timer-delay' @@ -37,7 +41,8 @@ export async function sendRemoteRuntimeRequestOnSocket( envelope?: RuntimeOrchestrationEnvelope, validateStatus?: (response: RuntimeRpcResponse) => void, signal?: AbortSignal, - clientCapabilities: readonly RuntimeCapability[] = [] + clientCapabilities: readonly RuntimeCapability[] = [], + expectedRuntimeSource?: ExpectedRuntimeSource ): Promise> { throwIfSignalAborted(signal) if (!isSafeTimerDelayMs(timeoutMs)) { @@ -62,7 +67,8 @@ export async function sendRemoteRuntimeRequestOnSocket( deviceToken: connection.credential.deviceToken, method, params, - envelope + envelope, + expectedRuntimeSource }) ) } From 0859a7503e576c2a2f2a521a9e5b558ad3f50cf8 Mon Sep 17 00:00:00 2001 From: Codeping223 Date: Sun, 25 Oct 2026 17:24:53 +0900 Subject: [PATCH 2/4] docs(cli): explain native request and transport contracts --- src/cli/agent-request-answer-file.ts | 3 +++ src/cli/agent-request-answer.ts | 4 ++++ src/cli/agent-request-inventory.ts | 9 +++++++++ src/cli/agent-request-test-fixtures.ts | 3 +++ src/cli/handler-group-manifest.ts | 1 + src/cli/handlers/agent-requests.ts | 4 ++++ src/cli/runtime/client.ts | 2 ++ src/cli/runtime/remote-runtime-compat-gate.ts | 1 + src/cli/runtime/runtime-source-fence.ts | 2 ++ src/cli/runtime/status.ts | 1 + src/cli/runtime/websocket-transport.ts | 2 ++ src/shared/remote-runtime-client.ts | 2 ++ src/shared/remote-runtime-memory-limits.ts | 1 + .../requests/remote-runtime-request-socket.ts | 1 + 14 files changed, 36 insertions(+) diff --git a/src/cli/agent-request-answer-file.ts b/src/cli/agent-request-answer-file.ts index d60143f82250..8f3a91f8e2f6 100644 --- a/src/cli/agent-request-answer-file.ts +++ b/src/cli/agent-request-answer-file.ts @@ -26,6 +26,7 @@ const AnswerFile = z .strict() export type AgentRequestAnswerFile = z.infer +/** Loads a size-checked JSON answer file and reports read or parse failures as safe CLI errors. */ export async function readAgentRequestAnswerFile(path: string): Promise { try { const info = await stat(path) @@ -45,6 +46,7 @@ export async function readAgentRequestAnswerFile(path: string): Promise, runtimeId: string): void { if (response._meta.runtimeId !== runtimeId) { requestRefusal( @@ -51,6 +53,7 @@ export function requireSameRuntime(response: RuntimeRpcSuccess, runtime } } +/** Returns the responding runtime ID only when authoritative native-request reads are supported. */ export async function readRequestHost(client: AgentRequestClient): Promise { const response = await client.call('status.get') const capabilities = response.result.capabilities ?? [] @@ -67,6 +70,7 @@ export async function readRequestHost(client: AgentRequestClient): Promise unknown ) { @@ -113,6 +115,7 @@ export function requestFixtureClient( return { id: 'test-request', ok: true, _meta: { runtimeId: REQUEST_RUNTIME }, result } }) const client: AgentRequestClient = { + /** Adapts fixture replies to the generic client API while recording each attempted RPC. */ async call( method: string, params?: unknown, diff --git a/src/cli/handler-group-manifest.ts b/src/cli/handler-group-manifest.ts index 859dd8981b37..feb460b97acf 100644 --- a/src/cli/handler-group-manifest.ts +++ b/src/cli/handler-group-manifest.ts @@ -213,6 +213,7 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ { name: 'agent-requests', keys: ['agent requests list', 'agent requests get', 'agent requests answer'], + /** Defers native-request dependencies until this command group is dispatched. */ load: async () => (await import('./handlers/agent-requests.js')).AGENT_REQUEST_HANDLERS }, { diff --git a/src/cli/handlers/agent-requests.ts b/src/cli/handlers/agent-requests.ts index f3544aa3328e..905a42480011 100644 --- a/src/cli/handlers/agent-requests.ts +++ b/src/cli/handlers/agent-requests.ts @@ -6,6 +6,7 @@ import { listAgentRequests, type AgentRequestScope } from '../agent-request-inve import { answerAgentRequest } from '../agent-request-answer' import { readAgentRequestAnswerFile } from '../agent-request-answer-file' +/** Requires explicit session/workspace selectors and refuses ambient focus or wildcard targets. */ function scope({ flags }: HandlerContext): AgentRequestScope { const worktree = getRequiredStringFlag(flags, 'worktree') if (['active', 'current', 'all', '*'].includes(worktree)) { @@ -21,6 +22,7 @@ function scope({ flags }: HandlerContext): AgentRequestScope { } } +/** Prints current scoped prompts and refuses item IDs outside the authoritative snapshot. */ const read: CommandHandler = async (context) => { const target = scope(context) const inventory = await listAgentRequests(context.client, target) @@ -49,10 +51,12 @@ const read: CommandHandler = async (context) => { export const AGENT_REQUEST_HANDLERS: Record = { 'agent requests list': read, + /** Requires a named item before performing the same authoritative scoped read. */ 'agent requests get': async (context) => { getRequiredStringFlag(context.flags, 'item') await read(context) }, + /** Reads exact answers from a file and prints their receipt without interpreting prompt text. */ 'agent requests answer': async (context) => { const target = scope(context) const input = await readAgentRequestAnswerFile( diff --git a/src/cli/runtime/client.ts b/src/cli/runtime/client.ts index 02ed77ef6bb7..4547dd1217dc 100644 --- a/src/cli/runtime/client.ts +++ b/src/cli/runtime/client.ts @@ -84,6 +84,7 @@ export class RuntimeClient { return this.remote !== null } + /** Routes authenticated RPCs with optional target-local pins and existing mutation recovery. */ async call( method: string, params?: unknown, @@ -218,6 +219,7 @@ export class RuntimeClient { return this.requestTimeoutMs } + /** Returns local or paired-host status while applying the paired runtime compatibility check. */ async getCliStatus(): Promise> { if (this.remote) { const response = await this.call('status.get') diff --git a/src/cli/runtime/remote-runtime-compat-gate.ts b/src/cli/runtime/remote-runtime-compat-gate.ts index ec86873c2ebd..8c425ac7937f 100644 --- a/src/cli/runtime/remote-runtime-compat-gate.ts +++ b/src/cli/runtime/remote-runtime-compat-gate.ts @@ -29,6 +29,7 @@ export class RemoteRuntimeCompatGate { private readonly environmentSelector: string | null ) {} + /** Checks remote compatibility when needed and carries the explicit pin to the target transport. */ send(args: { transport: WebSocketTransport connection: PairedRuntimeConnection diff --git a/src/cli/runtime/runtime-source-fence.ts b/src/cli/runtime/runtime-source-fence.ts index e86f14e87da5..8f8afcacc669 100644 --- a/src/cli/runtime/runtime-source-fence.ts +++ b/src/cli/runtime/runtime-source-fence.ts @@ -37,6 +37,7 @@ export class RuntimeSourceFence { } } + /** Rejects a changed runtime before probing and reconciles explicit and inherited profile pins. */ async check( metadata: RuntimeMetadata, method: string, @@ -58,6 +59,7 @@ export class RuntimeSourceFence { return pinnedSource ?? inheritedSource } + /** Verifies uncached runtime incarnations still serve the launching profile before admitting them. */ private async checkLaunchingSource( metadata: RuntimeMetadata, method: string diff --git a/src/cli/runtime/status.ts b/src/cli/runtime/status.ts index 1011d5f02ce1..5e1f24468354 100644 --- a/src/cli/runtime/status.ts +++ b/src/cli/runtime/status.ts @@ -102,6 +102,7 @@ function buildCliStatusResponse(result: CliStatusResult): RuntimeRpcSuccess, environmentSelector: string | null diff --git a/src/cli/runtime/websocket-transport.ts b/src/cli/runtime/websocket-transport.ts index 54fd450350e9..eeb54a58c092 100644 --- a/src/cli/runtime/websocket-transport.ts +++ b/src/cli/runtime/websocket-transport.ts @@ -19,6 +19,7 @@ const CLI_CLIENT_CAPABILITIES = [ ...AGENT_REQUEST_CLI_CAPABILITIES ] as const +/** Sends one paired RPC with CLI capabilities and an optional execution-host runtime pin. */ export async function sendWebSocketRequest( connection: PairedRuntimeConnection, method: string, @@ -46,6 +47,7 @@ export async function sendWebSocketRequest( } } +/** Validates status on the paired socket before sending the RPC with its target-local pin. */ export async function sendWebSocketRequestWithStatusPreflight( connection: PairedRuntimeConnection, method: string, diff --git a/src/shared/remote-runtime-client.ts b/src/shared/remote-runtime-client.ts index 33d4f4a2b82f..2e7d3ed39d81 100644 --- a/src/shared/remote-runtime-client.ts +++ b/src/shared/remote-runtime-client.ts @@ -32,6 +32,7 @@ export type RemoteRuntimeSubscriptionCallbacks = { onClose?: () => void } +/** Sends one authenticated remote request, keeping its runtime pin separate from forwarded metadata. */ export function sendRemoteRuntimeRequest( connection: PairedRuntimeConnection, method: string, @@ -55,6 +56,7 @@ export function sendRemoteRuntimeRequest( ) } +/** Runs the supplied status validator before the requested RPC on the same authenticated socket. */ export function sendRemoteRuntimeRequestWithStatusPreflight( connection: PairedRuntimeConnection, method: string, diff --git a/src/shared/remote-runtime-memory-limits.ts b/src/shared/remote-runtime-memory-limits.ts index 7a525af07855..55463d9d1bf4 100644 --- a/src/shared/remote-runtime-memory-limits.ts +++ b/src/shared/remote-runtime-memory-limits.ts @@ -69,6 +69,7 @@ export function measureRemoteRuntimeSubscriptionParams(params: unknown): number } } +/** Serializes a bounded RPC frame with an explicit transport pin, leaving forwarding metadata intact. */ export function serializeRemoteRuntimeRpcRequest(args: { requestId: string deviceToken: string diff --git a/src/shared/remote-runtime/requests/remote-runtime-request-socket.ts b/src/shared/remote-runtime/requests/remote-runtime-request-socket.ts index 8791e55ea069..eb889924a61b 100644 --- a/src/shared/remote-runtime/requests/remote-runtime-request-socket.ts +++ b/src/shared/remote-runtime/requests/remote-runtime-request-socket.ts @@ -33,6 +33,7 @@ import type { import type { RuntimeStatus } from '../../runtime-types' import { isSafeTimerDelayMs, MAX_TIMER_DELAY_MS } from '../../timer-delay' +/** Owns one E2EE RPC socket through authentication, optional preflight, bounded reply and cleanup. */ export async function sendRemoteRuntimeRequestOnSocket( connection: PairedRuntimeConnection, method: string, From ca9464789cada487c124de49de9bfe9590085e6f Mon Sep 17 00:00:00 2001 From: Codeping223 Date: Sun, 25 Oct 2026 17:37:03 +0900 Subject: [PATCH 3/4] fix(cli): reject malformed UTF-8 native answer files --- src/cli/agent-request-answer-file.ts | 8 +++--- src/cli/agent-request-answer.test.ts | 30 +++++++++++++++++++++- src/cli/agent-request-handlers.test.ts | 35 ++++++++++++++++++++++++++ src/cli/agent-request-test-fixtures.ts | 19 ++++++++++++++ 4 files changed, 88 insertions(+), 4 deletions(-) diff --git a/src/cli/agent-request-answer-file.ts b/src/cli/agent-request-answer-file.ts index 8f3a91f8e2f6..ce7ad2cc459e 100644 --- a/src/cli/agent-request-answer-file.ts +++ b/src/cli/agent-request-answer-file.ts @@ -1,4 +1,5 @@ import { readFile, stat } from 'node:fs/promises' +import { TextDecoder } from 'node:util' import { z } from 'zod' import { RuntimeClientError } from './runtime/types' import { AgentRequestMarkerSchema } from './agent-request-inventory' @@ -26,17 +27,18 @@ const AnswerFile = z .strict() export type AgentRequestAnswerFile = z.infer -/** Loads a size-checked JSON answer file and reports read or parse failures as safe CLI errors. */ +/** Loads size-checked JSON using strict UTF-8, allowing one leading BOM and rejecting invalid bytes. */ export async function readAgentRequestAnswerFile(path: string): Promise { try { const info = await stat(path) if (!info.isFile() || info.size > 128 * 1024) { throw new Error('size') } - const content = await readFile(path, 'utf8') - if (Buffer.byteLength(content, 'utf8') > 128 * 1024) { + const bytes = await readFile(path) + if (bytes.byteLength > 128 * 1024) { throw new Error('size') } + const content = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes) return parseAgentRequestAnswerFile(JSON.parse(content.replace(/^\uFEFF/, ''))) } catch { throw new RuntimeClientError( diff --git a/src/cli/agent-request-answer.test.ts b/src/cli/agent-request-answer.test.ts index d1b6be231f9f..6bdc02e2384a 100644 --- a/src/cli/agent-request-answer.test.ts +++ b/src/cli/agent-request-answer.test.ts @@ -1,6 +1,10 @@ import { describe, expect, it } from 'vitest' import { answerAgentRequest } from './agent-request-answer' -import { nativeAnswerParams, parseAgentRequestAnswerFile } from './agent-request-answer-file' +import { + nativeAnswerParams, + parseAgentRequestAnswerFile, + readAgentRequestAnswerFile +} from './agent-request-answer-file' import { REQUEST_MARKER, REQUEST_PROMPT, @@ -9,6 +13,7 @@ import { REQUEST_SOURCE, REQUEST_WORKSPACE, answerFile, + withAnswerBytes, requestFixtureClient } from './agent-request-test-fixtures' import { RuntimeRpcFailureError } from './runtime/types' @@ -25,6 +30,29 @@ const ok = (result: unknown) => ({ const isMutation = (method: string) => method.startsWith('agentSession.respondTo') describe('native answer JSON and admission', () => { + it.each([false, true])( + 'preserves valid Unicode and typed text with leading BOM=%s', + async (bom) => { + const { optionId: _option, ...base } = answerFile() + const answers = [ + { questionId: 'q1', optionIds: [], other: '한글 🙂\n둘째 줄 \uFFFD \uFEFF 그대로' } + ] + const input = { ...base, kind: 'question', answers } + const bytes = Buffer.from((bom ? '\uFEFF' : '') + JSON.stringify(input), 'utf8') + await withAnswerBytes(bytes, async (path) => { + expect(await readAgentRequestAnswerFile(path)).toMatchObject(input) + }) + } + ) + + it('rejects a second leading BOM rather than silently stripping it too', async () => { + const bytes = Buffer.from(`\uFEFF\uFEFF${JSON.stringify(answerFile())}`, 'utf8') + await withAnswerBytes(bytes, async (path) => { + await expect(readAgentRequestAnswerFile(path)).rejects.toMatchObject({ + code: 'invalid_argument' + }) + }) + }) it('preserves exact grouped question ids, choices, newlines and UTF-8 answer text', () => { const input = answerFile() const { optionId: _option, ...base } = input diff --git a/src/cli/agent-request-handlers.test.ts b/src/cli/agent-request-handlers.test.ts index 3c85c6e733ce..ac5145f37b74 100644 --- a/src/cli/agent-request-handlers.test.ts +++ b/src/cli/agent-request-handlers.test.ts @@ -2,14 +2,18 @@ import { describe, expect, it, vi } from 'vitest' import { parseArgs, specPaths, validateCommandAndFlags } from './args' import { AGENT_REQUEST_COMMAND_SPECS } from './specs/agent-requests' import { AGENT_REQUEST_HANDLERS } from './handlers/agent-requests' +import { parseAgentRequestAnswerFile } from './agent-request-answer-file' import type { HandlerContext } from './dispatch' import type { RuntimeClient } from './runtime-client' import { REQUEST_SESSION, REQUEST_WORKSPACE, + answerFile, + withAnswerBytes, requestFixtureClient } from './agent-request-test-fixtures' +/** Supplies a call-only runtime fake so rejected CLI input can be checked before any RPC. */ function context(entries: [string, string | boolean][]) { const { client, call } = requestFixtureClient() // SAFETY: these handlers consume only call; the test supplies that exact checked fake interface. @@ -23,6 +27,7 @@ function context(entries: [string, string | boolean][]) { return { value, call } } +/** Fails on missing registration and invokes the selected command with an isolated test context. */ async function handler(key: string, input: HandlerContext) { const selected = AGENT_REQUEST_HANDLERS[key] if (!selected) { @@ -32,6 +37,36 @@ async function handler(key: string, input: HandlerContext) { } describe('public scoped native-request commands', () => { + it('rejects an illegal UTF-8 byte inside valid JSON before reading or mutating the runtime', async () => { + const { optionId: _option, ...base } = answerFile() + const json = Buffer.from( + JSON.stringify({ + ...base, + kind: 'question', + answers: [{ questionId: 'q1', optionIds: [], other: 'UTF8_SENTINEL' }] + }) + ) + const marker = Buffer.from('UTF8_SENTINEL') + const index = json.indexOf(marker) + expect(index).toBeGreaterThan(0) + const bytes = Buffer.concat([ + json.subarray(0, index), + Buffer.from([0xff]), + json.subarray(index + marker.length) + ]) + expect(() => parseAgentRequestAnswerFile(JSON.parse(bytes.toString('utf8')))).not.toThrow() + await withAnswerBytes(bytes, async (path) => { + const { value, call } = context([ + ['worktree', `id:${REQUEST_WORKSPACE}`], + ['session', REQUEST_SESSION], + ['request-file', path] + ]) + await expect(handler('agent requests answer', value)).rejects.toMatchObject({ + code: 'invalid_argument' + }) + expect(call).not.toHaveBeenCalled() + }) + }) it('parses the three-level command and a valued same-operation retry', () => { const argv = [ 'agent', diff --git a/src/cli/agent-request-test-fixtures.ts b/src/cli/agent-request-test-fixtures.ts index 498da9153334..58705d366e1e 100644 --- a/src/cli/agent-request-test-fixtures.ts +++ b/src/cli/agent-request-test-fixtures.ts @@ -1,3 +1,6 @@ +import { mkdtemp, rm, rmdir, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' import { vi } from 'vitest' import type { RuntimeRpcSuccess } from './runtime-client' import type { AgentRequestClient } from './agent-request-inventory' @@ -55,6 +58,22 @@ export function answerFile() { } } +/** Gives byte-level file tests one temporary file and removes it even when their assertions fail. */ +export async function withAnswerBytes( + bytes: Uint8Array, + run: (path: string) => Promise +): Promise { + const directory = await mkdtemp(join(tmpdir(), 'orca-answer-utf8-')) + const path = join(directory, 'answer.json') + try { + await writeFile(path, bytes) + return await run(path) + } finally { + await rm(path, { force: true }) + await rmdir(directory) + } +} + /** Provides deterministic read/receipt responses; overrides simulate races without a live runtime. */ export function requestFixtureClient( override?: (method: string, params: unknown, options: unknown) => unknown From 7c37d9b5fc97c65c828c83641d368f164e50b5c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EA=B0=91=EC=97=B4?= Date: Wed, 25 Nov 2026 21:38:14 +0900 Subject: [PATCH 4/4] fix(cli): validate first execution after a missing native answer receipt --- docs/readme/agent-requests-cli.md | 32 +-- .../agents/agent-request-answer-file.test.ts | 118 +++++++++++ src/cli/agents/agent-request-answer-file.ts | 16 +- src/cli/agents/agent-request-answer.test.ts | 187 +++++++++++++++++- src/cli/agents/agent-request-answer.ts | 103 ++++++---- src/cli/agents/agent-request-handlers.test.ts | 5 +- src/cli/agents/agent-request-test-fixtures.ts | 13 +- src/cli/discovery/command-scoped-flag-help.ts | 2 +- src/cli/specs/agent-requests.ts | 6 +- ...gent-session-prompt-receipt-replay.test.ts | 120 +++++++++++ ...uctured-agent-session-command-admission.ts | 27 +++ ...ctured-agent-session-mutation-admission.ts | 2 + ...ructured-agent-session-mutation-context.ts | 10 + ...structured-agent-session-mutation-plans.ts | 2 + .../structured-agent-session-prompt-plan.ts | 1 + .../structured-agent-session-turns-prompt.ts | 1 + .../agent-session-runtime-capabilities.ts | 3 + .../failures/agent-session-refusal-details.ts | 1 + .../agent-session-refusal-reason-words.ts | 1 + .../structured-agent-session-params.ts | 1 + ...tructured-agent-session-question-params.ts | 1 + 21 files changed, 582 insertions(+), 70 deletions(-) create mode 100644 src/cli/agents/agent-request-answer-file.test.ts create mode 100644 src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-prompt-receipt-replay.test.ts diff --git a/docs/readme/agent-requests-cli.md b/docs/readme/agent-requests-cli.md index 6b2ec1d9b749..0b965c40f8af 100644 --- a/docs/readme/agent-requests-cli.md +++ b/docs/readme/agent-requests-cli.md @@ -40,7 +40,7 @@ the runtime, workspace and session fence. Copy the identities, marker and revision from the inspected result. Choose one offered approval `optionId`, or supply structured question `answers`. Do not invent an option, rewrite a question -ID, trim typed answers or repurpose an operation UUID. The UTF-8 file is limited to 128 KiB and +ID, trim typed answers or reuse an operation ID for a different answer. The UTF-8 file is limited to 128 KiB and rejects unknown top-level keys. Its required fields are: ```json @@ -61,11 +61,19 @@ rejects unknown top-level keys. Its required fields are: "kind": "approval", "expectedRuntimeFence": 7, "expectedRevision": 1, - "clientOperationId": "33333333-3333-4333-8333-333333333333", + "clientOperationId": "1795600000000-33333333333343338333333333333333", "optionId": "exact-offered-id" } ``` +Generate a fresh `clientOperationId` for the initial answer and save it in the file. It uses +the current Unix time in milliseconds, a hyphen, and 32 lowercase hexadecimal digits. +For example, this Node.js command prints one ID: + +```sh +node -p "Date.now() + '-' + require('node:crypto').randomUUID().replaceAll('-', '')" +``` + For a question use `"kind": "question"` and replace `optionId` with: ```json @@ -109,19 +117,21 @@ been committed before the provider connection failed. Acceptance is therefore no provider resumption or task completion; follow subsequent authoritative status separately. After a lost response, inspect the session first. If deliberately replaying the same operation, -reuse the exact original file and pass its UUID: +reuse the exact original file and pass its operation ID: ```text -orca agent requests answer --worktree id: --session --request-file answer.json --retry --json +orca agent requests answer --worktree id: --session --request-file answer.json --retry --json ``` -`--retry` must equal the file UUID. It sends that same native operation once and allows the -host's existing receipt-first replay even when the original prompt is no longer pending, its -marker changed or its fence advanced. Runtime, session and workspace must still match. The CLI -does not generate a fresh operation, retry automatically, choose another pending question or -claim that an unknown outcome failed. Explicit host refusals retain their code; uncertain -transport or mismatched receipts remain unknown. A closed tab whose workspace identity can no -longer be proved is refused even for replay. +`--retry` must match the file’s `clientOperationId`. The CLI first asks the same host for +the recorded outcome of that operation and payload. An existing receipt can be replayed +after the prompt closes or the marker changes. Only a confirmed missing receipt allows a +first submission. The CLI then rechecks the pending item, revision, fence, complete marker +and requested turn, just as it does for an initial answer. An uncertain lookup stops the +retry. Keep the original ID when checking an unknown outcome. + +Retries require a host that advertises receipt lookup for prompt responses. The session +must still be identifiable in the same workspace and runtime. No permission rejection, human-only platform requirement or unsupported native workflow is bypassed by these commands. Update the execution host when its native contracts are missing. diff --git a/src/cli/agents/agent-request-answer-file.test.ts b/src/cli/agents/agent-request-answer-file.test.ts new file mode 100644 index 000000000000..e51d6c75b788 --- /dev/null +++ b/src/cli/agents/agent-request-answer-file.test.ts @@ -0,0 +1,118 @@ +import { dirname } from 'node:path' +import { open } from 'node:fs/promises' +import * as fs from 'node:fs/promises' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + parseAgentRequestAnswerFile, + readAgentRequestAnswerFile +} from './agent-request-answer-file' +import { answerFile, withAnswerBytes } from './agent-request-test-fixtures' +import { createStructuredAgentSessionOperationId } from '../../shared/agent-session/lifecycle/operations/structured-agent-session-mutation' +import { parseAgentSessionOperationTimestamp } from '../../shared/agent-session/lifecycle/operations/agent-session-host-authority' + +vi.mock('node:fs/promises', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, open: vi.fn(actual.open) } +}) + +const MAX_BYTES = 128 * 1024 + +function paddedAnswer(size: number): Buffer { + const json = JSON.stringify(answerFile()) + return Buffer.from(json + ' '.repeat(size - Buffer.byteLength(json))) +} + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('native answer file input contract', () => { + it('accepts the shared generator output and preserves the host operation timestamp', () => { + const timestamp = 1795550000000 + const clientOperationId = createStructuredAgentSessionOperationId( + () => 'ABCDEF01-2345-4678-9ABC-DEF012345678', + timestamp + ) + const parsed = parseAgentRequestAnswerFile({ ...answerFile(), clientOperationId }) + expect(parsed.clientOperationId).toBe(clientOperationId) + expect(parseAgentSessionOperationTimestamp(parsed.clientOperationId)).toBe(timestamp) + }) + + it.each([ + '33333333-3333-4333-8333-333333333333', + '179555000000-33333333333343338333333333333333', + '17955500000000-33333333333343338333333333333333', + '1795550000000-ABCDEF01234546789ABCDEF012345678', + '1795550000000-3333333333334333833333333333333g' + ])('rejects operation ids the host cannot admit: %s', (clientOperationId) => { + expect(parseAgentSessionOperationTimestamp(clientOperationId)).toBeNull() + expect(() => parseAgentRequestAnswerFile({ ...answerFile(), clientOperationId })).toThrow() + }) + + it.each([MAX_BYTES, MAX_BYTES + 1])('enforces the byte boundary at %i bytes', async (size) => { + await withAnswerBytes(paddedAnswer(size), async (path) => { + if (size === MAX_BYTES) { + expect(await readAgentRequestAnswerFile(path)).toEqual(answerFile()) + } else { + await expect(readAgentRequestAnswerFile(path)).rejects.toMatchObject({ + code: 'invalid_argument' + }) + } + }) + }) + + it('caps reads after handle stat underreports a growing file and closes the handle', async () => { + await withAnswerBytes(paddedAnswer(MAX_BYTES * 2), async (path) => { + const handle = await open(path, 'r') + const stats = await handle.stat() + stats.size = 1 + vi.spyOn(handle, 'stat').mockResolvedValue(stats) + const read = vi.spyOn(handle, 'read') + const close = vi.spyOn(handle, 'close') + vi.mocked(fs.open).mockResolvedValueOnce(handle) + await expect(readAgentRequestAnswerFile(path)).rejects.toMatchObject({ + code: 'invalid_argument' + }) + let bytesRead = 0 + for (const result of read.mock.results) { + if (result.type === 'return') { + bytesRead += (await result.value).bytesRead + } + } + expect(bytesRead).toBe(MAX_BYTES + 1) + expect(close).toHaveBeenCalledOnce() + }) + }) + + it('continues after short reads through EOF on the same handle', async () => { + await withAnswerBytes(Buffer.from(JSON.stringify(answerFile())), async (path) => { + const handle = await open(path, 'r') + const originalRead = handle.read.bind(handle) + const read = vi.spyOn(handle, 'read').mockImplementation(async (...args: unknown[]) => { + const [buffer, offset, length, position] = args + if ( + Buffer.isBuffer(buffer) && + typeof offset === 'number' && + typeof length === 'number' && + (typeof position === 'number' || position === null) + ) { + return originalRead(buffer, offset, Math.min(length, 17), position) + } + throw new Error('Unexpected read signature') + }) + const close = vi.spyOn(handle, 'close') + vi.mocked(fs.open).mockResolvedValueOnce(handle) + expect(await readAgentRequestAnswerFile(path)).toEqual(answerFile()) + expect(read.mock.calls.length).toBeGreaterThan(2) + expect(close).toHaveBeenCalledOnce() + }) + }) + + it('rejects a nonregular file before reading its contents', async () => { + await withAnswerBytes(Buffer.alloc(0), async (path) => { + await expect(readAgentRequestAnswerFile(dirname(path))).rejects.toMatchObject({ + code: 'invalid_argument' + }) + }) + }) +}) diff --git a/src/cli/agents/agent-request-answer-file.ts b/src/cli/agents/agent-request-answer-file.ts index 34c4540867bc..ce52ef9f2e5a 100644 --- a/src/cli/agents/agent-request-answer-file.ts +++ b/src/cli/agents/agent-request-answer-file.ts @@ -1,4 +1,3 @@ -import { readFile, stat } from 'node:fs/promises' import { TextDecoder } from 'node:util' import { z } from 'zod' import { RuntimeClientError } from '../runtime/connection/types' @@ -6,6 +5,8 @@ import { AgentRequestMarkerSchema } from './agent-request-inventory' import { RespondParams } from '../../shared/rpc-contract/structured-agent-session/structured-agent-session-params' import { RespondToQuestionParams } from '../../shared/rpc-contract/structured-agent-session/structured-agent-session-question-params' import { structuredAgentSessionPayloadFingerprint } from '../../shared/agent-session/lifecycle/operations/structured-agent-session-mutation' +import { parseAgentSessionOperationTimestamp } from '../../shared/agent-session/lifecycle/operations/agent-session-host-authority' +import { readNodeFileWithinLimit } from '../../shared/file-content/node-bounded-file-reader' const AnswerFile = z .object({ @@ -17,7 +18,7 @@ const AnswerFile = z kind: z.enum(['approval', 'question']), expectedRuntimeFence: z.number().int().positive(), expectedRevision: z.number().int().positive(), - clientOperationId: z.string().uuid(), + clientOperationId: z.string().refine((id) => parseAgentSessionOperationTimestamp(id) !== null), turnItemId: z.string().min(1).optional(), optionId: z.string().optional(), answers: z.unknown().optional() @@ -28,14 +29,9 @@ export type AgentRequestAnswerFile = z.infer /** Loads size-checked JSON using strict UTF-8, allowing one leading BOM and rejecting invalid bytes. */ export async function readAgentRequestAnswerFile(path: string): Promise { try { - const info = await stat(path) - if (!info.isFile() || info.size > 128 * 1024) { - throw new Error('size') - } - const bytes = await readFile(path) - if (bytes.byteLength > 128 * 1024) { - throw new Error('size') - } + const { buffer: bytes } = await readNodeFileWithinLimit(path, 128 * 1024, { + regularFileOnly: true + }) const content = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes) return parseAgentRequestAnswerFile(JSON.parse(content.replace(/^\uFEFF/, ''))) } catch { diff --git a/src/cli/agents/agent-request-answer.test.ts b/src/cli/agents/agent-request-answer.test.ts index c5db67caa6ec..97b1c14274ce 100644 --- a/src/cli/agents/agent-request-answer.test.ts +++ b/src/cli/agents/agent-request-answer.test.ts @@ -19,6 +19,8 @@ import { import { RuntimeRpcFailureError } from '../runtime/connection/types' import { computeAgentSessionPayloadFingerprint } from '../../shared/agent-session/lifecycle/operations/agent-session-mutation-envelope' import { AGENT_REQUEST_CLI_CAPABILITIES } from './agent-request-capabilities' +import { refuse } from '../../shared/agent-session/failures/agent-session-wire-refusals' +import { RUNTIME_SOURCE_FENCE_RUNTIME_CAPABILITY } from '../../shared/remote-runtime/protocol/host-runtime-capabilities' const scope = { worktree: `id:${REQUEST_WORKSPACE}`, sessionId: REQUEST_SESSION } const ok = (result: unknown) => ({ @@ -252,18 +254,184 @@ describe('native answer JSON and admission', () => { } return undefined }) - const input = parseAgentRequestAnswerFile({ ...answerFile(), expectedRuntimeFence: 6 }) + const input = parseAgentRequestAnswerFile({ + ...answerFile(), + expectedRuntimeFence: 6, + turnItemId: 'finished-turn' + }) const result = await answerAgentRequest(client, scope, input, input.clientOperationId) expect(result.result.result.replayed).toBe(true) expect( call.mock.calls.filter(([method]) => method === 'agentSession.currentRequests') ).toHaveLength(0) - expect(call.mock.calls.filter(([method]) => isMutation(method))).toHaveLength(1) + const mutations = call.mock.calls.filter(([method]) => isMutation(method)) + expect(mutations).toHaveLength(1) + expect(mutations[0]?.[1]).toEqual({ ...nativeAnswerParams(input), replayOnly: true }) + expect(mutations[0]?.[2]).toEqual({ + expectedRuntimeSource: { sourceId: REQUEST_SOURCE, runtimeId: REQUEST_RUNTIME } + }) await expect( answerAgentRequest(client, scope, input, '44444444-4444-4444-8444-444444444444') ).rejects.toMatchObject({ code: 'invalid_argument' }) }) + it('refuses retry on a host without receipt-only support before sending', async () => { + const { client, call } = requestFixtureClient((method) => + method === 'status.get' + ? ok({ + runtimeId: REQUEST_RUNTIME, + capabilities: [ + ...AGENT_REQUEST_CLI_CAPABILITIES, + RUNTIME_SOURCE_FENCE_RUNTIME_CAPABILITY + ], + hostDescriptor: { installationId: REQUEST_SOURCE } + }) + : undefined + ) + const input = parseAgentRequestAnswerFile(answerFile()) + await expect( + answerAgentRequest(client, scope, input, input.clientOperationId) + ).rejects.toMatchObject({ + code: 'incompatible_runtime' + }) + expect(call.mock.calls.filter(([method]) => isMutation(method))).toHaveLength(0) + }) + + it('sends once after an exact receipt miss and successful current-request validation', async () => { + const { client, call } = requestFixtureClient((method, params) => { + if ( + isMutation(method) && + typeof params === 'object' && + params !== null && + 'replayOnly' in params + ) { + return ok({ + ok: false, + refusal: refuse( + 'agent_session_operation_invalid', + { reason: 'receiptMissing' }, + 'No recorded receipt.' + ) + }) + } + return undefined + }) + const input = parseAgentRequestAnswerFile(answerFile()) + const result = await answerAgentRequest(client, scope, input, input.clientOperationId) + expect(result.result.result.replayed).toBe(false) + const mutations = call.mock.calls.filter(([method]) => isMutation(method)) + expect(mutations.map(([, params]) => params)).toEqual([ + { ...nativeAnswerParams(input), replayOnly: true }, + nativeAnswerParams(input) + ]) + expect(mutations.map(([, , options]) => options)).toEqual([ + { expectedRuntimeSource: { sourceId: REQUEST_SOURCE, runtimeId: REQUEST_RUNTIME } }, + { expectedRuntimeSource: { sourceId: REQUEST_SOURCE, runtimeId: REQUEST_RUNTIME } } + ]) + const methods = call.mock.calls.map(([method]) => method) + expect(methods.indexOf('agentSession.currentRequests')).toBeGreaterThan( + methods.indexOf('agentSession.respondToApproval') + ) + }) + + it.each(['pending', 'turn', 'fence', 'marker', 'option'])( + 'never executes a missing retry receipt with an invalid current %s', + async (kind) => { + const { client, call } = requestFixtureClient((method, params) => { + if (isMutation(method)) { + return ok({ + ok: false, + refusal: refuse( + 'agent_session_operation_invalid', + { reason: 'receiptMissing' }, + 'No recorded receipt.' + ) + }) + } + if ( + kind === 'pending' && + method === 'agentSession.currentRequests' && + typeof params === 'object' && + params !== null && + 'version' in params && + params.version === REQUEST_MARKER.version + ) { + return ok({ marker: REQUEST_MARKER, json: '[]', nextCursor: null }) + } + return undefined + }) + const input = parseAgentRequestAnswerFile({ + ...answerFile(), + ...(kind === 'turn' ? { turnItemId: 'other-turn' } : {}), + ...(kind === 'fence' ? { expectedRuntimeFence: 6 } : {}), + ...(kind === 'marker' ? { expectedRequests: { ...REQUEST_MARKER, revision: 2 } } : {}), + ...(kind === 'option' ? { optionId: 'unoffered' } : {}) + }) + await expect( + answerAgentRequest(client, scope, input, input.clientOperationId) + ).rejects.toMatchObject({ + code: kind === 'option' ? 'invalid_argument' : 'agent_request_unverifiable' + }) + const mutations = call.mock.calls.filter(([method]) => isMutation(method)) + expect(mutations).toHaveLength(1) + expect(mutations[0]?.[1]).toEqual({ ...nativeAnswerParams(input), replayOnly: true }) + } + ) + + it.each([ + 'transport', + 'rpc-miss', + 'other-refusal', + 'malformed-miss', + 'malformed-success', + 'not-replayed' + ])('does not send after an unproven receipt miss: %s', async (kind) => { + const { client, call } = requestFixtureClient((method) => { + if (!isMutation(method)) { + return undefined + } + if (kind === 'transport') { + throw new Error('response lost') + } + if (kind === 'rpc-miss') { + throw new RuntimeRpcFailureError({ + id: 'test', + ok: false, + error: { code: 'agent_session_operation_invalid', message: 'receiptMissing' }, + _meta: { runtimeId: REQUEST_RUNTIME } + }) + } + if (kind === 'malformed-success') { + return ok({ ok: true, replayed: true }) + } + if (kind === 'not-replayed') { + return undefined + } + return ok({ + ok: false, + refusal: { + code: + kind === 'other-refusal' + ? 'agent_session_operation_unknown' + : 'agent_session_operation_invalid', + details: { reason: 'receiptMissing', unexpected: true } + } + }) + }) + const input = parseAgentRequestAnswerFile(answerFile()) + await expect( + answerAgentRequest(client, scope, input, input.clientOperationId) + ).rejects.toMatchObject({ + code: ['rpc-miss', 'malformed-miss'].includes(kind) + ? 'agent_session_operation_invalid' + : 'agent_session_operation_unknown' + }) + expect(call.mock.calls.filter(([method]) => isMutation(method))).toHaveLength(1) + expect( + call.mock.calls.filter(([method]) => method === 'agentSession.currentRequests') + ).toHaveLength(0) + }) + it('retains a definitive permission refusal instead of calling it a timeout', async () => { const { client } = requestFixtureClient((method) => { if (isMutation(method)) { @@ -301,7 +469,7 @@ describe('native answer JSON and admission', () => { expect(call.mock.calls.filter(([method]) => isMutation(method))).toHaveLength(1) }) - it.each(['item', 'choice', 'revision', 'malformed'])( + it.each(['item', 'choice', 'revision', 'malformed', 'retry-item', 'retry-choice'])( 'does not label a mismatched %s receipt accepted', async (kind) => { const { client } = requestFixtureClient((method) => { @@ -313,15 +481,15 @@ describe('native answer JSON and admission', () => { } return ok({ ok: true, - replayed: false, + replayed: kind.startsWith('retry-'), fence: 7, cursor: { epoch: REQUEST_MARKER.epoch, sequence: 2 }, value: { - itemId: kind === 'item' ? 'different-item' : answerFile().itemId, + itemId: kind.endsWith('item') ? 'different-item' : answerFile().itemId, revision: kind === 'revision' ? 0 : 2, resolution: { state: 'resolved', - selectedOptionId: kind === 'choice' ? 'deny' : 'approve', + selectedOptionId: kind.endsWith('choice') ? 'deny' : 'approve', resolvedBy: 'caller', resolvedAt: 100 } @@ -329,7 +497,12 @@ describe('native answer JSON and admission', () => { }) }) await expect( - answerAgentRequest(client, scope, parseAgentRequestAnswerFile(answerFile())) + answerAgentRequest( + client, + scope, + parseAgentRequestAnswerFile(answerFile()), + kind.startsWith('retry-') ? answerFile().clientOperationId : undefined + ) ).rejects.toMatchObject({ code: 'agent_session_operation_unknown' }) } ) diff --git a/src/cli/agents/agent-request-answer.ts b/src/cli/agents/agent-request-answer.ts index a054197f0189..54f4822b26b2 100644 --- a/src/cli/agents/agent-request-answer.ts +++ b/src/cli/agents/agent-request-answer.ts @@ -20,7 +20,10 @@ import type { AgentSessionMutationResult, AgentSessionPromptResult } from '../../shared/agent-session/agent-session-wire' -import { AGENT_SESSION_QUESTION_ANSWERS_RUNTIME_CAPABILITY } from '../../shared/agent-session/capabilities/agent-session-runtime-capabilities' +import { + AGENT_SESSION_QUESTION_ANSWERS_RUNTIME_CAPABILITY, + AGENT_SESSION_RESPONSE_REPLAY_ONLY_RUNTIME_CAPABILITY +} from '../../shared/agent-session/capabilities/agent-session-runtime-capabilities' import { RUNTIME_SOURCE_FENCE_RUNTIME_CAPABILITY } from '../../shared/remote-runtime/protocol/host-runtime-capabilities' import { isAgentJournalResolution } from '../../shared/agent-session/journal/agent-session-journal-schemas' import type { AgentJournalResolution } from '../../shared/agent-session/journal/agent-session-journal-types' @@ -42,8 +45,15 @@ const RefusedAnswer = z.object({ ok: z.literal(false), refusal: z.object({ code: z.string().min(1), details: z.unknown().optional() }) }) +const MissingReceipt = z.object({ + ok: z.literal(false), + refusal: z.object({ + code: z.literal('agent_session_operation_invalid'), + details: z.object({ reason: z.literal('receiptMissing') }).strict() + }) +}) /** - * Submits a pinned answer; retry resubmits the same operation and may execute it for the first time. + * Submits a pinned answer; retry checks its receipt before validating any first execution. * A matching receipt proves acceptance, not provider resumption. */ export async function answerAgentRequest( @@ -101,7 +111,7 @@ export async function answerAgentRequest( ) } } - if (retryOperationId === undefined) { + async function validateCurrentRequest(): Promise { const inventory = await listAgentRequests(client, constrainedScope, runtimeId) const prompt = inventory.requests.find((request) => request.itemId === input.itemId) if ( @@ -135,6 +145,9 @@ export async function answerAgentRequest( ) } } + if (retryOperationId === undefined) { + await validateCurrentRequest() + } const pinStatus = await client.call('status.get') requireSameRuntime(pinStatus, runtimeId) const sourceId = pinStatus.result.hostDescriptor?.installationId @@ -147,6 +160,16 @@ export async function answerAgentRequest( 'This host cannot atomically fence native answers to the inspected runtime. Nothing was sent.' ) } + if ( + retryOperationId !== undefined && + !pinStatus.result.capabilities?.includes(AGENT_SESSION_RESPONSE_REPLAY_ONLY_RUNTIME_CAPABILITY) + ) { + throw new RuntimeClientError( + 'incompatible_runtime', + 'This host cannot safely replay native answer receipts. Update the execution host. Nothing was sent.' + ) + } + const expectedRuntimeSource = { sourceId, runtimeId } const recovery = { clientOperationId: input.clientOperationId, expectedRuntimeId: runtimeId, @@ -154,37 +177,49 @@ export async function answerAgentRequest( workspaceId, resumed: 'unverified' as const } - let response: RuntimeRpcSuccess - try { - response = await client.call( - input.kind === 'approval' - ? 'agentSession.respondToApproval' - : 'agentSession.respondToQuestion', - params, - { expectedRuntimeSource: { sourceId, runtimeId } } - ) - requireSameRuntime(response, runtimeId) - } catch (error) { - if ( - (error instanceof RuntimeRpcFailureError && error.code !== 'internal_error') || - (error instanceof RuntimeClientError && - ['runtime_source_mismatch', 'runtime_source_unverifiable', 'incompatible_runtime'].includes( - error.code - )) - ) { - throw new RuntimeClientError(error.code, 'The execution host refused the native answer.', { - ...recovery, - outcome: error.code === 'agent_session_operation_unknown' ? 'unknown' : 'refused' - }) - } - throw new RuntimeClientError( - 'agent_session_operation_unknown', - 'Native answer outcome is unknown. Do not create a new operation or automatically resend it.', - { - ...recovery, - outcome: 'unknown' + async function sendAnswer(replayOnly: boolean): Promise> { + let response: RuntimeRpcSuccess + try { + response = await client.call( + input.kind === 'approval' + ? 'agentSession.respondToApproval' + : 'agentSession.respondToQuestion', + replayOnly ? { ...params, replayOnly: true } : params, + { expectedRuntimeSource } + ) + requireSameRuntime(response, runtimeId) + } catch (error) { + if ( + (error instanceof RuntimeRpcFailureError && error.code !== 'internal_error') || + (error instanceof RuntimeClientError && + [ + 'runtime_source_mismatch', + 'runtime_source_unverifiable', + 'incompatible_runtime' + ].includes(error.code)) + ) { + throw new RuntimeClientError(error.code, 'The execution host refused the native answer.', { + ...recovery, + outcome: error.code === 'agent_session_operation_unknown' ? 'unknown' : 'refused' + }) } - ) + throw new RuntimeClientError( + 'agent_session_operation_unknown', + 'Native answer outcome is unknown. Do not create a new operation or automatically resend it.', + { + ...recovery, + outcome: 'unknown' + } + ) + } + return response + } + let probingReceipt = retryOperationId !== undefined + let response = await sendAnswer(probingReceipt) + if (probingReceipt && MissingReceipt.safeParse(response.result).success) { + await validateCurrentRequest() + probingReceipt = false + response = await sendAnswer(false) } const refused = RefusedAnswer.safeParse(response.result) if (refused.success) { @@ -200,7 +235,7 @@ export async function answerAgentRequest( ) } const accepted = AcceptedAnswer.safeParse(response.result) - if (!accepted.success) { + if (!accepted.success || (probingReceipt && !accepted.data.replayed)) { throw new RuntimeClientError( 'agent_session_operation_unknown', 'The native answer response is invalid; acceptance is unknown.', diff --git a/src/cli/agents/agent-request-handlers.test.ts b/src/cli/agents/agent-request-handlers.test.ts index dc7d9088173f..d0a01607052d 100644 --- a/src/cli/agents/agent-request-handlers.test.ts +++ b/src/cli/agents/agent-request-handlers.test.ts @@ -7,6 +7,7 @@ import { parseAgentRequestAnswerFile } from './agent-request-answer-file' import type { HandlerContext } from '../dispatch/dispatch' import { RuntimeClient } from '../runtime/client' import { + REQUEST_OPERATION_ID, REQUEST_SESSION, REQUEST_WORKSPACE, answerFile, @@ -80,7 +81,7 @@ describe('public scoped native-request commands', () => { '--request-file', 'answer.json', '--retry', - '33333333-3333-4333-8333-333333333333', + REQUEST_OPERATION_ID, '--json' ] const parsed = parseArgs( @@ -90,7 +91,7 @@ describe('public scoped native-request commands', () => { ) validateCommandAndFlags(AGENT_REQUEST_COMMAND_SPECS, parsed) expect(parsed.commandPath).toEqual(['agent', 'requests', 'answer']) - expect(parsed.flags.get('retry')).toBe('33333333-3333-4333-8333-333333333333') + expect(parsed.flags.get('retry')).toBe(REQUEST_OPERATION_ID) }) it.each(['--yes', '--all', '--force', '--text', '--approve-all'])( diff --git a/src/cli/agents/agent-request-test-fixtures.ts b/src/cli/agents/agent-request-test-fixtures.ts index 265735848608..7a576e97af92 100644 --- a/src/cli/agents/agent-request-test-fixtures.ts +++ b/src/cli/agents/agent-request-test-fixtures.ts @@ -5,8 +5,13 @@ import { vi } from 'vitest' import type { RuntimeRpcSuccess } from '../../shared/remote-runtime/rpc/runtime-rpc-envelope' import type { AgentRequestClient } from './agent-request-inventory' import { AGENT_REQUEST_CLI_CAPABILITIES } from './agent-request-capabilities' +import { AGENT_SESSION_RESPONSE_REPLAY_ONLY_RUNTIME_CAPABILITY } from '../../shared/agent-session/capabilities/agent-session-runtime-capabilities' +import { createStructuredAgentSessionOperationId } from '../../shared/agent-session/lifecycle/operations/structured-agent-session-mutation' import { RUNTIME_SOURCE_FENCE_RUNTIME_CAPABILITY } from '../../shared/remote-runtime/protocol/host-runtime-capabilities' +export const REQUEST_OPERATION_ID = createStructuredAgentSessionOperationId( + () => '33333333-3333-4333-8333-333333333333' +) export const REQUEST_SESSION = 'chat_session_01' export const REQUEST_WORKSPACE = 'repo-id::C:/projects/example' export const REQUEST_RUNTIME = 'runtime-test' @@ -53,7 +58,7 @@ export function answerFile() { kind: 'approval' as const, expectedRuntimeFence: 7, expectedRevision: 1, - clientOperationId: '33333333-3333-4333-8333-333333333333', + clientOperationId: REQUEST_OPERATION_ID, optionId: 'approve' } } @@ -87,7 +92,11 @@ export function requestFixtureClient( if (method === 'status.get') { result = { runtimeId: REQUEST_RUNTIME, - capabilities: [...AGENT_REQUEST_CLI_CAPABILITIES, RUNTIME_SOURCE_FENCE_RUNTIME_CAPABILITY], + capabilities: [ + ...AGENT_REQUEST_CLI_CAPABILITIES, + RUNTIME_SOURCE_FENCE_RUNTIME_CAPABILITY, + AGENT_SESSION_RESPONSE_REPLAY_ONLY_RUNTIME_CAPABILITY + ], hostDescriptor: { installationId: REQUEST_SOURCE } } } else if (method === 'session.tabs.list') { diff --git a/src/cli/discovery/command-scoped-flag-help.ts b/src/cli/discovery/command-scoped-flag-help.ts index 14f9d23c7b73..e3c6fa9b2a4c 100644 --- a/src/cli/discovery/command-scoped-flag-help.ts +++ b/src/cli/discovery/command-scoped-flag-help.ts @@ -42,7 +42,7 @@ const COMMAND_SCOPED_FLAG_HELP: Record> = { ...AGENT_REQUEST_SCOPE_HELP, 'request-file': '--request-file UTF-8 JSON file containing the inspected request and answer', - retry: '--retry Resubmit the same operation ID and answer' + retry: '--retry Recover the original answer using its operation ID' }, 'agent show': { id: AGENT_ID_FLAG_HELP }, 'agent read': { diff --git a/src/cli/specs/agent-requests.ts b/src/cli/specs/agent-requests.ts index 297960e6cff6..bee080ba019d 100644 --- a/src/cli/specs/agent-requests.ts +++ b/src/cli/specs/agent-requests.ts @@ -29,13 +29,13 @@ export const AGENT_REQUEST_COMMAND_SPECS: CommandSpec[] = [ path: ['agent', 'requests', 'answer'], summary: 'Answer one inspected native request using an exact JSON file', usage: - 'orca agent requests answer --worktree --session --request-file [--turn ] [--retry ] [--json]', + 'orca agent requests answer --worktree --session --request-file [--turn ] [--retry ] [--json]', allowedFlags: [...GLOBAL_FLAGS, 'worktree', 'session', 'turn', 'request-file', 'retry'], notes: [ ...NOTES, - 'The UTF-8 JSON file must include workspaceId, sessionId, expectedRuntimeId, expectedRequests (the complete list marker), itemId, kind, expectedRuntimeFence, expectedRevision, and a caller-chosen clientOperationId UUID. It selects one optionId or the exact structured question answers. Optional turnItemId restricts ownership.', + 'The UTF-8 JSON file must include workspaceId, sessionId, expectedRuntimeId, expectedRequests (the complete list marker), itemId, kind, expectedRuntimeFence, expectedRevision, and a clientOperationId made from a 13-digit Unix timestamp in milliseconds, a hyphen, and 32 lowercase hex digits. It selects one optionId or the exact structured question answers. Optional turnItemId restricts ownership.', 'An initial answer requires the inspected runtime, workspace, session, fence, marker and item revision to remain current. The host finally enforces its existing lease, item revision and current provider ownership rules; newer hosts do not enforce the envelope fence themselves.', - '--retry must equal the file UUID and resends only that same operation and payload once, allowing the host to replay its receipt even when the prompt is no longer pending. Never replace an unknown operation with a fresh UUID or retry automatically.', + '--retry takes the original file’s clientOperationId. The host first looks up its receipt. If the host confirms the receipt is absent, the CLI checks the current request and turn before submitting the original answer. Retrying requires a host that supports receipt lookup.', 'A session no longer identifiable in this explicit workspace is refused even for replay. Older hosts lacking the native current-request contract are refused without mutation.' ] } diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-prompt-receipt-replay.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-prompt-receipt-replay.test.ts new file mode 100644 index 000000000000..55583cc923eb --- /dev/null +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-prompt-receipt-replay.test.ts @@ -0,0 +1,120 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../../shared/agent-session/journal/agent-session-journal-types' +import { + HOST_TEST_SESSION as SESSION, + hostTestOperationId +} from './structured-agent-session-host-test-data.test-fixture' +import { + createQueuedMessageTestRig, + QUEUED_RIG_CALLER as CALLER, + type QueuedMessageTestRig +} from './structured-agent-session-queued-message-rig.test-fixture' + +let rig: QueuedMessageTestRig + +afterEach(() => rig.dispose()) + +it.each(['approval', 'question'] as const)( + 'probes %s receipts without executing missing answers and replays after restart without opening', + async (kind) => { + rig = await createQueuedMessageTestRig() + await rig.workingSend() + const journal = rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal + const prompt = await journal.appendItem( + { provider: 'orca', clientMessageId: 'prompt' }, + { + ...(kind === 'approval' + ? { kind, title: 'Approve?', detail: null } + : { kind, question: 'Choose?' }), + options: [{ id: 'yes', label: 'Yes' }], + resolution: { + state: 'pending', + selectedOptionId: null, + resolvedBy: null, + resolvedAt: null + } + }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + const fields = { itemId: prompt.itemId, expectedRevision: prompt.revision, optionId: 'yes' } + const params = { + ...fields, + kind, + envelope: rig.envelope(fields, `agentSession.respondTo:${kind}`, hostTestOperationId()) + } + const answer = vi.spyOn(rig.host.collaboratorsForTests().deps.adapter, 'answerPrompt') + const before = await journal.reads.cursor() + expect(await rig.host.respondToPrompt(CALLER, { ...params, replayOnly: true })).toMatchObject({ + ok: false, + refusal: { code: 'agent_session_operation_invalid', details: { reason: 'receiptMissing' } } + }) + expect(await journal.reads.cursor()).toEqual(before) + expect( + await rig.store.readCommandReceipt( + { kind: 'caller', callerKey: CALLER.callerKey }, + params.envelope.clientOperationId + ) + ).toEqual({ verdict: 'absent' }) + expect(answer).not.toHaveBeenCalled() + + const accepted = await rig.host.respondToPrompt(CALLER, params) + expect(accepted).toMatchObject({ ok: true, replayed: false }) + expect(answer).toHaveBeenCalledTimes(1) + if (!accepted.ok) { + throw new Error('answer was refused') + } + const acceptedValue = accepted.value + rig.crashRestartHostProcess() + expect(rig.host.collaboratorsForTests().sessions.size).toBe(0) + const starts = rig.starts.mock.calls.length + expect(await rig.host.respondToPrompt(CALLER, { ...params, replayOnly: true })).toMatchObject({ + ok: true, + replayed: true, + value: acceptedValue + }) + expect(rig.host.collaboratorsForTests().sessions.size).toBe(0) + expect(rig.starts).toHaveBeenCalledTimes(starts) + expect(answer).toHaveBeenCalledTimes(1) + expect(await journal.reads.cursor()).toEqual(accepted.cursor) + expect( + await rig.host.respondToPrompt({ callerKey: 'other' }, { ...params, replayOnly: true }) + ).toMatchObject({ + ok: false, + refusal: { details: { reason: 'receiptMissing' } } + }) + const changed = { ...fields, optionId: 'no' } + expect( + await rig.host.respondToPrompt(CALLER, { + ...params, + ...changed, + replayOnly: true, + envelope: rig.envelope( + changed, + `agentSession.respondTo:${kind}`, + params.envelope.clientOperationId + ) + }) + ).toMatchObject({ ok: false, refusal: { code: 'agent_session_operation_conflict' } }) + vi.spyOn( + rig.host.collaboratorsForTests().deps.journalDatabase.readers, + 'point' + ).mockRejectedValueOnce(new Error('reader closed')) + expect(await rig.host.respondToPrompt(CALLER, { ...params, replayOnly: true })).toMatchObject({ + ok: false, + refusal: { code: 'agent_session_operation_unknown' } + }) + vi.spyOn(rig.store, 'readCommandReceipt').mockRejectedValueOnce(new Error('reader closed')) + expect(await rig.host.respondToPrompt(CALLER, { ...params, replayOnly: true })).toMatchObject({ + ok: false, + refusal: { code: 'agent_session_operation_unknown' } + }) + expect(rig.host.collaboratorsForTests().sessions.size).toBe(0) + expect(answer).toHaveBeenCalledTimes(1) + expect(await rig.host.respondToPrompt(CALLER, params)).toMatchObject({ + ok: true, + replayed: true, + value: acceptedValue + }) + expect(answer).toHaveBeenCalledTimes(1) + } +) diff --git a/src/main/native-chat/agent-session-wire/operations/structured-agent-session-command-admission.ts b/src/main/native-chat/agent-session-wire/operations/structured-agent-session-command-admission.ts index 758e8a176bdd..103849a92f36 100644 --- a/src/main/native-chat/agent-session-wire/operations/structured-agent-session-command-admission.ts +++ b/src/main/native-chat/agent-session-wire/operations/structured-agent-session-command-admission.ts @@ -68,6 +68,15 @@ export async function admitCommandReceiptMutation( if (read.verdict !== 'absent') { return answerCommandReceipt(request, hostFingerprint, read) } + if (commandReceipt.replayOnly) { + return refuseAgentSessionMutation( + agentSessionLedgerRefusal(envelope, { + decision: 'refused', + code: 'agent_session_operation_invalid', + details: { reason: 'receiptMissing' } + }) + ) + } store.requireWritableRecord(envelope.sessionId) const prepared = await request.prepareSession?.( 'admit', @@ -156,6 +165,24 @@ async function answerCommandReceipt( if (!record) { return unknown(request) } + const receiptOnly = plan.commandReceipt?.replayOnly + if (receiptOnly) { + const value = receiptOnly(receipt.result) + if (value === null || !request.readReceiptCursor) { + return unknown(request) + } + try { + return { + ok: true, + replayed: true, + fence: record.currentFence, + cursor: await request.readReceiptCursor(), + value + } + } catch { + return unknown(request) + } + } const prepared = await request.prepareSession?.('replay', record) if (prepared && !prepared.ok) { return prepared diff --git a/src/main/native-chat/agent-session-wire/operations/structured-agent-session-mutation-admission.ts b/src/main/native-chat/agent-session-wire/operations/structured-agent-session-mutation-admission.ts index ec481098ee46..01a239bff921 100644 --- a/src/main/native-chat/agent-session-wire/operations/structured-agent-session-mutation-admission.ts +++ b/src/main/native-chat/agent-session-wire/operations/structured-agent-session-mutation-admission.ts @@ -1,3 +1,4 @@ +import type { AgentJournalCursor } from '../../../../shared/agent-session/journal/agent-session-journal-identity' import type { JournalWorkReader } from '../../agent-session-journal/journal-work-read' import type { AgentSessionConversationView } from '../../../../shared/agent-session/lifecycle/leases/agent-session-conversation-view' // Validate fingerprints centrally. Prepare ledger replays without admitting writes; first runs @@ -73,6 +74,7 @@ export type AgentSessionMutationRequest = { plan: MutationPlan /** Read after preparation; absent if no conversation is held. */ journal: () => AgentSessionJournal | undefined + readReceiptCursor?: () => Promise currentWork?: () => Promise readWork?: JournalWorkReader /** Prepare between ledger evaluation and lease admission; return any terminal refusal. */ diff --git a/src/main/native-chat/agent-session-wire/operations/structured-agent-session-mutation-context.ts b/src/main/native-chat/agent-session-wire/operations/structured-agent-session-mutation-context.ts index f3faca5498bb..56ec964cec1c 100644 --- a/src/main/native-chat/agent-session-wire/operations/structured-agent-session-mutation-context.ts +++ b/src/main/native-chat/agent-session-wire/operations/structured-agent-session-mutation-context.ts @@ -99,6 +99,16 @@ export function runStructuredAgentSessionMutation( envelope, plan, journal: () => context.sessions.get(envelope.sessionId)?.journal, + readReceiptCursor: async () => { + const metadata = await context.deps.journalDatabase.readers.point({ + sessionId: envelope.sessionId, + operation: { kind: 'metadata' } + }) + if (metadata.kind !== 'metadata') { + throw new Error('journal reader returned no metadata') + } + return metadata.cursor + }, currentWork: () => hostStructuredAgentSessionCurrentWork( { store: context.deps.store, sessions: context.sessions }, diff --git a/src/main/native-chat/agent-session-wire/operations/structured-agent-session-mutation-plans.ts b/src/main/native-chat/agent-session-wire/operations/structured-agent-session-mutation-plans.ts index aec706668537..2a7500b40fd3 100644 --- a/src/main/native-chat/agent-session-wire/operations/structured-agent-session-mutation-plans.ts +++ b/src/main/native-chat/agent-session-wire/operations/structured-agent-session-mutation-plans.ts @@ -92,6 +92,8 @@ export type MutationPlan = { /** Insert acceptance with its effect, if absent. */ export type MutationCommandReceipt = { binding: JournalReceiptRowBinding + /** Return only this durable result without opening or recovering the conversation. */ + replayOnly?: (receipt: CommandReceiptResult) => TValue | null /** Resolve inside the effect transaction; draft writes have no journal row. */ result: (row: JournalRow | undefined) => CommandReceiptResult /** Commit a standalone receipt before answering a row-free result; null records nothing. */ diff --git a/src/main/native-chat/agent-session-wire/operations/structured-agent-session-prompt-plan.ts b/src/main/native-chat/agent-session-wire/operations/structured-agent-session-prompt-plan.ts index 6b5e82fbcc4c..9f4ecb7bc6ac 100644 --- a/src/main/native-chat/agent-session-wire/operations/structured-agent-session-prompt-plan.ts +++ b/src/main/native-chat/agent-session-wire/operations/structured-agent-session-prompt-plan.ts @@ -24,6 +24,7 @@ export function promptPlan( }, // Retain the resolved or previously recorded prompt answer in the receipt. commandReceipt: { + ...(params.replayOnly ? { replayOnly: acceptedPromptAnswer } : {}), binding: { at: 'last', kinds: ['item'], answer: 'prompt-answer' }, result: (row) => promptAnswerReceipt(promptRowAnswer(row)), unwritten: (value) => promptAnswerReceipt(value) diff --git a/src/main/native-chat/agent-session-wire/operations/structured-agent-session-turns-prompt.ts b/src/main/native-chat/agent-session-wire/operations/structured-agent-session-turns-prompt.ts index 23c385052311..07d0534d1426 100644 --- a/src/main/native-chat/agent-session-wire/operations/structured-agent-session-turns-prompt.ts +++ b/src/main/native-chat/agent-session-wire/operations/structured-agent-session-turns-prompt.ts @@ -31,6 +31,7 @@ import { import type { AgentSessionTurnContext, TurnOutcome } from './structured-agent-session-turns' export type AgentSessionPromptRequest = { + replayOnly?: true itemId: string expectedRevision: number kind: 'approval' | 'question' diff --git a/src/shared/agent-session/capabilities/agent-session-runtime-capabilities.ts b/src/shared/agent-session/capabilities/agent-session-runtime-capabilities.ts index 55bda175dbf8..d62d3c350787 100644 --- a/src/shared/agent-session/capabilities/agent-session-runtime-capabilities.ts +++ b/src/shared/agent-session/capabilities/agent-session-runtime-capabilities.ts @@ -110,6 +110,8 @@ export const AGENT_SESSION_BACKGROUND_TASK_STOP_CAPABILITY = // Question-answer params are strict: older hosts need packed optionId instead of structured answers. export const AGENT_SESSION_QUESTION_ANSWERS_RUNTIME_CAPABILITY = 'agent-session.question-answers.v1' as const +export const AGENT_SESSION_RESPONSE_REPLAY_ONLY_RUNTIME_CAPABILITY = + 'agent-session.response-replay-only.v1' as const // Paired attachments belong on the server; refuse unsupported servers instead of passing local machine paths. export const AGENT_SESSION_ATTACHMENTS_RUNTIME_CAPABILITY = 'agent-session.attachments.v1' as const // Why: hosts before this advertise attachments.v1 but refuse the upload methods from a phone. @@ -195,6 +197,7 @@ export const AGENT_SESSION_RUNTIME_CAPABILITIES = /* @__PURE__ */ (() => AGENT_SESSION_SEND_RECORDED_RUNTIME_CAPABILITY, AGENT_SESSION_BACKGROUND_TASK_STOP_CAPABILITY, AGENT_SESSION_QUESTION_ANSWERS_RUNTIME_CAPABILITY, + AGENT_SESSION_RESPONSE_REPLAY_ONLY_RUNTIME_CAPABILITY, AGENT_SESSION_ATTACHMENTS_RUNTIME_CAPABILITY, AGENT_SESSION_PHONE_ATTACHMENTS_RUNTIME_CAPABILITY, AGENT_SESSION_PHONE_THREAD_GOAL_RUNTIME_CAPABILITY, diff --git a/src/shared/agent-session/failures/agent-session-refusal-details.ts b/src/shared/agent-session/failures/agent-session-refusal-details.ts index b421c2fce9dc..ad0e9a119fa3 100644 --- a/src/shared/agent-session/failures/agent-session-refusal-details.ts +++ b/src/shared/agent-session/failures/agent-session-refusal-details.ts @@ -32,6 +32,7 @@ export const AGENT_SESSION_REFUSAL_REASONS = { // The request 'requestMalformed', 'operationIdInvalid', + 'receiptMissing', 'messageIdReused', 'operationRefusedEarlier', 'journalWriteFailed', diff --git a/src/shared/agent-session/failures/agent-session-refusal-reason-words.ts b/src/shared/agent-session/failures/agent-session-refusal-reason-words.ts index 1e541ee34842..668057220880 100644 --- a/src/shared/agent-session/failures/agent-session-refusal-reason-words.ts +++ b/src/shared/agent-session/failures/agent-session-refusal-reason-words.ts @@ -69,6 +69,7 @@ const REASON_WORDS = { agent_session_operation_invalid: { requestMalformed: codeWords('hostFinding'), operationIdInvalid: codeWords('hostFinding'), + receiptMissing: codeWords('hostFinding'), messageIdReused: codeWords('hostFinding'), // Settled under that id, so the control's retry goes out under a new one. operationRefusedEarlier: codeWords('retry'), diff --git a/src/shared/rpc-contract/structured-agent-session/structured-agent-session-params.ts b/src/shared/rpc-contract/structured-agent-session/structured-agent-session-params.ts index f3d8b43811b4..9a2a3ce93a12 100644 --- a/src/shared/rpc-contract/structured-agent-session/structured-agent-session-params.ts +++ b/src/shared/rpc-contract/structured-agent-session/structured-agent-session-params.ts @@ -173,6 +173,7 @@ export const QueuedMessagesResumeParams = z.object({ envelope: MutationEnvelope export const RespondParams = z .object({ envelope: MutationEnvelope, + replayOnly: z.literal(true).optional(), itemId: Identifier('Invalid item id'), /** Compare-and-set: the revision the client had on screen. */ expectedRevision: z.number().int().positive(), diff --git a/src/shared/rpc-contract/structured-agent-session/structured-agent-session-question-params.ts b/src/shared/rpc-contract/structured-agent-session/structured-agent-session-question-params.ts index 698b0f2e6905..3625387c2daa 100644 --- a/src/shared/rpc-contract/structured-agent-session/structured-agent-session-question-params.ts +++ b/src/shared/rpc-contract/structured-agent-session/structured-agent-session-question-params.ts @@ -36,6 +36,7 @@ const QuestionAnswer = z export const RespondToQuestionParams = z .object({ envelope: MutationEnvelope, + replayOnly: z.literal(true).optional(), itemId: Identifier('Invalid item id'), expectedRevision: z.number().int().positive(), /** An answer packed into one id, from clients that predate `answers`. */