jg-agent-hq 13.1.4 → 13.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +1 -1
  3. package/api/README.md +28 -22
  4. package/dist/actions/admission/admission.js +4 -4
  5. package/dist/actions/dispatch/dispatch.js +6 -2
  6. package/dist/actions/live/live.d.ts +2 -0
  7. package/dist/actions/live/live.js +22 -10
  8. package/dist/contracts/actions/types.d.ts +22 -0
  9. package/dist/contracts/actions/types.js +7 -2
  10. package/dist/contracts/browser/types.d.ts +22 -0
  11. package/dist/contracts/types.d.ts +22 -0
  12. package/dist/providers/claude/adapter.js +3 -2
  13. package/dist/providers/claude/control/constants.d.ts +1 -0
  14. package/dist/providers/claude/control/constants.js +8 -0
  15. package/dist/providers/claude/control/control.d.ts +1 -1
  16. package/dist/providers/claude/control/control.js +37 -26
  17. package/dist/providers/claude/control/index.d.ts +1 -0
  18. package/dist/providers/claude/control/index.js +2 -0
  19. package/dist/providers/claude/history/history.model.js +10 -5
  20. package/dist/providers/claude/history/types.d.ts +10 -0
  21. package/dist/providers/claude/history/types.js +16 -0
  22. package/dist/providers/claude/history/utilities.d.ts +26 -6
  23. package/dist/providers/claude/history/utilities.js +72 -19
  24. package/dist/providers/codex/adapter.js +5 -4
  25. package/dist/providers/codex/codex.js +16 -12
  26. package/dist/providers/codex/constants.d.ts +1 -0
  27. package/dist/providers/codex/constants.js +7 -0
  28. package/dist/providers/codex/types.d.ts +2 -1
  29. package/dist/providers/registry/registry.js +1 -1
  30. package/dist/providers/types.d.ts +12 -2
  31. package/dist/providers/utilities.d.ts +4 -3
  32. package/dist/providers/utilities.js +4 -3
  33. package/dist/sessions/evidence/origins.d.ts +2 -1
  34. package/dist/sessions/evidence/origins.js +2 -1
  35. package/dist/store/control/reads/reads.model.d.ts +1 -1
  36. package/dist/store/control/reads/reads.model.js +14 -3
  37. package/errors/README.md +2 -0
  38. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 13.2.0
4
+
5
+ - Allow an exact-turn `steer` to carry optional workspace files through the existing file integrity and size checks. Codex reuses its turn-start encoding; Claude sends text files as labeled text blocks and images as native image blocks. Claude rejects PDF steers before writing; ordinary PDF and text-document turn starts retain their encoding.
6
+ - Publish provider and session `inputSchema.steerMediaTypes` alongside general attachment support so consumers can determine eligibility before canceling queued work.
7
+ - Preserve Claude steer action UUIDs and extend 13.1.5's queued-prompt reader with exact original-text and source-UUID checks across history, evidence, details and images. Keep its record-before-parent behavior and original running turn. Projection version 12 rebuilds cached version-10/11 entries without a storage migration; exact acknowledged ledger and browser identity checks apply to live, saved and restarted reads.
8
+
9
+ ## 13.1.5
10
+
11
+ - Show a message Claude Code takes into a running turn, such as a steer at a tool boundary, in that turn's saved history. Claude Code saves it as a `queued_command` attachment rather than a user record, so it was missing from history and its live row never flushed. It reads as a `user-message` whose `provenance.nativeInputId` is the input the attachment names; background task notifications stay hidden. The reader's projection revision changes, so existing transcripts are indexed again on their next read.
12
+ - Flush a live input once history holds the queued record that names it, matching its turn, kind and text.
13
+
3
14
  ## 13.1.4
4
15
 
5
16
  - Correlate live user inputs against the same acknowledged native identity, turn and content fingerprint as saved history. Verified browser inputs also expose their original optional `browserActionId`, allowing an optimistic row to reconcile before the HTTP receipt arrives.
package/README.md CHANGED
@@ -75,7 +75,7 @@ Approval reads return indexed, cursor-paginated pending, answered and expired me
75
75
 
76
76
  Durable state includes `action.key`, which must stay private and accompany its SQLite database. Queued undelivered inputs and complete bounded final results are saved; ordinary input bodies and question answers are not.
77
77
 
78
- Text and skill inputs can attach up to 8 workspace files by path and media type, 16 MiB in all and 256 KiB per text file. The runtime verifies their content hashes again before queued delivery. Output schemas use native Codex turn parameters or Claude's structured-session flag; complete validated results and known token usage remain available on selected receipts after reconnect. Live previews stay bounded and explicitly mark truncation. See [file inputs and complete results](api/README.md#file-inputs-and-complete-results).
78
+ Text and skill inputs, and steers, can attach up to 8 workspace files by path and media type, 16 MiB in all and 256 KiB per text file. The runtime verifies their content hashes again before queued delivery or steering. Capabilities publish `inputSchema.steerMediaTypes` separately from general attachment support: Claude steers accept images and labeled UTF-8 text, but reject PDFs before writing. Ordinary Claude turn-start document encoding is unchanged. Output schemas use native Codex turn parameters or Claude's structured-session flag; complete validated results and known token usage remain available on selected receipts after reconnect. Live previews stay bounded and explicitly mark truncation. See [file inputs and complete results](api/README.md#file-inputs-and-complete-results).
79
79
 
80
80
  Use `suggest-thread-name --topic "Build usage" --state-root <directory>` for an editable label of up to 64 characters. Creation adds an ordinal suffix when a name is occupied, keeping the complete label within that limit. `MAX_THREAD_NAME_LENGTH` from `jg-agent-hq/contracts` is the public limit. Actions and relationships retain immutable IDs.
81
81
 
package/api/README.md CHANGED
@@ -220,7 +220,7 @@ Text and native skill inputs accept optional `files: [{ path, mediaType }]`. Pat
220
220
 
221
221
  The fixed limits are 8 references, 16,777,216 aggregate file bytes and 262,144 bytes per UTF-8 text file. Empty files, NUL-containing or invalid UTF-8 text, wrong signatures, unsupported media and oversized input are rejected. The 32,768-byte action envelope contains references, never base64. File bytes are encoded only inside the native 32 MiB frame; the file limits leave room even for worst-case JSON escaping.
222
222
 
