@opengeni/worker-bundle 0.20.0 → 0.20.3
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 +25 -2
- package/dist/activities/google-drive-publication.d.ts +53 -0
- package/dist/activities/image-generation-references.d.ts +2 -0
- package/dist/activities/knowledge-source-sync-driver.d.ts +21 -0
- package/dist/activities/knowledge-source-sync.d.ts +29 -1
- package/dist/activities/run-input.d.ts +20 -2
- package/dist/activities/session-state.d.ts +5 -3
- package/dist/activities/types.d.ts +27 -0
- package/dist/{activities-control-XURE4VKN.js → activities-control-BJSDRSIP.js} +369 -20
- package/dist/activities-control-BJSDRSIP.js.map +1 -0
- package/dist/activities-control.d.ts +2 -2
- package/dist/{activities-turn-6EBXGGLS.js → activities-turn-J5YO7XXX.js} +2281 -1074
- package/dist/activities-turn-J5YO7XXX.js.map +1 -0
- package/dist/activities.d.ts +3 -3
- package/dist/{chunk-TYNPCG4U.js → chunk-N5TJIFCE.js} +69 -1
- package/dist/chunk-N5TJIFCE.js.map +1 -0
- package/dist/{chunk-5GRJIP5H.js → chunk-P6Z2SLAA.js} +2 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -2
- package/dist/observability-metrics.d.ts +37 -0
- package/dist/workflow-bundle.js +174 -4
- package/dist/workflows/session.d.ts +17 -1
- package/package.json +13 -13
- package/src/activities/agent-turn.ts +1801 -1175
- package/src/activities/documents.ts +6 -4
- package/src/activities/google-drive-publication.ts +840 -0
- package/src/activities/image-generation-references.ts +11 -2
- package/src/activities/knowledge-source-sync-driver.ts +23 -0
- package/src/activities/knowledge-source-sync.ts +384 -9
- package/src/activities/run-input.ts +175 -51
- package/src/activities/session-state.ts +69 -5
- package/src/activities/types.ts +27 -0
- package/src/activities.ts +2 -0
- package/src/observability-metrics.ts +184 -3
- package/src/workflows/session.ts +199 -8
- package/dist/activities-control-XURE4VKN.js.map +0 -1
- package/dist/activities-turn-6EBXGGLS.js.map +0 -1
- package/dist/chunk-TYNPCG4U.js.map +0 -1
- /package/dist/{chunk-5GRJIP5H.js.map → chunk-P6Z2SLAA.js.map} +0 -0
|
@@ -8,13 +8,13 @@ import {
|
|
|
8
8
|
import { createHash } from "node:crypto";
|
|
9
9
|
import {
|
|
10
10
|
getActiveSessionHistoryItemsPaged,
|
|
11
|
-
|
|
11
|
+
getFilesForSubject,
|
|
12
12
|
getLatestRunState,
|
|
13
13
|
getHumanInputResumeForEvent,
|
|
14
14
|
getSandboxSessionEnvelope,
|
|
15
15
|
getSessionEvent,
|
|
16
16
|
listSessionSystemUpdatesForTurn,
|
|
17
|
-
|
|
17
|
+
requireFileForSubject,
|
|
18
18
|
type Database,
|
|
19
19
|
} from "@opengeni/db";
|
|
20
20
|
import {
|
|
@@ -76,17 +76,66 @@ export type PreparedTurnInput = {
|
|
|
76
76
|
|
|
77
77
|
export type TurnInputOptions = {
|
|
78
78
|
turnId: string;
|
|
79
|
+
/** Frozen initiating-human authority for every model-visible file read. */
|
|
80
|
+
fileAuthority: { accountId: string; subjectId: string | null };
|
|
79
81
|
recovering?: boolean;
|
|
80
82
|
unavailableSandboxFilesNote?: string;
|
|
81
83
|
runCredentialsNote?: string;
|
|
84
|
+
mcpAvailabilityNote?: string;
|
|
82
85
|
providerApi: HistoryProviderApi;
|
|
83
86
|
projectCanonicalHistory?: ModelHistoryAttachmentProjector;
|
|
84
87
|
materializeModelHistory?: ModelHistoryAttachmentProjector;
|
|
85
88
|
materializeSerializedRunState?: (serialized: string) => Promise<string>;
|
|
86
89
|
projectModelHistory?: ModelHistoryAttachmentProjector;
|
|
87
90
|
loadActiveHistory?: typeof getActiveSessionHistoryItemsPaged;
|
|
91
|
+
/** Bounded critical-path timings; telemetry failures never affect preparation. */
|
|
92
|
+
onPreparationPhase?: (measurement: HistoryPreparationPhaseMeasurement) => void;
|
|
88
93
|
};
|
|
89
94
|
|
|
95
|
+
export type HistoryPreparationPhase =
|
|
96
|
+
| "system_update_load"
|
|
97
|
+
| "current_attachment_resolution"
|
|
98
|
+
| "durable_history_load"
|
|
99
|
+
| "sandbox_envelope_load"
|
|
100
|
+
| "canonical_projection"
|
|
101
|
+
| "provider_projection"
|
|
102
|
+
| "attachment_ref_projection"
|
|
103
|
+
| "screenshot_materialization"
|
|
104
|
+
| "model_attachment_projection"
|
|
105
|
+
| "runtime_input_assembly"
|
|
106
|
+
| "artifact_candidate_scan";
|
|
107
|
+
|
|
108
|
+
export type HistoryPreparationPhaseMeasurement = {
|
|
109
|
+
phase: HistoryPreparationPhase;
|
|
110
|
+
outcome: "completed" | "failed";
|
|
111
|
+
durationSeconds: number;
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
async function measureHistoryPreparationPhase<T>(
|
|
115
|
+
options: Pick<TurnInputOptions, "onPreparationPhase">,
|
|
116
|
+
phase: HistoryPreparationPhase,
|
|
117
|
+
operation: () => T | Promise<T>,
|
|
118
|
+
): Promise<T> {
|
|
119
|
+
const startedAt = performance.now();
|
|
120
|
+
let outcome: HistoryPreparationPhaseMeasurement["outcome"] = "completed";
|
|
121
|
+
try {
|
|
122
|
+
return await operation();
|
|
123
|
+
} catch (error) {
|
|
124
|
+
outcome = "failed";
|
|
125
|
+
throw error;
|
|
126
|
+
} finally {
|
|
127
|
+
try {
|
|
128
|
+
options.onPreparationPhase?.({
|
|
129
|
+
phase,
|
|
130
|
+
outcome,
|
|
131
|
+
durationSeconds: (performance.now() - startedAt) / 1_000,
|
|
132
|
+
});
|
|
133
|
+
} catch {
|
|
134
|
+
// Diagnostics must not change durable history or provider input.
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
90
139
|
export const MAX_INLINE_MODEL_ATTACHMENT_BYTES = 20 * 1024 * 1024;
|
|
91
140
|
|
|
92
141
|
export type ModelAttachmentContent = {
|
|
@@ -244,6 +293,9 @@ function attachmentRefsFromItem(item: Record<string, unknown>): FileResourceRef[
|
|
|
244
293
|
}
|
|
245
294
|
|
|
246
295
|
function attachmentUnavailableText(ref: FileResourceRef, file: FileAsset | undefined): string {
|
|
296
|
+
if (!file) {
|
|
297
|
+
return `[Attachment unavailable or no longer authorized: ${ref.fileId}.]`;
|
|
298
|
+
}
|
|
247
299
|
const filename = file?.safeFilename ?? ref.fileId;
|
|
248
300
|
const mediaType = file?.contentType ?? "unknown type";
|
|
249
301
|
const path = file ? sandboxFilePath(ref, file) : `/workspace/${resourceMountPath(ref)}`;
|
|
@@ -261,7 +313,7 @@ function attachmentUnavailableText(ref: FileResourceRef, file: FileAsset | undef
|
|
|
261
313
|
*/
|
|
262
314
|
export function createModelHistoryAttachmentProjector(
|
|
263
315
|
db: Database,
|
|
264
|
-
workspaceId: string,
|
|
316
|
+
authority: { accountId: string; workspaceId: string; subjectId: string | null },
|
|
265
317
|
policy: ModelAttachmentInputPolicy,
|
|
266
318
|
readFileBytes?: (file: FileAsset) => Promise<Uint8Array>,
|
|
267
319
|
): ModelHistoryAttachmentProjector {
|
|
@@ -288,7 +340,10 @@ export function createModelHistoryAttachmentProjector(
|
|
|
288
340
|
|
|
289
341
|
const unknownIds = orderedFileIds.filter((id) => !fileById.has(id) && !missingFileIds.has(id));
|
|
290
342
|
if (unknownIds.length > 0) {
|
|
291
|
-
const files = await
|
|
343
|
+
const files = await getFilesForSubject(db, {
|
|
344
|
+
...authority,
|
|
345
|
+
fileIds: unknownIds,
|
|
346
|
+
});
|
|
292
347
|
for (const file of files) fileById.set(file.id, file);
|
|
293
348
|
for (const id of unknownIds) {
|
|
294
349
|
if (!fileById.has(id)) missingFileIds.add(id);
|
|
@@ -378,11 +433,16 @@ export async function turnInput(
|
|
|
378
433
|
if (!trigger) {
|
|
379
434
|
throw new Error("Missing trigger event");
|
|
380
435
|
}
|
|
381
|
-
const updates = await
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
436
|
+
const updates = await measureHistoryPreparationPhase(
|
|
437
|
+
options,
|
|
438
|
+
"system_update_load",
|
|
439
|
+
async () =>
|
|
440
|
+
await listSessionSystemUpdatesForTurn(
|
|
441
|
+
db,
|
|
442
|
+
trigger.workspaceId,
|
|
443
|
+
trigger.sessionId,
|
|
444
|
+
options.turnId,
|
|
445
|
+
),
|
|
386
446
|
);
|
|
387
447
|
if (updates.length > 0) {
|
|
388
448
|
const historyItemIds = new Set(
|
|
@@ -401,6 +461,7 @@ export async function turnInput(
|
|
|
401
461
|
: undefined,
|
|
402
462
|
options.unavailableSandboxFilesNote,
|
|
403
463
|
options.runCredentialsNote,
|
|
464
|
+
options.mcpAvailabilityNote,
|
|
404
465
|
);
|
|
405
466
|
if (trigger.type === "user.message") {
|
|
406
467
|
const payload = trigger.payload as {
|
|
@@ -413,10 +474,17 @@ export async function turnInput(
|
|
|
413
474
|
throw new Error("user.message payload is missing text and annotations");
|
|
414
475
|
}
|
|
415
476
|
const resources = Array.isArray(payload.resources) ? (payload.resources as ResourceRef[]) : [];
|
|
416
|
-
const fileAttachments = await
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
477
|
+
const fileAttachments = await measureHistoryPreparationPhase(
|
|
478
|
+
options,
|
|
479
|
+
"current_attachment_resolution",
|
|
480
|
+
async () =>
|
|
481
|
+
await resolveUserMessageFileAttachments(
|
|
482
|
+
db,
|
|
483
|
+
options.fileAuthority.accountId,
|
|
484
|
+
trigger.workspaceId,
|
|
485
|
+
options.fileAuthority.subjectId,
|
|
486
|
+
resources,
|
|
487
|
+
),
|
|
420
488
|
);
|
|
421
489
|
const attachmentContext = userMessageAttachmentsContext(fileAttachments);
|
|
422
490
|
return await messageInput(
|
|
@@ -432,6 +500,7 @@ export async function turnInput(
|
|
|
432
500
|
options.materializeModelHistory,
|
|
433
501
|
options.projectModelHistory,
|
|
434
502
|
options.loadActiveHistory,
|
|
503
|
+
options,
|
|
435
504
|
);
|
|
436
505
|
}
|
|
437
506
|
if (trigger.type === "system.update.delivered") {
|
|
@@ -451,6 +520,7 @@ export async function turnInput(
|
|
|
451
520
|
options.materializeModelHistory,
|
|
452
521
|
options.projectModelHistory,
|
|
453
522
|
options.loadActiveHistory,
|
|
523
|
+
options,
|
|
454
524
|
);
|
|
455
525
|
}
|
|
456
526
|
if (trigger.type === "user.approvalDecision") {
|
|
@@ -536,56 +606,103 @@ async function messageInput(
|
|
|
536
606
|
materializeModelHistory?: ModelHistoryAttachmentProjector,
|
|
537
607
|
projectModelHistory?: ModelHistoryAttachmentProjector,
|
|
538
608
|
loadActiveHistory: typeof getActiveSessionHistoryItemsPaged = getActiveSessionHistoryItemsPaged,
|
|
609
|
+
preparationOptions: Pick<TurnInputOptions, "onPreparationPhase"> = {},
|
|
539
610
|
): Promise<PreparedTurnInput> {
|
|
540
|
-
const stored = await
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
const
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
611
|
+
const [stored, envelope] = await Promise.all([
|
|
612
|
+
measureHistoryPreparationPhase(preparationOptions, "durable_history_load", async () =>
|
|
613
|
+
loadActiveHistory(db, trigger.workspaceId, trigger.sessionId),
|
|
614
|
+
),
|
|
615
|
+
measureHistoryPreparationPhase(preparationOptions, "sandbox_envelope_load", async () =>
|
|
616
|
+
getSandboxSessionEnvelope(db, trigger.workspaceId, trigger.sessionId),
|
|
617
|
+
),
|
|
618
|
+
]);
|
|
619
|
+
const canonicalView = await measureHistoryPreparationPhase(
|
|
620
|
+
preparationOptions,
|
|
621
|
+
"canonical_projection",
|
|
622
|
+
async () => {
|
|
623
|
+
const active = projectRejectedProviderArtifacts(stored);
|
|
624
|
+
return projectCanonicalHistory ? await projectCanonicalHistory(active) : active;
|
|
625
|
+
},
|
|
626
|
+
);
|
|
627
|
+
const providerView = await measureHistoryPreparationPhase(
|
|
628
|
+
preparationOptions,
|
|
629
|
+
"provider_projection",
|
|
630
|
+
() => projectHistoryForProvider(canonicalView, providerApi),
|
|
631
|
+
);
|
|
632
|
+
const referencedHistory = await measureHistoryPreparationPhase(
|
|
633
|
+
preparationOptions,
|
|
634
|
+
"attachment_ref_projection",
|
|
635
|
+
() => withCurrentUserAttachmentRefs(providerView, currentAttachmentRefs),
|
|
636
|
+
);
|
|
637
|
+
const materializedHistory = await measureHistoryPreparationPhase(
|
|
638
|
+
preparationOptions,
|
|
639
|
+
"screenshot_materialization",
|
|
640
|
+
async () =>
|
|
641
|
+
materializeModelHistory
|
|
642
|
+
? await materializeModelHistory(referencedHistory)
|
|
643
|
+
: referencedHistory,
|
|
644
|
+
);
|
|
645
|
+
const historyItems = await measureHistoryPreparationPhase(
|
|
646
|
+
preparationOptions,
|
|
647
|
+
"model_attachment_projection",
|
|
648
|
+
async () =>
|
|
649
|
+
projectModelHistory ? await projectModelHistory(materializedHistory) : materializedHistory,
|
|
650
|
+
);
|
|
651
|
+
const prepared = await measureHistoryPreparationPhase(
|
|
652
|
+
preparationOptions,
|
|
653
|
+
"runtime_input_assembly",
|
|
654
|
+
async () =>
|
|
655
|
+
await runtime.prepareInput(agent, {
|
|
656
|
+
kind: "message",
|
|
657
|
+
...(text ? { text } : {}),
|
|
658
|
+
...(internalContext ? { internalContext } : {}),
|
|
659
|
+
historyItems: historyItems as any,
|
|
660
|
+
sandboxEnvelope: envelope,
|
|
661
|
+
...(projectModelHistory ? { modelInputAlreadyProjected: true } : {}),
|
|
662
|
+
}),
|
|
663
|
+
);
|
|
664
|
+
const providerArtifactCandidates = await measureHistoryPreparationPhase(
|
|
665
|
+
preparationOptions,
|
|
666
|
+
"artifact_candidate_scan",
|
|
667
|
+
() => {
|
|
668
|
+
const preparedItems = Array.isArray(prepared.input)
|
|
669
|
+
? new Set(prepared.input)
|
|
670
|
+
: new Set<unknown>();
|
|
671
|
+
return {
|
|
672
|
+
knownHistoryItemIds: stored.map((row) => row.id),
|
|
673
|
+
historyItemIds: stored
|
|
674
|
+
.filter(
|
|
675
|
+
(row) =>
|
|
676
|
+
row.providerArtifactInvalidatedAt === null &&
|
|
677
|
+
hasOpaqueProviderArtifact(row.item) &&
|
|
678
|
+
preparedItems.has(row.item),
|
|
679
|
+
)
|
|
680
|
+
.map((row) => row.id),
|
|
681
|
+
};
|
|
682
|
+
},
|
|
683
|
+
);
|
|
565
684
|
return {
|
|
566
685
|
input: prepared,
|
|
567
686
|
persistedHistoryCount: prepared.persistedHistoryCount,
|
|
568
|
-
providerArtifactCandidates
|
|
569
|
-
knownHistoryItemIds: stored.map((row) => row.id),
|
|
570
|
-
historyItemIds: stored
|
|
571
|
-
.filter(
|
|
572
|
-
(row) =>
|
|
573
|
-
row.providerArtifactInvalidatedAt === null &&
|
|
574
|
-
hasOpaqueProviderArtifact(row.item) &&
|
|
575
|
-
preparedItems.has(row.item),
|
|
576
|
-
)
|
|
577
|
-
.map((row) => row.id),
|
|
578
|
-
},
|
|
687
|
+
providerArtifactCandidates,
|
|
579
688
|
};
|
|
580
689
|
}
|
|
581
690
|
|
|
582
691
|
export async function userMessageTextWithAttachments(
|
|
583
692
|
db: Database,
|
|
693
|
+
accountId: string,
|
|
584
694
|
workspaceId: string,
|
|
695
|
+
subjectId: string | null,
|
|
585
696
|
text: string,
|
|
586
697
|
resources: ResourceRef[],
|
|
587
698
|
): Promise<string> {
|
|
588
|
-
const fileAttachments = await resolveUserMessageFileAttachments(
|
|
699
|
+
const fileAttachments = await resolveUserMessageFileAttachments(
|
|
700
|
+
db,
|
|
701
|
+
accountId,
|
|
702
|
+
workspaceId,
|
|
703
|
+
subjectId,
|
|
704
|
+
resources,
|
|
705
|
+
);
|
|
589
706
|
const attachmentContext = userMessageAttachmentsContext(fileAttachments);
|
|
590
707
|
return attachmentContext ? [text, "", attachmentContext].join("\n") : text;
|
|
591
708
|
}
|
|
@@ -597,13 +714,20 @@ type UserMessageFileAttachment = {
|
|
|
597
714
|
|
|
598
715
|
async function resolveUserMessageFileAttachments(
|
|
599
716
|
db: Database,
|
|
717
|
+
accountId: string,
|
|
600
718
|
workspaceId: string,
|
|
719
|
+
subjectId: string | null,
|
|
601
720
|
resources: ResourceRef[],
|
|
602
721
|
): Promise<UserMessageFileAttachment[]> {
|
|
603
722
|
const attachments: UserMessageFileAttachment[] = [];
|
|
604
723
|
for (const resource of resources) {
|
|
605
724
|
if (resource.kind !== "file") continue;
|
|
606
|
-
const file = await
|
|
725
|
+
const file = await requireFileForSubject(db, {
|
|
726
|
+
accountId,
|
|
727
|
+
workspaceId,
|
|
728
|
+
subjectId,
|
|
729
|
+
fileId: resource.fileId,
|
|
730
|
+
});
|
|
607
731
|
attachments.push({ resource, file });
|
|
608
732
|
}
|
|
609
733
|
return attachments;
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
2
|
settleSessionAttemptInterruptions,
|
|
3
3
|
applySessionTurnSettlement,
|
|
4
|
+
enqueueSessionWorkflowWake,
|
|
5
|
+
failSessionWorkBeforeAttemptClaim,
|
|
4
6
|
requestSessionTurnRecovery,
|
|
5
7
|
recoverSessionDispatch,
|
|
6
8
|
reconcileSessionAttemptQuiescence,
|
|
@@ -26,6 +28,7 @@ import type {
|
|
|
26
28
|
ExpireSessionInteractionInterventionResult,
|
|
27
29
|
PeekSessionWorkInput,
|
|
28
30
|
FailSessionAttemptInput,
|
|
31
|
+
FailSessionAttemptResult,
|
|
29
32
|
SettleSessionInterruptionsInput,
|
|
30
33
|
MarkSessionIdleInput,
|
|
31
34
|
PersistSessionAttemptQuiescenceInput,
|
|
@@ -40,6 +43,8 @@ import type {
|
|
|
40
43
|
export type SessionStateActivityOverrides = Partial<{
|
|
41
44
|
settleSessionAttemptInterruptions: typeof settleSessionAttemptInterruptions;
|
|
42
45
|
applySessionTurnSettlement: typeof applySessionTurnSettlement;
|
|
46
|
+
enqueueSessionWorkflowWake: typeof enqueueSessionWorkflowWake;
|
|
47
|
+
failSessionWorkBeforeAttemptClaim: typeof failSessionWorkBeforeAttemptClaim;
|
|
43
48
|
requestSessionTurnRecovery: typeof requestSessionTurnRecovery;
|
|
44
49
|
recoverSessionDispatch: typeof recoverSessionDispatch;
|
|
45
50
|
reconcileSessionAttemptQuiescence: typeof reconcileSessionAttemptQuiescence;
|
|
@@ -73,6 +78,10 @@ export function createSessionStateActivities(
|
|
|
73
78
|
overrides.settleSessionAttemptInterruptions ?? settleSessionAttemptInterruptions;
|
|
74
79
|
const applySessionTurnSettlementFn =
|
|
75
80
|
overrides.applySessionTurnSettlement ?? applySessionTurnSettlement;
|
|
81
|
+
const enqueueSessionWorkflowWakeFn =
|
|
82
|
+
overrides.enqueueSessionWorkflowWake ?? enqueueSessionWorkflowWake;
|
|
83
|
+
const failSessionWorkBeforeAttemptClaimFn =
|
|
84
|
+
overrides.failSessionWorkBeforeAttemptClaim ?? failSessionWorkBeforeAttemptClaim;
|
|
76
85
|
const requestSessionTurnRecoveryFn =
|
|
77
86
|
overrides.requestSessionTurnRecovery ?? requestSessionTurnRecovery;
|
|
78
87
|
const recoverSessionDispatchFn = overrides.recoverSessionDispatch ?? recoverSessionDispatch;
|
|
@@ -100,19 +109,73 @@ export function createSessionStateActivities(
|
|
|
100
109
|
const notifyParentOfChildIdleFn = overrides.notifyParentOfChildIdle ?? notifyParentOfChildIdle;
|
|
101
110
|
const recordTurnsQueuedGaugeFn = overrides.recordTurnsQueuedGauge ?? recordTurnsQueuedGauge;
|
|
102
111
|
|
|
103
|
-
async function failSessionAttempt(
|
|
112
|
+
async function failSessionAttempt(
|
|
113
|
+
input: FailSessionAttemptInput,
|
|
114
|
+
): Promise<FailSessionAttemptResult> {
|
|
104
115
|
const { db, bus, settings, observability, wakeSessionWorkflow } = await services();
|
|
105
116
|
const session = await requireSessionFn(db, input.workspaceId, input.sessionId);
|
|
106
|
-
if (session.status === "failed") {
|
|
107
|
-
|
|
117
|
+
if (session.status === "failed" || session.status === "cancelled") {
|
|
118
|
+
// The activity may be retried after failure settlement committed but its
|
|
119
|
+
// response or event fanout was lost. Preserve terminal session truth so
|
|
120
|
+
// the workflow cannot interpret an idle peek as permission to synthesize
|
|
121
|
+
// an active-goal continuation.
|
|
122
|
+
return { action: "terminal" };
|
|
108
123
|
}
|
|
124
|
+
const workflowId =
|
|
125
|
+
input.workflowId ?? session.temporalWorkflowId ?? `session-${input.sessionId}`;
|
|
109
126
|
const turn = await getSessionTurnForAttemptFn(
|
|
110
127
|
db,
|
|
111
128
|
input.workspaceId,
|
|
112
129
|
input.sessionId,
|
|
113
130
|
input.attemptId,
|
|
114
131
|
);
|
|
115
|
-
if (!turn)
|
|
132
|
+
if (!turn) {
|
|
133
|
+
const attempt = await getSessionAttemptActivityRefFn(db, {
|
|
134
|
+
accountId: input.accountId,
|
|
135
|
+
workspaceId: input.workspaceId,
|
|
136
|
+
sessionId: input.sessionId,
|
|
137
|
+
attemptId: input.attemptId,
|
|
138
|
+
temporalWorkflowId: workflowId,
|
|
139
|
+
});
|
|
140
|
+
if (attempt) return { action: "stale" };
|
|
141
|
+
|
|
142
|
+
if (input.preClaimFailureDisposition === "permanent" && input.trigger) {
|
|
143
|
+
const failed = await failSessionWorkBeforeAttemptClaimFn(db, input.workspaceId, {
|
|
144
|
+
accountId: input.accountId,
|
|
145
|
+
sessionId: input.sessionId,
|
|
146
|
+
workflowId,
|
|
147
|
+
trigger: input.trigger,
|
|
148
|
+
error: input.error ?? "Agent turn admission failed before attempt claim.",
|
|
149
|
+
});
|
|
150
|
+
if (failed.action === "terminal") return { action: "terminal" };
|
|
151
|
+
if (failed.action === "stale") return { action: "stale" };
|
|
152
|
+
await publishDurableSessionEventsFn(bus, input.workspaceId, input.sessionId, failed.events);
|
|
153
|
+
if (failed.turnId) {
|
|
154
|
+
await deliverFailedChildTurnToParentFn(
|
|
155
|
+
{ db, bus, settings, observability, wakeSessionWorkflow },
|
|
156
|
+
input.workspaceId,
|
|
157
|
+
input.sessionId,
|
|
158
|
+
failed.turnId,
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
return { action: "failed" };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const requestedRetryDelayMs = input.retryDelayMs;
|
|
165
|
+
const retryDelayMs =
|
|
166
|
+
typeof requestedRetryDelayMs === "number" && Number.isFinite(requestedRetryDelayMs)
|
|
167
|
+
? Math.max(1_000, Math.min(60_000, Math.trunc(requestedRetryDelayMs)))
|
|
168
|
+
: 60_000;
|
|
169
|
+
await enqueueSessionWorkflowWakeFn(db, {
|
|
170
|
+
accountId: input.accountId,
|
|
171
|
+
workspaceId: input.workspaceId,
|
|
172
|
+
sessionId: input.sessionId,
|
|
173
|
+
temporalWorkflowId: workflowId,
|
|
174
|
+
reason: "turn_activity_failed_before_attempt_claim",
|
|
175
|
+
notBefore: new Date(Date.now() + retryDelayMs),
|
|
176
|
+
});
|
|
177
|
+
return { action: "unclaimed" };
|
|
178
|
+
}
|
|
116
179
|
const trigger = await getSessionEventFn(db, input.workspaceId, turn.triggerEventId);
|
|
117
180
|
const result = await applySessionTurnSettlementFn(db, input.workspaceId, {
|
|
118
181
|
sessionId: input.sessionId,
|
|
@@ -135,7 +198,7 @@ export function createSessionStateActivities(
|
|
|
135
198
|
],
|
|
136
199
|
});
|
|
137
200
|
if (result.action === "stale") {
|
|
138
|
-
return;
|
|
201
|
+
return { action: "stale" };
|
|
139
202
|
}
|
|
140
203
|
await publishDurableSessionEventsFn(bus, input.workspaceId, input.sessionId, result.events);
|
|
141
204
|
await deliverFailedChildTurnToParentFn(
|
|
@@ -144,6 +207,7 @@ export function createSessionStateActivities(
|
|
|
144
207
|
input.sessionId,
|
|
145
208
|
turn.id,
|
|
146
209
|
);
|
|
210
|
+
return { action: "failed" };
|
|
147
211
|
}
|
|
148
212
|
|
|
149
213
|
async function settleSessionInterruptions(
|
package/src/activities/types.ts
CHANGED
|
@@ -230,9 +230,36 @@ export type FailSessionAttemptInput = {
|
|
|
230
230
|
workspaceId: string;
|
|
231
231
|
sessionId: string;
|
|
232
232
|
attemptId: string;
|
|
233
|
+
/** Added in v2; old Temporal histories derive the session's canonical id. */
|
|
234
|
+
workflowId?: string;
|
|
235
|
+
/** Added in v2; old Temporal histories use the bounded 60-second floor. */
|
|
236
|
+
retryDelayMs?: number;
|
|
237
|
+
/** Added in v3. Upgraded turn workers classify failures from the atomic
|
|
238
|
+
* admission transaction; omission is a rolling-deploy/legacy unknown and
|
|
239
|
+
* deliberately keeps the recoverable wake behavior. */
|
|
240
|
+
preClaimFailureDisposition?: PreClaimFailureDisposition;
|
|
241
|
+
/** The workflow admission trigger is required to re-evaluate the same
|
|
242
|
+
* durable admission branch before terminally settling a permanent failure. */
|
|
243
|
+
trigger?: RunAgentTurnInput["trigger"];
|
|
233
244
|
error?: string;
|
|
234
245
|
};
|
|
235
246
|
|
|
247
|
+
export type FailSessionAttemptResult =
|
|
248
|
+
| { action: "failed" }
|
|
249
|
+
| { action: "unclaimed" }
|
|
250
|
+
| { action: "terminal" }
|
|
251
|
+
| { action: "stale" };
|
|
252
|
+
|
|
253
|
+
export type PreClaimFailureDisposition = "retryable" | "permanent";
|
|
254
|
+
|
|
255
|
+
export type PreClaimFailureDetail = {
|
|
256
|
+
disposition: PreClaimFailureDisposition;
|
|
257
|
+
code: "db_deadlock" | "db_serialization_failure" | "db_failure" | "claim_invariant";
|
|
258
|
+
};
|
|
259
|
+
|
|
260
|
+
export const PRE_CLAIM_FAILURE_TYPE = "OpenGeniPreClaimFailure";
|
|
261
|
+
export const PRE_CLAIM_FAILURE_MESSAGE = "Agent turn admission failed before attempt claim.";
|
|
262
|
+
|
|
236
263
|
export type RecoverDispatchInput = {
|
|
237
264
|
accountId: string;
|
|
238
265
|
workspaceId: string;
|
package/src/activities.ts
CHANGED
|
@@ -38,6 +38,8 @@ export type {
|
|
|
38
38
|
PersistSessionAttemptQuiescenceInput,
|
|
39
39
|
ReconcileSessionAttemptQuiescenceInput,
|
|
40
40
|
ReconcileSessionAttemptQuiescenceResult,
|
|
41
|
+
FailSessionAttemptInput,
|
|
42
|
+
FailSessionAttemptResult,
|
|
41
43
|
RunKnowledgeSourceSyncBatchInput,
|
|
42
44
|
RunKnowledgeSourceSyncBatchResult,
|
|
43
45
|
RunAgentTurnInput,
|