@opengeni/worker-bundle 0.16.14 → 0.16.21
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 +33 -52
- package/dist/activities/codex-rotation.d.ts +5 -9
- package/dist/activities/context-compaction.d.ts +0 -4
- package/dist/activities/file-upload-reaper.d.ts +6 -0
- package/dist/activities/run-input.d.ts +16 -73
- package/dist/index.js +350 -278
- 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 +242 -257
- package/src/activities/codex-capacity.ts +0 -1
- package/src/activities/codex-rotation.ts +10 -83
- package/src/activities/context-compaction.ts +2 -14
- package/src/activities/file-upload-reaper.ts +108 -7
- package/src/activities/run-input.ts +90 -150
- package/src/activities/sandbox-lease.ts +5 -2
- package/src/sandbox-routing.ts +5 -2
- package/src/workflows/session.ts +55 -32
|
@@ -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
|
|
|
@@ -95,6 +95,7 @@ import {
|
|
|
95
95
|
resolveModalCheckpointProviderBindingForLiveSandbox,
|
|
96
96
|
resolveModalCheckpointProviderBinding,
|
|
97
97
|
resolveModalCheckpointProviderBindingForSession,
|
|
98
|
+
sandboxBackendForSdkBackendId,
|
|
98
99
|
sandboxCommandExitCode,
|
|
99
100
|
sandboxCommandStillRunning,
|
|
100
101
|
sweepModalOrphanSandboxes,
|
|
@@ -1428,7 +1429,8 @@ async function probeDrainableProviderReadiness(
|
|
|
1428
1429
|
if (!lease.instanceId || !lease.resumeState) {
|
|
1429
1430
|
throw new Error("Expired workspace capture has no resumable provider identity");
|
|
1430
1431
|
}
|
|
1431
|
-
const
|
|
1432
|
+
const durableBackendId = (lease.resumeBackendId ?? lease.backend) as string;
|
|
1433
|
+
const backend = sandboxBackendForSdkBackendId(durableBackendId) ?? durableBackendId;
|
|
1432
1434
|
let established: Awaited<ReturnType<typeof establishSandboxSessionFromEnvelope>>;
|
|
1433
1435
|
try {
|
|
1434
1436
|
established = await establishSandboxSessionFromEnvelope(settings, lease.resumeState, {
|
|
@@ -1811,7 +1813,8 @@ export async function terminateProviderBox(
|
|
|
1811
1813
|
persistArchive: PersistArchiveFn,
|
|
1812
1814
|
createClientForBackend: CreateSandboxClientForBackendFn = createSandboxClientForBackend,
|
|
1813
1815
|
): Promise<ProviderTerminationOutcome> {
|
|
1814
|
-
const
|
|
1816
|
+
const durableBackendId = (lease.resumeBackendId ?? lease.backend) as string;
|
|
1817
|
+
const backend = sandboxBackendForSdkBackendId(durableBackendId) ?? durableBackendId;
|
|
1815
1818
|
// 'none' / no backend -> nothing to terminate.
|
|
1816
1819
|
if (!backend || backend === "none") {
|
|
1817
1820
|
return { terminated: true, providerMissingBeforeCapture: false };
|
package/src/sandbox-routing.ts
CHANGED
|
@@ -44,6 +44,7 @@ import {
|
|
|
44
44
|
RoutingBackendRecoveryRequiredError,
|
|
45
45
|
RoutingSandboxSession,
|
|
46
46
|
resolveModalCheckpointProviderBindingForSession,
|
|
47
|
+
sandboxBackendForSdkBackendId,
|
|
47
48
|
verifySandboxExecReadiness,
|
|
48
49
|
type ControlRpc,
|
|
49
50
|
type EstablishedSandboxSession,
|
|
@@ -322,7 +323,8 @@ async function resolveCurrentHomeBackend(
|
|
|
322
323
|
}
|
|
323
324
|
|
|
324
325
|
const resumeState = lease.resumeState;
|
|
325
|
-
const
|
|
326
|
+
const durableResumeBackend = lease.resumeBackendId ?? lease.backend ?? ids.backend;
|
|
327
|
+
const resumeBackend = sandboxBackendForSdkBackendId(durableResumeBackend) ?? durableResumeBackend;
|
|
326
328
|
if (
|
|
327
329
|
!resumeState ||
|
|
328
330
|
resumeBackend !== ids.backend ||
|
|
@@ -377,7 +379,8 @@ async function resolveCurrentHomeBackend(
|
|
|
377
379
|
// The provider identity must agree with the exact durable lease row before
|
|
378
380
|
// any caller can publish or route through this rebound handle. A mismatch is
|
|
379
381
|
// unverifiable local state, not permission to try the old handle.
|
|
380
|
-
|
|
382
|
+
const reboundBackend = sandboxBackendForSdkBackendId(rebound.backendId) ?? rebound.backendId;
|
|
383
|
+
if (rebound.instanceId !== lease.instanceId || reboundBackend !== resumeBackend) {
|
|
381
384
|
throw homeRouteRecoveryError(lease, lease.leaseEpoch);
|
|
382
385
|
}
|
|
383
386
|
services.onHomeSandboxRebound?.({
|
package/src/workflows/session.ts
CHANGED
|
@@ -215,6 +215,7 @@ export async function sessionWorkflow(input: SessionWorkflowInput): Promise<void
|
|
|
215
215
|
// every new run records v2 and uses the activity-owned receipt contract.
|
|
216
216
|
const receiptGatedCancellation = patched("session-attempt-quiescence-v2");
|
|
217
217
|
const writerSetQuiescenceRecovery = patched("session-attempt-writer-set-quiescence-v1");
|
|
218
|
+
const staleControlSignalIsOnlyWakeHint = patched("session-control-stale-wake-v1");
|
|
218
219
|
const turnActivity = turnActivityForTaskQueue(workflowInfo().taskQueue, receiptGatedCancellation);
|
|
219
220
|
let approvalWakeups = 0;
|
|
220
221
|
let interruptionWakeups = 0;
|
|
@@ -565,7 +566,7 @@ export async function sessionWorkflow(input: SessionWorkflowInput): Promise<void
|
|
|
565
566
|
): Promise<boolean> {
|
|
566
567
|
const capacityWaitEntryBaseline = { wakeups, capacityWakeups };
|
|
567
568
|
const attemptId = uuid4();
|
|
568
|
-
|
|
569
|
+
let interruptionBaseline = interruptionWakeups;
|
|
569
570
|
|
|
570
571
|
const scope = new CancellationScope();
|
|
571
572
|
const workflowExecution = workflowInfo();
|
|
@@ -583,39 +584,52 @@ export async function sessionWorkflow(input: SessionWorkflowInput): Promise<void
|
|
|
583
584
|
trigger,
|
|
584
585
|
}),
|
|
585
586
|
);
|
|
586
|
-
const
|
|
587
|
+
const turnOutcome: Promise<
|
|
587
588
|
| { kind: "result"; result: activities.RunAgentTurnResult }
|
|
588
|
-
| { kind: "
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
589
|
+
| { kind: "failure"; error: unknown }
|
|
590
|
+
> = turn.then(
|
|
591
|
+
(result: activities.RunAgentTurnResult) => ({
|
|
592
|
+
kind: "result" as const,
|
|
593
|
+
result,
|
|
594
|
+
}),
|
|
595
|
+
(error: unknown) => ({ kind: "failure" as const, error }),
|
|
596
|
+
);
|
|
597
|
+
let outcome:
|
|
598
|
+
| { kind: "result"; result: activities.RunAgentTurnResult }
|
|
599
|
+
| { kind: "failure"; error: unknown };
|
|
600
|
+
while (true) {
|
|
601
|
+
const racedOutcome:
|
|
602
|
+
| { kind: "result"; result: activities.RunAgentTurnResult }
|
|
603
|
+
| { kind: "control" }
|
|
604
|
+
| { kind: "failure"; error: unknown } = await Promise.race([
|
|
605
|
+
turnOutcome,
|
|
606
|
+
condition(() => interruptionWakeups !== interruptionBaseline).then(() => ({
|
|
607
|
+
kind: "control" as const,
|
|
608
|
+
})),
|
|
609
|
+
]);
|
|
610
|
+
// A Steer/Pause transaction fences the active attempt before its Temporal
|
|
611
|
+
// signal is necessarily handled. That fence can make the activity's typed
|
|
612
|
+
// cancellation win Promise.race by one workflow activation. Give only that
|
|
613
|
+
// confirmed cancellation shape a short deterministic arbitration window;
|
|
614
|
+
// the durable control signal is authoritative once observed. Ordinary
|
|
615
|
+
// failures and timeouts never wait here, and a cancellation with no session
|
|
616
|
+
// control still follows the failure/cancellation path below.
|
|
617
|
+
if (
|
|
618
|
+
racedOutcome.kind === "failure" &&
|
|
619
|
+
isTurnActivityFenceCancellation(racedOutcome.error) &&
|
|
620
|
+
interruptionWakeups === interruptionBaseline
|
|
621
|
+
) {
|
|
622
|
+
await condition(() => interruptionWakeups !== interruptionBaseline, "250ms");
|
|
623
|
+
}
|
|
624
|
+
const observedOutcome =
|
|
625
|
+
interruptionWakeups !== interruptionBaseline
|
|
626
|
+
? ({ kind: "control" } as const)
|
|
627
|
+
: racedOutcome;
|
|
617
628
|
|
|
618
|
-
|
|
629
|
+
if (observedOutcome.kind !== "control") {
|
|
630
|
+
outcome = observedOutcome;
|
|
631
|
+
break;
|
|
632
|
+
}
|
|
619
633
|
if (!receiptGatedCancellation) {
|
|
620
634
|
// Replay-only v1 command order. New histories always take the v2 path
|
|
621
635
|
// below. The current runAgentTurn still owns and writes the truthful
|
|
@@ -647,6 +661,7 @@ export async function sessionWorkflow(input: SessionWorkflowInput): Promise<void
|
|
|
647
661
|
if (!physicalStopConfirmed) throw termination.error;
|
|
648
662
|
return settlement.action !== "paused";
|
|
649
663
|
}
|
|
664
|
+
const observedInterruptionWakeups = interruptionWakeups;
|
|
650
665
|
const settlement = await activity.settleSessionInterruptions({
|
|
651
666
|
accountId,
|
|
652
667
|
workspaceId,
|
|
@@ -654,6 +669,14 @@ export async function sessionWorkflow(input: SessionWorkflowInput): Promise<void
|
|
|
654
669
|
attemptId,
|
|
655
670
|
workflowId: workflowInfo().workflowId,
|
|
656
671
|
});
|
|
672
|
+
if (staleControlSignalIsOnlyWakeHint && settlement.action === "stale") {
|
|
673
|
+
// sessionControl is replaceable transport, not authority. Keep
|
|
674
|
+
// observing the same activity when no durable interruption exists.
|
|
675
|
+
// Preserve signals received while settlement was in flight so a real
|
|
676
|
+
// concurrent Pause/Steer is evaluated on the next loop iteration.
|
|
677
|
+
interruptionBaseline = observedInterruptionWakeups;
|
|
678
|
+
continue;
|
|
679
|
+
}
|
|
657
680
|
// The transaction above is the authority fence: every late model/tool/UI
|
|
658
681
|
// write is rejected from this point onward. Request cancellation only
|
|
659
682
|
// after it commits, then stop observing the Temporal activity promise.
|