223
- Codex supports PNG, JPEG, WebP and UTF-8 text. Images use native `image` data inputs; text files become complete text inputs labeled with their canonical path and hash. Claude supports those formats plus GIF and PDF, using native image/document blocks. Media signatures establish the declared format, not complete image/PDF validity; native decoder or model rejection remains a provider failure. `capabilities.inputSchema` includes `supportedMediaTypes`, `maxFiles`, `maxFileBytes` and `maxTextFileBytes`. Native model-specific media limitations remain native errors.
223
+ Codex supports PNG, JPEG, WebP and UTF-8 text. Images use native `image` data inputs; text files become complete text inputs labeled with their canonical path and hash. Claude supports those formats plus GIF and PDF at turn start, using native image/document blocks. Media signatures establish the declared format, not complete image/PDF validity; native decoder or model rejection remains a provider failure. `capabilities.inputSchema` includes `supportedMediaTypes`, `steerMediaTypes`, `maxFiles`, `maxFileBytes` and `maxTextFileBytes`. Native model-specific media limitations remain native errors.
224
224
 
225
225
  Select a bounded JSON `outputSchema` in session settings or, for Codex, on a message/queue entry. Schemas are limited to 8,192 serialized UTF-8 bytes, 16 levels and 1,024 visited nodes, and must be supported by the installed Zod JSON Schema validator. External references are rejected and no remote schema is retrieved. Codex sends the selected schema as `turn/start.outputSchema`. Claude starts its owned structured process with `--json-schema`; a different schema requires close and explicit resume of the same native session. Its capability descriptor marks this as `idle-restart`.
226
226
 
