jg-agent-hq 10.2.0 → 10.4.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 (74) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +1 -1
  3. package/api/README.md +36 -15
  4. package/dist/actions/actions.d.ts +2 -1
  5. package/dist/actions/actions.js +211 -14
  6. package/dist/actions/resync/constants.d.ts +3 -0
  7. package/dist/actions/resync/constants.js +9 -0
  8. package/dist/actions/resync/index.d.ts +4 -0
  9. package/dist/actions/resync/index.js +6 -0
  10. package/dist/actions/resync/resync.d.ts +24 -0
  11. package/dist/actions/resync/resync.js +63 -0
  12. package/dist/actions/resync/types.d.ts +22 -0
  13. package/dist/actions/resync/types.js +1 -0
  14. package/dist/actions/resync/utilities.d.ts +18 -0
  15. package/dist/actions/resync/utilities.js +51 -0
  16. package/dist/index.d.ts +2 -2
  17. package/dist/ipc/index.d.ts +1 -1
  18. package/dist/ipc/index.js +1 -1
  19. package/dist/ipc/server.d.ts +6 -0
  20. package/dist/ipc/server.js +17 -2
  21. package/dist/locks/index.d.ts +1 -1
  22. package/dist/locks/index.js +1 -1
  23. package/dist/locks/locks.d.ts +8 -0
  24. package/dist/locks/locks.js +25 -0
  25. package/dist/providers/claude/claude.js +1 -1
  26. package/dist/providers/claude/configuration/configuration.d.ts +3 -1
  27. package/dist/providers/claude/configuration/configuration.js +5 -3
  28. package/dist/providers/claude/control/control.d.ts +5 -2
  29. package/dist/providers/claude/control/control.js +30 -11
  30. package/dist/providers/claude/control/permissions.js +6 -2
  31. package/dist/providers/claude/control/stream.d.ts +3 -1
  32. package/dist/providers/claude/control/stream.js +97 -34
  33. package/dist/providers/claude/control/types.d.ts +9 -0
  34. package/dist/providers/codex/adapter.js +28 -0
  35. package/dist/providers/codex/codex.js +4 -0
  36. package/dist/providers/codex/constants.d.ts +1 -0
  37. package/dist/providers/codex/constants.js +6 -0
  38. package/dist/providers/codex/events.js +137 -107
  39. package/dist/providers/codex/rpc.d.ts +1 -0
  40. package/dist/providers/codex/rpc.js +1 -1
  41. package/dist/providers/codex/transformers.d.ts +6 -3
  42. package/dist/providers/codex/transformers.js +7 -2
  43. package/dist/providers/codex/types.d.ts +8 -0
  44. package/dist/providers/codex/types.js +5 -0
  45. package/dist/providers/codex/websocket/websocket.js +57 -9
  46. package/dist/providers/index.d.ts +2 -2
  47. package/dist/providers/index.js +1 -1
  48. package/dist/providers/process.d.ts +1 -1
  49. package/dist/providers/process.js +2 -1
  50. package/dist/providers/registry/registry.d.ts +2 -0
  51. package/dist/providers/registry/registry.js +36 -1
  52. package/dist/providers/registry/types.d.ts +1 -0
  53. package/dist/providers/types.d.ts +51 -0
  54. package/dist/providers/types.js +21 -0
  55. package/dist/runtime/index.d.ts +1 -1
  56. package/dist/runtime/runtime.js +16 -7
  57. package/dist/runtime/state/state.d.ts +7 -3
  58. package/dist/runtime/state/state.js +71 -9
  59. package/dist/runtime/types.d.ts +6 -0
  60. package/dist/runtime/types.js +8 -0
  61. package/dist/store/control/constants.d.ts +1 -0
  62. package/dist/store/control/constants.js +7 -0
  63. package/dist/store/control/control.model.d.ts +30 -4
  64. package/dist/store/control/control.model.js +109 -9
  65. package/dist/store/control/index.d.ts +2 -2
  66. package/dist/store/control/index.js +1 -1
  67. package/dist/store/control/types.d.ts +22 -0
  68. package/dist/store/control/types.js +25 -1
  69. package/dist/store/store.d.ts +1 -1
  70. package/dist/store/store.js +9 -3
  71. package/dist/store/store.worker.js +13 -1
  72. package/dist/store/types.d.ts +79 -1
  73. package/dist/store/types.js +12 -2
  74. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 10.4.0
