Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
137 changes: 137 additions & 0 deletions docs/readme/agent-requests-cli.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
# 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:<workspaceId> --session <sessionId> --json
orca agent requests get --worktree id:<workspaceId> --session <sessionId> --item <itemId> --json
orca agent requests answer --worktree id:<workspaceId> --session <sessionId> --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 <turnItemId>` 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 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
{
"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": "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
{
"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 operation ID:

```text
orca agent requests answer --worktree id:<workspaceId> --session <sessionId> --request-file answer.json --retry <same-operationId> --json
```

`--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.
118 changes: 118 additions & 0 deletions src/cli/agents/agent-request-answer-file.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof fs>()
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'
})
})
})
})
95 changes: 95 additions & 0 deletions src/cli/agents/agent-request-answer-file.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { TextDecoder } from 'node:util'
import { z } from 'zod'
import { RuntimeClientError } from '../runtime/connection/types'
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({
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().refine((id) => parseAgentSessionOperationTimestamp(id) !== null),
turnItemId: z.string().min(1).optional(),
optionId: z.string().optional(),
answers: z.unknown().optional()
})
.strict()
export type AgentRequestAnswerFile = z.infer<typeof AnswerFile>

/** Loads size-checked JSON using strict UTF-8, allowing one leading BOM and rejecting invalid bytes. */
export async function readAgentRequestAnswerFile(path: string): Promise<AgentRequestAnswerFile> {
try {
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 {
throw new RuntimeClientError(
'invalid_argument',
'The request file is not a valid bounded native answer JSON file.'
)
}
}

/** Validates identity fields, matching session IDs and the native answer schema before submission. */
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
}

/** Fingerprints native answer fields while preserving question IDs, choices and typed text. */
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
})
}
}
}
Loading