jg-agent-hq 10.2.0 → 10.3.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
+ ## 10.3.0
4
+
5
+ - Keep Codex sessions running when the runtime stops. Shutdown no longer interrupts their turns, cleans their background terminals or declines a request still waiting on an answer, and leaves their records bound to the stopped runtime. At startup, the next runtime rejoins each one that had no action in flight: it reads the session's state and latest turn from Codex's daemon, records the turn still running or completes the one that finished meanwhile, delivers the queued input waiting on it, and joins with `thread/resume` without settings, which makes the daemon send a still-waiting request again. A session another client moved past HQ's last turn, or one HQ can't read or join, is marked uncertain instead. Claude sessions still stop with the runtime.
6
+ - Add the optional `readReattachment` and `reattachThread` to `IAgentProvider`, and `IProviderReattachment`, which the built-in Codex adapter implements. Registered provider factories don't keep sessions across restarts, so the runtime never calls them on theirs.
7
+
3
8
  ## 10.2.0
4
9
 
5
10
  - `thread-adopt` accepts optional `settings`, as `thread-resume` does, and applies them to the resume it runs, so a host can adopt a session in a chosen permission mode. Codex refuses them for a thread another client still holds, as it does on resume.
package/api/README.md CHANGED
@@ -66,7 +66,9 @@ Native snapshot qualification on 2026-10-23 used Codex 0.164.0 (gpt-6.1-sol) and
66
66
 
67
67
  `createAgentHq({ stateRoot, allowedRoots })` starts one controller and returns `IAgentHq`: its canonical `stateRoot`, a `closed` lifetime promise, `request(command)`, idempotent `close()`, a trusted Node-only `storage` descriptor and `withStorageMaintenance(callback)`. Paths must be absolute. Allowed roots must exist and are canonicalized at startup. A client-selected workspace must resolve inside an allowed root. State is a real directory owned by the current OS user with no group/other access. The controller creates it privately when absent.
68
68
 
69
- The controller exclusively creates `hq-owner.json`. A live, inactive, incomplete or unverifiable existing owner prevents another controller from starting. There is no automatic takeover. Before deliberate recovery, establish that the inspected host, its worker and native process group have stopped. Runtime shutdown sends interruption requests across the bounded session cohort concurrently, then closes IPC connections, SQLite and owned native processes before removing the exact owner. Failed cleanup preserves ownership evidence. A new runtime receives a new epoch.
69
+ The controller exclusively creates `hq-owner.json`. A live, inactive, incomplete or unverifiable existing owner prevents another controller from starting. There is no automatic takeover. Before deliberate recovery, establish that the inspected host, its worker and native process group have stopped. Runtime shutdown sends interruption requests across the bounded Claude session cohort concurrently, then closes IPC connections, SQLite and owned native processes before removing the exact owner. Failed cleanup preserves ownership evidence. A new runtime receives a new epoch.
70
+
71
+ Codex sessions outlive the runtime, because they run in Codex's shared app-server daemon. Shutdown leaves them running: it doesn't interrupt their turns, clean their background terminals or answer a request still waiting on one, and their managed records stay bound to the stopped runtime. At startup, the next runtime rejoins each one that had no action in flight, one at a time in the background. It reads the session's state and latest turn from the daemon, binds the record to its own epoch, then joins with `thread/resume` without settings. A turn still running stays the session's active turn. A turn that finished meanwhile completes its action's receipt, without a `result`, and lets a queued entry waiting on it advance. The daemon sends a still-waiting request again on joining, and it opens as a new approval in the new epoch. A session whose latest turn isn't the one HQ recorded, because another client ran one, or that can't be read or joined, has its ownership marked uncertain for explicit recovery. A crash leaves the same bound records, so those sessions are rejoined too. A restored snapshot marks every session uncertain, so it never rejoins one. Claude sessions are processes the runtime owns: their turns stop with it, and they wait inactive for an explicit resume.
70
72
 
71
73
  `requestAgentHq(stateRoot, command, signal?)` is a one-command IPC client. It verifies the private owner and socket, binds the command to the runtime epoch and checks the matching response. Cancellation closes that client's socket and reports transport failure; it never undoes an admitted action. Closing a client does not close the host. `stop` accepts a shutdown request; the SDK caller must await `runtime.closed` when it owns the runtime. The CLI confirms owner removal before reporting `state: stopped`.
72
74
 
@@ -92,6 +94,7 @@ The current built-in surfaces map to these native entry points:
92
94
  | Steer | `turn/steer` for the exact active turn | Explicitly unsupported by the structured interface |
93
95
  | Interrupt | `turn/interrupt` | `interrupt` control request; completion remains separate |
94
96
  | Close/recover | Native background-terminal cleanup/verification and `thread/unsubscribe` | Confirmed process-group shutdown and explicit session release/resume |
97
+ | Runtime restart | Sessions keep running, and the next runtime rejoins them | Turns stop with the runtime; sessions wait inactive for an explicit resume |
95
98
  | History | `thread/list`, `thread/read`, `thread/turns/list`, `thread/items/list` | Bounded worker-owned indexing of native transcripts |
96
99
  | Skills | `skills/list` and native skill input | Initialization command metadata and native invocation text |
97
100
  | Fork | `thread/fork` with verified source lineage | Native `--resume`, `--fork-session` and distinct `--session-id` |
@@ -265,9 +268,9 @@ Codex may keep an idle native thread loaded after `thread/unsubscribe`, as when
265
268
 
266
269
  Receipts separate `delivery` (`queued`, `submitted`, `acknowledged`, `uncertain`, `failed`, `canceled`) from nullable native turn `completion` (`completed`, `failed`, `interrupted`). Acknowledgement means the exact native request was accepted, not that the turn or tool completed. Permission replies remain submitted after a pipe write and become acknowledged only when Codex resolves the exact native request or Claude returns a tool-result block for the exact tool-use identity. Claude cancellation expires the prompt and leaves an unacknowledged written reply uncertain. Resolution does not prove a tool ran. The receipt includes HQ/native identity, request phase, digest, timestamps, safe failure classification and optional related action. Only selected receipts expose `nativeThreadId`, the native session of the action's thread once HQ records it, undelivered `queuedInput` and the nullable complete native `result`; collection reads omit all three. Queued input retains prepared text, native skill identity, content-bound file references and explicit turn settings, never file bytes or skill content. It is cleared after delivery acknowledgement or cancellation.
267
270
 
268
- A missing acknowledgement never triggers an automatic resend. Exact late responses reconcile delivery, including completion that arrived first. Native output loss marks the affected provider controls and submitted work uncertain. A Claude process failure affects its own session; a Codex transport failure affects its Codex cohort. Restart quarantines controls from an interrupted runtime; explicit recovery preserves the HQ identity and name. Successful shutdown proves native process-group exit before marking controls inactive. Unknown creation without a native identity remains uncertain.
271
+ A missing acknowledgement never triggers an automatic resend. Exact late responses reconcile delivery, including completion that arrived first. Native output loss marks the affected provider controls and submitted work uncertain. A Claude process failure affects its own session; a Codex transport failure affects its Codex cohort. Restart quarantines controls from an interrupted runtime, except the Codex sessions the next runtime rejoins; explicit recovery preserves the HQ identity and name. Successful shutdown proves native process-group exit before marking Claude controls inactive. Unknown creation without a native identity remains uncertain.
269
272
 
270
- Normal native turn completion may advance ready queued entries once, in creation/UUID order. Failure, interruption, explicit interrupt admission or restart pauses the queue. Permission prompts do not advance it. An unacknowledged start or metadata change blocks dependent starts until its outcome is reconciled or the stopped runtime is recovered explicitly. A turn's completion does not settle an unresolved steering receipt.
273
+ Normal native turn completion may advance ready queued entries once, in creation/UUID order. Failure, interruption, explicit interrupt admission or restart pauses the queue. A rejoined Codex session's queue advances again once the turn it waits on completes. Permission prompts do not advance it. An unacknowledged start or metadata change blocks dependent starts until its outcome is reconciled or the stopped runtime is recovered explicitly. A turn's completion does not settle an unresolved steering receipt.
271
274
 
272
275
  Native replies use one of these closed response forms:
273
276
 
@@ -421,6 +424,7 @@ The operation matrix describes the implemented native interfaces and their expli
421
424
  | Identity and native interaction | Both providers retained managed/native identities after compaction and reconnect with a fresh runtime epoch. Codex interruption and continuation passed. Claude AskUserQuestion and scoped MCP permission replies used exact native identities. | A timed-out compaction retained uncertain delivery even when completion later arrived; it was not resent. Explicit resume followed confirmed controller shutdown. |
