jg-agent-hq 13.0.0 → 13.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/README.md +1 -1
- package/api/README.md +4 -0
- package/dist/actions/actions.js +3 -2
- package/dist/actions/events/events.d.ts +1 -1
- package/dist/actions/events/events.js +18 -2
- package/dist/actions/reattach/reattach.d.ts +2 -0
- package/dist/actions/reattach/reattach.js +29 -4
- package/dist/providers/codex/events.js +37 -8
- package/dist/providers/codex/rpc.js +9 -1
- package/dist/store/control/lifecycle/lifecycle.model.d.ts +6 -1
- package/dist/store/control/lifecycle/lifecycle.model.js +18 -5
- package/dist/store/control/types.d.ts +1 -0
- package/docs/recovery.md +4 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 13.0.1
|
|
4
|
+
|
|
5
|
+
- 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.
|
|
6
|
+
- 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.
|
|
7
|
+
- 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.
|
|
8
|
+
- Keep the existing storage schema, action key and public request contracts unchanged.
|
|
9
|
+
|
|
3
10
|
## 13.0.0
|
|
4
11
|
|
|
5
12
|
- 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.
|
package/dist/actions/actions.js
CHANGED
|
@@ -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
|
-
|
|
68
|
+
const reattachment = createReattach(context, dispatcher, events);
|
|
69
|
+
context.runOwned(reattachment.reattach);
|
|
69
70
|
return {
|
|
70
71
|
live,
|
|
71
72
|
waits,
|
|
@@ -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
|
-
|
|
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,17 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import { capabilityUnavailable } from '../../providers/registry/index.js';
|
|
3
3
|
import { agentUnavailable } from '../utilities.js';
|
|
4
|
+
/**
|
|
5
|
+
* Refuses unknown execution state before restoring native control.
|
|
6
|
+
* @throws
|
|
7
|
+
* - JG_AGENT_HQ_PROVIDER_FAILED: The HQ provider integration failed
|
|
8
|
+
*/
|
|
9
|
+
const assertKnownTurn = (read) => {
|
|
10
|
+
if (read.thread.nativeState === 'systemError' ||
|
|
11
|
+
read.thread.nativeState === 'unknown' ||
|
|
12
|
+
(read.thread.nativeState === 'active' && read.latestTurn?.state !== 'running'))
|
|
13
|
+
agentUnavailable();
|
|
14
|
+
};
|
|
4
15
|
/**
|
|
5
16
|
* Rejoins the sessions the previous runtime left running in a native process that outlives it.
|
|
6
17
|
* @returns The rejoining operation, which the runtime runs once it starts.
|
|
@@ -18,7 +29,7 @@ export const createReattach = (context, dispatcher, events) => {
|
|
|
18
29
|
* @throws
|
|
19
30
|
* - JG_AGENT_HQ_STORE_FAILED: The HQ store failed
|
|
20
31
|
*/
|
|
21
|
-
const reattachThread = async (thread) => {
|
|
32
|
+
const reattachThread = async (thread, isReconnect = false) => {
|
|
22
33
|
const nativeId = thread.nativeId;
|
|
23
34
|
let isOwned = false;
|
|
24
35
|
try {
|
|
@@ -27,10 +38,10 @@ export const createReattach = (context, dispatcher, events) => {
|
|
|
27
38
|
capabilityUnavailable();
|
|
28
39
|
await validateRoot(thread);
|
|
29
40
|
const read = await control.readReattachment(nativeId, thread.workspaceRoot);
|
|
30
|
-
|
|
31
|
-
agentUnavailable();
|
|
41
|
+
assertKnownTurn(read);
|
|
32
42
|
const bound = await store.call('lifecycle', 'reattach', {
|
|
33
43
|
threadId: thread.id,
|
|
44
|
+
isReconnect,
|
|
34
45
|
latestTurn: read.latestTurn && {
|
|
35
46
|
nativeTurnId: read.latestTurn.nativeId,
|
|
36
47
|
state: read.latestTurn.state,
|
|
@@ -42,8 +53,11 @@ export const createReattach = (context, dispatcher, events) => {
|
|
|
42
53
|
own(thread.provider, nativeId);
|
|
43
54
|
isOwned = true;
|
|
44
55
|
const joined = await control.reattachThread(`${randomUUID()}:reattach`, nativeId, thread.workspaceRoot);
|
|
56
|
+
assertKnownTurn(joined);
|
|
45
57
|
const turnId = bound.thread.activeTurnId;
|
|
46
58
|
const latest = joined.latestTurn;
|
|
59
|
+
if ((latest?.nativeId ?? null) !== (read.latestTurn?.nativeId ?? null))
|
|
60
|
+
agentUnavailable();
|
|
47
61
|
if (turnId && latest?.nativeId === turnId && latest.state !== 'running') {
|
|
48
62
|
const { state: turnState } = latest;
|
|
49
63
|
live.completeTurn(key(thread.provider, nativeId), turnId);
|
|
@@ -80,5 +94,16 @@ export const createReattach = (context, dispatcher, events) => {
|
|
|
80
94
|
batch = await store.call('lifecycle', 'listReattachable');
|
|
81
95
|
}
|
|
82
96
|
};
|
|
83
|
-
|
|
97
|
+
/**
|
|
98
|
+
* Rechecks only controls captured before this connection lost its native evidence.
|
|
99
|
+
* @returns A promise resolved after the bounded cohort has been checked in order.
|
|
100
|
+
*/
|
|
101
|
+
const reconnect = async (threads) => {
|
|
102
|
+
for (const thread of threads) {
|
|
103
|
+
if (state.isClosing || state.isUnavailable || context.blockedProviders.has(thread.provider))
|
|
104
|
+
return;
|
|
105
|
+
await reattachThread(thread, true);
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
return { reattach, reconnect };
|
|
84
109
|
};
|
|
@@ -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:
|
|
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,
|
|
233
|
+
events.unpresentable(thread.data.threadId, reject);
|
|
217
234
|
else
|
|
218
|
-
void
|
|
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:
|
|
242
|
+
requestId: scopedRequestId(id),
|
|
226
243
|
fingerprint: JSON.stringify([method, params]),
|
|
227
244
|
presentation: toApprovalPresentation(prompt),
|
|
228
|
-
validate: (response) =>
|
|
229
|
-
|
|
230
|
-
|
|
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: () =>
|
|
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
|
-
|
|
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
|
}
|
|
@@ -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
|
-
*
|
|
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
|
-
*
|
|
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
|
|
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
|
-
|
|
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 ??
|
|
88
|
-
|
|
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) {
|
package/docs/recovery.md
CHANGED
|
@@ -30,6 +30,10 @@ 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
|
+
|
|
33
37
|
## Off-machine durability
|
|
34
38
|
|
|
35
39
|
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