@@ -230,8 +230,12 @@ Selected action receipts expose nullable `result: { state, format, text, structu
230
230
 
231
231
  `usage` is nullable and contains known `inputTokens`, `outputTokens`, `cachedInputTokens` and accounting `scope`. Built-in adapters expose per-turn observations, not billable counters; missing or malformed optional usage is unavailable without invalidating essential completion evidence. Native MCP/dynamic tool calls and Claude tool blocks appear as bounded `tool` items. Truncation and live gaps remain explicit. Complete final results are authoritative retained records, not a parallel conversation cache.
232
232
 
233
+ Steer file eligibility comes from the additive `inputSchema.steerMediaTypes` array on provider and session capabilities, a subset of general `supportedMediaTypes`. An empty list permits no files; consumers must treat absent or malformed metadata as unknown before canceling queued work. Codex lists PNG, JPEG, WebP and UTF-8 text, and reuses its turn-start input items. Claude lists PNG, JPEG, WebP, GIF and UTF-8 text. Its steers encode text files as `File <path> (SHA-256 <hash>):` followed by a newline and content, alongside native image blocks; PDF steers are rejected as a whole before writing. Claude's ordinary text/PDF document blocks at turn start are unchanged. File count, individual/aggregate bytes, workspace/link restrictions, hash binding and identical replay semantics match message and queue inputs. No attachment bytes are reread on an already admitted identical replay.
234
+
233
235
  ## Claude history
234
236
 
237
+ Visible Claude queued prompts (`attachment.type: queued_command`, `commandMode: prompt`) appear as user-message items; hidden meta records retain their exclusion. The graph UUID remains the history address; the validated `source_uuid` names the input for provenance, and its original first text block supplies `nativeInputSha256`. They inherit the running turn. New Claude steers use the exact action UUID as their wire UUID; exact acknowledged provider/session/hash/target matches can establish host or browser provenance, including a late ordinary-user replay whose own UUID becomes its turn. Legacy unrelated UUIDs remain unknown. Projection version 12 rebuilds cached version-10/11 indexes within the same budgets, preserving 13.1.5 queued-record-before-parent handling; no storage migration or transcript rewrite is required. Saved queued messages reconcile their live replay only when source UUID, hash, turn and normalized body match.
238
+
235
239
  Claude connects as the runtime starts through `claude --print --input-format stream-json --output-format stream-json --verbose`. No user prompt, bare mode, permission bypass or SDK dependency is used. Runtime status reports this adapter as `idle`, `ready` or `unavailable`, with its observed CLI version. History reads need this process only until it has once started and initialized, which the runtime's start-time warm-up does: the runtime keeps that check, so history reads use the transcripts alone, while usage, models and other reads that use the connection still open it. This session-less process closes after 5 minutes without a read and opens again on the next read that needs it; while it is closed, status reports `idle` with the last observed version. An unavailable native lane requires restarting the host after resolving the native problem.
236
240
 
237
241
  The structured CLI interface has no session-history listing operation. The Claude-owned reader therefore uses direct UUID JSONL files in the native project's directory beneath `CLAUDE_CONFIG_DIR`, or the normal `.claude` directory. CLI and transcript version labels do not gate reads. Required session identity, workspace, parent links, timestamps and message roles are validated, while additive fields and mixed version labels are tolerated. Claude Code can write a hidden record, such as an attachment or a scheduled-task event, a few lines before the record it follows; the reader holds it back until that parent is indexed. An indexing batch that ends between the two leaves the hidden record to the next batch, so they stay in one turn; one whose parent the transcript doesn't hold yet, or that a whole batch from it doesn't reach, starts a turn of its own. A message whose parent is unknown is never accepted. Encoded project keys longer than 200 characters, directory/file links, malformed required fields and records larger than 32 MiB report unavailable. Discovery never recurses into subdirectories, including excluded directories. Unsupported discovered sessions have `historyState: unavailable`; they do not prevent supported sessions from being listed.
@@ -242,32 +246,32 @@ The existing SQLite worker incrementally records file identity, complete-line of
242
246
 
243
247
  Current-chain membership and turn starts are indexed as metadata. Item continuations seek those indexes; they do not walk the full chain per page. A changed branch rebuilds membership before exposing that revision. Repeated native message identities can replace content while retaining their parent; a changed parent for the same identity is an unsupported format.
244
248
 
245
- Selected history reads refresh only that file, retain incomplete tails, and detect truncation or replaced identity. Changed branch/file revisions invalidate item continuations. Only the current parent-linked conversation chain is returned. A compaction's boundary has no parent and names the record before it, which the chain follows back to the start of the conversation; when the transcript holds no such record before the boundary, as in a chat Claude Code moved into a new session, whose boundary names the old session's record, the chain starts at the boundary. Claude Code links each tool result to its own call, so parallel calls whose results finish out of order would leave the later calls and results on a side branch; such a result follows the latest record of its call's turn instead, keeping every call of the response and all their results on the chain without changing its revision. Text is reread from the native file for the selected page and normalized as plain text. Thinking blocks are left out, and a record holding only thinking is hidden, as are `<task-notification>` records and a subagent's sidechain records. Live items leave a subagent's stream frames out likewise, and those frames start no turn, though a subagent's tool results still settle the approvals it asked for. Compaction summaries, `<local-command-stdout>` output and interruption markers are `notice` items, and a slash command is a `user-message` reading `/name args`. A `!` shell input and its output are `command` items, the output's `callId` being the input's UUID. A tool call shows its native name and input, with the block's ID as `callId`, which is null for a record calling several tools; its result is a `tool` item carrying that ID, `failed` when it has `is_error` and `succeeded` otherwise. An Edit or Write result whose metadata has a `filePath` and a `structuredPatch` is a `file-change` item reading the path and its patch lines, or a created file's content, every line of which counts as added. A result Claude Code saved to a file reads `Output too large (<size>), saved to a file` followed by its preview, without the file's path. A result made of content blocks, such as a screenshot with its caption, reads as its text blocks, each image as `[Image]`. Other non-text content has explicit native block labels. The index stores each entry's presented kind and visibility, so evidence kind filters match `items` and hidden records never shorten a page. An unknown record containing content is returned as an `unsupported` item when its identity and chain are trustworthy; it cannot imply an agent response, idle state or completion. Each selected page reads at most 4 MiB of record bytes beyond its first record and returns at most 4 MiB of serialized item presentation, so a large-text page can contain fewer rows than its requested limit.
249
+ Selected history reads refresh only that file, retain incomplete tails, and detect truncation or replaced identity. Changed branch/file revisions invalidate item continuations. Only the current parent-linked conversation chain is returned. A compaction's boundary has no parent and names the record before it, which the chain follows back to the start of the conversation; when the transcript holds no such record before the boundary, as in a chat Claude Code moved into a new session, whose boundary names the old session's record, the chain starts at the boundary. Claude Code links each tool result to its own call, so parallel calls whose results finish out of order would leave the later calls and results on a side branch; such a result follows the latest record of its call's turn instead, keeping every call of the response and all their results on the chain without changing its revision. Text is reread from the native file for the selected page and normalized as plain text. Thinking blocks are left out, and a record holding only thinking is hidden, as are `<task-notification>` records and a subagent's sidechain records. A message Claude Code takes into a running turn, such as a steer it takes in at a tool boundary, is saved as a `queued_command` attachment instead of a user record; it is a `user-message` of that turn whose `provenance.nativeInputId` is the native input the attachment names, and other queued commands, such as background task notifications, stay hidden. Live items leave a subagent's stream frames out likewise, and those frames start no turn, though a subagent's tool results still settle the approvals it asked for. Compaction summaries, `<local-command-stdout>` output and interruption markers are `notice` items, and a slash command is a `user-message` reading `/name args`. A `!` shell input and its output are `command` items, the output's `callId` being the input's UUID. A tool call shows its native name and input, with the block's ID as `callId`, which is null for a record calling several tools; its result is a `tool` item carrying that ID, `failed` when it has `is_error` and `succeeded` otherwise. An Edit or Write result whose metadata has a `filePath` and a `structuredPatch` is a `file-change` item reading the path and its patch lines, or a created file's content, every line of which counts as added. A result Claude Code saved to a file reads `Output too large (<size>), saved to a file` followed by its preview, without the file's path. A result made of content blocks, such as a screenshot with its caption, reads as its text blocks, each image as `[Image]`. Other non-text content has explicit native block labels. The index stores each entry's presented kind and visibility, so evidence kind filters match `items` and hidden records never shorten a page. An unknown record containing content is returned as an `unsupported` item when its identity and chain are trustworthy; it cannot imply an agent response, idle state or completion. Each selected page reads at most 4 MiB of record bytes beyond its first record and returns at most 4 MiB of serialized item presentation, so a large-text page can contain fewer rows than its requested limit.
246
250
 
247
- File timestamps and records do not prove that a native process is idle or a turn completed. Claude file-backed thread and turn states are therefore `unknown`, with no invented completion timestamp. Explicit native custom titles are preserved; a missing title remains null. A turn starts at a message the operator sends, including a slash command; task notifications, compaction summaries, local command output, interruption markers and `!` shell records belong to the turn before them. Grouping follows parent links and is not an authoritative execution boundary. A compaction starts a new chain whose first record names the record before it, so history reads on past the compaction to the start of the conversation.
251
+ File timestamps and records do not prove that a native process is idle or a turn completed. Claude file-backed thread and turn states are therefore `unknown`, with no invented completion timestamp. Explicit native custom titles are preserved; a missing title remains null. A turn starts at a message the operator sends, including a slash command, except a message taken into a running turn, which belongs to it; task notifications, compaction summaries, local command output, interruption markers and `!` shell records belong to the turn before them. Grouping follows parent links and is not an authoritative execution boundary. A compaction starts a new chain whose first record names the record before it, so history reads on past the compaction to the start of the conversation.
248
252
 
249
253
  ## Thread control and live input
250
254
 
251
255
  Send `{ kind: 'action', action: { id, runtimeEpoch, command } }`. Generate one UUID per user intent, take the epoch from `status` or the runtime's `runtimeEpoch`, and retain the complete envelope until its receipt can be read. The validated envelope is limited to `MAX_ACTION_BYTES`, 32,768 UTF-8 bytes of its JSON, which `jg-agent-hq/contracts` exports. It is recorded before native writes. Reusing the UUID with the identical envelope returns the saved receipt without dispatch; a changed envelope conflicts. This check also works for an original request read after restart. A new UUID with an expired epoch cannot execute.
252
256
 
253
- | Action | Fields and behavior |
254
- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
255
- | `thread-create` | `provider` (a registered provider ID), `workspaceRoot`, `name`, optional `input`. Creates an empty native thread and sets its readable name before reporting acknowledgement. With `input`, the same action then sends it as the session's first message, see [first input](#first-input). |
256
- | `thread-adopt` | The same fields plus `nativeId`, `operatorConfirmation`. Explicitly records an external thread as managed. Codex accepts it unloaded or idle, between turns of a terminal that still holds it, and resumes it with optional `settings`, which it refuses while another client holds the thread; Claude requires qualified workspace history and the native idle/session-identity checks, and refuses while a terminal runs it. |
257
- | `thread-resume` | `threadId`, `operatorConfirmation`. Resumes an inactive managed thread; the runtime does not fetch its complete conversation bodies. |
258
- | `thread-recover` | `threadId`, `operatorConfirmation`, `recovery`. The recovery is `{ kind: 'resume' }` for a known native identity, `{ kind: 'attach', nativeId }` for an inspected identity after uncertain creation, or `{ kind: 'create' }` to explicitly create a fresh empty thread when no native identity was recorded. The latter can leave an empty orphan from the uncertain creation; it never repeats a message. |
259
- | `thread-rename` | `threadId`, `name`. Changes the name only after the matching native acknowledgement. |
260
- | `thread-close` | `threadId`, optional `interrupt`. Requires an idle thread and pauses its queue. Codex cleans and verifies its native terminal list before unsubscribe. Claude closes the owned CLI and proves process-group exit before releasing control. With `interrupt: true`, a thread whose turn runs is interrupted first, by the same action: its `phase` is `interrupt` until the turn ends, then `clean` and `close`; an idle thread closes as without it. |
261
- | `thread-delete` | `provider`, `workspaceRoot`, `nativeId`. Deletes a session no process runs from its provider's storage, with the runtime's records of it, and runs within its request; see [thread deletion](#thread-deletion). |
262
- | `message` | `threadId`, `input`. Starts a turn only while idle. |
263
- | `steer` | `threadId`, `expectedTurnId`, `text`. Codex uses native `turn/steer`. Claude writes the text as a user message into the exact active turn, never interrupting it, and acknowledges it when Claude replays it: at the turn's next tool boundary, where the turn takes it in and ends with one result, or, for text written while the turn's final answer streams, after the turn's result, where it runs as the session's next turn under its own UUID. Either replay acknowledges the steer against the turn it named. A Claude steer never replayed fails 30 seconds after that turn ends, and one pending when the process stops fails at once. Otherwise a finished or changed turn cannot become a new turn. |
264
- | `queue` | `threadId`, `expectedTurnId`, `input`. Saves an explicit next-turn message or skill invocation, never a permission or question answer. |
265
- | `queue-send` | `queuedActionId`. Explicitly authorizes a still-undelivered queue entry, including a queue paused by restart or interruption. |
266
- | `queue-cancel` | `queuedActionId`. Cancels only an undelivered queue entry and clears its saved body. |
267
- | `interrupt` | `threadId`, `expectedTurnId`. A native request acknowledgement leaves the thread stopping until native completion evidence arrives. |
268
- | `native-reply` | `threadId`, `expectedTurnId`, `approvalId`, `response`. Answers one exact current native request; cannot consume queue text. |
269
-
270
- Message and queue input is a closed union: `{ kind: 'text', text }` or `{ kind: 'skill', skillId, arguments }`. Text is nonempty and at most 65,536 characters; skill arguments may be empty and cap at 16,384 characters. The envelope's UTF-8 limit still applies. A selected skill is resolved through the target thread's current native catalog before admission. Unavailable, missing or disabled selections cannot dispatch. Normal text needs no catalog read. Steering retains its `text` field and exact active-turn target.
257
+ | Action | Fields and behavior |
258
+ | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
259
+ | `thread-create` | `provider` (a registered provider ID), `workspaceRoot`, `name`, optional `input`. Creates an empty native thread and sets its readable name before reporting acknowledgement. With `input`, the same action then sends it as the session's first message, see [first input](#first-input). |
260
+ | `thread-adopt` | The same fields plus `nativeId`, `operatorConfirmation`. Explicitly records an external thread as managed. Codex accepts it unloaded or idle, between turns of a terminal that still holds it, and resumes it with optional `settings`, which it refuses while another client holds the thread; Claude requires qualified workspace history and the native idle/session-identity checks, and refuses while a terminal runs it. |
261
+ | `thread-resume` | `threadId`, `operatorConfirmation`. Resumes an inactive managed thread; the runtime does not fetch its complete conversation bodies. |
262
+ | `thread-recover` | `threadId`, `operatorConfirmation`, `recovery`. The recovery is `{ kind: 'resume' }` for a known native identity, `{ kind: 'attach', nativeId }` for an inspected identity after uncertain creation, or `{ kind: 'create' }` to explicitly create a fresh empty thread when no native identity was recorded. The latter can leave an empty orphan from the uncertain creation; it never repeats a message. |
263
+ | `thread-rename` | `threadId`, `name`. Changes the name only after the matching native acknowledgement. |
264
+ | `thread-close` | `threadId`, optional `interrupt`. Requires an idle thread and pauses its queue. Codex cleans and verifies its native terminal list before unsubscribe. Claude closes the owned CLI and proves process-group exit before releasing control. With `interrupt: true`, a thread whose turn runs is interrupted first, by the same action: its `phase` is `interrupt` until the turn ends, then `clean` and `close`; an idle thread closes as without it. |
265
+ | `thread-delete` | `provider`, `workspaceRoot`, `nativeId`. Deletes a session no process runs from its provider's storage, with the runtime's records of it, and runs within its request; see [thread deletion](#thread-deletion). |
266
+ | `message` | `threadId`, `input`. Starts a turn only while idle. |
267
+ | `steer` | `threadId`, `expectedTurnId`, `text`, optional top-level `files` (`InputFileSchema[]`). Codex uses native `turn/steer`. Claude writes text and qualified files as a user message into the exact active turn, never interrupting it, and acknowledges it when Claude replays it: at the turn's next tool boundary, where the turn takes it in and ends with one result, or, for text written while the turn's final answer streams, after the turn's result, where it runs as the session's next turn under its own UUID. Either replay acknowledges the steer against the turn it named. A Claude steer never replayed fails 30 seconds after that turn ends, and one pending when the process stops fails at once. Otherwise a finished or changed turn cannot become a new turn. Unlisted media types reject the complete input before native writing. No skills or settings are accepted. |
268
+ | `queue` | `threadId`, `expectedTurnId`, `input`. Saves an explicit next-turn message or skill invocation, never a permission or question answer. |
269
+ | `queue-send` | `queuedActionId`. Explicitly authorizes a still-undelivered queue entry, including a queue paused by restart or interruption. |
270
+ | `queue-cancel` | `queuedActionId`. Cancels only an undelivered queue entry and clears its saved body. |
271
+ | `interrupt` | `threadId`, `expectedTurnId`. A native request acknowledgement leaves the thread stopping until native completion evidence arrives. |
272
+ | `native-reply` | `threadId`, `expectedTurnId`, `approvalId`, `response`. Answers one exact current native request; cannot consume queue text. |
273
+
274
+ Message and queue input is a closed union: `{ kind: 'text', text }` or `{ kind: 'skill', skillId, arguments }`. Text is nonempty and at most 65,536 characters; skill arguments may be empty and cap at 16,384 characters. The envelope's UTF-8 limit still applies. A selected skill is resolved through the target thread's current native catalog before admission. Unavailable, missing or disabled selections cannot dispatch. Normal text needs no catalog read. Steering retains its `text` field and exact active-turn target, adding only optional top-level `files`. Text-only steers remain unchanged; skills and turn settings cannot be steered.
271
275
 
272
276
  Names use lowercase ASCII letters, digits and hyphens, start with a letter or digit, and have at most 64 characters, the public `MAX_THREAD_NAME_LENGTH` from `jg-agent-hq/contracts`. The same bound applies to create, adopt, rename and managed-thread responses. Names are unique without regard to case in one state directory. Creation and adoption resolve collisions atomically with ordinal suffixes such as `build-usage-2`, truncating the base to keep the complete name within 64 characters. Explicit rename rejects an occupied or pending name. Provider/native-session pairs remain unique. At most 32 native sessions are controlled concurrently; close idle sessions to release capacity. Native discovery remains independent of that limit. Confirm that other native CLI controllers are closed before adoption, resume or recovery. An unloaded native status cannot prove another CLI has stopped. The runtime provides exclusive coordination within one canonical state directory; it does not impose a global lock on independent CLIs. Recovery is permitted only after the producing runtime has stopped and its ownership evidence has been inspected.
273
277
 
@@ -369,7 +373,7 @@ The installed CLI exposes `suggest-thread-name --topic <topic>`. Suggestions nor
369
373
 
370
374
  Control pages default to 32 and cap at 128. Seek cursors are bound to their complete query and ordering. Reads recheck allowed workspaces. Rejected controls retain their known thread association, and native availability failures appear in each affected thread's replay. Lifecycle replay contains metadata, not token or tool output. Each provider has a bounded native lifecycle backlog; overflow stops that source and marks its state uncertain rather than losing events silently. Live items don't count toward it. The runtime recognizes a repeated lifecycle observation within one runtime; startup forgets the observations earlier runtimes recorded. Other providers retain their independent connection and admission state.
371
375
 
372
- Live item presentation is bounded to 128 items per cached thread, 32 windows and 4 MiB of serialized presentation across the runtime, including escaped text and identifiers. This leaves room inside the IPC response limit. Display text uses the same truncation contract as native history. Eviction, an unavailable window or missing chunks sets `hasGap`. Completed items remain `awaiting-flush` after thread closure until a native history page holds the same item, with exactly matching normalized content or, for an item with an outcome, the same final outcome, or the bounded cache evicts them. The outcome is enough because Codex shortens long command output when it saves it. An item still streaming when its turn ended, such as a message an interrupt or a Codex steer cut, stays `awaiting-flush` until a native history page holds an item of that turn, since the provider may never save it; the history then shows what was saved of it. A client's `items` read is one such page, and when a turn ends the runtime reads that turn's own history too, newest first and at most 8 pages of 128, until none of its finished items remain, so the window doesn't wait on a client that never reads them. Codex's saved state can trail its turn's end, so a turn whose items remain is read once more 2 seconds later; a failed read leaves them to the next history read. A client that shows live items should therefore expect them to leave the window before its own history read holds them. Read persisted history and the live window together after reconnect; a process restart cannot reconstruct unflushed in-memory content.
376
+ Live item presentation is bounded to 128 items per cached thread, 32 windows and 4 MiB of serialized presentation across the runtime, including escaped text and identifiers. This leaves room inside the IPC response limit. Display text uses the same truncation contract as native history. Eviction, an unavailable window or missing chunks sets `hasGap`. Completed items remain `awaiting-flush` after thread closure until a native history page holds the same item, with exactly matching normalized content or, for an item with an outcome, the same final outcome, or the bounded cache evicts them. A message Claude Code saved as a queued command matches the live input its `provenance.nativeInputId` names. The outcome is enough because Codex shortens long command output when it saves it. An item still streaming when its turn ended, such as a message an interrupt or a Codex steer cut, stays `awaiting-flush` until a native history page holds an item of that turn, since the provider may never save it; the history then shows what was saved of it. A client's `items` read is one such page, and when a turn ends the runtime reads that turn's own history too, newest first and at most 8 pages of 128, until none of its finished items remain, so the window doesn't wait on a client that never reads them. Codex's saved state can trail its turn's end, so a turn whose items remain is read once more 2 seconds later; a failed read leaves them to the next history read. A client that shows live items should therefore expect them to leave the window before its own history read holds them. Read persisted history and the live window together after reconnect; a process restart cannot reconstruct unflushed in-memory content.
373
377
 
374
378
  Items expose only normalized presentation fields, and one mapping per provider presents `items`, live items and `session-evidence` alike, as the provider's CLI shows them. Kinds are `user-message`, `agent-message`, `command`, `tool`, `file-change`, `notice` and `unsupported`. `callId` pairs a tool call with its result, or is null. `outcome` is `succeeded`, `failed`, or null when unknown or still running. `files` lists each file a file change touched, at most 128, with its added and removed lines, and is empty on other items. `outcome` and `files` come from the full native record, so `textLimit` never changes them. Unknown native kinds report `unsupported` without copying arbitrary payloads. Display text is bounded to 65,536 UTF-16 code units without splitting a surrogate pair; `isTruncated` reports omissions. An unsupported or oversized native transport frame fails explicitly. `createdAt` is the item's time in Unix milliseconds, or null when the provider records none. A Claude item takes its record's `timestamp`, and a live one the time its frame arrived. A Codex item takes its own native lifecycle timestamps, already in milliseconds: operator input prefers `startedAtMs`, and other items prefer `completedAtMs`, using the other item timestamp when the preferred one is missing. History entries and live notifications use the same mapping, with entry/notification metadata preferred over the matching embedded item field. Missing item timestamps remain null; turn times and observation times are never substituted. History pages and item details need no additional turn reads for timing.
375
379
 
@@ -461,6 +465,8 @@ Live reads accept `afterRevision`. A matching revision returns `unchanged: true`
461
465
 
462
466
  The operation matrix describes the implemented native interfaces and their explicit unavailable surfaces. Executed qualification is narrower than every possible model, configuration and account state. Native versions below are observations, never admission rules.
463
467
 
468
+ On 2026-11-07, Codex 0.167.0 consumed image and labeled text input through `turn/steer` in the running turn. Claude Code 2.1.319 with claude-opus-5-5 and normal `auto` permissions consumed text/PDF document blocks at turn start, and image plus labeled text blocks in the original running turn. A native PDF steer was dropped, so it is excluded from Claude's steer media list. The repaired runtime journey verified exact browser/action/source identity, original first-text hash, separate persisted prompt blocks, unchanged saved image bytes, live/history reconciliation, and provenance after restart without resending. The queued prompt's graph UUID differs from its input's source UUID. Its projection rebuild was also checked against the retained real transcript and an older cached index. These checks establish the observed native shapes and provider versions, without using an origin override or changing turn-start encoding.
469
+
464
470
  | Area | Executed evidence | Boundary |
465
471
  | --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
466
472
  | Provider integration | Public contract tests isolate an unavailable provider and tolerate additive fields and future version labels. Native lifecycle, configuration and file checks are listed in their sections above. | Other CLI versions need their own native qualification. |
@@ -224,16 +224,16 @@ export const createAdmission = (context, dispatcher) => {
224
224
  conflict();
225
225
  prompt.native.validate(command.response);
226
226
  }
227
- if (command.kind === 'message' || command.kind === 'queue') {
227
+ if (command.kind === 'message' || command.kind === 'queue' || command.kind === 'steer') {
228
228
  const thread = await store.call('reads', 'getThread', command.threadId);
229
229
  if (!thread?.nativeId)
230
230
  conflict();
231
231
  // a terminal that resumed a Claude session HQ runs has it now, so HQ sends nothing
232
232
  if (thread.provider === 'claude' && claudeTerminalOf(thread.nativeId))
233
233
  conflict();
234
- input = await prepareInput(command.input, command.settings ?? {}, thread.workspaceRoot, {
235
- threadId: command.threadId,
236
- });
234
+ input = await prepareInput(command.kind === 'steer'
235
+ ? { kind: 'text', text: command.text, files: command.files }
236
+ : command.input, command.kind === 'steer' ? {} : (command.settings ?? {}), thread.workspaceRoot, { threadId: command.threadId });
237
237
  await control.validateInput(thread.nativeId, input);
238
238
  prepared.input = input;
239
239
  }
@@ -224,9 +224,13 @@ export const createDispatch = (context) => {
224
224
  });
225
225
  }
226
226
  else if (phase === 'steer') {
227
- if (!nativeId || command?.kind !== 'steer')
227
+ if (!thread || !nativeId || command?.kind !== 'steer' || !input)
228
228
  conflict();
229
- const nativeTurnId = await control.steer(requestId, nativeId, command.expectedTurnId, command.text);
229
+ hasDispatched = false;
230
+ const files = await readInputFiles(input.files, thread.workspaceRoot, roots);
231
+ await control.validateInput(nativeId, input);
232
+ hasDispatched = true;
233
+ const nativeTurnId = await control.steer(requestId, nativeId, command.expectedTurnId, command.text, files);
230
234
  next = await apply({ kind: 'steer-accepted', actionId: receipt.id, phase, nativeTurnId });
231
235
  }
232
236
  else if (phase === 'interrupt') {
@@ -50,6 +50,8 @@ export declare class LiveItems {
50
50
  * content, or, for an item with an outcome, the same final outcome, since a provider can shorten
51
51
  * long output when it saves it, as Codex does. An item its turn ended before the provider
52
52
  * finished goes once persisted history holds that turn, which then shows what was saved of it.
53
+ * A message saved under another record than the live input it came from, as Claude Code saves a
54
+ * message sent while a turn ran, matches that input by the native input it names.
53
55
  */
54
56
  reconcile(nativeId: string, persisted: IHistoryItem[]): void;
55
57
  /**
@@ -152,6 +152,8 @@ export class LiveItems {
152
152
  * content, or, for an item with an outcome, the same final outcome, since a provider can shorten
153
153
  * long output when it saves it, as Codex does. An item its turn ended before the provider
154
154
  * finished goes once persisted history holds that turn, which then shows what was saved of it.
155
+ * A message saved under another record than the live input it came from, as Claude Code saves a
156
+ * message sent while a turn ran, matches that input by the native input it names.
155
157
  */
156
158
  reconcile(nativeId, persisted) {
157
159
  const thread = this.__threads.get(nativeId);
@@ -165,16 +167,26 @@ export class LiveItems {
165
167
  thread.revision = this.__change();
166
168
  }
167
169
  for (const item of persisted) {
168
- const key = JSON.stringify([item.turnId, item.nativeId]);
169
- const entry = thread.items.get(key);
170
- if (entry?.isComplete &&
171
- entry.item.nativeType === item.nativeType &&
172
- entry.item.kind === item.kind &&
173
- ((entry.item.text === item.text && entry.item.isTruncated === item.isTruncated) ||
174
- (item.outcome !== null && entry.item.outcome === item.outcome))) {
175
- this.__bytes -= entry.bytes;
176
- thread.items.delete(key);
177
- thread.revision = this.__change();
170
+ const { nativeInputId } = item.provenance;
171
+ const liveIds = item.kind === 'user-message' && nativeInputId !== null && nativeInputId !== item.nativeId
172
+ ? [item.nativeId, nativeInputId]
173
+ : [item.nativeId];
174
+ for (const liveId of liveIds) {
175
+ const key = JSON.stringify([item.turnId, liveId]);
176
+ const entry = thread.items.get(key);
177
+ if (entry?.isComplete &&
178
+ (liveId === item.nativeId ||
179
+ (item.provenance.nativeInputSha256 !== null &&
180
+ entry.item.provenance.nativeInputId === nativeInputId &&
181
+ entry.item.provenance.nativeInputSha256 === item.provenance.nativeInputSha256)) &&
182
+ entry.item.nativeType === item.nativeType &&
183
+ entry.item.kind === item.kind &&
184
+ ((entry.item.text === item.text && entry.item.isTruncated === item.isTruncated) ||
185
+ (item.outcome !== null && entry.item.outcome === item.outcome))) {
186
+ this.__bytes -= entry.bytes;
187
+ thread.items.delete(key);
188
+ thread.revision = this.__change();
189
+ }
178
190
  }
179
191
  }
180
192
  }
@@ -180,6 +180,17 @@ export declare const ActionCommandSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
180
180
  }, z.core.$strict>>;
181
181
  }, z.core.$strict>, z.ZodObject<{
182
182
  text: z.ZodString;
183
+ files: z.ZodOptional<z.ZodArray<z.ZodObject<{
184
+ path: z.ZodString;
185
+ mediaType: z.ZodEnum<{
186
+ "image/png": "image/png";
187
+ "image/jpeg": "image/jpeg";
188
+ "image/webp": "image/webp";
189
+ "image/gif": "image/gif";
190
+ "application/pdf": "application/pdf";
191
+ "text/plain": "text/plain";
192
+ }>;
193
+ }, z.core.$strict>>>;
183
194
  threadId: z.ZodUUID;
184
195
  expectedTurnId: z.ZodString;
185
196
  kind: z.ZodLiteral<"steer">;
@@ -429,6 +440,17 @@ export declare const ActionEnvelopeSchema: z.ZodObject<{
429
440
  }, z.core.$strict>>;
430
441
  }, z.core.$strict>, z.ZodObject<{
431
442
  text: z.ZodString;
443
+ files: z.ZodOptional<z.ZodArray<z.ZodObject<{
444
+ path: z.ZodString;
445
+ mediaType: z.ZodEnum<{
446
+ "image/png": "image/png";
447
+ "image/jpeg": "image/jpeg";
448
+ "image/webp": "image/webp";
449
+ "image/gif": "image/gif";
450
+ "application/pdf": "application/pdf";
451
+ "text/plain": "text/plain";
452
+ }>;
453
+ }, z.core.$strict>>>;
432
454
  threadId: z.ZodUUID;
433
455
  expectedTurnId: z.ZodString;
434
456
  kind: z.ZodLiteral<"steer">;
@@ -4,7 +4,7 @@ import { ProviderIdSchema } from '../providers/index.js';
4
4
  import { SessionSettingsSchema, TurnSettingsSchema } from '../configuration/index.js';
5
5
  import { MessageInputSchema, NativeSkillInputSchema } from '../skills/index.js';
6
6
  import { NativeIdSchema, NativeLineageSchema } from '../identities/index.js';
7
- import { BoundInputFileSchema, MAX_INPUT_FILES } from '../inputs/index.js';
7
+ import { BoundInputFileSchema, InputFileSchema, MAX_INPUT_FILES } from '../inputs/index.js';
8
8
  import { TurnResultSchema, OutputSchemaSchema } from '../results/index.js';
9
9
  // queue payloads preserve the exact native selection, content hashes and turn options
10
10
  export const PreparedInputSchema = z.object({
@@ -76,7 +76,12 @@ export const ActionCommandSchema = z.discriminatedUnion('kind', [
76
76
  input: MessageInputSchema,
77
77
  settings: TurnSettingsSchema.optional(),
78
78
  }),
79
- z.strictObject({ kind: z.literal('steer'), ...ActiveTargetFields, text: TextSchema }),
79
+ z.strictObject({
80
+ kind: z.literal('steer'),
81
+ ...ActiveTargetFields,
82
+ text: TextSchema,
83
+ files: z.array(InputFileSchema).max(MAX_INPUT_FILES).optional(),
84
+ }),
80
85
  z.strictObject({
81
86
  kind: z.literal('queue'),
82
87
  ...ActiveTargetFields,
@@ -158,6 +158,17 @@ export declare const BrowserCommandSchema: z.ZodDiscriminatedUnion<[z.ZodObject<
158
158
  }, z.core.$strict>>;
159
159
  }, z.core.$strict>, z.ZodObject<{
160
160
  text: z.ZodString;
161
+ files: z.ZodOptional<z.ZodArray<z.ZodObject<{
162
+ path: z.ZodString;
163
+ mediaType: z.ZodEnum<{
164
+ "image/png": "image/png";
165
+ "image/jpeg": "image/jpeg";
166
+ "image/webp": "image/webp";
167
+ "image/gif": "image/gif";
168
+ "application/pdf": "application/pdf";
169
+ "text/plain": "text/plain";
170
+ }>;
171
+ }, z.core.$strict>>>;
161
172
  threadId: z.ZodUUID;
162
173
  expectedTurnId: z.ZodString;
163
174
  kind: z.ZodLiteral<"steer">;
@@ -413,6 +424,17 @@ export declare const BrowserActionSchema: z.ZodObject<{
413
424
  }, z.core.$strict>>;
414
425
  }, z.core.$strict>, z.ZodObject<{
415
426
  text: z.ZodString;
427
+ files: z.ZodOptional<z.ZodArray<z.ZodObject<{
428
+ path: z.ZodString;
429
+ mediaType: z.ZodEnum<{
430
+ "image/png": "image/png";
431
+ "image/jpeg": "image/jpeg";
432
+ "image/webp": "image/webp";
433
+ "image/gif": "image/gif";
434
+ "application/pdf": "application/pdf";
435
+ "text/plain": "text/plain";
436
+ }>;
437
+ }, z.core.$strict>>>;
416
438
  threadId: z.ZodUUID;
417
439
  expectedTurnId: z.ZodString;
418
440
  kind: z.ZodLiteral<"steer">;
@@ -278,6 +278,17 @@ export declare const HqRequestSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
278
278
  }, z.core.$strict>>;
279
279
  }, z.core.$strict>, z.ZodObject<{
280
280
  text: z.ZodString;
281
+ files: z.ZodOptional<z.ZodArray<z.ZodObject<{
282
+ path: z.ZodString;
283
+ mediaType: z.ZodEnum<{
284
+ "image/png": "image/png";
285
+ "image/jpeg": "image/jpeg";
286
+ "image/webp": "image/webp";
287
+ "image/gif": "image/gif";
288
+ "application/pdf": "application/pdf";
289
+ "text/plain": "text/plain";
290
+ }>;
291
+ }, z.core.$strict>>>;
281
292
  threadId: z.ZodUUID;
282
293
  expectedTurnId: z.ZodString;
283
294
  kind: z.ZodLiteral<"steer">;
@@ -2774,6 +2785,17 @@ export declare const IpcRequestSchema: z.ZodObject<{
2774
2785
  }, z.core.$strict>>;
2775
2786
  }, z.core.$strict>, z.ZodObject<{
2776
2787
  text: z.ZodString;
2788
+ files: z.ZodOptional<z.ZodArray<z.ZodObject<{
2789
+ path: z.ZodString;
2790
+ mediaType: z.ZodEnum<{
2791
+ "image/png": "image/png";
2792
+ "image/jpeg": "image/jpeg";
2793
+ "image/webp": "image/webp";
2794
+ "image/gif": "image/gif";
2795
+ "application/pdf": "application/pdf";
2796
+ "text/plain": "text/plain";
2797
+ }>;
2798
+ }, z.core.$strict>>>;
2777
2799
  threadId: z.ZodUUID;
2778
2800
  expectedTurnId: z.ZodString;
2779
2801
  kind: z.ZodLiteral<"steer">;
@@ -4,7 +4,7 @@ import { SessionSettingsSchema, TurnSettingsSchema, } from '../../contracts/inde
4
4
  import { buildProviderCapabilities, MODEL_CATALOG_UNAVAILABLE, SUPPORTED_PROVIDER_OPERATION, } from '../index.js';
5
5
  import { HQ_ERRORS } from '../../errors/index.js';
6
6
  import { createClaudeProvider } from './claude.js';
7
- import { createClaudeControl } from './control/index.js';
7
+ import { CLAUDE_STEER_MEDIA_TYPES, createClaudeControl } from './control/index.js';
8
8
  import { deleteTranscript } from './history/index.js';
9
9
  /**
10
10
  * Combines native Claude reads and persistent controls behind the provider boundary.
@@ -66,6 +66,7 @@ export const createClaudeProviderFactory = (store, additionalDirectories) => ({
66
66
  'application/pdf',
67
67
  'text/plain',
68
68
  ],
69
+ steerMediaTypes: CLAUDE_STEER_MEDIA_TYPES,
69
70
  configurationSchema: {
70
71
  session: z.json().parse(z.toJSONSchema(SessionSettingsSchema.omit({ sandbox: true }))),
71
72
  turn: z.json().parse(z.toJSONSchema(TurnSettingsSchema.omit({ outputSchema: true }))),
@@ -131,7 +132,7 @@ export const createClaudeProviderFactory = (store, additionalDirectories) => ({
131
132
  control.validateInput(nativeId, input.settings);
132
133
  },
133
134
  startTurn: (requestId, nativeId, text, _skill, settings, files, call) => control.startTurn(requestId, nativeId, text, settings, call.signal, files),
134
- steer: (requestId, nativeId, expectedTurnId, text) => control.steer(requestId, nativeId, expectedTurnId, text),
135
+ steer: (requestId, nativeId, expectedTurnId, text, files) => control.steer(requestId, nativeId, expectedTurnId, text, files),
135
136
  interrupt: (requestId, nativeId, nativeTurnId) => control.interrupt(requestId, nativeId, nativeTurnId),
136
137
  cleanThread: (requestId, nativeId) => control.stopSession(requestId, nativeId),
137
138
  releaseThread: (requestId, nativeId) => control.releaseSession(requestId, nativeId),
@@ -0,0 +1 @@
1
+ export declare const CLAUDE_STEER_MEDIA_TYPES: readonly string[];
@@ -0,0 +1,8 @@
1
+ // qualified mid-turn attachments; Claude Code 2.1.319 drops PDF document blocks
2
+ export const CLAUDE_STEER_MEDIA_TYPES = [
3
+ 'image/png',
4
+ 'image/jpeg',
5
+ 'image/webp',
6
+ 'image/gif',
7
+ 'text/plain',
8
+ ];
@@ -147,7 +147,7 @@ export declare const createClaudeControl: (additionalDirectories?: string[]) =>
147
147
  * - JG_AGENT_HQ_CLAUDE_FAILED: The Claude integration failed
148
148
  * - JG_AGENT_HQ_TRANSPORT_FAILED: The HQ transport failed
149
149
  */
150
- steer(_requestId: string, nativeId: string, turnId: string, text: string): Promise<string>;
150
+ steer(requestId: string, nativeId: string, turnId: string, text: string, files?: IProviderInputFile[]): Promise<string>;
151
151
  /**
152
152
  * Requests interruption of the exact active turn, HQ input's or one Claude started; completion
153
153
  * arrives separately.
@@ -2,13 +2,36 @@ import { randomUUID } from 'node:crypto';
2
2
  import { Exception } from 'jg-exception';
3
3
  import { delay, isEqual } from 'jg-utilities';
4
4
  import { z } from 'zod';
5
+ import { ActionEnvelopeSchema } from '../../../contracts/index.js';
5
6
  import { parseActionRequest } from '../../utilities.js';
6
7
  import { capabilityUnavailable } from '../../registry/index.js';
7
8
  import { toClaudeConfiguration } from '../configuration/index.js';
8
9
  import { createClaudeRpc } from '../rpc.js';
9
10
  import { HQ_ERRORS, isCleanupUnconfirmed } from '../../../errors/index.js';
11
+ import { CLAUDE_STEER_MEDIA_TYPES } from './constants.js';
10
12
  import { failSteers, getActiveTurn, receiveClaudeMessage, setBackgroundCommands, } from './stream.js';
11
13
  import { toClaudeSkills } from './skills.js';
14
+ /** Keeps turn-start document encoding and uses labeled text for mid-turn text files. */
15
+ const toFileBlocks = (files, isSteer = false) => files.map((file) => {
16
+ if (file.mediaType === 'text/plain') {
17
+ const text = new TextDecoder('utf-8', { fatal: true }).decode(file.content);
18
+ return isSteer
19
+ ? { type: 'text', text: `File ${file.path} (SHA-256 ${file.sha256}):\n${text}` }
20
+ : {
21
+ type: 'document',
22
+ source: { type: 'text', media_type: 'text/plain', data: text },
23
+ title: file.path,
24
+ };
25
+ }
26
+ return {
27
+ type: file.mediaType.startsWith('image/') ? 'image' : 'document',
28
+ source: {
29
+ type: 'base64',
30
+ media_type: file.mediaType,
31
+ data: Buffer.from(file.content).toString('base64'),
32
+ },
33
+ };
34
+ });
12
35
  // a session idle this long since its last turn ended gives up its process until it is needed
13
36
  const IDLE_STOP_SECONDS = 3_600;
14
37
  /**
@@ -435,29 +458,7 @@ export const createClaudeControl = (additionalDirectories = []) => {
435
458
  session_id: nativeId,
436
459
  message: {
437
460
  role: 'user',
438
- content: files.length
439
- ? [
440
- { type: 'text', text },
441
- ...files.map((file) => file.mediaType === 'text/plain'
442
- ? {
443
- type: 'document',
444
- source: {
445
- type: 'text',
446
- media_type: 'text/plain',
447
- data: new TextDecoder('utf-8', { fatal: true }).decode(file.content),
448
- },
449
- title: file.path,
450
- }
451
- : {
452
- type: file.mediaType.startsWith('image/') ? 'image' : 'document',
453
- source: {
454
- type: 'base64',
455
- media_type: file.mediaType,
456
- data: Buffer.from(file.content).toString('base64'),
457
- },
458
- }),
459
- ]
460
- : text,
461
+ content: files.length ? [{ type: 'text', text }, ...toFileBlocks(files)] : text,
461
462
  },
462
463
  parent_tool_use_id: null,
463
464
  })
@@ -479,7 +480,12 @@ export const createClaudeControl = (additionalDirectories = []) => {
479
480
  * - JG_AGENT_HQ_CLAUDE_FAILED: The Claude integration failed
480
481
  * - JG_AGENT_HQ_TRANSPORT_FAILED: The HQ transport failed
481
482
  */
482
- async steer(_requestId, nativeId, turnId, text) {
483
+ async steer(requestId, nativeId, turnId, text, files = []) {
484
+ const parsedId = ActionEnvelopeSchema.shape.id.safeParse(requestId.endsWith(':steer') ? requestId.slice(0, -':steer'.length) : null);
485
+ if (!parsedId.success)
486
+ conflict();
487
+ if (files.some((file) => !CLAUDE_STEER_MEDIA_TYPES.includes(file.mediaType)))
488
+ capabilityUnavailable();
483
489
  // a parked session is idle, so it has no turn to steer
484
490
  return withSession(nativeId, false, (session) => {
485
491
  if (getActiveTurn(session)?.id !== turnId)
@@ -487,14 +493,19 @@ export const createClaudeControl = (additionalDirectories = []) => {
487
493
  if (session.isClosing || !session.connection?.isAvailable)
488
494
  unavailable();
489
495
  return new Promise((resolve, reject) => {
490
- const id = randomUUID();
496
+ const id = parsedId.data;
491
497
  session.steers.set(id, { id, turnId, resolve, reject });
492
498
  void session
493
499
  .connection.write({
494
500
  type: 'user',
495
501
  uuid: id,
496
502
  session_id: nativeId,
497
- message: { role: 'user', content: text },
503
+ message: {
504
+ role: 'user',
505
+ content: files.length
506
+ ? [{ type: 'text', text }, ...toFileBlocks(files, true)]
507
+ : text,
508
+ },
498
509
  parent_tool_use_id: null,
499
510
  })
500
511
  .catch((error) => {
@@ -1,3 +1,4 @@
1
1
  export { createClaudeControl } from './control.js';
2
2
  export type { IClaudeControlEvents, IClaudeFastMode } from './types.js';
3
+ export { CLAUDE_STEER_MEDIA_TYPES } from './constants.js';
3
4
  export { toClaudeSkills } from './skills.js';