jg-agent-hq 13.0.0 → 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,17 @@
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
+
8
+ ## 13.0.1
9
+
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.
11
+ - Stop and drain the old proxy before replacing it, and report its EOF and exit as one connection loss. Mark live output as incomplete and discard partial result capture across the gap.
12
+ - Scope native approval identities and reply callbacks to their connection. Reissued native request IDs open fresh approvals, while expired approvals cannot answer or decline a request on the replacement connection.
13
+ - Keep the existing storage schema, action key and public request contracts unchanged.
14
+
3
15
  ## 13.0.0
4
16
 
5
17
  - Accept managed-session names of 1 through 64 characters for create, adopt, rename and managed-thread responses. Export `MAX_THREAD_NAME_LENGTH` from `jg-agent-hq/contracts`; suggestions and atomic collision suffixes use the same limit. The lowercase ASCII alphabet, first-character rule, case-insensitive uniqueness and immutable identities are unchanged.
package/README.md CHANGED
@@ -110,7 +110,7 @@ The [qualification matrix](api/README.md#qualification) records native journeys,
110
110
  - `src/providers/configuration/` and `src/providers/lineage/`: bounded native choices and confirmed immutable session relationships.
111
111
  - `src/sessions/`: authorized discovery that merges folders' and providers' native pages with live session states, the active-session list, bounded evidence and provenance, cursor-bound history reads and short label suggestions.
112
112
  - `src/skills/`: bounded native catalogs and explicit input preparation.
113
- - `src/actions/`: durable action admission, phased native dispatch, ordered native events, rejoining kept sessions, bounded live presentation, and receipt waits and long-polls its own changes wake.
113
+ - `src/actions/`: durable action admission, phased native dispatch, ordered native events, rejoining kept sessions at startup and after a Codex connection loss, bounded live presentation, and receipt waits and long-polls its own changes wake.
114
114
  - `src/store/`: SQLite discovery metadata, observed sessions and state transitions, the action/control ledger and the snapshot's database copy in one worker, whose model methods the main thread calls with one typed `call`; `src/store/control/` splits the ledger into reads, rule-driven admission, native outcomes, native observations and runtime lifecycle.
115
115
  - `src/pending/`: the request bookkeeping, deadlines and late-response detection shared by the store worker and native connections.
116
116
  - `src/errors/`: the catalog of jg-agent-hq's coded errors and their safe boundary classifications.
package/api/README.md CHANGED
@@ -105,6 +105,10 @@ A session with an action in flight when a message is skipped, or when its turn s
105
105
 
106
106
  The socket accepts at most 32 simultaneous connections. Requests are bounded to 65,536 UTF-8 bytes; native and IPC response frames to 33,554,432 bytes. The runtime sends a Codex message over 1,048,576 bytes as fragments of at most that size. Structured transports reject malformed UTF-8/JSON, oversized frames and incomplete tails. Each native connection has at most 32 pending calls with a 30-second response deadline. IPC connections have a 35-second deadline. The SQLite worker bounds its queue to 128 commands, accommodating client reads, native lifecycle observations and action dispatch; collection operations remain limited to one page. Database work runs off the host event loop. The state directory is a same-user trust boundary, not a sandbox against other code running as that user.
107
107
 
108
+ After a live Codex connection loss, the runtime rechecks the bounded cohort it controlled with no action in flight before that loss. It stops the old proxy before replacing it, then reads and rejoins each eligible session once, without settings or input. The saved native turn must still match before and after joining. Matching running turns continue; confirmed completions settle their receipts without a result and release their ready queued input. Newer external turns, failed reads/joins and unacknowledged operations remain uncertain. Live output reports a gap, and partial result capture is discarded. This recovery does not claim that native commands or their process handles survived a daemon restart. It never resumes an external session or repeats an uncertain action. A second loss is a new bounded recovery attempt, not a retry of input.
109
+
110
+ 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.
111
+
108
112
  ## Providers and capabilities
109
113
 
110
114
  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.
@@ -267,7 +271,9 @@ Names use lowercase ASCII letters, digits and hyphens, start with a letter or di
267
271
 
268
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).
269
273
 
