@opengeni/worker-bundle 0.16.13 → 0.16.17
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/dist/activities/agent-turn.d.ts +10 -33
- package/dist/activities/codex-rotation.d.ts +5 -9
- package/dist/activities/context-compaction.d.ts +0 -4
- package/dist/activities/run-input.d.ts +16 -73
- package/dist/index.js +202 -215
- package/dist/index.js.map +1 -1
- package/dist/workflow-bundle.js +44 -28
- package/package.json +12 -12
- package/src/activities/agent-turn.ts +165 -183
- package/src/activities/codex-capacity.ts +0 -1
- package/src/activities/codex-rotation.ts +10 -83
- package/src/activities/context-compaction.ts +2 -12
- package/src/activities/run-input.ts +90 -150
- package/src/workflows/session.ts +55 -32
|
@@ -88,10 +88,7 @@ export function classifyCodexPin(args: {
|
|
|
88
88
|
export type RotationDecision =
|
|
89
89
|
// The chosen account. `moved` ⇒ it differs from the current active pointer, so
|
|
90
90
|
// the caller must persist the pointer move (and the switch is a "rotation").
|
|
91
|
-
|
|
92
|
-
// chosen account does NOT cover — populated ONLY on a Tier-2/unknown pick that
|
|
93
|
-
// can't cover (prefer-not-require: failover still happens, but the pill warns).
|
|
94
|
-
| { kind: "active"; credentialId: string; moved: boolean; droppedConnectors?: string[] }
|
|
91
|
+
| { kind: "active"; credentialId: string; moved: boolean }
|
|
95
92
|
// Every eligible account is capped/cooling: idle until the soonest instant ANY
|
|
96
93
|
// account clears every blocking condition (the multi-account generalization of
|
|
97
94
|
// the single-account idle-until-reset).
|
|
@@ -157,46 +154,10 @@ function cooling(acct: CodexRotationAccount, now: Date): boolean {
|
|
|
157
154
|
}
|
|
158
155
|
|
|
159
156
|
/**
|
|
160
|
-
*
|
|
161
|
-
* cached connector set is a SUPERSET of the session's used set. An empty used set is
|
|
162
|
-
* trivially covered by everyone (→ Tier 1 == all eligibles == byte-identical to P3).
|
|
163
|
-
* A null (never-probed) set is UNKNOWN: never credited as covering (Tier 2 only),
|
|
164
|
-
* but — critically — never excluded, so failover is fully preserved.
|
|
165
|
-
*/
|
|
166
|
-
function covers(acct: CodexRotationAccount, usedConnectors: string[]): boolean {
|
|
167
|
-
if (usedConnectors.length === 0) {
|
|
168
|
-
return true;
|
|
169
|
-
}
|
|
170
|
-
const owned = acct.connectorNamespaces;
|
|
171
|
-
if (owned === null) {
|
|
172
|
-
return false; // unprobed ⇒ unknown ⇒ never Tier 1 (but still a Tier-2 candidate)
|
|
173
|
-
}
|
|
174
|
-
const ownedSet = new Set(owned);
|
|
175
|
-
return usedConnectors.every((connector) => ownedSet.has(connector));
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
/**
|
|
179
|
-
* The used connectors the chosen account does NOT cover (the "switch dropped a
|
|
180
|
-
* connector" note). Empty when the account covers (superset) or nothing was used.
|
|
181
|
-
* A null (unknown) set surfaces ALL used connectors — we can't prove it covers them.
|
|
182
|
-
*/
|
|
183
|
-
function droppedConnectorsFor(acct: CodexRotationAccount, usedConnectors: string[]): string[] {
|
|
184
|
-
if (usedConnectors.length === 0) {
|
|
185
|
-
return [];
|
|
186
|
-
}
|
|
187
|
-
const owned = acct.connectorNamespaces;
|
|
188
|
-
if (owned === null) {
|
|
189
|
-
return [...usedConnectors];
|
|
190
|
-
}
|
|
191
|
-
const ownedSet = new Set(owned);
|
|
192
|
-
return usedConnectors.filter((connector) => !ownedSet.has(connector));
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
/**
|
|
196
|
-
* Healthy for an already-frozen/in-flight turn = connected/usable (status
|
|
157
|
+
* Healthy for an already-leased/in-flight turn = connected/usable (status
|
|
197
158
|
* "active", excludes needs_relogin/error), not cooling, and not exhausted in
|
|
198
159
|
* either provider window. Allocator eligibility is
|
|
199
|
-
* deliberately separate so disabling NEW work cannot break
|
|
160
|
+
* deliberately separate so disabling NEW work cannot break an existing live lease.
|
|
200
161
|
*/
|
|
201
162
|
export function isCodexCredentialHealthy(acct: CodexRotationAccount, now: Date): boolean {
|
|
202
163
|
return (
|
|
@@ -433,8 +394,8 @@ export const REACTIVE_PERSISTENCE_FAULT_FLOOR_MS = 5_000; // 5s
|
|
|
433
394
|
* Circuit-breaker slack (Finding 1b) added to the connected-account count to bound
|
|
434
395
|
* consecutive reactive failovers. Each legitimate failover cools one account, so
|
|
435
396
|
* after at most N failovers every account is capped and the reactive path takes the
|
|
436
|
-
* all-capped idle instead; the +margin absorbs benign re-ranks
|
|
437
|
-
*
|
|
397
|
+
* all-capped idle instead; the +margin absorbs benign capacity re-ranks without
|
|
398
|
+
* tripping the breaker in normal use.
|
|
438
399
|
*/
|
|
439
400
|
export const REACTIVE_ROTATION_MARGIN = 2;
|
|
440
401
|
/**
|
|
@@ -491,11 +452,6 @@ export function chooseRotationActive(args: {
|
|
|
491
452
|
priorCredentialId: string | null;
|
|
492
453
|
accounts: CodexRotationAccount[];
|
|
493
454
|
now: Date;
|
|
494
|
-
// P4 (Part B): the connectors the leaving session has access to (the leaving
|
|
495
|
-
// account's cached connector set, used as the "session needs these" proxy).
|
|
496
|
-
// Optional + defaults to [] ⇒ when absent/empty the ranker is BYTE-IDENTICAL to
|
|
497
|
-
// P3 (every account trivially covers → Tier 1 == all eligibles). Self-gating.
|
|
498
|
-
usedConnectors?: string[];
|
|
499
455
|
}): RotationDecision {
|
|
500
456
|
const { activeCredentialId, priorCredentialId, accounts, now } = args;
|
|
501
457
|
// Normalize at the entry point: rotation-enabled ALWAYS behaves as sharded
|
|
@@ -503,7 +459,6 @@ export function chooseRotationActive(args: {
|
|
|
503
459
|
// tests can still express stored legacy values.
|
|
504
460
|
const rotationStrategy = effectiveRotationStrategy(args.rotationStrategy);
|
|
505
461
|
const allocatableAccounts = accounts.filter((account) => account.allocatorEnabled);
|
|
506
|
-
const usedConnectors = args.usedConnectors ?? [];
|
|
507
462
|
|
|
508
463
|
if (allocatableAccounts.length === 0) {
|
|
509
464
|
return { kind: "none" };
|
|
@@ -523,14 +478,10 @@ export function chooseRotationActive(args: {
|
|
|
523
478
|
earliestResetAt: earliestReset(allocatableAccounts, now),
|
|
524
479
|
};
|
|
525
480
|
}
|
|
526
|
-
// P4: surface the dropped-connector note when the chosen account doesn't cover
|
|
527
|
-
// the session's used connectors (a Tier-2/unknown failover pick). Empty ⇒ omit.
|
|
528
|
-
const dropped = droppedConnectorsFor(chosen, usedConnectors);
|
|
529
481
|
return {
|
|
530
482
|
kind: "active",
|
|
531
483
|
credentialId: chosen.id,
|
|
532
484
|
moved: chosen.id !== activeCredentialId,
|
|
533
|
-
...(dropped.length > 0 ? { droppedConnectors: dropped } : {}),
|
|
534
485
|
};
|
|
535
486
|
};
|
|
536
487
|
|
|
@@ -568,26 +519,20 @@ export function chooseRotationActive(args: {
|
|
|
568
519
|
return decide(eligibles[0]);
|
|
569
520
|
}
|
|
570
521
|
|
|
571
|
-
// most_remaining (default + the correctness path).
|
|
572
|
-
// the SAME eligible set (prefer-not-require):
|
|
573
|
-
// Tier 1 — eligibles whose connector set COVERS the session's used set.
|
|
574
|
-
// Tier 2 — ALL eligibles, only if Tier 1 is empty (failover fully preserved).
|
|
575
|
-
// Within the chosen tier:
|
|
522
|
+
// most_remaining (default + the correctness path). Across the eligible set:
|
|
576
523
|
// 1. least active leases (concurrent turns spread before quota metadata moves),
|
|
577
524
|
// 2. most remaining binding quota,
|
|
578
525
|
// 3. fewest historical selections,
|
|
579
526
|
// 4. least-recently selected, then stable created_at/id input order.
|
|
580
527
|
// Base CodexAccountStatus values (pure legacy tests/reactive rank) default the
|
|
581
528
|
// lease/cursor metadata to zero/null, preserving deterministic stable ties.
|
|
582
|
-
const covering = eligibles.filter((acct) => covers(acct, usedConnectors));
|
|
583
|
-
const pool = covering.length > 0 ? covering : eligibles;
|
|
584
529
|
const activeLeases = (acct: CodexRotationAccount): number =>
|
|
585
530
|
"activeLeaseCount" in acct ? acct.activeLeaseCount : 0;
|
|
586
531
|
const selections = (acct: CodexRotationAccount): number =>
|
|
587
532
|
"selectionCount" in acct ? acct.selectionCount : 0;
|
|
588
533
|
const lastSelected = (acct: CodexRotationAccount): number =>
|
|
589
534
|
"lastSelectedAt" in acct && acct.lastSelectedAt ? acct.lastSelectedAt.getTime() : 0;
|
|
590
|
-
const chosen =
|
|
535
|
+
const chosen = eligibles.reduce<CodexRotationAccount | undefined>((best, acct) => {
|
|
591
536
|
if (!best) {
|
|
592
537
|
return acct;
|
|
593
538
|
}
|
|
@@ -613,7 +558,7 @@ export function chooseRotationActive(args: {
|
|
|
613
558
|
* the same until BOTH the deployment flag and workspace cutover are enabled;
|
|
614
559
|
* otherwise a rolling fleet would run two allocators at once. When the active
|
|
615
560
|
* pointer is no longer eligible, zeroing the additive metadata delegates to the
|
|
616
|
-
* same capacity
|
|
561
|
+
* same capacity ranking that the old selector used.
|
|
617
562
|
*/
|
|
618
563
|
export function chooseLegacyRotationActive(
|
|
619
564
|
args: Parameters<typeof chooseRotationActive>[0],
|
|
@@ -650,8 +595,6 @@ export function selectCodexCredentialLeaseForTurn(args: {
|
|
|
650
595
|
sessionPinnedCredentialId: string | null;
|
|
651
596
|
sessionPinSource: CodexPinSource | null;
|
|
652
597
|
sessionLastCredentialId: string | null;
|
|
653
|
-
/** Same-turn checkpoint/frozen account; temporary disable cannot move it. */
|
|
654
|
-
continuationCredentialId?: string | null;
|
|
655
598
|
now: Date;
|
|
656
599
|
}): CodexTurnLeaseSelection {
|
|
657
600
|
const {
|
|
@@ -681,21 +624,6 @@ export function selectCodexCredentialLeaseForTurn(args: {
|
|
|
681
624
|
};
|
|
682
625
|
}
|
|
683
626
|
|
|
684
|
-
const continuation = args.continuationCredentialId
|
|
685
|
-
? accounts.find((account) => account.id === args.continuationCredentialId)
|
|
686
|
-
: undefined;
|
|
687
|
-
if (continuation && isCodexCredentialHealthy(continuation, args.now)) {
|
|
688
|
-
return {
|
|
689
|
-
credentialId: continuation.id,
|
|
690
|
-
advanceActivePointer: false,
|
|
691
|
-
decision: {
|
|
692
|
-
kind: "active",
|
|
693
|
-
credentialId: continuation.id,
|
|
694
|
-
moved: continuation.id !== activeCredentialId,
|
|
695
|
-
},
|
|
696
|
-
};
|
|
697
|
-
}
|
|
698
|
-
|
|
699
627
|
const connectedIds = new Set(
|
|
700
628
|
accounts.filter((account) => account.allocatorEnabled).map((account) => account.id),
|
|
701
629
|
);
|
|
@@ -708,8 +636,8 @@ export function selectCodexCredentialLeaseForTurn(args: {
|
|
|
708
636
|
});
|
|
709
637
|
|
|
710
638
|
// A manual pin is user intent, not a policy hint. Never silently fail it over.
|
|
711
|
-
// We still reject allocator-disabled rows for a NEW turn; healthy live
|
|
712
|
-
// same-turn
|
|
639
|
+
// We still reject allocator-disabled rows for a NEW turn; a healthy live
|
|
640
|
+
// same-turn lease already returned above before this admission filter.
|
|
713
641
|
if (pinDisposition === "manual" && args.sessionPinnedCredentialId) {
|
|
714
642
|
const pinned = accounts.find((account) => account.id === args.sessionPinnedCredentialId);
|
|
715
643
|
if (!pinned?.allocatorEnabled) {
|
|
@@ -802,7 +730,6 @@ export function selectCodexCredentialLeaseForTurn(args: {
|
|
|
802
730
|
priorCredentialId: priorId,
|
|
803
731
|
accounts,
|
|
804
732
|
now: args.now,
|
|
805
|
-
usedConnectors: accounts.find((account) => account.id === priorId)?.connectorNamespaces ?? [],
|
|
806
733
|
});
|
|
807
734
|
return {
|
|
808
735
|
credentialId: decision.kind === "active" ? decision.credentialId : null,
|
|
@@ -22,7 +22,7 @@ import {
|
|
|
22
22
|
} from "@opengeni/runtime";
|
|
23
23
|
import { contextInputBudgetTokens, type Settings } from "@opengeni/config";
|
|
24
24
|
import type { SessionEvent } from "@opengeni/contracts";
|
|
25
|
-
import {
|
|
25
|
+
import { projectRejectedProviderArtifacts } from "./run-input";
|
|
26
26
|
import { TurnAttemptFencedError } from "./turn-attempt-fenced";
|
|
27
27
|
|
|
28
28
|
export type MaybeCompactResult =
|
|
@@ -85,15 +85,12 @@ export async function maybeCompactContext(
|
|
|
85
85
|
force?: boolean;
|
|
86
86
|
clearRequestedCompaction?: boolean;
|
|
87
87
|
trigger?: "auto" | "operator" | "proactive" | "overflow";
|
|
88
|
-
codexAccount?: TurnCodexAccount;
|
|
89
88
|
/** Frozen session mode; remote_v2 selects the Codex opaque path. */
|
|
90
89
|
codexCompactionMode?: "remote_v2" | "portable";
|
|
91
90
|
/** True when this turn's resolved provider is codex-subscription. */
|
|
92
91
|
isCodexSubscriptionTurn?: boolean;
|
|
93
92
|
/** Injected remote requester; required for the remote_v2 branch. */
|
|
94
93
|
requestRemoteCompactionV2?: RemoteCompactionV2Requester;
|
|
95
|
-
/** Tag persisted history with the Codex credential that produced it. */
|
|
96
|
-
producerCodexCredentialId?: string | null;
|
|
97
94
|
/**
|
|
98
95
|
* Live fanout for the attempt-fenced `compaction.started` event so the
|
|
99
96
|
* timeline can show progress before the provider call returns. Must never
|
|
@@ -144,10 +141,7 @@ export async function maybeCompactContext(
|
|
|
144
141
|
};
|
|
145
142
|
}
|
|
146
143
|
|
|
147
|
-
const canonicalItems =
|
|
148
|
-
active,
|
|
149
|
-
options.codexAccount ?? { currentCodexCredentialId: null },
|
|
150
|
-
) as CompactionItem[];
|
|
144
|
+
const canonicalItems = projectRejectedProviderArtifacts(active) as CompactionItem[];
|
|
151
145
|
const projectForWire = async (input: CompactionItem[]): Promise<CompactionItem[]> =>
|
|
152
146
|
sanitizeHistoryItemsForModel(
|
|
153
147
|
options.projectModelInput ? await options.projectModelInput(input) : input,
|
|
@@ -312,7 +306,6 @@ async function compactContextRemoteV2(
|
|
|
312
306
|
clearRequestedCompaction?: boolean;
|
|
313
307
|
trigger?: "auto" | "operator" | "proactive" | "overflow";
|
|
314
308
|
requestRemoteCompactionV2?: RemoteCompactionV2Requester;
|
|
315
|
-
producerCodexCredentialId?: string | null;
|
|
316
309
|
},
|
|
317
310
|
projectForWire: (items: CompactionItem[]) => Promise<CompactionItem[]>,
|
|
318
311
|
): Promise<MaybeCompactResult> {
|
|
@@ -348,9 +341,6 @@ async function compactContextRemoteV2(
|
|
|
348
341
|
summaryItem: tailItem as Record<string, unknown>,
|
|
349
342
|
replacementInputTokens: estimatedTokensAfter,
|
|
350
343
|
...(options.clearRequestedCompaction ? { clearRequestedCompaction: true } : {}),
|
|
351
|
-
...(options.producerCodexCredentialId
|
|
352
|
-
? { producerCodexCredentialId: options.producerCodexCredentialId }
|
|
353
|
-
: {}),
|
|
354
344
|
eventPayload: {
|
|
355
345
|
trigger: options.trigger ?? "auto",
|
|
356
346
|
implementation: REMOTE_COMPACTION_V2_IMPLEMENTATION,
|
|
@@ -18,88 +18,33 @@ import {
|
|
|
18
18
|
type Database,
|
|
19
19
|
} from "@opengeni/db";
|
|
20
20
|
import {
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
21
|
+
projectHistoryForProvider,
|
|
22
|
+
projectRejectedProviderArtifactsFromSerializedRunState,
|
|
23
|
+
projectRejectedReasoningArtifact,
|
|
24
|
+
hasOpaqueProviderArtifact,
|
|
25
|
+
type HistoryProviderApi,
|
|
24
26
|
type OpenGeniRuntime,
|
|
25
27
|
} from "@opengeni/runtime";
|
|
26
28
|
|
|
27
|
-
/**
|
|
28
|
-
|
|
29
|
-
* cross-account turn never replays another account's encrypted reasoning. The
|
|
30
|
-
* single rule across all paths: DROP any reasoning item whose producing codex
|
|
31
|
-
* account differs from `currentCodexCredentialId`.
|
|
32
|
-
*
|
|
33
|
-
* `currentCodexCredentialId` is the resolved codex credential id on a codex turn,
|
|
34
|
-
* or NULL on a non-codex turn (the "account" of the built-in Azure/OpenAI path).
|
|
35
|
-
* NULL is a real value in the comparison, not a "skip" sentinel: a non-codex turn
|
|
36
|
-
* (current = null) still drops codex-produced reasoning (producer != null) so a
|
|
37
|
-
* foreign encrypted blob never reaches the Azure/built-in Responses call. A
|
|
38
|
-
* session with no codex history (every producer == null == current) is a no-op.
|
|
39
|
-
*/
|
|
40
|
-
export type TurnCodexAccount = { currentCodexCredentialId: string | null };
|
|
41
|
-
|
|
42
|
-
/** A non-codex turn's account (current = null): no codex credential resolved. */
|
|
43
|
-
const NON_CODEX_TURN: TurnCodexAccount = { currentCodexCredentialId: null };
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* Apply the cross-account reasoning strip to a set of stored history rows. Pure +
|
|
47
|
-
* non-mutating. The single rule: a row whose producing codex account EQUALS the
|
|
48
|
-
* turn's current account replays verbatim (by reference); a row produced by a
|
|
49
|
-
* DIFFERENT account is treated by item type —
|
|
50
|
-
*
|
|
51
|
-
* - `reasoning` → DROPPED WHOLE (id + blob filtered out of the history). The
|
|
52
|
-
* foreign `rs_…` id is validated by the Responses backend, which rejects a
|
|
53
|
-
* reasoning item that has a foreign id and no encrypted_content (store:false),
|
|
54
|
-
* so blanking only the blob is not enough — the whole item must go.
|
|
55
|
-
* - `compaction` → kept, with only its account-bound `encrypted_content` blob
|
|
56
|
-
* stripped (its summary is real conversation content that must survive).
|
|
57
|
-
* - everything else (messages, tool calls, tool outputs) → kept verbatim by
|
|
58
|
-
* reference; message and tool content are never account-bound, never touched.
|
|
59
|
-
*
|
|
60
|
-
* Mismatch covers a foreign codex account, the non-codex/Azure producer (null on
|
|
61
|
-
* a codex turn), and legacy untagged rows (null): all are stripped, which is
|
|
62
|
-
* defensive and harmless (at most one turn of lost chain-of-thought continuity,
|
|
63
|
-
* never any content). No-op (rows by reference) when every producer equals the
|
|
64
|
-
* current account — a single-account workspace, an unchanged-account turn, or a
|
|
65
|
-
* non-codex turn over a history with no codex-produced reasoning.
|
|
66
|
-
*/
|
|
67
|
-
export function applyCodexHistoryStrip(
|
|
29
|
+
/** Project only artifacts explicitly rejected by the provider out of its next view. */
|
|
30
|
+
export function projectRejectedProviderArtifacts(
|
|
68
31
|
rows: ReadonlyArray<{
|
|
69
32
|
item: Record<string, unknown>;
|
|
70
|
-
producerCodexCredentialId: string | null;
|
|
71
33
|
providerArtifactInvalidatedAt?: Date | null;
|
|
72
34
|
}>,
|
|
73
|
-
current: TurnCodexAccount,
|
|
74
35
|
): Array<Record<string, unknown>> {
|
|
75
36
|
const out: Array<Record<string, unknown>> = [];
|
|
76
37
|
for (const row of rows) {
|
|
77
|
-
if (
|
|
78
|
-
row.producerCodexCredentialId === current.currentCodexCredentialId &&
|
|
79
|
-
!row.providerArtifactInvalidatedAt
|
|
80
|
-
) {
|
|
38
|
+
if (!row.providerArtifactInvalidatedAt) {
|
|
81
39
|
out.push(row.item);
|
|
82
40
|
continue;
|
|
83
41
|
}
|
|
84
42
|
const type = typeof row.item.type === "string" ? row.item.type : undefined;
|
|
85
43
|
if (type === "reasoning") {
|
|
86
|
-
|
|
87
|
-
continue;
|
|
88
|
-
}
|
|
89
|
-
if (type === "tool_search_call" || type === "tool_search_output") {
|
|
90
|
-
// Foreign tool_search items (progressive connector disclosure): drop WHOLE,
|
|
91
|
-
// like reasoning. The `tsc_…` id is minted by the producing account's
|
|
92
|
-
// backend, and the output's disclosure set reflects THAT account's
|
|
93
|
-
// connectors — replaying either into a different account risks a 400 /
|
|
94
|
-
// wrong-connector disclosure. Dropping both sides keeps the pair invariant
|
|
95
|
-
// (the history sanitizer would drop a stranded half anyway); the model
|
|
96
|
-
// simply re-searches on the new account, re-disclosing from the NEW
|
|
97
|
-
// account's own connector pool. Never any content loss — search items
|
|
98
|
-
// carry tool metadata, not conversation content.
|
|
44
|
+
out.push(projectRejectedReasoningArtifact(row.item));
|
|
99
45
|
continue;
|
|
100
46
|
}
|
|
101
47
|
if (type === "compaction") {
|
|
102
|
-
out.push(stripReasoningEncryptedContent(row.item));
|
|
103
48
|
continue;
|
|
104
49
|
}
|
|
105
50
|
out.push(row.item);
|
|
@@ -107,60 +52,26 @@ export function applyCodexHistoryStrip(
|
|
|
107
52
|
return out;
|
|
108
53
|
}
|
|
109
54
|
|
|
110
|
-
/**
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
* (encrypted_content + provider id) in the blob; when they match (including
|
|
117
|
-
* null == null for non-codex / single-account) the blob replays byte-for-byte
|
|
118
|
-
* (same string reference). This closes the gap where a frozen A-minted RunState
|
|
119
|
-
* was replayed verbatim into a turn that switched to account B (or to a non-codex
|
|
120
|
-
* turn), 400ing the resume.
|
|
121
|
-
*/
|
|
122
|
-
export function resumeRunStateForCodexAccount(
|
|
123
|
-
state: {
|
|
124
|
-
serializedRunState: string;
|
|
125
|
-
frozenCodexCredentialId: string | null;
|
|
126
|
-
providerArtifactInvalidatedAt?: Date | null;
|
|
127
|
-
},
|
|
128
|
-
current: TurnCodexAccount,
|
|
129
|
-
): string {
|
|
130
|
-
if (
|
|
131
|
-
state.frozenCodexCredentialId === current.currentCodexCredentialId &&
|
|
132
|
-
!state.providerArtifactInvalidatedAt
|
|
133
|
-
) {
|
|
55
|
+
/** Build the attempt-local RunState view after an explicit provider rejection. */
|
|
56
|
+
export function resumeRunState(state: {
|
|
57
|
+
serializedRunState: string;
|
|
58
|
+
providerArtifactInvalidatedAt?: Date | null;
|
|
59
|
+
}): string {
|
|
60
|
+
if (!state.providerArtifactInvalidatedAt) {
|
|
134
61
|
return state.serializedRunState;
|
|
135
62
|
}
|
|
136
|
-
|
|
137
|
-
// tool_search pairs to execution:"server" in place (count-preserving — HOLE E
|
|
138
|
-
// forbids removing blob items). The server flip makes the SDK skip its
|
|
139
|
-
// client-executor rehydration (which would THROW when the resuming account's
|
|
140
|
-
// connector pool differs from the freezing account's); the flipped shape is
|
|
141
|
-
// live-verified wire-safe. The model can still re-search on this account.
|
|
142
|
-
return neutralizeToolSearchItemsInSerializedRunState(
|
|
143
|
-
stripReasoningIdentityFromSerializedRunState(state.serializedRunState),
|
|
144
|
-
);
|
|
63
|
+
return projectRejectedProviderArtifactsFromSerializedRunState(state.serializedRunState);
|
|
145
64
|
}
|
|
146
65
|
|
|
147
|
-
/**
|
|
148
|
-
* A prepared turn input plus the watermark-seed discriminator the reconcile pass
|
|
149
|
-
* needs (HOLE E). `modelHistoryFromItems` is TRUE iff `state.history` was seeded
|
|
150
|
-
* from the cross-account-STRIPPED active history items (the items read path) — so
|
|
151
|
-
* the turn-end reconcile must seed `persistedHistoryCount` from the SAME strip
|
|
152
|
-
* (HOLE D). It is FALSE only when `state.history` was seeded from the approval
|
|
153
|
-
* RunState: there
|
|
154
|
-
* foreign reasoning is NEUTRALIZED-IN-PLACE by {@link resumeRunStateForCodexAccount}
|
|
155
|
-
* (the item is KEPT, only its id/encrypted_content go), so the blob's history
|
|
156
|
-
* length still COUNTS those items. Seeding the watermark with the strip on that
|
|
157
|
-
* path under-counts by K and the reconcile re-appends K already-persisted items at
|
|
158
|
-
* fresh positions — that is HOLE E. The watermark must therefore NOT strip on the
|
|
159
|
-
* blob path (count the raw sanitized active length, matching the blob).
|
|
160
|
-
*/
|
|
66
|
+
/** Prepared input and its exact durable-history prefix length for reconciliation. */
|
|
161
67
|
export type PreparedTurnInput = {
|
|
162
68
|
input: Awaited<ReturnType<OpenGeniRuntime["prepareInput"]>>;
|
|
163
|
-
|
|
69
|
+
persistedHistoryCount: number;
|
|
70
|
+
providerArtifactCandidates: {
|
|
71
|
+
knownHistoryItemIds: string[];
|
|
72
|
+
historyItemIds: string[];
|
|
73
|
+
runStateId?: string;
|
|
74
|
+
};
|
|
164
75
|
};
|
|
165
76
|
|
|
166
77
|
export type TurnInputOptions = {
|
|
@@ -168,6 +79,7 @@ export type TurnInputOptions = {
|
|
|
168
79
|
recovering?: boolean;
|
|
169
80
|
unavailableSandboxFilesNote?: string;
|
|
170
81
|
runCredentialsNote?: string;
|
|
82
|
+
providerApi: HistoryProviderApi;
|
|
171
83
|
projectModelHistory?: ModelHistoryAttachmentProjector;
|
|
172
84
|
};
|
|
173
85
|
|
|
@@ -457,7 +369,6 @@ export async function turnInput(
|
|
|
457
369
|
runtime: OpenGeniRuntime,
|
|
458
370
|
agent: any,
|
|
459
371
|
trigger: Awaited<ReturnType<typeof getSessionEvent>>,
|
|
460
|
-
current: TurnCodexAccount = NON_CODEX_TURN,
|
|
461
372
|
options: TurnInputOptions,
|
|
462
373
|
): Promise<PreparedTurnInput> {
|
|
463
374
|
if (!trigger) {
|
|
@@ -506,8 +417,8 @@ export async function turnInput(
|
|
|
506
417
|
trigger,
|
|
507
418
|
undefined,
|
|
508
419
|
joinInternalContext(internalContext, attachmentContext),
|
|
509
|
-
current,
|
|
510
420
|
fileAttachments.map((attachment) => attachment.resource),
|
|
421
|
+
options.providerApi,
|
|
511
422
|
options.projectModelHistory,
|
|
512
423
|
);
|
|
513
424
|
}
|
|
@@ -515,7 +426,17 @@ export async function turnInput(
|
|
|
515
426
|
if (updates.length === 0) {
|
|
516
427
|
throw new Error("Internal update inference has no delivered updates");
|
|
517
428
|
}
|
|
518
|
-
return await messageInput(
|
|
429
|
+
return await messageInput(
|
|
430
|
+
db,
|
|
431
|
+
runtime,
|
|
432
|
+
agent,
|
|
433
|
+
trigger,
|
|
434
|
+
undefined,
|
|
435
|
+
internalContext,
|
|
436
|
+
[],
|
|
437
|
+
options.providerApi,
|
|
438
|
+
options.projectModelHistory,
|
|
439
|
+
);
|
|
519
440
|
}
|
|
520
441
|
if (trigger.type === "user.approvalDecision") {
|
|
521
442
|
const payload = trigger.payload as {
|
|
@@ -529,22 +450,21 @@ export async function turnInput(
|
|
|
529
450
|
if (!state) {
|
|
530
451
|
throw new Error("No saved run state is available for approval decision");
|
|
531
452
|
}
|
|
453
|
+
const prepared = await runtime.prepareInput(agent, {
|
|
454
|
+
kind: "approval",
|
|
455
|
+
serializedRunState: resumeRunState(state),
|
|
456
|
+
approvalId: String(payload.approvalId ?? ""),
|
|
457
|
+
decision: payload.decision === "approve" ? "approve" : "reject",
|
|
458
|
+
...(typeof payload.message === "string" ? { message: payload.message } : {}),
|
|
459
|
+
});
|
|
532
460
|
return {
|
|
533
|
-
input:
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
decision: payload.decision === "approve" ? "approve" : "reject",
|
|
541
|
-
...(typeof payload.message === "string" ? { message: payload.message } : {}),
|
|
542
|
-
}),
|
|
543
|
-
// Model seeded from the run-state BLOB (neutralize-in-place), NOT stripped
|
|
544
|
-
// items: the reconcile watermark must NOT apply the cross-account strip
|
|
545
|
-
// (HOLE E) — else a cross-account approval resume re-appends K
|
|
546
|
-
// already-persisted items at fresh positions.
|
|
547
|
-
modelHistoryFromItems: false,
|
|
461
|
+
input: prepared,
|
|
462
|
+
persistedHistoryCount: prepared.persistedHistoryCount,
|
|
463
|
+
providerArtifactCandidates: {
|
|
464
|
+
knownHistoryItemIds: [],
|
|
465
|
+
historyItemIds: [],
|
|
466
|
+
runStateId: state.id,
|
|
467
|
+
},
|
|
548
468
|
};
|
|
549
469
|
}
|
|
550
470
|
if (trigger.type === "user.humanInputResponse") {
|
|
@@ -558,13 +478,19 @@ export async function turnInput(
|
|
|
558
478
|
if (!resume) {
|
|
559
479
|
throw new Error("Human-input response does not resolve to a durable request");
|
|
560
480
|
}
|
|
481
|
+
const prepared = await runtime.prepareInput(agent, {
|
|
482
|
+
kind: "human_input",
|
|
483
|
+
serializedRunState: resumeRunState(state),
|
|
484
|
+
toolCallId: resume.toolCallId,
|
|
485
|
+
});
|
|
561
486
|
return {
|
|
562
|
-
input:
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
487
|
+
input: prepared,
|
|
488
|
+
persistedHistoryCount: prepared.persistedHistoryCount,
|
|
489
|
+
providerArtifactCandidates: {
|
|
490
|
+
knownHistoryItemIds: [],
|
|
491
|
+
historyItemIds: [],
|
|
492
|
+
runStateId: state.id,
|
|
493
|
+
},
|
|
568
494
|
};
|
|
569
495
|
}
|
|
570
496
|
throw new Error(`Unsupported trigger event type: ${trigger.type}`);
|
|
@@ -583,29 +509,43 @@ async function messageInput(
|
|
|
583
509
|
trigger: NonNullable<Awaited<ReturnType<typeof getSessionEvent>>>,
|
|
584
510
|
text: string | undefined,
|
|
585
511
|
internalContext: string | undefined,
|
|
586
|
-
current: TurnCodexAccount = NON_CODEX_TURN,
|
|
587
512
|
currentAttachmentRefs: FileResourceRef[] = [],
|
|
513
|
+
providerApi: HistoryProviderApi = "responses",
|
|
588
514
|
projectModelHistory?: ModelHistoryAttachmentProjector,
|
|
589
515
|
): Promise<PreparedTurnInput> {
|
|
590
516
|
const stored = await getActiveSessionHistoryItems(db, trigger.workspaceId, trigger.sessionId);
|
|
591
517
|
const envelope = await getSandboxSessionEnvelope(db, trigger.workspaceId, trigger.sessionId);
|
|
592
|
-
const
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
);
|
|
518
|
+
const canonicalView = projectRejectedProviderArtifacts(stored);
|
|
519
|
+
const providerView = projectHistoryForProvider(canonicalView, providerApi);
|
|
520
|
+
const referencedHistory = withCurrentUserAttachmentRefs(providerView, currentAttachmentRefs);
|
|
596
521
|
const historyItems = projectModelHistory
|
|
597
522
|
? await projectModelHistory(referencedHistory)
|
|
598
523
|
: referencedHistory;
|
|
524
|
+
const prepared = await runtime.prepareInput(agent, {
|
|
525
|
+
kind: "message",
|
|
526
|
+
...(text ? { text } : {}),
|
|
527
|
+
...(internalContext ? { internalContext } : {}),
|
|
528
|
+
historyItems: historyItems as any,
|
|
529
|
+
sandboxEnvelope: envelope,
|
|
530
|
+
...(projectModelHistory ? { modelInputAlreadyProjected: true } : {}),
|
|
531
|
+
});
|
|
532
|
+
const preparedItems = Array.isArray(prepared.input)
|
|
533
|
+
? new Set(prepared.input)
|
|
534
|
+
: new Set<unknown>();
|
|
599
535
|
return {
|
|
600
|
-
input:
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
536
|
+
input: prepared,
|
|
537
|
+
persistedHistoryCount: prepared.persistedHistoryCount,
|
|
538
|
+
providerArtifactCandidates: {
|
|
539
|
+
knownHistoryItemIds: stored.map((row) => row.id),
|
|
540
|
+
historyItemIds: stored
|
|
541
|
+
.filter(
|
|
542
|
+
(row) =>
|
|
543
|
+
row.providerArtifactInvalidatedAt === null &&
|
|
544
|
+
hasOpaqueProviderArtifact(row.item) &&
|
|
545
|
+
preparedItems.has(row.item),
|
|
546
|
+
)
|
|
547
|
+
.map((row) => row.id),
|
|
548
|
+
},
|
|
609
549
|
};
|
|
610
550
|
}
|
|
611
551
|
|