422
425
  | Recovery | After removing all eight qualification transcripts, offline recovery retained the host preference and providers stayed idle. | Native transcripts, repository files and authentication remain separate recovery responsibilities. |
423
426
  | Shared Codex daemon | Codex 0.164.0: a terminal `codex` session ran on the shared daemon and appeared in `thread/list`. Without subscribing, HQ saw its `thread/status/changed`; after rejoining with `thread/resume`, HQ received the terminal's live turn and item notifications. A thread HQ created appeared in the terminal's `codex resume` picker, and closing HQ's connection left the daemon and the terminal session running. The daemon confirmed HQ's interrupt and close. Per-thread skill roots and output schemas worked on HQ threads, while another client's catalog and thread never saw the roots. Sessions read their own thread ID from `CODEX_THREAD_ID`. | A terminal started with `-c` overrides runs its thread in its own process (`source: cli`): it is listed, but a second writer is refused, so it cannot be followed live. The restart check ran against a separate app-server on its own socket rather than the shared daemon, which was serving other work: within one keepalive interval the session became uncertain and nothing was resent. A session Codex reloads from disk loses its capability roots. |
427
+ | Codex across restarts | Codex 0.166.0 on 2026-11-01: a turn whose client closed its connection mid-turn ran to completion in the daemon, which kept the session loaded and idle. A command approval that arrived before the connection closed stayed pending, with the session `waitingOnApproval`; after a new connection joined with `thread/resume`, the daemon sent it again under the same request ID, and answering it completed the turn. |
424
428
  | Claude active sessions | Claude Code 2.1.310 answered `claude agents --json` in 0.16 s. Interactive entries carry `status` (`busy`, `waiting`, `idle`) and `pid`; background entries carry `id` and `state` (`blocked`). Sessions HQ starts in structured mode are listed as interactive under their HQ name and disappear after close. | The list describes running processes only; history still comes from transcripts. |
425
429
  | Host coverage | Linux x86_64 package checks passed on Node 24.15.0 and 24.22.1. Identity, native interaction and recovery ran on the floor and on 24.22.1. | No macOS host was available for this run. Windows is outside the declared host contract. |
426
430
 
