jg-agent-hq 10.4.0 → 10.4.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 CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 10.4.1
4
+
5
+ - Keep the Codex provider working when a turn's end arrives twice: once read back from Codex after a lost or skipped message, and once as the turn's own `turn/completed`. In either order, the first recorded stands and the other only fills in a result the first lacked. The two used to differ when the notification carried the turn's result, which failed every managed Codex session.
6
+ - Keep HQ's own Codex turn going when its `turn/started` fails validation while the input that started it is still in flight. The session is watched instead of marked uncertain, and the turn keeps its result.
7
+ - Keep a Codex session's next turn that HQ didn't prepare, such as a compaction, working after a turn's end failed validation. An earlier turn's end no longer drops the result capture of the turn HQ prepared next.
8
+ - Read a Codex session whose status is newer than HQ knows as `nativeState: 'unknown'` in lists, reads, resumes and rejoins, instead of failing them. `IProviderThread`'s `nativeState` gains `unknown`.
9
+ - Keep a Claude session's process when Claude starts a turn of its own, or a call or background command begins, while HQ parks the session.
10
+ - Leave a state-root lock in place when it changes or can't be removed while startup reclaims it, instead of failing startup with an uncoded error.
11
+
3
12
  ## 10.4.0
4
13
 
5
14
  - Accept Claude permission requests that carry fields HQ doesn't list. Claude adds fields between releases, such as `decision_reason_code` and `tool_kind`, and HQ refused every such request before the operator saw it. Known fields keep their validation, the rest are dropped, and the reply still holds only the displayed input.
package/api/README.md CHANGED
@@ -78,7 +78,7 @@ One Codex connection carries every managed Codex session, so a message HQ can't
78
78
  - an idle session whose latest turn is the one HQ recorded, or that has no turns, is left alone;
79
79
  - anything else, such as a newer turn, a failed read or a lost approval resolution, marks the session uncertain: its submitted deliveries become uncertain and its pending approvals expire.
80
80
 
81
- A session with an action in flight when a message is skipped isn't read, since its newest turn may not be recorded yet; it is watched instead. The original notification arriving late leaves the session as reconciled. A response to HQ's own request that fails validation, a message that is neither a request, a notification nor a response, and other invalid framing still fail the connection.
81
+ A session with an action in flight when a message is skipped, or when its turn start is lost, isn't read, since its newest turn may not be recorded yet; it is watched instead. When a turn's end is both read back and received as its own notification, in either order, the first recorded stands, and the other only fills in a result the first lacked. A session status newer than HQ knows reads as `nativeState: 'unknown'` in lists and reads. A response to HQ's own request that fails validation, a message that is neither a request, a notification nor a response, and other invalid framing still fail the connection.
82
82
 
83
83
  `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`.
84
84
 
@@ -508,7 +508,8 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
508
508
  if (!record)
509
509
  return;
510
510
  // an action in flight may have started a turn the record doesn't hold yet
511
- if (request.lost === 'unknown' && record.hasPendingAction) {
511
+ if ((request.lost === 'unknown' || request.lost === 'turn-started') &&
512
+ record.hasPendingAction) {
512
513
  watched.add(key(provider, nativeId));
513
514
  return;
514
515
  }
@@ -366,11 +366,17 @@ export const removeStaleHqLock = async (root) => {
366
366
  }
367
367
  if (stored.kind !== 'owner' || getOwnerLiveness(stored.owner.pid) !== 'dead')
368
368
  return false;
369
- const current = await readStoredLock(path);
370
- if (current.kind !== 'owner' || current.content !== stored.content)
369
+ try {
370
+ const current = await readStoredLock(path);
371
+ if (current.kind !== 'owner' || current.content !== stored.content)
372
+ return false;
373
+ await rm(path);
374
+ return true;
375
+ }
376
+ catch {
377
+ // a lock that changed into something unreadable, or can't be removed, keeps its inspection
371
378
  return false;
372
- await rm(path);
373
- return true;
379
+ }
374
380
  };
375
381
  /**
376
382
  * Reports the HQ lock for status output without acquiring or changing it.
@@ -62,24 +62,26 @@ export const createClaudeControl = (additionalDirectories = []) => {
62
62
  session.idleStop = idleStop;
63
63
  void delay(IDLE_STOP_SECONDS, { signal: idleStop.signal }).then(() => park(session), () => undefined);
64
64
  };
65
+ // whether a call, a request or a background command still uses an idle session's process
66
+ const isHeld = (session) => activeCalls.has(session.id) ||
67
+ session.requests.size > 0 ||
68
+ session.backgroundTaskCount > 0 ||
69
+ hasExtensionRequest(session.id);
65
70
  /**
66
71
  * Reads an idle session's native settings once, then closes its process. The session stays idle
67
72
  * and records nothing; a call that arrives first keeps the process, and a background command
68
- * still running holds the session for another idle period, since closing would end it.
73
+ * still running holds the session for another idle period, since closing would end it. Both are
74
+ * checked again once the read answers, along with a turn that started meanwhile.
69
75
  */
