jg-agent-hq 13.1.5 → 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 (37) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +1 -1
  3. package/api/README.md +25 -19
  4. package/dist/actions/admission/admission.js +4 -4
  5. package/dist/actions/dispatch/dispatch.js +6 -2
  6. package/dist/actions/live/live.js +4 -0
  7. package/dist/contracts/actions/types.d.ts +22 -0
  8. package/dist/contracts/actions/types.js +7 -2
  9. package/dist/contracts/browser/types.d.ts +22 -0
  10. package/dist/contracts/types.d.ts +22 -0
  11. package/dist/providers/claude/adapter.js +3 -2
  12. package/dist/providers/claude/control/constants.d.ts +1 -0
  13. package/dist/providers/claude/control/constants.js +8 -0
  14. package/dist/providers/claude/control/control.d.ts +1 -1
  15. package/dist/providers/claude/control/control.js +37 -26
  16. package/dist/providers/claude/control/index.d.ts +1 -0
  17. package/dist/providers/claude/control/index.js +2 -0
  18. package/dist/providers/claude/history/history.model.js +1 -1
  19. package/dist/providers/claude/history/types.d.ts +5 -2
  20. package/dist/providers/claude/history/types.js +5 -2
  21. package/dist/providers/claude/history/utilities.d.ts +6 -0
  22. package/dist/providers/claude/history/utilities.js +40 -14
  23. package/dist/providers/codex/adapter.js +5 -4
  24. package/dist/providers/codex/codex.js +16 -12
  25. package/dist/providers/codex/constants.d.ts +1 -0
  26. package/dist/providers/codex/constants.js +7 -0
  27. package/dist/providers/codex/types.d.ts +2 -1
  28. package/dist/providers/registry/registry.js +1 -1
  29. package/dist/providers/types.d.ts +12 -2
  30. package/dist/providers/utilities.d.ts +4 -3
  31. package/dist/providers/utilities.js +4 -3
  32. package/dist/sessions/evidence/origins.d.ts +2 -1
  33. package/dist/sessions/evidence/origins.js +2 -1
  34. package/dist/store/control/reads/reads.model.d.ts +1 -1
  35. package/dist/store/control/reads/reads.model.js +14 -3
  36. package/errors/README.md +2 -0
  37. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
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
+
3
9
  ## 13.1.5
4
10
 
5
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.
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.
@@ -250,24 +254,24 @@ File timestamps and records do not prove that a native process is idle or a turn
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
 
@@ -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') {
@@ -175,6 +175,10 @@ export class LiveItems {
175
175
  const key = JSON.stringify([item.turnId, liveId]);
176
176
  const entry = thread.items.get(key);
177
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)) &&
178
182
  entry.item.nativeType === item.nativeType &&
179
183
  entry.item.kind === item.kind &&
180
184
  ((entry.item.text === item.text && entry.item.isTruncated === item.isTruncated) ||
@@ -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';
@@ -1,4 +1,6 @@
1
1
  // persistent native controls
2
2
  export { createClaudeControl } from './control.js';
3
+ // qualified attachment types
4
+ export { CLAUDE_STEER_MEDIA_TYPES } from './constants.js';
3
5
  // skills
4
6
  export { toClaudeSkills } from './skills.js';
@@ -14,7 +14,7 @@ const itemCursors = createRequestCursors(EntrySeekSchema);
14
14
  // a thread page's continuation: the activity time and session ID of the last transcript listed
15
15
  const THREAD_CURSOR = /^(\d{1,16}):(.+)$/;
16
16
  // identifies the path and record interpretation used by persisted projection entries
17
- const HISTORY_PROJECTION_VERSION = 11;
17
+ const HISTORY_PROJECTION_VERSION = 12;
18
18
  // the transcripts whose continuing session is remembered, oldest dropped first
19
19
  const MAX_CONTINUED_ANSWERS = 1_024;
20
20
  // one record, such as a tool result holding images
@@ -63,8 +63,11 @@ export type IRecord = z.infer<typeof RecordSchema>;
63
63
  export declare const QueuedPromptSchema: z.ZodObject<{
64
64
  type: z.ZodLiteral<"queued_command">;
65
65
  commandMode: z.ZodLiteral<"prompt">;
66
- prompt: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodUnknown>]>;
67
- source_uuid: z.ZodOptional<z.ZodString>;
66
+ prompt: z.ZodUnion<readonly [z.ZodString, z.ZodTuple<[z.ZodObject<{
67
+ type: z.ZodLiteral<"text">;
68
+ text: z.ZodString;
69
+ }, z.core.$strip>], z.ZodUnknown>]>;
70
+ source_uuid: z.ZodUUID;
68
71
  }, z.core.$strip>;
