jg-agent-hq 13.5.10 → 13.6.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.
Files changed (36) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/api/README.md +8 -2
  3. package/dist/actions/events/events.js +4 -0
  4. package/dist/actions/reattach/reattach.js +4 -0
  5. package/dist/contracts/actions/types.d.ts +20 -0
  6. package/dist/contracts/actions/types.js +2 -0
  7. package/dist/contracts/browser/types.d.ts +11 -0
  8. package/dist/contracts/index.d.ts +2 -2
  9. package/dist/contracts/index.js +1 -1
  10. package/dist/contracts/results/index.d.ts +2 -2
  11. package/dist/contracts/results/index.js +1 -1
  12. package/dist/contracts/results/types.d.ts +18 -0
  13. package/dist/contracts/results/types.js +11 -0
  14. package/dist/contracts/types.d.ts +56 -0
  15. package/dist/index.d.ts +1 -1
  16. package/dist/providers/claude/control/diagnostics.js +2 -2
  17. package/dist/providers/codex/adapter.js +6 -1
  18. package/dist/providers/codex/events.js +40 -2
  19. package/dist/providers/codex/transformers.js +2 -0
  20. package/dist/providers/codex/turn-error/index.d.ts +3 -0
  21. package/dist/providers/codex/turn-error/index.js +4 -0
  22. package/dist/providers/codex/turn-error/transformers.d.ts +7 -0
  23. package/dist/providers/codex/turn-error/transformers.js +74 -0
  24. package/dist/providers/codex/turn-error/types.d.ts +7 -0
  25. package/dist/providers/codex/turn-error/types.js +9 -0
  26. package/dist/providers/codex/types.d.ts +18 -0
  27. package/dist/providers/codex/types.js +4 -1
  28. package/dist/providers/results/results.d.ts +2 -2
  29. package/dist/providers/results/results.js +2 -1
  30. package/dist/providers/types.d.ts +8 -0
  31. package/dist/providers/types.js +2 -1
  32. package/dist/store/control/admission/admission.model.d.ts +6 -0
  33. package/dist/store/control/admission/admission.model.js +42 -1
  34. package/dist/store/control/observations/observations.model.d.ts +1 -1
  35. package/dist/store/control/observations/observations.model.js +17 -1
  36. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 13.6.0
4
+
5
+ - Retain bounded, redacted Codex turn diagnostics on selected receipts, including late completion errors and native reattachment reads.
6
+ - Add conditional continuation admission that atomically fences one host-requested recovery of the latest confirmed transient failure. Newer or queued input, pending approvals, native retries and manual-review failures prevent recovery; continuations cannot chain.
7
+
8
+ ## 13.5.11
9
+
10
+ - Reuse shared SHA-256 hashing for redacted Claude result subtype fingerprints.
11
+
3
12
  ## 13.5.10
4
13
 
5
14
  - Keep Claude control when a valid result arrives without a user-message UUID and without an active turn. Empty cycles produce no live turn or completion notice, and any input still waiting for replay completes under its own identity.
