@opengeni/worker-bundle 0.12.10 → 0.13.4

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 (72) hide show
  1. package/dist/activities/agent-turn.d.ts +778 -0
  2. package/dist/activities/capabilities.d.ts +18 -0
  3. package/dist/activities/codex-auth.d.ts +1 -0
  4. package/dist/activities/codex-capacity.d.ts +31 -0
  5. package/dist/activities/codex-fleet-shadow.d.ts +74 -0
  6. package/dist/activities/codex-rotation.d.ts +261 -0
  7. package/dist/activities/common.d.ts +17 -0
  8. package/dist/activities/context-compaction.d.ts +81 -0
  9. package/dist/activities/documents.d.ts +39 -0
  10. package/dist/activities/environment.d.ts +97 -0
  11. package/dist/activities/expiring-material-renewal.d.ts +38 -0
  12. package/dist/activities/file-upload-reaper.d.ts +25 -0
  13. package/dist/activities/git-credential-renewal.d.ts +41 -0
  14. package/dist/activities/goals.d.ts +16 -0
  15. package/dist/activities/mcp-credentials.d.ts +14 -0
  16. package/dist/activities/packs.d.ts +77 -0
  17. package/dist/activities/parent-wake.d.ts +54 -0
  18. package/dist/activities/recording.d.ts +90 -0
  19. package/dist/activities/redaction.d.ts +1 -0
  20. package/dist/activities/rig-verification.d.ts +131 -0
  21. package/dist/activities/run-credential-renewal.d.ts +28 -0
  22. package/dist/activities/run-credentials.d.ts +36 -0
  23. package/dist/activities/run-input.d.ts +106 -0
  24. package/dist/activities/sandbox-lease.d.ts +128 -0
  25. package/dist/activities/scheduled-tasks.d.ts +4 -0
  26. package/dist/activities/session-state.d.ts +39 -0
  27. package/dist/activities/streaming.d.ts +24 -0
  28. package/dist/activities/toolspace-token-renewal.d.ts +23 -0
  29. package/dist/activities/turn-attempt-fenced.d.ts +11 -0
  30. package/dist/activities/types.d.ts +240 -0
  31. package/dist/activities/workflow-wake.d.ts +15 -0
  32. package/dist/activities/workspace-capture.d.ts +105 -0
  33. package/dist/activities.d.ts +312 -0
  34. package/dist/concurrency.d.ts +19 -0
  35. package/dist/host-export-pump.d.ts +66 -0
  36. package/dist/host-export.d.ts +6 -67
  37. package/dist/http.d.ts +32 -0
  38. package/dist/index.d.ts +27 -388
  39. package/dist/index.js +2729 -1208
  40. package/dist/index.js.map +1 -1
  41. package/dist/observability-metrics.d.ts +200 -0
  42. package/dist/op-journal.d.ts +10 -0
  43. package/dist/sandbox-resume.d.ts +152 -0
  44. package/dist/sandbox-routing.d.ts +159 -0
  45. package/dist/worker-service-lifecycle.d.ts +20 -0
  46. package/dist/workflow-bundle.js +88 -20
  47. package/dist/workflows/activities.d.ts +27 -0
  48. package/dist/workflows/document-index.d.ts +41 -0
  49. package/dist/workflows/file-upload-reaper.d.ts +2 -0
  50. package/dist/workflows/rig-verification.d.ts +3 -0
  51. package/dist/workflows/sandbox-reaper.d.ts +1 -0
  52. package/dist/workflows/scheduled-tasks.d.ts +17 -0
  53. package/dist/workflows/session.d.ts +58 -0
  54. package/dist/workflows/workflow-wake.d.ts +3 -0
  55. package/dist/workflows.d.ts +7 -0
  56. package/package.json +13 -13
  57. package/src/activities/agent-turn.ts +873 -131
  58. package/src/activities/context-compaction.ts +265 -76
  59. package/src/activities/environment.ts +1 -0
  60. package/src/activities/goals.ts +14 -0
  61. package/src/activities/rig-verification.ts +2 -0
  62. package/src/activities/run-input.ts +18 -4
  63. package/src/activities/sandbox-lease.ts +787 -133
  64. package/src/activities/session-state.ts +56 -0
  65. package/src/activities/types.ts +21 -0
  66. package/src/activities/workspace-capture.ts +95 -4
  67. package/src/activities.ts +3 -0
  68. package/src/observability-metrics.ts +94 -0
  69. package/src/sandbox-resume.ts +383 -90
  70. package/src/sandbox-routing.ts +32 -10
  71. package/src/workflows/activities.ts +1 -0
  72. package/src/workflows/session.ts +70 -0