69
72
  export declare const FilePatchSchema: z.ZodObject<{
70
73
  filePath: z.ZodString;
@@ -38,8 +38,11 @@ export const RecordSchema = z.object({
38
38
  export const QueuedPromptSchema = z.object({
39
39
  type: z.literal('queued_command'),
40
40
  commandMode: z.literal('prompt'),
41
- prompt: z.union([z.string(), z.array(z.unknown())]),
42
- source_uuid: z.string().min(1).max(4096).optional(),
41
+ prompt: z.union([
42
+ z.string().min(1),
43
+ z.tuple([z.object({ type: z.literal('text'), text: z.string().min(1) })]).rest(z.unknown()),
44
+ ]),
45
+ source_uuid: z.uuid(),
43
46
  });
44
47
  // the file Claude Code records on an Edit or Write result; a created file's patch is empty
45
48
  export const FilePatchSchema = z.object({
@@ -66,6 +66,8 @@ export declare const readContinuedIn: (directory: string, nativeId: string) => s
66
66
  * @param record The record.
67
67
  * @returns The message as a user record's content and the native input it came from, or null for
68
68
  * any other record, such as a background task notification.
69
+ * @throws
70
+ * - JG_AGENT_HQ_CLAUDE_HISTORY_UNAVAILABLE: The Claude history is unavailable
69
71
  */
70
72
  export declare const readClaudeQueuedInput: (record: IRecord) => {
71
73
  content: string | unknown[];
@@ -86,6 +88,8 @@ export declare const toClaudeItem: (native: IRecord, turnId: string, fullBody?:
86
88
  * results' content, in order.
87
89
  * @param record The record.
88
90
  * @returns At most 64 images, each its base64 data, or null for one that has no base64 source.
91
+ * @throws
92
+ * - JG_AGENT_HQ_CLAUDE_HISTORY_UNAVAILABLE: The Claude history is unavailable
89
93
  */
90
94
  export declare const toClaudeImageData: (record: IRecord) => (string | null)[];
91
95
  /**
@@ -111,5 +115,7 @@ export declare const isClaudeCallFor: (candidate: IRecord, item: IHistoryItem) =
111
115
  * @param native The item's record.
112
116
  * @param call The call it answers, or null when it answers none or the call isn't found.
113
117
  * @returns The detail's parts; the item itself comes from `toClaudeItem`.
118
+ * @throws
119
+ * - JG_AGENT_HQ_CLAUDE_HISTORY_UNAVAILABLE: The Claude history is unavailable
114
120
  */
115
121
  export declare const toClaudeDetail: (native: IRecord, call: IRecord | null) => Omit<IItemDetail, "item">;
@@ -339,15 +339,16 @@ const toUserPresentation = (record, text) => {
339
339
  /*
340
340
  * The text a user record's input sent: its whole content, or its first block when that is text,
341
341
  * with a slash command or skill as the `/name args` that was sent, not the markup Claude records.
342
+ * Queued prompt text is already the original input and is never stripped as command markup.
342
343
  */
343
- const readInputText = (record) => {
344
+ const readInputText = (record, isQueuedInput = false) => {
344
345
  const content = record.message?.content;
345
346
  const first = Array.isArray(content) ? BlockSchema.safeParse(content[0]).data : undefined;
346
347
  const text = typeof content === 'string' ? content : first?.type === 'text' ? (first.text ?? null) : null;
347
- return text === null ? null : (readCommandText(text) ?? text);
348
+ return text === null || isQueuedInput ? text : (readCommandText(text) ?? text);
348
349
  };
349
350
  /** Presents a native record as the CLI shows it, or null for one it leaves out. */
350
- const toPresentation = (record) => {
351
+ const toPresentation = (record, isQueuedInput = false) => {
351
352
  const base = { nativeType: record.type, callId: null, outcome: null, files: [] };
352
353
  if (record.type !== 'user' && record.type !== 'assistant')
353
354
  return { ...base, kind: 'unsupported', text: UNSUPPORTED };
@@ -371,9 +372,11 @@ const toPresentation = (record) => {
371
372
  if (record.isCompactSummary)
372
373
  return { ...base, kind: 'notice', text: text ?? UNSUPPORTED };
373
374
  if (text !== undefined)
374
- return record.type === 'user'
375
- ? toUserPresentation(record, text)
376
- : { ...base, kind: 'agent-message', text };
375
+ return isQueuedInput
376
+ ? { ...base, kind: 'user-message', text }
377
+ : record.type === 'user'
378
+ ? toUserPresentation(record, text)
379
+ : { ...base, kind: 'agent-message', text };
377
380
  if (blocks.every((block) => block?.type === 'tool_result')) {
378
381
  const patch = FilePatchSchema.safeParse(record.toolUseResult);
379
382
  return {
@@ -386,7 +389,9 @@ const toPresentation = (record) => {
386
389
  outcome: blocks.some((block) => block.is_error) ? 'failed' : 'succeeded',
387
390
  };
388
391
  }
389
- const calls = blocks.filter((block) => block?.type === 'tool_use' && block.name);
392
+ const calls = isQueuedInput
393
+ ? []
394
+ : blocks.filter((block) => block?.type === 'tool_use' && block.name);
390
395
  return {
391
396
  ...base,
392
397
  kind: calls.length > 0 ? 'tool' : message,
@@ -411,16 +416,30 @@ const toPresentation = (record) => {
411
416
  * @param record The record.
412
417
  * @returns The message as a user record's content and the native input it came from, or null for
413
418
  * any other record, such as a background task notification.
419
+ * @throws
420
+ * - JG_AGENT_HQ_CLAUDE_HISTORY_UNAVAILABLE: The Claude history is unavailable
414
421
  */
415
422
  export const readClaudeQueuedInput = (record) => {
416
- if (record.type !== 'attachment')
423
+ if (record.type !== 'attachment' || record.isMeta)
424
+ return null;
425
+ const header = z
426
+ .object({ type: z.string(), commandMode: z.unknown().optional() })
427
+ .safeParse(record.attachment);
428
+ if (!header.success || header.data.type !== 'queued_command')
429
+ return null;
430
+ if (typeof header.data.commandMode === 'string' && header.data.commandMode !== 'prompt')
417
431
  return null;
418
432
  const queued = QueuedPromptSchema.safeParse(record.attachment);
419
- return queued.success
420
- ? { content: queued.data.prompt, inputId: queued.data.source_uuid ?? null }
421
- : null;
433
+ if (!queued.success || !z.uuid().safeParse(record.uuid).success)
434
+ throw HQ_ERRORS.create('claudeHistoryUnavailable', { data: { kind: 'agent-unavailable' } });
435
+ return { content: queued.data.prompt, inputId: queued.data.source_uuid };
422
436
  };
423
- // presents a queued command's message as the user record it stands for, and any other record as is
437
+ /**
438
+ * Presents a queued prompt as its user record while retaining the graph identity.
439
+ * @returns The normalized message record, or the original non-prompt record.
440
+ * @throws
441
+ * - JG_AGENT_HQ_CLAUDE_HISTORY_UNAVAILABLE: The Claude history is unavailable
442
+ */
424
443
  const toMessageRecord = (record) => {
425
444
  const queued = readClaudeQueuedInput(record);
426
445
  return queued
@@ -441,8 +460,9 @@ export const toClaudeItem = (native, turnId, fullBody = false) => {
441
460
  throw HQ_ERRORS.create('claudeHistoryUnavailable', {
442
461
  data: { kind: 'agent-unavailable' },
443
462
  });
463
+ const queued = readClaudeQueuedInput(native);
444
464
  const record = toMessageRecord(native);
445
- const presentation = toPresentation(record);
465
+ const presentation = toPresentation(record, queued !== null);
446
466
  if (!presentation)
447
467
  return null;
448
468
  const { text } = presentation;
@@ -455,7 +475,7 @@ export const toClaudeItem = (native, turnId, fullBody = false) => {
455
475
  nativeId: native.uuid,
456
476
  turnId,
457
477
  provenance: presentation.kind === 'user-message'
458
- ? nativeProvenance(presentation.kind, readClaudeQueuedInput(native)?.inputId ?? native.uuid, readInputText(record))
478
+ ? nativeProvenance(presentation.kind, queued?.inputId ?? native.uuid, readInputText(record, queued !== null))
459
479
  : nativeProvenance(presentation.kind),
460
480
  text: text.slice(0, end),
461
481
  isTruncated: end < text.length,
@@ -523,6 +543,8 @@ const toShellCommand = (input) => z.object({ command: z.string() }).safeParse(in
523
543
  * results' content, in order.
524
544
  * @param record The record.
525
545
  * @returns At most 64 images, each its base64 data, or null for one that has no base64 source.
546
+ * @throws
547
+ * - JG_AGENT_HQ_CLAUDE_HISTORY_UNAVAILABLE: The Claude history is unavailable
526
548
  */
527
549
  export const toClaudeImageData = (record) => toBlocks(toMessageRecord(record))
528
550
  .flatMap((block) => block.type === 'tool_result' && Array.isArray(block.content)
@@ -562,6 +584,8 @@ export const isClaudeCallFor = (candidate, item) => item.nativeType === 'tool-re
562
584
  * @param native The item's record.
563
585
  * @param call The call it answers, or null when it answers none or the call isn't found.
564
586
  * @returns The detail's parts; the item itself comes from `toClaudeItem`.
587
+ * @throws
588
+ * - JG_AGENT_HQ_CLAUDE_HISTORY_UNAVAILABLE: The Claude history is unavailable
565
589
  */
566
590
  export const toClaudeDetail = (native, call) => {
567
591
  const record = toMessageRecord(native);
@@ -571,6 +595,8 @@ export const toClaudeDetail = (native, call) => {
571
595
  files: [],
572
596
  images: toImages(record),
573
597
  };
598
+ if (native.type === 'attachment' && readClaudeQueuedInput(native) !== null)
599
+ return detail;
574
600
  const text = toText(record);
575
601
  if (record.type === 'user' && text !== undefined) {
576
602
  const input = SHELL_INPUT.exec(text);
@@ -8,7 +8,7 @@ import { buildProviderCapabilities, MODEL_CATALOG_UNAVAILABLE, SUPPORTED_PROVIDE
8
8
  import { capabilityUnavailable } from '../registry/index.js';
9
9
  import { HQ_ERRORS } from '../../errors/index.js';
10
10
  import { createCodexProvider } from './codex.js';
11
- import { MAX_LOADED_THREAD_PAGES } from './constants.js';
11
+ import { CODEX_SUPPORTED_MEDIA_TYPES, MAX_LOADED_THREAD_PAGES } from './constants.js';
12
12
  import { createCodexEvents, toProviderThread } from './events.js';
13
13
  /**
14
14
  * Describes current Codex controls and lazily owns a connection to the shared app-server daemon.
@@ -187,7 +187,8 @@ export const createCodexProviderFactory = (extraSkillRoots, daemonLauncher) => (
187
187
  return buildProviderCapabilities({
188
188
  provider: 'codex',
189
189
  operations: { models },
190
- supportedMediaTypes: ['image/png', 'image/jpeg', 'image/webp', 'text/plain'],
190
+ supportedMediaTypes: CODEX_SUPPORTED_MEDIA_TYPES,
191
+ steerMediaTypes: CODEX_SUPPORTED_MEDIA_TYPES,
191
192
  configurationSchema: {
192
193
  session: z
193
194
  .json()
@@ -253,11 +254,11 @@ export const createCodexProviderFactory = (extraSkillRoots, daemonLauncher) => (
253
254
  resumeThread: async (requestId, nativeId, _workspaceRoot, _name, settings, call) => toProviderThread(await native.resumeThread(requestId, nativeId, settings, call.signal)),
254
255
  nameThread: (requestId, nativeId, name) => native.nameThread(requestId, nativeId, name),
255
256
  async validateInput(_nativeId, input) {
256
- if (input.files.some((file) => file.mediaType === 'application/pdf' || file.mediaType === 'image/gif'))
257
+ if (input.files.some((file) => !CODEX_SUPPORTED_MEDIA_TYPES.includes(file.mediaType)))
257
258
  capabilityUnavailable();
258
259
  },
259
260
  startTurn: (requestId, nativeId, text, skill, settings, files) => native.startTurn(requestId, nativeId, text, skill, settings, files),
260
- steer: (requestId, nativeId, expectedTurnId, text) => native.steer(requestId, nativeId, expectedTurnId, text),
261
+ steer: (requestId, nativeId, expectedTurnId, text, files) => native.steer(requestId, nativeId, expectedTurnId, text, files),
261
262
  interrupt: (requestId, nativeId, nativeTurnId) => native.interrupt(requestId, nativeId, nativeTurnId),
262
263
  cleanThread: (requestId, nativeId) => native.cleanTerminals(requestId, nativeId),
263
264
  async releaseThread(requestId, nativeId) {
@@ -5,7 +5,7 @@ import { MAX_PAGE_SIZE, } from '../../contracts/index.js';
5
5
  import { NativeIdSchema } from '../../contracts/identities/index.js';
6
6
  import { decodeBase64Image, imageUnavailable, readImageFile } from '../../sessions/index.js';
7
7
  import { HQ_ERRORS } from '../../errors/index.js';
8
- import { LOADED_THREADS_PAGE_SIZE, NO_ROLLOUT_MESSAGE, SKILL_HINT_READ_CONCURRENCY, } from './constants.js';
8
+ import { CODEX_SUPPORTED_MEDIA_TYPES, LOADED_THREADS_PAGE_SIZE, NO_ROLLOUT_MESSAGE, SKILL_HINT_READ_CONCURRENCY, } from './constants.js';
9
9
  import { createCodexRpc } from './rpc.js';
10
10
  import { NativeBucketSchema, NativeSkillsSchema, NativeItemPageSchema, NativeThreadPageSchema, NativeThreadSchema, NativeTurnPageSchema, NativeUsageSchema, NativeTurnSchema, } from './types.js';
11
11
  import { toHistoryItem, toImageSources, toItemDetail, toThreadSummary, toTurnSummary, toUsageSnapshot, } from './transformers.js';
@@ -13,6 +13,16 @@ import { parseNative } from './validations.js';
13
13
  import { toCodexModels } from './models/index.js';
14
14
  import { HOST_SKILL_SCOPE, readSkillHint, readSkillRoots, toCapabilityRoots, } from './skill-roots/index.js';
15
15
  import { toCodexConfiguration, toCodexServiceTier, toCodexSessionSettings, readCodexConfigurationObservation, } from './configuration/index.js';
16
+ /** Builds the same checked file items for turn start and Steer. */
17
+ const toFileItems = (files) => files.map((file) => file.mediaType === 'text/plain'
18
+ ? {
19
+ type: 'text',
20
+ text: `File ${file.path} (SHA-256 ${file.sha256}):\n${new TextDecoder('utf-8', { fatal: true }).decode(file.content)}`,
21
+ }
22
+ : {
23
+ type: 'image',
24
+ url: `data:${file.mediaType};base64,${Buffer.from(file.content).toString('base64')}`,
25
+ });
16
26
  /**
17
27
  * Connects native history, usage observations and explicitly admitted runtime controls.
18
28
  * @returns The owned adapter. Its caller must close it on shutdown.
@@ -377,24 +387,18 @@ export const createCodexProvider = async (extraSkillRoots = [], daemonLauncher =
377
387
  input: [
378
388
  { type: 'text', text },
379
389
  ...(skill ? [{ type: 'skill', name: skill.name, path: skill.path }] : []),
380
- ...files.map((file) => file.mediaType === 'text/plain'
381
- ? {
382
- type: 'text',
383
- text: `File ${file.path} (SHA-256 ${file.sha256}):\n${new TextDecoder('utf-8', { fatal: true }).decode(file.content)}`,
384
- }
385
- : {
386
- type: 'image',
387
- url: `data:${file.mediaType};base64,${Buffer.from(file.content).toString('base64')}`,
388
- }),
390
+ ...toFileItems(files),
389
391
  ],
390
392
  }, requestId)).turn;
391
393
  },
392
- async steer(requestId, nativeId, expectedTurnId, text) {
394
+ async steer(requestId, nativeId, expectedTurnId, text, files = []) {
395
+ if (files.some((file) => !CODEX_SUPPORTED_MEDIA_TYPES.includes(file.mediaType)))
396
+ throw HQ_ERRORS.create('capabilityUnavailable', { data: { kind: 'agent-unavailable' } });
393
397
  const result = parseNative(z.object({ turnId: z.literal(expectedTurnId) }), await connection.request('turn/steer', {
394
398
  threadId: nativeId,
395
399
  expectedTurnId,
396
400
  clientUserMessageId: requestId,
397
- input: [{ type: 'text', text }],
401
+ input: [{ type: 'text', text }, ...toFileItems(files)],
398
402
  }, requestId));
399
403
  return result.turnId;
400
404
  },
@@ -1,3 +1,4 @@
1
+ export declare const CODEX_SUPPORTED_MEDIA_TYPES: readonly string[];
1
2
  export declare const LOADED_THREADS_PAGE_SIZE = 128;
2
3
  export declare const MAX_LOADED_THREAD_PAGES = 8;
3
4
  export declare const SKILL_HINT_READ_CONCURRENCY = 8;
@@ -1,3 +1,10 @@
1
+ // file types accepted by both Codex turn start and Steer
2
+ export const CODEX_SUPPORTED_MEDIA_TYPES = [
3
+ 'image/png',
4
+ 'image/jpeg',
5
+ 'image/webp',
6
+ 'text/plain',
7
+ ];
1
8
  // threads read per page of the daemon's loaded threads, and the most pages one connection reads
2
9
  export const LOADED_THREADS_PAGE_SIZE = 128;
3
10
  export const MAX_LOADED_THREAD_PAGES = 8;
@@ -280,9 +280,10 @@ export type ICodexProvider = {
280
280
  * Steers only the required active native turn and verifies its response identity.
281
281
  * @returns The acknowledged native turn identity.
282
282
  * @throws
283
+ * - JG_AGENT_HQ_CAPABILITY_UNAVAILABLE: The HQ capability is unavailable
283
284
  * - JG_AGENT_HQ_CODEX_FAILED: The Codex integration failed
284
285
  */
285
- steer(requestId: string, nativeId: string, expectedTurnId: string, text: string): Promise<string>;
286
+ steer(requestId: string, nativeId: string, expectedTurnId: string, text: string, files?: IProviderInputFile[]): Promise<string>;
286
287
  /**
287
288
  * Requests interruption; its acknowledgement does not prove completion.
288
289
  * @returns A promise resolved after native interruption-request acknowledgement.
@@ -242,7 +242,7 @@ export const createProviderRegistry = (factories, allowedRoots, runtimeEpoch) =>
242
242
  nameThread: (requestId, nativeId, name) => invokeControl((call) => adapter.nameThread(requestId, nativeId, name, call)),
243
243
  validateInput: (nativeId, input) => invoke((call) => adapter.validateInput(nativeId, input, call)),
244
244
  startTurn: (requestId, nativeId, text, skill, settings, files) => invokeControl((call) => adapter.startTurn(requestId, nativeId, text, skill, settings, files, call)),
245
- steer: (requestId, nativeId, expectedTurnId, text) => invokeControl((call) => adapter.steer(requestId, nativeId, expectedTurnId, text, call)),
245
+ steer: (requestId, nativeId, expectedTurnId, text, files) => invokeControl((call) => adapter.steer(requestId, nativeId, expectedTurnId, text, files, call)),
246
246
  interrupt: (requestId, nativeId, nativeTurnId) => invokeControl((call) => adapter.interrupt(requestId, nativeId, nativeTurnId, call)),
247
247
  cleanThread: (requestId, nativeId) => invokeControl((call) => adapter.cleanThread(requestId, nativeId, call)),
248
248
  releaseThread: (requestId, nativeId) => invokeControl((call) => adapter.releaseThread(requestId, nativeId, call)),
@@ -219,8 +219,18 @@ export type IAgentProvider = {
219
219
  startTurn(requestId: string, nativeId: string, text: string, skill: INativeSkillInput | null, settings: ITurnSettings, files: IProviderInputFile[], call: IProviderCall): Promise<{
220
220
  id: string;
221
221
  }>;
222
- /** @returns The acknowledged active turn identity, without creating a new turn. */
223
- steer(requestId: string, nativeId: string, expectedTurnId: string, text: string, call: IProviderCall): Promise<string>;
222
+ /**
223
+ * Sends text and qualified attachments to the exact active turn.
224
+ * @returns The acknowledged active turn identity, without creating a new turn.
225
+ * @throws
226
+ * - JG_AGENT_HQ_ACTION_CONFLICT: The HQ action conflicts with its recorded state
227
+ * - JG_AGENT_HQ_CAPABILITY_UNAVAILABLE: The HQ capability is unavailable
228
+ * - JG_AGENT_HQ_PROVIDER_FAILED: The HQ provider integration failed
229
+ * - JG_AGENT_HQ_CODEX_FAILED: The Codex integration failed
230
+ * - JG_AGENT_HQ_CLAUDE_FAILED: The Claude integration failed
231
+ * - JG_AGENT_HQ_TRANSPORT_FAILED: The HQ transport failed
232
+ */
233
+ steer(requestId: string, nativeId: string, expectedTurnId: string, text: string, files: IProviderInputFile[], call: IProviderCall): Promise<string>;
224
234
  /** @returns Acknowledgement of the interruption request, without implying completion. */
225
235
  interrupt(requestId: string, nativeId: string, nativeTurnId: string, call: IProviderCall): Promise<void>;
226
236
  /** @returns Native cleanup acknowledgement for the selected owned session. */
@@ -20,12 +20,13 @@ export declare const parseActionRequest: (requestId: string) => {
20
20
  * Builds a provider's capabilities from its operation support and the input limits both providers
21
21
  * share.
22
22
  * @param overrides The provider, the operations its native CLI reports now, the media types it
23
- * accepts, and its configuration schema.
23
+ * accepts at turn start and during steering, and its configuration schema.
24
24
  * @returns The provider's capability set.
25
25
  */
26
- export declare const buildProviderCapabilities: ({ provider, operations, supportedMediaTypes, configurationSchema, }: {
26
+ export declare const buildProviderCapabilities: ({ provider, operations, supportedMediaTypes, steerMediaTypes, configurationSchema, }: {
27
27
  provider: IProviderId;
28
28
  operations: Partial<IProviderCapabilitySet["operations"]>;
29
- supportedMediaTypes: string[];
29
+ supportedMediaTypes: readonly string[];
30
+ steerMediaTypes: readonly string[];
30
31
  configurationSchema: IProviderCapabilitySet["configurationSchema"];
31
32
  }) => IProviderCapabilitySet;
@@ -23,14 +23,15 @@ export const parseActionRequest = (requestId) => {
23
23
  * Builds a provider's capabilities from its operation support and the input limits both providers
24
24
  * share.
25
25
  * @param overrides The provider, the operations its native CLI reports now, the media types it
26
- * accepts, and its configuration schema.
26
+ * accepts at turn start and during steering, and its configuration schema.
27
27
  * @returns The provider's capability set.
28
28
  */
29
- export const buildProviderCapabilities = ({ provider, operations, supportedMediaTypes, configurationSchema, }) => ({
29
+ export const buildProviderCapabilities = ({ provider, operations, supportedMediaTypes, steerMediaTypes, configurationSchema, }) => ({
30
30
  operations: { ...PROVIDER_OPERATIONS[provider], ...operations },
31
31
  inputSchema: {
32
32
  ...PROVIDER_INPUT_SCHEMA,
33
- supportedMediaTypes,
33
+ supportedMediaTypes: [...supportedMediaTypes],
34
+ steerMediaTypes: [...steerMediaTypes],
34
35
  maxFiles: MAX_INPUT_FILES,
35
36
  maxFileBytes: MAX_INPUT_FILE_BYTES,
36
37
  maxTextFileBytes: MAX_TEXT_FILE_BYTES,
@@ -3,7 +3,8 @@ import type { IStore } from '../../store/index.js';
3
3
  type IProvenanceItem = Pick<IHistoryItem, 'kind' | 'provenance'> & (Pick<IHistoryItem, 'turnId'> | Pick<IEvidenceItem, 'reference'>);
4
4
  /**
5
5
  * Replaces provider assertions with provenance verified against acknowledged native inputs.
6
- * Only input identities and hashes cross the worker boundary; message bodies stay in their owner.
6
+ * Only input identities and hashes cross the worker boundary; Claude queued prompts use their
7
+ * source UUID, independently of the transcript's graph UUID. Bodies stay in their owner.
7
8
  * @param items Fresh presentation rows, including full-input fingerprints before preview cuts.
8
9
  * @param provider The provider whose native session supplied the rows.
9
10
  * @param nativeId The selected native session.
@@ -2,7 +2,8 @@ import { parseActionRequest } from '../../providers/index.js';
2
2
  import { resetProvenance } from './utilities.js';
3
3
  /**
4
4
  * Replaces provider assertions with provenance verified against acknowledged native inputs.
5
- * Only input identities and hashes cross the worker boundary; message bodies stay in their owner.
5
+ * Only input identities and hashes cross the worker boundary; Claude queued prompts use their
6
+ * source UUID, independently of the transcript's graph UUID. Bodies stay in their owner.
6
7
  * @param items Fresh presentation rows, including full-input fingerprints before preview cuts.
7
8
  * @param provider The provider whose native session supplied the rows.
8
9
  * @param nativeId The selected native session.
@@ -8,7 +8,7 @@ export declare class ControlReads extends ControlModel {
8
8
  getAction(id: string): IActionReceipt | null;
9
9
  /**
10
10
  * Resolves exact native input identities and content hashes; native roles grant no identity.
11
- * An input matches the action and phase its native ID names, or the turn it started.
11
+ * Claude steers name their action UUID while retaining the original target turn.
12
12
  */
13
13
  getEvidenceOrigins(command: IEvidenceOriginsRequest): (IHistoryProvenance | null)[];
14
14
  /** Returns one control record by immutable identity. */
@@ -9,17 +9,28 @@ export class ControlReads extends ControlModel {
9
9
  }
10
10
  /**
11
11
  * Resolves exact native input identities and content hashes; native roles grant no identity.
12
- * An input matches the action and phase its native ID names, or the turn it started.
12
+ * Claude steers name their action UUID while retaining the original target turn.
13
13
  */
14
14
  getEvidenceOrigins(command) {
15
+ const selection = `SELECT a.id, (SELECT b.id FROM agent_hq_browser_action b WHERE b.native_action_id = a.id AND b.native_thread_id = a.thread_id AND b.native_input_sha256 = a.input_sha256) AS browser_action_id
16
+ FROM agent_hq_action a JOIN agent_hq_thread t ON t.id = a.thread_id`;
15
17
  return command.items.map((item) => {
16
18
  if (item.nativeInputId === null || item.sha256 === null)
17
19
  return null;
18
- const rows = this._statements.all(`SELECT a.id, (SELECT b.id FROM agent_hq_browser_action b WHERE b.native_action_id = a.id AND b.native_thread_id = a.thread_id AND b.native_input_sha256 = a.input_sha256) AS browser_action_id
19
- FROM agent_hq_action a JOIN agent_hq_thread t ON t.id = a.thread_id
20
+ const rows = this._statements.all(`${selection}
20
21
  WHERE t.provider = ? AND t.native_id = ? AND a.native_turn_id = ? AND a.input_sha256 = ?
21
22
  AND a.delivery = 'acknowledged' AND ((a.id = ? AND a.phase = ?) OR a.native_turn_id = ?)
22
23
  ORDER BY a.id LIMIT 2`, command.provider, command.nativeId, item.turnId, item.sha256, item.request?.actionId ?? null, item.request?.phase ?? null, item.nativeInputId);
24
+ if (command.provider === 'claude') {
25
+ const steer = this._statements.get(`${selection}
26
+ WHERE a.id = ? AND t.provider = 'claude' AND t.native_id = ?
27
+ AND a.kind = 'steer' AND a.phase = 'steer' AND a.delivery = 'acknowledged'
28
+ AND a.native_turn_id IS NOT NULL AND a.native_turn_id = a.expected_turn_id
29
+ AND a.input_sha256 = ? AND (a.native_turn_id = ? OR a.id = ?)
30
+ LIMIT 1`, item.nativeInputId, command.nativeId, item.sha256, item.turnId, item.turnId);
31
+ if (steer && !rows.some((row) => row.id === steer.id))
32
+ rows.push(steer);
33
+ }
23
34
  if (rows.length !== 1)
24
35
  return null;
25
36
  const row = rows[0];
package/errors/README.md CHANGED
@@ -55,6 +55,8 @@ An `action-wait` reuses TARGET_FORBIDDEN as `receipt` does, and RUNTIME_NOT_RUNN
55
55
 
56
56
  Input-file admission reuses REQUEST_INVALID for invalid media, malformed UTF-8 and byte/count limits, and TARGET_FORBIDDEN for root or symlink escapes. A changed or missing content-bound file uses ACTION_CONFLICT before native submission; no input is replayed. Unsupported provider media or live output-schema changes use CAPABILITY_UNAVAILABLE. Schema mismatch, missing final output and result overflow are explicit receipt-result classifications rather than new exception codes. Native rejection and transport uncertainty retain the existing provider/action contracts.
57
57
 
58
+ Steer files use the same admission, content-binding and pre-send checks. Types outside the provider's `inputSchema.steerMediaTypes`, including Claude PDFs, use CAPABILITY_UNAVAILABLE before any native write, rejecting the complete input. An invalid internal Claude `<action UUID>:steer` request identity uses ACTION_CONFLICT before writing. A recognized malformed visible Claude queued prompt, including an unverifiable graph/source UUID or original first text block, uses CLAUDE_HISTORY_UNAVAILABLE; unsupported non-prompt attachment kinds remain hidden.
59
+
58
60
  Native form replies reuse REQUEST_INVALID for content outside the exact requested schema or response kind. Stale, expired, cross-thread or already answered request identities use ACTION_CONFLICT. Native writes without matching consumption evidence remain submitted or uncertain; expiry never proves a response was rejected. Unsupported native request variants are denied on their own native channel without granting permission.
59
61
 
60
62
  ## Public error messages
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jg-agent-hq",
3
- "version": "13.1.5",
3
+ "version": "13.2.0",
4
4
  "description": "Native Claude Code and Codex session control, history, usage and recoverable local storage for Node.js apps.",
5
5
  "type": "module",
6
6
  "license": "MIT",