jg-agent-hq 13.0.1 → 13.1.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
2
 
3
+ ## 13.1.0
4
+
5
+ - Let explicit `thread-recover` with `recovery: { kind: 'resume' }` rejoin a known Codex identity that remains loaded idle or active after its previous HQ runtime stopped. Read and bind its current turn before joining without settings or input, then verify the turn again before acknowledging recovery. A reissued approval belongs to that verified active turn.
6
+ - Keep earlier queued input paused and uncertain input receipts unresolved. Unknown native state, changed identity/workspace, and a turn that changes during the join refuse recovery. The previous-runtime ownership gate, automatic reconnect fences, storage schema and public request shapes are unchanged.
7
+
3
8
  ## 13.0.1
4
9
 
5
10
  - Rejoin eligible managed Codex sessions after the shared daemon connection stops, including a daemon update. Recheck the recorded native turn before and after joining, preserve session settings, and catch up confirmed completions and queued work without replaying input. A newer external turn, failed read, or unacknowledged operation remains uncertain.
package/api/README.md CHANGED
@@ -271,7 +271,9 @@ Names use lowercase ASCII letters, digits and hyphens, start with a letter or di
271
271
 
272
272
  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).
273
273
 
274
- 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. Active native threads, uncertain managed ownership and already controlled idle sessions remain blocked. Other adoption and recovery checks are unchanged.
274
+ 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.
275
+
276
+ After the producing HQ runtime stops, explicit `thread-recover` with `recovery: { kind: 'resume' }` may also rejoin that managed record's known Codex identity while it remains loaded idle or active. 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. Uncertain ownership from the current HQ runtime still requires that runtime to stop first. Recovery that attaches an identity after uncertain creation and ordinary adoption retain their existing unloaded-session checks.
275
277
 
276
278
  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.
277
279
 
@@ -3,7 +3,7 @@ import { HQ_ERRORS } from '../../errors/index.js';
3
3
  import { PROVIDER_OPERATIONS, readInputFiles } from '../../providers/index.js';
4
4
  import { capabilityUnavailable } from '../../providers/registry/index.js';
5
5
  import { resolveWorkspaceTarget } from '../../runtime/state/index.js';
6
- import { agentUnavailable, conflict } from '../utilities.js';
6
+ import { agentUnavailable, assertKnownTurn, conflict } from '../utilities.js';
7
7
  // the managed thread states a close accepts while no turn runs, which a deletion closes from