@@ -2,11 +2,15 @@ import {
2
2
  applyContextCompaction,
3
3
  getActiveSessionHistoryItems,
4
4
  recordSkippedContextCompaction,
5
+ recordStartedContextCompaction,
5
6
  type Database,
6
7
  } from "@opengeni/db";
7
8
  import {
9
+ EmptyCompactionSummaryError,
10
+ REMOTE_COMPACTION_V2_IMPLEMENTATION,
8
11
  SUMMARY_BUFFER_TOKENS,
9
12
  buildCompactionReplacementHistory,
13
+ buildRemoteV2ReplacementHistory,
10
14
  compactionReplacementFingerprint,
11
15
  decideCompaction,
12
16
  estimateTokens,
@@ -18,6 +22,7 @@ import {
18
22
  } from "@opengeni/runtime";
19
23
  import { contextInputBudgetTokens, type Settings } from "@opengeni/config";
20
24
  import type { SessionEvent } from "@opengeni/contracts";
25
+ import { applyCodexHistoryStrip, type TurnCodexAccount } from "./run-input";
21
26
  import { TurnAttemptFencedError } from "./turn-attempt-fenced";
22
27
 
23
28
  export type MaybeCompactResult =
@@ -40,25 +45,23 @@ export type MaybeCompactResult =
40
45
  };
41
46
 
42
47
  /**
43
- * Durable portable context compaction, following Codex CLI's local path.
48
+ * Durable context compaction.
44
49
  *
45
- * Runs before a fresh model call and on a same-turn compaction recovery.
46
- * Reads the active history rows + the most recent provider-reported input
47
- * tokens, applies the single Codex-parity threshold, and - when it should -
48
- * summarizes the active history with the Codex checkpoint prompt. The write
49
- * supersedes the old active rows and inserts replacement active rows:
50
- * all real user messages plus one summary.
50
+ * Portable path: Codex CLI local plaintext checkpoint for every provider and
51
+ * for Codex sessions frozen on `portable`.
51
52
  *
52
- * Before sampling, a temporary copy is fitted by minimizing old tool outputs
53
- * and then removing whole oldest work units if necessary. One authoritative
54
- * provider overflow permits one smaller refit. Other failures propagate. There
55
- * is no non-model fallback or mutation of canonical history before success.
56
- *
57
- * There is no kept assistant/tool tail. Assistant messages,
58
- * tool calls/results, reasoning, and images stay only in inactive audit rows.
53
+ * Remote v2 path: when the session is frozen on `remote_v2` and the turn is
54
+ * Codex, call Codex `/codex/responses` with `compaction_trigger` and persist the
55
+ * opaque compaction item. Fail closed — never silently fall back to portable.
59
56
  */
60
57
  export type CompactionSummarizer = (settings: Settings, input: CompactionItem[]) => Promise<string>;
61
58
 
