jg-agent-hq 12.0.1 → 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 +13 -0
- package/README.md +4 -2
- package/api/README.md +8 -2
- 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/contracts/actions/types.js +5 -2
- package/dist/contracts/constants.d.ts +1 -0
- package/dist/contracts/constants.js +2 -0
- package/dist/contracts/index.d.ts +1 -1
- package/dist/contracts/index.js +1 -1
- package/dist/providers/codex/events.js +37 -8
- package/dist/providers/codex/rpc.js +9 -1
- package/dist/sessions/names/utilities.js +3 -2
- 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 +10 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
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
|
+
|
|
10
|
+
## 13.0.0
|
|
11
|
+
|
|
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.
|
|
13
|
+
- This is a breaking producer-contract change: 12.x consumers with strict 32-character response schemas reject longer names. Upgrade runtime and consumers together.
|
|
14
|
+
- Keep the 12.0.1 storage schema, action key and host `user_version` unchanged. Existing names are retained. Before downgrading to 12.x, inventory managed sessions through bounded pages and explicitly shorten every name longer than 32, resolving collisions through supported rename actions. See [package downgrade](docs/recovery.md#package-downgrade).
|
|
15
|
+
|
|
3
16
|
## 12.0.1
|
|
4
17
|
|
|
5
18
|
- Refresh the cached metadata of an observed Codex session on `thread/name/updated` and reconnect, so a terminal rename or cleared name reaches `active-sessions`. Metadata-only changes preserve the session's activity time and append no state transition; active-list reads still make no native calls.
|
package/README.md
CHANGED
|
@@ -77,7 +77,9 @@ Durable state includes `action.key`, which must stay private and accompany its S
|
|
|
77
77
|
|
|
78
78
|
Text and skill inputs can attach up to 8 workspace files by path and media type, 16 MiB in all and 256 KiB per text file. The runtime verifies their content hashes again before queued delivery. Output schemas use native Codex turn parameters or Claude's structured-session flag; complete validated results and known token usage remain available on selected receipts after reconnect. Live previews stay bounded and explicitly mark truncation. See [file inputs and complete results](api/README.md#file-inputs-and-complete-results).
|
|
79
79
|
|
|
80
|
-
Use `suggest-thread-name --topic "Build usage" --state-root <directory>` for an editable label. Creation adds
|
|
80
|
+
Use `suggest-thread-name --topic "Build usage" --state-root <directory>` for an editable label of up to 64 characters. Creation adds an ordinal suffix when a name is occupied, keeping the complete label within that limit. `MAX_THREAD_NAME_LENGTH` from `jg-agent-hq/contracts` is the public limit. Actions and relationships retain immutable IDs.
|
|
81
|
+
|
|
82
|
+
Version 13 retains the 12.0.1 storage schema and action key without migration or reset, and leaves existing names intact. Upgrade runtime and consumers together: older strict response schemas reject names longer than 32 characters. Before a package downgrade, explicitly shorten every longer managed name through supported actions, resolving collisions. See [package downgrade](docs/recovery.md#package-downgrade).
|
|
81
83
|
|
|
82
84
|
Use `skills --workspace-root <directory> --state-root <directory>` to browse the native skill catalog a session started in that folder would have, with `--provider` (default `codex`), and add `--thread-id <id>` for a controlled session's own catalog. A skill input resolves its exact invocation from that catalog before it is sent. Missing native metadata is explicitly unavailable. The CLI loads all skill content and retains its permissions and invocation rules.
|
|
83
85
|
|
|
@@ -108,7 +110,7 @@ The [qualification matrix](api/README.md#qualification) records native journeys,
|
|
|
108
110
|
- `src/providers/configuration/` and `src/providers/lineage/`: bounded native choices and confirmed immutable session relationships.
|
|
109
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.
|
|
110
112
|
- `src/skills/`: bounded native catalogs and explicit input preparation.
|
|
111
|
-
- `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.
|
|
112
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.
|
|
113
115
|
- `src/pending/`: the request bookkeeping, deadlines and late-response detection shared by the store worker and native connections.
|
|
114
116
|
- `src/errors/`: the catalog of jg-agent-hq's coded errors and their safe boundary classifications.
|
package/api/README.md
CHANGED
|
@@ -19,7 +19,7 @@ Intentional Node API failures use `Exception` from `jg-exception`. The [error re
|
|
|
19
19
|
|
|
20
20
|
- Requests and responses: `HqRequestSchema`, `IHqRequest`, `IHqRequestInput`, `HqResponseSchema`, `IHqResponse`, `IHqResponseOf`, `RuntimeStatusSchema`, `IRuntimeStatus`, `IpcRequestSchema`, `IpcResponseSchema` and `IIpcResponse`; see [read commands](#read-commands).
|
|
21
21
|
- Errors: `ErrorKindSchema`, `IErrorKind`, `PUBLIC_ERROR_CODES` and `PUBLIC_ERROR_MESSAGES`; see the [public error messages](../errors/README.md#public-error-messages).
|
|
22
|
-
- Limits: `DEFAULT_PAGE_SIZE` and `MAX_PAGE_SIZE` for pages, `MAX_WORKSPACE_ROOTS` for one `threads` read, `MAX_ACTION_BYTES` for an action envelope, `MAX_WAIT_MS` for receipt waits and long-polls, and `MAX_ITEM_TEXT_LENGTH`, `MAX_ITEM_IMAGES` and `MAX_ITEM_IMAGE_BYTES` for items.
|
|
22
|
+
- Limits: `DEFAULT_PAGE_SIZE` and `MAX_PAGE_SIZE` for pages, `MAX_WORKSPACE_ROOTS` for one `threads` read, `MAX_THREAD_NAME_LENGTH` for complete managed-session names, `MAX_ACTION_BYTES` for an action envelope, `MAX_WAIT_MS` for receipt waits and long-polls, and `MAX_ITEM_TEXT_LENGTH`, `MAX_ITEM_IMAGES` and `MAX_ITEM_IMAGE_BYTES` for items.
|
|
23
23
|
- Providers and models: `ProviderIdSchema`, `IProviderId`, `ProviderCapabilitySchema`, `IProviderCapability`, `ProviderCapabilitySetSchema`, `IProviderCapabilitySet`, `ProviderCapabilitiesSchema`, `IProviderCapabilities`, `ProviderStatusSchema`, `IProviderStatus`, `ProviderModelSchema`, `IProviderModel`, `ProviderModelsRequestSchema`, `IProviderModelsRequest`, `ProviderModelPageSchema` and `IProviderModelPage`; see [providers and capabilities](#providers-and-capabilities).
|
|
24
24
|
- Sessions and history: `ThreadsPageSchema`, `IThreadsPage`, `ThreadSummarySchema`, `IThreadSummary`, `SessionTerminalSchema`, `ISessionTerminal`, `ActiveSessionsSchema`, `IActiveSessions`, `HistoryItemSchema`, `IHistoryItem`, `HistoryFileSchema`, `IHistoryFile`, `ItemDetailSchema`, `IItemDetail`, `ItemImageSchema`, `IItemImage`, `ItemImageMediaTypeSchema`, `IItemImageMediaType`, `LiveItemsSchema`, `NativeLineageSchema` and `INativeLineage`; see [session discovery](#session-discovery).
|
|
25
25
|
- Session states: `SessionStateSchema`, `ISessionState`, `SessionTransitionReasonSchema`, `ISessionTransitionReason`, `SessionTransitionSchema`, `ISessionTransition`, `SessionTransitionPageSchema`, `ObservationPaceSchema` and `IObservationPace`; see [session states](#session-states).
|
|
@@ -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.
|
|
@@ -263,7 +267,9 @@ Send `{ kind: 'action', action: { id, runtimeEpoch, command } }`. Generate one U
|
|
|
263
267
|
|
|
264
268
|
Message and queue input is a closed union: `{ kind: 'text', text }` or `{ kind: 'skill', skillId, arguments }`. Text is nonempty and at most 65,536 characters; skill arguments may be empty and cap at 16,384 characters. The envelope's UTF-8 limit still applies. A selected skill is resolved through the target thread's current native catalog before admission. Unavailable, missing or disabled selections cannot dispatch. Normal text needs no catalog read. Steering retains its `text` field and exact active-turn target.
|
|
265
269
|
|
|
266
|
-
Names use lowercase ASCII letters, digits and hyphens, start with a letter or digit, and have at most
|
|
270
|
+
Names use lowercase ASCII letters, digits and hyphens, start with a letter or digit, and have at most 64 characters, the public `MAX_THREAD_NAME_LENGTH` from `jg-agent-hq/contracts`. The same bound applies to create, adopt, rename and managed-thread responses. Names are unique without regard to case in one state directory. Creation and adoption resolve collisions atomically with ordinal suffixes such as `build-usage-2`, truncating the base to keep the complete name within 64 characters. Explicit rename rejects an occupied or pending name. Provider/native-session pairs remain unique. At most 32 native sessions are controlled concurrently; close idle sessions to release capacity. Native discovery remains independent of that limit. Confirm that other native CLI controllers are closed before adoption, resume or recovery. An unloaded native status cannot prove another CLI has stopped. The runtime provides exclusive coordination within one canonical state directory; it does not impose a global lock on independent CLIs. Recovery is permitted only after the producing runtime has stopped and its ownership evidence has been inspected.
|
|
271
|
+
|
|
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).
|
|
267
273
|
|
|
268
274
|
Codex may keep an idle native thread loaded after `thread/unsubscribe`, as when a terminal still holds it. An explicitly confirmed resume may reacquire that thread when its known managed control is inactive and managed, without settings overrides. Active native threads, uncertain managed ownership and already controlled idle sessions remain blocked. Other adoption and recovery checks are unchanged.
|
|
269
275
|
|
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,5 +1,5 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import { ACTION_PHASES, MAX_ACTION_BYTES } from '../constants.js';
|
|
2
|
+
import { ACTION_PHASES, MAX_ACTION_BYTES, MAX_THREAD_NAME_LENGTH } from '../constants.js';
|
|
3
3
|
import { ProviderIdSchema } from '../providers/index.js';
|
|
4
4
|
import { SessionSettingsSchema, TurnSettingsSchema } from '../configuration/index.js';
|
|
5
5
|
import { MessageInputSchema, NativeSkillInputSchema } from '../skills/index.js';
|
|
@@ -15,7 +15,10 @@ export const PreparedInputSchema = z.object({
|
|
|
15
15
|
});
|
|
16
16
|
// explicit local intent; native RPC methods and arbitrary configuration are never accepted
|
|
17
17
|
const ThreadIdSchema = z.uuid();
|
|
18
|
-
const NameSchema = z
|
|
18
|
+
const NameSchema = z
|
|
19
|
+
.string()
|
|
20
|
+
.max(MAX_THREAD_NAME_LENGTH)
|
|
21
|
+
.regex(/^[a-z0-9][a-z0-9-]*$/);
|
|
19
22
|
const TextSchema = z.string().min(1).max(65_536);
|
|
20
23
|
const ActiveTargetFields = { threadId: ThreadIdSchema, expectedTurnId: NativeIdSchema };
|
|
21
24
|
export const ActionCommandSchema = z.discriminatedUnion('kind', [
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export declare const DEFAULT_PAGE_SIZE = 32;
|
|
2
2
|
export declare const MAX_PAGE_SIZE = 128;
|
|
3
3
|
export declare const MAX_WORKSPACE_ROOTS = 64;
|
|
4
|
+
export declare const MAX_THREAD_NAME_LENGTH = 64;
|
|
4
5
|
export declare const MAX_ACTION_BYTES = 32768;
|
|
5
6
|
export declare const MAX_WAIT_MS = 30000;
|
|
6
7
|
export declare const ACTION_PHASES: readonly ["create", "resume", "name", "turn", "steer", "interrupt", "clean", "close", "delete", "reply"];
|
|
@@ -3,6 +3,8 @@ export const DEFAULT_PAGE_SIZE = 32;
|
|
|
3
3
|
export const MAX_PAGE_SIZE = 128;
|
|
4
4
|
// the most folders one `threads` read lists, so its cursor carries every source's continuation
|
|
5
5
|
export const MAX_WORKSPACE_ROOTS = 64;
|
|
6
|
+
// the complete editable managed-session label, including any collision suffix
|
|
7
|
+
export const MAX_THREAD_NAME_LENGTH = 64;
|
|
6
8
|
// the largest action envelope HQ admits, in UTF-8 bytes of its JSON
|
|
7
9
|
export const MAX_ACTION_BYTES = 32_768;
|
|
8
10
|
// the longest a receipt wait or a long-poll waits for a change, in milliseconds
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { ACTION_PHASES, DEFAULT_PAGE_SIZE, MAX_ITEM_IMAGE_BYTES, MAX_ITEM_IMAGES, MAX_ITEM_TEXT_LENGTH, MAX_ACTION_BYTES, MAX_PAGE_SIZE, MAX_WAIT_MS, MAX_WORKSPACE_ROOTS, PUBLIC_ERROR_CODES, PUBLIC_ERROR_MESSAGES, } from './constants.js';
|
|
1
|
+
export { ACTION_PHASES, DEFAULT_PAGE_SIZE, MAX_ITEM_IMAGE_BYTES, MAX_ITEM_IMAGES, MAX_ITEM_TEXT_LENGTH, MAX_ACTION_BYTES, MAX_PAGE_SIZE, MAX_THREAD_NAME_LENGTH, MAX_WAIT_MS, MAX_WORKSPACE_ROOTS, PUBLIC_ERROR_CODES, PUBLIC_ERROR_MESSAGES, } from './constants.js';
|
|
2
2
|
export { HqRequestSchema, SessionTerminalSchema, ThreadSummarySchema, ActiveSessionsSchema, ThreadsPageSchema, HistoryFileSchema, HistoryItemSchema, ItemImageMediaTypeSchema, ItemDetailSchema, ItemImageSchema, LiveItemsSchema, UsageWindowSchema, UsageSnapshotSchema, UsageCreditsSchema, UsageResetCreditsSchema, UsageWindowScopeSchema, RuntimeStatusSchema, HqResponseSchema, ErrorKindSchema, IpcRequestSchema, IpcResponseSchema, } from './types.js';
|
|
3
3
|
export { ProviderIdSchema, ProviderCapabilitySchema, ProviderCapabilitySetSchema, ProviderCapabilitiesSchema, ProviderStatusSchema, } from './providers/index.js';
|
|
4
4
|
export type { IProviderId, IProviderCapability, IProviderCapabilitySet, IProviderCapabilities, IProviderStatus, } from './providers/index.js';
|
package/dist/contracts/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// constants
|
|
2
|
-
export { ACTION_PHASES, DEFAULT_PAGE_SIZE, MAX_ITEM_IMAGE_BYTES, MAX_ITEM_IMAGES, MAX_ITEM_TEXT_LENGTH, MAX_ACTION_BYTES, MAX_PAGE_SIZE, MAX_WAIT_MS, MAX_WORKSPACE_ROOTS, PUBLIC_ERROR_CODES, PUBLIC_ERROR_MESSAGES, } from './constants.js';
|
|
2
|
+
export { ACTION_PHASES, DEFAULT_PAGE_SIZE, MAX_ITEM_IMAGE_BYTES, MAX_ITEM_IMAGES, MAX_ITEM_TEXT_LENGTH, MAX_ACTION_BYTES, MAX_PAGE_SIZE, MAX_THREAD_NAME_LENGTH, MAX_WAIT_MS, MAX_WORKSPACE_ROOTS, PUBLIC_ERROR_CODES, PUBLIC_ERROR_MESSAGES, } from './constants.js';
|
|
3
3
|
// wire contracts
|
|
4
4
|
export { HqRequestSchema, SessionTerminalSchema, ThreadSummarySchema, ActiveSessionsSchema, ThreadsPageSchema, HistoryFileSchema, HistoryItemSchema, ItemImageMediaTypeSchema, ItemDetailSchema, ItemImageSchema, LiveItemsSchema, UsageWindowSchema, UsageSnapshotSchema, UsageCreditsSchema, UsageResetCreditsSchema, UsageWindowScopeSchema, RuntimeStatusSchema, HqResponseSchema, ErrorKindSchema, IpcRequestSchema, IpcResponseSchema, } from './types.js';
|
|
5
5
|
// provider identity and capability discovery
|
|
@@ -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
|
}
|
|
@@ -1,12 +1,13 @@
|
|
|
1
|
+
import { MAX_THREAD_NAME_LENGTH } from '../../contracts/index.js';
|
|
1
2
|
/** Suggests a short, editable ASCII label without treating it as a session identity. */
|
|
2
3
|
export const suggestThreadName = (topic) => topic
|
|
3
4
|
.toLowerCase()
|
|
4
5
|
.replace(/[^a-z0-9]+/g, '-')
|
|
5
6
|
.replace(/^-+|-+$/g, '')
|
|
6
|
-
.slice(0,
|
|
7
|
+
.slice(0, MAX_THREAD_NAME_LENGTH)
|
|
7
8
|
.replace(/-+$/g, '') || 'session';
|
|
8
9
|
/** Adds an ordinal while keeping the complete label within the native-facing limit. */
|
|
9
10
|
export const suffixThreadName = (name, ordinal) => {
|
|
10
11
|
const suffix = `-${ordinal}`;
|
|
11
|
-
return `${name.slice(0,
|
|
12
|
+
return `${name.slice(0, MAX_THREAD_NAME_LENGTH - suffix.length).replace(/-+$/g, '')}${suffix}`;
|
|
12
13
|
};
|
|
@@ -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
|
@@ -24,6 +24,16 @@ Recover repositories and native files separately. Source paths are retained as e
|
|
|
24
24
|
|
|
25
25
|
Roll back by restoring an earlier snapshot into a new recovery workspace; never overwrite the current state root. A snapshot from another schema is refused with an error naming the package version that wrote it, so restore it with that version. Rollback accepts losing every change made after that snapshot, including host changes and later runtime receipts. Reconcile native ownership before enabling work.
|
|
26
26
|
|
|
27
|
+
## Package downgrade
|
|
28
|
+
|
|
29
|
+
Version 13.0.0 uses the same storage schema as 12.0.1, including the existing action key and host `user_version`; startup accepts that schema without migration or reset. The writing package version is diagnostic. Snapshot capture and restore retain longer managed names under the same schema.
|
|
30
|
+
|
|
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
|
+
|
|
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
|
+
|
|
27
37
|
## Off-machine durability
|
|
28
38
|
|
|
29
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