70
76
  const park = async (session) => {
71
77
  const connection = session.connection;
72
78
  if (isClosing ||
73
79
  session.isClosing ||
74
- session.input ||
75
- session.nativeTurn ||
80
+ isBusy(session) ||
76
81
  session.transition ||
77
82
  !connection?.isAvailable)
78
83
  return;
79
- if (activeCalls.has(session.id) ||
80
- session.requests.size ||
81
- session.backgroundTaskCount ||
82
- hasExtensionRequest(session.id)) {
84
+ if (isHeld(session)) {
83
85
  scheduleIdleStop(session);
84
86
  return;
85
87
  }
@@ -92,7 +94,10 @@ export const createClaudeControl = (additionalDirectories = []) => {
92
94
  scheduleIdleStop(session);
93
95
  return;
94
96
  }
95
- if (isClosing || session.isClosing || activeCalls.has(session.id)) {
97
+ // a turn that started meanwhile schedules the next idle period once it ends
98
+ if (isClosing || session.isClosing || isBusy(session))
99
+ return;
100
+ if (isHeld(session)) {
96
101
  scheduleIdleStop(session);
97
102
  return;
98
103
  }
@@ -4,3 +4,4 @@ export declare const TURN_TIMES_PAGE_SIZE = 128;
4
4
  export declare const MAX_TURN_TIME_PAGES = 8;
5
5
  export declare const RUNNING_TURNS_CAPACITY = 1024;
6
6
  export declare const LOST_NOTIFICATIONS: Map<string, "unknown" | "turn-started" | "turn-completed" | "approval-resolved">;
7
+ export declare const KNOWN_NATIVE_STATES: readonly ["notLoaded", "idle", "systemError", "active"];
@@ -12,3 +12,5 @@ export const LOST_NOTIFICATIONS = new Map([
12
12
  ['turn/completed', 'turn-completed'],
13
13
  ['serverRequest/resolved', 'approval-resolved'],
14
14
  ]);
15
+ // the session statuses this adapter knows; a newer one reads as an unknown native state
16
+ export const KNOWN_NATIVE_STATES = ['notLoaded', 'idle', 'systemError', 'active'];
@@ -6,7 +6,7 @@ import { NativeIdSchema } from '../../contracts/identities/index.js';
6
6
  import { LOST_NOTIFICATIONS, RUNNING_TURNS_CAPACITY } from './constants.js';
7
7
  import { NativeItemSchema, NativeThreadSchema, NativeThreadStatusSchema, NativeTurnSchema, } from './types.js';
8
8
  import { parseNative } from './validations.js';
9
- import { toHistoryItem, toNativeLineage, toSessionState, toTurnSummary } from './transformers.js';
9
+ import { toHistoryItem, toNativeLineage, toNativeState, toSessionState, toTurnSummary, } from './transformers.js';
10
10
  import { buildCodexReply, parseCodexPrompt, toApprovalPresentation } from './approvals/index.js';
11
11
  const TargetSchema = z.object({ threadId: NativeIdSchema, turnId: NativeIdSchema });
12
12
  const DeltaSchema = TargetSchema.extend({ itemId: NativeIdSchema, delta: z.string() });
@@ -18,7 +18,7 @@ export const toProviderThread = (thread) => ({
18
18
  nativeId: thread.id,
19
19
  nativeLineage: toNativeLineage(thread),
20
20
  workspaceRoot: thread.cwd,
21
- nativeState: thread.status.type,
21
+ nativeState: toNativeState(thread.status),
22
22
  });
23
23
  /**
24
24
  * Converts Codex protocol events to provider-bound evidence without owning action ledger state.
@@ -28,6 +28,25 @@ export const createCodexEvents = (native, events, observeSession, observeLoaded)
28
28
  const turns = new Map();
29
29
  // each thread's running turn, which times its live items
30
30
  const runningTurns = new Map();
31
+ /**
32
+ * Keeps HQ's result capture in step with a turn whose start or end failed validation: a lost
33
+ * start still binds the capture prepared for HQ's input, and a lost end drops its turn's capture,
34
+ * which would otherwise refuse the session's next turn that HQ didn't prepare, such as a
35
+ * compaction.
36
+ */
37
+ const settleLostCapture = (method, params) => {
38
+ const lifecycle = z
39
+ .object({ threadId: NativeIdSchema, turn: z.object({ id: NativeIdSchema }) })
40
+ .safeParse(params);
41
+ if (!lifecycle.success)
42
+ return;
43
+ const { threadId, turn } = lifecycle.data;
44
+ const captured = turns.get(threadId);
45
+ if (method === 'turn/started' && captured?.turnId === null)
46
+ captured.turnId = turn.id;
47
+ if (method === 'turn/completed' && captured?.turnId === turn.id)
48
+ turns.delete(threadId);
49
+ };
31
50
  /**
32
51
  * Turns one daemon notification into provider evidence.
33
52
  * @throws
@@ -70,7 +89,9 @@ export const createCodexEvents = (native, events, observeSession, observeLoaded)
70
89
  result.text = null;
71
90
  result.structuredOutput = null;
72
91
  }
73
- turns.delete(threadId);
92
+ // a capture prepared for the session's next turn outlives an earlier turn's end
93
+ if (captured)
94
+ turns.delete(threadId);
74
95
  events.observe({
75
96
  kind: 'turn-completed',
76
97
  provider: 'codex',
@@ -166,6 +187,7 @@ export const createCodexEvents = (native, events, observeSession, observeLoaded)
166
187
  // a notification that fails validation never fails the connection every session shares
167
188
  const thread = z.object({ threadId: NativeIdSchema }).safeParse(params);
168
189
  const threadId = thread.success ? thread.data.threadId : undefined;
190
+ settleLostCapture(method, params);
169
191
  const lost = LOST_NOTIFICATIONS.get(method);
170
192
  // a lost turn or approval notification is made up for by reading the session
171
193
  if (lost)
@@ -1,5 +1,6 @@
1
1
  import { type IHistoryItem, type IItemDetail, type IThreadSummary, type ITurnSummary, type IUsageSnapshot, type INativeLineage, type ISessionState } from '../../contracts/index.js';
2
2
  import type { INativeItem, INativeThread, INativeThreadStatus, INativeTurn, INativeUsage } from './types.js';
3
+ import { KNOWN_NATIVE_STATES } from './constants.js';
3
4
  /** Preserves exact native tree identities independently of managed-agent relationships. */
4
5
  export declare const toNativeLineage: (thread: INativeThread) => INativeLineage;
5
6
  /**
@@ -7,6 +8,8 @@ export declare const toNativeLineage: (thread: INativeThread) => INativeLineage;
7
8
  * operator, and a status newer than this adapter knows is unknown.
8
9
  */
9
10
  export declare const toSessionState: (status: INativeThreadStatus) => ISessionState;
11
+ /** @returns The native state a session status names, or `unknown` for one newer than this adapter knows. */
12
+ export declare const toNativeState: (status: INativeThreadStatus) => (typeof KNOWN_NATIVE_STATES)[number] | "unknown";
10
13
  /**
11
14
  * Converts native seconds to the public millisecond-based metadata contract.
12
15
  * @throws
@@ -2,6 +2,7 @@ import { z } from 'zod';
2
2
  import { UsageSnapshotSchema, UsageCreditsSchema, ThreadSummarySchema, TurnSummarySchema, HistoryItemSchema, MAX_ITEM_IMAGES, MAX_ITEM_TEXT_LENGTH, } from '../../contracts/index.js';
3
3
  import { countLines, describeBase64Image, keepTextEnd, toWholeFileDiff, } from '../../sessions/index.js';
4
4
  import { nativeProvenance } from '../../sessions/evidence/index.js';
5
+ import { KNOWN_NATIVE_STATES } from './constants.js';
5
6
  import { parseNative } from './validations.js';
6
7
  /** Preserves exact native tree identities independently of managed-agent relationships. */
7
8
  export const toNativeLineage = (thread) => ({
@@ -24,6 +25,8 @@ export const toSessionState = (status) => status.type === 'active'
24
25
  : status.type === 'systemError'
25
26
  ? 'failed'
26
27
  : 'unknown';
28
+ /** @returns The native state a session status names, or `unknown` for one newer than this adapter knows. */
29
+ export const toNativeState = (status) => KNOWN_NATIVE_STATES.find((state) => state === status.type) ?? 'unknown';
27
30
  /**
28
31
  * Converts native seconds to the public millisecond-based metadata contract.
29
32
  * @throws
@@ -37,7 +40,7 @@ export const toThreadSummary = (thread) => parseNative(ThreadSummarySchema, {
37
40
  name: thread.name ?? null,
38
41
  createdAt: thread.createdAt * 1000,
39
42
  updatedAt: thread.updatedAt * 1000,
40
- nativeState: thread.status.type,
43
+ nativeState: toNativeState(thread.status),
41
44
  state: toSessionState(thread.status),
42
45
  ownership: 'external',
43
46
  managedId: null,
@@ -4,6 +4,11 @@ import type { IProviderInputFile } from '../inputs/index.js';
4
4
  import type { IAgentProviderOutcome } from '../index.js';
5
5
  import type { IProviderSkills } from '../types.js';
6
6
  import type { IProviderMcpServerPage, IProviderMcpTools, IProviderMcpResources } from '../extensions/index.js';
7
+ export declare const NativeThreadStatusSchema: z.ZodObject<{
8
+ type: z.ZodString;
9
+ activeFlags: z.ZodOptional<z.ZodArray<z.ZodString>>;
10
+ }, z.core.$strip>;
11
+ export type INativeThreadStatus = z.infer<typeof NativeThreadStatusSchema>;
7
12
  export declare const NativeThreadSchema: z.ZodObject<{
8
13
  id: z.ZodString;
9
14
  sessionId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
@@ -15,20 +20,10 @@ export declare const NativeThreadSchema: z.ZodObject<{
15
20
  createdAt: z.ZodNumber;
16
21
  updatedAt: z.ZodNumber;
17
22
  status: z.ZodObject<{
18
- type: z.ZodEnum<{
19
- idle: "idle";
20
- notLoaded: "notLoaded";
21
- systemError: "systemError";
22
- active: "active";
23
- }>;
23
+ type: z.ZodString;
24
24
  activeFlags: z.ZodOptional<z.ZodArray<z.ZodString>>;
25
25
  }, z.core.$strip>;
26
26
  }, z.core.$strip>;
27
- export declare const NativeThreadStatusSchema: z.ZodObject<{
28
- type: z.ZodString;
29
- activeFlags: z.ZodOptional<z.ZodArray<z.ZodString>>;
30
- }, z.core.$strip>;
31
- export type INativeThreadStatus = z.infer<typeof NativeThreadStatusSchema>;
32
27
  export declare const NativeTurnSchema: z.ZodObject<{
33
28
  id: z.ZodString;
34
29
  status: z.ZodEnum<{
@@ -59,12 +54,7 @@ export declare const NativeThreadPageSchema: z.ZodObject<{
59
54
  createdAt: z.ZodNumber;
60
55
  updatedAt: z.ZodNumber;
61
56
  status: z.ZodObject<{
62
- type: z.ZodEnum<{
63
- idle: "idle";
64
- notLoaded: "notLoaded";
65
- systemError: "systemError";
66
- active: "active";
67
- }>;
57
+ type: z.ZodString;
68
58
  activeFlags: z.ZodOptional<z.ZodArray<z.ZodString>>;
69
59
  }, z.core.$strip>;
70
60
  }, z.core.$strip>>;
@@ -1,5 +1,10 @@
1
1
  import { z } from 'zod';
2
2
  import { MAX_PAGE_SIZE, UsageCreditsSchema, UsageResetCreditsSchema, } from '../../contracts/index.js';
3
+ // a session's status, which may name one newer than this adapter knows
4
+ export const NativeThreadStatusSchema = z.object({
5
+ type: z.string().min(1).max(256),
6
+ activeFlags: z.array(z.string()).optional(),
7
+ });
3
8
  // additive native responses are narrowed to fields this adapter actually uses
4
9
  export const NativeThreadSchema = z.object({
5
10
  id: z.string().min(1).max(4096),
@@ -12,15 +17,7 @@ export const NativeThreadSchema = z.object({
12
17
  ephemeral: z.boolean().optional(),
13
18
  createdAt: z.number().int().safe(),
14
19
  updatedAt: z.number().int().safe(),
15
- status: z.object({
16
- type: z.enum(['notLoaded', 'idle', 'systemError', 'active']),
17
- activeFlags: z.array(z.string()).optional(),
18
- }),
19
- });
20
- // a status the daemon broadcasts, which may name one newer than this adapter knows
21
- export const NativeThreadStatusSchema = z.object({
22
- type: z.string().min(1).max(256),
23
- activeFlags: z.array(z.string()).optional(),
20
+ status: NativeThreadStatusSchema,
24
21
  });
25
22
  export const NativeTurnSchema = z.object({
26
23
  id: z.string().min(1).max(4096),
@@ -13,6 +13,7 @@ export declare const ProviderThreadSchema: z.ZodObject<{
13
13
  forkedFromId: z.ZodNullable<z.ZodString>;
14
14
  }, z.core.$strip>>;
15
15
  nativeState: z.ZodEnum<{
16
+ unknown: "unknown";
16
17
  idle: "idle";
17
18
  notLoaded: "notLoaded";
18
19
  systemError: "systemError";
@@ -79,6 +80,7 @@ export declare const ProviderReattachmentSchema: z.ZodObject<{
79
80
  forkedFromId: z.ZodNullable<z.ZodString>;
80
81
  }, z.core.$strip>>;
81
82
  nativeState: z.ZodEnum<{
83
+ unknown: "unknown";
82
84
  idle: "idle";
83
85
  notLoaded: "notLoaded";
84
86
  systemError: "systemError";
@@ -6,7 +6,9 @@ export const ProviderThreadSchema = ThreadSummarySchema.pick({
6
6
  nativeId: true,
7
7
  nativeLineage: true,
8
8
  workspaceRoot: true,
9
- }).extend({ nativeState: z.enum(['notLoaded', 'idle', 'systemError', 'active']) });
9
+ }).extend({
10
+ nativeState: z.enum(['notLoaded', 'idle', 'systemError', 'active', 'unknown']),
11
+ });
10
12
  export const ProviderInspectionSchema = z.object({
11
13
  thread: ThreadSummarySchema,
12
14
  canAdopt: z.boolean(),
@@ -849,8 +849,17 @@ export class ControlModel {
849
849
  .prepare('SELECT digest FROM hq_event WHERE runtime_epoch = ? AND event_key = ?')
850
850
  .get(this.__epoch, key);
851
851
  if (prior) {
852
- if (prior.digest !== digest)
852
+ /*
853
+ * a turn's end can arrive twice, once read back from its saved history after a lost
854
+ * notification and once as the notification itself: the first recorded stands, and the
855
+ * other only fills in a result the first lacked
856
+ */
857
+ if (prior.digest !== digest && observation.kind !== 'turn-completed')
853
858
  this.__conflict();
859
+ if (prior.digest !== digest && observation.kind === 'turn-completed' && observation.result)
860
+ this.__database
861
+ .prepare("UPDATE hq_action SET result = ?, updated_at = ? WHERE thread_id = ? AND native_turn_id = ? AND kind IN ('message', 'queue', 'thread-compact') AND result IS NULL")
862
+ .run(JSON.stringify(observation.result), now, thread.id, observation.nativeTurnId);
854
863
  return { thread: toManagedThread(thread), canDispatchQueued: false };
855
864
  }
856
865
  const turnId = 'nativeTurnId' in observation ? observation.nativeTurnId : null;
@@ -197,6 +197,7 @@ export declare const NativeOutcomeSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
197
197
  kind: z.ZodLiteral<"created">;
198
198
  }, z.core.$strict>, z.ZodObject<{
199
199
  nativeState: z.ZodEnum<{
200
+ unknown: "unknown";
200
201
  idle: "idle";
201
202
  notLoaded: "notLoaded";
202
203
  systemError: "systemError";
@@ -60,7 +60,7 @@ export const NativeOutcomeSchema = z.discriminatedUnion('kind', [
60
60
  z.strictObject({
61
61
  kind: z.literal('resumed'),
62
62
  ...OutcomeFields,
63
- nativeState: z.enum(['notLoaded', 'idle', 'systemError', 'active']),
63
+ nativeState: z.enum(['notLoaded', 'idle', 'systemError', 'active', 'unknown']),
64
64
  nativeLineage: NativeLineageSchema.nullable(),
65
65
  }),
66
66
  z.strictObject({ kind: z.literal('closed'), ...OutcomeFields }),
@@ -1163,6 +1163,7 @@ export declare const StoreCommandSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
1163
1163
  kind: z.ZodLiteral<"created">;
1164
1164
  }, z.core.$strict>, z.ZodObject<{
1165
1165
  nativeState: z.ZodEnum<{
1166
+ unknown: "unknown";
1166
1167
  idle: "idle";
1167
1168
  notLoaded: "notLoaded";
1168
1169
  systemError: "systemError";
@@ -2541,6 +2542,7 @@ export declare const StoreRequestSchema: z.ZodObject<{
2541
2542
  kind: z.ZodLiteral<"created">;
2542
2543
  }, z.core.$strict>, z.ZodObject<{
2543
2544
  nativeState: z.ZodEnum<{
2545
+ unknown: "unknown";
2544
2546
  idle: "idle";
2545
2547
  notLoaded: "notLoaded";
2546
2548
  systemError: "systemError";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jg-agent-hq",
3
- "version": "10.4.0",
3
+ "version": "10.4.1",
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",