59
+ /** Returns the opaque Codex remote compaction v2 item. */
60
+ export type RemoteCompactionV2Requester = (
61
+ settings: Settings,
62
+ input: CompactionItem[],
63
+ ) => Promise<CompactionItem>;
64
+
62
65
  export async function maybeCompactContext(
63
66
  db: Database,
64
67
  settings: Settings,
@@ -82,8 +85,32 @@ export async function maybeCompactContext(
82
85
  force?: boolean;
83
86
  clearRequestedCompaction?: boolean;
84
87
  trigger?: "auto" | "operator" | "proactive" | "overflow";
88
+ codexAccount?: TurnCodexAccount;
89
+ /** Frozen session mode; remote_v2 selects the Codex opaque path. */
90
+ codexCompactionMode?: "remote_v2" | "portable";
91
+ /** True when this turn's resolved provider is codex-subscription. */
92
+ isCodexSubscriptionTurn?: boolean;
93
+ /** Injected remote requester; required for the remote_v2 branch. */
94
+ requestRemoteCompactionV2?: RemoteCompactionV2Requester;
95
+ /** Tag persisted history with the Codex credential that produced it. */
96
+ producerCodexCredentialId?: string | null;
97
+ /**
98
+ * Live fanout for the attempt-fenced `compaction.started` event so the
99
+ * timeline can show progress before the provider call returns. Must never
100
+ * append again — the event is already durable.
101
+ */
102
+ publishLiveEvents?: (events: SessionEvent[]) => Promise<void>;
85
103
  } = {},
86
104
  ): Promise<MaybeCompactResult> {
105
+ if (options.codexCompactionMode === "remote_v2" && options.isCodexSubscriptionTurn !== true) {
106
+ // Fail closed: a V2-locked session must never silently take the portable path
107
+ // (mixed history shapes). Admission should have blocked this already.
108
+ throw new Error(
109
+ "session is locked to Codex remote compaction v2 but this turn is not a Codex subscription turn",
110
+ );
111
+ }
112
+ const useRemoteV2 = options.codexCompactionMode === "remote_v2";
113
+
87
114
  const active = await getActiveSessionHistoryItems(db, scope.workspaceId, scope.sessionId);
88
115
  if (active.length === 0) {
89
116
  let requestConsumed = false;
@@ -107,10 +134,17 @@ export async function maybeCompactContext(
107
134
  requestConsumed,
108
135
  };
109
136
  }
110
- return { compacted: false, reason: "no_history", events: [], requestConsumed };
137
+ return {
138
+ compacted: false,
139
+ reason: "no_history",
140
+ events: [],
141
+ requestConsumed,
142
+ };
111
143
  }
112
144
 