8
8
  const CLOSABLE_STATES = new Set([
9
9
  'idle',
@@ -182,7 +182,29 @@ export const createAdmission = (context, dispatcher) => {
182
182
  conflict();
183
183
  if (nativeId) {
184
184
  const target = await control.inspectThread(nativeId, thread.workspaceRoot);
185
- const canResume = target.canAdopt ||
185
+ const isKnownCodexRecovery = command.kind === 'thread-recover' &&
186
+ command.recovery.kind === 'resume' &&
187
+ thread.provider === 'codex' &&
188
+ !target.canAdopt;
189
+ if (isKnownCodexRecovery) {
190
+ if (thread.ownership !== 'uncertain' || thread.runtimeEpoch === epoch)
191
+ conflict();
192
+ if (!control.readReattachment || !control.reattachThread)
193
+ capabilityUnavailable();
194
+ const read = await control.readReattachment(nativeId, thread.workspaceRoot);
195
+ assertKnownTurn(read);
196
+ if (read.thread.nativeId !== nativeId ||
197
+ (await resolveWorkspaceTarget(read.thread.workspaceRoot, roots)) !==
198
+ thread.workspaceRoot ||
199
+ !['idle', 'active'].includes(read.thread.nativeState))
200
+ conflict();
201
+ prepared.recoveryTurn = read.latestTurn && {
202
+ nativeTurnId: read.latestTurn.nativeId,
203
+ state: read.latestTurn.state,
204
+ };
205
+ }
206
+ const canResume = isKnownCodexRecovery ||
207
+ target.canAdopt ||
186
208
  (command.kind === 'thread-resume' &&
187
209
  thread.state === 'inactive' &&
188
210
  thread.ownership === 'managed' &&
@@ -250,7 +272,7 @@ export const createAdmission = (context, dispatcher) => {
250
272
  input = receipt.queuedInput;
251
273
  }
252
274
  context.runOwned(async () => {
253
- await dispatch(receipt, thread, dispatchedCommand, input);
275
+ await dispatch(receipt, thread, dispatchedCommand, input, prepared.recoveryTurn);
254
276
  });
255
277
  }
256
278
  return admitted.receipt;
@@ -12,5 +12,7 @@ export declare const createDispatch: (context: IActionsContext) => {
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
- dispatch: (initial: IActionReceipt, originalThread: IManagedThread | null, command?: IActionEnvelope["command"], input?: IPreparedInput) => Promise<unknown>;
15
+ dispatch: (initial: IActionReceipt, originalThread: IManagedThread | null, command?: IActionEnvelope["command"], input?: IPreparedInput, recoveryTurn?: Extract<INativeOutcome, {
16
+ kind: "resumed";
17
+ }>["latestTurn"]) => Promise<unknown>;
16
18
  };
@@ -3,7 +3,7 @@ import { z } from 'zod';
3
3
  import { HQ_ERRORS, toActionFailure } from '../../errors/index.js';
4
4
  import { retainNativeLineage, readInputFiles, toActionRequestId } from '../../providers/index.js';
5
5
  import { resolveWorkspaceTarget } from '../../runtime/state/index.js';
6
- import { agentUnavailable, conflict } from '../utilities.js';
6
+ import { agentUnavailable, assertKnownTurn, conflict } from '../utilities.js';
7
7
  import { NEXT_PHASES } from './constants.js';
8
8
  const NativeRejectionSchema = z.union([
9
9
  z.object({ nativeCode: z.number() }),
@@ -92,13 +92,14 @@ export const createDispatch = (context) => {
92
92
  * @param originalThread The action's thread, or null for a deletion of a session HQ doesn't manage.
93
93
  * @param command The admitted command, when dispatch starts from admission.
94
94
  * @param input The prepared input of a turn, unless the receipt holds it as queued input.
95
+ * @param recoveryTurn The verified current turn for explicit recovery of a loaded Codex session.
95
96
  * @returns A promise resolved after delivery evidence or uncertainty is persisted, to the
96
97
  * failure it recorded, if any.
97
98
  * @throws
98
99
  * - JG_AGENT_HQ_ACTION_CONFLICT: The HQ action conflicts with its recorded state
99
100
  * - JG_AGENT_HQ_STORE_FAILED: The HQ store failed
100
101
  */
101
- const dispatch = async (initial, originalThread, command, input) => {
102
+ const dispatch = async (initial, originalThread, command, input, recoveryTurn) => {
102
103
  let receipt = initial;
103
104
  let thread = originalThread;
104
105
  let hasDispatched = false;
@@ -157,6 +158,30 @@ export const createDispatch = (context) => {
157
158
  if (!thread || !nativeId)
158
159
  conflict();
159
160
  context.own(thread.provider, nativeId);
161
+ if (recoveryTurn !== undefined) {
162
+ if (!control.reattachThread)
163
+ conflict();
164
+ // only the verified join may acknowledge this recovery, after its second turn read
165
+ const joined = await control.reattachThread(`${receipt.id}:recover`, nativeId, thread.workspaceRoot);
166
+ assertKnownTurn(joined);
167
+ if (joined.thread.nativeId !== nativeId ||
168
+ (joined.latestTurn?.nativeId ?? null) !== (recoveryTurn?.nativeTurnId ?? null) ||
169
+ (recoveryTurn?.state !== 'running' && joined.latestTurn?.state === 'running'))
170
+ agentUnavailable();
171
+ const verified = await verifyThread(thread, joined.thread);
172
+ await applyAfterEvents({
173
+ kind: 'resumed',
174
+ actionId: receipt.id,
175
+ phase,
176
+ nativeState: verified.nativeState,
177
+ nativeLineage: verified.nativeLineage,
178
+ latestTurn: joined.latestTurn && {
179
+ nativeTurnId: joined.latestTurn.nativeId,
180
+ state: joined.latestTurn.state,
181
+ },
182
+ });
183
+ return undefined;
184
+ }
160
185
  const resumed = await verifyThread(thread, await control.resumeThread(requestId, nativeId, thread.workspaceRoot, thread.name, command?.kind === 'thread-resume' || command?.kind === 'thread-adopt'
161
186
  ? (command.settings ?? {})
162
187
  : {}));
@@ -250,6 +275,17 @@ export const createDispatch = (context) => {
250
275
  }
251
276
  }
252
277
  catch (error) {
278
+ if (recoveryTurn !== undefined && thread?.nativeId) {
279
+ await store.call('observations', 'observe', {
280
+ kind: 'native-unavailable',
281
+ provider: thread.provider,
282
+ nativeThreadId: thread.nativeId,
283
+ });
284
+ for (const [id, pending] of context.prompts)
285
+ if (pending.threadId === thread.id)
286
+ context.prompts.delete(id);
287
+ waits.notifyThread(thread.id);
288
+ }
253
289
  // Only a matching native error response proves rejection. Transport loss and malformed results remain uncertain.
254
290
  const explicit = isException(error) &&
255
291
  (NativeRejectionSchema.safeParse(error.data).success ||
@@ -1,17 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { capabilityUnavailable } from '../../providers/registry/index.js';
3
- import { agentUnavailable } from '../utilities.js';
4
- /**
5
- * Refuses unknown execution state before restoring native control.
6
- * @throws
7
- * - JG_AGENT_HQ_PROVIDER_FAILED: The HQ provider integration failed
8
- */
9
- const assertKnownTurn = (read) => {
10
- if (read.thread.nativeState === 'systemError' ||
11
- read.thread.nativeState === 'unknown' ||
12
- (read.thread.nativeState === 'active' && read.latestTurn?.state !== 'running'))
13
- agentUnavailable();
14
- };
3
+ import { agentUnavailable, assertKnownTurn } from '../utilities.js';
15
4
  /**
16
5
  * Rejoins the sessions the previous runtime left running in a native process that outlives it.
17
6
  * @returns The rejoining operation, which the runtime runs once it starts.
@@ -1,4 +1,5 @@
1
1
  import type { IManagedThread } from '../contracts/index.js';
2
+ import type { IProviderReattachment } from '../providers/index.js';
2
3
  /**
3
4
  * Refuses an action whose recorded state doesn't allow it.
4
5
  * @throws
@@ -11,4 +12,10 @@ export declare const conflict: () => never;
11
12
  * - JG_AGENT_HQ_PROVIDER_FAILED: The HQ provider integration failed
12
13
  */
13
14
  export declare const agentUnavailable: () => never;
15
+ /**
16
+ * Refuses unknown execution state before restoring native control.
17
+ * @throws
18
+ * - JG_AGENT_HQ_PROVIDER_FAILED: The HQ provider integration failed
19
+ */
20
+ export declare const assertKnownTurn: (read: IProviderReattachment) => void;
14
21
  export declare const keepsSessions: (provider: IManagedThread["provider"]) => boolean;
@@ -17,5 +17,17 @@ export const conflict = () => {
17
17
  export const agentUnavailable = () => {
18
18
  throw HQ_ERRORS.create('providerFailed', { data: { kind: 'agent-unavailable' } });
19
19
  };
20
+ /**
21
+ * Refuses unknown execution state before restoring native control.
22
+ * @throws
23
+ * - JG_AGENT_HQ_PROVIDER_FAILED: The HQ provider integration failed
24
+ */
25
+ export const assertKnownTurn = (read) => {
26
+ if (read.thread.nativeState === 'systemError' ||
27
+ read.thread.nativeState === 'unknown' ||
28
+ (read.thread.nativeState === 'active' && read.latestTurn?.state !== 'running') ||
29
+ (read.thread.nativeState === 'idle' && read.latestTurn?.state === 'running'))
30
+ agentUnavailable();
31
+ };
20
32
  // Codex runs sessions in its shared daemon, which keeps them running when the runtime stops
21
33
  export const keepsSessions = (provider) => provider === 'codex';
@@ -217,6 +217,18 @@ export class ControlAdmission extends ControlModel {
217
217
  if (isCreating)
218
218
  phase = 'create';
219
219
  this._statements.run("UPDATE agent_hq_thread SET ownership = 'managed', runtime_epoch = ?, pending_action_id = ?, active_turn_id = NULL, state = ?, updated_at = ? WHERE id = ?", this._epoch, action.id, isCreating ? 'creating' : 'starting', now, threadId);
220
+ if (prepared.recoveryTurn !== undefined) {
221
+ if (command.kind !== 'thread-recover' ||
222
+ command.recovery.kind !== 'resume' ||
223
+ thread.provider !== 'codex' ||
224
+ thread.native_id !== prepared.nativeId)
225
+ this._conflict();
226
+ const latest = prepared.recoveryTurn;
227
+ const isRunning = latest?.state === 'running';
228
+ // bind before joining so a reissued native request finds the exact active turn
229
+ this._statements.run('UPDATE agent_hq_thread SET active_turn_id = ?, last_turn_id = ?, last_turn_state = ?, state = ? WHERE id = ?', isRunning ? latest.nativeTurnId : null, latest && !isRunning ? latest.nativeTurnId : thread.last_turn_id, latest && !isRunning ? latest.state : thread.last_turn_state, latest?.state ?? 'idle', threadId);
230
+ this._statements.run("UPDATE agent_hq_action SET queue_ready = 0 WHERE thread_id = ? AND delivery = 'queued'", threadId);
231
+ }
220
232
  if (isCreating)
221
233
  this._statements.run('UPDATE agent_hq_action SET requested_name = ? WHERE id = ?', thread.name, action.id);
222
234
  break;
@@ -94,6 +94,13 @@ export class ControlOutcomes extends ControlModel {
94
94
  this._statements.run("UPDATE agent_hq_action SET delivery = 'acknowledged', failure = NULL, thread_id = NULL, updated_at = ? WHERE id = ?", now, action.id);
95
95
  }
96
96
  else {
97
+ if (outcome.kind === 'resumed' &&
98
+ outcome.latestTurn !== undefined &&
99
+ (!ownsThread ||
100
+ thread.pending_action_id !== action.id ||
101
+ (thread.active_turn_id !== null &&
102
+ thread.active_turn_id !== outcome.latestTurn?.nativeTurnId)))
103
+ this._conflict();
97
104
  let nativeTurnId = action.native_turn_id;
98
105
  if (outcome.kind === 'turn-accepted' || outcome.kind === 'steer-accepted')
99
106
  nativeTurnId = outcome.nativeTurnId;
@@ -104,8 +111,30 @@ export class ControlOutcomes extends ControlModel {
104
111
  if (ownsThread) {
105
112
  if (outcome.kind === 'closed')
106
113
  this._statements.run("UPDATE agent_hq_thread SET runtime_epoch = NULL, pending_action_id = NULL, active_turn_id = NULL, state = 'inactive', updated_at = ? WHERE id = ? AND pending_action_id = ?", now, thread.id, action.id);
107
- else if (outcome.kind === 'resumed')
108
- this._statements.run('UPDATE agent_hq_thread SET pending_action_id = NULL, ownership = ?, state = ?, native_lineage = ?, updated_at = ? WHERE id = ? AND pending_action_id = ?', outcome.nativeState === 'idle' ? 'managed' : 'uncertain', outcome.nativeState === 'idle' ? 'idle' : 'unknown', outcome.nativeLineage === null ? null : JSON.stringify(outcome.nativeLineage), now, thread.id, action.id);
114
+ else if (outcome.kind === 'resumed') {
115
+ if (outcome.latestTurn !== undefined) {
116
+ const latest = outcome.latestTurn;
117
+ const hasFinished = latest &&
118
+ thread.last_turn_id === latest.nativeTurnId &&
119
+ thread.last_turn_state !== null &&
120
+ thread.active_turn_id === null;
121
+ const isRunning = latest?.state === 'running' && !hasFinished;
122
+ const state = isRunning
123
+ ? ['waiting-input', 'waiting-approval'].includes(thread.state)
124
+ ? thread.state
125
+ : 'running'
126
+ : hasFinished
127
+ ? thread.last_turn_state
128
+ : (latest?.state ?? 'idle');
129
+ this._statements.run('UPDATE agent_hq_thread SET pending_action_id = NULL, active_turn_id = ?, last_turn_id = ?, last_turn_state = ?, state = ?, native_lineage = ?, updated_at = ? WHERE id = ?', isRunning ? latest.nativeTurnId : null, latest && !isRunning ? latest.nativeTurnId : thread.last_turn_id, hasFinished
130
+ ? thread.last_turn_state
131
+ : latest && !isRunning
132
+ ? latest.state
133
+ : thread.last_turn_state, state, outcome.nativeLineage === null ? null : JSON.stringify(outcome.nativeLineage), now, thread.id);
134
+ }
135
+ else
136
+ this._statements.run('UPDATE agent_hq_thread SET pending_action_id = NULL, ownership = ?, state = ?, native_lineage = ?, updated_at = ? WHERE id = ? AND pending_action_id = ?', outcome.nativeState === 'idle' ? 'managed' : 'uncertain', outcome.nativeState === 'idle' ? 'idle' : 'unknown', outcome.nativeLineage === null ? null : JSON.stringify(outcome.nativeLineage), now, thread.id, action.id);
137
+ }
109
138
  else if (outcome.kind === 'renamed') {
110
139
  if (!action.requested_name)
111
140
  this._conflict();
@@ -57,6 +57,7 @@ export type INativeOutcome = IOutcomeFields & ({
57
57
  kind: 'resumed';
58
58
  nativeState: 'notLoaded' | 'idle' | 'systemError' | 'active' | 'unknown';
59
59
  nativeLineage: INativeLineage | null;
60
+ latestTurn?: IReattachment['latestTurn'];
60
61
  } | {
61
62
  kind: 'closed';
62
63
  } | {
@@ -109,6 +110,7 @@ export type IAdmission = {
109
110
  workspaceRoot?: string;
110
111
  nativeId?: string;
111
112
  input?: IPreparedInput;
113
+ recoveryTurn?: IReattachment['latestTurn'];
112
114
  };
113
115
  };
114
116
  export type IAdmissionResult = {
package/docs/recovery.md CHANGED
@@ -34,6 +34,8 @@ The expanded name contract is still a breaking change for older consumers: 12.x
34
34
 
35
35
  A shared Codex daemon restart can interrupt every managed Codex session's live connection while HQ stays running. The runtime rechecks only its previously controlled sessions with no action in flight and rejoins matching native turns without changing settings or repeating input. Confirmed completions advance their waiting queues; unacknowledged actions and changed turns remain uncertain. Native command handles may have been lost, so rejoining establishes session control rather than successful command execution. See [runtime lifecycle](../api/README.md#runtime-lifecycle).
36
36
 
37
+ For a session left uncertain, stop its producing HQ runtime and inspect the native identity and competing controllers before explicit recovery in the next runtime. `thread-recover` with `recovery: { kind: 'resume' }` can rejoin its already known Codex identity even when the daemon still holds it idle or active. The verified current turn is bound before joining and checked again afterward; no settings or input are sent. Reissued approvals can then be answered explicitly. Earlier queued entries stay paused, uncertain input receipts stay unresolved, and unknown state or a turn changing during the join leaves control uncertain. Never use attach/create to replace a known native identity or replay work to recover control.
38
+
37
39
  ## Off-machine durability
38
40
 
39
41
  The development helper examples/shared-storage.ts demonstrates a host-owned application table, maintenance, capture and offline restore using public exports. Capture already returns verified metadata, so the helper avoids an immediate extra full-database inspection. Its application transaction commits independently of capture. Inspect the restored values before starting a recovered runtime with explicitly chosen roots.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jg-agent-hq",
3
- "version": "13.0.1",
3
+ "version": "13.1.0",
4
4
  "description": "Native Claude Code and Codex session control, history, usage and recoverable local storage for Node.js apps.",
5
5
  "type": "module",
6
6
  "license": "MIT",