4
+
5
+ - Accept Claude permission requests that carry fields HQ doesn't list. Claude adds fields between releases, such as `decision_reason_code` and `tool_kind`, and HQ refused every such request before the operator saw it. Known fields keep their validation, the rest are dropped, and the reply still holds only the displayed input.
6
+ - Refuse a Claude control request HQ still can't present with the error `HQ couldn't present this request`, which Claude records as the tool call's failed result, instead of `Unsupported request`.
7
+ - Report a Claude session's `systemInstructions` and `developerInstructions` as null when its process resumed the conversation, since Claude keeps the instructions it recorded when the conversation began.
8
+ - Keep a Claude session available when Claude starts a turn of its own, as it does after a background command finishes. That turn's first frame used to fail the session and end its process group. HQ now records the turn under an ID it generates: the thread reports running, its items stream as live items, its permission prompts can be answered, Stop interrupts it, and its result completes it. Input written just before such a turn waits for Claude's replay after it, and keeps its own turn and result.
9
+ - Keep a Claude session's process while a background command it started is still running, instead of parking the session after its idle hour, which ended the command.
10
+ - Record a turn's or a compaction's acknowledgement after the lifecycle events its provider reported before it, so a turn the agent started and finished meanwhile can't be taken for it.
11
+ - Leave approval requests on a Codex session another client drives for that client to answer. The shared daemon sends a session's requests to every connection that joined it, and HQ declined them at once, which declined the terminal user's approval. HQ now neither answers nor records them.
12
+ - Add `unpresentable(nativeId, reject)` to `IAgentProviderEvents`, for a request an adapter can't present. HQ refuses it only on a session it controls.
13
+ - Keep the Codex connection every managed Codex session shares open when a notification fails validation. A notification about items, text deltas, token usage or a session's status is dropped, with a gap in a managed session's live window, and a status newer than HQ knows makes the session `unknown`. A lost turn start, turn end or approval resolution makes HQ read the session from the daemon instead: a finished turn completes, a running turn whose start was lost continues, an ambiguous turn is read once more 2 seconds later, an unchanged idle session is left alone, and anything else marks the session uncertain.
14
+ - Add `resync(nativeId, lost)` to `IAgentProviderEvents`, `IResyncLoss`, and the optional `isInferred` on `IProviderReattachment`'s latest turn, which the built-in Codex adapter sets when the saved turn is still in progress.
15
+ - Skip a Codex message over the 8 MiB frame limit, through its final fragment, instead of failing the shared connection. Every managed Codex session is then read from the daemon: an idle, unchanged session is left alone, and a running one continues, watched until Codex reports it idle, when it is read as if its turn's end had been lost. A request whose response was skipped fails at its 30-second deadline.
16
+ - Add the optional `isPreviousRuntimeStopped` to `createAgentHq`, which lets startup recover a state root a runtime left after an unclean exit. When the recorded owner's process no longer exists and the host's check resolves true, startup replaces the owner record, removes a state-root lock whose holder is gone and a leftover `hq.sock`, and starts. The host guarantees that at most one caller reclaims a state root at a time. Add `IPreviousRuntimeCheck` and `IPreviousRuntimeOwner`.
17
+
18
+ ## 10.3.0
19
+
20
+ - Keep Codex sessions running when the runtime stops. Shutdown no longer interrupts their turns, cleans their background terminals or declines a request still waiting on an answer, and leaves their records bound to the stopped runtime. At startup, the next runtime rejoins each one that had no action in flight: it reads the session's state and latest turn from Codex's daemon, records the turn still running or completes the one that finished meanwhile, delivers the queued input waiting on it, and joins with `thread/resume` without settings, which makes the daemon send a still-waiting request again. A session another client moved past HQ's last turn, or one HQ can't read or join, is marked uncertain instead. Claude sessions still stop with the runtime.
21
+ - Add the optional `readReattachment` and `reattachThread` to `IAgentProvider`, and `IProviderReattachment`, which the built-in Codex adapter implements. Registered provider factories don't keep sessions across restarts, so the runtime never calls them on theirs.
22
+
3
23
  ## 10.2.0
4
24
 
5
25
  - `thread-adopt` accepts optional `settings`, as `thread-resume` does, and applies them to the resume it runs, so a host can adopt a session in a chosen permission mode. Codex refuses them for a thread another client still holds, as it does on resume.
package/README.md CHANGED
@@ -37,7 +37,7 @@ Testing maintenance can reuse an existing version when only these six aggregate
37
37
 
38
38
  ## Lock ownership
39
39
 
40
- Callers supply a trusted state root. Locks live in its private `.runtime/hq.lock`. A holder records its process ID, nonce, safe operation label and creation time. Live holders are awaited. Dead, incomplete or unverifiable owners require inspection and are never automatically reclaimed, because child processes may remain alive.
40
+ Callers supply a trusted state root. Locks live in its private `.runtime/hq.lock`. A holder records its process ID, nonce, safe operation label and creation time. Live holders are awaited. Dead, incomplete or unverifiable owners require inspection and are never automatically reclaimed, because child processes may remain alive. The one exception is a runtime that stopped without releasing the state root: when the host's `isPreviousRuntimeStopped` check proves no process of that runtime remains, the next runtime replaces its owner record and removes a lock whose holder no longer exists and the socket it left behind. The host guarantees that at most one caller reclaims a given state root at a time.
41
41
 
42
42
  Short metadata operations use `withHqLock`. Long-lived runtime ownership must use a separate owner record; never hold a metadata lock for an agent turn's lifetime. The lock coordinates cooperating processes and does not isolate hostile code running as the same OS user.
43
43
 
package/api/README.md CHANGED
@@ -66,7 +66,19 @@ Native snapshot qualification on 2026-10-23 used Codex 0.164.0 (gpt-6.1-sol) and
66
66
 
67
67
  `createAgentHq({ stateRoot, allowedRoots })` starts one controller and returns `IAgentHq`: its canonical `stateRoot`, a `closed` lifetime promise, `request(command)`, idempotent `close()`, a trusted Node-only `storage` descriptor and `withStorageMaintenance(callback)`. Paths must be absolute. Allowed roots must exist and are canonicalized at startup. A client-selected workspace must resolve inside an allowed root. State is a real directory owned by the current OS user with no group/other access. The controller creates it privately when absent.
68
68
 
69
- The controller exclusively creates `hq-owner.json`. A live, inactive, incomplete or unverifiable existing owner prevents another controller from starting. There is no automatic takeover. Before deliberate recovery, establish that the inspected host, its worker and native process group have stopped. Runtime shutdown sends interruption requests across the bounded session cohort concurrently, then closes IPC connections, SQLite and owned native processes before removing the exact owner. Failed cleanup preserves ownership evidence. A new runtime receives a new epoch.
69
+ The controller exclusively creates `hq-owner.json`. A live, inactive, incomplete or unverifiable existing owner prevents another controller from starting. There is no automatic takeover. Before deliberate recovery, establish that the inspected host, its worker and native process group have stopped. Runtime shutdown sends interruption requests across the bounded Claude session cohort concurrently, then closes IPC connections, SQLite and owned native processes before removing the exact owner. Failed cleanup preserves ownership evidence. A new runtime receives a new epoch.
70
+
71
+ Codex sessions outlive the runtime, because they run in Codex's shared app-server daemon. Shutdown leaves them running: it doesn't interrupt their turns, clean their background terminals or answer a request still waiting on one, and their managed records stay bound to the stopped runtime. At startup, the next runtime rejoins each one that had no action in flight, one at a time in the background. It reads the session's state and latest turn from the daemon, binds the record to its own epoch, then joins with `thread/resume` without settings. A turn still running stays the session's active turn. A turn that finished meanwhile completes its action's receipt, without a `result`, and lets a queued entry waiting on it advance. The daemon sends a still-waiting request again on joining, and it opens as a new approval in the new epoch. A session whose latest turn isn't the one HQ recorded, because another client ran one, or that can't be read or joined, has its ownership marked uncertain for explicit recovery. A crash leaves the same bound records, so those sessions are rejoined too. A restored snapshot marks every session uncertain, so it never rejoins one. Claude sessions are processes the runtime owns: their turns stop with it, and they wait inactive for an explicit resume.
72
+
73
+ One Codex connection carries every managed Codex session, so a message HQ can't validate never fails it. A notification about items, text deltas, token usage or a session's status that fails validation is dropped, and a session HQ controls reports a gap in its live window; a status newer than HQ knows makes the session `unknown`. A message over 8,388,608 bytes, including its continuation fragments, is skipped through its final fragment without being buffered; a request whose response was skipped fails at its 30-second deadline. A turn start, turn end or approval resolution that fails validation, or a skipped message, whose session can't be known so every session HQ controls is affected, is made up for by reading the session from the daemon, one session at a time and outside the order other sessions' events keep:
74
+
75
+ - a turn the saved history shows finished completes its receipt, without a `result`, and lets queued input waiting on it advance;
76
+ - a running turn whose start was lost continues, and after a skipped message it continues watched: when Codex next reports the session neither running nor waiting while that turn is still recorded as active, the session is read as if the turn's end had been lost;
77
+ - a running turn whose end was lost, or a turn still in progress in the saved history while the session is idle, is read once more 2 seconds later, then completes or makes the session uncertain;
78
+ - an idle session whose latest turn is the one HQ recorded, or that has no turns, is left alone;
79
+ - anything else, such as a newer turn, a failed read or a lost approval resolution, marks the session uncertain: its submitted deliveries become uncertain and its pending approvals expire.
80
+
81
+ A session with an action in flight when a message is skipped isn't read, since its newest turn may not be recorded yet; it is watched instead. The original notification arriving late leaves the session as reconciled. A response to HQ's own request that fails validation, a message that is neither a request, a notification nor a response, and other invalid framing still fail the connection.
70
82
 
71
83
  `requestAgentHq(stateRoot, command, signal?)` is a one-command IPC client. It verifies the private owner and socket, binds the command to the runtime epoch and checks the matching response. Cancellation closes that client's socket and reports transport failure; it never undoes an admitted action. Closing a client does not close the host. `stop` accepts a shutdown request; the SDK caller must await `runtime.closed` when it owns the runtime. The CLI confirms owner removal before reporting `state: stopped`.
72
84
 
@@ -78,7 +90,7 @@ The socket accepts at most 32 simultaneous connections. Requests are bounded to
78
90
 
79
91
  Factories receive canonical allowed roots, the runtime epoch, a cancellation signal and runtime-owned event callbacks. They return `IAgentProvider`, which owns native protocol validation, processes, authentication, capabilities, history, skill invocation spelling and concrete session controls. Each operation receives a bounded `IProviderCall.signal`. Factories must clean up partial initialization before rejecting; `close()` must be idempotent and confirm that owned resources stopped. HQ retains ownership evidence when cleanup cannot be confirmed. Failed construction is not automatically replayed.
80
92
 
81
- `IAgentProviderEvents` carries normalized observations, items, deltas, prompts, outcomes, observed session states and connection loss. `session(nativeId, state)` reports the live state of a session another client drives inside the allowed workspaces; HQ ignores it for sessions it controls. An adapter that reports such sessions may implement the optional `readObservedThread(nativeId)`, returning the session's summary with the workspace it runs in; without it, those sessions are left out of `active-sessions`. `validateInput` rejects unsupported media/output options before admission and again at dispatch. `startTurn` receives content-bound `IProviderInputFile` bytes read by HQ. A turn-completed observation may carry a validated complete result whose state must match that observation. Registration binds provider identity. Echo each supplied request ID unchanged; HQ derives its action identity and verifies the exact receipt, runtime, provider, native session and workspace. A late create/fork/resume/unarchive/revert outcome also supplies verified native session metadata. Unknown control states cannot establish success or idle ownership. Callback metadata may grow additively; known identity and state fields remain validated. Native permission requests keep their exact reply channel and validation. An unsupported request is denied rather than approved.
93
+ `IAgentProviderEvents` carries normalized observations, items, deltas, prompts, outcomes, observed session states and connection loss. `session(nativeId, state)` reports the live state of a session another client drives inside the allowed workspaces; HQ ignores it for sessions it controls. An adapter that reports such sessions may implement the optional `readObservedThread(nativeId)`, returning the session's summary with the workspace it runs in; without it, those sessions are left out of `active-sessions`. `validateInput` rejects unsupported media/output options before admission and again at dispatch. `startTurn` receives content-bound `IProviderInputFile` bytes read by HQ. A turn-completed observation may carry a validated complete result whose state must match that observation. Registration binds provider identity. Echo each supplied request ID unchanged; HQ derives its action identity and verifies the exact receipt, runtime, provider, native session and workspace. A late create/fork/resume/unarchive/revert outcome also supplies verified native session metadata. Unknown control states cannot establish success or idle ownership. Callback metadata may grow additively; known identity and state fields remain validated. Native permission requests keep their exact reply channel and validation. An adapter reports a request it can't present with `unpresentable(nativeId, reject)`. `resync(nativeId, lost)` reports a lost turn start, turn end, approval resolution or `unknown` notification; HQ then reads the session through the adapter's optional `readReattachment`, or every session it controls through the adapter when `nativeId` is undefined. `readReattachment` sets `isInferred` on a latest turn whose saved state is still in progress, so its state comes from the session's status. HQ answers requests only on sessions it controls: on one of those, an unsupported request is denied rather than approved, while a request on a session another client drives, presentable or not, gets no reply and leaves no record, so that client answers it.
82
94
 
83
95
  `{ kind: 'capabilities', provider, threadId? }` returns `IProviderCapabilities`. The optional managed thread must belong to that provider and an allowed workspace. The response includes provider/session scope, observation time, concrete operation support, and supported HQ input/configuration schemas. Each operation is `supported`, `unsupported`, `unavailable` or `unknown`, with a structured reason when support cannot be established. Supported settings describe whether a change is live or requires an idle restart. Configuration schemas describe typed session and turn settings, their live or idle-restart change mode, and native permission/sandbox choices. Model and effort values come from the native model catalog. Capabilities are observations, not permission grants or execution authority.
84
96
 
@@ -92,6 +104,7 @@ The current built-in surfaces map to these native entry points:
92
104
  | Steer | `turn/steer` for the exact active turn | Explicitly unsupported by the structured interface |
93
105
  | Interrupt | `turn/interrupt` | `interrupt` control request; completion remains separate |
94
106
  | Close/recover | Native background-terminal cleanup/verification and `thread/unsubscribe` | Confirmed process-group shutdown and explicit session release/resume |
107
+ | Runtime restart | Sessions keep running, and the next runtime rejoins them | Turns stop with the runtime; sessions wait inactive for an explicit resume |
95
108
  | History | `thread/list`, `thread/read`, `thread/turns/list`, `thread/items/list` | Bounded worker-owned indexing of native transcripts |
96
109
  | Skills | `skills/list` and native skill input | Initialization command metadata and native invocation text |
97
110
  | Fork | `thread/fork` with verified source lineage | Native `--resume`, `--fork-session` and distinct `--session-id` |
@@ -190,7 +203,7 @@ Native qualification on 2026-10-23 used Codex 0.163.0 and Claude Code 2.1.309. B
190
203
 
191
204
  `models` returns native model IDs, display metadata, nullable effort choices/defaults and bounded continuation. Model/effort names are not fixed to a CLI release. Codex retains its native cursor; Claude uses an inventory revision and stable model key. Changed catalogs invalidate continuation.
192
205
 
193
- `configuration` accepts `provider`, authorized `workspaceRoot`, optional managed `threadId`, `limit` and `cursor`. Session selection must match both provider and workspace. The result includes `nativeId`, `workingDirectory`, known `effective` settings, bounded `instructionSources` with `isComplete`, and one page of native `choices` (`agent` or `profile`). Null means unknown or unavailable, never a fabricated default. A null `choices` value means the optional native inventory is unavailable; an empty array means a known empty inventory. Effective settings remain readable when Claude omits its optional agent catalog. Native inventory is bounded to 4096 entries; choice continuation binds the query and inventory revision. Instruction source paths are metadata only; HQ does not load those files through this operation. Claude uses an owned session's settings or a disposable workspace-scoped read process with no user prompt. At most four workspace read processes run concurrently; cancellation and runtime shutdown confirm their exit, including reads still initializing. Unconfirmed cleanup retains runtime ownership. Whole configuration documents, source layers and credentials are not returned.
206
+ `configuration` accepts `provider`, authorized `workspaceRoot`, optional managed `threadId`, `limit` and `cursor`. Session selection must match both provider and workspace. The result includes `nativeId`, `workingDirectory`, known `effective` settings, bounded `instructionSources` with `isComplete`, and one page of native `choices` (`agent` or `profile`). Null means unknown or unavailable, never a fabricated default. A null `choices` value means the optional native inventory is unavailable; an empty array means a known empty inventory. Effective settings remain readable when Claude omits its optional agent catalog. Native inventory is bounded to 4096 entries; choice continuation binds the query and inventory revision. Instruction source paths are metadata only; HQ does not load those files through this operation. Claude uses an owned session's settings or a disposable workspace-scoped read process with no user prompt. Claude records a conversation's instructions once (`--system-prompt-snapshot`, on by default) and reuses them on resume, so `systemInstructions` and `developerInstructions` are reported only for a session whose current process started its conversation, and are null for one that resumed it. At most four workspace read processes run concurrently; cancellation and runtime shutdown confirm their exit, including reads still initializing. Unconfirmed cleanup retains runtime ownership. Whole configuration documents, source layers and credentials are not returned.
194
207
 
195
208
  `thread-create`, `thread-resume` and `thread-adopt`, for the resume it runs, accept optional `settings`: `model`, `effort`, `outputSchema`, `permissionMode`, `systemInstructions`, `developerInstructions`, plus Codex `sandbox` or Claude `nativeAgent`. The workspace is the native working directory. Codex system/developer instructions map to native base/developer overrides. Claude system instructions use `--system-prompt`, and developer instructions use `--append-system-prompt`. Omitted fields keep native defaults. These are explicit native settings, separate from native tool approvals. The action envelope byte limit still applies.
196
209
 
@@ -265,9 +278,9 @@ Codex may keep an idle native thread loaded after `thread/unsubscribe`, as when
265
278
 
266
279
  Receipts separate `delivery` (`queued`, `submitted`, `acknowledged`, `uncertain`, `failed`, `canceled`) from nullable native turn `completion` (`completed`, `failed`, `interrupted`). Acknowledgement means the exact native request was accepted, not that the turn or tool completed. Permission replies remain submitted after a pipe write and become acknowledged only when Codex resolves the exact native request or Claude returns a tool-result block for the exact tool-use identity. Claude cancellation expires the prompt and leaves an unacknowledged written reply uncertain. Resolution does not prove a tool ran. The receipt includes HQ/native identity, request phase, digest, timestamps, safe failure classification and optional related action. Only selected receipts expose `nativeThreadId`, the native session of the action's thread once HQ records it, undelivered `queuedInput` and the nullable complete native `result`; collection reads omit all three. Queued input retains prepared text, native skill identity, content-bound file references and explicit turn settings, never file bytes or skill content. It is cleared after delivery acknowledgement or cancellation.
267
280
 
268
- A missing acknowledgement never triggers an automatic resend. Exact late responses reconcile delivery, including completion that arrived first. Native output loss marks the affected provider controls and submitted work uncertain. A Claude process failure affects its own session; a Codex transport failure affects its Codex cohort. Restart quarantines controls from an interrupted runtime; explicit recovery preserves the HQ identity and name. Successful shutdown proves native process-group exit before marking controls inactive. Unknown creation without a native identity remains uncertain.
281
+ A missing acknowledgement never triggers an automatic resend. Exact late responses reconcile delivery, including completion that arrived first. Native output loss marks the affected provider controls and submitted work uncertain. A Claude process failure affects its own session; a Codex transport failure affects its Codex cohort. Restart quarantines controls from an interrupted runtime, except the Codex sessions the next runtime rejoins; explicit recovery preserves the HQ identity and name. Successful shutdown proves native process-group exit before marking Claude controls inactive. Unknown creation without a native identity remains uncertain.
269
282
 
270
- Normal native turn completion may advance ready queued entries once, in creation/UUID order. Failure, interruption, explicit interrupt admission or restart pauses the queue. Permission prompts do not advance it. An unacknowledged start or metadata change blocks dependent starts until its outcome is reconciled or the stopped runtime is recovered explicitly. A turn's completion does not settle an unresolved steering receipt.
283
+ Normal native turn completion may advance ready queued entries once, in creation/UUID order. Failure, interruption, explicit interrupt admission or restart pauses the queue. A rejoined Codex session's queue advances again once the turn it waits on completes. Permission prompts do not advance it. An unacknowledged start or metadata change blocks dependent starts until its outcome is reconciled or the stopped runtime is recovered explicitly. A turn's completion does not settle an unresolved steering receipt.
271
284
 
272
285
  Native replies use one of these closed response forms:
273
286
 
@@ -282,13 +295,15 @@ Each record contains identity, `kind`, `isBlocking`, `state`, `replyActionId`, t
282
295
 
283
296
  ### Claude native control
284
297
 
285
- Each controlled session has one native `claude` process in the authorized workspace while it is in use. A session idle for 60 minutes since its last turn ended, or since it opened, gives up its process: HQ reads its native settings once and closes the process, and the session stays idle with no state transition. Its skills and configuration reads answer from what it kept, an interrupt is refused as for any idle session, and stopping or releasing it needs no process. Input, renames, extension control and MCP reads first reopen it with `--resume`, or `--session-id` when it never had input, and its kept settings. A parked session keeps its controlled-thread slot, of 32 per runtime, and a runtime restart treats it like any other managed Claude session. A running or waiting session is never stopped. HQ adds structured input/output, replayed user-message acknowledgements, partial-message output and `--permission-prompt-tool=stdio`. It applies only explicitly selected startup options, including model, instructions or an output schema. It preserves normal native settings, session persistence and permission handling. Native skills remain available. Native idle initialization, session identity and matching acknowledgements establish capability. Version labels and missing diagnostic version metadata do not disable compatible controls or file history.
298
+ Each controlled session has one native `claude` process in the authorized workspace while it is in use. A session idle for 60 minutes since its last turn ended, or since it opened, gives up its process: HQ reads its native settings once and closes the process, and the session stays idle with no state transition. Its skills and configuration reads answer from what it kept, an interrupt is refused as for any idle session, and stopping or releasing it needs no process. Input, renames, extension control and MCP reads first reopen it with `--resume`, or `--session-id` when it never had input, and its kept settings. A parked session keeps its controlled-thread slot, of 32 per runtime, and a runtime restart treats it like any other managed Claude session. A running or waiting session is never stopped, and neither is one with a background command still running, as Claude's `system:background_tasks_changed` list reports it, since closing its process would end the command; it waits another idle period instead. HQ adds structured input/output, replayed user-message acknowledgements, partial-message output and `--permission-prompt-tool=stdio`. It applies only explicitly selected startup options, including model, instructions or an output schema. It preserves normal native settings, session persistence and permission handling. Native skills remain available. Native idle initialization, session identity and matching acknowledgements establish capability. Version labels and missing diagnostic version metadata do not disable compatible controls or file history.
286
299
 
287
300
  Creation chooses a native UUID without inference, then names that exact session. Resume uses native `--resume` and verifies the session-id fence on the name control before marking the session idle. The operator's handoff confirmation establishes that another CLI controller is closed; file timestamps and file-backed unknown states do not establish this. Independently running CLIs are outside HQ's state-directory coordination boundary.
288
301
 
289
302
  An ordinary message is submitted only while idle. Its native UUID becomes the turn identity. A matching native replay or result acknowledges delivery, and the native result establishes completion. A request-success envelope can acknowledge a name change or interruption without a response body. HQ never writes queued follow-up input into Claude's own busy queue; the shared HQ queue dispatches it only after the previous result. Interruption acknowledgement alone does not establish a stop. An error result is classified as interrupted only when the qualified native interruption marker was observed for an explicitly interrupted input. Other terminal errors remain failed.
290
303
 
291
- Claude questions use exact question text as their answer identity and expose whether multiple selections are supported. Claude can_use_tool permissions use response `{ kind: 'decision', decision: 'accept' | 'decline' }`; question replies use `{ kind: 'answers', answers }`. The response kind `permission` with a turn/session scope belongs to Codex additional permissions. Tool permissions offer `accept` or `decline` for the displayed input only. Complete request details include native policy hints and reasons as untrusted display data; none authorizes a response. Unsupported permission fields or interaction surfaces receive an unsupported-request error. Requests requiring a native interaction card cannot be answered with generic approval; supported `AskUserQuestion` cards use their typed answer contract. Session-wide permission changes are unavailable; HQ does not apply native permission suggestions automatically. A reply is written through the separate control channel and acknowledged only by the matching tool result. Tool execution can still fail after that acknowledgement. Reused raw request IDs in different CLI processes have distinct controller scopes. Prompt bodies and replies remain out of SQLite.
304
+ Claude also starts turns of its own while no HQ input's turn is active, such as after a background command finishes. Claude sends no user message for such a turn, so HQ records it under an ID it generates: the thread reports running from the turn's first frame, its items stream as live items under that ID, its permission prompts are presented and answered like any other, Stop interrupts it, and its result completes it without a captured result, since no action owns it. Input sent while it runs waits in the HQ queue. Input written just before it began is replayed by Claude after its result, as its own turn with its own result; when that turn outlasts the 30-second acknowledgement bound, the input's receipt is uncertain until the replay acknowledges it. A frame that fits none of these rules still makes the session unavailable.
305
+
306
+ Claude questions use exact question text as their answer identity and expose whether multiple selections are supported. Claude can_use_tool permissions use response `{ kind: 'decision', decision: 'accept' | 'decline' }`; question replies use `{ kind: 'answers', answers }`. The response kind `permission` with a turn/session scope belongs to Codex additional permissions. Tool permissions offer `accept` or `decline` for the displayed input only. Complete request details include native policy hints and reasons as untrusted display data; none authorizes a response. Fields Claude adds to a permission request that HQ doesn't list are dropped, so the request still reaches the operator with its known fields, and the reply still holds only the displayed input. Unsupported interaction surfaces receive the error `HQ couldn't present this request`, which Claude records as the tool call's failed result. Requests requiring a native interaction card cannot be answered with generic approval; supported `AskUserQuestion` cards use their typed answer contract. Session-wide permission changes are unavailable; HQ does not apply native permission suggestions automatically. A reply is written through the separate control channel and acknowledged only by the matching tool result. Tool execution can still fail after that acknowledgement. Reused raw request IDs in different CLI processes have distinct controller scopes. Prompt bodies and replies remain out of SQLite.
292
307
 