package/api/README.md CHANGED
@@ -14,7 +14,7 @@ Intentional Node API failures use `Exception` from `jg-exception`. The [error re
14
14
  - Errors: `getErrorKind`, which reads an error's safe classification.
15
15
  - Host storage: `openHostDatabase`, `IStorageDescriptor` and `IStorageMaintenanceOperation`; see [shared storage](#shared-storage).
16
16
  - Snapshots: `restoreHqSnapshot`, `packHqSnapshot`, `unpackHqSnapshot`, `IHqSnapshotInspection`, `IHqRestoreOptions` and `IHqRestoreResult`; see [snapshot and restore](#snapshot-and-restore).
17
- - Contract types also exported by `jg-agent-hq/contracts`: `IProviderId`, `IProviderCapability`, `IProviderCapabilitySet`, `IProviderCapabilities`, `IProviderStatus`, `IProviderModel`, `IProviderModelPage`, `IProviderModelsRequest`, `ITurnSettings`, `ISessionSettings`, `IConfigurationRequest`, `IConfigurationChoice`, `ISessionConfiguration`, `INativeLineage`, `IInputFile`, `IBoundInputFile`, `IOutputSchema`, `ITurnUsage`, `ITurnResult` and `IPreparedInput`.
17
+ - Contract types also exported by `jg-agent-hq/contracts`: `IProviderId`, `IProviderCapability`, `IProviderCapabilitySet`, `IProviderCapabilities`, `IProviderStatus`, `IProviderModel`, `IProviderModelPage`, `IProviderModelsRequest`, `ITurnSettings`, `ISessionSettings`, `IConfigurationRequest`, `IConfigurationChoice`, `ISessionConfiguration`, `INativeLineage`, `IInputFile`, `IBoundInputFile`, `IOutputSchema`, `ITurnUsage`, `ITurnResult`, `ITurnError` and `IPreparedInput`.
18
18
 
19
19
  `jg-agent-hq/contracts` holds browser-safe Zod schemas, the types inferred from them and the limits they enforce. Importing it loads no host runtime.
20
20
 
@@ -29,7 +29,7 @@ Intentional Node API failures use `Exception` from `jg-exception`. The [error re
29
29
  - Actions and replies: `ActionCommandSchema`, `IActionCommand`, `ActionEnvelopeSchema`, `IActionEnvelope`, `ActionReceiptSchema`, `IActionReceipt`, `ActionSummarySchema`, `IActionSummary`, `ActionWaitSchema`, `IActionWait`, `ACTION_PHASES`, `IActionPhase`, `ManagedThreadSchema`, `IManagedThread`, `PreparedInputSchema`, `IPreparedInput`, `NativeApprovalSchema`, `INativeApproval`, `NativeApprovalSummarySchema`, `INativeApprovalSummary`, `ApprovalPresentationSchema`, `IApprovalPresentation`, `NativeElicitationSchema` and `INativeElicitation`; see [thread control and live input](#thread-control-and-live-input).
30
30
  - Skills: `SkillIdSchema`, `SkillSchema`, `ISkill`, `SkillPageSchema`, `ISkillPage`, `NativeSkillInputSchema`, `INativeSkillInput`, `MessageInputSchema` and `IMessageInput`; see [native skill catalog](#native-skill-catalog).
31
31
  - Configuration: `TurnSettingsSchema`, `ITurnSettings`, `SessionSettingsSchema`, `ISessionSettings`, `ConfigurationRequestSchema`, `IConfigurationRequest`, `ConfigurationChoiceSchema`, `IConfigurationChoice`, `SessionConfigurationSchema` and `ISessionConfiguration`; see [native configuration](#native-configuration).
32
- - Files and results: `InputFileSchema`, `IInputFile`, `BoundInputFileSchema`, `IBoundInputFile`, `MAX_INPUT_FILES`, `MAX_INPUT_FILE_BYTES`, `MAX_TEXT_FILE_BYTES`, `OutputSchemaSchema`, `IOutputSchema`, `TurnUsageSchema`, `ITurnUsage`, `TurnResultSchema`, `ITurnResult` and `MAX_RESULT_BYTES`; see [file inputs and complete results](#file-inputs-and-complete-results).
32
+ - Files and results: `InputFileSchema`, `IInputFile`, `BoundInputFileSchema`, `IBoundInputFile`, `MAX_INPUT_FILES`, `MAX_INPUT_FILE_BYTES`, `MAX_TEXT_FILE_BYTES`, `OutputSchemaSchema`, `IOutputSchema`, `TurnUsageSchema`, `ITurnUsage`, `TurnResultSchema`, `ITurnResult`, `TurnErrorSchema` and `MAX_RESULT_BYTES`; see [file inputs and complete results](#file-inputs-and-complete-results).
33
33
  - Usage: `UsageSnapshotSchema`, `IUsageSnapshot`, `UsageWindowSchema`, `UsageWindowScopeSchema`, `IUsageWindowScope`, `UsageCreditsSchema`, `IUsageCredits`, `UsageResetCreditsSchema` and `IUsageResetCredits`; see [subscription observations](#subscription-observations).
34
34
  - Browser hosts: `BrowserCommandSchema`, `BrowserActionSchema`, `IBrowserAction`, `BrowserReceiptSchema`, `IBrowserReceipt` and `BrowserThreadDetailSchema`; see [browser host integration](#browser-host-integration).
35
35
  - Machine locks: `LockStateSchema`, `ILockState`, `LocksSchema` and `ILocks`; see [machine locks](#machine-locks).
@@ -224,6 +224,12 @@ Managed threads expose `nativeLineage: { sessionId, parentThreadId, forkedFromId
224
224
 
225
225
  ## File inputs and complete results
226
226
 
227
+ Codex failures can additionally carry `result.error`, validated by `TurnErrorSchema` (`ITurnError`): nullable native `code`, `message` (4,096 characters), nullable `details` (8,192 characters), nullable `httpStatusCode`, `retryable` and `willRetry`. Known credentials, authorization values, URL credentials and sensitive query parameters are redacted before persistence. Errors received just after a failed completion enrich its receipt without replacing the earlier result body. Native history reads also retain a failed turn's diagnostic during reattachment or resynchronization. Missing or malformed diagnostics leave the terminal state intact.
228
+
229
+ `retryable` is conservative evidence for a host decision, not an automatic package retry. It requires a recognized transient native code, no native retry in progress, and no prompt/policy, credential, permission, quota, rate-limit or context rejection. HTTP failures are eligible only with a null status, 408 or 5xx; malformed and unknown classifications are ineligible. A host must also exclude newer input, pending approvals and continuing background work.
230
+
231
+ A trusted host may submit `{ kind: 'message', threadId, input: { kind: 'text', text: 'continue' }, continueAfterActionId }`. Admission atomically requires that exact acknowledged, failed action to be the controlled Codex session's latest failed turn in this runtime, with eligible diagnostics and no pending or queued input or approval. Files and setting overrides are forbidden. It records `result.recoveryActionId` on the source and `relatedActionId` on the continuation in the existing ledger transaction before dispatch. Competing attempts, a changed turn, an earlier attempted recovery and recovery of a continuation are refused with the existing state-conflict classification. The claim survives restart; no uncertain send is replayed. Ordinary messages remain unchanged.
232
+
227
233
  Text and native skill inputs accept optional `files: [{ path, mediaType }]`. Paths may be absolute or relative to the managed workspace and must resolve inside an operator-authorized root. The runtime opens a checked regular-file descriptor, validates UTF-8 or the declared format signature, and binds the canonical path, byte count and SHA-256 before admission. It rereads and verifies that binding immediately before native delivery. Missing, changed or escaping queued files fail without sending input. Symlinks cannot redirect delivery outside the trusted roots. URLs are never fetched.
228
234
 
229
235
  The fixed limits are 8 references, 16,777,216 aggregate file bytes and 262,144 bytes per UTF-8 text file. Empty files, NUL-containing or invalid UTF-8 text, wrong signatures, unsupported media and oversized input are rejected. The 32,768-byte action envelope contains references, never base64. File bytes are encoded only inside the native 32 MiB frame; the file limits leave room even for worst-case JSON escaping.
@@ -6,6 +6,7 @@ import { z } from 'zod';
6
6
  import { MAX_ITEM_TEXT_LENGTH, MAX_PAGE_SIZE, } from '../../contracts/index.js';
7
7
  import { HQ_ERRORS, getErrorKind } from '../../errors/index.js';
8
8
  import { capabilityUnavailable } from '../../providers/registry/index.js';
9
+ import { toTurnResult } from '../../providers/results/index.js';
9
10
  import { correlateEvidenceOrigins } from '../../sessions/index.js';
10
11
  import { RESYNC_REREAD_DELAY_SECONDS, Resyncs, decideResync, } from '../resync/index.js';
11
12
  import { agentUnavailable, conflict, keepsSessions } from '../utilities.js';
@@ -384,6 +385,9 @@ export const createEvents = (context, dispatcher, reconnect) => {
384
385
  nativeThreadId: nativeId,
385
386
  nativeTurnId: decision.nativeTurnId,
386
387
  state: decision.state,
388
+ ...(decision.state === 'failed' && latest?.error
389
+ ? { result: toTurnResult('failed', null, undefined, undefined, null, latest.error) }
390
+ : {}),
387
391
  });
388
392
  else if (decision.kind === 'gap')
389
393
  live.markGap(key(provider, nativeId));
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { capabilityUnavailable } from '../../providers/registry/index.js';
3
+ import { toTurnResult } from '../../providers/results/index.js';
3
4
  import { agentUnavailable, assertKnownTurn } from '../utilities.js';
4
5
  /**
5
6
  * Rejoins the sessions the previous runtime left running in a native process that outlives it.
@@ -98,6 +99,9 @@ export const createReattach = (context, dispatcher, events) => {
98
99
  nativeThreadId: nativeId,
99
100
  nativeTurnId: turnId,
100
101
  state: turnState,
102
+ ...(turnState === 'failed' && latest.error
103
+ ? { result: toTurnResult('failed', null, undefined, undefined, null, latest.error) }
104
+ : {}),
101
105
  }));
102
106
  }
103
107
  if (bound.canDispatchQueued)
@@ -178,6 +178,7 @@ export declare const ActionCommandSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
178
178
  fast: z.ZodOptional<z.ZodBoolean>;
179
179
  outputSchema: z.ZodOptional<z.ZodPreprocess<z.ZodRecord<z.ZodString, z.ZodJSONSchema>, unknown>>;
180
180
  }, z.core.$strict>>;
181
+ continueAfterActionId: z.ZodOptional<z.ZodUUID>;
181
182
  }, z.core.$strict>, z.ZodObject<{
182
183
  text: z.ZodString;
183
184
  files: z.ZodOptional<z.ZodArray<z.ZodObject<{
@@ -438,6 +439,7 @@ export declare const ActionEnvelopeSchema: z.ZodObject<{
438
439
  fast: z.ZodOptional<z.ZodBoolean>;
439
440
  outputSchema: z.ZodOptional<z.ZodPreprocess<z.ZodRecord<z.ZodString, z.ZodJSONSchema>, unknown>>;
440
441
  }, z.core.$strict>>;
442
+ continueAfterActionId: z.ZodOptional<z.ZodUUID>;
441
443
  }, z.core.$strict>, z.ZodObject<{
442
444
  text: z.ZodString;
443
445
  files: z.ZodOptional<z.ZodArray<z.ZodObject<{
@@ -657,6 +659,15 @@ export declare const ActionReceiptSchema: z.ZodObject<{
657
659
  thread: "thread";
658
660
  }>;
659
661
  }, z.core.$strip>>;
662
+ error: z.ZodOptional<z.ZodObject<{
663
+ code: z.ZodNullable<z.ZodString>;
664
+ message: z.ZodString;
665
+ details: z.ZodNullable<z.ZodString>;
666
+ httpStatusCode: z.ZodNullable<z.ZodNumber>;
667
+ retryable: z.ZodBoolean;
668
+ willRetry: z.ZodBoolean;
669
+ }, z.core.$strip>>;
670
+ recoveryActionId: z.ZodOptional<z.ZodUUID>;
660
671
  }, z.core.$strip>>;
661
672
  createdAt: z.ZodNumber;
662
673
  updatedAt: z.ZodNumber;
@@ -843,6 +854,15 @@ export declare const ActionWaitSchema: z.ZodObject<{
843
854
  thread: "thread";
844
855
  }>;
845
856
  }, z.core.$strip>>;
857
+ error: z.ZodOptional<z.ZodObject<{
858
+ code: z.ZodNullable<z.ZodString>;
859
+ message: z.ZodString;
860
+ details: z.ZodNullable<z.ZodString>;
861
+ httpStatusCode: z.ZodNullable<z.ZodNumber>;
862
+ retryable: z.ZodBoolean;
863
+ willRetry: z.ZodBoolean;
864
+ }, z.core.$strip>>;
865
+ recoveryActionId: z.ZodOptional<z.ZodUUID>;
846
866
  }, z.core.$strip>>;
847
867
  createdAt: z.ZodNumber;
848
868
  updatedAt: z.ZodNumber;
@@ -75,6 +75,8 @@ export const ActionCommandSchema = z.discriminatedUnion('kind', [
75
75
  threadId: ThreadIdSchema,
76
76
  input: MessageInputSchema,
77
77
  settings: TurnSettingsSchema.optional(),
78
+ // one conditional continuation of this exact failed action, never a replay of its input
79
+ continueAfterActionId: z.uuid().optional(),
78
80
  }),
79
81
  z.strictObject({
80
82
  kind: z.literal('steer'),
@@ -156,6 +156,7 @@ export declare const BrowserCommandSchema: z.ZodDiscriminatedUnion<[z.ZodObject<
156
156
  fast: z.ZodOptional<z.ZodBoolean>;
157
157
  outputSchema: z.ZodOptional<z.ZodPreprocess<z.ZodRecord<z.ZodString, z.ZodJSONSchema>, unknown>>;
158
158
  }, z.core.$strict>>;
159
+ continueAfterActionId: z.ZodOptional<z.ZodUUID>;
159
160
  }, z.core.$strict>, z.ZodObject<{
160
161
  text: z.ZodString;
161
162
  files: z.ZodOptional<z.ZodArray<z.ZodObject<{
@@ -422,6 +423,7 @@ export declare const BrowserActionSchema: z.ZodObject<{
422
423
  fast: z.ZodOptional<z.ZodBoolean>;
423
424
  outputSchema: z.ZodOptional<z.ZodPreprocess<z.ZodRecord<z.ZodString, z.ZodJSONSchema>, unknown>>;
424
425
  }, z.core.$strict>>;
426
+ continueAfterActionId: z.ZodOptional<z.ZodUUID>;
425
427
  }, z.core.$strict>, z.ZodObject<{
426
428
  text: z.ZodString;
427
429
  files: z.ZodOptional<z.ZodArray<z.ZodObject<{
@@ -657,6 +659,15 @@ export declare const BrowserReceiptSchema: z.ZodObject<{
657
659
  thread: "thread";
658
660
  }>;
659
661
  }, z.core.$strip>>;
662
+ error: z.ZodOptional<z.ZodObject<{
663
+ code: z.ZodNullable<z.ZodString>;
664
+ message: z.ZodString;
665
+ details: z.ZodNullable<z.ZodString>;
666
+ httpStatusCode: z.ZodNullable<z.ZodNumber>;
667
+ retryable: z.ZodBoolean;
668
+ willRetry: z.ZodBoolean;
669
+ }, z.core.$strip>>;
670
+ recoveryActionId: z.ZodOptional<z.ZodUUID>;
660
671
  }, z.core.$strip>>;
661
672
  createdAt: z.ZodNumber;
662
673
  updatedAt: z.ZodNumber;
@@ -20,8 +20,8 @@ export type { ITurnSettings, ISessionSettings, IConfigurationRequest, IConfigura
20
20
  export { BrowserThreadDetailSchema } from './browser/index.js';
21
21
  export { InputFileSchema, BoundInputFileSchema, MAX_INPUT_FILES, MAX_INPUT_FILE_BYTES, MAX_TEXT_FILE_BYTES, } from './inputs/index.js';
22
22
  export type { IInputFile, IBoundInputFile } from './inputs/index.js';
23
- export { MAX_RESULT_BYTES, OutputSchemaSchema, TurnUsageSchema, TurnResultSchema, } from './results/index.js';
24
- export type { IOutputSchema, ITurnUsage, ITurnResult } from './results/index.js';
23
+ export { MAX_RESULT_BYTES, OutputSchemaSchema, TurnUsageSchema, TurnErrorSchema, TurnResultSchema, } from './results/index.js';
24
+ export type { IOutputSchema, ITurnUsage, ITurnResult, ITurnError } from './results/index.js';
25
25
  export { EvidenceRequestSchema, EvidencePageSchema, EvidenceItemSchema, HistoryProvenanceSchema, } from './evidence/index.js';
26
26
  export type { IEvidenceRequest, IEvidencePage, IEvidenceItem, IHistoryProvenance, } from './evidence/index.js';
27
27
  export { SessionStateSchema, SessionTransitionReasonSchema, SessionTransitionSchema, SessionTransitionPageSchema, ObservationPaceSchema, } from './sessions/index.js';
@@ -22,7 +22,7 @@ export { TurnSettingsSchema, SessionSettingsSchema, ConfigurationRequestSchema,
22
22
  export { BrowserThreadDetailSchema } from './browser/index.js';
23
23
  // bounded file inputs and complete native results
24
24
  export { InputFileSchema, BoundInputFileSchema, MAX_INPUT_FILES, MAX_INPUT_FILE_BYTES, MAX_TEXT_FILE_BYTES, } from './inputs/index.js';
25
- export { MAX_RESULT_BYTES, OutputSchemaSchema, TurnUsageSchema, TurnResultSchema, } from './results/index.js';
25
+ export { MAX_RESULT_BYTES, OutputSchemaSchema, TurnUsageSchema, TurnErrorSchema, TurnResultSchema, } from './results/index.js';
26
26
  // bounded historical evidence
27
27
  export { EvidenceRequestSchema, EvidencePageSchema, EvidenceItemSchema, HistoryProvenanceSchema, } from './evidence/index.js';
28
28
  // session states and transitions
@@ -1,2 +1,2 @@
1
- export type { IOutputSchema, ITurnUsage, ITurnResult } from './types.js';
2
- export { MAX_RESULT_BYTES, OutputSchemaSchema, TurnUsageSchema, TurnResultSchema, } from './types.js';
1
+ export type { IOutputSchema, ITurnUsage, ITurnResult, ITurnError } from './types.js';
2
+ export { MAX_RESULT_BYTES, OutputSchemaSchema, TurnUsageSchema, TurnResultSchema, TurnErrorSchema, } from './types.js';
@@ -1,2 +1,2 @@
1
1
  // contracts
2
- export { MAX_RESULT_BYTES, OutputSchemaSchema, TurnUsageSchema, TurnResultSchema, } from './types.js';
2
+ export { MAX_RESULT_BYTES, OutputSchemaSchema, TurnUsageSchema, TurnResultSchema, TurnErrorSchema, } from './types.js';
@@ -12,6 +12,15 @@ export declare const TurnUsageSchema: z.ZodObject<{
12
12
  }>;
13
13
  }, z.core.$strip>;
14
14
  export type ITurnUsage = z.infer<typeof TurnUsageSchema>;
15
+ export declare const TurnErrorSchema: z.ZodObject<{
16
+ code: z.ZodNullable<z.ZodString>;
17
+ message: z.ZodString;
18
+ details: z.ZodNullable<z.ZodString>;
19
+ httpStatusCode: z.ZodNullable<z.ZodNumber>;
20
+ retryable: z.ZodBoolean;
21
+ willRetry: z.ZodBoolean;
22
+ }, z.core.$strip>;
23
+ export type ITurnError = z.infer<typeof TurnErrorSchema>;
15
24
  export declare const TurnResultSchema: z.ZodObject<{
16
25
  state: z.ZodEnum<{
17
26
  completed: "completed";
@@ -40,5 +49,14 @@ export declare const TurnResultSchema: z.ZodObject<{
40
49
  thread: "thread";
41
50
  }>;
42
51
  }, z.core.$strip>>;
52
+ error: z.ZodOptional<z.ZodObject<{
53
+ code: z.ZodNullable<z.ZodString>;
54
+ message: z.ZodString;
55
+ details: z.ZodNullable<z.ZodString>;
56
+ httpStatusCode: z.ZodNullable<z.ZodNumber>;
57
+ retryable: z.ZodBoolean;
58
+ willRetry: z.ZodBoolean;
59
+ }, z.core.$strip>>;
60
+ recoveryActionId: z.ZodOptional<z.ZodUUID>;
43
61
  }, z.core.$strip>;
44
62
  export type ITurnResult = z.infer<typeof TurnResultSchema>;
@@ -40,6 +40,15 @@ export const TurnUsageSchema = z.object({
40
40
  cachedInputTokens: z.number().int().nonnegative().safe().nullable(),
41
41
  scope: z.enum(['turn', 'thread']),
42
42
  });
43
+ // redacted native diagnostics; retryability never authorizes replaying the original input.
44
+ export const TurnErrorSchema = z.object({
45
+ code: z.string().min(1).max(256).nullable(),
46
+ message: z.string().min(1).max(4096),
47
+ details: z.string().max(8192).nullable(),
48
+ httpStatusCode: z.number().int().min(100).max(599).nullable(),
49
+ retryable: z.boolean(),
50
+ willRetry: z.boolean(),
51
+ });
43
52
  export const TurnResultSchema = z
44
53
  .object({
45
54
  state: z.enum(['completed', 'failed', 'interrupted']),
@@ -51,5 +60,7 @@ export const TurnResultSchema = z
51
60
  .enum(['native-error', 'invalid-structured-output', 'result-too-large', 'missing-result'])
52
61
  .nullable(),
53
62
  usage: TurnUsageSchema.nullable(),
63
+ error: TurnErrorSchema.optional(),
64
+ recoveryActionId: z.uuid().optional(),
54
65
  })
55
66
  .refine((result) => new TextEncoder().encode(JSON.stringify(result)).length <= MAX_RESULT_BYTES);
@@ -276,6 +276,7 @@ export declare const HqRequestSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
276
276
  fast: z.ZodOptional<z.ZodBoolean>;
277
277
  outputSchema: z.ZodOptional<z.ZodPreprocess<z.ZodRecord<z.ZodString, z.ZodJSONSchema>, unknown>>;
278
278
  }, z.core.$strict>>;
279
+ continueAfterActionId: z.ZodOptional<z.ZodUUID>;
279
280
  }, z.core.$strict>, z.ZodObject<{
280
281
  text: z.ZodString;
281
282
  files: z.ZodOptional<z.ZodArray<z.ZodObject<{
@@ -1910,6 +1911,15 @@ export declare const HqResponseSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
1910
1911
  thread: "thread";
1911
1912
  }>;
1912
1913
  }, z.core.$strip>>;
1914
+ error: z.ZodOptional<z.ZodObject<{
1915
+ code: z.ZodNullable<z.ZodString>;
1916
+ message: z.ZodString;
1917
+ details: z.ZodNullable<z.ZodString>;
1918
+ httpStatusCode: z.ZodNullable<z.ZodNumber>;
1919
+ retryable: z.ZodBoolean;
1920
+ willRetry: z.ZodBoolean;
1921
+ }, z.core.$strip>>;
1922
+ recoveryActionId: z.ZodOptional<z.ZodUUID>;
1913
1923
  }, z.core.$strip>>;
1914
1924
  createdAt: z.ZodNumber;
1915
1925
  updatedAt: z.ZodNumber;
@@ -2029,6 +2039,15 @@ export declare const HqResponseSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
2029
2039
  thread: "thread";
2030
2040
  }>;
2031
2041
  }, z.core.$strip>>;
2042
+ error: z.ZodOptional<z.ZodObject<{
2043
+ code: z.ZodNullable<z.ZodString>;
2044
+ message: z.ZodString;
2045
+ details: z.ZodNullable<z.ZodString>;
2046
+ httpStatusCode: z.ZodNullable<z.ZodNumber>;
2047
+ retryable: z.ZodBoolean;
2048
+ willRetry: z.ZodBoolean;
2049
+ }, z.core.$strip>>;
2050
+ recoveryActionId: z.ZodOptional<z.ZodUUID>;
2032
2051
  }, z.core.$strip>>;
2033
2052
  createdAt: z.ZodNumber;
2034
2053
  updatedAt: z.ZodNumber;
@@ -2149,6 +2168,15 @@ export declare const HqResponseSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
2149
2168
  thread: "thread";
2150
2169
  }>;
2151
2170
  }, z.core.$strip>>;
2171
+ error: z.ZodOptional<z.ZodObject<{
2172
+ code: z.ZodNullable<z.ZodString>;
2173
+ message: z.ZodString;
2174
+ details: z.ZodNullable<z.ZodString>;
2175
+ httpStatusCode: z.ZodNullable<z.ZodNumber>;
2176
+ retryable: z.ZodBoolean;
2177
+ willRetry: z.ZodBoolean;
2178
+ }, z.core.$strip>>;
2179
+ recoveryActionId: z.ZodOptional<z.ZodUUID>;
2152
2180
  }, z.core.$strip>>;
2153
2181
  createdAt: z.ZodNumber;
2154
2182
  updatedAt: z.ZodNumber;
@@ -2888,6 +2916,7 @@ export declare const IpcRequestSchema: z.ZodObject<{
2888
2916
  fast: z.ZodOptional<z.ZodBoolean>;
2889
2917
  outputSchema: z.ZodOptional<z.ZodPreprocess<z.ZodRecord<z.ZodString, z.ZodJSONSchema>, unknown>>;
2890
2918
  }, z.core.$strict>>;
2919
+ continueAfterActionId: z.ZodOptional<z.ZodUUID>;
2891
2920
  }, z.core.$strict>, z.ZodObject<{
2892
2921
  text: z.ZodString;
2893
2922
  files: z.ZodOptional<z.ZodArray<z.ZodObject<{
@@ -3978,6 +4007,15 @@ export declare const IpcResponseSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
3978
4007
  thread: "thread";
3979
4008
  }>;
3980
4009
  }, z.core.$strip>>;
4010
+ error: z.ZodOptional<z.ZodObject<{
4011
+ code: z.ZodNullable<z.ZodString>;
4012
+ message: z.ZodString;
4013
+ details: z.ZodNullable<z.ZodString>;
4014
+ httpStatusCode: z.ZodNullable<z.ZodNumber>;
4015
+ retryable: z.ZodBoolean;
4016
+ willRetry: z.ZodBoolean;
4017
+ }, z.core.$strip>>;
4018
+ recoveryActionId: z.ZodOptional<z.ZodUUID>;
3981
4019
  }, z.core.$strip>>;
3982
4020
  createdAt: z.ZodNumber;
3983
4021
  updatedAt: z.ZodNumber;
@@ -4097,6 +4135,15 @@ export declare const IpcResponseSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
4097
4135
  thread: "thread";
4098
4136
  }>;
4099
4137
  }, z.core.$strip>>;
4138
+ error: z.ZodOptional<z.ZodObject<{
4139
+ code: z.ZodNullable<z.ZodString>;
4140
+ message: z.ZodString;
4141
+ details: z.ZodNullable<z.ZodString>;
4142
+ httpStatusCode: z.ZodNullable<z.ZodNumber>;
4143
+ retryable: z.ZodBoolean;
4144
+ willRetry: z.ZodBoolean;
4145
+ }, z.core.$strip>>;
4146
+ recoveryActionId: z.ZodOptional<z.ZodUUID>;
4100
4147
  }, z.core.$strip>>;
4101
4148
  createdAt: z.ZodNumber;
4102
4149
  updatedAt: z.ZodNumber;
@@ -4217,6 +4264,15 @@ export declare const IpcResponseSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
4217
4264
  thread: "thread";
4218
4265
  }>;
4219
4266
  }, z.core.$strip>>;
4267
+ error: z.ZodOptional<z.ZodObject<{
4268
+ code: z.ZodNullable<z.ZodString>;
4269
+ message: z.ZodString;
4270
+ details: z.ZodNullable<z.ZodString>;
4271
+ httpStatusCode: z.ZodNullable<z.ZodNumber>;
4272
+ retryable: z.ZodBoolean;
4273
+ willRetry: z.ZodBoolean;
4274
+ }, z.core.$strip>>;
4275
+ recoveryActionId: z.ZodOptional<z.ZodUUID>;
4220
4276
  }, z.core.$strip>>;
4221
4277
  createdAt: z.ZodNumber;
4222
4278
  updatedAt: z.ZodNumber;
package/dist/index.d.ts CHANGED
@@ -11,4 +11,4 @@ export { openHostDatabase } from './storage/index.js';
11
11
  export type { IStorageDescriptor, IStorageMaintenanceOperation } from './storage/index.js';
12
12
  export { restoreHqSnapshot, packHqSnapshot, unpackHqSnapshot } from './snapshots/index.js';
13
13
  export type { IHqSnapshotInspection, IHqRestoreOptions, IHqRestoreResult, } from './snapshots/index.js';
14
- export type { IInputFile, IBoundInputFile, IOutputSchema, ITurnUsage, ITurnResult, IPreparedInput, } from './contracts/index.js';
14
+ export type { IInputFile, IBoundInputFile, IOutputSchema, ITurnUsage, ITurnResult, ITurnError, IPreparedInput, } from './contracts/index.js';
@@ -1,4 +1,4 @@
1
- import { createHash } from 'node:crypto';
1
+ import { hashValue } from 'jg-crypto';
2
2
  import { z } from 'zod';
3
3
  // keep result diagnostics independent of structural validation so malformed results are visible too
4
4
  const MAX_DIAGNOSTIC_IDS = 64;
@@ -54,7 +54,7 @@ const describeResult = (session, result) => {
54
54
  replayedSteerIds: collectIds(session.replayedSteers ?? []),
55
55
  subtype: knownSubtype.success ? knownSubtype.data : null,
56
56
  subtypeFingerprint: !knownSubtype.success && typeof subtype === 'string' && subtype.length <= 64
57
- ? createHash('sha256').update(subtype).digest('hex')
57
+ ? hashValue(subtype, 'sha256')
58
58
  : null,
59
59
  isError: typeof metadata?.is_error === 'boolean' ? metadata.is_error : null,
60
60
  numTurns: TurnCountSchema.safeParse(metadata?.num_turns).data ?? null,
@@ -85,7 +85,12 @@ export const createCodexProviderFactory = (extraSkillRoots, daemonLauncher) => (
85
85
  if (!turn)
86
86
  return null;
87
87
  if (turn.state !== 'inProgress' && turn.state !== 'unknown')
88
- return { nativeId: turn.nativeId, state: turn.state, isInferred: false };
88
+ return {
89
+ nativeId: turn.nativeId,
90
+ state: turn.state,
91
+ isInferred: false,
92
+ ...(turn.error ? { error: turn.error } : {}),
93
+ };
89
94
  /*
90
95
  * A turn cut short when the daemon stopped stays in progress in its saved history, and so
91
96
  * does one whose end the history hasn't saved yet, so its state comes from the status.
@@ -11,6 +11,7 @@ import { NativeItemSchema, NativeThreadSchema, NativeThreadStatusSchema, NativeT
11
11
  import { parseNative } from './validations.js';
12
12
  import { toHistoryItem, toNativeLineage, toNativeState, toSessionState } from './transformers.js';
13
13
  import { buildCodexReply, parseCodexPrompt, toApprovalPresentation } from './approvals/index.js';
14
+ import { CodexTurnErrorSchema, toTurnError } from './turn-error/index.js';
14
15
  const TargetSchema = z.object({ threadId: NativeIdSchema, turnId: NativeIdSchema });
15
16
  const DeltaSchema = TargetSchema.extend({ itemId: NativeIdSchema, delta: z.string() });
16
17
  /** @returns Exact native session metadata normalized to the common control boundary. */
@@ -29,6 +30,14 @@ export const createCodexEvents = (native, events, observeSession, observeLoaded)
29
30
  let connectionId = randomUUID();
30
31
  const scopedRequestId = (id) => JSON.stringify([connectionId, id]);
31
32
  const turns = new Map();
33
+ // bounded per-turn diagnostics also retain a failed end long enough to accept a late error.
34
+ const turnErrors = new Map();
35
+ const errorKey = (threadId, turnId) => JSON.stringify([threadId, turnId]);
36
+ const rememberError = (key, value) => {
37
+ if (!turnErrors.has(key) && turnErrors.size >= 128)
38
+ turnErrors.delete(turnErrors.keys().next().value);
39
+ turnErrors.set(key, value);
40
+ };
32
41
  /**
33
42
  * Keeps HQ's result capture in step with a turn whose start or end failed validation: a lost
34
43
  * start still binds the capture prepared for HQ's input, and a lost end drops its turn's capture,
@@ -73,9 +82,16 @@ export const createCodexEvents = (native, events, observeSession, observeLoaded)
73
82
  else if (turn.status !== 'inProgress') {
74
83
  const pending = turns.get(threadId);
75
84
  const captured = pending?.turnId === turn.id ? pending : undefined;
76
- const result = captured
77
- ? toTurnResult(turn.status, captured.text, undefined, captured.schema, captured.usage)
85
+ const key = errorKey(threadId, turn.id);
86
+ const diagnostic = turn.error ? toTurnError(turn.error, false) : turnErrors.get(key)?.error;
87
+ const result = captured || turn.status === 'failed'
88
+ ? toTurnResult(turn.status, captured?.text ?? null, undefined, captured?.schema, captured?.usage ?? null, turn.status === 'failed' ? diagnostic : undefined)
78
89
  : undefined;
90
+ if (turn.status === 'failed') {
91
+ rememberError(key, { terminal: true, ...(diagnostic ? { error: diagnostic } : {}) });
92
+ }
93
+ else
94
+ turnErrors.delete(key);
79
95
  if (result && captured?.oversized) {
80
96
  result.state = 'failed';
81
97
  result.failure = 'result-too-large';
@@ -98,6 +114,27 @@ export const createCodexEvents = (native, events, observeSession, observeLoaded)
98
114
  else
99
115
  parseNative(z.never(), params);
100
116
  }
117
+ else if (method === 'error') {
118
+ const { threadId, turnId, error, willRetry } = parseNative(TargetSchema.extend({
119
+ error: CodexTurnErrorSchema,
120
+ willRetry: z.boolean(),
121
+ }), params);
122
+ const key = errorKey(threadId, turnId);
123
+ const terminal = turnErrors.get(key)?.terminal ?? false;
124
+ const diagnostic = toTurnError(error, willRetry);
125
+ rememberError(key, { terminal, error: diagnostic });
126
+ if (terminal) {
127
+ const result = toTurnResult('failed', null, undefined, undefined, null, diagnostic);
128
+ events.observe({
129
+ kind: 'turn-completed',
130
+ provider: 'codex',
131
+ nativeThreadId: threadId,
132
+ nativeTurnId: turnId,
133
+ state: 'failed',
134
+ result,
135
+ });
136
+ }
137
+ }
101
138
  else if (method === 'item/started' || method === 'item/completed') {
102
139
  const { threadId, turnId, item, startedAtMs, completedAtMs } = parseNative(TargetSchema.extend({
103
140
  item: NativeItemSchema.shape.item,
@@ -302,6 +339,7 @@ export const createCodexEvents = (native, events, observeSession, observeLoaded)
302
339
  connectionId = randomUUID();
303
340
  // a disconnected stream cannot supply a complete result from its partial capture
304
341
  turns.clear();
342
+ turnErrors.clear();
305
343
  events.unavailable();
306
344
  },
307
345
  connected: () => observeLoaded(),
@@ -5,6 +5,7 @@ import { nativeProvenance } from '../../sessions/evidence/index.js';
5
5
  import { TurnSummarySchema, } from './types.js';
6
6
  import { KNOWN_NATIVE_STATES } from './constants.js';
7
7
  import { parseNative } from './validations.js';
8
+ import { toTurnError } from './turn-error/index.js';
8
9
  /** Preserves exact native tree identities independently of managed-agent relationships. */
9
10
  export const toNativeLineage = (thread) => ({
10
11
  sessionId: thread.sessionId ?? null,
@@ -60,6 +61,7 @@ export const toTurnSummary = (turn) => parseNative(TurnSummarySchema, {
60
61
  state: turn.status,
61
62
  startedAt: turn.startedAt == null ? null : turn.startedAt * 1000,
62
63
  completedAt: turn.completedAt == null ? null : turn.completedAt * 1000,
64
+ ...(turn.status === 'failed' && turn.error ? { error: toTurnError(turn.error, false) } : {}),
63
65
  });
64
66
  const TextPartsSchema = z.object({
65
67
  content: z
@@ -0,0 +1,3 @@
1
+ export { CodexTurnErrorSchema } from './types.js';
2
+ export type { ICodexTurnError } from './types.js';
3
+ export { toTurnError } from './transformers.js';
@@ -0,0 +1,4 @@
1
+ // native contracts
2
+ export { CodexTurnErrorSchema } from './types.js';
3
+ // diagnostic projection
4
+ export { toTurnError } from './transformers.js';
@@ -0,0 +1,7 @@
1
+ import type { ITurnError } from '../../../contracts/index.js';
2
+ import type { ICodexTurnError } from './types.js';
3
+ /**
4
+ * Projects native diagnostics without treating policy, credential or quota failures as transient.
5
+ * @returns A bounded redacted diagnostic, with conservative recovery eligibility.
6
+ */
7
+ export declare const toTurnError: (error: ICodexTurnError, willRetry: boolean) => ITurnError;
@@ -0,0 +1,74 @@
1
+ import { redactSecrets, redactUrlQueryParams, SECRET_TOKEN_PATTERNS } from 'jg-utilities';
2
+ import { z } from 'zod';
3
+ const HttpErrorSchema = z.object({ httpStatusCode: z.number().int().min(100).max(599).nullable() });
4
+ const TRANSIENT_CODES = new Set([
5
+ 'internalServerError',
6
+ 'serverOverloaded',
7
+ 'httpConnectionFailed',
8
+ 'responseStreamConnectionFailed',
9
+ 'responseStreamDisconnected',
10
+ 'responseTooManyFailedAttempts',
11
+ ]);
12
+ const MANUAL_REVIEW_PATTERN = /policy|invalid[ _-]?prompt|content[ _-]?filter|unauthori[sz]ed|authenticat|quota|usage[ _-]?limit|context[ _-]?window|rate[ _-]?limit|permission|access[ _-]?denied/iu;
13
+ const SECRET_QUERY_NAMES = [
14
+ 'token',
15
+ 'access_token',
16
+ 'api_key',
17
+ 'key',
18
+ 'authorization',
19
+ 'secret',
20
+ 'password',
21
+ 'signature',
22
+ ];
23
+ const DIAGNOSTIC_SECRET_PATTERNS = [
24
+ ...SECRET_TOKEN_PATTERNS,
25
+ /\b(?:Bearer|Basic)\s+[^\s,;]+/giu,
26
+ /\b(?:api[_-]?key|access[_-]?token|password|secret)\s*[:=]\s*[^\s,;]+/giu,
27
+ ];
28
+ /** Removes credentials before bounding a diagnostic without splitting its final surrogate pair. */
29
+ const safeDiagnostic = (text, limit) => redactSecrets(text, { patterns: DIAGNOSTIC_SECRET_PATTERNS })
30
+ .text.replace(/https?:\/\/[^\s"<>]+/gu, (url) => {
31
+ try {
32
+ const address = new URL(redactUrlQueryParams(url, SECRET_QUERY_NAMES));
33
+ address.username = '';
34
+ address.password = '';
35
+ return address.toString();
36
+ }
37
+ catch {
38
+ return '[redacted URL]';
39
+ }
40
+ })
41
+ .slice(0, limit)
42
+ .replace(/[\uD800-\uDBFF]$/u, '');
43
+ /**
44
+ * Projects native diagnostics without treating policy, credential or quota failures as transient.
45
+ * @returns A bounded redacted diagnostic, with conservative recovery eligibility.
46
+ */
47
+ export const toTurnError = (error, willRetry) => {
48
+ const entries = typeof error.codexErrorInfo === 'object' && error.codexErrorInfo !== null
49
+ ? Object.entries(error.codexErrorInfo)
50
+ : [];
51
+ const code = typeof error.codexErrorInfo === 'string'
52
+ ? error.codexErrorInfo
53
+ : entries.length === 1
54
+ ? entries[0][0]
55
+ : null;
56
+ const parsed = entries.length === 1 ? HttpErrorSchema.safeParse(entries[0][1]) : null;
57
+ const httpStatusCode = parsed?.success ? (parsed.data.httpStatusCode ?? null) : null;
58
+ const isTransientStatus = httpStatusCode === null || httpStatusCode === 408 || httpStatusCode >= 500;
59
+ const requiresReview = MANUAL_REVIEW_PATTERN.test(error.message) ||
60
+ MANUAL_REVIEW_PATTERN.test(error.additionalDetails ?? '');
61
+ return {
62
+ code: code ? safeDiagnostic(code, 256) : null,
63
+ message: safeDiagnostic(error.message, 4096),
64
+ details: error.additionalDetails == null ? null : safeDiagnostic(error.additionalDetails, 8192),
65
+ httpStatusCode,
66
+ retryable: !willRetry &&
67
+ code !== null &&
68
+ TRANSIENT_CODES.has(code) &&
69
+ (entries.length === 0 || parsed?.success === true) &&
70
+ isTransientStatus &&
71
+ !requiresReview,
72
+ willRetry,
73
+ };
74
+ };
@@ -0,0 +1,7 @@
1
+ import { z } from 'zod';
2
+ export declare const CodexTurnErrorSchema: z.ZodObject<{
3
+ message: z.ZodString;
4
+ codexErrorInfo: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodRecord<z.ZodString, z.ZodUnknown>]>>>;
5
+ additionalDetails: z.ZodOptional<z.ZodNullable<z.ZodString>>;
6
+ }, z.core.$strip>;
7
+ export type ICodexTurnError = z.infer<typeof CodexTurnErrorSchema>;
@@ -0,0 +1,9 @@
1
+ import { z } from 'zod';
2
+ // native diagnostics are bounded independently of the normalized public message.
3
+ export const CodexTurnErrorSchema = z.object({
4
+ message: z.string().min(1).max(131_072),
5
+ codexErrorInfo: z
6
+ .union([z.string().max(256), z.record(z.string().max(256), z.unknown())])
7
+ .nullish(),
8
+ additionalDetails: z.string().max(131_072).nullish(),
9
+ });
@@ -32,6 +32,11 @@ export declare const NativeTurnSchema: z.ZodObject<{
32
32
  }>;
33
33
  startedAt: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
34
34
  completedAt: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
35
+ error: z.ZodCatch<z.ZodOptional<z.ZodNullable<z.ZodObject<{
36
+ message: z.ZodString;
37
+ codexErrorInfo: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodRecord<z.ZodString, z.ZodUnknown>]>>>;
38
+ additionalDetails: z.ZodOptional<z.ZodNullable<z.ZodString>>;
39
+ }, z.core.$strip>>>>;
35
40
  }, z.core.$strip>;
36
41
  export declare const TurnSummarySchema: z.ZodObject<{
37
42
  nativeId: z.ZodString;
@@ -44,6 +49,14 @@ export declare const TurnSummarySchema: z.ZodObject<{
44
49
  }>;
45
50
  startedAt: z.ZodNullable<z.ZodNumber>;
46
51
  completedAt: z.ZodNullable<z.ZodNumber>;
52
+ error: z.ZodOptional<z.ZodObject<{
53
+ code: z.ZodNullable<z.ZodString>;
54
+ message: z.ZodString;
55
+ details: z.ZodNullable<z.ZodString>;
56
+ httpStatusCode: z.ZodNullable<z.ZodNumber>;
57
+ retryable: z.ZodBoolean;
58
+ willRetry: z.ZodBoolean;
59
+ }, z.core.$strip>>;
47
60
  }, z.core.$strip>;
48
61
  export type ITurnSummary = z.infer<typeof TurnSummarySchema>;
49
62
  export declare const NativeItemSchema: z.ZodObject<{
@@ -86,6 +99,11 @@ export declare const NativeTurnPageSchema: z.ZodObject<{
86
99
  }>;
87
100
  startedAt: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
88
101
  completedAt: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
102
+ error: z.ZodCatch<z.ZodOptional<z.ZodNullable<z.ZodObject<{
103
+ message: z.ZodString;
104
+ codexErrorInfo: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodRecord<z.ZodString, z.ZodUnknown>]>>>;
105
+ additionalDetails: z.ZodOptional<z.ZodNullable<z.ZodString>>;
106
+ }, z.core.$strip>>>>;
89
107
  }, z.core.$strip>>;
90
108
  nextCursor: z.ZodNullable<z.ZodString>;
91
109
  }, z.core.$strip>;
@@ -1,5 +1,6 @@
1
1
  import { z } from 'zod';
2
- import { MAX_PAGE_SIZE, UsageCreditsSchema, UsageResetCreditsSchema, } from '../../contracts/index.js';
2
+ import { MAX_PAGE_SIZE, UsageCreditsSchema, UsageResetCreditsSchema, TurnErrorSchema, } from '../../contracts/index.js';
3
+ import { CodexTurnErrorSchema } from './turn-error/index.js';
3
4
  // a session's status, which may name one newer than this adapter knows
4
5
  export const NativeThreadStatusSchema = z.object({
5
6
  type: z.string().min(1).max(256),
@@ -24,6 +25,7 @@ export const NativeTurnSchema = z.object({
24
25
  status: z.enum(['completed', 'interrupted', 'failed', 'inProgress']),
25
26
  startedAt: z.number().int().safe().nullable().optional(),
26
27
  completedAt: z.number().int().safe().nullable().optional(),
28
+ error: CodexTurnErrorSchema.nullish().catch(null),
27
29
  });
28
30
  // a turn's state and times in Unix milliseconds, as HQ reads them from a native turn
29
31
  export const TurnSummarySchema = z.object({
@@ -31,6 +33,7 @@ export const TurnSummarySchema = z.object({
31
33
  state: z.enum(['completed', 'interrupted', 'failed', 'inProgress', 'unknown']),
32
34
  startedAt: z.number().int().nullable(),
33
35
  completedAt: z.number().int().nullable(),
36
+ error: TurnErrorSchema.optional(),
34
37
  });
35
38
  // recorded native item lifecycle times are milliseconds; older producers may omit them
36
39
  const NativeItemTimeSchema = z
@@ -1,6 +1,6 @@
1
- import { type IOutputSchema, type ITurnResult, type ITurnUsage } from '../../contracts/index.js';
1
+ import { type IOutputSchema, type ITurnResult, type ITurnUsage, type ITurnError } from '../../contracts/index.js';
2
2
  /**
3
3
  * Validates a complete native final result without substituting a presentation excerpt.
4
4
  * @returns A complete result, or an explicit failed result when capture/validation cannot succeed.
5
5
  */
6
- export declare const toTurnResult: (state: ITurnResult["state"], text: string | null, structuredOutput: unknown, schema: IOutputSchema | undefined, usage: ITurnUsage | null) => ITurnResult;
6
+ export declare const toTurnResult: (state: ITurnResult["state"], text: string | null, structuredOutput: unknown, schema: IOutputSchema | undefined, usage: ITurnUsage | null, error?: ITurnError) => ITurnResult;
@@ -4,7 +4,7 @@ import { MAX_RESULT_BYTES, } from '../../contracts/index.js';
4
4
  * Validates a complete native final result without substituting a presentation excerpt.
5
5
  * @returns A complete result, or an explicit failed result when capture/validation cannot succeed.
6
6
  */
7
- export const toTurnResult = (state, text, structuredOutput, schema, usage) => {
7
+ export const toTurnResult = (state, text, structuredOutput, schema, usage, error) => {
8
8
  const result = {
9
9
  state,
10
10
  format: schema ? 'json-schema' : 'text',
@@ -13,6 +13,7 @@ export const toTurnResult = (state, text, structuredOutput, schema, usage) => {
13
13
  isComplete: true,
14
14
  failure: state === 'failed' ? 'native-error' : null,
15
15
  usage,
16
+ ...(error ? { error } : {}),
16
17
  };
17
18
  try {
18
19
  if (Buffer.byteLength(JSON.stringify([text, structuredOutput ?? null])) > MAX_RESULT_BYTES) {
@@ -101,6 +101,14 @@ export declare const ProviderReattachmentSchema: z.ZodObject<{
101
101
  running: "running";
102
102
  }>;
103
103
  isInferred: z.ZodOptional<z.ZodBoolean>;
104
+ error: z.ZodOptional<z.ZodObject<{
105
+ code: z.ZodNullable<z.ZodString>;
106
+ message: z.ZodString;
107
+ details: z.ZodNullable<z.ZodString>;
108
+ httpStatusCode: z.ZodNullable<z.ZodNumber>;
109
+ retryable: z.ZodBoolean;
110
+ willRetry: z.ZodBoolean;
111
+ }, z.core.$strip>>;
104
112
  }, z.core.$strip>>;
105
113
  }, z.core.$strip>;
106
114
  export type IProviderReattachment = z.infer<typeof ProviderReattachmentSchema>;
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod';
2
- import { SkillPageSchema, SkillSchema, ThreadSummarySchema } from '../contracts/index.js';
2
+ import { SkillPageSchema, SkillSchema, ThreadSummarySchema, TurnErrorSchema, } from '../contracts/index.js';
3
3
  import { NativeIdSchema } from '../contracts/identities/index.js';
4
4
  // control acknowledgements retain exact identities without interpreting unknown execution states
5
5
  export const ProviderThreadSchema = ThreadSummarySchema.pick({
@@ -23,6 +23,7 @@ export const ProviderReattachmentSchema = z.object({
23
23
  state: z.enum(['running', 'completed', 'failed', 'interrupted']),
24
24
  // the saved turn is still in progress, so its state comes from the session's status
25
25
  isInferred: z.boolean().optional(),
26
+ error: TurnErrorSchema.optional(),
26
27
  })
27
28
  .nullable(),
28
29
  });
@@ -54,6 +54,12 @@ export declare class ControlAdmission extends ControlModel {
54
54
  /** Requires the control the rule names over the thread. */
55
55
  private __requireControl;
56
56
  private __requireIdle;
57
+ /**
58
+ * Claims one continuation inside admission, before any native input can start.
59
+ * @throws
60
+ * - JG_AGENT_HQ_ACTION_CONFLICT: The HQ action conflicts with its recorded state
61
+ */
62
+ private __claimContinuation;
57
63
  /** Starts the turn an action's input begins, holding the thread until native acknowledges it. */
58
64
  private __beginTurn;
59
65
  }
@@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto';
2
2
  import { hashValue, signHmac } from 'jg-crypto';
3
3
  import { isException } from 'jg-exception';
4
4
  import { z } from 'zod';
5
- import { ErrorKindSchema, } from '../../../contracts/index.js';
5
+ import { ErrorKindSchema, MAX_RESULT_BYTES, } from '../../../contracts/index.js';
6
6
  import { toActionFailure } from '../../../errors/index.js';
7
7
  import { ControlModel } from '../control.model.js';
8
8
  import { ACTION_COLUMNS } from '../constants.js';
@@ -275,6 +275,9 @@ export class ControlAdmission extends ControlModel {
275
275
  this._statements.run('UPDATE agent_hq_thread SET pending_action_id = ? WHERE id = ?', action.id, threadId);
276
276
  break;
277
277
  case 'message':
278
+ if (command.continueAfterActionId !== undefined) {
279
+ this.__claimContinuation(action.id, thread, command);
280
+ }
278
281
  this.__beginTurn(action.id, threadId);
279
282
  break;
280
283
  case 'queue':
@@ -405,6 +408,44 @@ export class ControlAdmission extends ControlModel {
405
408
  !['idle', 'completed', 'failed', 'interrupted'].includes(thread.state))
406
409
  this._conflict();
407
410
  }
411
+ /**
412
+ * Claims one continuation inside admission, before any native input can start.
413
+ * @throws
414
+ * - JG_AGENT_HQ_ACTION_CONFLICT: The HQ action conflicts with its recorded state
415
+ */
416
+ __claimContinuation(actionId, thread, command) {
417
+ const source = this._action(command.continueAfterActionId);
418
+ const result = source?.result ? JSON.parse(source.result) : null;
419
+ if (thread.provider !== 'codex' ||
420
+ thread.state !== 'failed' ||
421
+ thread.last_turn_state !== 'failed' ||
422
+ !source ||
423
+ source.thread_id !== thread.id ||
424
+ source.runtime_epoch !== this._epoch ||
425
+ !['message', 'queue', 'thread-create'].includes(source.kind) ||
426
+ source.delivery !== 'acknowledged' ||
427
+ source.completion !== 'failed' ||
428
+ source.native_turn_id !== thread.last_turn_id ||
429
+ source.related_action_id !== null ||
430
+ result?.failure !== 'native-error' ||
431
+ result.error?.retryable !== true ||
432
+ result.error.willRetry ||
433
+ result.recoveryActionId !== undefined ||
434
+ command.input.kind !== 'text' ||
435
+ command.input.text !== 'continue' ||
436
+ (command.input.files?.length ?? 0) !== 0 ||
437
+ command.settings !== undefined)
438
+ this._conflict();
439
+ const pending = this._statements.get("SELECT id FROM agent_hq_action WHERE thread_id = ? AND delivery IN ('queued', 'submitted', 'uncertain') AND id <> ? LIMIT 1", thread.id, actionId);
440
+ const approval = this._statements.get("SELECT id FROM agent_hq_native_approval WHERE thread_id = ? AND state = 'pending' LIMIT 1", thread.id);
441
+ if (pending || approval)
442
+ this._conflict();
443
+ const claimedResult = JSON.stringify({ ...result, recoveryActionId: actionId });
444
+ if (Buffer.byteLength(claimedResult) > MAX_RESULT_BYTES)
445
+ this._conflict();
446
+ this._statements.run('UPDATE agent_hq_action SET result = ?, updated_at = ? WHERE id = ?', claimedResult, Date.now(), source.id);
447
+ this._statements.run('UPDATE agent_hq_action SET related_action_id = ? WHERE id = ?', source.id, actionId);
448
+ }
408
449
  /** Starts the turn an action's input begins, holding the thread until native acknowledges it. */
409
450
  __beginTurn(actionId, threadId) {
410
451
  const now = Date.now();
@@ -1,4 +1,4 @@
1
- import type { IManagedThread } from '../../../contracts/index.js';
1
+ import { type IManagedThread } from '../../../contracts/index.js';
2
2
  import { ControlModel } from '../control.model.js';
3
3
  import type { IApprovalRecord, INativeObservation, IObservationResult } from '../types.js';
4
4
  /** Applies ordered native evidence, such as turns, items and approvals, to controlled threads. */
@@ -1,4 +1,5 @@
1
1
  import { signHmac } from 'jg-crypto';
2
+ import { MAX_RESULT_BYTES } from '../../../contracts/index.js';
2
3
  import { ControlModel } from '../control.model.js';
3
4
  import { CONTROLLED_THREAD_CAPACITY } from '../constants.js';
4
5
  import { toManagedThread } from '../transformers.js';
@@ -81,8 +82,23 @@ export class ControlObservations extends ControlModel {
81
82
  */
82
83
  if (prior.digest !== digest && observation.kind !== 'turn-completed')
83
84
  this._conflict();
84
- if (prior.digest !== digest && observation.kind === 'turn-completed' && observation.result)
85
+ if (prior.digest !== digest &&
86
+ observation.kind === 'turn-completed' &&
87
+ observation.result) {
85
88
  this._statements.run("UPDATE agent_hq_action SET result = ?, updated_at = ? WHERE thread_id = ? AND native_turn_id = ? AND kind IN ('message', 'queue', 'thread-create') AND result IS NULL", JSON.stringify(observation.result), now, thread.id, observation.nativeTurnId);
89
+ if (observation.result.error) {
90
+ const error = JSON.stringify(observation.result.error);
91
+ const oversized = JSON.stringify({
92
+ ...observation.result,
93
+ failure: 'result-too-large',
94
+ isComplete: false,
95
+ text: null,
96
+ structuredOutput: null,
97
+ });
98
+ // a late diagnostic fills its own field without losing an earlier body or recovery fence.
99
+ this._statements.run("UPDATE agent_hq_action SET result = CASE WHEN length(CAST(result AS BLOB)) + ? <= ? THEN json_set(result, '$.error', json(?)) ELSE ? END, updated_at = ? WHERE thread_id = ? AND native_turn_id = ? AND kind IN ('message', 'queue', 'thread-create') AND completion = 'failed' AND result IS NOT NULL AND json_extract(result, '$.error') IS NULL", Buffer.byteLength(error) + 32, MAX_RESULT_BYTES, error, oversized, now, thread.id, observation.nativeTurnId);
100
+ }
101
+ }
86
102
  return { thread: toManagedThread(thread), canDispatchQueued: false };
87
103
  }
88
104
  if (observation.kind === 'turn-started') {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jg-agent-hq",
3
- "version": "13.5.10",
3
+ "version": "13.6.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",