270
- 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.
271
277
 
272
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.
273
279
 
@@ -63,9 +63,10 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
63
63
  };
64
64
  const { state, prompts, controlled, live, waits } = context;
65
65
  const dispatcher = createDispatch(context);
66
- const events = createEvents(context, dispatcher);
66
+ const events = createEvents(context, dispatcher, (threads) => reattachment.reconnect(threads));
67
67
  const { admitAndDispatch } = createAdmission(context, dispatcher);
68
- context.runOwned(createReattach(context, dispatcher, events).reattach);
68
+ const reattachment = createReattach(context, dispatcher, events);
69
+ context.runOwned(reattachment.reattach);
69
70
  return {
70
71
  live,
71
72
  waits,
@@ -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 ||
@@ -7,7 +7,7 @@ import type { IActionsContext } from '../types.js';
7
7
  * provider, re-checking sessions whose evidence was lost.
8
8
  * @returns The event operations dispatch and reattachment share.
9
9
  */
10
- export declare const createEvents: (context: IActionsContext, dispatcher: ReturnType<typeof createDispatch>) => {
10
+ export declare const createEvents: (context: IActionsContext, dispatcher: ReturnType<typeof createDispatch>, reconnect: (threads: IManagedThread[]) => Promise<void>) => {
11
11
  recordObservation: (observation: INativeObservation) => Promise<import("../../store/control/types.ts").IObservationResult>;
12
12
  failEvents: (cause?: unknown) => void;
13
13
  enqueue: (provider: IManagedThread["provider"], operation: () => Promise<void>) => void;
@@ -13,7 +13,7 @@ import { TURN_FLUSH_PAGES } from './constants.js';
13
13
  * provider, re-checking sessions whose evidence was lost.
14
14
  * @returns The event operations dispatch and reattachment share.
15
15
  */
16
- export const createEvents = (context, dispatcher) => {
16
+ export const createEvents = (context, dispatcher, reconnect) => {
17
17
  const { registry, store, epoch, actionKey, runBackground, state, prompts, controlled, live } = context;
18
18
  const { watched, waits, resyncLifetime, key, own, runOwned } = context;
19
19
  const { verifyThread, advanceQueue, apply, dispatch } = dispatcher;
@@ -411,7 +411,11 @@ export const createEvents = (context, dispatcher) => {
411
411
  unavailable(provider, nativeId) {
412
412
  if (state.isClosing || context.blockedProviders.has(provider))
413
413
  return;
414
+ const canReconnect = provider === 'codex' && nativeId === undefined;
415
+ let reconnectable = [];
414
416
  enqueue(provider, async () => {
417
+ if (canReconnect)
418
+ reconnectable = await store.call('lifecycle', 'listReconnectable');
415
419
  await recordObservation({
416
420
  kind: 'native-unavailable',
417
421
  provider,
@@ -424,8 +428,20 @@ export const createEvents = (context, dispatcher) => {
424
428
  if (prompt.native.provider === provider &&
425
429
  (!nativeId || prompt.native.nativeThreadId === nativeId))
426
430
  prompts.delete(id);
431
+ for (const entry of controlled.values())
432
+ if (entry.provider === provider && (!nativeId || entry.nativeId === nativeId))
433
+ live.markGap(key(provider, entry.nativeId));
427
434
  });
428
- runNativeOwned(provider, nativeId, async () => registry.stopControl(provider, nativeId));
435
+ if (canReconnect) {
436
+ const persisted = state.lane;
437
+ runOwned(async () => {
438
+ await persisted;
439
+ if (!state.isClosing && !state.isUnavailable && !context.blockedProviders.has(provider))
440
+ await reconnect(reconnectable);
441
+ });
442
+ }
443
+ else
444
+ runNativeOwned(provider, nativeId, async () => registry.stopControl(provider, nativeId));
429
445
  },
430
446
  });
431
447
  return { recordObservation, failEvents, enqueue, observe };
@@ -1,3 +1,4 @@
1
+ import type { IManagedThread } from '../../contracts/index.js';
1
2
  import type { createDispatch } from '../dispatch/index.js';
2
3
  import type { createEvents } from '../events/index.js';
3
4
  import type { IActionsContext } from '../types.js';
@@ -7,4 +8,5 @@ import type { IActionsContext } from '../types.js';
7
8
  */
8
9
  export declare const createReattach: (context: IActionsContext, dispatcher: ReturnType<typeof createDispatch>, events: ReturnType<typeof createEvents>) => {
9
10
  reattach: () => Promise<void>;
11
+ reconnect: (threads: IManagedThread[]) => Promise<void>;
10
12
  };
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { capabilityUnavailable } from '../../providers/registry/index.js';
3
- import { agentUnavailable } from '../utilities.js';
3
+ import { agentUnavailable, assertKnownTurn } from '../utilities.js';
4
4
  /**
5
5
  * Rejoins the sessions the previous runtime left running in a native process that outlives it.
6
6
  * @returns The rejoining operation, which the runtime runs once it starts.
@@ -18,7 +18,7 @@ export const createReattach = (context, dispatcher, events) => {
18
18
  * @throws
19
19
  * - JG_AGENT_HQ_STORE_FAILED: The HQ store failed
20
20
  */
21
- const reattachThread = async (thread) => {
21
+ const reattachThread = async (thread, isReconnect = false) => {
22
22
  const nativeId = thread.nativeId;
23
23
  let isOwned = false;
24
24
  try {
@@ -27,10 +27,10 @@ export const createReattach = (context, dispatcher, events) => {
27
27
  capabilityUnavailable();
28
28
  await validateRoot(thread);
29
29
  const read = await control.readReattachment(nativeId, thread.workspaceRoot);
30
- if (read.thread.nativeState === 'systemError')
31
- agentUnavailable();
30
+ assertKnownTurn(read);
32
31
  const bound = await store.call('lifecycle', 'reattach', {
33
32
  threadId: thread.id,
33
+ isReconnect,
34
34
  latestTurn: read.latestTurn && {
35
35
  nativeTurnId: read.latestTurn.nativeId,
36
36
  state: read.latestTurn.state,
@@ -42,8 +42,11 @@ export const createReattach = (context, dispatcher, events) => {
42
42
  own(thread.provider, nativeId);
43
43
  isOwned = true;
44
44
  const joined = await control.reattachThread(`${randomUUID()}:reattach`, nativeId, thread.workspaceRoot);
45
+ assertKnownTurn(joined);
45
46
  const turnId = bound.thread.activeTurnId;
46
47
  const latest = joined.latestTurn;
48
+ if ((latest?.nativeId ?? null) !== (read.latestTurn?.nativeId ?? null))
49
+ agentUnavailable();
47
50
  if (turnId && latest?.nativeId === turnId && latest.state !== 'running') {
48
51
  const { state: turnState } = latest;
49
52
  live.completeTurn(key(thread.provider, nativeId), turnId);
@@ -80,5 +83,16 @@ export const createReattach = (context, dispatcher, events) => {
80
83
  batch = await store.call('lifecycle', 'listReattachable');
81
84
  }
82
85
  };
83
- return { reattach };
86
+ /**
87
+ * Rechecks only controls captured before this connection lost its native evidence.
88
+ * @returns A promise resolved after the bounded cohort has been checked in order.
89
+ */
90
+ const reconnect = async (threads) => {
91
+ for (const thread of threads) {
92
+ if (state.isClosing || state.isUnavailable || context.blockedProviders.has(thread.provider))
93
+ return;
94
+ await reattachThread(thread, true);
95
+ }
96
+ };
97
+ return { reattach, reconnect };
84
98
  };
@@ -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';
@@ -1,6 +1,8 @@
1
+ import { randomUUID } from 'node:crypto';
1
2
  import { isException } from 'jg-exception';
2
3
  import { z } from 'zod';
3
4
  import { MAX_RESULT_BYTES, } from '../../contracts/index.js';
5
+ import { HQ_ERRORS } from '../../errors/index.js';
4
6
  import { toTurnResult } from '../results/index.js';
5
7
  import { NativeIdSchema } from '../../contracts/identities/index.js';
6
8
  import { parseActionRequest } from '../utilities.js';
@@ -23,6 +25,9 @@ export const toProviderThread = (thread) => ({
23
25
  * @returns The callbacks installed on the native Codex connection.
24
26
  */
25
27
  export const createCodexEvents = (native, events, observeSession, observeLoaded) => {
28
+ // native request IDs may be reused by the replacement daemon
29
+ let connectionId = randomUUID();
30
+ const scopedRequestId = (id) => JSON.stringify([connectionId, id]);
26
31
  const turns = new Map();
27
32
  // each thread's running turn, which times its live items
28
33
  const runningTurns = new Map();
@@ -169,7 +174,7 @@ export const createCodexEvents = (native, events, observeSession, observeLoaded)
169
174
  kind: 'request-resolved',
170
175
  provider: 'codex',
171
176
  nativeThreadId: threadId,
172
- requestId: JSON.stringify(requestId),
177
+ requestId: scopedRequestId(requestId),
173
178
  });
174
179
  }
175
180
  };
@@ -208,26 +213,44 @@ export const createCodexEvents = (native, events, observeSession, observeLoaded)
208
213
  }
209
214
  },
210
215
  request(id, method, params) {
216
+ const requestConnection = connectionId;
217
+ /**
218
+ * Refuses a reply on a replacement connection that may reuse the native request ID.
219
+ * @throws
220
+ * - JG_AGENT_HQ_CODEX_FAILED: The Codex integration failed
221
+ */
222
+ const assertCurrentRequest = () => {
223
+ if (requestConnection !== connectionId)
224
+ throw HQ_ERRORS.create('codexFailed', { data: { kind: 'state-conflict' } });
225
+ };
226
+ // a stale refusal must not decline a different request on the replacement connection
227
+ const reject = () => requestConnection === connectionId ? native.reject(id) : Promise.resolve();
211
228
  const prompt = parseCodexPrompt(method, params);
212
229
  if (!prompt) {
213
230
  // a request on a session is refused only when HQ controls that session
214
231
  const thread = z.object({ threadId: NativeIdSchema }).safeParse(params);
215
232
  if (thread.success)
216
- events.unpresentable(thread.data.threadId, () => native.reject(id));
233
+ events.unpresentable(thread.data.threadId, reject);
217
234
  else
218
- void native.reject(id).catch(() => events.unavailable());
235
+ void reject().catch(() => events.unavailable());
219
236
  return;
220
237
  }
221
238
  events.prompt({
222
239
  provider: 'codex',
223
240
  nativeThreadId: prompt.params.threadId,
224
241
  nativeTurnId: prompt.params.turnId,
225
- requestId: JSON.stringify(id),
242
+ requestId: scopedRequestId(id),
226
243
  fingerprint: JSON.stringify([method, params]),
227
244
  presentation: toApprovalPresentation(prompt),
228
- validate: (response) => buildCodexReply(prompt, response),
229
- reply: (result) => native.reply(id, result),
230
- reject: () => native.reject(id),
245
+ validate: (response) => {
246
+ assertCurrentRequest();
247
+ return buildCodexReply(prompt, response);
248
+ },
249
+ reply: (result) => {
250
+ assertCurrentRequest();
251
+ return native.reply(id, result);
252
+ },
253
+ reject,
231
254
  });
232
255
  },
233
256
  lateResponse(requestId, result, error) {
@@ -280,7 +303,13 @@ export const createCodexEvents = (native, events, observeSession, observeLoaded)
280
303
  }
281
304
  events.outcome(outcome, thread);
282
305
  },
283
- unavailable: () => events.unavailable(),
306
+ unavailable: () => {
307
+ connectionId = randomUUID();
308
+ // a disconnected stream cannot supply a complete result from its partial capture
309
+ turns.clear();
310
+ runningTurns.clear();
311
+ events.unavailable();
312
+ },
284
313
  connected: () => observeLoaded(),
285
314
  // a discarded message's session can't be known, so every session HQ controls is read
286
315
  discarded: () => events.resync(undefined, 'unknown'),
@@ -123,7 +123,14 @@ export const createCodexRpc = async (daemonLauncher, handlers) => {
123
123
  cause,
124
124
  });
125
125
  }
126
- const transport = createProviderProcess('codex', ['app-server', 'proxy'], receive, stopped, undefined, createWebSocketFraming(), () => handlers.discarded());
126
+ // EOF and child exit describe one loss; an old exit must not invalidate a replacement.
127
+ let hasStopped = false;
128
+ const transport = createProviderProcess('codex', ['app-server', 'proxy'], receive, (cause) => {
129
+ if (hasStopped)
130
+ return;
131
+ hasStopped = true;
132
+ stopped(cause);
133
+ }, undefined, createWebSocketFraming(), () => handlers.discarded());
127
134
  try {
128
135
  const initialized = z
129
136
  .object({ userAgent: z.string().max(4096).nullable().optional().catch(null) })
@@ -171,6 +178,7 @@ export const createCodexRpc = async (daemonLauncher, handlers) => {
171
178
  });
172
179
  reopening ??= (async () => {
173
180
  try {
181
+ await connection.transport.close();
174
182
  connection = await open();
175
183
  handlers.opened();
176
184
  }
@@ -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;
@@ -28,7 +28,12 @@ export declare class ControlLifecycle extends ControlModel {
28
28
  /** Lists the sessions another runtime left running, which this runtime rejoins, oldest first. */
29
29
  listReattachable(): IManagedThread[];
30
30
  /**
31
- * Binds a session another runtime left running to this runtime, as its native process reports
31
+ * Lists the current controls that have no unacknowledged operation in flight.
32
+ * @returns The bounded cohort eligible for rechecking after a connection loss.
33
+ */
34
+ listReconnectable(): IManagedThread[];
35
+ /**
36
+ * Binds a kept or reconnecting session to this runtime, as its native process reports
32
37
  * it before the runtime rejoins it. A turn that finished meanwhile completes its action and lets
33
38
  * the session's queued input advance, which this runtime then delivers. A session whose latest
34
39
  * turn isn't the one HQ recorded, because another client started one, has its ownership marked
@@ -53,7 +53,16 @@ export class ControlLifecycle extends ControlModel {
53
53
  .map(toManagedThread);
54
54
  }
55
55
  /**
56
- * Binds a session another runtime left running to this runtime, as its native process reports
56
+ * Lists the current controls that have no unacknowledged operation in flight.
57
+ * @returns The bounded cohort eligible for rechecking after a connection loss.
58
+ */
59
+ listReconnectable() {
60
+ return this._statements
61
+ .all(`SELECT ${THREAD_COLUMNS} FROM agent_hq_thread WHERE runtime_epoch = ? AND ${KEPT_SESSION_CONDITION} ORDER BY created_at ASC, id ASC LIMIT ?`, this._epoch, CONTROLLED_THREAD_CAPACITY)
62
+ .map(toManagedThread);
63
+ }
64
+ /**
65
+ * Binds a kept or reconnecting session to this runtime, as its native process reports
57
66
  * it before the runtime rejoins it. A turn that finished meanwhile completes its action and lets
58
67
  * the session's queued input advance, which this runtime then delivers. A session whose latest
59
68
  * turn isn't the one HQ recorded, because another client started one, has its ownership marked
@@ -64,7 +73,9 @@ export class ControlLifecycle extends ControlModel {
64
73
  */
65
74
  reattach(input) {
66
75
  return this._transaction(() => {
67
- const thread = this._statements.get(`SELECT ${THREAD_COLUMNS} FROM agent_hq_thread WHERE id = ? AND runtime_epoch IS NOT NULL AND runtime_epoch != ? AND ${KEPT_SESSION_CONDITION}`, input.threadId, this._epoch);
76
+ const thread = this._statements.get(`SELECT ${THREAD_COLUMNS} FROM agent_hq_thread WHERE id = ? AND ${input.isReconnect
77
+ ? "runtime_epoch = ? AND ownership = 'uncertain' AND native_id IS NOT NULL AND pending_action_id IS NULL AND provider = 'codex'"
78
+ : `runtime_epoch IS NOT NULL AND runtime_epoch != ? AND ${KEPT_SESSION_CONDITION}`}`, input.threadId, this._epoch);
68
79
  if (!thread)
69
80
  return null;
70
81
  const now = Date.now();
@@ -72,7 +83,8 @@ export class ControlLifecycle extends ControlModel {
72
83
  const isRunning = latest?.state === 'running';
73
84
  if ((latest?.nativeTurnId ?? null) !== (thread.active_turn_id ?? thread.last_turn_id) ||
74
85
  (isRunning && thread.active_turn_id === null)) {
75
- this.__quarantine(thread.id, now);
86
+ if (!input.isReconnect)
87
+ this.__quarantine(thread.id, now);
76
88
  return { thread: this._managedThread(thread.id), canDispatchQueued: false };
77
89
  }
78
90
  this._availableSlot();
@@ -84,8 +96,9 @@ export class ControlLifecycle extends ControlModel {
84
96
  ? thread.state === 'stopping'
85
97
  ? 'stopping'
86
98
  : 'running'
87
- : (finished?.state ?? thread.state);
88
- this._statements.run('UPDATE agent_hq_thread SET runtime_epoch = ?, active_turn_id = ?, last_turn_id = ?, last_turn_state = ?, state = ?, updated_at = ? WHERE id = ?', this._epoch, isRunning ? latest.nativeTurnId : null, finished?.nativeTurnId ?? thread.last_turn_id, finished?.state ?? thread.last_turn_state, state, now, thread.id);
99
+ : (finished?.state ??
100
+ (input.isReconnect ? (thread.last_turn_state ?? 'idle') : thread.state));
101
+ this._statements.run("UPDATE agent_hq_thread SET ownership = 'managed', runtime_epoch = ?, active_turn_id = ?, last_turn_id = ?, last_turn_state = ?, state = ?, updated_at = ? WHERE id = ?", this._epoch, isRunning ? latest.nativeTurnId : null, finished?.nativeTurnId ?? thread.last_turn_id, finished?.state ?? thread.last_turn_state, state, now, thread.id);
89
102
  this._statements.run("UPDATE agent_hq_action SET runtime_epoch = ?, updated_at = ? WHERE thread_id = ? AND delivery = 'queued'", this._epoch, now, thread.id);
90
103
  const canDispatchQueued = finished?.state === 'completed' && thread.state !== 'stopping';
91
104
  if (finished) {
@@ -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 = {
@@ -129,6 +131,7 @@ export type IObservationResult = {
129
131
  };
130
132
  export type IReattachment = {
131
133
  threadId: string;
134
+ isReconnect?: boolean;
132
135
  latestTurn: {
133
136
  nativeTurnId: string;
134
137
  state: 'running' | 'completed' | 'failed' | 'interrupted';
package/docs/recovery.md CHANGED
@@ -30,6 +30,12 @@ Version 13.0.0 uses the same storage schema as 12.0.1, including the existing ac
30
30
 
31
31
  The expanded name contract is still a breaking change for older consumers: 12.x strict schemas reject managed names longer than 32 characters. Before installing 12.x, pause new session creation and naming actions, inventory every managed session using bounded `managed-threads` pages for each workspace, and use 13.x supported `thread-rename` actions to shorten each longer name. Resolve occupied or pending-name conflicts and verify the complete inventory contains no name longer than 32 before switching runtime and consumers together. Renaming retains the managed and native identities. Do not edit the database or stamp, reset storage, or replay session creation to make a downgrade work. Keep the existing database and `action.key` together.
32
32
 
33
+ ## Codex connection recovery
34
+
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
+
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
+
33
39
  ## Off-machine durability
34
40
 
35
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.0",
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",