293
308
  Both providers support turn-correlated MCP `form` and `url` elicitation. Forms use bounded local JSON Schema validation (8 KiB, 16 levels, 1,024 nodes); responses stay within the action envelope’s 32 KiB budget. Unknown modes, unsupported schemas and Codex requests without a native turn are denied. Elicitation URLs are HTTP(S) links without embedded credentials; applications decide how to display or open them. Never render native strings as HTML or terminal instructions, and never infer a permission decision from model output or form metadata. Codex acknowledges an elicitation reply through its exact native request-resolution event. Claude supplies no equivalent form-reply acknowledgement: a successful write stays submitted, and terminal completion or cancellation expires the request and makes its unresolved reply uncertain. Retrying that same action returns its receipt without sending again.
294
309
 
@@ -308,6 +323,8 @@ Trusted runtime construction also accepts `codexExtraSkillRoots?: string[]` and
308
323
 
309
324
  `codexDaemonLauncher?: string[]`, also trusted, names a command and its arguments that run `codex app-server daemon start`, such as `['systemd-run', '--user', '--scope', '--quiet', '--collect']`. HQ runs the start through it, while the proxy still runs directly. Codex's daemon detaches into its own session, but on Linux it stays in the cgroup of whatever started it, so a host that runs as a systemd service and starts the daemon itself would take the daemon, and the work of every terminal session on it, down whenever the service stops. A new scope gives the daemon a lifetime of its own. The installed `serve` command doesn't expose it.
