jg-agent-hq 13.4.2 → 13.5.1
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.
- package/CHANGELOG.md +10 -0
- package/README.md +7 -0
- package/api/README.md +8 -4
- package/dist/actions/actions.js +5 -2
- package/dist/actions/admission/admission.js +27 -4
- package/dist/actions/dispatch/dispatch.d.ts +4 -4
- package/dist/actions/dispatch/dispatch.js +25 -2
- package/dist/actions/events/events.d.ts +4 -2
- package/dist/actions/events/events.js +217 -26
- package/dist/actions/types.d.ts +11 -5
- package/dist/providers/claude/adapter.js +21 -5
- package/dist/providers/claude/agents/agents.d.ts +3 -2
- package/dist/providers/claude/agents/agents.js +20 -2
- package/dist/providers/claude/agents/index.d.ts +1 -1
- package/dist/providers/claude/agents/types.d.ts +5 -0
- package/dist/providers/claude/control/control.d.ts +29 -2
- package/dist/providers/claude/control/control.js +260 -31
- package/dist/providers/claude/control/quarantine.d.ts +12 -0
- package/dist/providers/claude/control/quarantine.js +125 -0
- package/dist/providers/claude/control/stream.d.ts +2 -1
- package/dist/providers/claude/control/stream.js +6 -3
- package/dist/providers/claude/control/types.d.ts +7 -12
- package/dist/providers/claude/rpc.d.ts +14 -1
- package/dist/providers/claude/rpc.js +105 -11
- package/dist/providers/index.d.ts +1 -1
- package/dist/providers/process.d.ts +1 -0
- package/dist/providers/process.js +2 -0
- package/dist/providers/registry/registry.d.ts +16 -3
- package/dist/providers/registry/registry.js +127 -37
- package/dist/providers/registry/types.d.ts +2 -2
- package/dist/providers/types.d.ts +56 -13
- package/dist/runtime/runtime.js +4 -1
- package/dist/store/control/admission/admission.model.js +33 -5
- package/dist/store/control/admission/constants.js +1 -1
- package/dist/store/control/lifecycle/lifecycle.model.d.ts +12 -0
- package/dist/store/control/lifecycle/lifecycle.model.js +52 -4
- package/dist/store/control/observations/observations.model.js +1 -1
- package/dist/store/control/outcomes/outcomes.model.js +18 -3
- package/dist/store/control/types.d.ts +2 -0
- package/docs/recovery.md +15 -1
- package/errors/README.md +6 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 13.5.1
|
|
4
|
+
|
|
5
|
+
- Allow confirmed recovery of a known quarantined Codex identity in the current HQ runtime, including loaded active, idle and unloaded sessions, without restarting HQ. Verify the native turn before and after joining, retain paused queues and unresolved receipts, and send no settings or input. Healthy controls, pending dispatches and unverified identities remain refused.
|
|
6
|
+
|
|
7
|
+
## 13.5.0
|
|
8
|
+
|
|
9
|
+
- Quarantine attributable Claude interpretation, registry and persisted-evidence failures without terminating native work or other controlled sessions. Suspend rich interpretation and controls; require fresh native idle, a known empty full task snapshot and no unresolved requests before automatic cleanup. Partial task activity invalidates older emptiness, and ordinary idle parking cannot bypass quarantine.
|
|
10
|
+
- Return only the matching conversation to managed/inactive after its exact owned process group is proven stopped and its controller is released. Resume keeps its native identity and history; uncertain input stays uncertain, pending approvals expire and queued work stays paused without replay. The storage schema and action key are unchanged.
|
|
11
|
+
- Reuse confirmed `thread-close` with `interrupt: true` to stop a current-runtime owned quarantined Claude session and unfinished background work. Preserve action deduplication, close/cleanup races and ownership fences without guessing a turn or adding a recovery command.
|
|
12
|
+
|
|
3
13
|
## 13.4.2
|
|
4
14
|
|
|
5
15
|
- Reconcile completed Claude messages and tool activity by their session-scoped native UUID when autonomous follow-ups have a generated live turn ID but saved history groups them under the preceding input. Completed activity no longer remains live below later answers. Operator inputs retain exact turn/provenance checks, and Codex reconciliation is unchanged.
|
package/README.md
CHANGED
|
@@ -75,6 +75,12 @@ Use `models --provider <id>` for native model and effort choices, and `configura
|
|
|
75
75
|
|
|
76
76
|
Native execution settings, instructions, skills and tool permissions remain with each CLI. Claude uses an owned structured process per controlled session, closes it after 60 idle minutes and reopens it for the next input, and steers its active turn with a structured user message. Close other CLI controllers before confirming adoption, resume or recovery. The runtime coordinates sessions sharing one state directory; it cannot lock independently running native CLIs. Integrating browser hosts can use durable host-action admission and operator-scoped reconciliation through the programmatic API; see the [browser host contract](api/README.md#browser-host-integration). The standalone CLI advertises only commands it implements.
|
|
77
77
|
|
|
78
|
+
When Claude sends structurally valid evidence HQ cannot interpret, HQ suspends that session's controls and live interpretation while its native work continues. It closes the quarantined controller automatically only after fresh native idle, a known empty task snapshot and no unresolved requests establish that work has finished. Unknown evidence or an unanswered approval keeps it alive; confirmed `thread-close` with `interrupt: true` explicitly stops its owned process group, including unfinished background work. Identity and transport-integrity failures retain their shutdown handling.
|
|
79
|
+
|
|
80
|
+
A quarantined known Codex identity offers confirmed recovery in the current runtime without an HQ restart. Recovery verifies the native turn before and after joining, sends no input or settings, keeps earlier queues paused and leaves uncertain receipts unresolved. Automatic reconnect still refuses changed turns; inspect the session and close competing clients before confirming recovery.
|
|
81
|
+
|
|
82
|
+
After verified owned-group shutdown and controller release, that conversation becomes managed and inactive without restarting HQ. Resume retains its native identity and history. Unacknowledged input stays uncertain, earlier queued work stays paused, and pending approvals expire. Unconfirmed shutdown or a competing native terminal keeps ownership uncertain; another controlled conversation remains usable. See [Claude connection recovery](docs/recovery.md#claude-connection-recovery).
|
|
83
|
+
|
|
78
84
|
Approval reads return indexed, cursor-paginated pending, answered and expired metadata after reconnect or restart. Sensitive presentation is available only while the exact native request is live. Native permissions require explicit responses; unknown request kinds or scopes are denied. See [native replies and reconnect reads](api/README.md#thread-control-and-live-input).
|
|
79
85
|
|
|
80
86
|
Codex asynchronous questions retain their explicit `asyncInput` metadata through live items, saved history, details and evidence. They do not replace ordinary final results or create native approval requests. Trusted Node hosts use `hq.observeAsyncInputs(listener)` to enqueue complete controlled-session observations and recovery work independently of browser reads. Hosts own durable question resolution and explicit ordinary-message or exact-turn steer answers. See [async questions](api/README.md#async-questions).
|
|
@@ -133,6 +139,7 @@ The [qualification matrix](api/README.md#qualification) records native journeys,
|
|
|
133
139
|
- `docs/website.md`: durable website architecture, verification and generated-asset sources.
|
|
134
140
|
- `docs/architecture.md`: provider and database ownership, schema initialization and host maintenance.
|
|
135
141
|
- `docs/recovery.md`: local snapshot coverage, offline recovery and the host's remote durability responsibilities.
|
|
142
|
+
- [`docs/delivery.md`](https://github.com/jesusgraterol/jg-agent-hq/blob/main/docs/delivery.md): ordered development, main and npm publication stops, operators and release verification.
|
|
136
143
|
|
|
137
144
|
`/docs` is reserved for concise, quickly scannable documentation of essential durable concepts and processes. API references remain outside `/docs`.
|
|
138
145
|
|
package/api/README.md
CHANGED
|
@@ -113,10 +113,14 @@ After a live Codex connection loss, the runtime rechecks the bounded cohort it c
|
|
|
113
113
|
|
|
114
114
|
Shutdown preserves a quarantined Codex record's uncertain ownership, producing runtime epoch and recorded native-turn evidence. The next runtime leaves it quarantined for explicit recovery, including when the native turn is still active. Stopping HQ does not prove that Codex stopped or that an uncertain action failed, and never converts that record into a managed inactive control.
|
|
115
115
|
|
|
116
|
+
A failed Claude connection first makes its conversation uncertain. Once the runtime proves the exact owned process group has exited and releases that controller, the matching known conversation becomes managed and inactive in the same runtime. Its producing epoch, active turn and pending action reference clear; pending approvals expire, submitted deliveries stay uncertain and queued entries stay paused. This proof does not complete an acknowledged turn or establish whether uncertain input ran. A stale controller, changed runtime/workspace/native identity, or competing native terminal cannot release a replacement owner. Failed shutdown proof retains uncertainty and prevents runtime ownership release. An explicit `thread-resume` can reopen the inactive conversation under its existing native identity without replaying earlier input.
|
|
117
|
+
|
|
116
118
|
Codex approval identities are scoped to their native connection, because a replacement daemon may reuse request IDs. A reissued request opens a new approval; earlier approvals stay expired. A response prepared for an earlier connection cannot write to or decline a request on its replacement. The native response still uses the exact request ID supplied by Codex.
|
|
117
119
|
|
|
118
120
|
## Providers and capabilities
|
|
119
121
|
|
|
122
|
+
A quarantined Claude controller closes automatically only after fresh matching native idle inventory, a known empty full task snapshot, no unresolved requests and no intervening activity. Default zero, unknown or stale evidence cannot authorize cleanup. The existing 60-minute parking timer is cancelled and cannot close quarantined work, including after a pending settings read. Unanswered native approvals may stall progress. A confirmed `thread-close` with `interrupt: true` can explicitly stop that exact current-runtime owned controller and its unfinished background work. Previous-runtime uncertainty, missing ownership handles or a competing terminal do not qualify. See [Claude connection recovery](../docs/recovery.md#claude-connection-recovery).
|
|
123
|
+
|
|
120
124
|
jg-agent-hq has two built-in providers, `codex` and `claude`. The runtime creates both adapters as it starts, as [runtime lifecycle](#runtime-lifecycle) describes, and bounds every adapter operation by 30 seconds and the runtime's lifetime. Each adapter owns its native protocol validation, processes, authentication, capabilities, history, skill invocation spelling and concrete session controls; the runtime doesn't parse an adapter's output again. Adapters clean up partial initialization before failing, and closing an adapter confirms that the resources it owns stopped. The runtime retains ownership evidence when cleanup cannot be confirmed. Failed construction is not automatically replayed.
|
|
121
125
|
|
|
122
126
|
An adapter reports normalized observations, items, deltas, prompts, outcomes, observed session states and connection loss. Each outcome echoes the request identity the runtime issued, from which the runtime derives the action it settles, and the runtime verifies the exact receipt, runtime, provider, native session and workspace. A late create/resume outcome also supplies verified native session metadata. Unknown control states cannot establish success or idle ownership. Native permission requests keep their exact reply channel and validation. The runtime answers requests only on sessions it controls: on one of those, a request the adapter can't present 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. A lost turn start, turn end, approval resolution or unidentified notification makes the runtime read the session again, or every session it controls through that provider when the session can't be known; a latest turn whose saved state is still in progress takes its state from the session's status.
|
|
@@ -143,7 +147,7 @@ Availability depends on the selected native connection and, for session metadata
|
|
|
143
147
|
|
|
144
148
|
Local qualification on 2026-10-23 used Codex 0.163.0 and Claude Code 2.1.309 with native settings and authentication in a disposable workspace. Both created and named sessions with selected models and startup instructions, acknowledged a text message, reported native completion and exposed live presentation. Both resumed the same native identity after runtime restart and applied next-turn model/effort selections with native readback. Both also accepted a PNG and UTF-8 document through the runtime's file-reference path and returned a validated structured READY result with per-turn token observations (Codex gpt-6.1-sol; Claude claude-haiku-4-5-20251001). Owned controllers and runtimes shut down cleanly. This checks those controls on this host; other controls and platforms require their own qualification.
|
|
145
149
|
|
|
146
|
-
An adapter failure that isn't one of the adapters' own exceptions uses JG_AGENT_HQ_PROVIDER_FAILED, retaining safe diagnostic causes. Canonical request/access/state errors and JG_AGENT_HQ_CAPABILITY_UNAVAILABLE retain their meaning. An explicit native rejection may carry `nativeRejection: true`; use it only when native rejection is proven. Timeouts and lost responses remain uncertain and are not retried with a new identity. Capability reads normally return availability data; an unusable descriptor does not disable unrelated session controls. Quota reads return an unavailable observation when no trustworthy measurement can be obtained.
|
|
150
|
+
An adapter failure that isn't one of the adapters' own exceptions uses JG_AGENT_HQ_PROVIDER_FAILED, retaining safe diagnostic causes. Canonical request/access/state errors and JG_AGENT_HQ_CAPABILITY_UNAVAILABLE retain their meaning. An explicit native rejection may carry `nativeRejection: true`; use it only when native rejection is proven. Timeouts and lost responses remain uncertain and are not retried with a new identity. Capability reads normally return availability data; an unusable descriptor does not disable unrelated session controls. Quota reads return an unavailable observation when no trustworthy measurement can be obtained. An unparseable control response or lifecycle backlog overflow normally quarantines the provider. For a verified owned Claude source, interpretation/schema failures, conflicting observation/approval evidence and overflow instead suspend only that controller's rich interpretation and controls while native work continues. Pending HQ promises reject with JG_AGENT_HQ_CLAUDE_FAILED and private diagnostic causes, without claiming native rejection. Stale source callbacks cannot affect a replacement controller. Live items stay in the runtime's memory and never enter these queues. SQLite failures still affect the shared store.
|
|
147
151
|
|
|
148
152
|
## Read commands
|
|
149
153
|
|
|
@@ -277,7 +281,7 @@ Send `{ kind: 'action', action: { id, runtimeEpoch, command } }`. Generate one U
|
|
|
277
281
|
| `thread-resume` | `threadId`, `operatorConfirmation`. Resumes an inactive managed thread; the runtime does not fetch its complete conversation bodies. |
|
|
278
282
|
| `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. |
|
|
279
283
|
| `thread-rename` | `threadId`, `name`. Changes the name only after the matching native acknowledgement. |
|
|
280
|
-
| `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.
|
|
284
|
+
| `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. For a verified current-runtime quarantined Claude controller, explicit interrupting close instead starts at clean/close, without guessing a turn; unknown work may still be running. |
|
|
281
285
|
| `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). |
|
|
282
286
|
| `message` | `threadId`, `input`. Starts a turn only while idle. |
|
|
283
287
|
| `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. |
|
|
@@ -289,13 +293,13 @@ Send `{ kind: 'action', action: { id, runtimeEpoch, command } }`. Generate one U
|
|
|
289
293
|
|
|
290
294
|
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.
|
|
291
295
|
|
|
292
|
-
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
|
|
296
|
+
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 requires inspected ownership evidence and a stopped producing runtime, except confirmed resume of a known quarantined Codex identity with no action in flight, which the current runtime can recover.
|
|
293
297
|
|
|
294
298
|
Version 13 expands the producer contract: a 12.x consumer's strict 32-character schema rejects a response containing a longer managed name. Run matching runtime and consumer releases. Storage remains compatible with 12.0.1, but a package downgrade first requires shortening all longer managed names with supported rename actions and resolving collisions; see [package downgrade](../docs/recovery.md#package-downgrade).
|
|
295
299
|
|
|
296
300
|
Codex may keep an idle native thread loaded after `thread/unsubscribe`, as when a terminal still holds it. An explicitly confirmed resume may reacquire that thread when its known managed control is inactive and managed, without settings overrides. Ordinary resume still refuses active native threads, uncertain managed ownership and already controlled idle sessions.
|
|
297
301
|
|
|
298
|
-
|
|
302
|
+
Explicit `thread-recover` with `recovery: { kind: 'resume' }` can rejoin a quarantined managed record's known Codex identity in the current runtime without restarting HQ, whether unloaded or still loaded idle or active. No action may remain in flight. The operator must inspect its ownership evidence and stop competing controllers that could submit work. HQ reads its current native turn, binds it before joining so reissued approvals find their turn, then verifies the same turn again before acknowledging recovery. It changes no settings, sends no input, leaves earlier queued entries paused and does not resolve uncertain input receipts. Unknown execution state, a mismatched workspace/identity or a changed turn refuses recovery. Healthy ownership and pending dispatches remain ineligible. Earlier queued receipts retain this recovery action as `relatedActionId`; completion and later automatic reconnects leave those entries paused until explicitly sent or cancelled. Recovery that attaches an identity after uncertain creation and ordinary adoption retain their existing unloaded-session checks.
|
|
299
303
|
|
|
300
304
|
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 managed and native identity, its nullable `provider`, digest, timestamps, safe failure classification and optional related action. Its `phase` is the native step the action takes now: `create`, `resume`, `name`, `turn`, `steer`, `interrupt`, `clean`, `close`, `delete` or `reply`. A create continues with `name` once its session exists, and with `turn` when it carries a first input; a close's `interrupt` continues with `clean` once the turn ends, and its `clean` with `close`; a deletion of a session the runtime runs takes `clean` and `close` before `delete`. An action that sends nothing native, such as queued input before it is sent, has none. Only selected receipts expose `nativeThreadId`, the native session of the action's thread once the runtime 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.
|
|
301
305
|
|
package/dist/actions/actions.js
CHANGED
|
@@ -63,7 +63,7 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
|
|
|
63
63
|
},
|
|
64
64
|
};
|
|
65
65
|
const { state, prompts, controlled, live, waits } = context;
|
|
66
|
-
const dispatcher = createDispatch(context);
|
|
66
|
+
const dispatcher = createDispatch(context, (actionId, owner) => events.finishControlAction(actionId, owner));
|
|
67
67
|
const events = createEvents(context, dispatcher, (threads) => reattachment.reconnect(threads));
|
|
68
68
|
const { admitAndDispatch } = createAdmission(context, dispatcher);
|
|
69
69
|
const reattachment = createReattach(context, dispatcher, events);
|
|
@@ -147,7 +147,10 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
|
|
|
147
147
|
await owned.close();
|
|
148
148
|
await state.lane.catch(() => undefined);
|
|
149
149
|
const providerStates = new Map(registry.statuses().map((status) => [status.provider, status.state]));
|
|
150
|
-
for (const
|
|
150
|
+
for (const entry of stopped) {
|
|
151
|
+
const { provider, nativeId } = entry;
|
|
152
|
+
if (controlled.get(key(provider, nativeId)) !== entry)
|
|
153
|
+
continue;
|
|
151
154
|
if (providerStates.get(provider) === 'unavailable')
|
|
152
155
|
continue;
|
|
153
156
|
const control = await registry.get(provider);
|
|
@@ -185,9 +185,9 @@ export const createAdmission = (context, dispatcher) => {
|
|
|
185
185
|
const isKnownCodexRecovery = command.kind === 'thread-recover' &&
|
|
186
186
|
command.recovery.kind === 'resume' &&
|
|
187
187
|
thread.provider === 'codex' &&
|
|
188
|
-
!target.canAdopt;
|
|
188
|
+
(!target.canAdopt || thread.runtimeEpoch === epoch);
|
|
189
189
|
if (isKnownCodexRecovery) {
|
|
190
|
-
if (thread.ownership !== 'uncertain'
|
|
190
|
+
if (thread.ownership !== 'uncertain')
|
|
191
191
|
conflict();
|
|
192
192
|
if (!control.readReattachment || !control.reattachThread)
|
|
193
193
|
capabilityUnavailable();
|
|
@@ -196,7 +196,7 @@ export const createAdmission = (context, dispatcher) => {
|
|
|
196
196
|
if (read.thread.nativeId !== nativeId ||
|
|
197
197
|
(await resolveWorkspaceTarget(read.thread.workspaceRoot, roots)) !==
|
|
198
198
|
thread.workspaceRoot ||
|
|
199
|
-
!['idle', 'active'].includes(read.thread.nativeState))
|
|
199
|
+
!['notLoaded', 'idle', 'active'].includes(read.thread.nativeState))
|
|
200
200
|
conflict();
|
|
201
201
|
prepared.recoveryTurn = read.latestTurn && {
|
|
202
202
|
nativeTurnId: read.latestTurn.nativeId,
|
|
@@ -224,6 +224,29 @@ export const createAdmission = (context, dispatcher) => {
|
|
|
224
224
|
conflict();
|
|
225
225
|
prompt.native.validate(command.response);
|
|
226
226
|
}
|
|
227
|
+
else if (command.kind === 'thread-close' && command.interrupt && provider === 'claude') {
|
|
228
|
+
const target = await store.call('reads', 'getThread', command.threadId);
|
|
229
|
+
const source = target?.nativeId
|
|
230
|
+
? registry.getControlSource(provider, target.nativeId)
|
|
231
|
+
: undefined;
|
|
232
|
+
if (source && registry.isControlQuarantined(provider, source)) {
|
|
233
|
+
await state.lane.catch(() => undefined);
|
|
234
|
+
const current = await store.call('reads', 'getThread', command.threadId);
|
|
235
|
+
if (state.isClosing ||
|
|
236
|
+
state.isUnavailable ||
|
|
237
|
+
!current ||
|
|
238
|
+
current.provider !== 'claude' ||
|
|
239
|
+
current.runtimeEpoch !== epoch ||
|
|
240
|
+
current.ownership !== 'uncertain' ||
|
|
241
|
+
current.nativeId !== source.nativeId ||
|
|
242
|
+
current.workspaceRoot !== source.workspaceRoot ||
|
|
243
|
+
claudeTerminalOf(source.nativeId) ||
|
|
244
|
+
!registry.isCurrentControl(provider, source) ||
|
|
245
|
+
!registry.isControlQuarantined(provider, source))
|
|
246
|
+
conflict();
|
|
247
|
+
prepared.quarantinedControl = source;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
227
250
|
if (command.kind === 'message' || command.kind === 'queue' || command.kind === 'steer') {
|
|
228
251
|
const thread = await store.call('reads', 'getThread', command.threadId);
|
|
229
252
|
if (!thread?.nativeId)
|
|
@@ -272,7 +295,7 @@ export const createAdmission = (context, dispatcher) => {
|
|
|
272
295
|
input = receipt.queuedInput;
|
|
273
296
|
}
|
|
274
297
|
context.runOwned(async () => {
|
|
275
|
-
await dispatch(receipt, thread, dispatchedCommand, input, prepared.recoveryTurn);
|
|
298
|
+
await dispatch(receipt, thread, dispatchedCommand, input, prepared.recoveryTurn, prepared.quarantinedControl);
|
|
276
299
|
});
|
|
277
300
|
}
|
|
278
301
|
return admitted.receipt;
|
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
import type { IActionEnvelope, IActionReceipt, IManagedThread, IPreparedInput } from '../../contracts/index.js';
|
|
2
|
-
import type { IProviderThread } from '../../providers/index.js';
|
|
2
|
+
import type { IControlSource, IProviderThread } from '../../providers/index.js';
|
|
3
3
|
import type { INativeOutcome } from '../../store/control/index.js';
|
|
4
|
-
import type { IActionsContext } from '../types.js';
|
|
4
|
+
import type { IActionsContext, IOwnedControl } from '../types.js';
|
|
5
5
|
/**
|
|
6
6
|
* Dispatches admitted actions to their native sessions, one phase at a time, and applies each
|
|
7
7
|
* phase's outcome to the action ledger.
|
|
8
8
|
* @returns The dispatch operations the runtime's events, admission and reattachment share.
|
|
9
9
|
*/
|
|
10
|
-
export declare const createDispatch: (context: IActionsContext) => {
|
|
10
|
+
export declare const createDispatch: (context: IActionsContext, finishControlAction: (actionId: string, owner: IOwnedControl | undefined) => Promise<void>) => {
|
|
11
11
|
validateRoot: (thread: IManagedThread) => Promise<void>;
|
|
12
12
|
verifyThread: (thread: IManagedThread, native: IProviderThread) => Promise<IProviderThread>;
|
|
13
13
|
advanceQueue: (threadId: string, provider: IManagedThread["provider"]) => void;
|
|
14
14
|
apply: (outcome: INativeOutcome) => Promise<IActionReceipt | null>;
|
|
15
15
|
dispatch: (initial: IActionReceipt, originalThread: IManagedThread | null, command?: IActionEnvelope["command"], input?: IPreparedInput, recoveryTurn?: Extract<INativeOutcome, {
|
|
16
16
|
kind: "resumed";
|
|
17
|
-
}>["latestTurn"]) => Promise<unknown>;
|
|
17
|
+
}>["latestTurn"], quarantinedControl?: IControlSource) => Promise<unknown>;
|
|
18
18
|
};
|
|
@@ -14,7 +14,7 @@ const NativeRejectionSchema = z.union([
|
|
|
14
14
|
* phase's outcome to the action ledger.
|
|
15
15
|
* @returns The dispatch operations the runtime's events, admission and reattachment share.
|
|
16
16
|
*/
|
|
17
|
-
export const createDispatch = (context) => {
|
|
17
|
+
export const createDispatch = (context, finishControlAction) => {
|
|
18
18
|
const { registry, store, roots, state, controlled, watched, waits } = context;
|
|
19
19
|
const validateRoot = async (thread) => {
|
|
20
20
|
if ((await resolveWorkspaceTarget(thread.workspaceRoot, roots)) !== thread.workspaceRoot)
|
|
@@ -95,16 +95,20 @@ export const createDispatch = (context) => {
|
|
|
95
95
|
* @param command The admitted command, when dispatch starts from admission.
|
|
96
96
|
* @param input The prepared input of a turn, unless the receipt holds it as queued input.
|
|
97
97
|
* @param recoveryTurn The verified current turn for explicit recovery of a loaded Codex session.
|
|
98
|
+
* @param quarantinedControl The exact owned Claude controller admitted for an explicit Stop.
|
|
98
99
|
* @returns A promise resolved after delivery evidence or uncertainty is persisted, to the
|
|
99
100
|
* failure it recorded, if any.
|
|
100
101
|
* @throws
|
|
101
102
|
* - JG_AGENT_HQ_ACTION_CONFLICT: The HQ action conflicts with its recorded state
|
|
102
103
|
* - JG_AGENT_HQ_STORE_FAILED: The HQ store failed
|
|
103
104
|
*/
|
|
104
|
-
const dispatch = async (initial, originalThread, command, input, recoveryTurn) => {
|
|
105
|
+
const dispatch = async (initial, originalThread, command, input, recoveryTurn, quarantinedControl) => {
|
|
105
106
|
let receipt = initial;
|
|
106
107
|
let thread = originalThread;
|
|
107
108
|
let hasDispatched = false;
|
|
109
|
+
let owner = thread?.nativeId
|
|
110
|
+
? controlled.get(context.key(thread.provider, thread.nativeId))
|
|
111
|
+
: undefined;
|
|
108
112
|
try {
|
|
109
113
|
const provider = thread?.provider ?? receipt.provider;
|
|
110
114
|
if (!provider)
|
|
@@ -138,6 +142,20 @@ export const createDispatch = (context) => {
|
|
|
138
142
|
const { phase } = receipt;
|
|
139
143
|
if (!phase)
|
|
140
144
|
conflict();
|
|
145
|
+
if (quarantinedControl) {
|
|
146
|
+
hasDispatched = false;
|
|
147
|
+
if (command?.kind !== 'thread-close' ||
|
|
148
|
+
command.interrupt !== true ||
|
|
149
|
+
thread?.provider !== 'claude' ||
|
|
150
|
+
thread.runtimeEpoch !== context.epoch ||
|
|
151
|
+
thread.nativeId !== quarantinedControl.nativeId ||
|
|
152
|
+
thread.workspaceRoot !== quarantinedControl.workspaceRoot ||
|
|
153
|
+
controlled.get(context.key(thread.provider, thread.nativeId)) !== owner ||
|
|
154
|
+
!registry.isCurrentControl('claude', quarantinedControl) ||
|
|
155
|
+
!registry.isControlQuarantined('claude', quarantinedControl) ||
|
|
156
|
+
(phase !== 'clean' && phase !== 'close'))
|
|
157
|
+
conflict();
|
|
158
|
+
}
|
|
141
159
|
const requestId = toActionRequestId(receipt.id, phase);
|
|
142
160
|
const nativeId = thread?.nativeId;
|
|
143
161
|
hasDispatched = true;
|
|
@@ -148,6 +166,7 @@ export const createDispatch = (context) => {
|
|
|
148
166
|
const created = await verifyThread(thread, await control.startThread(requestId, thread.workspaceRoot, command?.kind === 'thread-create' ? (command.settings ?? {}) : {}));
|
|
149
167
|
// bind the exact response before attempting the next, independently receipted phase
|
|
150
168
|
context.own(thread.provider, created.nativeId);
|
|
169
|
+
owner = controlled.get(context.key(thread.provider, created.nativeId));
|
|
151
170
|
next = await apply({
|
|
152
171
|
kind: 'created',
|
|
153
172
|
actionId: receipt.id,
|
|
@@ -160,6 +179,7 @@ export const createDispatch = (context) => {
|
|
|
160
179
|
if (!thread || !nativeId)
|
|
161
180
|
conflict();
|
|
162
181
|
context.own(thread.provider, nativeId);
|
|
182
|
+
owner = controlled.get(context.key(thread.provider, nativeId));
|
|
163
183
|
if (recoveryTurn !== undefined) {
|
|
164
184
|
if (!control.reattachThread)
|
|
165
185
|
conflict();
|
|
@@ -306,6 +326,9 @@ export const createDispatch = (context) => {
|
|
|
306
326
|
: { kind: 'uncertain', actionId: receipt.id, phase: receipt.phase });
|
|
307
327
|
return error;
|
|
308
328
|
}
|
|
329
|
+
finally {
|
|
330
|
+
await finishControlAction(initial.id, owner);
|
|
331
|
+
}
|
|
309
332
|
};
|
|
310
333
|
return {
|
|
311
334
|
validateRoot,
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { type IManagedThread } from '../../contracts/index.js';
|
|
2
|
+
import type { IControlSource } from '../../providers/index.js';
|
|
2
3
|
import type { INativeObservation } from '../../store/control/index.js';
|
|
3
4
|
import type { createDispatch } from '../dispatch/index.js';
|
|
4
|
-
import type { IActionsContext } from '../types.js';
|
|
5
|
+
import type { IActionsContext, IOwnedControl } from '../types.js';
|
|
5
6
|
/**
|
|
6
7
|
* Receives native evidence from the providers and persists it in order, one bounded lane per
|
|
7
8
|
* provider, re-checking sessions whose evidence was lost.
|
|
@@ -10,6 +11,7 @@ import type { IActionsContext } from '../types.js';
|
|
|
10
11
|
export declare const createEvents: (context: IActionsContext, dispatcher: ReturnType<typeof createDispatch>, reconnect: (threads: IManagedThread[]) => Promise<void>) => {
|
|
11
12
|
recordObservation: (observation: INativeObservation) => Promise<import("../../store/control/types.ts").IObservationResult>;
|
|
12
13
|
failEvents: (cause?: unknown) => void;
|
|
13
|
-
enqueue: (provider: IManagedThread["provider"], operation: () => Promise<void
|
|
14
|
+
enqueue: (provider: IManagedThread["provider"], operation: () => Promise<void>, source?: IControlSource) => void;
|
|
14
15
|
observe: (observation: INativeObservation) => Promise<void>;
|
|
16
|
+
finishControlAction: (actionId: string, owner: IOwnedControl | undefined) => Promise<void>;
|
|
15
17
|
};
|