mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
feat(cli): list and read agents by their Orca session ID with orca agent list/show/read
This commit is contained in:
@@ -240,6 +240,19 @@ By default, `terminal read` returns the accumulated output stream with terminal
|
||||
|
||||
For long output, use cursor reads. Save `nextCursor` from one stream read, then pass it back with `--cursor` to fetch only new output.
|
||||
|
||||
## Agents by ID
|
||||
|
||||
```bash
|
||||
orca agent list --json
|
||||
orca agent show orca_session_id:claude_1234 --json
|
||||
orca agent read orca_session_id:claude_1234 --limit 10
|
||||
orca agent read orca_session_id:claude_1234 --cursor <cursor> --json
|
||||
```
|
||||
|
||||
Every agent, chat or terminal, has an Orca session ID (`orca_session_id:<agent>_<uuid>`), what Copy Orca Session ID copies on a chat and Copy Agent ID on a terminal. `agent list` lists the agents open in this host's workspaces with their IDs; a terminal agent shows none until it first reports to Orca. A chat keeps its ID across `/clear`; a terminal agent gets a new one. IDs belong to the host that runs the agent: agents on other hosts are not listed, and the output names those hosts with the `--environment` that lists them.
|
||||
|
||||
`agent read` reads the conversation, not a screen: a chat's history, or a terminal agent's own transcript. The agent need not be running and reading never starts it. A terminal agent can be read while Orca knows where its transcript is (it is open, or asleep in a workspace). Pass the printed `cursor` back with `--cursor` to read only what came after. To message an agent, use `orca terminal send` or `orca orchestration send`.
|
||||
|
||||
## Chats
|
||||
|
||||
```bash
|
||||
|
||||
@@ -68,6 +68,16 @@ ORCA terminal send --terminal <handle> --text "<task brief>" --enter --json
|
||||
|
||||
If a launch reply is lost, use the returned `operationId` to re-issue the exact same command from the same directory against the same execution host with `--retry-launch <operationId>`. Keep that ID on every retry: the host replays the accepted launch instead of starting another agent or submitting the brief twice. Do not retry as a fresh launch. If replay says the outcome is unknown or expired, or an older host gives no replay ID, inspect the workspace and agent without sending input before deciding whether another launch is needed. A host that cannot safely carry prompts or honor background/focus requests is refused before launch; update Orca on that execution host.
|
||||
|
||||
## Agents by ID
|
||||
|
||||
Every agent, chat or terminal, has an Orca session ID (`orca_session_id:<agent>_<uuid>`; what Copy Orca Session ID copies on a chat and Copy Agent ID on a terminal). Use it to find and read agents:
|
||||
|
||||
- `ORCA agent list --json` lists the agents open in this host's workspaces, with `orcaSessionId`, `kind` (chat or terminal), state, workspace and last reply. A terminal agent has no ID until it first reports to Orca. Agents on other hosts are not listed; the output names those hosts and the `--environment` to use.
|
||||
- `ORCA agent show <id> --json` shows where one agent is open (none if closed, two if resumed in two panes).
|
||||
- `ORCA agent read <id> --json` reads what the agent said: a chat's history or a terminal agent's transcript, never its screen. It needs no running agent and never starts one. Pass the returned `cursor` with `--cursor` to read only newer entries. A terminal agent is readable while Orca knows its transcript (open, or asleep in a workspace).
|
||||
|
||||
A chat keeps its ID across `/clear`; a terminal agent gets a new one. A provider's own conversation id or a `term_…` handle is refused with the ID to use. To message an agent, use `terminal send` or `orchestration send` as below.
|
||||
|
||||
## Worktrees
|
||||
|
||||
An Orca worktree is Orca's tracked view of a repo checkout, its metadata, terminals, browser tabs, and UI state.
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { RuntimeClient } from '../runtime/client'
|
||||
import { RuntimeClientError } from '../runtime/types'
|
||||
import { AGENT_CONVERSATION_HANDLERS } from './agent-conversations'
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('tells the user to update a host that predates agent commands', async () => {
|
||||
const client = new RuntimeClient('/tmp/orca-agent-test', 60_000, null, null)
|
||||
vi.spyOn(client, 'call').mockRejectedValue(
|
||||
new RuntimeClientError('method_not_found', 'Unknown method: agent.read')
|
||||
)
|
||||
|
||||
await expect(
|
||||
AGENT_CONVERSATION_HANDLERS['agent read']({
|
||||
flags: new Map([['id', 'orca_session_id:claude_5688af50_12a0_4b0b_9a4a_098d87fe1e68']]),
|
||||
client,
|
||||
cwd: '/tmp/worktree',
|
||||
json: true
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'incompatible_runtime' })
|
||||
})
|
||||
@@ -0,0 +1,166 @@
|
||||
import type { CommandHandler } from '../dispatch/dispatch'
|
||||
import {
|
||||
getOptionalPositiveIntegerFlag,
|
||||
getOptionalStringFlag,
|
||||
getRequiredStringFlag
|
||||
} from '../arguments/flags'
|
||||
import { printResult } from '../output/command-result-output'
|
||||
import { RuntimeClientError } from '../runtime/types'
|
||||
import type { RuntimeClient } from '../runtime/client'
|
||||
import { getOptionalWorktreeSelector } from '../workspace-selection/workspace-selector'
|
||||
import {
|
||||
annotateOmittedHostScope,
|
||||
formatListingHostScope,
|
||||
type WithAnnotatedHostScope
|
||||
} from '../hosts/omitted-host-scope-selectors'
|
||||
import {
|
||||
AGENT_READ_MAX_LIMIT,
|
||||
type AgentConversationRow,
|
||||
type AgentListResult,
|
||||
type AgentReadResult,
|
||||
type AgentShowResult
|
||||
} from '../../shared/agent-conversations/agent-conversation-contracts'
|
||||
import { AGENT_STATUS_STATES } from '../../shared/agent-status/contracts/agent-status-types'
|
||||
import type { RuntimeWorktreeRecord } from '../../shared/runtime-worktree-contracts'
|
||||
import { ORCA_SESSION_ADDRESS_PREFIX } from '../../shared/orca-session-address-prefix'
|
||||
import {
|
||||
AGENT_SESSION_UNATTACHED_REFUSAL_CODE,
|
||||
isUnattachedAgentSessionReadRefusal
|
||||
} from '../../shared/agent-session/failures/structured-agent-session-read-refusal'
|
||||
|
||||
export const AGENT_CONVERSATION_HANDLERS: Record<string, CommandHandler> = {
|
||||
'agent list': async ({ flags, client, cwd, json }) => {
|
||||
const state = getOptionalStringFlag(flags, 'state')
|
||||
if (state !== undefined && !AGENT_STATUS_STATES.some((known) => known === state)) {
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
`--state must be one of: ${AGENT_STATUS_STATES.join(', ')}.`
|
||||
)
|
||||
}
|
||||
const selector = await getOptionalWorktreeSelector(flags, 'worktree', cwd, client)
|
||||
const worktreeId = selector
|
||||
? (
|
||||
await client.call<{ worktree: RuntimeWorktreeRecord }>('worktree.show', {
|
||||
worktree: selector,
|
||||
matchFolderWorkspaces: true
|
||||
})
|
||||
).result.worktree.id
|
||||
: undefined
|
||||
const result = await callAgentMethod<WithAnnotatedHostScope<AgentListResult>>(
|
||||
client,
|
||||
'agent.list',
|
||||
{ ...(worktreeId ? { worktreeId } : {}), ...(state ? { state } : {}) }
|
||||
)
|
||||
await annotateOmittedHostScope(result.result)
|
||||
printResult(result, json, formatAgentList)
|
||||
},
|
||||
'agent show': async ({ flags, client, json }) => {
|
||||
const result = await callAgentMethod<AgentShowResult>(client, 'agent.show', {
|
||||
id: getRequiredStringFlag(flags, 'id')
|
||||
})
|
||||
printResult(result, json, formatAgentShow)
|
||||
},
|
||||
'agent read': async ({ flags, client, json }) => {
|
||||
const limit = getOptionalPositiveIntegerFlag(flags, 'limit')
|
||||
if (limit !== undefined && limit > AGENT_READ_MAX_LIMIT) {
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
`--limit can be at most ${AGENT_READ_MAX_LIMIT}.`
|
||||
)
|
||||
}
|
||||
const cursor = getOptionalStringFlag(flags, 'cursor')
|
||||
const result = await callAgentMethod<AgentReadResult>(client, 'agent.read', {
|
||||
id: getRequiredStringFlag(flags, 'id'),
|
||||
...(limit !== undefined ? { limit } : {}),
|
||||
...(cursor ? { cursor } : {})
|
||||
})
|
||||
printResult(result, json, formatAgentRead)
|
||||
}
|
||||
}
|
||||
|
||||
async function callAgentMethod<TResult>(client: RuntimeClient, method: string, params: unknown) {
|
||||
return client.call<TResult>(method, params).catch((error: unknown) => {
|
||||
if (!(error instanceof RuntimeClientError)) {
|
||||
throw error
|
||||
}
|
||||
if (error.code === 'method_not_found') {
|
||||
throw new RuntimeClientError(
|
||||
'incompatible_runtime',
|
||||
'This Orca host has no agent commands yet. Update Orca on that host to use agent commands.'
|
||||
)
|
||||
}
|
||||
// Chat reads answer with bare wire codes; say what they mean.
|
||||
if ([error.code, error.message].includes('structured_agent_session_unsupported')) {
|
||||
throw new RuntimeClientError(
|
||||
'incompatible_runtime',
|
||||
"This Orca host can't read that chat from the CLI. Update Orca on that host, or check that it has chats turned on."
|
||||
)
|
||||
}
|
||||
if (isUnattachedAgentSessionReadRefusal(error)) {
|
||||
throw new RuntimeClientError(
|
||||
AGENT_SESSION_UNATTACHED_REFUSAL_CODE,
|
||||
'That chat is opening or closing right now. Try again in a moment.'
|
||||
)
|
||||
}
|
||||
throw error
|
||||
})
|
||||
}
|
||||
|
||||
function address(row: { orcaSessionId: string | null }): string {
|
||||
return row.orcaSessionId
|
||||
? `${ORCA_SESSION_ADDRESS_PREFIX}${row.orcaSessionId}`
|
||||
: 'none yet (Orca names a terminal agent after its first report)'
|
||||
}
|
||||
|
||||
function formatAgentRow(row: AgentConversationRow): string {
|
||||
return [
|
||||
`${row.workspace} · ${row.agent ?? 'agent'} ${row.kind} · ${row.state}`,
|
||||
` id: ${address(row)}`,
|
||||
...(row.title ? [` title: ${row.title}`] : []),
|
||||
...(row.lastAssistantMessage
|
||||
? [` last reply: ${row.lastAssistantMessage.replace(/\s+/g, ' ').slice(0, 200)}`]
|
||||
: [])
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function formatAgentList(result: WithAnnotatedHostScope<AgentListResult>): string {
|
||||
const scope = result.hostScope
|
||||
const lines = [
|
||||
result.agents.length === 0 ? 'No open agents.' : result.agents.map(formatAgentRow).join('\n\n')
|
||||
]
|
||||
// Agents on hosts this one does not list are reached by running there or with --environment.
|
||||
if (!scope || scope.omittedHostIds.length > 0) {
|
||||
lines.push('', formatListingHostScope(scope))
|
||||
}
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
function formatAgentShow(result: AgentShowResult): string {
|
||||
const id = `${ORCA_SESSION_ADDRESS_PREFIX}${result.orcaSessionId}`
|
||||
if (result.places.length === 0) {
|
||||
return `Agent ${id} (${result.kind}) isn't open in any workspace right now. Read what it said with \`orca agent read ${id}\`.`
|
||||
}
|
||||
return result.places.map(formatAgentRow).join('\n\n')
|
||||
}
|
||||
|
||||
function formatAgentRead(result: AgentReadResult): string {
|
||||
const lines = result.entries.map((entry) => {
|
||||
if (entry.kind === 'message') {
|
||||
return `${entry.role}: ${entry.text}`
|
||||
}
|
||||
if (entry.kind === 'error') {
|
||||
return `[error] ${entry.text}`
|
||||
}
|
||||
if (entry.kind === 'tool') {
|
||||
return `[tool ${entry.name}${entry.state ? `: ${entry.state}` : ''}]`
|
||||
}
|
||||
return `[${entry.kind}${entry.pending ? ', waiting for an answer' : ''}] ${entry.text}`
|
||||
})
|
||||
if (lines.length === 0) {
|
||||
lines.push('Nothing new.')
|
||||
}
|
||||
if (result.cursor) {
|
||||
lines.push('', `More later: --cursor ${result.cursor}`)
|
||||
}
|
||||
return lines.join('\n')
|
||||
}
|
||||
@@ -4,7 +4,19 @@ import { COMPUTER_WAIT_DEFAULT_TIMEOUT_MS } from '../../shared/computer-wait-tim
|
||||
const FILE_OPEN_FOCUS_HELP =
|
||||
"--focus Bring the user to the file (switches Orca's window to its worktree)"
|
||||
|
||||
const AGENT_ID_FLAG_HELP =
|
||||
"--id <id> The agent's orca_session_id: ID; also accepted positionally"
|
||||
|
||||
const COMMAND_SCOPED_FLAG_HELP: Record<string, Record<string, string>> = {
|
||||
'agent list': {
|
||||
state: '--state <state> Only agents in this state: working, blocked, waiting or done'
|
||||
},
|
||||
'agent show': { id: AGENT_ID_FLAG_HELP },
|
||||
'agent read': {
|
||||
id: AGENT_ID_FLAG_HELP,
|
||||
limit: '--limit <n> Entries to return (default 20, at most 100)',
|
||||
cursor: '--cursor <cursor> Cursor from a previous agent read; returns only what came after'
|
||||
},
|
||||
'extension reload': {
|
||||
'extension-id':
|
||||
'--extension-id <id> Installed unpacked extension ID; also accepted positionally',
|
||||
|
||||
@@ -129,6 +129,9 @@ export const ROOT_HELP_TEXT_PRIMARY = [
|
||||
'',
|
||||
'Agents:',
|
||||
' agent launch Start an agent in a worktree, as a chat or terminal per your settings',
|
||||
' agent list List open agents, chats and terminals, with their Orca session IDs',
|
||||
' agent show Show where an agent is open, by its Orca session ID',
|
||||
' agent read Read what an agent said, by its Orca session ID',
|
||||
' agent hooks Inspect and toggle Orca agent lifecycle hooks',
|
||||
' claude-teams Start Claude Code Agent Teams in the current Orca terminal',
|
||||
'',
|
||||
|
||||
@@ -210,6 +210,11 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [
|
||||
keys: ['agent launch'],
|
||||
load: async () => (await import('../agents/agent-launch.js')).AGENT_LAUNCH_HANDLERS
|
||||
},
|
||||
{
|
||||
name: 'agent-conversations',
|
||||
keys: ['agent list', 'agent show', 'agent read'],
|
||||
load: async () => (await import('../agents/agent-conversations.js')).AGENT_CONVERSATION_HANDLERS
|
||||
},
|
||||
{
|
||||
name: 'chat',
|
||||
keys: ['chat rename'],
|
||||
|
||||
@@ -5,7 +5,15 @@ import type {
|
||||
} from '../../shared/runtime-rpc-envelope'
|
||||
import { RemoteRuntimeClientError } from '../../shared/remote-runtime/remote-runtime-client-error'
|
||||
import { AGENT_LAUNCH_RUNTIME_CAPABILITY } from '../../shared/agent-launch/contracts/agent-launch-runtime-capability'
|
||||
import { AGENT_SESSION_RENAME_ONLY_CLIENT_CAPABILITY } from '../../shared/agent-session/structured-agent-session-surface-capabilities'
|
||||
import {
|
||||
AGENT_SESSION_RENAME_ONLY_CLIENT_CAPABILITY,
|
||||
PI_STRUCTURED_DIALOGS_RUNTIME_CAPABILITY,
|
||||
STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY
|
||||
} from '../../shared/agent-session/structured-agent-session-surface-capabilities'
|
||||
import {
|
||||
CLAUDE_STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY,
|
||||
STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY
|
||||
} from '../../shared/agent-session/agent-session-runtime-capabilities'
|
||||
import { REPO_SEARCH_QUALIFIED_REFS_RUNTIME_CAPABILITY } from '../../shared/worktree-runtime-capabilities'
|
||||
import { CLI_AGENT_CALLER_CLIENT_CAPABILITY } from '../../shared/remote-runtime/cli-agent-caller-capability'
|
||||
import { sendRemoteRuntimeRequestOnSocket } from '../../shared/remote-runtime/requests/remote-runtime-request-socket'
|
||||
@@ -20,6 +28,20 @@ const CLI_CLIENT_CAPABILITIES = [
|
||||
CLI_AGENT_CALLER_CLIENT_CAPABILITY
|
||||
] as const
|
||||
|
||||
// `agent read` prints chats as text the host projects, so it reads every chat agent; only that
|
||||
// request says so, leaving how other commands launch and list chats unchanged.
|
||||
const AGENT_READ_CLIENT_CAPABILITIES = [
|
||||
...CLI_CLIENT_CAPABILITIES,
|
||||
STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY,
|
||||
CLAUDE_STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY,
|
||||
STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY,
|
||||
PI_STRUCTURED_DIALOGS_RUNTIME_CAPABILITY
|
||||
] as const
|
||||
|
||||
function clientCapabilitiesFor(method: string) {
|
||||
return method === 'agent.read' ? AGENT_READ_CLIENT_CAPABILITIES : CLI_CLIENT_CAPABILITIES
|
||||
}
|
||||
|
||||
export async function sendWebSocketRequest<TResult>(
|
||||
connection: PairedRuntimeConnection,
|
||||
method: string,
|
||||
@@ -36,7 +58,7 @@ export async function sendWebSocketRequest<TResult>(
|
||||
envelope,
|
||||
undefined,
|
||||
undefined,
|
||||
CLI_CLIENT_CAPABILITIES,
|
||||
clientCapabilitiesFor(method),
|
||||
undefined,
|
||||
undefined
|
||||
)
|
||||
@@ -66,7 +88,7 @@ export async function sendWebSocketRequestWithStatusPreflight<TResult>(
|
||||
envelope,
|
||||
validateStatus,
|
||||
undefined,
|
||||
CLI_CLIENT_CAPABILITIES,
|
||||
clientCapabilitiesFor(method),
|
||||
requestSelection,
|
||||
undefined
|
||||
)
|
||||
|
||||
@@ -296,6 +296,16 @@ const ORCA_CLI_MARKDOWN = [
|
||||
"",
|
||||
"If a launch reply is lost, use the returned `operationId` to re-issue the exact same command from the same directory against the same execution host with `--retry-launch <operationId>`. Keep that ID on every retry: the host replays the accepted launch instead of starting another agent or submitting the brief twice. Do not retry as a fresh launch. If replay says the outcome is unknown or expired, or an older host gives no replay ID, inspect the workspace and agent without sending input before deciding whether another launch is needed. A host that cannot safely carry prompts or honor background/focus requests is refused before launch; update Orca on that execution host.",
|
||||
"",
|
||||
"## Agents by ID",
|
||||
"",
|
||||
"Every agent, chat or terminal, has an Orca session ID (`orca_session_id:<agent>_<uuid>`; what Copy Orca Session ID copies on a chat and Copy Agent ID on a terminal). Use it to find and read agents:",
|
||||
"",
|
||||
"- `ORCA agent list --json` lists the agents open in this host's workspaces, with `orcaSessionId`, `kind` (chat or terminal), state, workspace and last reply. A terminal agent has no ID until it first reports to Orca. Agents on other hosts are not listed; the output names those hosts and the `--environment` to use.",
|
||||
"- `ORCA agent show <id> --json` shows where one agent is open (none if closed, two if resumed in two panes).",
|
||||
"- `ORCA agent read <id> --json` reads what the agent said: a chat's history or a terminal agent's transcript, never its screen. It needs no running agent and never starts one. Pass the returned `cursor` with `--cursor` to read only newer entries. A terminal agent is readable while Orca knows its transcript (open, or asleep in a workspace).",
|
||||
"",
|
||||
"A chat keeps its ID across `/clear`; a terminal agent gets a new one. A provider's own conversation id or a `term_…` handle is refused with the ID to use. To message an agent, use `terminal send` or `orchestration send` as below.",
|
||||
"",
|
||||
"## Worktrees",
|
||||
"",
|
||||
"An Orca worktree is Orca's tracked view of a repo checkout, its metadata, terminals, browser tabs, and UI state.",
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { CommandSpec } from '../discovery/command-spec'
|
||||
import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary'
|
||||
|
||||
export const AGENT_CONVERSATION_COMMAND_SPECS: CommandSpec[] = [
|
||||
{
|
||||
path: ['agent', 'list'],
|
||||
summary: 'List open agents, chats and terminals, with their Orca session IDs',
|
||||
usage: 'orca agent list [--worktree <selector>] [--state <state>] [--json]',
|
||||
allowedFlags: [...GLOBAL_FLAGS, 'worktree', 'state'],
|
||||
notes: [
|
||||
"Lists the agents open in this Orca host's workspaces: chats and terminal agents alike, each with its `orca_session_id:` ID. A terminal agent shows no ID until it first reports to Orca.",
|
||||
'A chat keeps its ID across /clear; a terminal agent gets a new one when /clear starts a new conversation.',
|
||||
'--state keeps agents in one state: working, blocked, waiting or done.',
|
||||
'Agents on other hosts are not listed here; the output names those hosts and the `--environment` that lists them.'
|
||||
],
|
||||
examples: ['orca agent list --json', 'orca agent list --worktree active --state working']
|
||||
},
|
||||
{
|
||||
path: ['agent', 'show'],
|
||||
summary: 'Show where an agent is open, by its Orca session ID',
|
||||
usage: 'orca agent show <id> [--json]',
|
||||
allowedFlags: [...GLOBAL_FLAGS, 'id'],
|
||||
positionalArgs: ['id'],
|
||||
notes: [
|
||||
'<id> is the `orca_session_id:` ID from `orca agent list`, Copy Orca Session ID on a chat or Copy Agent ID on a terminal.',
|
||||
'An agent resumed in two panes shows both; one that is not open shows none.'
|
||||
],
|
||||
examples: ['orca agent show orca_session_id:claude_1234 --json']
|
||||
},
|
||||
{
|
||||
path: ['agent', 'read'],
|
||||
summary: 'Read what an agent said, by its Orca session ID',
|
||||
usage: 'orca agent read <id> [--limit <n>] [--cursor <cursor>] [--json]',
|
||||
allowedFlags: [...GLOBAL_FLAGS, 'id', 'limit', 'cursor'],
|
||||
positionalArgs: ['id'],
|
||||
notes: [
|
||||
"Reads the conversation, not a terminal screen: a chat's history, or a terminal agent's own transcript. The agent need not be running, and reading never starts it.",
|
||||
'--limit is the number of entries (default 20, at most 100). Pass the printed --cursor to read only what came after.',
|
||||
'A terminal agent can be read while Orca knows where its transcript is: while it is open, or asleep in a workspace.'
|
||||
],
|
||||
examples: [
|
||||
'orca agent read orca_session_id:claude_1234 --limit 10',
|
||||
'orca agent read orca_session_id:codex_1234 --cursor <cursor> --json'
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -14,6 +14,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_CONVERSATION_COMMAND_SPECS } from './agent-conversations'
|
||||
import { CONNECTOR_COMMAND_SPECS } from './connector'
|
||||
import { DIAGNOSTICS_COMMAND_SPECS } from './diagnostics'
|
||||
import { SPEECH_COMMAND_SPECS } from './speech'
|
||||
@@ -51,6 +52,7 @@ export const COMMAND_SPECS: CommandSpec[] = [
|
||||
...COMPUTER_COMMAND_SPECS,
|
||||
...AGENT_HOOK_COMMAND_SPECS,
|
||||
...AGENT_LAUNCH_COMMAND_SPECS,
|
||||
...AGENT_CONVERSATION_COMMAND_SPECS,
|
||||
...CHAT_COMMAND_SPECS,
|
||||
...CONNECTOR_COMMAND_SPECS,
|
||||
...DIAGNOSTICS_COMMAND_SPECS,
|
||||
|
||||
@@ -7,7 +7,7 @@ import type {
|
||||
import type { WorkerRequestTransport } from '../../worker-threads/worker-thread-transport'
|
||||
import type { AgentIdentityClient, AgentIdentityLookup } from './agent-identity-worker-client'
|
||||
import { handleAgentIdentityRequest } from './agent-identity-worker-entry'
|
||||
import { isOrcaSessionId } from '../../../shared/orca-session-address'
|
||||
import { isOrcaSessionId, type OrcaSessionId } from '../../../shared/orca-session-address'
|
||||
|
||||
/** The worker's real SQL handler behind an asynchronous boundary, counting requests. Each answer
|
||||
* can be held so a test decides when (and in which order) replies arrive. */
|
||||
@@ -43,6 +43,36 @@ export class InProcessAgentIdentityClient implements AgentIdentityClient {
|
||||
return response.ok && typeof response.value === 'boolean' ? response.value : undefined
|
||||
}
|
||||
|
||||
async providerKeyOf(
|
||||
path: string,
|
||||
orcaSessionId: string
|
||||
): Promise<{ key: AgentProviderKey | null } | undefined> {
|
||||
const response = handleAgentIdentityRequest({
|
||||
id: 0,
|
||||
kind: 'providerKeyOf',
|
||||
path,
|
||||
orcaSessionId
|
||||
})
|
||||
return response.ok && typeof response.value === 'object' && !Array.isArray(response.value)
|
||||
? { key: response.value }
|
||||
: undefined
|
||||
}
|
||||
|
||||
async idsOfProviderSession(
|
||||
path: string,
|
||||
providerSessionId: string
|
||||
): Promise<OrcaSessionId[] | undefined> {
|
||||
const response = handleAgentIdentityRequest({
|
||||
id: 0,
|
||||
kind: 'idsOfProviderSession',
|
||||
path,
|
||||
providerSessionId
|
||||
})
|
||||
return response.ok && Array.isArray(response.value)
|
||||
? response.value.filter(isOrcaSessionId)
|
||||
: undefined
|
||||
}
|
||||
|
||||
/** Lets every held request answer, oldest first. */
|
||||
release(): void {
|
||||
for (const resolve of this.held.splice(0)) {
|
||||
@@ -76,7 +106,11 @@ export class ScriptedIdentityWorkers {
|
||||
answer: (request: AgentIdentityWorkerRequest) => ScriptedAnswer = (request) =>
|
||||
request.kind === 'identify'
|
||||
? { id: request.id, ok: true, value: `claude_${request.key.providerSessionId}` }
|
||||
: { id: request.id, ok: true, value: this.known.has(request.orcaSessionId) }
|
||||
: {
|
||||
id: request.id,
|
||||
ok: true,
|
||||
value: request.kind === 'has' && this.known.has(request.orcaSessionId)
|
||||
}
|
||||
private readonly exits: (() => void)[] = []
|
||||
|
||||
readonly factory = (): WorkerRequestTransport => {
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { OrcaSessionId } from '../../../shared/orca-session-address'
|
||||
import type { AgentProviderKey } from './agent-provider-key'
|
||||
import type { AgentIdentityClient } from './agent-identity-worker-client'
|
||||
import type { RowAgentIdentity } from './pane-agent-identities'
|
||||
import { AgentIdentityLookupQueue, type AgentIdentityLookup } from './agent-identity-lookup-queue'
|
||||
|
||||
/** One exact provider key some current row or caller needs: the identity they all carry, the
|
||||
* places to re-stamp, and explicit callers waiting for its answer. Dropped once nothing current
|
||||
@@ -13,7 +14,9 @@ export type KeyDemand = {
|
||||
waiters: Set<(id: OrcaSessionId | null) => void>
|
||||
}
|
||||
|
||||
type Operation = { kind: 'identify'; keyString: string } | { kind: 'has'; id: string }
|
||||
type Operation =
|
||||
| { kind: 'identify'; keyString: string }
|
||||
| { kind: 'lookup'; lookup: AgentIdentityLookup }
|
||||
|
||||
const RETRY_DELAY_MS = 30_000
|
||||
/** An explicit caller (Copy, refusal) waits at most this long; its row demand outlives it. */
|
||||
@@ -39,7 +42,8 @@ export class AgentIdentityDemand {
|
||||
private readonly unresolved = new Set<string>()
|
||||
/** Keys a Copy click may send once despite the failure backoff. */
|
||||
private readonly bypass = new Set<string>()
|
||||
private readonly memberships = new Map<string, Set<(known: boolean | undefined) => void>>()
|
||||
/** Explicit read-only questions (membership, an `orca agent` read), unsent, in order. */
|
||||
private readonly lookups = new AgentIdentityLookupQueue(CALLER_WAIT_MS)
|
||||
|
||||
constructor(
|
||||
private readonly databasePath: () => string | null,
|
||||
@@ -113,29 +117,21 @@ export class AgentIdentityDemand {
|
||||
}
|
||||
|
||||
/** Membership shares the failure gate: during the backoff it answers unavailable at once. */
|
||||
async has(id: string): Promise<boolean | undefined> {
|
||||
has = (id: string) => this.lookup((client, path) => client.has(path, id))
|
||||
|
||||
/** An explicit read-only question under the store's one-at-a-time queue and failure gate;
|
||||
* undefined when the store cannot answer now. A sent question leaves `lookups`. */
|
||||
async lookup<T>(
|
||||
run: (client: AgentIdentityClient, path: string) => Promise<T | undefined>
|
||||
): Promise<T | undefined> {
|
||||
this.syncAuthority()
|
||||
if (!this.authorityPath || Date.now() < this.retryAt) {
|
||||
return undefined
|
||||
}
|
||||
const generation = this.generationValue
|
||||
const known = await new Promise<boolean | undefined>((resolve) => {
|
||||
const waiters = this.memberships.get(id) ?? new Set()
|
||||
const waiter = (answer: boolean | undefined): void => {
|
||||
clearTimeout(timer)
|
||||
waiters.delete(waiter)
|
||||
if (waiters.size === 0 && this.memberships.get(id) === waiters) {
|
||||
this.memberships.delete(id)
|
||||
}
|
||||
resolve(answer)
|
||||
}
|
||||
const timer = setTimeout(() => waiter(undefined), CALLER_WAIT_MS)
|
||||
timer.unref()
|
||||
waiters.add(waiter)
|
||||
this.memberships.set(id, waiters)
|
||||
this.schedulePump()
|
||||
})
|
||||
return generation === this.generationValue ? known : undefined
|
||||
const answer = this.lookups.enqueue(run)
|
||||
this.schedulePump()
|
||||
return generation === this.generationValue ? await answer : undefined
|
||||
}
|
||||
|
||||
/** A different store path is a different authority: nothing carries across. */
|
||||
@@ -164,12 +160,7 @@ export class AgentIdentityDemand {
|
||||
this.failing = false
|
||||
this.clearWake()
|
||||
this.bypass.clear()
|
||||
for (const waiters of this.memberships.values()) {
|
||||
for (const waiter of waiters) {
|
||||
waiter(undefined)
|
||||
}
|
||||
}
|
||||
this.memberships.clear()
|
||||
this.lookups.cancelAll()
|
||||
for (const [keyString, demand] of this.keys) {
|
||||
for (const waiter of demand.waiters) {
|
||||
waiter(null)
|
||||
@@ -236,9 +227,9 @@ export class AgentIdentityDemand {
|
||||
}
|
||||
return { kind: 'identify', keyString: explicit }
|
||||
}
|
||||
const membership = this.memberships.keys().next().value
|
||||
if (membership !== undefined) {
|
||||
return { kind: 'has', id: membership }
|
||||
const lookup = this.lookups.next()
|
||||
if (lookup) {
|
||||
return { kind: 'lookup', lookup }
|
||||
}
|
||||
const keyString = this.unresolved.values().next().value
|
||||
return keyString === undefined ? null : { kind: 'identify', keyString }
|
||||
@@ -264,15 +255,10 @@ export class AgentIdentityDemand {
|
||||
this.active = operation
|
||||
const generation = this.generationValue
|
||||
const current = (): boolean => generation === this.generationValue
|
||||
if (operation.kind === 'has') {
|
||||
void client.has(path, operation.id).then((known) => {
|
||||
if (current()) {
|
||||
for (const waiter of this.memberships.get(operation.id) ?? []) {
|
||||
waiter(known)
|
||||
}
|
||||
}
|
||||
this.finish(operation, generation, known === undefined)
|
||||
})
|
||||
if (operation.kind === 'lookup') {
|
||||
void operation.lookup
|
||||
.send(client, path)
|
||||
.then((failed) => this.finish(operation, generation, failed))
|
||||
return
|
||||
}
|
||||
const { keyString } = operation
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import type { AgentIdentityClient } from './agent-identity-worker-client'
|
||||
|
||||
/** One explicit read-only question: `send` resolves true when the store could not answer. */
|
||||
export type AgentIdentityLookup = {
|
||||
send: (client: AgentIdentityClient, path: string) => Promise<boolean>
|
||||
cancel: () => void
|
||||
}
|
||||
|
||||
/** Questions for the identity store's one-at-a-time queue; each caller waits at most `waitMs`,
|
||||
* and a question already sent may finish after its caller stopped waiting. */
|
||||
export class AgentIdentityLookupQueue {
|
||||
/** Callers still waiting, in arrival order; a sent question stays until it is answered. */
|
||||
private readonly waiting = new Set<AgentIdentityLookup>()
|
||||
private readonly sent = new WeakSet<AgentIdentityLookup>()
|
||||
|
||||
constructor(private readonly waitMs: number) {}
|
||||
|
||||
enqueue<T>(
|
||||
run: (client: AgentIdentityClient, path: string) => Promise<T | undefined>
|
||||
): Promise<T | undefined> {
|
||||
return new Promise((resolve) => {
|
||||
const done = (value: T | undefined): void => {
|
||||
clearTimeout(timer)
|
||||
this.waiting.delete(lookup)
|
||||
resolve(value)
|
||||
}
|
||||
const lookup: AgentIdentityLookup = {
|
||||
send: async (client, path) => {
|
||||
const value = await run(client, path)
|
||||
done(value)
|
||||
return value === undefined
|
||||
},
|
||||
cancel: () => done(undefined)
|
||||
}
|
||||
const timer = setTimeout(lookup.cancel, this.waitMs)
|
||||
timer.unref()
|
||||
this.waiting.add(lookup)
|
||||
})
|
||||
}
|
||||
|
||||
/** The oldest question not yet sent, marked sent. */
|
||||
next(): AgentIdentityLookup | undefined {
|
||||
for (const lookup of this.waiting) {
|
||||
if (!this.sent.has(lookup)) {
|
||||
this.sent.add(lookup)
|
||||
return lookup
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** An ended store authority: every waiting caller gets no answer now. */
|
||||
cancelAll(): void {
|
||||
for (const lookup of this.waiting) {
|
||||
lookup.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import type {
|
||||
} from '../../worker-threads/worker-thread-transport'
|
||||
import { isOrcaSessionId, type OrcaSessionId } from '../../../shared/orca-session-address'
|
||||
import type { AgentProviderKey } from './agent-provider-key'
|
||||
import { isRecord } from '../../../shared/agent-status/child-work/agent-status-child-work-value-guards'
|
||||
import type {
|
||||
AgentIdentityWorkerRequest,
|
||||
AgentIdentityWorkerResponse
|
||||
@@ -27,6 +28,15 @@ export type AgentIdentityLookup = { id: OrcaSessionId | null } | undefined
|
||||
export type AgentIdentityClient = {
|
||||
identify(path: string, key: AgentProviderKey): Promise<AgentIdentityLookup>
|
||||
has(path: string, orcaSessionId: string): Promise<boolean | undefined>
|
||||
/** `{ key: null }`: this host never linked `orcaSessionId`; undefined: no answer now. */
|
||||
providerKeyOf(
|
||||
path: string,
|
||||
orcaSessionId: string
|
||||
): Promise<{ key: AgentProviderKey | null } | undefined>
|
||||
idsOfProviderSession(
|
||||
path: string,
|
||||
providerSessionId: string
|
||||
): Promise<OrcaSessionId[] | undefined>
|
||||
/** Terminated but not yet exited: a replacement must wait for `retired()`. */
|
||||
readonly isRetiring: boolean
|
||||
retired(): Promise<void>
|
||||
@@ -76,6 +86,30 @@ export class AgentIdentityWorkerClient implements AgentIdentityClient {
|
||||
return typeof value === 'boolean' ? value : undefined
|
||||
}
|
||||
|
||||
async providerKeyOf(
|
||||
path: string,
|
||||
orcaSessionId: string
|
||||
): Promise<{ key: AgentProviderKey | null } | undefined> {
|
||||
const value = await this.request((id) => ({ id, kind: 'providerKeyOf', path, orcaSessionId }))
|
||||
if (value === null) {
|
||||
return { key: null }
|
||||
}
|
||||
return isProviderKey(value) ? { key: value } : undefined
|
||||
}
|
||||
|
||||
async idsOfProviderSession(
|
||||
path: string,
|
||||
providerSessionId: string
|
||||
): Promise<OrcaSessionId[] | undefined> {
|
||||
const value = await this.request((id) => ({
|
||||
id,
|
||||
kind: 'idsOfProviderSession',
|
||||
path,
|
||||
providerSessionId
|
||||
}))
|
||||
return Array.isArray(value) ? value.filter(isOrcaSessionId) : undefined
|
||||
}
|
||||
|
||||
get isRetiring(): boolean {
|
||||
return this.queue.isRetiring
|
||||
}
|
||||
@@ -92,7 +126,7 @@ export class AgentIdentityWorkerClient implements AgentIdentityClient {
|
||||
* dispatch; callers' waits are bounded by the owner, not here. */
|
||||
private async request(
|
||||
build: (id: number) => AgentIdentityWorkerRequest
|
||||
): Promise<string | null | boolean | undefined> {
|
||||
): Promise<Extract<AgentIdentityWorkerResponse, { ok: true }>['value'] | undefined> {
|
||||
try {
|
||||
const response = await this.queue.dispatch(build, OPERATION_TIMEOUT_MS)
|
||||
if (!response.ok) {
|
||||
@@ -105,3 +139,12 @@ export class AgentIdentityWorkerClient implements AgentIdentityClient {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isProviderKey(value: unknown): value is AgentProviderKey {
|
||||
return (
|
||||
isRecord(value) &&
|
||||
['executionHost', 'wslDistro', 'agent', 'providerSessionId', 'locator'].every(
|
||||
(field) => typeof value[field] === 'string'
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -30,6 +30,12 @@ CREATE TABLE IF NOT EXISTS provider_links(
|
||||
|
||||
const SELECT_LINK = `SELECT orca_session_id FROM provider_links
|
||||
WHERE execution_host = ? AND wsl_distro = ? AND agent = ? AND provider_session_id = ? AND locator = ?`
|
||||
// Reverse lookups for `orca agent` reads; indexes only, so older builds open the file unchanged.
|
||||
const LOOKUP_INDEX_SQL = `CREATE INDEX IF NOT EXISTS provider_links_by_orca_session
|
||||
ON provider_links(orca_session_id);
|
||||
CREATE INDEX IF NOT EXISTS provider_links_by_provider_session
|
||||
ON provider_links(provider_session_id);`
|
||||
const PROVIDER_SESSION_ID_MATCH_LIMIT = 8
|
||||
|
||||
/** Orca ids for provider conversations, which nothing can rebuild: the file is never deleted, and
|
||||
* an unreadable one throws so ids stay unavailable. A linked key is never relinked. Runs only in
|
||||
@@ -97,6 +103,36 @@ export class AgentIdentityStore {
|
||||
)
|
||||
}
|
||||
|
||||
/** The provider conversation `id` names: each mint links exactly one key. */
|
||||
providerKeyOf(id: string): AgentProviderKey | null {
|
||||
const row = this.db
|
||||
.prepare(
|
||||
`SELECT execution_host, wsl_distro, agent, provider_session_id, locator
|
||||
FROM provider_links WHERE orca_session_id = ? LIMIT 1`
|
||||
)
|
||||
.get(id)
|
||||
return row
|
||||
? {
|
||||
executionHost: String(row.execution_host),
|
||||
wslDistro: String(row.wsl_distro),
|
||||
agent: String(row.agent),
|
||||
providerSessionId: String(row.provider_session_id),
|
||||
locator: String(row.locator)
|
||||
}
|
||||
: null
|
||||
}
|
||||
|
||||
/** Orca ids linked to a provider's own session id, so a caller can be told which to use. */
|
||||
idsOfProviderSession(providerSessionId: string): OrcaSessionId[] {
|
||||
return this.db
|
||||
.prepare(
|
||||
`SELECT DISTINCT orca_session_id FROM provider_links WHERE provider_session_id = ? LIMIT ${PROVIDER_SESSION_ID_MATCH_LIMIT}`
|
||||
)
|
||||
.all(providerSessionId)
|
||||
.map((row) => row.orca_session_id)
|
||||
.filter((id): id is OrcaSessionId => typeof id === 'string' && isOrcaSessionId(id))
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.db.close()
|
||||
}
|
||||
@@ -140,6 +176,12 @@ function openIdentityDatabase(
|
||||
throw error
|
||||
}
|
||||
}
|
||||
try {
|
||||
db.exec(LOOKUP_INDEX_SQL)
|
||||
} catch (error) {
|
||||
// A busy file still answers lookups, by scan; the next open adds the indexes.
|
||||
console.warn('[agent-hooks] agent identity lookup indexes deferred', error)
|
||||
}
|
||||
return { db, readOnly: false }
|
||||
} catch (error) {
|
||||
db.close()
|
||||
@@ -168,9 +210,20 @@ export function handleAgentIdentityRequest(
|
||||
): AgentIdentityWorkerResponse {
|
||||
try {
|
||||
const opened = storeFor(request.path)
|
||||
return request.kind === 'identify'
|
||||
? { id: request.id, ok: true, value: opened.identify(request.key) }
|
||||
: { id: request.id, ok: true, value: opened.has(request.orcaSessionId) }
|
||||
switch (request.kind) {
|
||||
case 'identify':
|
||||
return { id: request.id, ok: true, value: opened.identify(request.key) }
|
||||
case 'has':
|
||||
return { id: request.id, ok: true, value: opened.has(request.orcaSessionId) }
|
||||
case 'providerKeyOf':
|
||||
return { id: request.id, ok: true, value: opened.providerKeyOf(request.orcaSessionId) }
|
||||
case 'idsOfProviderSession':
|
||||
return {
|
||||
id: request.id,
|
||||
ok: true,
|
||||
value: opened.idsOfProviderSession(request.providerSessionId)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// A store that failed to open is reopened by the next request, never rebuilt.
|
||||
store?.store.close()
|
||||
|
||||
@@ -4,8 +4,10 @@ import type { AgentProviderKey } from './agent-provider-key'
|
||||
export type AgentIdentityWorkerRequest =
|
||||
| { id: number; kind: 'identify'; path: string; key: AgentProviderKey }
|
||||
| { id: number; kind: 'has'; path: string; orcaSessionId: string }
|
||||
| { id: number; kind: 'providerKeyOf'; path: string; orcaSessionId: string }
|
||||
| { id: number; kind: 'idsOfProviderSession'; path: string; providerSessionId: string }
|
||||
|
||||
/** `identify` answers the committed id, or null for an unlinked key in a read-only file. */
|
||||
export type AgentIdentityWorkerResponse =
|
||||
| { id: number; ok: true; value: string | null | boolean }
|
||||
| { id: number; ok: true; value: string | null | boolean | AgentProviderKey | string[] }
|
||||
| { id: number; ok: false; error: string }
|
||||
|
||||
@@ -248,7 +248,8 @@ describe('PaneAgentIdentities authority', () => {
|
||||
: {
|
||||
id: request.id,
|
||||
ok: true,
|
||||
value: request.orcaSessionId.startsWith(`claude_${request.path}`)
|
||||
value:
|
||||
request.kind === 'has' && request.orcaSessionId.startsWith(`claude_${request.path}`)
|
||||
}
|
||||
let path = 'storeA'
|
||||
const settled: SettledAgentIdentityPlace[] = []
|
||||
|
||||
@@ -165,6 +165,18 @@ export class PaneAgentIdentities {
|
||||
return authority === this.demand.generation ? known : undefined
|
||||
}
|
||||
|
||||
/** The provider conversation this host linked `id` to: `{ key: null }` for none, undefined
|
||||
* when the store cannot answer now. An explicit lookup, never per hook. */
|
||||
async providerKeyOf(id: string): Promise<{ key: AgentProviderKey | null } | undefined> {
|
||||
return this.demand.lookup((client, path) => client.providerKeyOf(path, id))
|
||||
}
|
||||
|
||||
async idsOfProviderSession(providerSessionId: string): Promise<OrcaSessionId[] | undefined> {
|
||||
return this.demand.lookup((client, path) =>
|
||||
client.idsOfProviderSession(path, providerSessionId)
|
||||
)
|
||||
}
|
||||
|
||||
/** Keeps the indexes and demand subscriptions exact: `place` is a legacy row key or a
|
||||
* canonical subject. Admission subscribes here, after the row is stored. */
|
||||
setPlace(place: string, paneKey: string, identity: RowAgentIdentity | undefined): void {
|
||||
|
||||
@@ -9,7 +9,11 @@ import {
|
||||
type ProviderSessionSighting,
|
||||
type SettledAgentIdentityPlace
|
||||
} from '../identity/pane-agent-identities'
|
||||
import type { SleepingAgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-resume'
|
||||
import type {
|
||||
AgentProviderSessionMetadata,
|
||||
SleepingAgentSessionRecord
|
||||
} from '../../../shared/agent-session/lifecycle/agent-session-resume'
|
||||
import type { AgentProviderKey } from '../identity/agent-provider-key'
|
||||
import type { OrcaSessionId } from '../../../shared/orca-session-address'
|
||||
|
||||
import type { EnrichedAgentHookEventPayload } from './server-types'
|
||||
@@ -26,6 +30,12 @@ type SleepingAgentSighting = Pick<
|
||||
'agent' | 'providerSession' | 'connectionId'
|
||||
>
|
||||
|
||||
/** One terminal agent conversation's own transcript, as the payload naming it reported it. */
|
||||
export type TerminalAgentTranscriptSource = {
|
||||
key: AgentProviderKey
|
||||
providerSession: AgentProviderSessionMetadata
|
||||
}
|
||||
|
||||
/** Terminal agent ids are named when a row is admitted, so walks and publications only copy them. */
|
||||
export abstract class AgentHookServerAgentIdentities extends AgentHookServerState {
|
||||
private identityPath: { from: string | null; path: string | null } = { from: null, path: null }
|
||||
@@ -173,6 +183,86 @@ export abstract class AgentHookServerAgentIdentities extends AgentHookServerStat
|
||||
return places
|
||||
}
|
||||
|
||||
/** Whether this host minted terminal agent `id`; undefined when the store cannot answer now. */
|
||||
async isTerminalAgentId(id: string): Promise<boolean | undefined> {
|
||||
return this.agentIdentities.isTerminalIdentity(id)
|
||||
}
|
||||
|
||||
/** Orca ids this host linked to a provider's own session id. */
|
||||
async terminalAgentIdsOfProviderSession(providerSessionId: string): Promise<OrcaSessionId[]> {
|
||||
return (await this.agentIdentities.idsOfProviderSession(providerSessionId)) ?? []
|
||||
}
|
||||
|
||||
/** Where terminal agent `id`'s transcript is: a current row carrying the id, in any state (a read
|
||||
* needs no running agent), else a sleeping record naming its provider key. The session id and
|
||||
* path come from one payload, never from a pane, so a row attributed to the wrong pane still
|
||||
* names its own conversation. null: nothing names it now; undefined: the store cannot answer. */
|
||||
async terminalAgentTranscriptSource(
|
||||
id: string,
|
||||
listSleeping: () => readonly SleepingAgentSighting[]
|
||||
): Promise<TerminalAgentTranscriptSource | null | undefined> {
|
||||
const authority = this.agentIdentities.authority()
|
||||
const live = this.liveTranscriptSource(id)
|
||||
if (live) {
|
||||
return live
|
||||
}
|
||||
const linked = await this.agentIdentities.providerKeyOf(id)
|
||||
if (!linked || authority !== this.agentIdentities.generation) {
|
||||
return undefined
|
||||
}
|
||||
const { key } = linked
|
||||
// Sleeping records carry no WSL distro, so on Windows one cannot name its guest's path.
|
||||
if (!key || process.platform === 'win32') {
|
||||
return null
|
||||
}
|
||||
for (const record of listSleeping()) {
|
||||
const recordKey = agentProviderKeyOf({
|
||||
agent: record.agent,
|
||||
providerSession: record.providerSession,
|
||||
connectionId: record.connectionId ?? null
|
||||
})
|
||||
if (recordKey && sameProviderKey(recordKey, key)) {
|
||||
return { key, providerSession: record.providerSession }
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private liveTranscriptSource(id: string): TerminalAgentTranscriptSource | null {
|
||||
let best: { key: AgentProviderKey; row: EnrichedAgentHookEventPayload } | null = null
|
||||
for (const place of this.agentIdentities.placesOf(id)) {
|
||||
const subject = place.canonical
|
||||
? this.canonicalSubjectsByPane.get(place.paneKey)?.get(place.key)
|
||||
: undefined
|
||||
const status = subject && this.canonicalStatusStore.getParent(subject)?.status
|
||||
const row = place.canonical
|
||||
? status && structuredStatusLegacyEvent(status)
|
||||
: // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Main admits enriched legacy rows; the shared view declares their base event type.
|
||||
(this.state.lastStatusByPaneKey.get(place.key) as
|
||||
| EnrichedAgentHookEventPayload
|
||||
| undefined)
|
||||
const key = place.canonical
|
||||
? this.agentIdentities.canonicalIdentity(place.key)?.key
|
||||
: row?.agentIdentity?.key
|
||||
if (!row?.providerSession || !key) {
|
||||
continue
|
||||
}
|
||||
// Rows of one conversation share its key; prefer one that reported the transcript path.
|
||||
const hasPath = (candidate: EnrichedAgentHookEventPayload): boolean =>
|
||||
Boolean(candidate.providerSession?.transcriptPath)
|
||||
if (
|
||||
!best ||
|
||||
(hasPath(row) && !hasPath(best.row)) ||
|
||||
(hasPath(row) === hasPath(best.row) && row.receivedAt > best.row.receivedAt)
|
||||
) {
|
||||
best = { key, row }
|
||||
}
|
||||
}
|
||||
return best?.row.providerSession
|
||||
? { key: best.key, providerSession: best.row.providerSession }
|
||||
: null
|
||||
}
|
||||
|
||||
/** The pane's terminal agent id, keyed as Copy Session ID picks its id: a confirmed live row
|
||||
* (legacy or tmux-selected) wins even without a provider session; only an absent or
|
||||
* unconfirmed row falls back to the pane's sleeping record. An explicit request: it waits for
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import { mkdtempSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, expect, it } from 'vitest'
|
||||
import { normalizeHookPayload } from '../../../../../shared/agent-hook-listener/normalization/normalize-hook-payload'
|
||||
import { createHookListenerState } from '../../../../../shared/agent-hook-listener/listener-state'
|
||||
import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id'
|
||||
import { InProcessAgentIdentityClient } from '../../../identity/agent-identity-client.test-fixtures'
|
||||
import type { AgentIdentityClient } from '../../../identity/agent-identity-worker-client'
|
||||
import { AgentHookServer } from '../../agent-hook-server'
|
||||
import { buildBody } from '../server.test-fixtures'
|
||||
|
||||
const WSL = 'wsl:Ubuntu'
|
||||
const PANE = makePaneKey('tab-0', '00000000-0000-4000-8000-000000000000')
|
||||
const cleanups: (() => void)[] = []
|
||||
afterEach(() => {
|
||||
for (const cleanup of cleanups.splice(0)) {
|
||||
cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
class IdentityTestServer extends AgentHookServer {
|
||||
protected override createAgentIdentityClient(): AgentIdentityClient {
|
||||
return new InProcessAgentIdentityClient()
|
||||
}
|
||||
}
|
||||
|
||||
function hook(sessionId: string, transcriptPath: string) {
|
||||
const event = normalizeHookPayload(
|
||||
createHookListenerState(),
|
||||
'claude',
|
||||
buildBody(
|
||||
{
|
||||
hook_event_name: 'UserPromptSubmit',
|
||||
session_id: sessionId,
|
||||
transcript_path: transcriptPath,
|
||||
prompt: 'task'
|
||||
},
|
||||
{ paneKey: PANE, tabId: 'tab-0' }
|
||||
),
|
||||
'production'
|
||||
)
|
||||
if (!event) {
|
||||
throw new Error('hook was rejected')
|
||||
}
|
||||
return event
|
||||
}
|
||||
|
||||
async function started(): Promise<IdentityTestServer> {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'agent-transcript-source-'))
|
||||
const server = new IdentityTestServer()
|
||||
cleanups.unshift(() => rmSync(dir, { recursive: true, force: true }))
|
||||
cleanups.unshift(() => server.stop())
|
||||
await server.start({ env: 'production', userDataPath: dir })
|
||||
return server
|
||||
}
|
||||
|
||||
const answered = () => new Promise((resolve) => setImmediate(resolve))
|
||||
|
||||
it('reads a terminal agent by its own conversation, never by the pane it was attributed to', async () => {
|
||||
const server = await started()
|
||||
server.ingestRemote(hook('session-a', '/home/u/.claude/projects/p/a.jsonl'), WSL)
|
||||
await answered()
|
||||
const first = server.getStatusSnapshot()[0]?.orcaSessionId
|
||||
// Another agent's hooks land on the same pane, as in the split-pane misattribution.
|
||||
server.ingestRemote(hook('session-b', '/home/u/.claude/projects/p/b.jsonl'), WSL)
|
||||
await answered()
|
||||
const second = server.getStatusSnapshot()[0]?.orcaSessionId
|
||||
expect(first).toMatch(/^claude_/)
|
||||
expect(second).toMatch(/^claude_/)
|
||||
expect(second).not.toBe(first)
|
||||
|
||||
expect(await server.terminalAgentTranscriptSource(second!, () => [])).toMatchObject({
|
||||
key: { wslDistro: 'Ubuntu', agent: 'claude', providerSessionId: 'session-b' },
|
||||
providerSession: { id: 'session-b', transcriptPath: '/home/u/.claude/projects/p/b.jsonl' }
|
||||
})
|
||||
// The first conversation's pane now shows the second: it has no transcript location, not b's.
|
||||
expect(await server.terminalAgentTranscriptSource(first!, () => [])).toBeNull()
|
||||
expect(await server.terminalAgentIdsOfProviderSession('session-a')).toEqual([first])
|
||||
})
|
||||
|
||||
it.skipIf(process.platform === 'win32')(
|
||||
"finds a dormant agent's transcript only through a sleeping record naming its conversation",
|
||||
async () => {
|
||||
const server = await started()
|
||||
server.ingestRemote(hook('session-a', '/home/u/.claude/projects/p/a.jsonl'), WSL)
|
||||
await answered()
|
||||
const id = server.getStatusSnapshot()[0]?.orcaSessionId
|
||||
server.dropStatusEntry(PANE, { preserveResumeIdentity: false })
|
||||
const sleeping = (sessionId: string) => ({
|
||||
agent: 'claude' as const,
|
||||
providerSession: {
|
||||
key: 'session_id' as const,
|
||||
id: sessionId,
|
||||
transcriptPath: `/home/u/.claude/projects/p/${sessionId}.jsonl`
|
||||
},
|
||||
connectionId: WSL
|
||||
})
|
||||
|
||||
expect(await server.terminalAgentTranscriptSource(id!, () => [sleeping('other')])).toBeNull()
|
||||
expect(
|
||||
await server.terminalAgentTranscriptSource(id!, () => [
|
||||
sleeping('other'),
|
||||
sleeping('session-a')
|
||||
])
|
||||
).toMatchObject({
|
||||
key: { wslDistro: 'Ubuntu', providerSessionId: 'session-a' },
|
||||
providerSession: { transcriptPath: '/home/u/.claude/projects/p/session-a.jsonl' }
|
||||
})
|
||||
}
|
||||
)
|
||||
@@ -27,6 +27,28 @@ export class MemoryAgentIdentityClient implements AgentIdentityClient {
|
||||
return [...this.ids].some(([key, id]) => id === orcaSessionId && key.startsWith(pathPrefix))
|
||||
}
|
||||
|
||||
async providerKeyOf(
|
||||
path: string,
|
||||
orcaSessionId: string
|
||||
): Promise<{ key: AgentProviderKey | null }> {
|
||||
const linked = [...this.ids].find(([keyString, id]) => {
|
||||
return id === orcaSessionId && keyString.startsWith(JSON.stringify([path]).slice(0, -1))
|
||||
})
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: map keys are JSON.stringify([path, key]) written above.
|
||||
return { key: linked ? (JSON.parse(linked[0]) as [string, AgentProviderKey])[1] : null }
|
||||
}
|
||||
|
||||
async idsOfProviderSession(path: string, providerSessionId: string): Promise<OrcaSessionId[]> {
|
||||
const pathPrefix = JSON.stringify([path]).slice(0, -1)
|
||||
return [...this.ids]
|
||||
.filter(
|
||||
([keyString]) =>
|
||||
keyString.startsWith(pathPrefix) &&
|
||||
keyString.includes(`"providerSessionId":${JSON.stringify(providerSessionId)}`)
|
||||
)
|
||||
.map(([, id]) => id)
|
||||
}
|
||||
|
||||
readonly isRetiring = false
|
||||
|
||||
retired(): Promise<void> {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { resolveAgentConversation } from './agent-conversation-address'
|
||||
|
||||
const hookServer = vi.hoisted(() => ({
|
||||
isTerminalAgentId: vi.fn<(id: string) => Promise<boolean | undefined>>(),
|
||||
terminalAgentIdsOfProviderSession: vi.fn<(id: string) => Promise<string[]>>()
|
||||
}))
|
||||
const chats = vi.hoisted(() => ({ ids: new Set<string>(), aliases: new Map<string, string>() }))
|
||||
|
||||
vi.mock('../../agent-hooks/server/agent-hook-server', () => ({ agentHookServer: hookServer }))
|
||||
vi.mock('../orchestration/addressing/session-lineage/structured-session-lineage', async (load) => ({
|
||||
...(await load<object>()),
|
||||
readAgentSessionRecordStore: () => ({
|
||||
getRecord: (id: string) =>
|
||||
chats.ids.has(id) ? { sessionId: id, provider: 'codex', providerHandleChain: [] } : null,
|
||||
listRecords: () => [],
|
||||
providerAliasOwner: (id: string) => chats.aliases.get(id) ?? null
|
||||
})
|
||||
}))
|
||||
|
||||
const CHAT = 'codex_0b8f2a4e_6c1d_4f7a_9e3b_5a2c8d1f0e47'
|
||||
const TERMINAL = 'claude_5688af50_12a0_4b0b_9a4a_098d87fe1e68'
|
||||
const runtime = { ensureStructuredAgentSessionHost: async () => undefined }
|
||||
|
||||
beforeEach(() => {
|
||||
chats.ids = new Set([CHAT])
|
||||
chats.aliases = new Map()
|
||||
hookServer.isTerminalAgentId.mockReset().mockResolvedValue(false)
|
||||
hookServer.terminalAgentIdsOfProviderSession.mockReset().mockResolvedValue([])
|
||||
})
|
||||
|
||||
describe('resolveAgentConversation', () => {
|
||||
it('resolves a chat from the chat store alone, without the terminal identity store', async () => {
|
||||
await expect(
|
||||
resolveAgentConversation(runtime, ` orca_session_id:${CHAT}\n`)
|
||||
).resolves.toMatchObject({ kind: 'chat', orcaSessionId: CHAT })
|
||||
expect(hookServer.isTerminalAgentId).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('names the Orca ID for a terminal provider id before refusing its spelling', async () => {
|
||||
hookServer.terminalAgentIdsOfProviderSession.mockResolvedValue([TERMINAL])
|
||||
await expect(
|
||||
resolveAgentConversation(runtime, '7f201ef0-437e-44d9-94da-6323eee9a3f4')
|
||||
).rejects.toMatchObject({
|
||||
code: 'agent_provider_id',
|
||||
message: expect.stringContaining(`orca_session_id:${TERMINAL}`)
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses a terminal handle, and an ID no store on this host knows', async () => {
|
||||
await expect(resolveAgentConversation(runtime, 'term_0a1b2c')).rejects.toMatchObject({
|
||||
code: 'agent_terminal_handle'
|
||||
})
|
||||
await expect(resolveAgentConversation(runtime, TERMINAL)).rejects.toMatchObject({
|
||||
code: 'agent_unknown'
|
||||
})
|
||||
hookServer.isTerminalAgentId.mockResolvedValue(true)
|
||||
await expect(resolveAgentConversation(runtime, TERMINAL)).resolves.toEqual({
|
||||
kind: 'terminal',
|
||||
orcaSessionId: TERMINAL
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,104 @@
|
||||
import { ORCA_SESSION_ADDRESS_PREFIX } from '../../../shared/orca-session-address-prefix'
|
||||
import {
|
||||
isOrcaSessionId,
|
||||
parseOrcaSessionAddress,
|
||||
type OrcaSessionId
|
||||
} from '../../../shared/orca-session-address'
|
||||
import { isTerminalHandle } from '../../../shared/terminal-handle-prefix'
|
||||
import type { AgentSessionConversationView } from '../../../shared/agent-session/lifecycle/agent-session-conversation-view'
|
||||
import { AGENT_CONVERSATION_REFUSAL_CODES as CODES } from '../../../shared/agent-conversations/agent-conversation-contracts'
|
||||
import { lookupOrcaAgentSession } from '../orchestration/mailbox/routing/structured-session-mail-address'
|
||||
import {
|
||||
readAgentSessionRecordStore,
|
||||
type AgentSessionRecordReader
|
||||
} from '../orchestration/addressing/session-lineage/structured-session-lineage'
|
||||
import { canonicalOrcaSessionId } from '../orchestration/addressing/session-lineage/canonical-orca-session-id'
|
||||
import { agentHookServer } from '../../agent-hooks/server/agent-hook-server'
|
||||
import { AgentConversationRefusal } from './agent-conversation-refusal'
|
||||
|
||||
export type ResolvedAgentConversation =
|
||||
| {
|
||||
kind: 'chat'
|
||||
/** The conversation's /clear root, the ID Copy Orca Session ID copies. */
|
||||
orcaSessionId: OrcaSessionId
|
||||
record: AgentSessionConversationView
|
||||
store: AgentSessionRecordReader
|
||||
}
|
||||
| { kind: 'terminal'; orcaSessionId: OrcaSessionId }
|
||||
|
||||
/** One Orca session ID to the conversation it names on this host: chats first, from the chat
|
||||
* store alone, then this host's terminal agent ids. Resolution reads records only; it never
|
||||
* needs, starts or wakes a running agent. */
|
||||
export async function resolveAgentConversation(
|
||||
runtime: { ensureStructuredAgentSessionHost(): Promise<unknown> },
|
||||
input: string
|
||||
): Promise<ResolvedAgentConversation> {
|
||||
const text = input.trim()
|
||||
if (isTerminalHandle(text)) {
|
||||
throw new AgentConversationRefusal(
|
||||
CODES.terminalHandle,
|
||||
`${text} is a terminal handle, which changes when the terminal restarts. Use \`orca terminal …\` for it, or the agent's \`orca_session_id:\` from \`orca agent list\`.`
|
||||
)
|
||||
}
|
||||
const id = text.startsWith(ORCA_SESSION_ADDRESS_PREFIX)
|
||||
? parseOrcaSessionAddress(text)
|
||||
: isOrcaSessionId(text)
|
||||
? text
|
||||
: null
|
||||
// The chat store opens lazily; installing it reads records and starts no agent.
|
||||
await runtime.ensureStructuredAgentSessionHost().catch(() => undefined)
|
||||
const store = readAgentSessionRecordStore()
|
||||
const found = store ? lookupOrcaAgentSession(store, id ?? text) : null
|
||||
if (found?.kind === 'provider-id') {
|
||||
throw providerIdRefusal(text, [found.orcaSessionId], store)
|
||||
}
|
||||
if (found?.kind === 'found' && store && id) {
|
||||
return {
|
||||
kind: 'chat',
|
||||
orcaSessionId: canonicalOrcaSessionId(id, store),
|
||||
record: found.record,
|
||||
store
|
||||
}
|
||||
}
|
||||
if (id) {
|
||||
const known = await agentHookServer.isTerminalAgentId(id)
|
||||
if (known === true) {
|
||||
return { kind: 'terminal', orcaSessionId: id }
|
||||
}
|
||||
if (known === undefined) {
|
||||
throw new AgentConversationRefusal(
|
||||
CODES.unavailable,
|
||||
`Orca can't look up terminal agent IDs right now, so it can't tell whether agent ${id} runs here. Try again in a moment.`
|
||||
)
|
||||
}
|
||||
}
|
||||
// A provider's own id (a bare UUID can also pass as an Orca ID) gets the ID to use instead.
|
||||
const linked = text ? await agentHookServer.terminalAgentIdsOfProviderSession(text) : []
|
||||
if (linked.length > 0) {
|
||||
throw providerIdRefusal(text, linked, store)
|
||||
}
|
||||
throw id
|
||||
? new AgentConversationRefusal(
|
||||
CODES.unknown,
|
||||
`No agent ${id} on this Orca. If it runs on another host, run this there or add \`--environment <host>\`.`
|
||||
)
|
||||
: new AgentConversationRefusal(
|
||||
CODES.invalidId,
|
||||
`${text || 'That'} is not an Orca session ID. Find agents' IDs with \`orca agent list\`, or copy one with Copy Orca Session ID (Copy Agent ID on a terminal).`
|
||||
)
|
||||
}
|
||||
|
||||
function providerIdRefusal(
|
||||
given: string,
|
||||
orcaSessionIds: readonly string[],
|
||||
store: AgentSessionRecordReader | null
|
||||
): AgentConversationRefusal {
|
||||
const addresses = orcaSessionIds.map(
|
||||
(id) =>
|
||||
`${ORCA_SESSION_ADDRESS_PREFIX}${isOrcaSessionId(id) ? canonicalOrcaSessionId(id, store) : id}`
|
||||
)
|
||||
return new AgentConversationRefusal(
|
||||
CODES.providerId,
|
||||
`${given} is the agent's own conversation id, not its Orca session ID. Address it as ${addresses.join(' or ')}.`
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import type {
|
||||
AgentConversationRow,
|
||||
AgentListResult
|
||||
} from '../../../shared/agent-conversations/agent-conversation-contracts'
|
||||
import type { AgentStatusState } from '../../../shared/agent-status/contracts/agent-status-types'
|
||||
import type { RuntimeWorktreePsResult } from '../../../shared/runtime-worktree-contracts'
|
||||
import { structuredAgentSessionIdFromTabId } from '../../../shared/agent-session/view/structured-agent-session-tab-id'
|
||||
|
||||
/** `worktree.ps` agent rows as one flat list of chats and terminal agents, oldest state first. */
|
||||
export function projectAgentConversationList(
|
||||
ps: RuntimeWorktreePsResult,
|
||||
filter: { worktreeId?: string; state?: AgentStatusState } = {}
|
||||
): AgentListResult {
|
||||
const agents: AgentConversationRow[] = []
|
||||
for (const worktree of ps.worktrees) {
|
||||
if (filter.worktreeId && worktree.worktreeId !== filter.worktreeId) {
|
||||
continue
|
||||
}
|
||||
for (const row of worktree.agents) {
|
||||
if (filter.state && row.state !== filter.state) {
|
||||
continue
|
||||
}
|
||||
agents.push({
|
||||
orcaSessionId: row.orcaSessionId ?? null,
|
||||
// A chat's pane key leads with its tab id.
|
||||
kind: structuredAgentSessionIdFromTabId(row.paneKey) === null ? 'terminal' : 'chat',
|
||||
agent: row.agentType,
|
||||
state: row.state,
|
||||
worktreeId: worktree.worktreeId,
|
||||
workspace: worktree.displayName,
|
||||
...(worktree.hostId ? { hostId: worktree.hostId } : {}),
|
||||
paneKey: row.paneKey,
|
||||
title: row.conversationName ?? row.displayName ?? row.taskTitle,
|
||||
lastAssistantMessage: row.lastAssistantMessage,
|
||||
updatedAt: row.updatedAt
|
||||
})
|
||||
}
|
||||
}
|
||||
return {
|
||||
agents,
|
||||
truncated: ps.truncated,
|
||||
...(ps.hostScope ? { hostScope: ps.hostScope } : {})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
import {
|
||||
AGENT_CONVERSATION_REFUSAL_CODES as CODES,
|
||||
AGENT_READ_DEFAULT_LIMIT,
|
||||
type AgentReadEntry,
|
||||
type AgentReadResult
|
||||
} from '../../../shared/agent-conversations/agent-conversation-contracts'
|
||||
import { AGENT_SESSION_HISTORY_MAX_LIMIT } from '../../../shared/agent-session/agent-session-wire'
|
||||
import type { AgentJournalRenderItem } from '../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import { isRootAgentJournalItem } from '../../../shared/agent-session/journal/agent-session-journal-producer'
|
||||
import { agentSessionPromptQuestions } from '../../../shared/agent-session/agent-session-question-answer'
|
||||
import { isActionableStructuredAgentSessionPrompt } from '../../../shared/agent-session/view/structured-agent-session-live-turn'
|
||||
import type { NativeChatMessage } from '../../../shared/native-chat/native-chat-types'
|
||||
import type { RpcContext } from '../rpc/core'
|
||||
import {
|
||||
requireInstalledStructuredHost,
|
||||
requireStructuredAgentAudience
|
||||
} from '../rpc/methods/structured-sessions/creation/structured-agent-session-gate'
|
||||
import { resolveLineageRunningSession } from '../orchestration/addressing/session-lineage/structured-session-lineage'
|
||||
import {
|
||||
canReadWorkerTranscript,
|
||||
readWorkerTranscript
|
||||
} from '../orchestration/workers/transcripts/worker-transcript-read'
|
||||
import { createWorkerOutputSourceIdentity } from '../orchestration/workers/transcripts/worker-output-cursor'
|
||||
import { agentHookServer } from '../../agent-hooks/server/agent-hook-server'
|
||||
import type { TerminalAgentTranscriptSource } from '../../agent-hooks/server/server-agent-identities'
|
||||
import { sameProviderKey } from '../../agent-hooks/identity/agent-provider-key'
|
||||
import type { ResolvedAgentConversation } from './agent-conversation-address'
|
||||
import { AgentConversationRefusal } from './agent-conversation-refusal'
|
||||
import {
|
||||
decodeReadCursor,
|
||||
encodeReadCursor,
|
||||
invalidCursor,
|
||||
type ReadCursor
|
||||
} from './agent-read-cursor'
|
||||
|
||||
type ReadRequest = { limit?: number; cursor?: string }
|
||||
|
||||
/** One page of what an agent said, by its conversation, never by a pane: a chat's own history,
|
||||
* or a terminal agent's transcript. Reading needs no running agent and never starts one.
|
||||
*
|
||||
* Trust boundary: a terminal agent's transcript is the file its own hooks reported for that
|
||||
* conversation. It is read only through that provider's transcript decoder, which yields the
|
||||
* provider's messages and nothing else; there is no raw-file fallback. Callers need the same
|
||||
* workspace permission `orchestration worker-read` uses for the same reader. */
|
||||
export async function readAgentConversation(
|
||||
ctx: RpcContext,
|
||||
resolved: ResolvedAgentConversation,
|
||||
request: ReadRequest
|
||||
): Promise<AgentReadResult> {
|
||||
const limit = request.limit ?? AGENT_READ_DEFAULT_LIMIT
|
||||
const cursor = request.cursor ? decodeReadCursor(request.cursor, resolved.orcaSessionId) : null
|
||||
return resolved.kind === 'chat'
|
||||
? readChat(ctx, resolved, limit, cursor)
|
||||
: readTerminalTranscript(ctx, resolved.orcaSessionId, limit, cursor)
|
||||
}
|
||||
|
||||
async function readChat(
|
||||
ctx: RpcContext,
|
||||
resolved: Extract<ResolvedAgentConversation, { kind: 'chat' }>,
|
||||
limit: number,
|
||||
cursor: ReadCursor | null
|
||||
): Promise<AgentReadResult> {
|
||||
const { record, store, orcaSessionId } = resolved
|
||||
if (cursor && cursor.s !== 'chat') {
|
||||
throw invalidCursor()
|
||||
}
|
||||
requireStructuredAgentAudience(ctx, record.provider)
|
||||
// The session that continues the conversation now: a /clear root reads its current chat.
|
||||
const running = resolveLineageRunningSession(store, record.sessionId)
|
||||
if (running.kind === 'other-host') {
|
||||
throw new AgentConversationRefusal(
|
||||
CODES.unavailable,
|
||||
`Agent ${orcaSessionId} runs on another host. Read it there, or add \`--environment <host>\`.`
|
||||
)
|
||||
}
|
||||
const sessionId = running.kind === 'here' ? running.sessionId : record.sessionId
|
||||
if (cursor && cursor.session !== sessionId) {
|
||||
throw sourceChanged(orcaSessionId)
|
||||
}
|
||||
const host = await requireInstalledStructuredHost(ctx, sessionId)
|
||||
const history = await host.history({
|
||||
sessionId,
|
||||
direction: cursor ? 'after' : 'tail',
|
||||
...(cursor ? { cursor: cursor.journal } : {}),
|
||||
limit: AGENT_SESSION_HISTORY_MAX_LIMIT
|
||||
})
|
||||
if (!history.ok && cursor) {
|
||||
throw sourceChanged(orcaSessionId)
|
||||
}
|
||||
const { page } = history
|
||||
const all = chatEntries(page.items, page.actionablePromptIds)
|
||||
// A first read is the latest entries; a cursor read is everything after it, so none are skipped.
|
||||
const entries = cursor ? all : all.slice(-limit)
|
||||
const next = cursor ? page.window.nextCursor : (page.liveCursor ?? page.window.newest)
|
||||
return {
|
||||
orcaSessionId,
|
||||
kind: 'chat',
|
||||
agent: record.provider,
|
||||
source: 'chat',
|
||||
entries,
|
||||
cursor: next
|
||||
? encodeReadCursor({ v: 1, id: orcaSessionId, s: 'chat', session: sessionId, journal: next })
|
||||
: null,
|
||||
limited: cursor ? page.hasNewer : page.hasOlder || all.length > limit
|
||||
}
|
||||
}
|
||||
|
||||
async function readTerminalTranscript(
|
||||
ctx: RpcContext,
|
||||
orcaSessionId: string,
|
||||
limit: number,
|
||||
cursor: ReadCursor | null
|
||||
): Promise<AgentReadResult> {
|
||||
if (cursor && cursor.s !== 'transcript') {
|
||||
throw invalidCursor()
|
||||
}
|
||||
const locate = (): Promise<TerminalAgentTranscriptSource | null | undefined> =>
|
||||
agentHookServer.terminalAgentTranscriptSource(orcaSessionId, () =>
|
||||
ctx.runtime.listSleepingAgentSessionRecords()
|
||||
)
|
||||
const source = await locate()
|
||||
if (source === undefined) {
|
||||
throw new AgentConversationRefusal(
|
||||
CODES.unavailable,
|
||||
`Orca can't look up where agent ${orcaSessionId}'s transcript is right now. Try again in a moment.`
|
||||
)
|
||||
}
|
||||
if (source === null || !canReadWorkerTranscript(source.key.agent)) {
|
||||
throw new AgentConversationRefusal(
|
||||
CODES.noTranscript,
|
||||
source === null
|
||||
? `Orca has no transcript location for agent ${orcaSessionId} right now.`
|
||||
: `Orca can't read ${source.key.agent} transcripts, so agent ${orcaSessionId} has nothing to read here.`
|
||||
)
|
||||
}
|
||||
const { key, providerSession } = source
|
||||
const transcript = await readWorkerTranscript({
|
||||
agent: key.agent,
|
||||
sessionId: providerSession.id,
|
||||
transcriptPath: providerSession.transcriptPath,
|
||||
// The key's own distro keeps a WSL agent's guest path on that guest.
|
||||
...(key.wslDistro ? { wslDistro: key.wslDistro } : {}),
|
||||
limit,
|
||||
...(cursor?.s === 'transcript'
|
||||
? { offset: cursor.p, ...(cursor.c ? { expectedBoundaryCheckpoint: cursor.c } : {}) }
|
||||
: {})
|
||||
})
|
||||
if (!transcript.ok) {
|
||||
if (cursor) {
|
||||
throw sourceChanged(orcaSessionId)
|
||||
}
|
||||
throw new AgentConversationRefusal(
|
||||
CODES.noTranscript,
|
||||
`Orca couldn't read agent ${orcaSessionId}'s transcript (${transcript.reason.replaceAll('_', ' ')}).`
|
||||
)
|
||||
}
|
||||
const sourceIdentity = createWorkerOutputSourceIdentity([
|
||||
'agent-transcript',
|
||||
key.executionHost,
|
||||
key.wslDistro,
|
||||
key.agent,
|
||||
key.providerSessionId,
|
||||
key.locator,
|
||||
transcript.filePath,
|
||||
transcript.sourceFingerprint
|
||||
])
|
||||
// The conversation must still name the file just read: its row may have moved on meanwhile.
|
||||
const after = await locate()
|
||||
if (
|
||||
(cursor?.s === 'transcript' && cursor.i !== sourceIdentity) ||
|
||||
!after ||
|
||||
!sameProviderKey(after.key, key) ||
|
||||
after.providerSession.id !== providerSession.id ||
|
||||
after.providerSession.transcriptPath !== providerSession.transcriptPath
|
||||
) {
|
||||
throw sourceChanged(orcaSessionId)
|
||||
}
|
||||
return {
|
||||
orcaSessionId,
|
||||
kind: 'terminal',
|
||||
agent: key.agent,
|
||||
source: 'transcript',
|
||||
entries: transcriptEntries(transcript.messages),
|
||||
cursor: encodeReadCursor({
|
||||
v: 1,
|
||||
id: orcaSessionId,
|
||||
s: 'transcript',
|
||||
i: sourceIdentity,
|
||||
p: transcript.nextOffset,
|
||||
...(transcript.boundaryCheckpoint ? { c: transcript.boundaryCheckpoint } : {})
|
||||
}),
|
||||
limited: transcript.limited
|
||||
}
|
||||
}
|
||||
|
||||
/** The conversation as a reader follows it: messages, the tools the agent ran, and the approvals
|
||||
* and questions it raised. Status frames, turn markers and subagent rows are left out. */
|
||||
function chatEntries(
|
||||
items: readonly AgentJournalRenderItem[],
|
||||
actionablePromptIds?: readonly string[]
|
||||
): AgentReadEntry[] {
|
||||
// An ended agent's unanswered prompts stay pending in the journal but can no longer be answered.
|
||||
const waiting = (item: AgentJournalRenderItem, state: string): boolean =>
|
||||
state === 'pending' &&
|
||||
isActionableStructuredAgentSessionPrompt(item.itemId, actionablePromptIds)
|
||||
const entries: AgentReadEntry[] = []
|
||||
for (const item of items) {
|
||||
if (!isRootAgentJournalItem(item)) {
|
||||
continue
|
||||
}
|
||||
const body = item.body
|
||||
if (body.kind === 'message') {
|
||||
const text = body.blocks
|
||||
.map((block) =>
|
||||
block.type === 'text' ? block.text : block.type === 'image-ref' ? '[image]' : ''
|
||||
)
|
||||
.filter((part) => part.length > 0)
|
||||
.join('\n')
|
||||
.trim()
|
||||
// Reasoning is the model's scratch work, folded away in the app too.
|
||||
if (text.length > 0 && body.role !== 'reasoning') {
|
||||
entries.push({ kind: 'message', role: body.role, text })
|
||||
}
|
||||
} else if (body.kind === 'status' && body.tone === 'error') {
|
||||
entries.push({ kind: 'error', text: String(body.text) })
|
||||
} else if (body.kind === 'tool-call') {
|
||||
entries.push({ kind: 'tool', name: body.name, state: body.state })
|
||||
} else if (body.kind === 'approval') {
|
||||
entries.push({
|
||||
kind: 'approval',
|
||||
text: body.title,
|
||||
pending: waiting(item, body.resolution.state)
|
||||
})
|
||||
} else if (body.kind === 'question') {
|
||||
entries.push({
|
||||
kind: 'question',
|
||||
// Grouped prompts keep their real questions in `questions`; `question` is then a heading.
|
||||
text: agentSessionPromptQuestions(body)
|
||||
.map((question) => question.question)
|
||||
.join('\n'),
|
||||
pending: waiting(item, body.resolution.state)
|
||||
})
|
||||
}
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
function transcriptEntries(messages: readonly NativeChatMessage[]): AgentReadEntry[] {
|
||||
const entries: AgentReadEntry[] = []
|
||||
for (const message of messages) {
|
||||
if (message.role === 'reasoning' || message.role === 'tool') {
|
||||
continue
|
||||
}
|
||||
const text = message.blocks
|
||||
.map((block) => (block.type === 'text' ? block.text : ''))
|
||||
.filter((part) => part.length > 0)
|
||||
.join('\n')
|
||||
.trim()
|
||||
if (text.length > 0) {
|
||||
entries.push({ kind: 'message', role: message.role, text })
|
||||
}
|
||||
for (const block of message.blocks) {
|
||||
if (block.type === 'tool-call') {
|
||||
entries.push({
|
||||
kind: 'tool',
|
||||
name: block.name,
|
||||
...(block.state ? { state: block.state } : {})
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
function sourceChanged(orcaSessionId: string): AgentConversationRefusal {
|
||||
return new AgentConversationRefusal(
|
||||
CODES.sourceChanged,
|
||||
`What agent ${orcaSessionId}'s cursor pointed into has changed (the chat was cleared or its transcript moved). Read again without --cursor.`
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { AGENT_CONVERSATION_REFUSAL_CODES as CODES } from '../../../shared/agent-conversations/agent-conversation-contracts'
|
||||
|
||||
/** A refusal an `orca agent` command shows as is; `code` is for `--json` callers. */
|
||||
export class AgentConversationRefusal extends Error {
|
||||
constructor(
|
||||
readonly code: (typeof CODES)[keyof typeof CODES],
|
||||
message: string
|
||||
) {
|
||||
super(message)
|
||||
this.name = 'AgentConversationRefusal'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { AGENT_CONVERSATION_REFUSAL_CODES as CODES } from '../../../shared/agent-conversations/agent-conversation-contracts'
|
||||
import type { AgentJournalCursor } from '../../../shared/agent-session/journal/agent-session-journal-identity'
|
||||
import { AgentConversationRefusal } from './agent-conversation-refusal'
|
||||
import { isRecord } from '../../../shared/agent-status/child-work/agent-status-child-work-value-guards'
|
||||
|
||||
const CURSOR_PREFIX = 'oar1_'
|
||||
|
||||
/** Where the next `orca agent read` continues, pinned to one agent and one source. */
|
||||
export type ReadCursor =
|
||||
| { v: 1; id: string; s: 'chat'; session: string; journal: AgentJournalCursor }
|
||||
| { v: 1; id: string; s: 'transcript'; i: string; p: number; c?: string }
|
||||
|
||||
export function encodeReadCursor(cursor: ReadCursor): string {
|
||||
return `${CURSOR_PREFIX}${Buffer.from(JSON.stringify(cursor)).toString('base64url')}`
|
||||
}
|
||||
|
||||
export function decodeReadCursor(value: string, orcaSessionId: string): ReadCursor {
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = value.startsWith(CURSOR_PREFIX)
|
||||
? JSON.parse(Buffer.from(value.slice(CURSOR_PREFIX.length), 'base64url').toString('utf8'))
|
||||
: null
|
||||
} catch {
|
||||
throw invalidCursor()
|
||||
}
|
||||
if (!isReadCursor(parsed)) {
|
||||
throw invalidCursor()
|
||||
}
|
||||
if (parsed.id !== orcaSessionId) {
|
||||
throw new AgentConversationRefusal(
|
||||
CODES.invalidCursor,
|
||||
`That cursor is from another agent's read; read agent ${orcaSessionId} without it first.`
|
||||
)
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
function isReadCursor(cursor: unknown): cursor is ReadCursor {
|
||||
if (!isRecord(cursor) || cursor.v !== 1 || typeof cursor.id !== 'string') {
|
||||
return false
|
||||
}
|
||||
if (cursor.s === 'chat') {
|
||||
return (
|
||||
typeof cursor.session === 'string' &&
|
||||
isRecord(cursor.journal) &&
|
||||
typeof cursor.journal.epoch === 'string' &&
|
||||
Number.isSafeInteger(cursor.journal.sequence)
|
||||
)
|
||||
}
|
||||
return (
|
||||
cursor.s === 'transcript' &&
|
||||
typeof cursor.i === 'string' &&
|
||||
typeof cursor.p === 'number' &&
|
||||
Number.isSafeInteger(cursor.p) &&
|
||||
cursor.p >= 0 &&
|
||||
(cursor.c === undefined || typeof cursor.c === 'string')
|
||||
)
|
||||
}
|
||||
|
||||
export function invalidCursor(): AgentConversationRefusal {
|
||||
return new AgentConversationRefusal(
|
||||
CODES.invalidCursor,
|
||||
'That read cursor is not valid. Read again without --cursor.'
|
||||
)
|
||||
}
|
||||
+11
@@ -16,6 +16,17 @@ export function canonicalOrcaSessionId(
|
||||
return createCanonicalOrcaSessionResolver(store)(orcaSessionId)
|
||||
}
|
||||
|
||||
/** A chat row's Orca session ID: its conversation's /clear root, from one lineage index. */
|
||||
export function createChatOrcaSessionIdResolver(
|
||||
store: Pick<
|
||||
AgentSessionRecordReader,
|
||||
'listRecords' | 'lineageRevision'
|
||||
> | null = readAgentSessionRecordStore()
|
||||
): (sessionId: string) => string {
|
||||
const root = createCanonicalOrcaSessionResolver(store)
|
||||
return (sessionId) => (isOrcaSessionId(sessionId) ? root(sessionId) : sessionId)
|
||||
}
|
||||
|
||||
/** Clear edges per lineage revision: mail checks ask per message, and must not rescan every record each time. */
|
||||
const clearEdgesByRevision = new WeakMap<object, ReadonlyMap<string, string>>()
|
||||
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { defineMethod } from '../../core'
|
||||
import {
|
||||
AgentListParams,
|
||||
AgentReadParams,
|
||||
AgentShowParams
|
||||
} from '../../../../../shared/rpc-contract/agent-conversation-params'
|
||||
import type {
|
||||
AgentListResult,
|
||||
AgentReadResult,
|
||||
AgentShowResult
|
||||
} from '../../../../../shared/agent-conversations/agent-conversation-contracts'
|
||||
import { projectAgentConversationList } from '../../../agent-conversations/agent-conversation-list'
|
||||
import { resolveAgentConversation } from '../../../agent-conversations/agent-conversation-address'
|
||||
import { readAgentConversation } from '../../../agent-conversations/agent-conversation-read'
|
||||
|
||||
// Listing reads every workspace's open agents, so no workspace page may hide one.
|
||||
const AGENT_LIST_WORKTREE_LIMIT = 10_000
|
||||
|
||||
/** `orca agent list/show/read`: agents by their Orca session ID, chats and terminals alike.
|
||||
* Read-only: none of these sends to, starts or wakes an agent. */
|
||||
export const AGENT_CONVERSATION_METHODS = [
|
||||
defineMethod({
|
||||
name: 'agent.list',
|
||||
permission: 'workspace',
|
||||
params: AgentListParams,
|
||||
handler: async (params, { runtime }): Promise<AgentListResult> =>
|
||||
projectAgentConversationList(await runtime.getWorktreePs(AGENT_LIST_WORKTREE_LIMIT), params)
|
||||
}),
|
||||
defineMethod({
|
||||
name: 'agent.show',
|
||||
permission: 'workspace',
|
||||
params: AgentShowParams,
|
||||
handler: async (params, { runtime }): Promise<AgentShowResult> => {
|
||||
const resolved = await resolveAgentConversation(runtime, params.id)
|
||||
const { agents } = projectAgentConversationList(
|
||||
await runtime.getWorktreePs(AGENT_LIST_WORKTREE_LIMIT)
|
||||
)
|
||||
return {
|
||||
orcaSessionId: resolved.orcaSessionId,
|
||||
kind: resolved.kind,
|
||||
places: agents.filter((row) => row.orcaSessionId === resolved.orcaSessionId)
|
||||
}
|
||||
}
|
||||
}),
|
||||
defineMethod({
|
||||
name: 'agent.read',
|
||||
permission: 'workspace',
|
||||
params: AgentReadParams,
|
||||
handler: async (params, ctx): Promise<AgentReadResult> =>
|
||||
readAgentConversation(ctx, await resolveAgentConversation(ctx.runtime, params.id), params)
|
||||
})
|
||||
]
|
||||
@@ -76,6 +76,7 @@ import { MANAGED_RUNTIME_INSTALL_METHODS } from './host-management/managed-runti
|
||||
import { ARTIFACT_METHODS } from './artifacts/artifacts'
|
||||
import { AGENT_HOOK_METHODS } from './agent-hooks/agent-hooks'
|
||||
import { AGENT_LAUNCH_METHODS } from './agent-launch/agent-launch'
|
||||
import { AGENT_CONVERSATION_METHODS } from './agent-conversations/agent-conversation-methods'
|
||||
import { CONNECTOR_METHODS } from './connectors/connector'
|
||||
import {
|
||||
LAYOUT_APPLY_METHODS,
|
||||
@@ -109,6 +110,7 @@ export const ALL_RPC_METHODS = [
|
||||
...STRUCTURED_AGENT_SESSION_AGENTS_METHODS,
|
||||
...MANAGED_RUNTIME_INSTALL_METHODS,
|
||||
...AGENT_LAUNCH_METHODS,
|
||||
...AGENT_CONVERSATION_METHODS,
|
||||
...CONNECTOR_METHODS,
|
||||
...TERMINAL_METHODS,
|
||||
...TERMINAL_ORPHAN_METHODS,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { BranchSwitchCollisionError } from '../../../git/worktrees/checkout/branch-switch-target'
|
||||
import { AgentConversationRefusal } from '../../agent-conversations/agent-conversation-refusal'
|
||||
import { SparsePresetValidationError } from '../../../../shared/worktree/creation/sparse-preset-failure'
|
||||
import {
|
||||
RECIPE_VM_REFUSAL_CODES,
|
||||
@@ -207,6 +208,9 @@ export function mapRuntimeError(id: string, meta: RpcEnvelopeMeta, error: unknow
|
||||
if (isAgentSessionRefusalError(error)) {
|
||||
return agentSessionRefusalErrorResponse(id, meta, error)
|
||||
}
|
||||
if (error instanceof AgentConversationRefusal) {
|
||||
return errorResponse(id, meta, error.code, message)
|
||||
}
|
||||
// A recipe workspace removal keeps its environment's own code (archive hook, PTY stop, selector).
|
||||
if (
|
||||
error instanceof RecipeVmWakeUnavailableError ||
|
||||
|
||||
@@ -11,6 +11,10 @@ export const EXECUTION_HOST_METHODS = [
|
||||
'ui.mutateJiraSavedFilters',
|
||||
'agent.launch',
|
||||
'agent.launchReplay',
|
||||
// Agent ids, chat records and transcripts live on the host that runs the agent.
|
||||
'agent.list',
|
||||
'agent.read',
|
||||
'agent.show',
|
||||
// Read state lives with the host whose worktree.ps reports it.
|
||||
'agentActivity.clear',
|
||||
'agentActivity.setRead',
|
||||
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
import { expect, it } from 'vitest'
|
||||
import { collectRuntimeWorktreePtyAgentSources } from './runtime-worktree-pty-agent-sources'
|
||||
import { createChatOrcaSessionIdResolver } from '../../orchestration/addressing/session-lineage/canonical-orca-session-id'
|
||||
import type { AgentSessionRecordReader } from '../../orchestration/addressing/session-lineage/structured-session-lineage'
|
||||
import {
|
||||
structuredAgentSessionPaneKey,
|
||||
structuredAgentSessionTabId
|
||||
} from '../../../../shared/agent-session/view/structured-agent-session-projection'
|
||||
import type { AgentStatusIpcPayload } from '../../../../shared/agent-status/contracts/agent-status-ipc-payload'
|
||||
|
||||
const ROOT = 'codex_0b8f2a4e_6c1d_4f7a_9e3b_5a2c8d1f0e47'
|
||||
const AFTER_CLEAR = 'codex_7d3e9b21_4a6c_4e8f_b2d5_1c9a7e3f6b08'
|
||||
|
||||
it('names a chat row by its conversation /clear root, the ID Copy Orca Session ID copies', () => {
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the resolver reads only each record's id and committed /clear.
|
||||
const store = {
|
||||
listRecords: () => [
|
||||
{
|
||||
sessionId: ROOT,
|
||||
conversationCommand: {
|
||||
command: 'clear',
|
||||
phase: 'committed',
|
||||
replacementSessionId: AFTER_CLEAR
|
||||
}
|
||||
}
|
||||
]
|
||||
} as unknown as Pick<AgentSessionRecordReader, 'listRecords'>
|
||||
const tabId = structuredAgentSessionTabId(AFTER_CLEAR)
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a chat's status row with the fields source collection reads.
|
||||
const chatRow = {
|
||||
paneKey: structuredAgentSessionPaneKey(tabId, AFTER_CLEAR),
|
||||
tabId,
|
||||
worktreeId: 'repo::/workspace',
|
||||
connectionId: null,
|
||||
structuredHost: 'owned',
|
||||
state: 'working',
|
||||
prompt: '',
|
||||
agentType: 'codex',
|
||||
receivedAt: 1,
|
||||
stateStartedAt: 1
|
||||
} as AgentStatusIpcPayload
|
||||
|
||||
const [source] = collectRuntimeWorktreePtyAgentSources({
|
||||
hookSnapshots: [chatRow],
|
||||
mirroredWorktreeIdByTabId: new Map(),
|
||||
connectedPtyEvidence: {
|
||||
tabIds: new Set(),
|
||||
paneKeys: new Set(),
|
||||
ptyIdByTerminalHandle: new Map()
|
||||
},
|
||||
chatOrcaSessionId: createChatOrcaSessionIdResolver(store)
|
||||
})
|
||||
|
||||
expect(source?.orcaSessionId).toBe(ROOT)
|
||||
})
|
||||
@@ -13,6 +13,7 @@ import type { AgentSessionStatusSummary } from '../../../../shared/agent-session
|
||||
import { structuredAgentSessionPaneKey } from '../../../../shared/agent-session/view/structured-agent-session-projection'
|
||||
import { structuredAgentSessionIdFromTabId } from '../../../../shared/agent-session/view/structured-agent-session-tab-id'
|
||||
import type { RuntimeWorktreeAgentSource } from './runtime-worktree-agent-source'
|
||||
import { createChatOrcaSessionIdResolver } from '../../orchestration/addressing/session-lineage/canonical-orca-session-id'
|
||||
|
||||
export type ConnectedPtyEvidence = {
|
||||
tabIds: ReadonlySet<string>
|
||||
@@ -44,17 +45,29 @@ export function collectRuntimeWorktreePtyAgentSources(args: {
|
||||
readStructuredSummary?: (sessionId: string) => AgentSessionStatusSummary | undefined
|
||||
mirroredWorktreeIdByTabId: ReadonlyMap<string, string>
|
||||
connectedPtyEvidence: ConnectedPtyEvidence
|
||||
/** A chat's /clear root: the Orca session ID its row names. Defaults to this host's records. */
|
||||
chatOrcaSessionId?: (sessionId: string) => string
|
||||
}): RuntimeWorktreeAgentSource[] {
|
||||
const rowSources = new Map<
|
||||
string,
|
||||
RuntimeWorktreeAgentSource & { payload: ParsedAgentStatusPayload }
|
||||
>()
|
||||
let chatOrcaSessionId = args.chatOrcaSessionId
|
||||
for (const entry of args.hookSnapshots) {
|
||||
if (entry.restoredUnconfirmed === true || entry.providerSessionOnly === true) {
|
||||
continue
|
||||
}
|
||||
const hookPayload = pickParsedAgentStatusPayload(entry)
|
||||
const children = publishedStructuredChildren(entry, args.readStructuredSummary)
|
||||
const chatSessionId =
|
||||
entry.structuredHost && entry.connectionId === null && entry.tabId
|
||||
? structuredAgentSessionIdFromTabId(entry.tabId)
|
||||
: null
|
||||
const orcaSessionId =
|
||||
entry.orcaSessionId ??
|
||||
(chatSessionId
|
||||
? (chatOrcaSessionId ??= createChatOrcaSessionIdResolver())(chatSessionId)
|
||||
: undefined)
|
||||
rowSources.set(entry.paneKey, {
|
||||
paneKey: entry.paneKey,
|
||||
ptyId: entry.terminalHandle
|
||||
@@ -69,7 +82,7 @@ export function collectRuntimeWorktreePtyAgentSources(args: {
|
||||
...(entry.workingMode ? { workingMode: entry.workingMode } : {}),
|
||||
agentType: entry.agentType ?? null,
|
||||
...(entry.providerSession?.id ? { providerSessionId: entry.providerSession.id } : {}),
|
||||
...(entry.orcaSessionId ? { orcaSessionId: entry.orcaSessionId } : {}),
|
||||
...(orcaSessionId ? { orcaSessionId } : {}),
|
||||
prompt: entry.prompt,
|
||||
lastAssistantMessage: entry.lastAssistantMessage ?? null,
|
||||
toolName: entry.toolName ?? null,
|
||||
|
||||
@@ -2,6 +2,7 @@ import { crewWorkspaceNames } from '../../orchestration/crew/crew-workspace-name
|
||||
import { isDeepStrictEqual } from 'node:util'
|
||||
import type { ExecutionHostId } from '../../../../shared/execution-host'
|
||||
import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types'
|
||||
import type { SleepingAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-resume'
|
||||
import { TerminalListHostScope } from '../../terminal/query/terminal-list-host-scope'
|
||||
|
||||
export abstract class OrcaRuntimeWithGetRuntimeId extends TerminalListHostScope {
|
||||
@@ -49,6 +50,20 @@ export abstract class OrcaRuntimeWithGetRuntimeId extends TerminalListHostScope
|
||||
}
|
||||
}
|
||||
|
||||
/** Every saved sleeping-agent record, for an explicit lookup by conversation (never per hook). */
|
||||
listSleepingAgentSessionRecords(): SleepingAgentSessionRecord[] {
|
||||
const sessions = new Set<WorkspaceSessionState>()
|
||||
for (const worktreeId of this.getKnownWorkspaceSessionWorktreeIds()) {
|
||||
const session = this.workspaceSessions.get(worktreeId)
|
||||
if (session) {
|
||||
sessions.add(session)
|
||||
}
|
||||
}
|
||||
return [...sessions].flatMap((session) =>
|
||||
Object.values(session.sleepingAgentSessionsByPaneKey ?? {})
|
||||
)
|
||||
}
|
||||
|
||||
protected getKnownWorkspaceSessionWorktreeIds(): Set<string> {
|
||||
return this.workspaceSessions.getKnownWorktreeIds()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import type { AgentStatusState } from '../agent-status/contracts/agent-status-types'
|
||||
import type { RuntimeListingHostScope } from '../runtime-listing-host-scope'
|
||||
|
||||
export type AgentConversationKind = 'chat' | 'terminal'
|
||||
|
||||
/** One open agent, chat or terminal, as `orca agent list` shows it. */
|
||||
export type AgentConversationRow = {
|
||||
/** The conversation's Orca session ID (a chat's /clear root); null for a terminal agent the
|
||||
* host has not named yet, which no command can address by ID. */
|
||||
orcaSessionId: string | null
|
||||
kind: AgentConversationKind
|
||||
agent: string | null
|
||||
state: AgentStatusState
|
||||
worktreeId: string
|
||||
workspace: string
|
||||
hostId?: string
|
||||
paneKey: string
|
||||
title: string | null
|
||||
lastAssistantMessage: string | null
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
export type AgentListResult = {
|
||||
agents: AgentConversationRow[]
|
||||
truncated: boolean
|
||||
/** The hosts this listing covered and those it did not; absent from hosts that predate it. */
|
||||
hostScope?: RuntimeListingHostScope
|
||||
}
|
||||
|
||||
export type AgentShowResult = {
|
||||
orcaSessionId: string
|
||||
kind: AgentConversationKind
|
||||
/** Where it is open now: none when it isn't open, two for one conversation resumed in two panes. */
|
||||
places: AgentConversationRow[]
|
||||
}
|
||||
|
||||
export type AgentReadEntry =
|
||||
| { kind: 'message'; role: string; text: string }
|
||||
| { kind: 'tool'; name: string; state?: string }
|
||||
| { kind: 'approval' | 'question'; text: string; pending: boolean }
|
||||
| { kind: 'error'; text: string }
|
||||
|
||||
export type AgentReadResult = {
|
||||
orcaSessionId: string
|
||||
kind: AgentConversationKind
|
||||
agent: string | null
|
||||
/** `chat`: the chat's own history; `transcript`: the terminal agent's transcript file. */
|
||||
source: 'chat' | 'transcript'
|
||||
entries: AgentReadEntry[]
|
||||
/** Pass back as `cursor` to read only what came after this page; tied to this source. */
|
||||
cursor: string | null
|
||||
/** Older entries exist that this page did not include. */
|
||||
limited: boolean
|
||||
}
|
||||
|
||||
export const AGENT_READ_DEFAULT_LIMIT = 20
|
||||
export const AGENT_READ_MAX_LIMIT = 100
|
||||
|
||||
/** Codes `orca agent` refusals carry in `--json`; the message says what to do. */
|
||||
export const AGENT_CONVERSATION_REFUSAL_CODES = {
|
||||
unknown: 'agent_unknown',
|
||||
providerId: 'agent_provider_id',
|
||||
terminalHandle: 'agent_terminal_handle',
|
||||
invalidId: 'agent_invalid_id',
|
||||
unavailable: 'agent_unavailable',
|
||||
noTranscript: 'agent_no_transcript',
|
||||
sourceChanged: 'agent_read_source_changed',
|
||||
invalidCursor: 'agent_read_cursor_invalid'
|
||||
} as const
|
||||
@@ -0,0 +1,20 @@
|
||||
import * as z from 'zod'
|
||||
import { AGENT_STATUS_STATES } from '../agent-status/contracts/agent-status-types'
|
||||
import { AGENT_READ_MAX_LIMIT } from '../agent-conversations/agent-conversation-contracts'
|
||||
import { requiredString } from './rpc-param-primitives'
|
||||
|
||||
// Not strict: a newer CLI's filters must not break an older host's list.
|
||||
export const AgentListParams = z.object({
|
||||
worktreeId: z.string().min(1).optional(),
|
||||
state: z.enum(AGENT_STATUS_STATES).optional()
|
||||
})
|
||||
|
||||
export const AgentShowParams = z.object({
|
||||
id: requiredString('Missing agent ID')
|
||||
})
|
||||
|
||||
export const AgentReadParams = z.object({
|
||||
id: requiredString('Missing agent ID'),
|
||||
limit: z.number().int().positive().max(AGENT_READ_MAX_LIMIT).optional(),
|
||||
cursor: z.string().min(1).max(4096).optional()
|
||||
})
|
||||
@@ -90,6 +90,7 @@ import {
|
||||
AgentActivityClearParams,
|
||||
AgentActivitySetReadParams
|
||||
} from './agent-activity/agent-activity-params'
|
||||
import { AgentListParams, AgentReadParams, AgentShowParams } from './agent-conversation-params'
|
||||
import { AgentLaunch, AgentLaunchReplay } from './agent-launch/agent-launch-params'
|
||||
import { AgentLaunchSettingsMutation } from './agent-launch/agent-launch-settings-params'
|
||||
import {
|
||||
@@ -857,6 +858,9 @@ export const RPC_PARAMS_BY_METHOD = {
|
||||
'accounts.zcodePlanSaveApiKey': UsageCredentialApiKeyParams,
|
||||
'agent.launch': AgentLaunch,
|
||||
'agent.launchReplay': AgentLaunchReplay,
|
||||
'agent.list': AgentListParams,
|
||||
'agent.read': AgentReadParams,
|
||||
'agent.show': AgentShowParams,
|
||||
'agentActivity.clear': AgentActivityClearParams,
|
||||
'agentActivity.setRead': AgentActivitySetReadParams,
|
||||
'agentHooks.prepareCodexForWslPane': PrepareCodexForWslPaneParams,
|
||||
|
||||
@@ -34,7 +34,7 @@ export type RuntimeWorktreeSetResult = {
|
||||
|
||||
export type RuntimeWorktreeAgentRow = {
|
||||
paneKey: string
|
||||
/** The host's Orca id for this terminal agent's conversation; old hosts omit it. */
|
||||
/** The host's Orca id for this agent's conversation (a chat's /clear root); old hosts omit it. */
|
||||
orcaSessionId?: string
|
||||
parentPaneKey: string | null
|
||||
state: AgentStatusState
|
||||
|
||||
Reference in New Issue
Block a user