310
325
 
326
+ `isPreviousRuntimeStopped?: (owner: { pid: number; createdAt: string }) => Promise<boolean>`, also trusted, lets startup recover a state root a runtime left behind after an unclean exit, such as a crash or a SIGKILL. It is called only when the recorded owner's process no longer exists, and must resolve true only when no process of that runtime remains, for example because the service's cgroup holds only the caller and its descendants. Startup then removes the owner record, only while it still holds the bytes it checked, and claims the state root again; in the same step it removes a `.runtime/hq.lock` whose holder no longer exists and a leftover `hq.sock`, only when it is a socket and not a symbolic link. When the owner's process exists, no check is supplied, or the check resolves false or rejects, startup fails with JG_AGENT_HQ_RUNTIME_ALREADY_OWNED as before, with a rejected check as the private cause. Removing a record after checking it isn't atomic, so the host must guarantee that at most one caller reclaims a given state root at a time; a starter without a check can't take a root a reclaimer is checking, because its exclusive create fails while the old record exists. The installed `serve` command doesn't expose it.
327
+
311
328
  ## Control reads and reconnect
312
329
 
313
330
  | Command | Fields | Result |
@@ -415,14 +432,18 @@ Live reads accept `afterRevision`. A matching revision returns `unchanged: true`
415
432
 