@@ -44,7 +44,8 @@ export declare const createActions: (registry: ReturnType<typeof createProviderR
44
44
  /** Attaches sensitive presentation only to the exact current native request. */
45
45
  approvalPresentation(approval: INativeApprovalSummary): INativeApproval;
46
46
  /**
47
- * Stops admission, interrupts active work, cleans native terminals and confirms shutdown.
47
+ * Stops admission, interrupts active work, cleans native terminals and confirms shutdown. A
48
+ * session that outlives the runtime keeps running, with its terminals, for the next runtime.
48
49
  * @returns A promise resolved after native exit and release of durable control ownership.
49
50
  * @throws
50
51
  * - JG_AGENT_HQ_PROVIDER_FAILED: The HQ provider integration failed
@@ -504,6 +504,9 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
504
504
  live.append(key(provider, nativeId), turnId, itemId, text);
505
505
  },
506
506
  prompt(provider, prompt) {
507
+ // a session that outlives the runtime keeps its request for the next runtime to answer
508
+ if (closing && registry.keepsSessions(provider))
509
+ return;
507
510
  if (!controlled.has(key(provider, prompt.nativeThreadId)) || prompts.size >= 32 || closing) {
508
511
  runNativeOwned(provider, prompt.nativeThreadId, prompt.reject);
509
512
  return;
@@ -849,6 +852,78 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
849
852
  }
850
853
  return admitted.receipt;
851
854
  };
855
+ /**
856
+ * Rejoins one session the previous runtime left running in a native process that outlives it.
857
+ * The session is bound to this runtime as that process reports it before joining, so a request
858
+ * the process sends again on joining finds its turn, and a turn that finished between the two
859
+ * reads then completes. A session that can't be rejoined has its ownership marked uncertain.
860
+ * @returns A promise resolved once the session is rejoined or marked uncertain.
861
+ * @throws
862
+ * - JG_AGENT_HQ_STORE_FAILED: The HQ store failed
863
+ */
864
+ const reattachThread = async (thread) => {
865
+ const nativeId = thread.nativeId;
866
+ let isOwned = false;
867
+ try {
868
+ const control = await registry.get(thread.provider);
869
+ if (!control.readReattachment || !control.reattachThread)
870
+ capabilityUnavailable();
871
+ await validateRoot(thread);
872
+ const read = await control.readReattachment(nativeId, thread.workspaceRoot);
873
+ if (read.thread.nativeState === 'systemError')
874
+ agentUnavailable();
875
+ const bound = await store.reattach({
876
+ threadId: thread.id,
877
+ latestTurn: read.latestTurn && {
878
+ nativeTurnId: read.latestTurn.nativeId,
879
+ state: read.latestTurn.state,
880
+ },
881
+ });
882
+ waits.notifyThread(thread.id);
883
+ if (bound?.thread?.ownership !== 'managed' || bound.thread.runtimeEpoch !== epoch)
884
+ return;
885
+ own(thread.provider, nativeId);
886
+ isOwned = true;
887
+ const joined = await control.reattachThread(`${randomUUID()}:reattach`, nativeId, thread.workspaceRoot);
888
+ const turnId = bound.thread.activeTurnId;
889
+ const latest = joined.latestTurn;
890
+ if (turnId && latest?.nativeId === turnId && latest.state !== 'running') {
891
+ const { state } = latest;
892
+ live.completeTurn(key(thread.provider, nativeId), turnId);
893
+ enqueue(thread.provider, () => observe({
894
+ kind: 'turn-completed',
895
+ provider: thread.provider,
896
+ nativeThreadId: nativeId,
897
+ nativeTurnId: turnId,
898
+ state,
899
+ }));
900
+ }
901
+ if (bound.canDispatchQueued)
902
+ advanceQueue(thread.id, thread.provider);
903
+ }
904
+ catch {
905
+ if (isOwned)
906
+ await recordObservation({
907
+ kind: 'native-unavailable',
908
+ provider: thread.provider,
909
+ nativeThreadId: nativeId,
910
+ });
911
+ else
912
+ await store.quarantineThread(thread.id);
913
+ waits.notifyThread(thread.id);
914
+ }
915
+ };
916
+ /** Rejoins, one at a time, every session the previous runtime left running. */
917
+ const reattach = async () => {
918
+ let batch = await store.listReattachable();
919
+ while (batch.length > 0 && !closing) {
920
+ for (const thread of batch)
921
+ if (!closing)
922
+ await reattachThread(thread);
923
+ batch = await store.listReattachable();
924
+ }
925
+ };
926
+ runOwned(reattach);
852
927
  return {
853
928
  /**
854
929
  * Reads live native authentication presentation without replaying an interrupted action.
@@ -936,7 +1011,8 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
936
1011
  };
937
1012
  },
938
1013
  /**
939
- * Stops admission, interrupts active work, cleans native terminals and confirms shutdown.
1014
+ * Stops admission, interrupts active work, cleans native terminals and confirms shutdown. A
1015
+ * session that outlives the runtime keeps running, with its terminals, for the next runtime.
940
1016
  * @returns A promise resolved after native exit and release of durable control ownership.
941
1017
  * @throws
942
1018
  * - JG_AGENT_HQ_PROVIDER_FAILED: The HQ provider integration failed
@@ -951,8 +1027,9 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
951
1027
  let cleanupFailure;
952
1028
  try {
953
1029
  await Promise.allSettled([...admissions]);
1030
+ const stopped = [...controlled.values()].filter(({ provider }) => !registry.keepsSessions(provider));
954
1031
  // Active turn IDs come from ordered native evidence, never from an interrupt acknowledgement.
955
- await Promise.all([...controlled.values()].map(async ({ provider, nativeId }) => {
1032
+ await Promise.all(stopped.map(async ({ provider, nativeId }) => {
956
1033
  const thread = await store.getThreadByNativeId(provider, nativeId);
957
1034
  if (thread?.activeTurnId) {
958
1035
  try {
@@ -968,7 +1045,7 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
968
1045
  await Promise.allSettled([...tasks]);
969
1046
  await lane.catch(() => undefined);
970
1047
  const providerStates = new Map(registry.statuses().map((status) => [status.provider, status.state]));
971
- for (const { provider, nativeId } of controlled.values()) {
1048
+ for (const { provider, nativeId } of stopped) {
972
1049
  if (providerStates.get(provider) === 'unavailable')
973
1050
  continue;
974
1051
  const control = await registry.get(provider);
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ export { type IHqLockOwner, type IOwnerLiveness, type IHqLockOptions, type IHqLo
2
2
  export { createAgentHq } from './runtime/index.js';
3
3
  export type { IAgentHq, IAgentHqOptions } from './runtime/index.js';
4
4
  export { requestAgentHq } from './ipc/index.js';
5
- export type { IAgentProvider, IAgentProviderFactory, IAgentProviderContext, IAgentProviderEvents, IAgentProviderOutcome, INativePrompt, IProviderCall, IProviderThread, IProviderInspection, IProviderSkills, IProviderMcpServerPage, IProviderMcpTools, IProviderMcpResources, } from './providers/index.js';
5
+ export type { IAgentProvider, IAgentProviderFactory, IAgentProviderContext, IAgentProviderEvents, IAgentProviderOutcome, INativePrompt, IProviderCall, IProviderThread, IProviderInspection, IProviderReattachment, IProviderSkills, IProviderMcpServerPage, IProviderMcpTools, IProviderMcpResources, } from './providers/index.js';
6
6
  export type { IProviderId, IProviderCapability, IProviderCapabilitySet, IProviderCapabilities, IProviderStatus, } from './contracts/providers/index.js';
7
7
  export type { IProviderModel, IProviderModelPage, IProviderModelsRequest, } from './contracts/models/index.js';
8
8
  export type { ITurnSettings, ISessionSettings, IConfigurationRequest, IConfigurationChoice, ISessionConfiguration, } from './contracts/configuration/index.js';
@@ -76,6 +76,19 @@ export const createCodexProviderFactory = (extraSkillRoots, daemonLauncher) => (
76
76
  data: { kind: 'access-denied' },
77
77
  });
78
78
  };
79
+ // a session's latest turn, which runs only while the daemon reports the session active
80
+ const readLatestTurn = async (thread) => {
81
+ const [turn] = (await native.listTurns(thread.nativeId, 1)).data;
82
+ if (!turn)
83
+ return null;
84
+ if (turn.state !== 'inProgress' && turn.state !== 'unknown')
85
+ return { nativeId: turn.nativeId, state: turn.state };
86
+ // a turn cut short when the daemon stopped stays in progress in its saved history
87
+ return {
88
+ nativeId: turn.nativeId,
89
+ state: thread.nativeState === 'active' ? 'running' : 'interrupted',
90
+ };
91
+ };
79
92
  const readHistory = async (command) => {
80
93
  const position = command.kind === 'session-evidence' ? evidencePosition(command) : undefined;
81
94
  const { cursor, ...filters } = {
@@ -318,6 +331,17 @@ export const createCodexProviderFactory = (extraSkillRoots, daemonLauncher) => (
318
331
  canResume: thread.nativeState === 'idle',
319
332
  };
320
333
  },
334
+ async readReattachment(nativeId, workspaceRoot) {
335
+ const thread = toProviderThread(await native.readNativeThread(nativeId));
336
+ await verifyRoot(thread.workspaceRoot, workspaceRoot);
337
+ return { thread, latestTurn: await readLatestTurn(thread) };
338
+ },
339
+ async reattachThread(requestId, nativeId, workspaceRoot, call) {
340
+ // without settings, Codex joins a session it has loaded rather than refusing it
341
+ const thread = toProviderThread(await native.resumeThread(requestId, nativeId, {}, call.signal));
342
+ await verifyRoot(thread.workspaceRoot, workspaceRoot);
343
+ return { thread, latestTurn: await readLatestTurn(thread) };
344
+ },
321
345
  readUsage: () => native.readUsage(),
322
346
  readAccount: () => native.readAccount(),
323
347
  readLogin: (requestId) => native.readLogin(requestId),
@@ -325,6 +325,9 @@ export const createCodexProvider = async (extraSkillRoots = [], daemonLauncher =
325
325
  thread: NativeThreadSchema.refine((thread) => thread.id === nativeId && thread.status.type === 'idle'),
326
326
  }), await connection.request('thread/revert', { threadId: nativeId, beforeTurnId }, requestId)).thread;
327
327
  },
328
+ async readNativeThread(nativeId) {
329
+ return parseNative(z.object({ thread: NativeThreadSchema.refine((thread) => thread.id === nativeId) }), await connection.request('thread/read', { threadId: nativeId, includeTurns: false })).thread;
330
+ },
328
331
  async readThread(nativeId) {
329
332
  const result = parseNative(z.object({ thread: NativeThreadSchema.refine((thread) => thread.id === nativeId) }), await connection.request('thread/read', { threadId: nativeId, includeTurns: false }));
330
333
  return toThreadSummary(result.thread);
@@ -192,6 +192,8 @@ export type ICodexProvider = {
192
192
  readonly isAvailable: boolean;
193
193
  listThreads(workspaceRoot: string, limit: number, cursor?: string, search?: string): Promise<INativePage<IThreadSummary>>;
194
194
  readThread(nativeId: string): Promise<IThreadSummary>;
195
+ /** @returns A session's native metadata and status, without joining it. */
196
+ readNativeThread(nativeId: string): Promise<INativeThread>;
195
197
  /** @returns A session's summary, with its workspace, and whether Codex doesn't save it. */
196
198
  readObservedThread(nativeId: string): Promise<{
197
199
  thread: IThreadSummary;
@@ -1,6 +1,6 @@
1
1
  export { retainNativeLineage } from './lineage/index.js';
2
- export type { IProviderProcess, IProviderFraming, INativePrompt, IProviderSkills, IProviderCall, IProviderThread, IProviderInspection, IAgentProvider, IAgentProviderFactory, IAgentProviderContext, IAgentProviderEvents, IAgentProviderOutcome, } from './types.js';
3
- export { ProviderThreadSchema, ProviderInspectionSchema, ProviderSkillsSchema } from './types.js';
2
+ export type { IProviderProcess, IProviderFraming, INativePrompt, IProviderSkills, IProviderCall, IProviderThread, IProviderInspection, IProviderReattachment, IAgentProvider, IAgentProviderFactory, IAgentProviderContext, IAgentProviderEvents, IAgentProviderOutcome, } from './types.js';
3
+ export { ProviderThreadSchema, ProviderInspectionSchema, ProviderReattachmentSchema, ProviderSkillsSchema, } from './types.js';
4
4
  export { PROVIDER_INPUT_SCHEMA, SUPPORTED_PROVIDER_OPERATION } from './constants.js';
5
5
  export { createProviderProcess, isOwnedProcess } from './process.js';
6
6
  export { createCodexProvider, createCodexProviderFactory, NativeThreadSchema, NativeTurnSchema, NativeItemSchema, toHistoryItem, parseNative, parseCodexPrompt, buildCodexReply, toApprovalPresentation, } from './codex/index.js';
@@ -1,6 +1,6 @@
1
1
  // transport
2
2
  export { retainNativeLineage } from './lineage/index.js';
3
- export { ProviderThreadSchema, ProviderInspectionSchema, ProviderSkillsSchema } from './types.js';
3
+ export { ProviderThreadSchema, ProviderInspectionSchema, ProviderReattachmentSchema, ProviderSkillsSchema, } from './types.js';
4
4
  export { PROVIDER_INPUT_SCHEMA, SUPPORTED_PROVIDER_OPERATION } from './constants.js';
5
5
  export { createProviderProcess, isOwnedProcess } from './process.js';
6
6
  // Codex
@@ -8,6 +8,8 @@ import type { IBoundAgentProvider, IProviderRegistration, IProviderRegistryEvent
8
8
  */
9
9
  export declare const createProviderRegistry: (registrations: IProviderRegistration[], allowedRoots: string[], runtimeEpoch: string) => {
10
10
  get: (provider: IProviderId) => Promise<IBoundAgentProvider>;
11
+ /** @returns Whether the provider's sessions outlive the runtime, which rejoins them. */
12
+ keepsSessions: (provider: IProviderId) => boolean;
11
13
  /** Quarantines one provider after a source-specific lifecycle gap or invalid control response. */
12
14
  quarantine(provider: IProviderId, cause: unknown): void;
13
15
  /** Installs runtime-owned callbacks without constructing any adapter. */
@@ -7,7 +7,7 @@ import { MAX_FRAME_BYTES } from '../../ipc/index.js';
7
7
  import { resetProvenance } from '../../sessions/evidence/index.js';
8
8
  import { ApprovalRecordSchema } from '../../store/control/index.js';
9
9
  import { ProviderMcpServerPageSchema, ProviderMcpToolsSchema, ProviderMcpResourcesSchema, } from '../extensions/index.js';
10
- import { ProviderInspectionSchema, ProviderThreadSchema, ProviderSkillsSchema, } from '../index.js';
10
+ import { ProviderInspectionSchema, ProviderReattachmentSchema, ProviderThreadSchema, ProviderSkillsSchema, } from '../index.js';
11
11
  import { capabilityUnavailable, normalizeProviderError } from './utilities.js';
12
12
  import { parseProviderObservation, parseProviderOutcome, rejectProviderResponse, validateProviderHistory, } from './validations.js';
13
13
  const CleanupSchema = z.object({ cleanupUnconfirmed: z.literal(true) });
@@ -438,6 +438,22 @@ export const createProviderRegistry = (registrations, allowedRoots, runtimeEpoch
438
438
  }
439
439
  return parsed.data;
440
440
  }),
441
+ ...(adapter.readReattachment && adapter.reattachThread
442
+ ? {
443
+ readReattachment: (nativeId, workspaceRoot) => invokeControl(async (call) => {
444
+ const result = ProviderReattachmentSchema.parse(await adapter.readReattachment(nativeId, workspaceRoot, call));
445
+ if (result.thread.nativeId !== nativeId)
446
+ rejectProviderResponse();
447
+ return result;
448
+ }),
449
+ reattachThread: (requestId, nativeId, workspaceRoot) => invokeControl(async (call) => {
450
+ const result = ProviderReattachmentSchema.parse(await adapter.reattachThread(requestId, nativeId, workspaceRoot, call));
451
+ if (result.thread.nativeId !== nativeId)
452
+ rejectProviderResponse();
453
+ return result;
454
+ }),
455
+ }
456
+ : {}),
441
457
  nameThread: (requestId, nativeId, name) => invokeControl((call) => adapter.nameThread(requestId, nativeId, name, call)),
442
458
  validateInput: (nativeId, input) => invoke((call) => adapter.validateInput(nativeId, input, call)),
443
459
  startTurn: (requestId, nativeId, text, skill, settings, files) => invokeControl(async (call) => z
@@ -460,6 +476,8 @@ export const createProviderRegistry = (registrations, allowedRoots, runtimeEpoch
460
476
  };
461
477
  return {
462
478
  get,
479
+ /** @returns Whether the provider's sessions outlive the runtime, which rejoins them. */
480
+ keepsSessions: (provider) => entries.get(provider)?.registration.keepsSessions === true,
463
481
  /** Quarantines one provider after a source-specific lifecycle gap or invalid control response. */
464
482
  quarantine(provider, cause) {
465
483
  const entry = entries.get(provider);
@@ -4,6 +4,7 @@ import type { IAgentProvider, IAgentProviderEvents, IProviderCall, IAgentProvide
4
4
  export type IProviderRegistration = {
5
5
  factory: IAgentProviderFactory;
6
6
  isBuiltIn: boolean;
7
+ keepsSessions?: boolean;
7
8
  };
8
9
  export type IBoundAgentProvider = {
9
10
  [K in keyof IAgentProvider]: NonNullable<IAgentProvider[K]> extends (...inputs: infer TInputs) => infer TResult ? TInputs extends [...infer TOperationInputs, IProviderCall] ? (...inputs: TOperationInputs) => TResult : IAgentProvider[K] : IAgentProvider[K];
@@ -69,6 +69,33 @@ export declare const ProviderInspectionSchema: z.ZodObject<{
69
69
  canResume: z.ZodBoolean;
70
70
  }, z.core.$strip>;
71
71
  export type IProviderInspection = z.infer<typeof ProviderInspectionSchema>;
72
+ export declare const ProviderReattachmentSchema: z.ZodObject<{
73
+ thread: z.ZodObject<{
74
+ workspaceRoot: z.ZodString;
75
+ nativeId: z.ZodString;
76
+ nativeLineage: z.ZodNullable<z.ZodObject<{
77
+ sessionId: z.ZodNullable<z.ZodString>;
78
+ parentThreadId: z.ZodNullable<z.ZodString>;
79
+ forkedFromId: z.ZodNullable<z.ZodString>;
80
+ }, z.core.$strip>>;
81
+ nativeState: z.ZodEnum<{
82
+ idle: "idle";
83
+ notLoaded: "notLoaded";
84
+ systemError: "systemError";
85
+ active: "active";
86
+ }>;
87
+ }, z.core.$strip>;
88
+ latestTurn: z.ZodNullable<z.ZodObject<{
89
+ nativeId: z.ZodString;
90
+ state: z.ZodEnum<{
91
+ completed: "completed";
92
+ failed: "failed";
93
+ interrupted: "interrupted";
94
+ running: "running";
95
+ }>;
96
+ }, z.core.$strip>>;
97
+ }, z.core.$strip>;
98
+ export type IProviderReattachment = z.infer<typeof ProviderReattachmentSchema>;
72
99
  export type IProviderCall = {
73
100
  signal: AbortSignal;
74
101
  };
@@ -129,6 +156,19 @@ export type IAgentProvider = {
129
156
  readObservedThread?(nativeId: string, call: IProviderCall): Promise<IThreadSummary>;
130
157
  /** @returns Verified native metadata and explicit eligibility for adoption or reattachment. */
131
158
  inspectThread(nativeId: string, workspaceRoot: string, call: IProviderCall): Promise<IProviderInspection>;
159
+ /**
160
+ * Reads a session a shared native process kept running after the previous runtime stopped,
161
+ * without joining it. A built-in provider whose sessions outlive the runtime implements this and
162
+ * reattachThread.
163
+ * @returns The session's native metadata, checked against its workspace, and its latest turn.
164
+ */
165
+ readReattachment?(nativeId: string, workspaceRoot: string, call: IProviderCall): Promise<IProviderReattachment>;
166
+ /**
167
+ * Joins a session a shared native process kept running, without changing its settings. The
168
+ * native process then sends this runtime the requests still waiting on an answer.
169
+ * @returns The session once joined, with its latest turn.
170
+ */
171
+ reattachThread?(requestId: string, nativeId: string, workspaceRoot: string, call: IProviderCall): Promise<IProviderReattachment>;
132
172
  /** @returns Native quota observations without starting a model turn. */
133
173
  readUsage(call: IProviderCall): Promise<IUsageSnapshot>;
134
174
  /** @returns Safe native account metadata, with an explicit unavailable observation when absent. */
@@ -1,5 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { SkillPageSchema, SkillSchema, ThreadSummarySchema } from '../contracts/index.js';
3
+ import { NativeIdSchema } from '../contracts/identities/index.js';
3
4
  // control acknowledgements retain exact identities without interpreting unknown execution states
4
5
  export const ProviderThreadSchema = ThreadSummarySchema.pick({
5
6
  nativeId: true,
@@ -11,6 +12,16 @@ export const ProviderInspectionSchema = z.object({
11
12
  canAdopt: z.boolean(),
12
13
  canResume: z.boolean(),
13
14
  });
15
+ // a session a shared native process kept running, with its latest turn, or null before any turn
16
+ export const ProviderReattachmentSchema = z.object({
17
+ thread: ProviderThreadSchema,
18
+ latestTurn: z
19
+ .object({
20
+ nativeId: NativeIdSchema,
21
+ state: z.enum(['running', 'completed', 'failed', 'interrupted']),
22
+ })
23
+ .nullable(),
24
+ });
14
25
  // normalized native inventory, bounded before client paging, with the prefix that invokes a skill
15
26
  export const ProviderSkillsSchema = z.object({
16
27
  invocationPrefix: SkillPageSchema.shape.invocationPrefix.unwrap(),
@@ -62,12 +62,15 @@ export const createAgentHq = async (options) => {
62
62
  try {
63
63
  const databasePath = await prepareDatabase(stateRoot);
64
64
  actionKey = await prepareActionKey(stateRoot, databasePath);
65
- store = await createStore(databasePath, ownership.owner.nonce, actionKey);
65
+ // Codex sessions run in its shared daemon, so they keep running while the runtime restarts
66
+ const codex = {
67
+ factory: createCodexProviderFactory(codexExtraSkillRoots, parsed.data.codexDaemonLauncher ?? []),
68
+ isBuiltIn: true,
69
+ keepsSessions: true,
70
+ };
71
+ store = await createStore(databasePath, ownership.owner.nonce, actionKey, [codex.factory.id]);
66
72
  registry = createProviderRegistry([
67
- {
68
- factory: createCodexProviderFactory(codexExtraSkillRoots, parsed.data.codexDaemonLauncher ?? []),
69
- isBuiltIn: true,
70
- },
73
+ codex,
71
74
  {
72
75
  factory: createClaudeProviderFactory(store, claudeAdditionalDirectories),
73
76
  isBuiltIn: true,
@@ -1,5 +1,6 @@
1
1
  export declare const CONTROLLED_THREAD_CAPACITY = 32;
2
2
  export declare const UNSTARTED_CONDITION = "active_turn_id IS NULL AND last_turn_id IS NULL AND is_archived = 0\n AND state != 'inactive' AND fork_source_thread_id IS NULL\n AND EXISTS (SELECT 1 FROM hq_action WHERE hq_action.id = hq_thread.registration_action_id\n AND hq_action.kind = 'thread-create')";
3
+ export declare const KEPT_SESSION_CONDITION = "ownership = 'managed' AND native_id IS NOT NULL\n AND pending_action_id IS NULL AND is_archived = 0 AND provider IN (SELECT value FROM json_each(?))";
3
4
  export declare const THREAD_COLUMNS = "id, provider, native_id, native_lineage, fork_source_thread_id, is_archived, name, workspace_root, ownership, runtime_epoch, active_turn_id, last_turn_id, last_turn_state, pending_action_id, state, registration_action_id, created_at, updated_at";
4
5
  export declare const ACTION_METADATA_COLUMNS = "id, digest, requested_runtime_epoch, runtime_epoch, kind, provider, control_state, thread_id, expected_turn_id, native_turn_id, native_request_id, delivery, completion, failure, related_action_id, requested_name, queue_ready, created_at, updated_at";
5
6
  export declare const ACTION_COLUMNS = "id, digest, requested_runtime_epoch, runtime_epoch, kind, provider, control_state, thread_id, expected_turn_id, native_turn_id, native_request_id, delivery, completion, failure, related_action_id, requested_name, queue_ready, created_at, updated_at, queued_input, result";
@@ -8,6 +8,13 @@ export const UNSTARTED_CONDITION = `active_turn_id IS NULL AND last_turn_id IS N
8
8
  AND state != 'inactive' AND fork_source_thread_id IS NULL
9
9
  AND EXISTS (SELECT 1 FROM hq_action WHERE hq_action.id = hq_thread.registration_action_id
10
10
  AND hq_action.kind = 'thread-create')`;
11
+ /*
12
+ * A managed session with no action in flight whose provider runs sessions in a native process that
13
+ * outlives the runtime. A runtime leaves it bound to itself at shutdown, and the next one rejoins
14
+ * it instead of marking its ownership uncertain. Its parameter is a JSON array of those providers.
15
+ */
16
+ export const KEPT_SESSION_CONDITION = `ownership = 'managed' AND native_id IS NOT NULL
17
+ AND pending_action_id IS NULL AND is_archived = 0 AND provider IN (SELECT value FROM json_each(?))`;
11
18
  // explicit selections keep queue bodies out of collection reads
12
19
  export const THREAD_COLUMNS = 'id, provider, native_id, native_lineage, fork_source_thread_id, is_archived, name, workspace_root, ownership, runtime_epoch, active_turn_id, last_turn_id, last_turn_state, pending_action_id, state, registration_action_id, created_at, updated_at';
13
20
  export const ACTION_METADATA_COLUMNS = 'id, digest, requested_runtime_epoch, runtime_epoch, kind, provider, control_state, thread_id, expected_turn_id, native_turn_id, native_request_id, delivery, completion, failure, related_action_id, requested_name, queue_ready, created_at, updated_at';
@@ -1,14 +1,18 @@
1
1
  import type { DatabaseSync } from 'node:sqlite';
2
2
  import { type INativeApprovalSummary, type IActionReceipt, type IActionSummary, type IManagedThread, type ILifecycleEvent, type IHistoryProvenance } from '../../contracts/index.js';
3
3
  import type { IEvidenceOriginsRequest } from '../../sessions/evidence/index.js';
4
- import { type IAdmission, type IAdmissionResult, type IControlPage, type IApprovalPageRequest, type IEventPage, type INativeOutcome, type INativeObservation, type IObservationResult, type IDispatch, type IApprovalRecord } from './types.js';
4
+ import { type IAdmission, type IAdmissionResult, type IControlPage, type IApprovalPageRequest, type IEventPage, type INativeOutcome, type INativeObservation, type IObservationResult, type IDispatch, type IApprovalRecord, type IReattachment } from './types.js';
5
5
  /** Owns synchronous control-ledger transactions inside the dedicated SQLite worker. */
6
6
  export declare class ControlModel {
7
7
  private readonly __database;
8
8
  private readonly __epoch;
9
9
  private readonly __digestKey;
10
- /** Quarantines unsettled controls from another runtime before accepting new actions. */
11
- constructor(database: DatabaseSync, runtimeEpoch: string, digestKey: Uint8Array);
10
+ private readonly __keepingProviders;
11
+ /**
12
+ * Quarantines unsettled controls from another runtime before accepting new actions, except the
13
+ * sessions a provider in keepingProviders still runs, which the runtime rejoins.
14
+ */
15
+ constructor(database: DatabaseSync, runtimeEpoch: string, digestKey: Uint8Array, keepingProviders: string[]);
12
16
  /** Returns one receipt, including an undelivered queue body when present. */
13
17
  getAction(id: string): IActionReceipt | null;
14
18
  /** Resolves exact native input identities and content hashes; native roles grant no identity. */
@@ -95,8 +99,28 @@ export declare class ControlModel {
95
99
  * - JG_AGENT_HQ_ACTION_CONFLICT: The HQ action conflicts with its recorded state
96
100
  */
97
101
  observe(observation: INativeObservation): IObservationResult;
98
- /** Marks controls inactive only after its caller has proven native shutdown. */
102
+ /**
103
+ * Marks controls inactive only after its caller has proven native shutdown. A session a native
104
+ * process keeps running stays bound to this runtime, for the next one to rejoin.
105
+ */
99
106
  releaseControls(): void;
107
+ /** Lists the sessions another runtime left running, which this runtime rejoins, oldest first. */
108
+ listReattachable(): IManagedThread[];
109
+ /**
110
+ * Binds a session another runtime left running to this runtime, as its native process reports
111
+ * it before the runtime rejoins it. A turn that finished meanwhile completes its action and lets
112
+ * the session's queued input advance, which this runtime then delivers. A session whose latest
113
+ * turn isn't the one HQ recorded, because another client started one, has its ownership marked
114
+ * uncertain instead.
115
+ * @returns The thread and whether its queue may advance, or null when it is no longer one to rejoin.
116
+ * @throws
117
+ * - JG_AGENT_HQ_ACTION_CONFLICT: The HQ action conflicts with its recorded state
118
+ */
119
+ reattach(input: IReattachment): IObservationResult | null;
120
+ /** Marks a session's ownership uncertain when this runtime can't rejoin it. */
121
+ quarantineThread(threadId: string): void;
122
+ /** Quarantines one session another runtime left bound to itself, once. */
123
+ private __quarantine;
100
124
  private __thread;
101
125
  /** Recomputes the visible wait state after one of several native prompts ends. */
102
126
  private __refreshApprovalState;
@@ -4,7 +4,7 @@ import { z } from 'zod';
4
4
  import { LifecycleEventSchema, PreparedInputSchema, NativeApprovalSummarySchema, } from '../../contracts/index.js';
5
5
  import { getErrorKind } from '../../errors/index.js';
6
6
  import { suffixThreadName } from '../../sessions/names/index.js';
7
- import { ACTION_COLUMNS, ACTION_METADATA_COLUMNS, ACTION_RECEIPT_COLUMNS, CONTROLLED_THREAD_CAPACITY, EVENT_COLUMNS, THREAD_COLUMNS, UNSTARTED_CONDITION, } from './constants.js';
7
+ import { ACTION_COLUMNS, ACTION_METADATA_COLUMNS, ACTION_RECEIPT_COLUMNS, CONTROLLED_THREAD_CAPACITY, EVENT_COLUMNS, KEPT_SESSION_CONDITION, THREAD_COLUMNS, UNSTARTED_CONDITION, } from './constants.js';
8
8
  import { toActionReceipt, toActionSummary, toManagedThread } from './transformers.js';
9
9
  import { ActionReceiptRowSchema, ActionRowSchema, ThreadRowSchema, } from './types.js';
10
10
  const FailureSchema = z.object({
@@ -16,16 +16,22 @@ export class ControlModel {
16
16
  __database;
17
17
  __epoch;
18
18
  __digestKey;
19
- /** Quarantines unsettled controls from another runtime before accepting new actions. */
20
- constructor(database, runtimeEpoch, digestKey) {
19
+ // a JSON array of the providers whose sessions outlive the runtime, which it rejoins
20
+ __keepingProviders;
21
+ /**
22
+ * Quarantines unsettled controls from another runtime before accepting new actions, except the
23
+ * sessions a provider in keepingProviders still runs, which the runtime rejoins.
24
+ */
25
+ constructor(database, runtimeEpoch, digestKey, keepingProviders) {
21
26
  this.__database = database;
22
27
  this.__epoch = runtimeEpoch;
23
28
  this.__digestKey = createSecretKey(digestKey);
29
+ this.__keepingProviders = JSON.stringify(keepingProviders);
24
30
  const now = Date.now();
25
31
  this.__transaction(() => {
26
32
  database
27
- .prepare("UPDATE hq_thread SET ownership = 'uncertain', state = 'unknown', updated_at = ? WHERE runtime_epoch IS NOT NULL AND runtime_epoch != ? AND ownership = 'managed'")
28
- .run(now, runtimeEpoch);
33
+ .prepare(`UPDATE hq_thread SET ownership = 'uncertain', state = 'unknown', updated_at = ? WHERE runtime_epoch IS NOT NULL AND runtime_epoch != ? AND ownership = 'managed' AND NOT (${KEPT_SESSION_CONDITION})`)
34
+ .run(now, runtimeEpoch, this.__keepingProviders);
29
35
  database
30
36
  .prepare("UPDATE hq_action SET delivery = 'uncertain', updated_at = ? WHERE runtime_epoch != ? AND delivery = 'submitted'")
31
37
  .run(now, runtimeEpoch);
@@ -937,13 +943,16 @@ export class ControlModel {
937
943
  };
938
944
  });
939
945
  }
940
- /** Marks controls inactive only after its caller has proven native shutdown. */
946
+ /**
947
+ * Marks controls inactive only after its caller has proven native shutdown. A session a native
948
+ * process keeps running stays bound to this runtime, for the next one to rejoin.
949
+ */
941
950
  releaseControls() {
942
951
  this.__transaction(() => {
943
952
  const now = Date.now();
944
953
  this.__database
945
- .prepare("UPDATE hq_thread SET runtime_epoch = NULL, pending_action_id = NULL, active_turn_id = NULL, ownership = CASE WHEN native_id IS NULL THEN 'uncertain' ELSE 'managed' END, state = CASE WHEN native_id IS NULL THEN 'unknown' ELSE 'inactive' END, updated_at = ? WHERE runtime_epoch = ?")
946
- .run(now, this.__epoch);
954
+ .prepare(`UPDATE hq_thread SET runtime_epoch = NULL, pending_action_id = NULL, active_turn_id = NULL, ownership = CASE WHEN native_id IS NULL THEN 'uncertain' ELSE 'managed' END, state = CASE WHEN native_id IS NULL THEN 'unknown' ELSE 'inactive' END, updated_at = ? WHERE runtime_epoch = ? AND NOT (${KEPT_SESSION_CONDITION})`)
955
+ .run(now, this.__epoch, this.__keepingProviders);
947
956
  this.__database
948
957
  .prepare("UPDATE hq_action SET delivery = 'uncertain', updated_at = ? WHERE runtime_epoch = ? AND delivery = 'submitted'")
949
958
  .run(now, this.__epoch);
@@ -955,6 +964,81 @@ export class ControlModel {
955
964
  .run(now, this.__epoch);
956
965
  });
957
966
  }
967
+ /** Lists the sessions another runtime left running, which this runtime rejoins, oldest first. */
968
+ listReattachable() {
969
+ return this.__database
970
+ .prepare(`SELECT ${THREAD_COLUMNS} FROM hq_thread WHERE runtime_epoch IS NOT NULL AND runtime_epoch != ? AND ${KEPT_SESSION_CONDITION} ORDER BY created_at ASC, id ASC LIMIT ?`)
971
+ .all(this.__epoch, this.__keepingProviders, CONTROLLED_THREAD_CAPACITY)
972
+ .map((row) => toManagedThread(ThreadRowSchema.parse(row)));
973
+ }
974
+ /**
975
+ * Binds a session another runtime left running to this runtime, as its native process reports
976
+ * it before the runtime rejoins it. A turn that finished meanwhile completes its action and lets
977
+ * the session's queued input advance, which this runtime then delivers. A session whose latest
978
+ * turn isn't the one HQ recorded, because another client started one, has its ownership marked
979
+ * uncertain instead.
980
+ * @returns The thread and whether its queue may advance, or null when it is no longer one to rejoin.
981
+ * @throws
982
+ * - JG_AGENT_HQ_ACTION_CONFLICT: The HQ action conflicts with its recorded state
983
+ */
984
+ reattach(input) {
985
+ return this.__transaction(() => {
986
+ const row = this.__database
987
+ .prepare(`SELECT ${THREAD_COLUMNS} FROM hq_thread WHERE id = ? AND runtime_epoch IS NOT NULL AND runtime_epoch != ? AND ${KEPT_SESSION_CONDITION}`)
988
+ .get(input.threadId, this.__epoch, this.__keepingProviders);
989
+ if (!row)
990
+ return null;
991
+ const thread = ThreadRowSchema.parse(row);
992
+ const now = Date.now();
993
+ const latest = input.latestTurn;
994
+ const isRunning = latest?.state === 'running';
995
+ if ((latest?.nativeTurnId ?? null) !== (thread.active_turn_id ?? thread.last_turn_id) ||
996
+ (isRunning && thread.active_turn_id === null)) {
997
+ this.__quarantine(thread.id, now);
998
+ return { thread: this.getThread(thread.id), canDispatchQueued: false };
999
+ }
1000
+ this.__availableSlot();
1001
+ // the turn HQ left running, when it has finished since
1002
+ const finished = thread.active_turn_id !== null && latest && latest.state !== 'running'
1003
+ ? { nativeTurnId: latest.nativeTurnId, state: latest.state }
1004
+ : null;
1005
+ const state = isRunning
1006
+ ? thread.state === 'stopping'
1007
+ ? 'stopping'
1008
+ : 'running'
1009
+ : (finished?.state ?? thread.state);
1010
+ this.__database
1011
+ .prepare('UPDATE hq_thread SET runtime_epoch = ?, active_turn_id = ?, last_turn_id = ?, last_turn_state = ?, state = ?, updated_at = ? WHERE id = ?')
1012
+ .run(this.__epoch, isRunning ? latest.nativeTurnId : null, finished?.nativeTurnId ?? thread.last_turn_id, finished?.state ?? thread.last_turn_state, state, now, thread.id);
1013
+ this.__database
1014
+ .prepare("UPDATE hq_action SET runtime_epoch = ?, updated_at = ? WHERE thread_id = ? AND delivery = 'queued'")
1015
+ .run(this.__epoch, now, thread.id);
1016
+ const canDispatchQueued = finished?.state === 'completed' && thread.state !== 'stopping';
1017
+ if (finished) {
1018
+ this.__database
1019
+ .prepare('UPDATE hq_action SET completion = ?, updated_at = ? WHERE thread_id = ? AND native_turn_id = ? AND completion IS NULL')
1020
+ .run(finished.state, now, thread.id, finished.nativeTurnId);
1021
+ if (canDispatchQueued)
1022
+ this.__database
1023
+ .prepare("UPDATE hq_action SET queue_ready = 1 WHERE thread_id = ? AND expected_turn_id = ? AND delivery = 'queued'")
1024
+ .run(thread.id, finished.nativeTurnId);
1025
+ }
1026
+ this.__event('thread-updated', thread.id, null, latest?.nativeTurnId ?? null);
1027
+ return { thread: this.getThread(thread.id), canDispatchQueued };
1028
+ });
1029
+ }
1030
+ /** Marks a session's ownership uncertain when this runtime can't rejoin it. */
1031
+ quarantineThread(threadId) {
1032
+ this.__transaction(() => this.__quarantine(threadId, Date.now()));
1033
+ }
1034
+ /** Quarantines one session another runtime left bound to itself, once. */
1035
+ __quarantine(threadId, now) {
1036
+ const { changes } = this.__database
1037
+ .prepare("UPDATE hq_thread SET ownership = 'uncertain', state = 'unknown', updated_at = ? WHERE id = ? AND runtime_epoch IS NOT NULL AND runtime_epoch != ? AND ownership = 'managed'")
1038
+ .run(now, threadId, this.__epoch);
1039
+ if (changes)
1040
+ this.__event('native-unavailable', threadId, null);
1041
+ }
958
1042
  __thread(id) {
959
1043
  const row = this.__database
960
1044
  .prepare(`SELECT ${THREAD_COLUMNS} FROM hq_thread WHERE id = ?`)
@@ -1,5 +1,5 @@
1
- export { ThreadRowSchema, ActionRowSchema, NativeOutcomeSchema, NativeObservationSchema, AdmissionSchema, AdmissionResultSchema, DispatchSchema, ObservationResultSchema, ControlPageSchema, ApprovalPageRequestSchema, ApprovalPageSchema, EventPageSchema, ApprovalRecordSchema, ManagedThreadPageSchema, ActionPageSchema, LifecyclePageSchema, } from './types.js';
2
- export type { IThreadRow, IActionRow, INativeOutcome, INativeObservation, IAdmission, IAdmissionResult, IDispatch, IObservationResult, IControlPage, IApprovalPageRequest, IEventPage, IApprovalRecord, } from './types.js';
1
+ export { ThreadRowSchema, ActionRowSchema, NativeOutcomeSchema, NativeObservationSchema, AdmissionSchema, AdmissionResultSchema, DispatchSchema, ObservationResultSchema, ReattachmentSchema, ControlPageSchema, ApprovalPageRequestSchema, ApprovalPageSchema, EventPageSchema, ApprovalRecordSchema, ManagedThreadPageSchema, ActionPageSchema, LifecyclePageSchema, } from './types.js';
2
+ export type { IThreadRow, IActionRow, INativeOutcome, INativeObservation, IAdmission, IAdmissionResult, IDispatch, IObservationResult, IReattachment, IControlPage, IApprovalPageRequest, IEventPage, IApprovalRecord, } from './types.js';
3
3
  export { ApprovalIdentitySchema } from './types.js';
4
4
  export { ControlModel } from './control.model.js';
5
5
  export { THREAD_COLUMNS } from './constants.js';
@@ -1,5 +1,5 @@
1
1
  // worker-owned control contracts
2
- export { ThreadRowSchema, ActionRowSchema, NativeOutcomeSchema, NativeObservationSchema, AdmissionSchema, AdmissionResultSchema, DispatchSchema, ObservationResultSchema, ControlPageSchema, ApprovalPageRequestSchema, ApprovalPageSchema, EventPageSchema, ApprovalRecordSchema, ManagedThreadPageSchema, ActionPageSchema, LifecyclePageSchema, } from './types.js';
2
+ export { ThreadRowSchema, ActionRowSchema, NativeOutcomeSchema, NativeObservationSchema, AdmissionSchema, AdmissionResultSchema, DispatchSchema, ObservationResultSchema, ReattachmentSchema, ControlPageSchema, ApprovalPageRequestSchema, ApprovalPageSchema, EventPageSchema, ApprovalRecordSchema, ManagedThreadPageSchema, ActionPageSchema, LifecyclePageSchema, } from './types.js';
3
3
  export { ApprovalIdentitySchema } from './types.js';
4
4
  export { ControlModel } from './control.model.js';
5
5
  // selected worker-only thread projections
@@ -1039,6 +1039,19 @@ export declare const ObservationResultSchema: z.ZodObject<{
1039
1039
  canDispatchQueued: z.ZodBoolean;
1040
1040
  }, z.core.$strip>;
1041
1041
  export type IObservationResult = z.infer<typeof ObservationResultSchema>;
1042
+ export declare const ReattachmentSchema: z.ZodObject<{
1043
+ threadId: z.ZodUUID;
1044
+ latestTurn: z.ZodNullable<z.ZodObject<{
1045
+ nativeTurnId: z.ZodString;
1046
+ state: z.ZodEnum<{
1047
+ completed: "completed";
1048
+ failed: "failed";
1049
+ interrupted: "interrupted";
1050
+ running: "running";
1051
+ }>;
1052
+ }, z.core.$strict>>;
1053
+ }, z.core.$strict>;
1054
+ export type IReattachment = z.infer<typeof ReattachmentSchema>;
1042
1055
  export declare const ControlPageSchema: z.ZodObject<{
1043
1056
  limit: z.ZodNumber;
1044
1057
  position: z.ZodNullable<z.ZodObject<{
@@ -170,6 +170,16 @@ export const ObservationResultSchema = z.object({
170
170
  thread: ManagedThreadSchema.nullable(),
171
171
  canDispatchQueued: z.boolean(),
172
172
  });
173
+ // a session another runtime left running, with its latest turn as its native process reports it
174
+ export const ReattachmentSchema = z.strictObject({
175
+ threadId: z.uuid(),
176
+ latestTurn: z
177
+ .strictObject({
178
+ nativeTurnId: NativeIdSchema,
179
+ state: z.enum(['running', 'completed', 'failed', 'interrupted']),
180
+ })
181
+ .nullable(),
182
+ });
173
183
  // public cursors are decoded and query-bound before these trusted seek positions are sent
174
184
  export const ControlPageSchema = z.strictObject({
175
185
  limit: z.number().int().min(1).max(128),
@@ -7,4 +7,4 @@ import { type IStore } from './types.js';
7
7
  * - JG_AGENT_HQ_STORAGE_INVALID: The HQ storage is invalid
8
8
  * - JG_AGENT_HQ_ACTION_KEY_UNAVAILABLE: The HQ action key is unavailable
9
9
  */
10
- export declare const createStore: (databasePath: string, runtimeEpoch: string, actionKey: Uint8Array) => Promise<IStore>;
10
+ export declare const createStore: (databasePath: string, runtimeEpoch: string, actionKey: Uint8Array, keepingProviders: string[]) => Promise<IStore>;
@@ -14,7 +14,7 @@ import { StoreRequestSchema, StoreResponseSchema, } from './types.js';
14
14
  * - JG_AGENT_HQ_STORAGE_INVALID: The HQ storage is invalid
15
15
  * - JG_AGENT_HQ_ACTION_KEY_UNAVAILABLE: The HQ action key is unavailable
16
16
  */
17
- export const createStore = async (databasePath, runtimeEpoch, actionKey) => {
17
+ export const createStore = async (databasePath, runtimeEpoch, actionKey, keepingProviders) => {
18
18
  const worker = new Worker(new URL('./store.worker.js', import.meta.url), {
19
19
  // the worker loads a file, even when its caller used Node's string-input mode
20
20
  execArgv: process.execArgv.filter((argument, index, arguments_) => argument !== '--input-type' &&
@@ -22,7 +22,7 @@ export const createStore = async (databasePath, runtimeEpoch, actionKey) => {
22
22
  arguments_[index - 1] !== '--input-type'),
23
23
  // indexing a large transcript otherwise grows the young generation to V8's default maximum
24
24
  resourceLimits: { maxYoungGenerationSizeMb: 16 },
25
- workerData: { databasePath, runtimeEpoch, actionKey },
25
+ workerData: { databasePath, runtimeEpoch, actionKey, keepingProviders },
26
26
  });
27
27
  let hasExited = false;
28
28
  const exited = new Promise((resolve) => worker.once('exit', () => {
@@ -205,6 +205,11 @@ export const createStore = async (databasePath, runtimeEpoch, actionKey) => {
205
205
  releaseControls: async () => {
206
206
  await request({ kind: 'release' }, z.null());
207
207
  },
208
+ listReattachable: () => request({ kind: 'reattachable' }, z.array(ManagedThreadSchema)),
209
+ reattach: (input) => request({ kind: 'reattach', input }, ObservationResultSchema.nullable()),
210
+ quarantineThread: async (threadId) => {
211
+ await request({ kind: 'quarantine', threadId }, z.null());
212
+ },
208
213
  close: () => (closing ??= (async () => {
209
214
  try {
210
215
  await request({ kind: 'close' }, z.null());
@@ -26,7 +26,7 @@ const startWorker = async () => {
26
26
  };
27
27
  const browser = new BrowserModel(database, options.runtimeEpoch, options.actionKey);
28
28
  const sessions = new SessionsModel(database);
29
- const controls = new ControlModel(database, options.runtimeEpoch, options.actionKey);
29
+ const controls = new ControlModel(database, options.runtimeEpoch, options.actionKey, options.keepingProviders);
30
30
  const claudeHistory = new ClaudeHistoryModel(database);
31
31
  port.on('message', async (message) => {
32
32
  const parsed = StoreRequestSchema.safeParse(message);
@@ -146,6 +146,15 @@ const startWorker = async () => {
146
146
  case 'release':
147
147
  controls.releaseControls();
148
148
  break;
149
+ case 'reattachable':
150
+ result = controls.listReattachable();
151
+ break;
152
+ case 'reattach':
153
+ result = controls.reattach(command.input);
154
+ break;
155
+ case 'quarantine':
156
+ controls.quarantineThread(command.threadId);
157
+ break;
149
158
  }
150
159
  port.postMessage({ kind: 'result', id, result, error: null });
151
160
  }
@@ -4,7 +4,7 @@ import type { IHistoryRequest } from '../sessions/index.js';
4
4
  import { type IEvidenceOriginsRequest } from '../sessions/evidence/index.js';
5
5
  import type { IClaudeHistoryRead } from '../providers/claude/history/index.js';
6
6
  import { type IStorageDescriptor } from '../storage/index.js';
7
- import { type IAdmission, type INativeOutcome, type INativeObservation, type IControlPage, type IApprovalPageRequest, type IEventPage, type IApprovalRecord, type IAdmissionResult, type IDispatch, type IObservationResult } from './control/index.js';
7
+ import { type IAdmission, type INativeOutcome, type INativeObservation, type IControlPage, type IApprovalPageRequest, type IEventPage, type IApprovalRecord, type IAdmissionResult, type IDispatch, type IObservationResult, type IReattachment } from './control/index.js';
8
8
  import type { IActiveSessionRecord } from './sessions/index.js';
9
9
  export declare const StoreCommandSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
10
10
  kind: z.ZodLiteral<"evidence-origins">;
@@ -1356,6 +1356,25 @@ export declare const StoreCommandSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
1356
1356
  }, z.core.$strict>;
1357
1357
  }, z.core.$strict>, z.ZodObject<{
1358
1358
  kind: z.ZodLiteral<"release">;
1359
+ }, z.core.$strict>, z.ZodObject<{
1360
+ kind: z.ZodLiteral<"reattachable">;
1361
+ }, z.core.$strict>, z.ZodObject<{
1362
+ kind: z.ZodLiteral<"reattach">;
1363
+ input: z.ZodObject<{
1364
+ threadId: z.ZodUUID;
1365
+ latestTurn: z.ZodNullable<z.ZodObject<{
1366
+ nativeTurnId: z.ZodString;
1367
+ state: z.ZodEnum<{
1368
+ completed: "completed";
1369
+ failed: "failed";
1370
+ interrupted: "interrupted";
1371
+ running: "running";
1372
+ }>;
1373
+ }, z.core.$strict>>;
1374
+ }, z.core.$strict>;
1375
+ }, z.core.$strict>, z.ZodObject<{
1376
+ kind: z.ZodLiteral<"quarantine">;
1377
+ threadId: z.ZodUUID;
1359
1378
  }, z.core.$strict>], "kind">;
1360
1379
  export type IStoreCommand = z.infer<typeof StoreCommandSchema>;
1361
1380
  export declare const StoreRequestSchema: z.ZodObject<{
@@ -2710,6 +2729,25 @@ export declare const StoreRequestSchema: z.ZodObject<{
2710
2729
  }, z.core.$strict>;
2711
2730
  }, z.core.$strict>, z.ZodObject<{
2712
2731
  kind: z.ZodLiteral<"release">;
2732
+ }, z.core.$strict>, z.ZodObject<{
2733
+ kind: z.ZodLiteral<"reattachable">;
2734
+ }, z.core.$strict>, z.ZodObject<{
2735
+ kind: z.ZodLiteral<"reattach">;
2736
+ input: z.ZodObject<{
2737
+ threadId: z.ZodUUID;
2738
+ latestTurn: z.ZodNullable<z.ZodObject<{
2739
+ nativeTurnId: z.ZodString;
2740
+ state: z.ZodEnum<{
2741
+ completed: "completed";
2742
+ failed: "failed";
2743
+ interrupted: "interrupted";
2744
+ running: "running";
2745
+ }>;
2746
+ }, z.core.$strict>>;
2747
+ }, z.core.$strict>;
2748
+ }, z.core.$strict>, z.ZodObject<{
2749
+ kind: z.ZodLiteral<"quarantine">;
2750
+ threadId: z.ZodUUID;
2713
2751
  }, z.core.$strict>], "kind">;
2714
2752
  }, z.core.$strict>;
2715
2753
  export declare const StoreResponseSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
@@ -2765,6 +2803,7 @@ export declare const StoreWorkerSchema: z.ZodObject<{
2765
2803
  databasePath: z.ZodString;
2766
2804
  runtimeEpoch: z.ZodUUID;
2767
2805
  actionKey: z.ZodInstanceOf<Uint8Array<ArrayBuffer>>;
2806
+ keepingProviders: z.ZodArray<z.ZodString>;
2768
2807
  }, z.core.$strict>;
2769
2808
  export type IStore = {
2770
2809
  /** Correlates native input identities and hashes with durable host submissions.
@@ -3030,6 +3069,28 @@ export type IStore = {
3030
3069
  * - JG_AGENT_HQ_STORE_FAILED: The HQ store failed
3031
3070
  */
3032
3071
  releaseControls(): Promise<void>;
3072
+ /**
3073
+ * Lists the sessions another runtime left running, which this runtime rejoins.
3074
+ * @returns At most one runtime's worth of controlled sessions, oldest first.
3075
+ * @throws
3076
+ * - JG_AGENT_HQ_STORE_FAILED: The HQ store failed
3077
+ */
3078
+ listReattachable(): Promise<IManagedThread[]>;
3079
+ /**
3080
+ * Binds a session another runtime left running to this runtime before it rejoins the session.
3081
+ * @returns The thread and whether its queue may advance, or null when it is no longer one to rejoin.
3082
+ * @throws
3083
+ * - JG_AGENT_HQ_STORE_FAILED: The HQ store failed
3084
+ * - JG_AGENT_HQ_ACTION_CONFLICT: The HQ action conflicts with its recorded state
3085
+ */
3086
+ reattach(input: IReattachment): Promise<IObservationResult | null>;
3087
+ /**
3088
+ * Marks a session's ownership uncertain when this runtime can't rejoin it.
3089
+ * @returns A promise resolved after the change is committed.
3090
+ * @throws
3091
+ * - JG_AGENT_HQ_STORE_FAILED: The HQ store failed
3092
+ */
3093
+ quarantineThread(threadId: string): Promise<void>;
3033
3094
  /**
3034
3095
  * Closes SQLite and waits for the worker to exit.
3035
3096
  * @returns A promise resolved after SQLite closes and the worker exits.
@@ -1,8 +1,8 @@
1
1
  import { z } from 'zod';
2
- import { BrowserActionSchema, BrowserReceiptSchema, MAX_PAGE_SIZE, ManagedThreadSchema, ErrorKindSchema, HqRequestSchema, SessionStateSchema, } from '../contracts/index.js';
2
+ import { BrowserActionSchema, BrowserReceiptSchema, MAX_PAGE_SIZE, MAX_PROVIDERS, ManagedThreadSchema, ErrorKindSchema, HqRequestSchema, SessionStateSchema, } from '../contracts/index.js';
3
3
  import { EvidenceOriginsRequestSchema, } from '../sessions/evidence/index.js';
4
4
  import { StorageDescriptorSchema } from '../storage/index.js';
5
- import { AdmissionSchema, NativeOutcomeSchema, NativeObservationSchema, ControlPageSchema, ApprovalPageRequestSchema, EventPageSchema, ApprovalRecordSchema, } from './control/index.js';
5
+ import { AdmissionSchema, NativeOutcomeSchema, NativeObservationSchema, ControlPageSchema, ApprovalPageRequestSchema, EventPageSchema, ApprovalRecordSchema, ReattachmentSchema, } from './control/index.js';
6
6
  // worker messages are closed, bounded operations rather than arbitrary SQL
7
7
  export const StoreCommandSchema = z.discriminatedUnion('kind', [
8
8
  z.strictObject({ kind: z.literal('evidence-origins'), request: EvidenceOriginsRequestSchema }),
@@ -98,6 +98,9 @@ export const StoreCommandSchema = z.discriminatedUnion('kind', [
98
98
  z.strictObject({ kind: z.literal('claim-queue'), threadId: z.uuid() }),
99
99
  z.strictObject({ kind: z.literal('approval'), input: ApprovalRecordSchema }),
100
100
  z.strictObject({ kind: z.literal('release') }),
101
+ z.strictObject({ kind: z.literal('reattachable') }),
102
+ z.strictObject({ kind: z.literal('reattach'), input: ReattachmentSchema }),
103
+ z.strictObject({ kind: z.literal('quarantine'), threadId: z.uuid() }),
101
104
  ]);
102
105
  export const StoreRequestSchema = z.strictObject({
103
106
  id: z.number().int(),
@@ -122,4 +125,6 @@ export const StoreWorkerSchema = z.strictObject({
122
125
  databasePath: z.string().min(1),
123
126
  runtimeEpoch: z.uuid(),
124
127
  actionKey: z.instanceof(Uint8Array).refine((key) => key.length === 32),
128
+ // the providers whose sessions outlive the runtime, which it rejoins
129
+ keepingProviders: z.array(ManagedThreadSchema.shape.provider).max(MAX_PROVIDERS),
125
130
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jg-agent-hq",
3
- "version": "10.2.0",
3
+ "version": "10.3.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",