113
- const items = sanitizeHistoryItemsForModel(active.map((row) => row.item) as CompactionItem[]);
145
+ const items = sanitizeHistoryItemsForModel(
146
+ applyCodexHistoryStrip(active, options.codexAccount ?? { currentCodexCredentialId: null }),
147
+ ) as CompactionItem[];
114
148
  const decision = decideCompaction({
115
149
  items,
116
150
  lastInputTokens,
@@ -129,6 +163,216 @@ export async function maybeCompactContext(
129
163
  };
130
164
  }
131
165
 
166
+ const trigger = options.trigger ?? "auto";
167
+ const estimatedTokensBefore = estimateTokens(items);
168
+ const started = await recordStartedContextCompaction(db, {
169
+ ...scope,
170
+ expectedExecutionGeneration: scope.executionGeneration,
171
+ expectedAttemptId: scope.attemptId,
172
+ trigger,
173
+ estimatedTokensBefore,
174
+ ...(useRemoteV2 ? { implementation: REMOTE_COMPACTION_V2_IMPLEMENTATION } : {}),
175
+ });
176
+ if (!started.recorded) {
177
+ throw new TurnAttemptFencedError(
178
+ `turn attempt was fenced while recording context compaction start: ${started.reason}`,
179
+ );
180
+ }
181
+ await options.publishLiveEvents?.(started.events);
182
+
183
+ if (useRemoteV2) {
184
+ const outcome = await compactContextRemoteV2(db, settings, scope, items, decision, options);
185
+ return prependCompactionEvents(started.events, outcome);
186
+ }
187
+
188
+ const outcome = await compactContextPortable(
189
+ db,
190
+ settings,
191
+ scope,
192
+ items,
193
+ decision,
194
+ summarize,
195
+ options,
196
+ );
197
+ return prependCompactionEvents(started.events, outcome);
198
+ }
199
+
200
+ /**
201
+ * After `compaction.started`, record a visible skip so the timeline cannot
202
+ * stick on "Compacting…". Used when the provider/summarizer throws a terminal
203
+ * (non-retryable) failure — including auto/overflow paths that never set
204
+ * `compactRequested`.
205
+ */
206
+ export async function settleFailedContextCompactionLandmark(
207
+ db: Database,
208
+ scope: {
209
+ accountId: string;
210
+ workspaceId: string;
211
+ sessionId: string;
212
+ turnId: string;
213
+ executionGeneration: number;
214
+ attemptId: string;
215
+ },
216
+ options: {
217
+ clearRequestedCompaction?: boolean;
218
+ publishLiveEvents?: (events: SessionEvent[]) => Promise<void>;
219
+ } = {},
220
+ ): Promise<Extract<MaybeCompactResult, { compacted: false }>> {
221
+ const settled = await settleSkippedAfterStart(db, scope, options, "summarization_failed");
222
+ await options.publishLiveEvents?.(settled.events);
223
+ return settled;
224
+ }
225
+
226
+ function prependCompactionEvents(
227
+ prefix: SessionEvent[],
228
+ outcome: MaybeCompactResult,
229
+ ): MaybeCompactResult {
230
+ if (prefix.length === 0) return outcome;
231
+ return { ...outcome, events: [...prefix, ...outcome.events] };
232
+ }
233
+
234
+ async function settleSkippedAfterStart(
235
+ db: Database,
236
+ scope: {
237
+ accountId: string;
238
+ workspaceId: string;
239
+ sessionId: string;
240
+ turnId: string;
241
+ executionGeneration: number;
242
+ attemptId: string;
243
+ },
244
+ options: {
245
+ clearRequestedCompaction?: boolean;
246
+ },
247
+ reason:
248
+ | "no_history"
249
+ | "replacement_not_smaller"
250
+ | "replacement_unchanged"
251
+ | "summarization_failed",
252
+ ): Promise<Extract<MaybeCompactResult, { compacted: false }>> {
253
+ const clearRequestedCompaction = options.clearRequestedCompaction === true;
254
+ const skipped = await recordSkippedContextCompaction(db, {
255
+ ...scope,
256
+ expectedExecutionGeneration: scope.executionGeneration,
257
+ expectedAttemptId: scope.attemptId,
258
+ reason,
259
+ // After `compaction.started`, always settle the landmark. Do not require
260
+ // an operator `/compact` flag — auto/overflow never set one.
261
+ requirePendingRequest: false,
262
+ clearRequestedCompaction,
263
+ });
264
+ if (!skipped.recorded) {
265
+ throw new TurnAttemptFencedError(
266
+ `turn attempt was fenced while recording a context compaction skip (${reason}): ${skipped.reason}`,
267
+ );
268
+ }
269
+ return {
270
+ compacted: false,
271
+ reason,
272
+ events: skipped.events,
273
+ requestConsumed: clearRequestedCompaction,
274
+ };
275
+ }
276
+
277
+ async function compactContextRemoteV2(
278
+ db: Database,
279
+ settings: Settings,
280
+ scope: {
281
+ accountId: string;
282
+ workspaceId: string;
283
+ sessionId: string;
284
+ turnId: string;
285
+ executionGeneration: number;
286
+ attemptId: string;
287
+ },
288
+ items: CompactionItem[],
289
+ decision: { signalTokens: number; thresholdTokens: number },
290
+ options: {
291
+ clearRequestedCompaction?: boolean;
292
+ trigger?: "auto" | "operator" | "proactive" | "overflow";
293
+ requestRemoteCompactionV2?: RemoteCompactionV2Requester;
294
+ producerCodexCredentialId?: string | null;
295
+ },
296
+ ): Promise<MaybeCompactResult> {
297
+ if (!options.requestRemoteCompactionV2) {
298
+ throw new EmptyCompactionSummaryError({
299
+ stage: "remote_v2_requester",
300
+ reason: "missing_requester",
301
+ });
302
+ }
303
+ const estimatedTokensBefore = estimateTokens(items);
304
+ // Codex remote_v2: on a valid compaction item, install and recompute usage.
305
+ // No local "must shrink / must differ" gate — that is portable-only.
306
+ // Fail closed on provider/extract failure — no portable fallback.
307
+ const compactionItem = await options.requestRemoteCompactionV2(settings, items);
308
+ const replacementHistory = buildRemoteV2ReplacementHistory(items, compactionItem);
309
+ const estimatedTokensAfter = estimateTokens(replacementHistory);
310
+ const replacementFingerprint = compactionReplacementFingerprint(replacementHistory);
311
+ const tailItem = replacementHistory.at(-1);
312
+ if (!tailItem) {
313
+ throw new EmptyCompactionSummaryError({
314
+ stage: "remote_v2_replacement",
315
+ reason: "no_replacement_history",
316
+ });
317
+ }
318
+ const applied = await applyContextCompaction(db, {
319
+ accountId: scope.accountId,
320
+ workspaceId: scope.workspaceId,
321
+ sessionId: scope.sessionId,
322
+ turnId: scope.turnId,
323
+ expectedExecutionGeneration: scope.executionGeneration,
324
+ expectedAttemptId: scope.attemptId,
325
+ replacementItems: replacementHistory.slice(0, -1),
326
+ summaryItem: tailItem as Record<string, unknown>,
327
+ replacementInputTokens: estimatedTokensAfter,
328
+ ...(options.clearRequestedCompaction ? { clearRequestedCompaction: true } : {}),
329
+ ...(options.producerCodexCredentialId
330
+ ? { producerCodexCredentialId: options.producerCodexCredentialId }
331
+ : {}),
332
+ eventPayload: {
333
+ trigger: options.trigger ?? "auto",
334
+ implementation: REMOTE_COMPACTION_V2_IMPLEMENTATION,
335
+ estimatedTokensBefore,
336
+ estimatedTokensAfter,
337
+ },
338
+ });
339
+ if (!applied.applied) {
340
+ throw new TurnAttemptFencedError(
341
+ `turn attempt was fenced during remote context compaction: ${applied.reason}`,
342
+ );
343
+ }
344
+ return {
345
+ compacted: true,
346
+ supersededFrom: applied.supersededFrom,
347
+ summaryPosition: applied.summaryPosition,
348
+ signalTokens: decision.signalTokens,
349
+ thresholdTokens: decision.thresholdTokens,
350
+ estimatedTokensBefore,
351
+ estimatedTokensAfter,
352
+ replacementFingerprint,
353
+ events: applied.events,
354
+ };
355
+ }
356
+
357
+ async function compactContextPortable(
358
+ db: Database,
359
+ settings: Settings,
360
+ scope: {
361
+ accountId: string;
362
+ workspaceId: string;
363
+ sessionId: string;
364
+ turnId: string;
365
+ executionGeneration: number;
366
+ attemptId: string;
367
+ },
368
+ items: CompactionItem[],
369
+ decision: { signalTokens: number; thresholdTokens: number },
370
+ summarize: CompactionSummarizer,
371
+ options: {
372
+ clearRequestedCompaction?: boolean;
373
+ trigger?: "auto" | "operator" | "proactive" | "overflow";
374
+ },
375
+ ): Promise<MaybeCompactResult> {
132
376
  const estimatedTokensBefore = estimateTokens(items);
133
377
  const summarized = await summarizeWithCodexOverflowTrimming(summarize, settings, items);
134
378
  const summaryBody = summarized.summaryBody;
@@ -138,70 +382,15 @@ export async function maybeCompactContext(
138
382
  const previousReplacementFingerprint = latestCompactionReplacementFingerprint(items);
139
383
  const summaryItem = replacementHistory.at(-1);
140
384
  if (!summaryItem) {
141
- return {
142
- compacted: false,
143
- reason: "compaction produced no replacement history",
144
- events: [],
145
- requestConsumed: false,
146
- };
385
+ // Started already fanout; settle visibly so the landmark cannot stick on
386
+ // "Compacting…". This is not an operator-request clear path.
387
+ return await settleSkippedAfterStart(db, scope, options, "summarization_failed");
147
388
  }
148
389
  if (previousReplacementFingerprint === replacementFingerprint) {
149
- let requestConsumed = false;
150
- if (options.clearRequestedCompaction) {
151
- const skipped = await recordSkippedContextCompaction(db, {
152
- ...scope,
153
- expectedExecutionGeneration: scope.executionGeneration,
154
- expectedAttemptId: scope.attemptId,
155
- reason: "replacement_unchanged",
156
- });
157
- if (!skipped.recorded) {
158
- throw new TurnAttemptFencedError(
159
- "turn attempt was fenced while consuming an unchanged context compaction request",
160
- );
161
- }
162
- requestConsumed = true;
163
- return {
164
- compacted: false,
165
- reason: "replacement_unchanged",
166
- events: skipped.events,
167
- requestConsumed,
168
- };
169
- }
170
- return {
171
- compacted: false,
172
- reason: "replacement_unchanged",
173
- events: [],
174
- requestConsumed,
175
- };
390
+ return await settleSkippedAfterStart(db, scope, options, "replacement_unchanged");
176
391
  }
177
392
  if (estimatedTokensAfter >= estimatedTokensBefore) {
178
- let requestConsumed = false;
179
- if (options.clearRequestedCompaction) {
180
- const skipped = await recordSkippedContextCompaction(db, {
181
- ...scope,
182
- expectedExecutionGeneration: scope.executionGeneration,
183
- expectedAttemptId: scope.attemptId,
184
- reason: "replacement_not_smaller",
185
- });
186
- if (!skipped.recorded) {
187
- throw new TurnAttemptFencedError(
188
- "turn attempt was fenced while consuming a non-shrinking context compaction request",
189
- );
190
- }
191
- requestConsumed = true;
192
- return {
193
- compacted: false,
194
- reason: "replacement_not_smaller",
195
- events: skipped.events,
196
- requestConsumed,
197
- };
198
- }
199
- return {
200
- compacted: false,
201
- reason: "replacement_not_smaller",
202
- events: [],
203
- requestConsumed,
204
- };
393
+ return await settleSkippedAfterStart(db, scope, options, "replacement_not_smaller");
205
394
  }
206
395
  const applied = await applyContextCompaction(db, {
207
396
  accountId: scope.accountId,
@@ -94,6 +94,7 @@ export async function mintSandboxToolspaceToken(
94
94
  subjectLabel: "sandbox toolspace",
95
95
  permissions: ["toolspace:call"],
96
96
  sessionId: authority.sessionId,
97
+ principalKind: "service",
97
98
  exp: expiresAtSeconds,
98
99
  });
99
100
  return { token, expiresAt: new Date(expiresAtSeconds * 1000) };
@@ -5,11 +5,13 @@ import {
5
5
  } from "@opengeni/config";
6
6
  import {
7
7
  evaluateWorkspaceModelPolicy,
8
+ latencyModeForMetadata,
8
9
  mergeToolRefs,
9
10
  reasoningEffortForMetadata,
10
11
  type SessionGoal,
11
12
  type ToolRef,
12
13
  } from "@opengeni/contracts";
14
+ import { isCodexBilledModel } from "@opengeni/codex";
13
15
  import {
14
16
  enqueueSessionWorkflowWakeIfRunnable,
15
17
  getBillingBalance,
@@ -65,6 +67,8 @@ export function createGoalActivities(services: () => Promise<ActivityServices>)
65
67
  const continuationReasoningEffort =
66
68
  latestStartedTurn?.reasoningEffort ??
67
69
  reasoningEffortForMetadata(session.metadata, settings.openaiReasoningEffort);
70
+ const continuationLatencyMode =
71
+ latestStartedTurn?.latencyMode ?? latencyModeForMetadata(session.metadata, "standard");
68
72
  // Workspace model policy: a continuation inherits the last STARTED turn's
69
73
  // model, so a single policy-violating turn would otherwise re-arm itself on
70
74
  // every continuation (exactly how one bare-model turn kept a goal loop on
@@ -89,6 +93,15 @@ export function createGoalActivities(services: () => Promise<ActivityServices>)
89
93
  }
90
94
  }
91
95
  }
96
+ // remote_v2 sessions may only continue on Codex models — refuse synthesis
97
+ // that would leave the portable/non-Codex path (and mixed history shapes).
98
+ if (
99
+ !modelPolicyBlocked &&
100
+ session.codexCompactionMode === "remote_v2" &&
101
+ !isCodexBilledModel(continuationModel)
102
+ ) {
103
+ modelPolicyBlocked = `session is locked to Codex remote compaction v2; model "${continuationModel}" is not a Codex subscription model`;
104
+ }
92
105
  // A codex-model goal continuation is paid by the user's ChatGPT/Codex plan,
93
106
  // so it must not be budget-paused for zero OpenGeni credits. This file uses
94
107
  // BASE settings (no codex overlay); the predicate does its own credential read.
@@ -122,6 +135,7 @@ export function createGoalActivities(services: () => Promise<ActivityServices>)
122
135
  policy: {
123
136
  model: continuationModel,
124
137
  reasoningEffort: continuationReasoningEffort,
138
+ latencyMode: continuationLatencyMode,
125
139
  tools: withFirstPartyTools(settings, session.tools),
126
140
  sandboxBackend: session.sandboxBackend,
127
141
  },
@@ -1,4 +1,5 @@
1
1
  import type { AccessGrant, Rig, RigChange, RigVersion } from "@opengeni/contracts";
2
+ import { sandboxArchiveCaptureTimeoutMs } from "@opengeni/config";
2
3
  import {
3
4
  recordRigAuditEvent,
4
5
  classifyRigVerificationOutcome,
@@ -492,6 +493,7 @@ export async function runWithOwnedRigVerificationSandbox<T>(
492
493
  rigVersionId: input.rigVersionId,
493
494
  leaseTtlMs: RIG_VERIFICATION_OWNER_TTL_MS,
494
495
  warmingLeaseTtlMs: RIG_VERIFICATION_OWNER_TTL_MS,
496
+ captureWaitMs: sandboxArchiveCaptureTimeoutMs(input.settings),
495
497
  });
496
498
  acquired = true;
497
499
  expectedEpoch = lease.lease.leaseEpoch;
@@ -58,12 +58,19 @@ const NON_CODEX_TURN: TurnCodexAccount = { currentCodexCredentialId: null };
58
58
  * non-codex turn over a history with no codex-produced reasoning.
59
59
  */
60
60
  export function applyCodexHistoryStrip(
61
- rows: ReadonlyArray<{ item: Record<string, unknown>; producerCodexCredentialId: string | null }>,
61
+ rows: ReadonlyArray<{
62
+ item: Record<string, unknown>;
63
+ producerCodexCredentialId: string | null;
64
+ providerArtifactInvalidatedAt?: Date | null;
65
+ }>,
62
66
  current: TurnCodexAccount,
63
67
  ): Array<Record<string, unknown>> {
64
68
  const out: Array<Record<string, unknown>> = [];
65
69
  for (const row of rows) {
66
- if (row.producerCodexCredentialId === current.currentCodexCredentialId) {
70
+ if (
71
+ row.producerCodexCredentialId === current.currentCodexCredentialId &&
72
+ !row.providerArtifactInvalidatedAt
73
+ ) {
67
74
  out.push(row.item);
68
75
  continue;
69
76
  }
@@ -106,10 +113,17 @@ export function applyCodexHistoryStrip(
106
113
  * turn), 400ing the resume.
107
114
  */
108
115
  export function resumeRunStateForCodexAccount(
109
- state: { serializedRunState: string; frozenCodexCredentialId: string | null },
116
+ state: {
117
+ serializedRunState: string;
118
+ frozenCodexCredentialId: string | null;
119
+ providerArtifactInvalidatedAt?: Date | null;
120
+ },
110
121
  current: TurnCodexAccount,
111
122
  ): string {
112
- if (state.frozenCodexCredentialId === current.currentCodexCredentialId) {
123
+ if (
124
+ state.frozenCodexCredentialId === current.currentCodexCredentialId &&
125
+ !state.providerArtifactInvalidatedAt
126
+ ) {
113
127
  return state.serializedRunState;
114
128
  }
115
129
  // Cross-account: neutralize reasoning identity in place AND flip frozen