416
433
  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.
417
434
 
418
- | Area | Executed evidence | Boundary |
419
- | ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
420
- | Provider integration | Public contract tests route a third provider, isolate unavailable providers and tolerate additive fields and future version labels. Native lifecycle, configuration, files, account and extension checks are listed in their sections above. | Each additional adapter needs its own native qualification. |
421
- | Identity and native interaction | Both providers retained managed/native identities after compaction and reconnect with a fresh runtime epoch. Codex interruption and continuation passed. Claude AskUserQuestion and scoped MCP permission replies used exact native identities. | A timed-out compaction retained uncertain delivery even when completion later arrived; it was not resent. Explicit resume followed confirmed controller shutdown. |
422
- | Recovery | After removing all eight qualification transcripts, offline recovery retained the host preference and providers stayed idle. | Native transcripts, repository files and authentication remain separate recovery responsibilities. |
423
- | Shared Codex daemon | Codex 0.164.0: a terminal `codex` session ran on the shared daemon and appeared in `thread/list`. Without subscribing, HQ saw its `thread/status/changed`; after rejoining with `thread/resume`, HQ received the terminal's live turn and item notifications. A thread HQ created appeared in the terminal's `codex resume` picker, and closing HQ's connection left the daemon and the terminal session running. The daemon confirmed HQ's interrupt and close. Per-thread skill roots and output schemas worked on HQ threads, while another client's catalog and thread never saw the roots. Sessions read their own thread ID from `CODEX_THREAD_ID`. | A terminal started with `-c` overrides runs its thread in its own process (`source: cli`): it is listed, but a second writer is refused, so it cannot be followed live. The restart check ran against a separate app-server on its own socket rather than the shared daemon, which was serving other work: within one keepalive interval the session became uncertain and nothing was resent. A session Codex reloads from disk loses its capability roots. |
424
- | Claude active sessions | Claude Code 2.1.310 answered `claude agents --json` in 0.16 s. Interactive entries carry `status` (`busy`, `waiting`, `idle`) and `pid`; background entries carry `id` and `state` (`blocked`). Sessions HQ starts in structured mode are listed as interactive under their HQ name and disappear after close. | The list describes running processes only; history still comes from transcripts. |
425
- | Host coverage | Linux x86_64 package checks passed on Node 24.15.0 and 24.22.1. Identity, native interaction and recovery ran on the floor and on 24.22.1. | No macOS host was available for this run. Windows is outside the declared host contract. |
435
+ | Area | Executed evidence | Boundary |
436
+ | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
437
+ | Provider integration | Public contract tests route a third provider, isolate unavailable providers and tolerate additive fields and future version labels. Native lifecycle, configuration, files, account and extension checks are listed in their sections above. | Each additional adapter needs its own native qualification. |
438
+ | Identity and native interaction | Both providers retained managed/native identities after compaction and reconnect with a fresh runtime epoch. Codex interruption and continuation passed. Claude AskUserQuestion and scoped MCP permission replies used exact native identities. | A timed-out compaction retained uncertain delivery even when completion later arrived; it was not resent. Explicit resume followed confirmed controller shutdown. |
439
+ | Recovery | After removing all eight qualification transcripts, offline recovery retained the host preference and providers stayed idle. | Native transcripts, repository files and authentication remain separate recovery responsibilities. |
440
+ | Shared Codex daemon | Codex 0.164.0: a terminal `codex` session ran on the shared daemon and appeared in `thread/list`. Without subscribing, HQ saw its `thread/status/changed`; after rejoining with `thread/resume`, HQ received the terminal's live turn and item notifications. A thread HQ created appeared in the terminal's `codex resume` picker, and closing HQ's connection left the daemon and the terminal session running. The daemon confirmed HQ's interrupt and close. Per-thread skill roots and output schemas worked on HQ threads, while another client's catalog and thread never saw the roots. Sessions read their own thread ID from `CODEX_THREAD_ID`. | A terminal started with `-c` overrides runs its thread in its own process (`source: cli`): it is listed, but a second writer is refused, so it cannot be followed live. The restart check ran against a separate app-server on its own socket rather than the shared daemon, which was serving other work: within one keepalive interval the session became uncertain and nothing was resent. A session Codex reloads from disk loses its capability roots. |
441
+ | Codex across restarts | Codex 0.166.0 on 2026-11-01: a turn whose client closed its connection mid-turn ran to completion in the daemon, which kept the session loaded and idle. A command approval that arrived before the connection closed stayed pending, with the session `waitingOnApproval`; after a new connection joined with `thread/resume`, the daemon sent it again under the same request ID, and answering it completed the turn. |
442
+ | Claude permission requests | Claude Code 2.1.316 on 2026-11-01, in the default permission mode: a Write request carried `description`, `display_name`, `input`, `permission_suggestions`, `subtype`, `tool_name` and `tool_use_id`, and an error reply was recorded in the transcript as the tool call's failed result with the reply's text. | Fields such as `decision_reason_code` and `tool_kind` appear only in other modes, so their shape comes from the CLI's own code, not an observed request. |
443
+ | Claude turns it starts itself | Claude Code 2.1.316 on 2026-11-01, in the auto permission mode with its input held open: when a background command finished after its turn, Claude sent `system:task_notification` and started a turn of its own, `system:init` then stream and assistant frames, ending in a `result` without `user_message_uuid`. Input written during that turn was replayed after its result as its own turn. Each HQ input's replayed message came before its turn's first stream and assistant frames. An interrupt ended such a turn with the interruption marker, then an `error_during_execution` result. `system:background_tasks_changed` listed the background commands running, and was empty once the last one ended. | The frame order is an observation of this version, not a native contract. |
444
+ | Approvals on other clients' sessions | Codex 0.166.0 on 2026-11-01, on the shared daemon: connection A joined a thread connection B started, with `thread/resume`. When B's turn asked to run a command, the daemon sent the same approval request, with the same request ID, to both connections, and sent both `serverRequest/resolved` once B answered. | A thread only accepts `thread/resume` once its first turn has written its rollout. |
445
+ | Claude active sessions | Claude Code 2.1.310 answered `claude agents --json` in 0.16 s. Interactive entries carry `status` (`busy`, `waiting`, `idle`) and `pid`; background entries carry `id` and `state` (`blocked`). Sessions HQ starts in structured mode are listed as interactive under their HQ name and disappear after close. | The list describes running processes only; history still comes from transcripts. |
446
+ | Host coverage | Linux x86_64 package checks passed on Node 24.15.0 and 24.22.1. Identity, native interaction and recovery ran on the floor and on 24.22.1. | No macOS host was available for this run. Windows is outside the declared host contract. |
426
447
 
427
448
  The identity and recovery checks used gpt-6.1-sol with medium effort and claude-opus-5-5 with medium effort in disposable workspaces on 2026-10-23. The shared-daemon and Claude active-session checks ran on 2026-10-25 with the installed CLIs' default models in disposable workspaces. The [Node release index](https://nodejs.org/dist/index.json) identified 24.22.1 as the current LTS patch at qualification time. Local checks do not establish a published npm release or a deployed website.
428
449
 
@@ -44,7 +44,8 @@ export declare const createActions: (registry: ReturnType<typeof createProviderR
44
44
  /** Attaches sensitive presentation only to the exact current native request. */
45
45
  approvalPresentation(approval: INativeApprovalSummary): INativeApproval;
46
46
  /**
47
- * Stops admission, interrupts active work, cleans native terminals and confirms shutdown.
47
+ * Stops admission, interrupts active work, cleans native terminals and confirms shutdown. A
48
+ * session that outlives the runtime keeps running, with its terminals, for the next runtime.
48
49
  * @returns A promise resolved after native exit and release of durable control ownership.
49
50
  * @throws
50
51
  * - JG_AGENT_HQ_PROVIDER_FAILED: The HQ provider integration failed
@@ -1,11 +1,13 @@
1
1
  import { createHmac, randomUUID } from 'node:crypto';
2
2
  import { Exception, extractMessage, isException } from 'jg-exception';
3
+ import { delay } from 'jg-utilities';
3
4
  import { z } from 'zod';
4
5
  import { getErrorKind } from '../errors/index.js';
5
6
  import { retainNativeLineage, readInputFiles } from '../providers/index.js';
6
7
  import { capabilityUnavailable } from '../providers/registry/index.js';
7
8
  import { resolveWorkspaceTarget } from '../runtime/state/index.js';
8
9
  import { LiveItems } from './live/index.js';
10
+ import { RESYNC_REREAD_DELAY_SECONDS, Resyncs, decideResync, } from './resync/index.js';
9
11
  import { ActionWaits } from './waits/index.js';
10
12
  // item observations never change a receipt, and are too frequent to wake waits for
11
13
  const ITEM_OBSERVATIONS = new Set([
@@ -237,6 +239,7 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
237
239
  const thread = await store.getThread(receipt.threadId);
238
240
  if (thread?.nativeId && (outcome.kind === 'closed' || outcome.kind === 'archived')) {
239
241
  controlled.delete(key(thread.provider, thread.nativeId));
242
+ watched.delete(key(thread.provider, thread.nativeId));
240
243
  }
241
244
  if (thread?.state === 'completed' &&
242
245
  outcome.kind !== 'control-accepted' &&
@@ -244,6 +247,15 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
244
247
  advanceQueue(thread.id, thread.provider);
245
248
  return receipt;
246
249
  };
250
+ /**
251
+ * Applies a turn's acknowledgement after the lifecycle events reported before it, such as a
252
+ * turn the agent started and ended while the input waited, so the ledger sees them in order.
253
+ * @returns The updated receipt.
254
+ */
255
+ const applyAfterEvents = async (outcome) => {
256
+ await lane.catch(() => undefined);
257
+ return apply(outcome);
258
+ };
247
259
  const continuePhases = async (receipt, thread) => {
248
260
  const requestId = receipt.nativeRequestId;
249
261
  if (!requestId || !thread.nativeId || closing)
@@ -381,7 +393,7 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
381
393
  conflict();
382
394
  live.reset(key(thread.provider, nativeId));
383
395
  const turn = await control.compactThread(requestId, nativeId);
384
- await apply({
396
+ await applyAfterEvents({
385
397
  kind: 'compaction-accepted',
386
398
  actionId: receipt.id,
387
399
  requestId,
@@ -396,7 +408,7 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
396
408
  await control.validateInput(nativeId, input);
397
409
  hasDispatched = true;
398
410
  const turn = await control.startTurn(requestId, nativeId, input.text, input.skill, input.settings, files);
399
- await apply({
411
+ await applyAfterEvents({
400
412
  kind: 'turn-accepted',
401
413
  actionId: receipt.id,
402
414
  requestId,
@@ -449,6 +461,7 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
449
461
  const observe = async (observation) => {
450
462
  const result = await recordObservation(observation);
451
463
  if (observation.kind === 'turn-completed') {
464
+ watched.delete(key(observation.provider, observation.nativeThreadId));
452
465
  for (const [id, prompt] of prompts)
453
466
  if (prompt.native.provider === observation.provider &&
454
467
  prompt.native.nativeThreadId === observation.nativeThreadId &&
@@ -464,15 +477,100 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
464
477
  if (result.canDispatchQueued && result.thread)
465
478
  advanceQueue(result.thread.id, result.thread.provider);
466
479
  };
480
+ /** Orders one observation about a controlled session behind the events before it. */
481
+ const receiveObservation = (provider, observation) => {
482
+ if (!('nativeThreadId' in observation) ||
483
+ !observation.nativeThreadId ||
484
+ !controlled.has(key(provider, observation.nativeThreadId)))
485
+ return;
486
+ if (observation.kind === 'turn-completed')
487
+ live.completeTurn(key(provider, observation.nativeThreadId), observation.nativeTurnId);
488
+ enqueue(provider, () => observe(observation));
489
+ };
490
+ // ends the waits of delayed re-checks when the runtime closes
491
+ const resyncLifetime = new AbortController();
492
+ /*
493
+ * Sessions a re-check after an unidentified loss left running, or skipped while an action was in
494
+ * flight. Codex reporting one idle while its turn is recorded as active triggers the re-check a
495
+ * lost turn end gets, since that turn's completion may have been the lost message.
496
+ */
497
+ const watched = new Set();
498
+ /**
499
+ * Makes up for a lost notification by reading the session from its native process, outside the
500
+ * shared lane, then orders only the resulting observation behind the events before it. A failed
501
+ * read makes the session uncertain.
502
+ * @returns A promise resolved once the decision is applied or scheduled.
503
+ */
504
+ const recheck = async (provider, nativeId, request) => {
505
+ if (closing || !controlled.has(key(provider, nativeId)))
506
+ return;
507
+ const record = await store.getTurnRecord(provider, nativeId);
508
+ if (!record)
509
+ return;
510
+ // an action in flight may have started a turn the record doesn't hold yet
511
+ if (request.lost === 'unknown' && record.hasPendingAction) {
512
+ watched.add(key(provider, nativeId));
513
+ return;
514
+ }
515
+ let latest;
516
+ try {
517
+ const control = await registry.get(provider);
518
+ if (!control.readReattachment)
519
+ capabilityUnavailable();
520
+ latest = (await control.readReattachment(nativeId, record.workspaceRoot)).latestTurn;
521
+ }
522
+ catch {
523
+ latest = undefined;
524
+ }
525
+ const decision = latest === undefined
526
+ ? { kind: 'uncertain' }
527
+ : decideResync(record, latest, request);
528
+ if (decision.kind === 'complete')
529
+ receiveObservation(provider, {
530
+ kind: 'turn-completed',
531
+ provider,
532
+ nativeThreadId: nativeId,
533
+ nativeTurnId: decision.nativeTurnId,
534
+ state: decision.state,
535
+ });
536
+ else if (decision.kind === 'gap')
537
+ live.markGap(key(provider, nativeId));
538
+ else if (decision.kind === 'watch') {
539
+ live.markGap(key(provider, nativeId));
540
+ watched.add(key(provider, nativeId));
541
+ }
542
+ else if (decision.kind === 'reread') {
543
+ const reread = { lost: request.lost, isLastAttempt: true, turnId: decision.nativeTurnId };
544
+ // the wait holds back no other session's re-check
545
+ runOwned(async () => {
546
+ try {
547
+ await delay(RESYNC_REREAD_DELAY_SECONDS, { signal: resyncLifetime.signal });
548
+ }
549
+ catch {
550
+ return;
551
+ }
552
+ if (!closing)
553
+ resyncs.request(provider, nativeId, reread);
554
+ });
555
+ }
556
+ else if (decision.kind === 'uncertain')
557
+ enqueue(provider, () => observe({ kind: 'native-unavailable', provider, nativeThreadId: nativeId }));
558
+ };
559
+ const resyncs = new Resyncs(recheck, runOwned);
467
560
  registry.setEvents({
468
- observe(provider, observation) {
469
- if (!('nativeThreadId' in observation) ||
470
- !observation.nativeThreadId ||
471
- !controlled.has(key(provider, observation.nativeThreadId)))
561
+ observe: receiveObservation,
562
+ resync(provider, nativeId, lost) {
563
+ if (closing)
472
564
  return;
473
- if (observation.kind === 'turn-completed')
474
- live.completeTurn(key(provider, observation.nativeThreadId), observation.nativeTurnId);
475
- enqueue(provider, () => observe(observation));
565
+ const request = { lost, isLastAttempt: false, turnId: null };
566
+ // without a session, every session this runtime controls through the provider is read
567
+ if (nativeId === undefined) {
568
+ for (const thread of controlled.values())
569
+ if (thread.provider === provider)
570
+ resyncs.request(provider, thread.nativeId, request);
571
+ }
572
+ else if (controlled.has(key(provider, nativeId)))
573
+ resyncs.request(provider, nativeId, request);
476
574
  },
477
575
  item(provider, nativeId, item, isComplete, replacedIds) {
478
576
  if (!controlled.has(key(provider, nativeId)))
@@ -494,9 +592,19 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
494
592
  },
495
593
  session(provider, nativeId, state) {
496
594
  observingProviders.add(provider);
595
+ const sessionKey = key(provider, nativeId);
497
596
  // a session this runtime controls reports its transitions through its own thread state
498
- if (controlled.has(key(provider, nativeId)))
597
+ if (controlled.has(sessionKey)) {
598
+ if (watched.has(sessionKey) && state !== 'running' && state !== 'waiting') {
599
+ watched.delete(sessionKey);
600
+ resyncs.request(provider, nativeId, {
601
+ lost: 'turn-completed',
602
+ isLastAttempt: false,
603
+ turnId: null,
604
+ });
605
+ }
499
606
  return;
607
+ }
500
608
  enqueue(provider, () => store.observeSessions(provider, [{ nativeId, state }], false));
501
609
  },
502
610
  delta(provider, nativeId, turnId, itemId, text) {
@@ -504,7 +612,13 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
504
612
  live.append(key(provider, nativeId), turnId, itemId, text);
505
613
  },
506
614
  prompt(provider, prompt) {
507
- if (!controlled.has(key(provider, prompt.nativeThreadId)) || prompts.size >= 32 || closing) {
615
+ // a session that outlives the runtime keeps its request for the next runtime to answer
616
+ if (closing && registry.keepsSessions(provider))
617
+ return;
618
+ // the client driving a session HQ doesn't control answers its requests, so HQ stays silent
619
+ if (!controlled.has(key(provider, prompt.nativeThreadId)))
620
+ return;
621
+ if (prompts.size >= 32 || closing) {
508
622
  runNativeOwned(provider, prompt.nativeThreadId, prompt.reject);
509
623
  return;
510
624
  }
@@ -531,6 +645,14 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
531
645
  });
532
646
  });
533
647
  },
648
+ unpresentable(provider, nativeId, reject) {
649
+ if (closing && registry.keepsSessions(provider))
650
+ return;
651
+ // only a session HQ controls waits on HQ for an answer
652
+ if (!controlled.has(key(provider, nativeId)))
653
+ return;
654
+ runNativeOwned(provider, nativeId, reject);
655
+ },
534
656
  outcome(provider, outcome, nativeThread) {
535
657
  if (closing)
536
658
  return;
@@ -849,6 +971,78 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
849
971
  }
850
972
  return admitted.receipt;
851
973
  };
974
+ /**
975
+ * Rejoins one session the previous runtime left running in a native process that outlives it.
976
+ * The session is bound to this runtime as that process reports it before joining, so a request
977
+ * the process sends again on joining finds its turn, and a turn that finished between the two
978
+ * reads then completes. A session that can't be rejoined has its ownership marked uncertain.
979
+ * @returns A promise resolved once the session is rejoined or marked uncertain.
980
+ * @throws
981
+ * - JG_AGENT_HQ_STORE_FAILED: The HQ store failed
982
+ */
983
+ const reattachThread = async (thread) => {
984
+ const nativeId = thread.nativeId;
985
+ let isOwned = false;
986
+ try {
987
+ const control = await registry.get(thread.provider);
988
+ if (!control.readReattachment || !control.reattachThread)
989
+ capabilityUnavailable();
990
+ await validateRoot(thread);
991
+ const read = await control.readReattachment(nativeId, thread.workspaceRoot);
992
+ if (read.thread.nativeState === 'systemError')
993
+ agentUnavailable();
994
+ const bound = await store.reattach({
995
+ threadId: thread.id,
996
+ latestTurn: read.latestTurn && {
997
+ nativeTurnId: read.latestTurn.nativeId,
998
+ state: read.latestTurn.state,
999
+ },
1000
+ });
1001
+ waits.notifyThread(thread.id);
1002
+ if (bound?.thread?.ownership !== 'managed' || bound.thread.runtimeEpoch !== epoch)
1003
+ return;
1004
+ own(thread.provider, nativeId);
1005
+ isOwned = true;
1006
+ const joined = await control.reattachThread(`${randomUUID()}:reattach`, nativeId, thread.workspaceRoot);
1007
+ const turnId = bound.thread.activeTurnId;
1008
+ const latest = joined.latestTurn;
1009
+ if (turnId && latest?.nativeId === turnId && latest.state !== 'running') {
1010
+ const { state } = latest;
1011
+ live.completeTurn(key(thread.provider, nativeId), turnId);
1012
+ enqueue(thread.provider, () => observe({
1013
+ kind: 'turn-completed',
1014
+ provider: thread.provider,
1015
+ nativeThreadId: nativeId,
1016
+ nativeTurnId: turnId,
1017
+ state,
1018
+ }));
1019
+ }
1020
+ if (bound.canDispatchQueued)
1021
+ advanceQueue(thread.id, thread.provider);
1022
+ }
1023
+ catch {
1024
+ if (isOwned)
1025
+ await recordObservation({
1026
+ kind: 'native-unavailable',
1027
+ provider: thread.provider,
1028
+ nativeThreadId: nativeId,
1029
+ });
1030
+ else
1031
+ await store.quarantineThread(thread.id);
1032
+ waits.notifyThread(thread.id);
1033
+ }
1034
+ };
1035
+ /** Rejoins, one at a time, every session the previous runtime left running. */
1036
+ const reattach = async () => {
1037
+ let batch = await store.listReattachable();
1038
+ while (batch.length > 0 && !closing) {
1039
+ for (const thread of batch)
1040
+ if (!closing)
1041
+ await reattachThread(thread);
1042
+ batch = await store.listReattachable();
1043
+ }
1044
+ };
1045
+ runOwned(reattach);
852
1046
  return {
853
1047
  /**
854
1048
  * Reads live native authentication presentation without replaying an interrupted action.
@@ -936,7 +1130,8 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
936
1130
  };
937
1131
  },
938
1132
  /**
939
- * Stops admission, interrupts active work, cleans native terminals and confirms shutdown.
1133
+ * Stops admission, interrupts active work, cleans native terminals and confirms shutdown. A
1134
+ * session that outlives the runtime keeps running, with its terminals, for the next runtime.
940
1135
  * @returns A promise resolved after native exit and release of durable control ownership.
941
1136
  * @throws
942
1137
  * - JG_AGENT_HQ_PROVIDER_FAILED: The HQ provider integration failed
@@ -948,11 +1143,13 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
948
1143
  */
949
1144
  async close() {
950
1145
  closing = true;
1146
+ resyncLifetime.abort();
951
1147
  let cleanupFailure;
952
1148
  try {
953
1149
  await Promise.allSettled([...admissions]);
1150
+ const stopped = [...controlled.values()].filter(({ provider }) => !registry.keepsSessions(provider));
954
1151
  // Active turn IDs come from ordered native evidence, never from an interrupt acknowledgement.
955
- await Promise.all([...controlled.values()].map(async ({ provider, nativeId }) => {
1152
+ await Promise.all(stopped.map(async ({ provider, nativeId }) => {
956
1153
  const thread = await store.getThreadByNativeId(provider, nativeId);
957
1154
  if (thread?.activeTurnId) {
958
1155
  try {
@@ -968,7 +1165,7 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
968
1165
  await Promise.allSettled([...tasks]);
969
1166
  await lane.catch(() => undefined);
970
1167
  const providerStates = new Map(registry.statuses().map((status) => [status.provider, status.state]));
971
- for (const { provider, nativeId } of controlled.values()) {
1168
+ for (const { provider, nativeId } of stopped) {
972
1169
  if (providerStates.get(provider) === 'unavailable')
973
1170
  continue;
974
1171
  const control = await registry.get(provider);
@@ -0,0 +1,3 @@
1
+ import type { IResyncLoss } from '../../providers/index.js';
2
+ export declare const RESYNC_REREAD_DELAY_SECONDS = 2;
3
+ export declare const RESYNC_LOSS_ORDER: readonly IResyncLoss[];
@@ -0,0 +1,9 @@
1
+ // how long a re-check waits before reading again a turn whose saved state may trail its notification
2
+ export const RESYNC_REREAD_DELAY_SECONDS = 2;
3
+ // lost kinds in rising order of what their re-check must prove; merged requests keep the highest
4
+ export const RESYNC_LOSS_ORDER = [
5
+ 'unknown',
6
+ 'turn-started',
7
+ 'turn-completed',
8
+ 'approval-resolved',
9
+ ];
@@ -0,0 +1,4 @@
1
+ export type { IResyncDecision, IResyncRequest } from './types.js';
2
+ export { RESYNC_REREAD_DELAY_SECONDS } from './constants.js';
3
+ export { decideResync } from './utilities.js';
4
+ export { Resyncs } from './resync.js';