@bastani/atomic 0.9.45 → 0.9.46-alpha.1
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/CHANGELOG.md +34 -0
- package/dist/builtin/intercom/CHANGELOG.md +11 -0
- package/dist/builtin/intercom/broker/broker.ts +124 -10
- package/dist/builtin/intercom/broker/client.ts +177 -25
- package/dist/builtin/intercom/broker/multinode-router.ts +228 -27
- package/dist/builtin/intercom/broker/multinode-state-store.ts +10 -0
- package/dist/builtin/intercom/broker/recipient-receipts.ts +38 -4
- package/dist/builtin/intercom/broker/send-handler.ts +9 -2
- package/dist/builtin/intercom/broker/sql-outbox-store.ts +29 -4
- package/dist/builtin/intercom/group.ts +25 -0
- package/dist/builtin/intercom/index.bundle.mjs +177 -35
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/intercom/retry-policy.ts +7 -0
- package/dist/builtin/intercom/types.ts +21 -0
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/CHANGELOG.md +10 -0
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/subagents/src/extension/index.bundle.mjs +150 -54
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +39 -0
- package/dist/builtin/workflows/builtin/{chunk-6901nsd6.js → chunk-6jpwc09k.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-vwx023ge.js → chunk-qhm35ntx.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-jvna28mq.js → chunk-zhyqnf5g.js} +331 -68
- package/dist/builtin/workflows/builtin/goal.js +2 -2
- package/dist/builtin/workflows/builtin/index.js +3 -3
- package/dist/builtin/workflows/builtin/ralph.js +2 -2
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/skills/prompt-engineer/SKILL.md +1 -0
- package/dist/builtin/workflows/skills/prompt-engineer/references/gpt_6.md +2 -2
- package/dist/builtin/workflows/skills/prompt-engineer/references/gpt_6_1_sol.md +2 -2
- package/dist/builtin/workflows/skills/prompt-engineer/references/gpt_6_1_terra.md +77 -0
- package/dist/builtin/workflows/src/authoring.d.ts +1 -1
- package/dist/builtin/workflows/src/durable/journal/internal.d.ts +2 -0
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +7076 -3386
- package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +11075 -7261
- package/dist/builtin/workflows/src/index.js +6768 -3605
- package/dist/builtin/workflows/src/local-worker-entry.mjs +11075 -7261
- package/dist/builtin/workflows/src/shared/authoring-contract-ui.d.ts +19 -0
- package/dist/core/agent-session-boundaries.d.ts.map +1 -1
- package/dist/core/agent-session-boundaries.js +1 -0
- package/dist/core/agent-session-boundaries.js.map +1 -1
- package/dist/core/agent-session-events.d.ts.map +1 -1
- package/dist/core/agent-session-events.js +2 -1
- package/dist/core/agent-session-events.js.map +1 -1
- package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
- package/dist/core/agent-session-extension-bindings.js +15 -2
- package/dist/core/agent-session-extension-bindings.js.map +1 -1
- package/dist/core/agent-session-methods.d.ts +3 -2
- package/dist/core/agent-session-methods.d.ts.map +1 -1
- package/dist/core/agent-session-methods.js.map +1 -1
- package/dist/core/agent-session-prompt.d.ts +4 -2
- package/dist/core/agent-session-prompt.d.ts.map +1 -1
- package/dist/core/agent-session-prompt.js +13 -8
- package/dist/core/agent-session-prompt.js.map +1 -1
- package/dist/core/agent-session-recovery.d.ts.map +1 -1
- package/dist/core/agent-session-recovery.js +92 -1
- package/dist/core/agent-session-recovery.js.map +1 -1
- package/dist/core/agent-session-transfer.d.ts.map +1 -1
- package/dist/core/agent-session-transfer.js +5 -0
- package/dist/core/agent-session-transfer.js.map +1 -1
- package/dist/core/agent-session.d.ts +2 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +2 -0
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/copilot-errors.d.ts +6 -0
- package/dist/core/copilot-errors.d.ts.map +1 -0
- package/dist/core/copilot-errors.js +17 -0
- package/dist/core/copilot-errors.js.map +1 -0
- package/dist/core/execution-model-router.d.ts.map +1 -1
- package/dist/core/execution-model-router.js +12 -2
- package/dist/core/execution-model-router.js.map +1 -1
- package/dist/core/extensions/context-types.d.ts +7 -0
- package/dist/core/extensions/context-types.d.ts.map +1 -1
- package/dist/core/extensions/context-types.js.map +1 -1
- package/dist/core/extensions/runner-context.d.ts.map +1 -1
- package/dist/core/extensions/runner-context.js +6 -0
- package/dist/core/extensions/runner-context.js.map +1 -1
- package/dist/core/extensions/workflow-activity-hub.d.ts +4 -0
- package/dist/core/extensions/workflow-activity-hub.d.ts.map +1 -1
- package/dist/core/extensions/workflow-activity-hub.js +26 -5
- package/dist/core/extensions/workflow-activity-hub.js.map +1 -1
- package/dist/core/extensions/workflow-events.d.ts +5 -0
- package/dist/core/extensions/workflow-events.d.ts.map +1 -1
- package/dist/core/extensions/workflow-events.js.map +1 -1
- package/dist/core/messages.d.ts +5 -0
- package/dist/core/messages.d.ts.map +1 -1
- package/dist/core/messages.js +1 -1
- package/dist/core/messages.js.map +1 -1
- package/dist/core/model-fallback-failures.d.ts +1 -1
- package/dist/core/model-fallback-failures.d.ts.map +1 -1
- package/dist/core/model-fallback-failures.js +37 -3
- package/dist/core/model-fallback-failures.js.map +1 -1
- package/dist/core/model-runtime-streaming.js +2 -2
- package/dist/core/model-runtime-streaming.js.map +1 -1
- package/dist/core/provider-composer.d.ts.map +1 -1
- package/dist/core/provider-composer.js +19 -11
- package/dist/core/provider-composer.js.map +1 -1
- package/dist/core/provider-rate-limits.d.ts +55 -6
- package/dist/core/provider-rate-limits.d.ts.map +1 -1
- package/dist/core/provider-rate-limits.js +182 -29
- package/dist/core/provider-rate-limits.js.map +1 -1
- package/dist/core/provider-request-admission.d.ts.map +1 -1
- package/dist/core/provider-request-admission.js +42 -18
- package/dist/core/provider-request-admission.js.map +1 -1
- package/dist/core/storage/node-sqlite.d.ts.map +1 -1
- package/dist/core/storage/node-sqlite.js +176 -19
- package/dist/core/storage/node-sqlite.js.map +1 -1
- package/dist/core/storage/provider.d.ts +4 -2
- package/dist/core/storage/provider.d.ts.map +1 -1
- package/dist/core/storage/provider.js +94 -5
- package/dist/core/storage/provider.js.map +1 -1
- package/dist/core/structured-output/index.d.ts.map +1 -1
- package/dist/core/structured-output/index.js +15 -8
- package/dist/core/structured-output/index.js.map +1 -1
- package/dist/core/structured-output/provider-failure.d.ts +17 -0
- package/dist/core/structured-output/provider-failure.d.ts.map +1 -0
- package/dist/core/structured-output/provider-failure.js +28 -0
- package/dist/core/structured-output/provider-failure.js.map +1 -0
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +13 -7
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/shell-task-render.d.ts +1 -0
- package/dist/core/tools/shell-task-render.d.ts.map +1 -1
- package/dist/core/tools/shell-task-render.js +7 -2
- package/dist/core/tools/shell-task-render.js.map +1 -1
- package/dist/extensions/tool-search/tool.d.ts +5 -0
- package/dist/extensions/tool-search/tool.d.ts.map +1 -1
- package/dist/extensions/tool-search/tool.js +38 -5
- package/dist/extensions/tool-search/tool.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-actions.js +3 -2
- package/dist/modes/interactive/components/chat-session-host-actions.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +42 -14
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/interactive-extension-context.js +2 -1
- package/dist/modes/interactive/interactive-extension-context.js.map +1 -1
- package/dist/modes/interactive/interactive-startup.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-startup.js +5 -6
- package/dist/modes/interactive/interactive-startup.js.map +1 -1
- package/dist/modes/rpc/rpc-client-process.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client-process.js +8 -1
- package/dist/modes/rpc/rpc-client-process.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +7 -1
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/utils/ansi.d.ts +2 -0
- package/dist/utils/ansi.d.ts.map +1 -1
- package/dist/utils/ansi.js +5 -0
- package/dist/utils/ansi.js.map +1 -1
- package/docs/codemode.md +1 -1
- package/docs/intercom/reference.md +3 -3
- package/docs/models/evals.md +31 -12
- package/docs/models/reference.md +23 -51
- package/docs/models.md +3 -4
- package/docs/providers.md +5 -15
- package/docs/settings.md +1 -1
- package/docs/storage.md +2 -2
- package/docs/tools.md +1 -1
- package/docs/workflows/api-reference.md +20 -1
- package/docs/workflows/operations.md +17 -4
- package/npm-shrinkwrap.json +64 -44
- package/package.json +4 -4
|
@@ -12,6 +12,8 @@ export class WorkflowActivityHub {
|
|
|
12
12
|
disposed = false;
|
|
13
13
|
dispatch;
|
|
14
14
|
pendingDispatches = [];
|
|
15
|
+
/** Publishes root changes the current publisher has coalesced but not yet published. */
|
|
16
|
+
pendingPublications;
|
|
15
17
|
bindDispatcher(dispatch) {
|
|
16
18
|
if (this.disposed)
|
|
17
19
|
return;
|
|
@@ -33,6 +35,11 @@ export class WorkflowActivityHub {
|
|
|
33
35
|
this.pendingDispatches.push(deliver);
|
|
34
36
|
}
|
|
35
37
|
getSnapshotFrame() {
|
|
38
|
+
this.pendingPublications?.();
|
|
39
|
+
return this.currentSnapshotFrame();
|
|
40
|
+
}
|
|
41
|
+
/** The published state as is; publications the source still coalesces are not flushed. */
|
|
42
|
+
currentSnapshotFrame() {
|
|
36
43
|
return this.availability === "ready"
|
|
37
44
|
? {
|
|
38
45
|
kind: "snapshot",
|
|
@@ -48,10 +55,14 @@ export class WorkflowActivityHub {
|
|
|
48
55
|
this.record("ObserverDisposed");
|
|
49
56
|
return { dispose: () => { } };
|
|
50
57
|
}
|
|
58
|
+
// Publish coalesced changes before this observer exists, so they reach it inside its snapshot
|
|
59
|
+
// rather than as frames queued ahead of it (#4009).
|
|
60
|
+
this.pendingPublications?.();
|
|
51
61
|
if (this.availability !== "ready")
|
|
52
62
|
this.record(this.availability === "recovering" ? "SourceRecovering" : "SourceUnavailable");
|
|
63
|
+
const snapshot = this.currentSnapshotFrame();
|
|
53
64
|
this.observers.add(lease);
|
|
54
|
-
this.enqueue(lease,
|
|
65
|
+
this.enqueue(lease, snapshot);
|
|
55
66
|
return { dispose: () => this.disposeLease(lease) };
|
|
56
67
|
}
|
|
57
68
|
disposeLease(lease) {
|
|
@@ -64,7 +75,7 @@ export class WorkflowActivityHub {
|
|
|
64
75
|
}
|
|
65
76
|
enqueue(lease, frame) {
|
|
66
77
|
if (lease.queue.length >= 256) {
|
|
67
|
-
lease.queue = [this.
|
|
78
|
+
lease.queue = [this.currentSnapshotFrame()];
|
|
68
79
|
this.record("ObserverOverflow");
|
|
69
80
|
}
|
|
70
81
|
else
|
|
@@ -100,10 +111,11 @@ export class WorkflowActivityHub {
|
|
|
100
111
|
let active = !this.disposed;
|
|
101
112
|
if (active) {
|
|
102
113
|
this.cursor = { epoch: randomUUID(), revision: 0 };
|
|
114
|
+
this.pendingPublications = undefined;
|
|
103
115
|
this.availability = "unavailable";
|
|
104
116
|
this.roots.clear();
|
|
105
117
|
this.record("SourceUnavailable");
|
|
106
|
-
this.broadcast(this.
|
|
118
|
+
this.broadcast(this.currentSnapshotFrame());
|
|
107
119
|
}
|
|
108
120
|
const epoch = this.cursor.epoch;
|
|
109
121
|
const isCurrent = () => active && !this.disposed && this.cursor.epoch === epoch;
|
|
@@ -122,7 +134,7 @@ export class WorkflowActivityHub {
|
|
|
122
134
|
this.availability = input.availability;
|
|
123
135
|
this.roots = new Map(input.availability === "ready" ? input.roots.map((root) => [root.rootRunId, { ...root }]) : []);
|
|
124
136
|
this.advance();
|
|
125
|
-
this.broadcast(this.
|
|
137
|
+
this.broadcast(this.currentSnapshotFrame());
|
|
126
138
|
},
|
|
127
139
|
publishChanged: (root) => {
|
|
128
140
|
if (!admitted())
|
|
@@ -151,6 +163,15 @@ export class WorkflowActivityHub {
|
|
|
151
163
|
if (admitted())
|
|
152
164
|
this.emit(event, isCurrent);
|
|
153
165
|
},
|
|
166
|
+
bindPendingPublications: (flush) => {
|
|
167
|
+
if (!isCurrent())
|
|
168
|
+
return;
|
|
169
|
+
const pending = () => {
|
|
170
|
+
if (isCurrent())
|
|
171
|
+
flush();
|
|
172
|
+
};
|
|
173
|
+
this.pendingPublications = pending;
|
|
174
|
+
},
|
|
154
175
|
dispose: () => {
|
|
155
176
|
if (!active)
|
|
156
177
|
return;
|
|
@@ -162,7 +183,7 @@ export class WorkflowActivityHub {
|
|
|
162
183
|
this.roots.clear();
|
|
163
184
|
this.advance();
|
|
164
185
|
this.record("SourceUnavailable");
|
|
165
|
-
this.broadcast(this.
|
|
186
|
+
this.broadcast(this.currentSnapshotFrame());
|
|
166
187
|
},
|
|
167
188
|
};
|
|
168
189
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workflow-activity-hub.js","sourceRoot":"","sources":["../../../src/core/extensions/workflow-activity-hub.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAoBzC,MAAM,OAAO,mBAAmB;IACd,WAAW,CAAoD;IAChF,YAAY,WAAW,GAAsD,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,EAAE;QAC1F,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IAChC,CAAC;IACO,MAAM,GAA8B,EAAE,KAAK,EAAE,UAAU,EAAE,EAAE,QAAQ,EAAE,CAAC,EAAE,CAAC;IACzE,YAAY,GAA2C,aAAa,CAAC;IACrE,KAAK,GAAG,IAAI,GAAG,EAAgC,CAAC;IAChD,SAAS,GAAG,IAAI,GAAG,EAAiB,CAAC;IACrC,QAAQ,GAAoC,EAAE,CAAC;IAC/C,QAAQ,GAAG,K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IAAI,CAAC,iBAAiB,GAAG,EAAE,CAAC;QAC5B,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,SAAS;YAAE,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;IAC9D,CAAC;IACD,WAAW;QACV,OAAO,eAAe,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACvC,CAAC;IACO,MAAM,CAAC,IAA2C;QACzD,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,GAAG,IAAI,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;QACzD,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,GAAG,GAAG;YAAE,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;IACvD,CAAC;CACD","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type {\n\tWorkflowActivityFrame,\n\tWorkflowActivityObserver,\n\tWorkflowActivityPublisher,\n\tWorkflowActivitySnapshotFrame,\n\tWorkflowActivitySubscription,\n\tWorkflowEvent,\n\tWorkflowObservationCursor,\n\tWorkflowObservationDiagnostic,\n\tWorkflowRootActivity,\n} from \"./workflow-events.js\";\n\ninterface ObserverLease {\n\tobserver: WorkflowActivityObserver;\n\tqueue: WorkflowActivityFrame[];\n\tdelivering: boolean;\n\tactive: boolean;\n}\n\nexport class WorkflowActivityHub {\n\tprivate readonly runDelivery: (operation: () => Promise<void>) => Promise<void>;\n\tconstructor(runDelivery: (operation: () => Promise<void>) => Promise<void> = (run) => run()) {\n\t\tthis.runDelivery = runDelivery;\n\t}\n\tprivate cursor: WorkflowObservationCursor = { epoch: randomUUID(), revision: 0 };\n\tprivate availability: \"ready\" | \"recovering\" | \"unavailable\" = \"unavailable\";\n\tprivate roots = new Map<string, WorkflowRootActivity>();\n\tprivate observers = new Set<ObserverLease>();\n\tprivate failures: WorkflowObservationDiagnostic[] = [];\n\tprivate disposed = false;\n\tprivate dispatch?: (event: WorkflowEvent, isCurrent: () => boolean) => Promise<void>;\n\tprivate pendingDispatches: (() => void)[] = [];\n\tbindDispatcher(dispatch: (event: WorkflowEvent, isCurrent: () => boolean) => Promise<void>): void {\n\t\tif (this.disposed) return;\n\t\tthis.dispatch = dispatch;\n\t\tfor (const deliver of this.pendingDispatches) deliver();\n\t\tthis.pendingDispatches = [];\n\t}\n\tprivate emit(event: WorkflowEvent, isCurrent: () => boolean): void {\n\t\tconst copy = structuredClone(event);\n\t\tconst deliver = () =>\n\t\t\tqueueMicrotask(() => {\n\t\t\t\tif (!isCurrent()) return;\n\t\t\t\tvoid this.dispatch?.(copy, isCurrent).catch(() => this.record(\"ObserverDeliveryFailed\"));\n\t\t\t});\n\t\tif (this.dispatch) deliver();\n\t\telse this.pendingDispatches.push(deliver);\n\t}\n\n\tgetSnapshotFrame(): WorkflowActivitySnapshotFrame {\n\t\treturn this.availability === \"ready\"\n\t\t\t? {\n\t\t\t\t\tkind: \"snapshot\",\n\t\t\t\t\tcursor: { ...this.cursor },\n\t\t\t\t\tavailability: \"ready\",\n\t\t\t\t\troots: [...this.roots.values()].map((root) => ({ ...root })),\n\t\t\t\t}\n\t\t\t: { kind: \"snapshot\", cursor: { ...this.cursor }, availability: this.availability };\n\t}\n\tobserveWorkflowActivity(observer: WorkflowActivityObserver): WorkflowActivitySubscription {\n\t\tconst lease: ObserverLease = { observer, queue: [], delivering: false, active: true };\n\t\tif (this.disposed) {\n\t\t\tthis.record(\"ObserverDisposed\");\n\t\t\treturn { dispose: () => {} };\n\t\t}\n\t\tif (this.availability !== \"ready\")\n\t\t\tthis.record(this.availability === \"recovering\" ? \"SourceRecovering\" : \"SourceUnavailable\");\n\t\tthis.observers.add(lease);\n\t\tthis.enqueue(lease, this.getSnapshotFrame());\n\t\treturn { dispose: () => this.disposeLease(lease) };\n\t}\n\tprivate disposeLease(lease: ObserverLease): void {\n\t\tif (!lease.active) return;\n\t\tlease.active = false;\n\t\tlease.queue = [];\n\t\tthis.observers.delete(lease);\n\t\tthis.record(\"ObserverDisposed\");\n\t}\n\tprivate enqueue(lease: ObserverLease, frame: WorkflowActivityFrame): void {\n\t\tif (lease.queue.length >= 256) {\n\t\t\tlease.queue = [this.getSnapshotFrame()];\n\t\t\tthis.record(\"ObserverOverflow\");\n\t\t} else lease.queue.push(frame);\n\t\tif (lease.delivering) return;\n\t\tlease.delivering = true;\n\t\tvoid this.runDelivery(async () => {\n\t\t\tawait new Promise<void>((resolve) => queueMicrotask(resolve));\n\t\t\tawait this.deliver(lease);\n\t\t});\n\t}\n\tprivate async deliver(lease: ObserverLease): Promise<void> {\n\t\twhile (lease.active && lease.queue.length) {\n\t\t\ttry {\n\t\t\t\tawait lease.observer(structuredClone(lease.queue.shift()!));\n\t\t\t} catch {\n\t\t\t\tthis.record(\"ObserverDeliveryFailed\");\n\t\t\t}\n\t\t}\n\t\tlease.delivering = false;\n\t}\n\tprivate broadcast(frame: WorkflowActivityFrame): void {\n\t\tfor (const lease of this.observers) this.enqueue(lease, frame);\n\t}\n\tprivate advance(): WorkflowObservationCursor {\n\t\tthis.cursor = { ...this.cursor, revision: this.cursor.revision + 1 };\n\t\treturn { ...this.cursor };\n\t}\n\tregisterWorkflowActivityPublisher(): WorkflowActivityPublisher {\n\t\tlet active = !this.disposed;\n\t\tif (active) {\n\t\t\tthis.cursor = { epoch: randomUUID(), revision: 0 };\n\t\t\tthis.availability = \"unavailable\";\n\t\t\tthis.roots.clear();\n\t\t\tthis.record(\"SourceUnavailable\");\n\t\t\tthis.broadcast(this.getSnapshotFrame());\n\t\t}\n\t\tconst epoch = this.cursor.epoch;\n\t\tconst isCurrent = () => active && !this.disposed && this.cursor.epoch === epoch;\n\t\tconst admitted = () => {\n\t\t\tif (isCurrent()) return true;\n\t\t\tthis.record(\"PublisherFenced\");\n\t\t\treturn false;\n\t\t};\n\t\treturn {\n\t\t\tpublishSnapshot: (input) => {\n\t\t\t\tif (!admitted()) return;\n\t\t\t\tif (input.availability !== \"ready\")\n\t\t\t\t\tthis.record(input.availability === \"recovering\" ? \"SourceRecovering\" : \"SourceUnavailable\");\n\t\t\t\tthis.availability = input.availability;\n\t\t\t\tthis.roots = new Map(\n\t\t\t\t\tinput.availability === \"ready\" ? input.roots.map((root) => [root.rootRunId, { ...root }]) : [],\n\t\t\t\t);\n\t\t\t\tthis.advance();\n\t\t\t\tthis.broadcast(this.getSnapshotFrame());\n\t\t\t},\n\t\t\tpublishChanged: (root) => {\n\t\t\t\tif (!admitted()) return;\n\t\t\t\tthis.roots.set(root.rootRunId, { ...root });\n\t\t\t\tconst cursor = this.advance();\n\t\t\t\tthis.broadcast({ kind: \"changed\", cursor, root: { ...root } });\n\t\t\t\tthis.emit({ type: \"workflow_activity_changed\", cursor, root: { ...root } }, isCurrent);\n\t\t\t},\n\t\t\tpublishRemoved: (rootRunId) => {\n\t\t\t\tif (!admitted()) return;\n\t\t\t\tthis.roots.delete(rootRunId);\n\t\t\t\tthis.broadcast({ kind: \"removed\", cursor: this.advance(), rootRunId });\n\t\t\t},\n\t\t\tpublishLifecycle: (input) => {\n\t\t\t\tif (!admitted()) return;\n\t\t\t\tconst event = { ...input, cursor: this.advance() };\n\t\t\t\tthis.emit(event, isCurrent);\n\t\t\t\tif (event.target.kind === \"stage\" && event.target.status === \"completed\") {\n\t\t\t\t\tthis.emit(\n\t\t\t\t\t\t{ ...event, type: \"workflow_stage_completed\", target: { ...event.target, status: \"completed\" } },\n\t\t\t\t\t\tisCurrent,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t},\n\t\t\tpublishHeartbeat: (event) => {\n\t\t\t\tif (admitted()) this.emit(event, isCurrent);\n\t\t\t},\n\t\t\tdispose: () => {\n\t\t\t\tif (!active) return;\n\t\t\t\tconst current = admitted();\n\t\t\t\tactive = false;\n\t\t\t\tif (!current) return;\n\t\t\t\tthis.availability = \"unavailable\";\n\t\t\t\tthis.roots.clear();\n\t\t\t\tthis.advance();\n\t\t\t\tthis.record(\"SourceUnavailable\");\n\t\t\t\tthis.broadcast(this.getSnapshotFrame());\n\t\t\t},\n\t\t};\n\t}\n\tdispose(): void {\n\t\tif (this.disposed) return;\n\t\tthis.disposed = true;\n\t\tthis.dispatch = undefined;\n\t\tthis.pendingDispatches = [];\n\t\tfor (const lease of this.observers) this.disposeLease(lease);\n\t}\n\tdiagnostics(): readonly WorkflowObservationDiagnostic[] {\n\t\treturn structuredClone(this.failures);\n\t}\n\tprivate record(kind: WorkflowObservationDiagnostic[\"kind\"]): void {\n\t\tthis.failures.push({ kind, cursor: { ...this.cursor } });\n\t\tif (this.failures.length > 256) this.failures.shift();\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"workflow-activity-hub.js","sourceRoot":"","sources":["../../../src/core/extensions/workflow-activity-hub.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAoBzC,MAAM,OAAO,mBAAmB;IACd,WAAW,CAAoD;IAChF,YAAY,WAAW,GAAsD,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,EAAE;QAC1F,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IAChC,CAAC;IACO,MAAM,GAA8B,EAAE,KAAK,EAAE,UAAU,EAAE,EAAE,QAAQ,EAAE,CAAC,EAAE,CAAC;IACzE,YAAY,GAA2C,aAAa,CAAC;IACrE,KAAK,GAAG,IAAI,GAAG,EAAgC,CAAC;IAChD,SAAS,GAAG,IAAI,GAAG,EAAiB,CAAC;IACrC,QAAQ,GAAoC,EAAE,CAAC;IAC/C,QAAQ,GAAG,KAAK,CAAC;IACjB,QAAQ,CAAqE;IAC7E,iBAAiB,GAAmB,EAAE,CAAC;IAC/C,wFAAwF;IAChF,mBAAmB,CAAc;IACzC,cAAc,CAAC,QAA2E;QACzF,IAAI,IAAI,CAAC,QAAQ;YAAE,OAAO;QAC1B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,iBAAiB;YAAE,OAAO,EAAE,CAA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AI,CAAC,MAAM,CAAC,mBAAmB,CAAC,CAAC;gBACjC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,oBAAoB,EAAE,CAAC,CAAC;YAC7C,CAAC;SACD,CAAC;IACH,CAAC;IACD,OAAO;QACN,IAAI,IAAI,CAAC,QAAQ;YAAE,OAAO;QAC1B,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;QACrB,IAAI,CAAC,QAAQ,GAAG,SAAS,CAAC;QAC1B,IAAI,CAAC,iBAAiB,GAAG,EAAE,CAAC;QAC5B,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,SAAS;YAAE,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;IAC9D,CAAC;IACD,WAAW;QACV,OAAO,eAAe,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACvC,CAAC;IACO,MAAM,CAAC,IAA2C;QACzD,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,GAAG,IAAI,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;QACzD,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,GAAG,GAAG;YAAE,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;IACvD,CAAC;CACD","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type {\n\tWorkflowActivityFrame,\n\tWorkflowActivityObserver,\n\tWorkflowActivityPublisher,\n\tWorkflowActivitySnapshotFrame,\n\tWorkflowActivitySubscription,\n\tWorkflowEvent,\n\tWorkflowObservationCursor,\n\tWorkflowObservationDiagnostic,\n\tWorkflowRootActivity,\n} from \"./workflow-events.js\";\n\ninterface ObserverLease {\n\tobserver: WorkflowActivityObserver;\n\tqueue: WorkflowActivityFrame[];\n\tdelivering: boolean;\n\tactive: boolean;\n}\n\nexport class WorkflowActivityHub {\n\tprivate readonly runDelivery: (operation: () => Promise<void>) => Promise<void>;\n\tconstructor(runDelivery: (operation: () => Promise<void>) => Promise<void> = (run) => run()) {\n\t\tthis.runDelivery = runDelivery;\n\t}\n\tprivate cursor: WorkflowObservationCursor = { epoch: randomUUID(), revision: 0 };\n\tprivate availability: \"ready\" | \"recovering\" | \"unavailable\" = \"unavailable\";\n\tprivate roots = new Map<string, WorkflowRootActivity>();\n\tprivate observers = new Set<ObserverLease>();\n\tprivate failures: WorkflowObservationDiagnostic[] = [];\n\tprivate disposed = false;\n\tprivate dispatch?: (event: WorkflowEvent, isCurrent: () => boolean) => Promise<void>;\n\tprivate pendingDispatches: (() => void)[] = [];\n\t/** Publishes root changes the current publisher has coalesced but not yet published. */\n\tprivate pendingPublications?: () => void;\n\tbindDispatcher(dispatch: (event: WorkflowEvent, isCurrent: () => boolean) => Promise<void>): void {\n\t\tif (this.disposed) return;\n\t\tthis.dispatch = dispatch;\n\t\tfor (const deliver of this.pendingDispatches) deliver();\n\t\tthis.pendingDispatches = [];\n\t}\n\tprivate emit(event: WorkflowEvent, isCurrent: () => boolean): void {\n\t\tconst copy = structuredClone(event);\n\t\tconst deliver = () =>\n\t\t\tqueueMicrotask(() => {\n\t\t\t\tif (!isCurrent()) return;\n\t\t\t\tvoid this.dispatch?.(copy, isCurrent).catch(() => this.record(\"ObserverDeliveryFailed\"));\n\t\t\t});\n\t\tif (this.dispatch) deliver();\n\t\telse this.pendingDispatches.push(deliver);\n\t}\n\n\tgetSnapshotFrame(): WorkflowActivitySnapshotFrame {\n\t\tthis.pendingPublications?.();\n\t\treturn this.currentSnapshotFrame();\n\t}\n\t/** The published state as is; publications the source still coalesces are not flushed. */\n\tprivate currentSnapshotFrame(): WorkflowActivitySnapshotFrame {\n\t\treturn this.availability === \"ready\"\n\t\t\t? {\n\t\t\t\t\tkind: \"snapshot\",\n\t\t\t\t\tcursor: { ...this.cursor },\n\t\t\t\t\tavailability: \"ready\",\n\t\t\t\t\troots: [...this.roots.values()].map((root) => ({ ...root })),\n\t\t\t\t}\n\t\t\t: { kind: \"snapshot\", cursor: { ...this.cursor }, availability: this.availability };\n\t}\n\tobserveWorkflowActivity(observer: WorkflowActivityObserver): WorkflowActivitySubscription {\n\t\tconst lease: ObserverLease = { observer, queue: [], delivering: false, active: true };\n\t\tif (this.disposed) {\n\t\t\tthis.record(\"ObserverDisposed\");\n\t\t\treturn { dispose: () => {} };\n\t\t}\n\t\t// Publish coalesced changes before this observer exists, so they reach it inside its snapshot\n\t\t// rather than as frames queued ahead of it (#4009).\n\t\tthis.pendingPublications?.();\n\t\tif (this.availability !== \"ready\")\n\t\t\tthis.record(this.availability === \"recovering\" ? \"SourceRecovering\" : \"SourceUnavailable\");\n\t\tconst snapshot = this.currentSnapshotFrame();\n\t\tthis.observers.add(lease);\n\t\tthis.enqueue(lease, snapshot);\n\t\treturn { dispose: () => this.disposeLease(lease) };\n\t}\n\tprivate disposeLease(lease: ObserverLease): void {\n\t\tif (!lease.active) return;\n\t\tlease.active = false;\n\t\tlease.queue = [];\n\t\tthis.observers.delete(lease);\n\t\tthis.record(\"ObserverDisposed\");\n\t}\n\tprivate enqueue(lease: ObserverLease, frame: WorkflowActivityFrame): void {\n\t\tif (lease.queue.length >= 256) {\n\t\t\tlease.queue = [this.currentSnapshotFrame()];\n\t\t\tthis.record(\"ObserverOverflow\");\n\t\t} else lease.queue.push(frame);\n\t\tif (lease.delivering) return;\n\t\tlease.delivering = true;\n\t\tvoid this.runDelivery(async () => {\n\t\t\tawait new Promise<void>((resolve) => queueMicrotask(resolve));\n\t\t\tawait this.deliver(lease);\n\t\t});\n\t}\n\tprivate async deliver(lease: ObserverLease): Promise<void> {\n\t\twhile (lease.active && lease.queue.length) {\n\t\t\ttry {\n\t\t\t\tawait lease.observer(structuredClone(lease.queue.shift()!));\n\t\t\t} catch {\n\t\t\t\tthis.record(\"ObserverDeliveryFailed\");\n\t\t\t}\n\t\t}\n\t\tlease.delivering = false;\n\t}\n\tprivate broadcast(frame: WorkflowActivityFrame): void {\n\t\tfor (const lease of this.observers) this.enqueue(lease, frame);\n\t}\n\tprivate advance(): WorkflowObservationCursor {\n\t\tthis.cursor = { ...this.cursor, revision: this.cursor.revision + 1 };\n\t\treturn { ...this.cursor };\n\t}\n\tregisterWorkflowActivityPublisher(): WorkflowActivityPublisher {\n\t\tlet active = !this.disposed;\n\t\tif (active) {\n\t\t\tthis.cursor = { epoch: randomUUID(), revision: 0 };\n\t\t\tthis.pendingPublications = undefined;\n\t\t\tthis.availability = \"unavailable\";\n\t\t\tthis.roots.clear();\n\t\t\tthis.record(\"SourceUnavailable\");\n\t\t\tthis.broadcast(this.currentSnapshotFrame());\n\t\t}\n\t\tconst epoch = this.cursor.epoch;\n\t\tconst isCurrent = () => active && !this.disposed && this.cursor.epoch === epoch;\n\t\tconst admitted = () => {\n\t\t\tif (isCurrent()) return true;\n\t\t\tthis.record(\"PublisherFenced\");\n\t\t\treturn false;\n\t\t};\n\t\treturn {\n\t\t\tpublishSnapshot: (input) => {\n\t\t\t\tif (!admitted()) return;\n\t\t\t\tif (input.availability !== \"ready\")\n\t\t\t\t\tthis.record(input.availability === \"recovering\" ? \"SourceRecovering\" : \"SourceUnavailable\");\n\t\t\t\tthis.availability = input.availability;\n\t\t\t\tthis.roots = new Map(\n\t\t\t\t\tinput.availability === \"ready\" ? input.roots.map((root) => [root.rootRunId, { ...root }]) : [],\n\t\t\t\t);\n\t\t\t\tthis.advance();\n\t\t\t\tthis.broadcast(this.currentSnapshotFrame());\n\t\t\t},\n\t\t\tpublishChanged: (root) => {\n\t\t\t\tif (!admitted()) return;\n\t\t\t\tthis.roots.set(root.rootRunId, { ...root });\n\t\t\t\tconst cursor = this.advance();\n\t\t\t\tthis.broadcast({ kind: \"changed\", cursor, root: { ...root } });\n\t\t\t\tthis.emit({ type: \"workflow_activity_changed\", cursor, root: { ...root } }, isCurrent);\n\t\t\t},\n\t\t\tpublishRemoved: (rootRunId) => {\n\t\t\t\tif (!admitted()) return;\n\t\t\t\tthis.roots.delete(rootRunId);\n\t\t\t\tthis.broadcast({ kind: \"removed\", cursor: this.advance(), rootRunId });\n\t\t\t},\n\t\t\tpublishLifecycle: (input) => {\n\t\t\t\tif (!admitted()) return;\n\t\t\t\tconst event = { ...input, cursor: this.advance() };\n\t\t\t\tthis.emit(event, isCurrent);\n\t\t\t\tif (event.target.kind === \"stage\" && event.target.status === \"completed\") {\n\t\t\t\t\tthis.emit(\n\t\t\t\t\t\t{ ...event, type: \"workflow_stage_completed\", target: { ...event.target, status: \"completed\" } },\n\t\t\t\t\t\tisCurrent,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t},\n\t\t\tpublishHeartbeat: (event) => {\n\t\t\t\tif (admitted()) this.emit(event, isCurrent);\n\t\t\t},\n\t\t\tbindPendingPublications: (flush) => {\n\t\t\t\tif (!isCurrent()) return;\n\t\t\t\tconst pending = () => {\n\t\t\t\t\tif (isCurrent()) flush();\n\t\t\t\t};\n\t\t\t\tthis.pendingPublications = pending;\n\t\t\t},\n\t\t\tdispose: () => {\n\t\t\t\tif (!active) return;\n\t\t\t\tconst current = admitted();\n\t\t\t\tactive = false;\n\t\t\t\tif (!current) return;\n\t\t\t\tthis.availability = \"unavailable\";\n\t\t\t\tthis.roots.clear();\n\t\t\t\tthis.advance();\n\t\t\t\tthis.record(\"SourceUnavailable\");\n\t\t\t\tthis.broadcast(this.currentSnapshotFrame());\n\t\t\t},\n\t\t};\n\t}\n\tdispose(): void {\n\t\tif (this.disposed) return;\n\t\tthis.disposed = true;\n\t\tthis.dispatch = undefined;\n\t\tthis.pendingDispatches = [];\n\t\tfor (const lease of this.observers) this.disposeLease(lease);\n\t}\n\tdiagnostics(): readonly WorkflowObservationDiagnostic[] {\n\t\treturn structuredClone(this.failures);\n\t}\n\tprivate record(kind: WorkflowObservationDiagnostic[\"kind\"]): void {\n\t\tthis.failures.push({ kind, cursor: { ...this.cursor } });\n\t\tif (this.failures.length > 256) this.failures.shift();\n\t}\n}\n"]}
|
|
@@ -159,6 +159,11 @@ export interface WorkflowActivityPublisher {
|
|
|
159
159
|
publishRemoved(rootRunId: string): void;
|
|
160
160
|
publishLifecycle(event: Omit<WorkflowLifecycleEvent, "cursor">): void;
|
|
161
161
|
publishHeartbeat(event: WorkflowHeartbeatEvent): void;
|
|
162
|
+
/**
|
|
163
|
+
* Registers how to publish root changes the source has coalesced but not yet published, so
|
|
164
|
+
* every read of the published activity sees them first.
|
|
165
|
+
*/
|
|
166
|
+
bindPendingPublications?(flush: () => void): void;
|
|
162
167
|
dispose(): void;
|
|
163
168
|
}
|
|
164
169
|
export interface WorkflowObservationDiagnostic {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workflow-events.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/workflow-events.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,qBAAqB,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAAC;AACnE,MAAM,MAAM,sBAAsB,GAC/B,WAAW,GACX,wBAAwB,GACxB,UAAU,GACV,UAAU,GACV,gBAAgB,GAChB,qBAAqB,GACrB,QAAQ,GACR,WAAW,CAAC;AAGf,MAAM,MAAM,iBAAiB,GAC1B,SAAS,GACT,SAAS,GACT,QAAQ,GACR,WAAW,GACX,SAAS,GACT,WAAW,GACX,SAAS,GACT,QAAQ,GACR,QAAQ,CAAC;AACZ,MAAM,MAAM,mBAAmB,GAC5B,SAAS,GACT,SAAS,GACT,gBAAgB,GAChB,QAAQ,GACR,SAAS,GACT,WAAW,GACX,QAAQ,GACR,SAAS,CAAC;AACb,MAAM,MAAM,sBAAsB,GAAG,SAAS,GAAG,SAAS,GAAG,WAAW,GAAG,QAAQ,GAAG,QAAQ,GAAG,WAAW,CAAC;AAC7G,MAAM,MAAM,qBAAqB,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,QAAQ,CAAC;AAEzE,yFAAyF;AACzF,MAAM,WAAW,uBAAuB;IACvC,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,OAAO,GAAG,SAAS,GAAG,QAAQ,GAAG,QAAQ,GAAG,QAA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AClC,IAAI,EAAE,oBAAoB,CAAC;CAC3B;AACD,MAAM,WAAW,sBAAsB;IACtC,IAAI,EAAE,oBAAoB,CAAC;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,EAAE,MAAM,CAAC;IACvB,WAAW,EAAE,MAAM,CAAC;IACpB,eAAe,EAAE,MAAM,CAAC;CACxB;AACD,MAAM,MAAM,aAAa,GACtB,sBAAsB,GACtB,2BAA2B,GAC3B,4BAA4B,GAC5B,sBAAsB,CAAC;AAC1B,MAAM,WAAW,yBAAyB;IACzC,eAAe,CAAC,KAAK,EAAE,6BAA6B,GAAG,IAAI,CAAC;IAC5D,cAAc,CAAC,IAAI,EAAE,oBAAoB,GAAG,IAAI,CAAC;IACjD,cAAc,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACxC,gBAAgB,CAAC,KAAK,EAAE,IAAI,CAAC,sBAAsB,EAAE,QAAQ,CAAC,GAAG,IAAI,CAAC;IACtE,gBAAgB,CAAC,KAAK,EAAE,sBAAsB,GAAG,IAAI,CAAC;IACtD;;;OAGG;IACH,uBAAuB,CAAC,CAAC,KAAK,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC;IAClD,OAAO,IAAI,IAAI,CAAC;CAChB;AACD,MAAM,WAAW,6BAA6B;IAC7C,IAAI,EACD,kBAAkB,GAClB,kBAAkB,GAClB,mBAAmB,GACnB,wBAAwB,GACxB,kBAAkB,GAClB,iBAAiB,CAAC;IACrB,MAAM,EAAE,yBAAyB,CAAC;CAClC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workflow-events.js","sourceRoot":"","sources":["../../../src/core/extensions/workflow-events.ts"],"names":[],"mappings":"","sourcesContent":["export type WorkflowActivityState = \"working\" | \"idle\" | \"blocked\";\nexport type WorkflowActivityReason =\n\t| \"executing\"\n\t| \"automatic_continuation\"\n\t| \"retrying\"\n\t| \"stopping\"\n\t| \"awaiting_input\"\n\t| \"manual_intervention\"\n\t| \"paused\"\n\t| \"quiescent\";\n\n// Kept in sync with workflows/shared/store-types without a host runtime dependency.\nexport type WorkflowRunStatus =\n\t| \"pending\"\n\t| \"running\"\n\t| \"paused\"\n\t| \"completed\"\n\t| \"skipped\"\n\t| \"cancelled\"\n\t| \"blocked\"\n\t| \"failed\"\n\t| \"killed\";\nexport type WorkflowStageStatus =\n\t| \"pending\"\n\t| \"running\"\n\t| \"awaiting_input\"\n\t| \"paused\"\n\t| \"blocked\"\n\t| \"completed\"\n\t| \"failed\"\n\t| \"skipped\";\nexport type WorkflowToolNodeStatus = \"pending\" | \"running\" | \"completed\" | \"failed\" | \"cached\" | \"cancelled\";\nexport type WorkflowControlAction = \"quit\" | \"kill\" | \"pause\" | \"resume\";\n\n/** Snapshot-safe descriptor of a human-input prompt waiting on a workflow graph node. */\nexport interface WorkflowGraphNodePrompt {\n\tid: string;\n\tkind: \"input\" | \"confirm\" | \"select\" | \"editor\" | \"custom\";\n\tmessage: string;\n\tchoices?: readonly string[];\n\tcreatedAt: number;\n}\ninterface WorkflowGraphNodeBase {\n\t/** Graph-unique node id: run-local in the root run, `${runId}:${nodeId}` inside nested child runs. */\n\tid: string;\n\t/** Run that owns the node. */\n\trunId: string;\n\t/** Run-local stage id or tool node id. */\n\tnodeId: string;\n\tname: string;\n\t/** Graph-unique ids of the node's parents. */\n\tparentIds: readonly string[];\n\t/** Admission order shared by stages and tool nodes within one run. */\n\texecutionOrder?: number;\n\t/** Nested workflow depth; 0 for the root run. */\n\tdepth: number;\n}\nexport interface WorkflowGraphStageNode extends WorkflowGraphNodeBase {\n\tkind: \"stage\";\n\tstatus: WorkflowStageStatus;\n\tpendingPrompt?: WorkflowGraphNodePrompt;\n}\nexport interface WorkflowGraphToolNode extends WorkflowGraphNodeBase {\n\tkind: \"tool\";\n\tstatus: WorkflowToolNodeStatus;\n\t/** Invocation ordinal of this `ctx.tool` call within its run. */\n\tordinal: number;\n}\nexport type WorkflowGraphNode = WorkflowGraphStageNode | WorkflowGraphToolNode;\n/** A human-input prompt raised by a run itself rather than by one of its stages. */\nexport interface WorkflowGraphRunPrompt extends WorkflowGraphNodePrompt {\n\t/** Run that owns the prompt. */\n\trunId: string;\n}\n/** Expanded graph of one root run, including nested child workflow runs. */\nexport interface WorkflowRootGraph {\n\tnodes: readonly WorkflowGraphNode[];\n\t/** Run-level prompts awaiting an answer; absent when there are none. */\n\trunPrompts?: readonly WorkflowGraphRunPrompt[];\n}\n\nexport interface WorkflowRootActivity {\n\trootRunId: string;\n\townerSessionId: string;\n\tstate: WorkflowActivityState;\n\treason: WorkflowActivityReason;\n\tactiveExecutionCount: number;\n\tactionableBlockCount: number;\n\tblockedPromptKind?: WorkflowGraphNodePrompt[\"kind\"];\n\tendedStatus?: Extract<WorkflowRunStatus, \"completed\" | \"cancelled\" | \"killed\" | \"failed\">;\n\tneedsAttention: boolean;\n\t/** Graph topology and node statuses; absent when the publisher reports no graph. */\n\tgraph?: WorkflowRootGraph;\n}\nexport interface WorkflowObservationCursor {\n\tepoch: string;\n\trevision: number;\n}\nexport type WorkflowActivitySnapshotInput =\n\t| { availability: \"ready\"; roots: readonly WorkflowRootActivity[] }\n\t| { availability: \"recovering\" | \"unavailable\" };\nexport type WorkflowActivitySnapshotFrame = WorkflowActivitySnapshotInput & {\n\tkind: \"snapshot\";\n\tcursor: WorkflowObservationCursor;\n};\nexport type WorkflowActivityFrame =\n\t| WorkflowActivitySnapshotFrame\n\t| { kind: \"changed\"; cursor: WorkflowObservationCursor; root: WorkflowRootActivity }\n\t| { kind: \"removed\"; cursor: WorkflowObservationCursor; rootRunId: string };\nexport type WorkflowActivityObserver = (frame: WorkflowActivityFrame) => void | Promise<void>;\nexport interface WorkflowActivitySubscription {\n\tdispose(): void;\n}\nexport type WorkflowLifecycleDelivery = \"live\" | \"replay\";\nexport type WorkflowLifecycleTarget =\n\t| {\n\t\t\tkind: \"run\";\n\t\t\trunId: string;\n\t\t\tpreviousStatus?: WorkflowRunStatus;\n\t\t\tstatus: WorkflowRunStatus;\n\t\t\taction?: WorkflowControlAction;\n\t }\n\t| {\n\t\t\tkind: \"stage\";\n\t\t\trunId: string;\n\t\t\tstageId: string;\n\t\t\tstageName: string;\n\t\t\tpreviousStatus?: WorkflowStageStatus;\n\t\t\tstatus: WorkflowStageStatus;\n\t }\n\t| {\n\t\t\tkind: \"tool\";\n\t\t\trunId: string;\n\t\t\ttoolNodeId: string;\n\t\t\ttoolName: string;\n\t\t\tpreviousStatus?: WorkflowToolNodeStatus;\n\t\t\tstatus: WorkflowToolNodeStatus;\n\t }\n\t| { kind: \"prompt\"; runId: string; stageId?: string; promptId: string; status: \"opened\" | \"answered\" | \"cancelled\" };\nexport interface WorkflowLifecycleEvent {\n\ttype: \"workflow_lifecycle\";\n\teventId: string;\n\tcursor: WorkflowObservationCursor;\n\trunId: string;\n\trootRunId: string;\n\townerSessionId: string;\n\toccurredAt: number;\n\tobservedAt: number;\n\tdelivery: WorkflowLifecycleDelivery;\n\ttarget: WorkflowLifecycleTarget;\n\tattribution?: \"user\" | \"agent\" | \"scheduler\" | \"recovery\" | \"unknown\";\n}\nexport interface WorkflowStageCompletedEvent extends Omit<WorkflowLifecycleEvent, \"type\" | \"target\"> {\n\ttype: \"workflow_stage_completed\";\n\ttarget: Extract<WorkflowLifecycleTarget, { kind: \"stage\" }> & { status: \"completed\" };\n}\nexport interface WorkflowActivityChangedEvent {\n\ttype: \"workflow_activity_changed\";\n\tcursor: WorkflowObservationCursor;\n\troot: WorkflowRootActivity;\n}\nexport interface WorkflowHeartbeatEvent {\n\ttype: \"workflow_heartbeat\";\n\trunId: string;\n\trootRunId: string;\n\townerSessionId: string;\n\tscheduledAt: number;\n\tintervalMinutes: number;\n}\nexport type WorkflowEvent =\n\t| WorkflowLifecycleEvent\n\t| WorkflowStageCompletedEvent\n\t| WorkflowActivityChangedEvent\n\t| WorkflowHeartbeatEvent;\nexport interface WorkflowActivityPublisher {\n\tpublishSnapshot(input: WorkflowActivitySnapshotInput): void;\n\tpublishChanged(root: WorkflowRootActivity): void;\n\tpublishRemoved(rootRunId: string): void;\n\tpublishLifecycle(event: Omit<WorkflowLifecycleEvent, \"cursor\">): void;\n\tpublishHeartbeat(event: WorkflowHeartbeatEvent): void;\n\tdispose(): void;\n}\nexport interface WorkflowObservationDiagnostic {\n\tkind:\n\t\t| \"ObserverDisposed\"\n\t\t| \"SourceRecovering\"\n\t\t| \"SourceUnavailable\"\n\t\t| \"ObserverDeliveryFailed\"\n\t\t| \"ObserverOverflow\"\n\t\t| \"PublisherFenced\";\n\tcursor: WorkflowObservationCursor;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"workflow-events.js","sourceRoot":"","sources":["../../../src/core/extensions/workflow-events.ts"],"names":[],"mappings":"","sourcesContent":["export type WorkflowActivityState = \"working\" | \"idle\" | \"blocked\";\nexport type WorkflowActivityReason =\n\t| \"executing\"\n\t| \"automatic_continuation\"\n\t| \"retrying\"\n\t| \"stopping\"\n\t| \"awaiting_input\"\n\t| \"manual_intervention\"\n\t| \"paused\"\n\t| \"quiescent\";\n\n// Kept in sync with workflows/shared/store-types without a host runtime dependency.\nexport type WorkflowRunStatus =\n\t| \"pending\"\n\t| \"running\"\n\t| \"paused\"\n\t| \"completed\"\n\t| \"skipped\"\n\t| \"cancelled\"\n\t| \"blocked\"\n\t| \"failed\"\n\t| \"killed\";\nexport type WorkflowStageStatus =\n\t| \"pending\"\n\t| \"running\"\n\t| \"awaiting_input\"\n\t| \"paused\"\n\t| \"blocked\"\n\t| \"completed\"\n\t| \"failed\"\n\t| \"skipped\";\nexport type WorkflowToolNodeStatus = \"pending\" | \"running\" | \"completed\" | \"failed\" | \"cached\" | \"cancelled\";\nexport type WorkflowControlAction = \"quit\" | \"kill\" | \"pause\" | \"resume\";\n\n/** Snapshot-safe descriptor of a human-input prompt waiting on a workflow graph node. */\nexport interface WorkflowGraphNodePrompt {\n\tid: string;\n\tkind: \"input\" | \"confirm\" | \"select\" | \"editor\" | \"custom\";\n\tmessage: string;\n\tchoices?: readonly string[];\n\tcreatedAt: number;\n}\ninterface WorkflowGraphNodeBase {\n\t/** Graph-unique node id: run-local in the root run, `${runId}:${nodeId}` inside nested child runs. */\n\tid: string;\n\t/** Run that owns the node. */\n\trunId: string;\n\t/** Run-local stage id or tool node id. */\n\tnodeId: string;\n\tname: string;\n\t/** Graph-unique ids of the node's parents. */\n\tparentIds: readonly string[];\n\t/** Admission order shared by stages and tool nodes within one run. */\n\texecutionOrder?: number;\n\t/** Nested workflow depth; 0 for the root run. */\n\tdepth: number;\n}\nexport interface WorkflowGraphStageNode extends WorkflowGraphNodeBase {\n\tkind: \"stage\";\n\tstatus: WorkflowStageStatus;\n\tpendingPrompt?: WorkflowGraphNodePrompt;\n}\nexport interface WorkflowGraphToolNode extends WorkflowGraphNodeBase {\n\tkind: \"tool\";\n\tstatus: WorkflowToolNodeStatus;\n\t/** Invocation ordinal of this `ctx.tool` call within its run. */\n\tordinal: number;\n}\nexport type WorkflowGraphNode = WorkflowGraphStageNode | WorkflowGraphToolNode;\n/** A human-input prompt raised by a run itself rather than by one of its stages. */\nexport interface WorkflowGraphRunPrompt extends WorkflowGraphNodePrompt {\n\t/** Run that owns the prompt. */\n\trunId: string;\n}\n/** Expanded graph of one root run, including nested child workflow runs. */\nexport interface WorkflowRootGraph {\n\tnodes: readonly WorkflowGraphNode[];\n\t/** Run-level prompts awaiting an answer; absent when there are none. */\n\trunPrompts?: readonly WorkflowGraphRunPrompt[];\n}\n\nexport interface WorkflowRootActivity {\n\trootRunId: string;\n\townerSessionId: string;\n\tstate: WorkflowActivityState;\n\treason: WorkflowActivityReason;\n\tactiveExecutionCount: number;\n\tactionableBlockCount: number;\n\tblockedPromptKind?: WorkflowGraphNodePrompt[\"kind\"];\n\tendedStatus?: Extract<WorkflowRunStatus, \"completed\" | \"cancelled\" | \"killed\" | \"failed\">;\n\tneedsAttention: boolean;\n\t/** Graph topology and node statuses; absent when the publisher reports no graph. */\n\tgraph?: WorkflowRootGraph;\n}\nexport interface WorkflowObservationCursor {\n\tepoch: string;\n\trevision: number;\n}\nexport type WorkflowActivitySnapshotInput =\n\t| { availability: \"ready\"; roots: readonly WorkflowRootActivity[] }\n\t| { availability: \"recovering\" | \"unavailable\" };\nexport type WorkflowActivitySnapshotFrame = WorkflowActivitySnapshotInput & {\n\tkind: \"snapshot\";\n\tcursor: WorkflowObservationCursor;\n};\nexport type WorkflowActivityFrame =\n\t| WorkflowActivitySnapshotFrame\n\t| { kind: \"changed\"; cursor: WorkflowObservationCursor; root: WorkflowRootActivity }\n\t| { kind: \"removed\"; cursor: WorkflowObservationCursor; rootRunId: string };\nexport type WorkflowActivityObserver = (frame: WorkflowActivityFrame) => void | Promise<void>;\nexport interface WorkflowActivitySubscription {\n\tdispose(): void;\n}\nexport type WorkflowLifecycleDelivery = \"live\" | \"replay\";\nexport type WorkflowLifecycleTarget =\n\t| {\n\t\t\tkind: \"run\";\n\t\t\trunId: string;\n\t\t\tpreviousStatus?: WorkflowRunStatus;\n\t\t\tstatus: WorkflowRunStatus;\n\t\t\taction?: WorkflowControlAction;\n\t }\n\t| {\n\t\t\tkind: \"stage\";\n\t\t\trunId: string;\n\t\t\tstageId: string;\n\t\t\tstageName: string;\n\t\t\tpreviousStatus?: WorkflowStageStatus;\n\t\t\tstatus: WorkflowStageStatus;\n\t }\n\t| {\n\t\t\tkind: \"tool\";\n\t\t\trunId: string;\n\t\t\ttoolNodeId: string;\n\t\t\ttoolName: string;\n\t\t\tpreviousStatus?: WorkflowToolNodeStatus;\n\t\t\tstatus: WorkflowToolNodeStatus;\n\t }\n\t| { kind: \"prompt\"; runId: string; stageId?: string; promptId: string; status: \"opened\" | \"answered\" | \"cancelled\" };\nexport interface WorkflowLifecycleEvent {\n\ttype: \"workflow_lifecycle\";\n\teventId: string;\n\tcursor: WorkflowObservationCursor;\n\trunId: string;\n\trootRunId: string;\n\townerSessionId: string;\n\toccurredAt: number;\n\tobservedAt: number;\n\tdelivery: WorkflowLifecycleDelivery;\n\ttarget: WorkflowLifecycleTarget;\n\tattribution?: \"user\" | \"agent\" | \"scheduler\" | \"recovery\" | \"unknown\";\n}\nexport interface WorkflowStageCompletedEvent extends Omit<WorkflowLifecycleEvent, \"type\" | \"target\"> {\n\ttype: \"workflow_stage_completed\";\n\ttarget: Extract<WorkflowLifecycleTarget, { kind: \"stage\" }> & { status: \"completed\" };\n}\nexport interface WorkflowActivityChangedEvent {\n\ttype: \"workflow_activity_changed\";\n\tcursor: WorkflowObservationCursor;\n\troot: WorkflowRootActivity;\n}\nexport interface WorkflowHeartbeatEvent {\n\ttype: \"workflow_heartbeat\";\n\trunId: string;\n\trootRunId: string;\n\townerSessionId: string;\n\tscheduledAt: number;\n\tintervalMinutes: number;\n}\nexport type WorkflowEvent =\n\t| WorkflowLifecycleEvent\n\t| WorkflowStageCompletedEvent\n\t| WorkflowActivityChangedEvent\n\t| WorkflowHeartbeatEvent;\nexport interface WorkflowActivityPublisher {\n\tpublishSnapshot(input: WorkflowActivitySnapshotInput): void;\n\tpublishChanged(root: WorkflowRootActivity): void;\n\tpublishRemoved(rootRunId: string): void;\n\tpublishLifecycle(event: Omit<WorkflowLifecycleEvent, \"cursor\">): void;\n\tpublishHeartbeat(event: WorkflowHeartbeatEvent): void;\n\t/**\n\t * Registers how to publish root changes the source has coalesced but not yet published, so\n\t * every read of the published activity sees them first.\n\t */\n\tbindPendingPublications?(flush: () => void): void;\n\tdispose(): void;\n}\nexport interface WorkflowObservationDiagnostic {\n\tkind:\n\t\t| \"ObserverDisposed\"\n\t\t| \"SourceRecovering\"\n\t\t| \"SourceUnavailable\"\n\t\t| \"ObserverDeliveryFailed\"\n\t\t| \"ObserverOverflow\"\n\t\t| \"PublisherFenced\";\n\tcursor: WorkflowObservationCursor;\n}\n"]}
|
package/dist/core/messages.d.ts
CHANGED
|
@@ -102,6 +102,11 @@ export declare function deferMessagesInterleavedWithToolBatch<TMessage extends A
|
|
|
102
102
|
export interface ToolCallPairRepairOptions {
|
|
103
103
|
/** Close a final unanswered tool call when reopening an inactive session. */
|
|
104
104
|
repairTrailing?: boolean;
|
|
105
|
+
/**
|
|
106
|
+
* Calls that are running again (an interrupted question asked anew on resume): they are
|
|
107
|
+
* pending, not interrupted, so no interrupted result is inserted for them.
|
|
108
|
+
*/
|
|
109
|
+
inFlightToolCallIds?: ReadonlySet<string>;
|
|
105
110
|
}
|
|
106
111
|
export declare function repairOrphanToolResults<TMessage extends AgentMessage>(messages: TMessage[], options?: ToolCallPairRepairOptions): (TMessage | ToolResultMessage)[];
|
|
107
112
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../src/core/messages.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AACnG,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAGlE,eAAO,MAAM,qBAAqB,iGAGjC,CAAC;AAEF,eAAO,MAAM,qBAAqB,eAAe,CAAC;AAElD;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACpC,IAAI,EAAE,eAAe,CAAC;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,SAAS,EAAE,OAAO,CAAC;IACnB,SAAS,EAAE,OAAO,CAAC;IACnB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,SAAS,EAAE,MAAM,CAAC;IAClB,qEAAqE;IACrE,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC7B;AAED;;;GAGG;AAEH,MAAM,WAAW,aAAa,CAAC,CAAC,GAAG,OAAO;IACzC,IAAI,EAAE,QAAQ,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,GAAG,CAAC,WAAW,GA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,GAAG,CAAC,WAAW,GAAG,YAAY,CAAC,EAAE,EAChD,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,OAAO,GAAG,SAAS,EAC5B,SAAS,EAAE,MAAM,EACjB,kBAAkB,CAAC,EAAE,OAAO,EAC5B,iBAAiB,CAAC,EAAE,MAAM,GACxB,0BAA0B,CAY5B;AA2BD;;;;;;;;GAQG;AACH,wBAAgB,qCAAqC,CAAC,QAAQ,SAAS,YAAY,EAAE,QAAQ,EAAE,QAAQ,EAAE,GAAG,QAAQ,EAAE,CAuCrH;AAED;;;;;;;;;;GAUG;AACH,MAAM,WAAW,yBAAyB;IACzC,6EAA6E;IAC7E,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB;;;OAGG;IACH,mBAAmB,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;CAC1C;AAED,wBAAgB,uBAAuB,CAAC,QAAQ,SAAS,YAAY,EACpE,QAAQ,EAAE,QAAQ,EAAE,EACpB,OAAO,GAAE,yBAA8B,GACrC,CAAC,QAAQ,GAAG,iBAAiB,CAAC,EAAE,CAsElC;AAID;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,QAAQ,EAAE,YAAY,EAAE,GAAG,OAAO,EAAE,CAiDhE"}
|
package/dist/core/messages.js
CHANGED
|
@@ -253,7 +253,7 @@ export function repairOrphanToolResults(messages, options = {}) {
|
|
|
253
253
|
const repaired = [];
|
|
254
254
|
const flushUnanswered = () => {
|
|
255
255
|
for (const call of pendingToolCalls) {
|
|
256
|
-
if (answeredToolCallIds?.has(call.id))
|
|
256
|
+
if (answeredToolCallIds?.has(call.id) || options.inFlightToolCallIds?.has(call.id))
|
|
257
257
|
continue;
|
|
258
258
|
const interrupted = {
|
|
259
259
|
role: "toolResult",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messages.js","sourceRoot":"","sources":["../../src/core/messages.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,EAAE,mBAAmB,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AM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC;IACjC,OAAO,uBAAuB,CAAC,mBAAmB,CAAC,SAAS,CAAC,CAAC,CAAC;AAChE,CAAC","sourcesContent":["/**\n * Custom message types and transformers for the coding agent.\n *\n * Extends the base AgentMessage type with coding-agent specific message types,\n * and provides a transformer to convert them to LLM-compatible messages.\n */\n\nimport type { ImageContent, Message, TextContent, ToolResultMessage } from \"@bastani/pi-ai/compat\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport { uniquifyToolCallIds } from \"./context-tool-pairing.js\";\n\nexport const BRANCH_SUMMARY_PREFIX = `The following is a summary of a branch that this conversation came back from:\n\n<summary>\n`;\n\nexport const BRANCH_SUMMARY_SUFFIX = `</summary>`;\n\n/**\n * Message type for bash executions via the ! command.\n */\nexport interface BashExecutionMessage {\n\trole: \"bashExecution\";\n\tcommand: string;\n\toutput: string;\n\texitCode: number | undefined;\n\tcancelled: boolean;\n\ttruncated: boolean;\n\tfullOutputPath?: string;\n\ttimestamp: number;\n\t/** If true, this message is excluded from LLM context (!! prefix) */\n\texcludeFromContext?: boolean;\n}\n\n/**\n * Message type for extension-injected messages via sendMessage().\n * These are custom messages that extensions can inject into the conversation.\n */\n\nexport interface CustomMessage<T = unknown> {\n\trole: \"custom\";\n\tcustomType: string;\n\tcontent: string | (TextContent | ImageContent)[];\n\tdisplay: boolean;\n\tdetails?: T;\n\ttimestamp: number;\n}\n\nexport type StageAdmittedCustomMessage<T = unknown> = CustomMessage<T> & {\n\t/** Stable producer identity used for exactly-once workflow-stage admission. */\n\tstageAdmissionKey?: string;\n\t/** Whether this admission joined active stage work or started after the assistant had settled. */\n};\n\nexport interface BranchSummaryMessage {\n\trole: \"branchSummary\";\n\tsummary: string;\n\tfromId: string | null;\n\ttimestamp: number;\n}\n\n// Extend CustomAgentMessages via declaration merging\ndeclare module \"@earendil-works/pi-agent-core\" {\n\tinterface CustomAgentMessages {\n\t\tbashExecution: BashExecutionMessage;\n\t\tcustom: CustomMessage;\n\t\tbranchSummary: BranchSummaryMessage;\n\t}\n}\n\n/** Normalize lax JavaScript/legacy message input before it reaches history or providers. */\nexport function normalizeMessageContent<T extends AgentMessage>(message: T): T {\n\tswitch (message.role) {\n\t\tcase \"user\":\n\t\tcase \"assistant\":\n\t\tcase \"toolResult\":\n\t\tcase \"custom\":\n\t\t\treturn message.content == null ? ({ ...message, content: [] } as T) : message;\n\t\tdefault:\n\t\t\treturn message;\n\t}\n}\n\nexport function userLikeContentBlockIsLlmVisible(block: unknown): boolean {\n\tif (!block || typeof block !== \"object\") return false;\n\tconst candidate = block as { type?: unknown; text?: unknown };\n\tif (candidate.type === \"image\") return true;\n\tif (candidate.type === \"text\") return typeof candidate.text === \"string\" && candidate.text.trim().length > 0;\n\t// Future provider-supported blocks must fail visible; only malformed/untyped blocks fail closed.\n\treturn typeof candidate.type === \"string\" && candidate.type.trim().length > 0;\n}\n\n/** Whether user/custom content survives provider conversion as a visible input. */\nexport function userLikeContentIsLlmVisible(\n\tcontent: unknown,\n\tdeletedBlockIndexes: ReadonlySet<number> = new Set<number>(),\n): boolean {\n\tif (typeof content === \"string\") return content.trim().length > 0;\n\tif (!Array.isArray(content)) return false;\n\treturn content.some((block, index) => !deletedBlockIndexes.has(index) && userLikeContentBlockIsLlmVisible(block));\n}\n\n/** Whether an Atomic message emits an LLM-visible user-like turn boundary. */\nexport function messageStartsLlmUserTurn(\n\tmessage: AgentMessage,\n\tdeletedBlockIndexes: ReadonlySet<number> = new Set<number>(),\n): boolean {\n\tswitch (message.role) {\n\t\tcase \"user\":\n\t\t\treturn userLikeContentIsLlmVisible(message.content, deletedBlockIndexes);\n\t\tcase \"custom\":\n\t\t\treturn (\n\t\t\t\t(message as CustomMessage & { excludeFromContext?: boolean }).excludeFromContext !== true &&\n\t\t\t\tuserLikeContentIsLlmVisible(message.content, deletedBlockIndexes)\n\t\t\t);\n\t\tcase \"branchSummary\":\n\t\t\t// Empty summaries are omitted by session reconstruction. Whitespace is\n\t\t\t// visible because the branch-summary wrapper itself is non-whitespace.\n\t\t\treturn typeof message.summary === \"string\" && message.summary.length > 0;\n\t\tcase \"bashExecution\":\n\t\t\treturn message.excludeFromContext !== true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\n/** Whether an Atomic message survives conversion into provider-visible context. */\nexport function messageIsLlmVisible(\n\tmessage: AgentMessage,\n\tdeletedBlockIndexes: ReadonlySet<number> = new Set<number>(),\n): boolean {\n\tif (message.role === \"system\" || message.role === \"assistant\" || message.role === \"toolResult\") return true;\n\treturn messageStartsLlmUserTurn(message, deletedBlockIndexes);\n}\n\n/** Filter invalid user-like blocks only in transient provider-bound content. */\nfunction filterUserLikeContentBlocks(content: unknown[]): unknown[] {\n\treturn content.filter(userLikeContentBlockIsLlmVisible);\n}\n\n/** Normalize raw blocks only in the transient LLM-compatible message returned by convertToLlm. */\nfunction normalizeRawRedactedThinking(message: AgentMessage): AgentMessage {\n\tif (message.role !== \"assistant\" || !Array.isArray(message.content)) return message;\n\tlet changed = false;\n\tconst content = message.content.map((block) => {\n\t\tif (!block || typeof block !== \"object\") return block;\n\t\tconst candidate = block as { type?: unknown; data?: unknown };\n\t\tif (candidate.type !== \"redacted_thinking\" || typeof candidate.data !== \"string\") return block;\n\t\tchanged = true;\n\t\treturn {\n\t\t\ttype: \"thinking\" as const,\n\t\t\tthinking: \"\",\n\t\t\tthinkingSignature: candidate.data,\n\t\t\tredacted: true,\n\t\t};\n\t});\n\treturn changed ? ({ ...message, content } as AgentMessage) : message;\n}\n\n/**\n * Convert a BashExecutionMessage to user message text for LLM context.\n */\nexport function bashExecutionToText(msg: BashExecutionMessage): string {\n\tlet text = `Ran \\`${msg.command}\\`\\n`;\n\tif (msg.output) {\n\t\ttext += `\\`\\`\\`\\n${msg.output}\\n\\`\\`\\``;\n\t} else {\n\t\ttext += \"(no output)\";\n\t}\n\tif (msg.cancelled) {\n\t\ttext += \"\\n\\n(command cancelled)\";\n\t} else if (msg.exitCode !== null && msg.exitCode !== undefined && msg.exitCode !== 0) {\n\t\ttext += `\\n\\nCommand exited with code ${msg.exitCode}`;\n\t}\n\tif (msg.truncated && msg.fullOutputPath) {\n\t\ttext += `\\n\\n[Output truncated. Full output: ${msg.fullOutputPath}]`;\n\t}\n\treturn text;\n}\n\nexport const VERBATIM_COMPACTION_PREFIX =\n\t'The earlier conversation was compacted. Below is the verbatim transcript of the retained lines; elided spans are marked \"(filtered N lines)\".\\n\\n';\nexport const SUMMARY_COMPACTION_PREFIX = \"The following is a summary of the earlier conversation:\\n\\n\";\nconst verbatimCompactionMessages = new WeakSet<CustomMessage>();\n\nexport function isVerbatimCompactionMessage(message: CustomMessage): boolean {\n\treturn verbatimCompactionMessages.has(message);\n}\n\n/**\n * Create the visible custom-role boundary used to replay a verbatim compaction.\n *\n * `retainedTail` holds the serialized kept tail. Its text merges into the boundary text and\n * its image blocks stay intact, so preserved content is not reduced to a placeholder.\n */\nexport function createVerbatimCompactionMessage(\n\tcompactedText: string,\n\ttokensBefore: number,\n\ttimestamp: string,\n\tdetails?: unknown,\n\tretainedTail?: readonly (TextContent | ImageContent)[],\n): CustomMessage {\n\tconst prefix =\n\t\ttypeof details === \"object\" && details !== null && \"backend\" in details && details.backend === \"summary\"\n\t\t\t? SUMMARY_COMPACTION_PREFIX\n\t\t\t: VERBATIM_COMPACTION_PREFIX;\n\tconst content: (TextContent | ImageContent)[] = [{ type: \"text\", text: prefix + compactedText }];\n\tfor (const block of retainedTail ?? []) {\n\t\tconst last = content[content.length - 1];\n\t\tif (block.type === \"text\" && last.type === \"text\") last.text += block.text;\n\t\telse content.push({ ...block });\n\t}\n\t// Ensure the authoritative whole-context count survives on the message details so\n\t// the boundary renderer can show it even when the caller supplied its own details\n\t// object. An existing tokensBefore is never overridden (#2052).\n\tconst mergedDetails = (() => {\n\t\tif (details === undefined) return { tokensBefore };\n\t\tif (typeof details !== \"object\" || details === null) return details;\n\t\treturn \"tokensBefore\" in details ? details : { ...details, tokensBefore };\n\t})();\n\tconst message = createCustomMessage(\"compaction\", content, true, mergedDetails, timestamp);\n\tverbatimCompactionMessages.add(message);\n\treturn message;\n}\n\nexport function createBranchSummaryMessage(summary: string, fromId: string, timestamp: string): BranchSummaryMessage {\n\treturn {\n\t\trole: \"branchSummary\",\n\t\tsummary,\n\t\tfromId,\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n}\n\n/** Convert CustomMessageEntry to AgentMessage format */\nexport function createCustomMessage(\n\tcustomType: string,\n\tcontent: string | (TextContent | ImageContent)[],\n\tdisplay: boolean,\n\tdetails: unknown | undefined,\n\ttimestamp: string,\n\texcludeFromContext?: boolean,\n\tstageAdmissionKey?: string,\n): StageAdmittedCustomMessage {\n\tconst message: StageAdmittedCustomMessage & { excludeFromContext?: boolean } = {\n\t\trole: \"custom\",\n\t\tcustomType,\n\t\tcontent: content ?? [],\n\t\tdisplay,\n\t\tdetails,\n\t\t...(stageAdmissionKey === undefined ? {} : { stageAdmissionKey }),\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n\tif (excludeFromContext === true) message.excludeFromContext = true;\n\treturn message;\n}\n\ninterface AssistantToolCallRef {\n\tid: string;\n\tname: string;\n}\n\nfunction collectAssistantToolCalls(message: AgentMessage): AssistantToolCallRef[] {\n\tconst content = (message as { content?: unknown }).content;\n\tconst calls: AssistantToolCallRef[] = [];\n\tif (!Array.isArray(content)) return calls;\n\tfor (const block of content) {\n\t\tif (!block || typeof block !== \"object\") continue;\n\t\tconst candidate = block as { type?: unknown; id?: unknown; name?: unknown };\n\t\tif (candidate.type === \"toolCall\" && typeof candidate.id === \"string\" && typeof candidate.name === \"string\") {\n\t\t\tcalls.push({ id: candidate.id, name: candidate.name });\n\t\t}\n\t}\n\treturn calls;\n}\n\nfunction getToolResultCallId(message: AgentMessage): string | undefined {\n\tif (message.role !== \"toolResult\") return undefined;\n\tconst toolCallId = (message as { toolCallId?: unknown }).toolCallId;\n\treturn typeof toolCallId === \"string\" ? toolCallId : undefined;\n}\n\n/**\n * Keep every tool result adjacent to the assistant turn that announced it.\n *\n * A message admitted while a tool batch is still running (an Intercom delivery, a\n * workflow lifecycle card, a durable stage admission) is persisted between the tool\n * call and its result in raw history. The provider requires the results to follow the\n * call directly, so derived context defers such messages until the batch is answered.\n * The durable transcript keeps its admission order.\n */\nexport function deferMessagesInterleavedWithToolBatch<TMessage extends AgentMessage>(messages: TMessage[]): TMessage[] {\n\tlet pending: Set<string> | undefined;\n\tlet deferred: TMessage[] = [];\n\tlet changed = false;\n\tconst ordered: TMessage[] = [];\n\tconst flushDeferred = (): void => {\n\t\tif (deferred.length > 0) {\n\t\t\tordered.push(...deferred);\n\t\t\tdeferred = [];\n\t\t}\n\t\tpending = undefined;\n\t};\n\tfor (const message of messages) {\n\t\tif (message.role === \"assistant\") {\n\t\t\tflushDeferred();\n\t\t\tordered.push(message);\n\t\t\tconst calls = collectAssistantToolCalls(message);\n\t\t\tpending =\n\t\t\t\tmessage.stopReason === \"toolUse\" && calls.length > 0 ? new Set(calls.map((call) => call.id)) : undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tif (pending) {\n\t\t\tconst toolCallId = getToolResultCallId(message);\n\t\t\tif (toolCallId !== undefined && pending.has(toolCallId)) {\n\t\t\t\tordered.push(message);\n\t\t\t\tpending.delete(toolCallId);\n\t\t\t\tif (pending.size === 0) flushDeferred();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (message.role !== \"system\") {\n\t\t\t\tdeferred.push(message);\n\t\t\t\tchanged = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tordered.push(message);\n\t}\n\tflushDeferred();\n\treturn changed ? ordered : messages;\n}\n\n/**\n * Enforce the provider's tool-pairing invariant on a converted message list.\n *\n * A provider rejects orphaned/duplicate `tool_result` blocks and any later turn\n * that crosses an unanswered `tool_use`. Keep exactly the first result for each\n * announced id. If a persisted session continues after its engine died before\n * recording every result, insert provider-only error results before that later\n * turn. The repair exists only in derived context; the durable transcript stays\n * unchanged, and the text makes no claim about whether admitted work completed\n * or produced side effects.\n */\nexport interface ToolCallPairRepairOptions {\n\t/** Close a final unanswered tool call when reopening an inactive session. */\n\trepairTrailing?: boolean;\n}\n\nexport function repairOrphanToolResults<TMessage extends AgentMessage>(\n\tmessages: TMessage[],\n\toptions: ToolCallPairRepairOptions = {},\n): (TMessage | ToolResultMessage)[] {\n\tlet allowedToolCallIds: Set<string> | undefined;\n\tlet answeredToolCallIds: Set<string> | undefined;\n\tlet pendingToolCalls: AssistantToolCallRef[] = [];\n\tlet pendingTimestamp = 0;\n\tlet changed = false;\n\tconst repaired: (TMessage | ToolResultMessage)[] = [];\n\tconst flushUnanswered = (): void => {\n\t\tfor (const call of pendingToolCalls) {\n\t\t\tif (answeredToolCallIds?.has(call.id)) continue;\n\t\t\tconst interrupted: ToolResultMessage = {\n\t\t\t\trole: \"toolResult\",\n\t\t\t\ttoolCallId: call.id,\n\t\t\t\ttoolName: call.name,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Tool execution was interrupted after it started; its result is unavailable. Inspect side effects before deciding whether to retry it.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tisError: true,\n\t\t\t\ttimestamp: pendingTimestamp,\n\t\t\t};\n\t\t\trepaired.push(interrupted);\n\t\t\tchanged = true;\n\t\t}\n\t\tallowedToolCallIds = undefined;\n\t\tansweredToolCallIds = undefined;\n\t\tpendingToolCalls = [];\n\t};\n\tfor (const message of messages) {\n\t\t// Instruction/tool updates never close a pending tool batch.\n\t\tif (message.role === \"system\") {\n\t\t\trepaired.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.role === \"assistant\") {\n\t\t\tflushUnanswered();\n\t\t\tconst announcedToolCalls = collectAssistantToolCalls(message);\n\t\t\t// Only toolUse turns represent admitted executions. Error, aborted, and\n\t\t\t// length-limited turns may contain partial calls that providers discard.\n\t\t\tpendingToolCalls = message.stopReason === \"toolUse\" ? announcedToolCalls : [];\n\t\t\tallowedToolCallIds = new Set(announcedToolCalls.map((call) => call.id));\n\t\t\tansweredToolCallIds = new Set<string>();\n\t\t\tpendingTimestamp = message.timestamp;\n\t\t\trepaired.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.role === \"toolResult\") {\n\t\t\tconst toolCallId = getToolResultCallId(message);\n\t\t\tif (toolCallId && allowedToolCallIds?.has(toolCallId) && answeredToolCallIds?.has(toolCallId) === false) {\n\t\t\t\tansweredToolCallIds.add(toolCallId);\n\t\t\t\trepaired.push(message);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tchanged = true;\n\t\t\tcontinue;\n\t\t}\n\t\t// A context-excluded card admitted while a tool was still running sits between\n\t\t// the call and its result in raw history but never reaches the provider, so it\n\t\t// cannot close the pending batch.\n\t\tif (!messageStartsLlmUserTurn(message)) {\n\t\t\trepaired.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tflushUnanswered();\n\t\trepaired.push(message);\n\t}\n\tif (options.repairTrailing) flushUnanswered();\n\treturn changed ? repaired : messages;\n}\n\nconst LEGACY_COMPACTION_SUMMARY_ROLE = \"compactionSummary\";\n\n/**\n * Transform AgentMessages (including custom types) to LLM-compatible Messages.\n *\n * This is used by:\n * - Agent's transormToLlm option (for prompt calls and queued messages)\n * - Branch summarization (for summarizing abandoned branches)\n * - Custom extensions and tools\n */\nexport function convertToLlm(messages: AgentMessage[]): Message[] {\n\tconst converted = messages\n\t\t.map((rawMessage): Message | undefined => {\n\t\t\tconst m = normalizeRawRedactedThinking(normalizeMessageContent(rawMessage));\n\t\t\tconst role: string = m.role;\n\t\t\tif (role === LEGACY_COMPACTION_SUMMARY_ROLE) return undefined;\n\t\t\tswitch (m.role) {\n\t\t\t\tcase \"bashExecution\":\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: bashExecutionToText(m) }],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"custom\": {\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\tconst content =\n\t\t\t\t\t\ttypeof m.content === \"string\"\n\t\t\t\t\t\t\t? [{ type: \"text\" as const, text: m.content }]\n\t\t\t\t\t\t\t: (filterUserLikeContentBlocks(m.content) as Message[\"content\"]);\n\t\t\t\t\treturn { role: \"user\", content, timestamp: m.timestamp } as Message;\n\t\t\t\t}\n\t\t\t\tcase \"branchSummary\":\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: BRANCH_SUMMARY_PREFIX + m.summary + BRANCH_SUMMARY_SUFFIX }],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"user\": {\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\tif (!Array.isArray(m.content)) return m;\n\t\t\t\t\treturn { ...m, content: filterUserLikeContentBlocks(m.content) } as Message;\n\t\t\t\t}\n\t\t\t\tcase \"system\":\n\t\t\t\t\treturn m;\n\t\t\t\tcase \"assistant\":\n\t\t\t\tcase \"toolResult\":\n\t\t\t\t\treturn m;\n\t\t\t\tdefault: {\n\t\t\t\t\t// Exhaustiveness guard: new AgentMessage roles must define provider conversion explicitly.\n\t\t\t\t\tconst _exhaustiveCheck: never = m;\n\t\t\t\t\tvoid _exhaustiveCheck;\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.filter((m) => m !== undefined);\n\treturn repairOrphanToolResults(uniquifyToolCallIds(converted));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"messages.js","sourceRoot":"","sources":["../../src/core/messages.ts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M,gBAAgB,GAAU,CAAC,CAAC;gBAClC,KAAK,gBAAgB,CAAC;gBACtB,OAAO,SAAS,CAAC;YAClB,CAAC;QACF,CAAC;IACF,CAAC,CAAC;SACD,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC;IACjC,OAAO,uBAAuB,CAAC,mBAAmB,CAAC,SAAS,CAAC,CAAC,CAAC;AAChE,CAAC","sourcesContent":["/**\n * Custom message types and transformers for the coding agent.\n *\n * Extends the base AgentMessage type with coding-agent specific message types,\n * and provides a transformer to convert them to LLM-compatible messages.\n */\n\nimport type { ImageContent, Message, TextContent, ToolResultMessage } from \"@bastani/pi-ai/compat\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport { uniquifyToolCallIds } from \"./context-tool-pairing.js\";\n\nexport const BRANCH_SUMMARY_PREFIX = `The following is a summary of a branch that this conversation came back from:\n\n<summary>\n`;\n\nexport const BRANCH_SUMMARY_SUFFIX = `</summary>`;\n\n/**\n * Message type for bash executions via the ! command.\n */\nexport interface BashExecutionMessage {\n\trole: \"bashExecution\";\n\tcommand: string;\n\toutput: string;\n\texitCode: number | undefined;\n\tcancelled: boolean;\n\ttruncated: boolean;\n\tfullOutputPath?: string;\n\ttimestamp: number;\n\t/** If true, this message is excluded from LLM context (!! prefix) */\n\texcludeFromContext?: boolean;\n}\n\n/**\n * Message type for extension-injected messages via sendMessage().\n * These are custom messages that extensions can inject into the conversation.\n */\n\nexport interface CustomMessage<T = unknown> {\n\trole: \"custom\";\n\tcustomType: string;\n\tcontent: string | (TextContent | ImageContent)[];\n\tdisplay: boolean;\n\tdetails?: T;\n\ttimestamp: number;\n}\n\nexport type StageAdmittedCustomMessage<T = unknown> = CustomMessage<T> & {\n\t/** Stable producer identity used for exactly-once workflow-stage admission. */\n\tstageAdmissionKey?: string;\n\t/** Whether this admission joined active stage work or started after the assistant had settled. */\n};\n\nexport interface BranchSummaryMessage {\n\trole: \"branchSummary\";\n\tsummary: string;\n\tfromId: string | null;\n\ttimestamp: number;\n}\n\n// Extend CustomAgentMessages via declaration merging\ndeclare module \"@earendil-works/pi-agent-core\" {\n\tinterface CustomAgentMessages {\n\t\tbashExecution: BashExecutionMessage;\n\t\tcustom: CustomMessage;\n\t\tbranchSummary: BranchSummaryMessage;\n\t}\n}\n\n/** Normalize lax JavaScript/legacy message input before it reaches history or providers. */\nexport function normalizeMessageContent<T extends AgentMessage>(message: T): T {\n\tswitch (message.role) {\n\t\tcase \"user\":\n\t\tcase \"assistant\":\n\t\tcase \"toolResult\":\n\t\tcase \"custom\":\n\t\t\treturn message.content == null ? ({ ...message, content: [] } as T) : message;\n\t\tdefault:\n\t\t\treturn message;\n\t}\n}\n\nexport function userLikeContentBlockIsLlmVisible(block: unknown): boolean {\n\tif (!block || typeof block !== \"object\") return false;\n\tconst candidate = block as { type?: unknown; text?: unknown };\n\tif (candidate.type === \"image\") return true;\n\tif (candidate.type === \"text\") return typeof candidate.text === \"string\" && candidate.text.trim().length > 0;\n\t// Future provider-supported blocks must fail visible; only malformed/untyped blocks fail closed.\n\treturn typeof candidate.type === \"string\" && candidate.type.trim().length > 0;\n}\n\n/** Whether user/custom content survives provider conversion as a visible input. */\nexport function userLikeContentIsLlmVisible(\n\tcontent: unknown,\n\tdeletedBlockIndexes: ReadonlySet<number> = new Set<number>(),\n): boolean {\n\tif (typeof content === \"string\") return content.trim().length > 0;\n\tif (!Array.isArray(content)) return false;\n\treturn content.some((block, index) => !deletedBlockIndexes.has(index) && userLikeContentBlockIsLlmVisible(block));\n}\n\n/** Whether an Atomic message emits an LLM-visible user-like turn boundary. */\nexport function messageStartsLlmUserTurn(\n\tmessage: AgentMessage,\n\tdeletedBlockIndexes: ReadonlySet<number> = new Set<number>(),\n): boolean {\n\tswitch (message.role) {\n\t\tcase \"user\":\n\t\t\treturn userLikeContentIsLlmVisible(message.content, deletedBlockIndexes);\n\t\tcase \"custom\":\n\t\t\treturn (\n\t\t\t\t(message as CustomMessage & { excludeFromContext?: boolean }).excludeFromContext !== true &&\n\t\t\t\tuserLikeContentIsLlmVisible(message.content, deletedBlockIndexes)\n\t\t\t);\n\t\tcase \"branchSummary\":\n\t\t\t// Empty summaries are omitted by session reconstruction. Whitespace is\n\t\t\t// visible because the branch-summary wrapper itself is non-whitespace.\n\t\t\treturn typeof message.summary === \"string\" && message.summary.length > 0;\n\t\tcase \"bashExecution\":\n\t\t\treturn message.excludeFromContext !== true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\n/** Whether an Atomic message survives conversion into provider-visible context. */\nexport function messageIsLlmVisible(\n\tmessage: AgentMessage,\n\tdeletedBlockIndexes: ReadonlySet<number> = new Set<number>(),\n): boolean {\n\tif (message.role === \"system\" || message.role === \"assistant\" || message.role === \"toolResult\") return true;\n\treturn messageStartsLlmUserTurn(message, deletedBlockIndexes);\n}\n\n/** Filter invalid user-like blocks only in transient provider-bound content. */\nfunction filterUserLikeContentBlocks(content: unknown[]): unknown[] {\n\treturn content.filter(userLikeContentBlockIsLlmVisible);\n}\n\n/** Normalize raw blocks only in the transient LLM-compatible message returned by convertToLlm. */\nfunction normalizeRawRedactedThinking(message: AgentMessage): AgentMessage {\n\tif (message.role !== \"assistant\" || !Array.isArray(message.content)) return message;\n\tlet changed = false;\n\tconst content = message.content.map((block) => {\n\t\tif (!block || typeof block !== \"object\") return block;\n\t\tconst candidate = block as { type?: unknown; data?: unknown };\n\t\tif (candidate.type !== \"redacted_thinking\" || typeof candidate.data !== \"string\") return block;\n\t\tchanged = true;\n\t\treturn {\n\t\t\ttype: \"thinking\" as const,\n\t\t\tthinking: \"\",\n\t\t\tthinkingSignature: candidate.data,\n\t\t\tredacted: true,\n\t\t};\n\t});\n\treturn changed ? ({ ...message, content } as AgentMessage) : message;\n}\n\n/**\n * Convert a BashExecutionMessage to user message text for LLM context.\n */\nexport function bashExecutionToText(msg: BashExecutionMessage): string {\n\tlet text = `Ran \\`${msg.command}\\`\\n`;\n\tif (msg.output) {\n\t\ttext += `\\`\\`\\`\\n${msg.output}\\n\\`\\`\\``;\n\t} else {\n\t\ttext += \"(no output)\";\n\t}\n\tif (msg.cancelled) {\n\t\ttext += \"\\n\\n(command cancelled)\";\n\t} else if (msg.exitCode !== null && msg.exitCode !== undefined && msg.exitCode !== 0) {\n\t\ttext += `\\n\\nCommand exited with code ${msg.exitCode}`;\n\t}\n\tif (msg.truncated && msg.fullOutputPath) {\n\t\ttext += `\\n\\n[Output truncated. Full output: ${msg.fullOutputPath}]`;\n\t}\n\treturn text;\n}\n\nexport const VERBATIM_COMPACTION_PREFIX =\n\t'The earlier conversation was compacted. Below is the verbatim transcript of the retained lines; elided spans are marked \"(filtered N lines)\".\\n\\n';\nexport const SUMMARY_COMPACTION_PREFIX = \"The following is a summary of the earlier conversation:\\n\\n\";\nconst verbatimCompactionMessages = new WeakSet<CustomMessage>();\n\nexport function isVerbatimCompactionMessage(message: CustomMessage): boolean {\n\treturn verbatimCompactionMessages.has(message);\n}\n\n/**\n * Create the visible custom-role boundary used to replay a verbatim compaction.\n *\n * `retainedTail` holds the serialized kept tail. Its text merges into the boundary text and\n * its image blocks stay intact, so preserved content is not reduced to a placeholder.\n */\nexport function createVerbatimCompactionMessage(\n\tcompactedText: string,\n\ttokensBefore: number,\n\ttimestamp: string,\n\tdetails?: unknown,\n\tretainedTail?: readonly (TextContent | ImageContent)[],\n): CustomMessage {\n\tconst prefix =\n\t\ttypeof details === \"object\" && details !== null && \"backend\" in details && details.backend === \"summary\"\n\t\t\t? SUMMARY_COMPACTION_PREFIX\n\t\t\t: VERBATIM_COMPACTION_PREFIX;\n\tconst content: (TextContent | ImageContent)[] = [{ type: \"text\", text: prefix + compactedText }];\n\tfor (const block of retainedTail ?? []) {\n\t\tconst last = content[content.length - 1];\n\t\tif (block.type === \"text\" && last.type === \"text\") last.text += block.text;\n\t\telse content.push({ ...block });\n\t}\n\t// Ensure the authoritative whole-context count survives on the message details so\n\t// the boundary renderer can show it even when the caller supplied its own details\n\t// object. An existing tokensBefore is never overridden (#2052).\n\tconst mergedDetails = (() => {\n\t\tif (details === undefined) return { tokensBefore };\n\t\tif (typeof details !== \"object\" || details === null) return details;\n\t\treturn \"tokensBefore\" in details ? details : { ...details, tokensBefore };\n\t})();\n\tconst message = createCustomMessage(\"compaction\", content, true, mergedDetails, timestamp);\n\tverbatimCompactionMessages.add(message);\n\treturn message;\n}\n\nexport function createBranchSummaryMessage(summary: string, fromId: string, timestamp: string): BranchSummaryMessage {\n\treturn {\n\t\trole: \"branchSummary\",\n\t\tsummary,\n\t\tfromId,\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n}\n\n/** Convert CustomMessageEntry to AgentMessage format */\nexport function createCustomMessage(\n\tcustomType: string,\n\tcontent: string | (TextContent | ImageContent)[],\n\tdisplay: boolean,\n\tdetails: unknown | undefined,\n\ttimestamp: string,\n\texcludeFromContext?: boolean,\n\tstageAdmissionKey?: string,\n): StageAdmittedCustomMessage {\n\tconst message: StageAdmittedCustomMessage & { excludeFromContext?: boolean } = {\n\t\trole: \"custom\",\n\t\tcustomType,\n\t\tcontent: content ?? [],\n\t\tdisplay,\n\t\tdetails,\n\t\t...(stageAdmissionKey === undefined ? {} : { stageAdmissionKey }),\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n\tif (excludeFromContext === true) message.excludeFromContext = true;\n\treturn message;\n}\n\ninterface AssistantToolCallRef {\n\tid: string;\n\tname: string;\n}\n\nfunction collectAssistantToolCalls(message: AgentMessage): AssistantToolCallRef[] {\n\tconst content = (message as { content?: unknown }).content;\n\tconst calls: AssistantToolCallRef[] = [];\n\tif (!Array.isArray(content)) return calls;\n\tfor (const block of content) {\n\t\tif (!block || typeof block !== \"object\") continue;\n\t\tconst candidate = block as { type?: unknown; id?: unknown; name?: unknown };\n\t\tif (candidate.type === \"toolCall\" && typeof candidate.id === \"string\" && typeof candidate.name === \"string\") {\n\t\t\tcalls.push({ id: candidate.id, name: candidate.name });\n\t\t}\n\t}\n\treturn calls;\n}\n\nfunction getToolResultCallId(message: AgentMessage): string | undefined {\n\tif (message.role !== \"toolResult\") return undefined;\n\tconst toolCallId = (message as { toolCallId?: unknown }).toolCallId;\n\treturn typeof toolCallId === \"string\" ? toolCallId : undefined;\n}\n\n/**\n * Keep every tool result adjacent to the assistant turn that announced it.\n *\n * A message admitted while a tool batch is still running (an Intercom delivery, a\n * workflow lifecycle card, a durable stage admission) is persisted between the tool\n * call and its result in raw history. The provider requires the results to follow the\n * call directly, so derived context defers such messages until the batch is answered.\n * The durable transcript keeps its admission order.\n */\nexport function deferMessagesInterleavedWithToolBatch<TMessage extends AgentMessage>(messages: TMessage[]): TMessage[] {\n\tlet pending: Set<string> | undefined;\n\tlet deferred: TMessage[] = [];\n\tlet changed = false;\n\tconst ordered: TMessage[] = [];\n\tconst flushDeferred = (): void => {\n\t\tif (deferred.length > 0) {\n\t\t\tordered.push(...deferred);\n\t\t\tdeferred = [];\n\t\t}\n\t\tpending = undefined;\n\t};\n\tfor (const message of messages) {\n\t\tif (message.role === \"assistant\") {\n\t\t\tflushDeferred();\n\t\t\tordered.push(message);\n\t\t\tconst calls = collectAssistantToolCalls(message);\n\t\t\tpending =\n\t\t\t\tmessage.stopReason === \"toolUse\" && calls.length > 0 ? new Set(calls.map((call) => call.id)) : undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tif (pending) {\n\t\t\tconst toolCallId = getToolResultCallId(message);\n\t\t\tif (toolCallId !== undefined && pending.has(toolCallId)) {\n\t\t\t\tordered.push(message);\n\t\t\t\tpending.delete(toolCallId);\n\t\t\t\tif (pending.size === 0) flushDeferred();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (message.role !== \"system\") {\n\t\t\t\tdeferred.push(message);\n\t\t\t\tchanged = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tordered.push(message);\n\t}\n\tflushDeferred();\n\treturn changed ? ordered : messages;\n}\n\n/**\n * Enforce the provider's tool-pairing invariant on a converted message list.\n *\n * A provider rejects orphaned/duplicate `tool_result` blocks and any later turn\n * that crosses an unanswered `tool_use`. Keep exactly the first result for each\n * announced id. If a persisted session continues after its engine died before\n * recording every result, insert provider-only error results before that later\n * turn. The repair exists only in derived context; the durable transcript stays\n * unchanged, and the text makes no claim about whether admitted work completed\n * or produced side effects.\n */\nexport interface ToolCallPairRepairOptions {\n\t/** Close a final unanswered tool call when reopening an inactive session. */\n\trepairTrailing?: boolean;\n\t/**\n\t * Calls that are running again (an interrupted question asked anew on resume): they are\n\t * pending, not interrupted, so no interrupted result is inserted for them.\n\t */\n\tinFlightToolCallIds?: ReadonlySet<string>;\n}\n\nexport function repairOrphanToolResults<TMessage extends AgentMessage>(\n\tmessages: TMessage[],\n\toptions: ToolCallPairRepairOptions = {},\n): (TMessage | ToolResultMessage)[] {\n\tlet allowedToolCallIds: Set<string> | undefined;\n\tlet answeredToolCallIds: Set<string> | undefined;\n\tlet pendingToolCalls: AssistantToolCallRef[] = [];\n\tlet pendingTimestamp = 0;\n\tlet changed = false;\n\tconst repaired: (TMessage | ToolResultMessage)[] = [];\n\tconst flushUnanswered = (): void => {\n\t\tfor (const call of pendingToolCalls) {\n\t\t\tif (answeredToolCallIds?.has(call.id) || options.inFlightToolCallIds?.has(call.id)) continue;\n\t\t\tconst interrupted: ToolResultMessage = {\n\t\t\t\trole: \"toolResult\",\n\t\t\t\ttoolCallId: call.id,\n\t\t\t\ttoolName: call.name,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Tool execution was interrupted after it started; its result is unavailable. Inspect side effects before deciding whether to retry it.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tisError: true,\n\t\t\t\ttimestamp: pendingTimestamp,\n\t\t\t};\n\t\t\trepaired.push(interrupted);\n\t\t\tchanged = true;\n\t\t}\n\t\tallowedToolCallIds = undefined;\n\t\tansweredToolCallIds = undefined;\n\t\tpendingToolCalls = [];\n\t};\n\tfor (const message of messages) {\n\t\t// Instruction/tool updates never close a pending tool batch.\n\t\tif (message.role === \"system\") {\n\t\t\trepaired.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.role === \"assistant\") {\n\t\t\tflushUnanswered();\n\t\t\tconst announcedToolCalls = collectAssistantToolCalls(message);\n\t\t\t// Only toolUse turns represent admitted executions. Error, aborted, and\n\t\t\t// length-limited turns may contain partial calls that providers discard.\n\t\t\tpendingToolCalls = message.stopReason === \"toolUse\" ? announcedToolCalls : [];\n\t\t\tallowedToolCallIds = new Set(announcedToolCalls.map((call) => call.id));\n\t\t\tansweredToolCallIds = new Set<string>();\n\t\t\tpendingTimestamp = message.timestamp;\n\t\t\trepaired.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.role === \"toolResult\") {\n\t\t\tconst toolCallId = getToolResultCallId(message);\n\t\t\tif (toolCallId && allowedToolCallIds?.has(toolCallId) && answeredToolCallIds?.has(toolCallId) === false) {\n\t\t\t\tansweredToolCallIds.add(toolCallId);\n\t\t\t\trepaired.push(message);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tchanged = true;\n\t\t\tcontinue;\n\t\t}\n\t\t// A context-excluded card admitted while a tool was still running sits between\n\t\t// the call and its result in raw history but never reaches the provider, so it\n\t\t// cannot close the pending batch.\n\t\tif (!messageStartsLlmUserTurn(message)) {\n\t\t\trepaired.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tflushUnanswered();\n\t\trepaired.push(message);\n\t}\n\tif (options.repairTrailing) flushUnanswered();\n\treturn changed ? repaired : messages;\n}\n\nconst LEGACY_COMPACTION_SUMMARY_ROLE = \"compactionSummary\";\n\n/**\n * Transform AgentMessages (including custom types) to LLM-compatible Messages.\n *\n * This is used by:\n * - Agent's transormToLlm option (for prompt calls and queued messages)\n * - Branch summarization (for summarizing abandoned branches)\n * - Custom extensions and tools\n */\nexport function convertToLlm(messages: AgentMessage[]): Message[] {\n\tconst converted = messages\n\t\t.map((rawMessage): Message | undefined => {\n\t\t\tconst m = normalizeRawRedactedThinking(normalizeMessageContent(rawMessage));\n\t\t\tconst role: string = m.role;\n\t\t\tif (role === LEGACY_COMPACTION_SUMMARY_ROLE) return undefined;\n\t\t\tswitch (m.role) {\n\t\t\t\tcase \"bashExecution\":\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: bashExecutionToText(m) }],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"custom\": {\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\tconst content =\n\t\t\t\t\t\ttypeof m.content === \"string\"\n\t\t\t\t\t\t\t? [{ type: \"text\" as const, text: m.content }]\n\t\t\t\t\t\t\t: (filterUserLikeContentBlocks(m.content) as Message[\"content\"]);\n\t\t\t\t\treturn { role: \"user\", content, timestamp: m.timestamp } as Message;\n\t\t\t\t}\n\t\t\t\tcase \"branchSummary\":\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: BRANCH_SUMMARY_PREFIX + m.summary + BRANCH_SUMMARY_SUFFIX }],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"user\": {\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\tif (!Array.isArray(m.content)) return m;\n\t\t\t\t\treturn { ...m, content: filterUserLikeContentBlocks(m.content) } as Message;\n\t\t\t\t}\n\t\t\t\tcase \"system\":\n\t\t\t\t\treturn m;\n\t\t\t\tcase \"assistant\":\n\t\t\t\tcase \"toolResult\":\n\t\t\t\t\treturn m;\n\t\t\t\tdefault: {\n\t\t\t\t\t// Exhaustiveness guard: new AgentMessage roles must define provider conversion explicitly.\n\t\t\t\t\tconst _exhaustiveCheck: never = m;\n\t\t\t\t\tvoid _exhaustiveCheck;\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.filter((m) => m !== undefined);\n\treturn repairOrphanToolResults(uniquifyToolCallIds(converted));\n}\n"]}
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* module free of AgentSession and workflow imports so the published SDK can
|
|
7
7
|
* expose it to the raw-TypeScript companion packages without a cycle.
|
|
8
8
|
*/
|
|
9
|
-
export type ModelFallbackFailureKind = "auth_on_candidate_provider" | "rate_limit" | "provider_unavailable" | "network_timeout" | "transport_error" | "model_unavailable" | "request_incompatible" | "cancelled" | "task_failure" | "unknown";
|
|
9
|
+
export type ModelFallbackFailureKind = "auth_on_candidate_provider" | "rate_limit" | "quota_exhausted" | "provider_unavailable" | "network_timeout" | "transport_error" | "model_unavailable" | "request_incompatible" | "cancelled" | "task_failure" | "unknown";
|
|
10
10
|
export type ModelFallbackFailureSource = "assistant_message" | "diagnostic" | "throw" | "structured" | "string_fallback";
|
|
11
11
|
export interface ModelFallbackFailureSignal {
|
|
12
12
|
readonly kind: ModelFallbackFailureKind;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model-fallback-failures.d.ts","sourceRoot":"","sources":["../../src/core/model-fallback-failures.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;
|
|
1
|
+
{"version":3,"file":"model-fallback-failures.d.ts","sourceRoot":"","sources":["../../src/core/model-fallback-failures.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAmFH,MAAM,MAAM,wBAAwB,GACjC,4BAA4B,GAC5B,YAAY,GACZ,iBAAiB,GACjB,sBAAsB,GACtB,iBAAiB,GACjB,iBAAiB,GACjB,mBAAmB,GACnB,sBAAsB,GACtB,WAAW,GACX,cAAc,GACd,SAAS,CAAC;AAEb,MAAM,MAAM,0BAA0B,GACnC,mBAAmB,GACnB,YAAY,GACZ,OAAO,GACP,YAAY,GACZ,iBAAiB,CAAC;AAErB,MAAM,WAAW,0BAA0B;IAC1C,QAAQ,CAAC,IAAI,EAAE,wBAAwB,CAAC;IACxC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,MAAM,EAAE,0BAA0B,CAAC;IAC5C,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IAChC,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;CACvB;AAijBD,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAKnD;AAED,qEAAqE;AACrE,eAAO,MAAM,mBAAmB,qBAAe,CAAC;AAEhD,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,OAAO,GAAG,0BAA0B,CAuBtF;AAED,2EAA2E;AAC3E,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAK9D;AAED,8EAA8E;AAC9E,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAG/D;AASD,gFAAgF;AAChF,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAcnE"}
|
|
@@ -10,6 +10,7 @@ import { isExtensionStartupFailure } from "./extension-startup-failure.js";
|
|
|
10
10
|
const RETRYABLE_MODEL_FAILURE_PATTERNS = [
|
|
11
11
|
/rate\s*limit/i,
|
|
12
12
|
/too\s*many\s*requests/i,
|
|
13
|
+
/\bthrottl(?:ing|ed)\b/i,
|
|
13
14
|
/\b429\b/,
|
|
14
15
|
/quota/i,
|
|
15
16
|
/usage[\s_-]*limit/i,
|
|
@@ -39,6 +40,7 @@ const RETRYABLE_MODEL_FAILURE_PATTERNS = [
|
|
|
39
40
|
/timed\s*out/i,
|
|
40
41
|
/\b50[0-4]\b/,
|
|
41
42
|
/\b52[0-4]\b/,
|
|
43
|
+
/\b529\b/,
|
|
42
44
|
/provider.?returned.?error/i,
|
|
43
45
|
/server.?error/i,
|
|
44
46
|
/internal.?error/i,
|
|
@@ -83,6 +85,7 @@ const TRANSPORT_CANCELLATION_FAILURE_PATTERNS = [
|
|
|
83
85
|
const FALLBACKABLE_FAILURE_KINDS = new Set([
|
|
84
86
|
"auth_on_candidate_provider",
|
|
85
87
|
"rate_limit",
|
|
88
|
+
"quota_exhausted",
|
|
86
89
|
"provider_unavailable",
|
|
87
90
|
"network_timeout",
|
|
88
91
|
"transport_error",
|
|
@@ -120,7 +123,12 @@ function statusFrom(value) {
|
|
|
120
123
|
}
|
|
121
124
|
function codeFrom(value) {
|
|
122
125
|
const rawCode = field(value, "code");
|
|
123
|
-
|
|
126
|
+
if (typeof rawCode === "string" || typeof rawCode === "number")
|
|
127
|
+
return rawCode;
|
|
128
|
+
// Provider failure diagnostics (`bedrock_response_failure`) keep the modeled error code in `details.errorCode`,
|
|
129
|
+
// because the provider's display message replaces the exception name with a readable prefix.
|
|
130
|
+
const detailsCode = field(field(value, "details"), "errorCode");
|
|
131
|
+
return typeof detailsCode === "string" ? detailsCode : undefined;
|
|
124
132
|
}
|
|
125
133
|
function stopReasonFrom(value) {
|
|
126
134
|
return stringField(value, "stopReason");
|
|
@@ -175,6 +183,8 @@ function messageLooksLikeModelUnavailable(message) {
|
|
|
175
183
|
lower.includes("not found") ||
|
|
176
184
|
lower.includes("unknown")));
|
|
177
185
|
}
|
|
186
|
+
/** GitHub Copilot rejects a model this client integration cannot use with a generic 400 `invalid_request_error`. */
|
|
187
|
+
const MODEL_UNAVAILABLE_FOR_INTEGRATOR_PATTERN = /model_not_available_for_integrator|not available for integrator/i;
|
|
178
188
|
function kindFromStatus(status) {
|
|
179
189
|
switch (status) {
|
|
180
190
|
case 400:
|
|
@@ -188,6 +198,8 @@ function kindFromStatus(status) {
|
|
|
188
198
|
return "network_timeout";
|
|
189
199
|
case 404:
|
|
190
200
|
return "model_unavailable";
|
|
201
|
+
case 402:
|
|
202
|
+
return "quota_exhausted";
|
|
191
203
|
case 429:
|
|
192
204
|
return "rate_limit";
|
|
193
205
|
default:
|
|
@@ -276,12 +288,16 @@ function kindFromCode(code) {
|
|
|
276
288
|
case "rate_limit":
|
|
277
289
|
case "rate_limit_exceeded":
|
|
278
290
|
case "too_many_requests":
|
|
291
|
+
case "throttlingexception":
|
|
292
|
+
return "rate_limit";
|
|
279
293
|
case "quota_exceeded":
|
|
280
294
|
case "insufficient_quota":
|
|
281
295
|
case "usage_limit":
|
|
282
296
|
case "usage_limit_reached":
|
|
283
297
|
case "usage_limit_exceeded":
|
|
284
|
-
|
|
298
|
+
case "payment_required":
|
|
299
|
+
case "servicequotaexceededexception":
|
|
300
|
+
return "quota_exhausted";
|
|
285
301
|
case "aborterror":
|
|
286
302
|
case "aborted":
|
|
287
303
|
case "cancelled":
|
|
@@ -291,6 +307,7 @@ function kindFromCode(code) {
|
|
|
291
307
|
case "model_unavailable":
|
|
292
308
|
case "model_disabled":
|
|
293
309
|
case "unknown_model":
|
|
310
|
+
case "model_not_available_for_integrator":
|
|
294
311
|
return "model_unavailable";
|
|
295
312
|
case "provider_error":
|
|
296
313
|
case "api_error":
|
|
@@ -344,6 +361,12 @@ const TRANSPORT_OUTAGE_FAILURE_PATTERNS = [
|
|
|
344
361
|
// `withStreamDeadline`, so a stalled stream fails over instead of hanging.
|
|
345
362
|
/\bstream\s+deadline\s+exceeded\b/i,
|
|
346
363
|
];
|
|
364
|
+
// HTTP 402 and explicit quota exhaustion: the account cannot be served again until its quota resets.
|
|
365
|
+
// Codes that also appear as free-text wording for short limits ("quota exceeded", "usage limit reached")
|
|
366
|
+
// count only as a JSON `code`/`type` value, as in a raw error body some providers put in the message.
|
|
367
|
+
// A service-quota exception and a per-day quota violation in a JSON error body (`"quotaId": "...PerDay..."`)
|
|
368
|
+
// also last until the quota resets.
|
|
369
|
+
const QUOTA_EXHAUSTED_FAILURE_PATTERN = /(?<![a-z0-9.])402(?![a-z0-9.])|payment[_\s-]*required|insufficient[_\s-]*quota|\bServiceQuotaExceededException\b|"quotaId"\s*:\s*"[^"]*PerDay|"(?:code|type|error_code)"\s*:\s*"(?:quota_exceeded|usage_limit|usage_limit_reached|usage_limit_exceeded)"/i;
|
|
347
370
|
function transportOutageKindFromMessage(message) {
|
|
348
371
|
return TRANSPORT_OUTAGE_FAILURE_PATTERNS.some((pattern) => pattern.test(message.trim()))
|
|
349
372
|
? "transport_error"
|
|
@@ -367,16 +390,20 @@ function fallbackKindFromMessage(message, name) {
|
|
|
367
390
|
const transportOutageKind = transportOutageKindFromMessage(message);
|
|
368
391
|
if (transportOutageKind !== undefined)
|
|
369
392
|
return transportOutageKind;
|
|
393
|
+
if (MODEL_UNAVAILABLE_FOR_INTEGRATOR_PATTERN.test(message))
|
|
394
|
+
return "model_unavailable";
|
|
370
395
|
if (REQUEST_INCOMPATIBLE_FAILURE_PATTERNS.some((pattern) => pattern.test(message)))
|
|
371
396
|
return "request_incompatible";
|
|
372
397
|
const nameKind = kindFromCode(name);
|
|
373
398
|
if (nameKind !== undefined)
|
|
374
399
|
return nameKind;
|
|
400
|
+
if (QUOTA_EXHAUSTED_FAILURE_PATTERN.test(message))
|
|
401
|
+
return "quota_exhausted";
|
|
375
402
|
const hasRetryablePattern = RETRYABLE_MODEL_FAILURE_PATTERNS.some((pattern) => pattern.test(message)) ||
|
|
376
403
|
messageLooksLikeModelUnavailable(message);
|
|
377
404
|
if (!hasRetryablePattern)
|
|
378
405
|
return undefined;
|
|
379
|
-
if (/rate\s*limit|too\s*many\s*requests|\b429\b|quota|usage[\s_-]*limit|billing|credit/i.test(message))
|
|
406
|
+
if (/rate\s*limit|too\s*many\s*requests|\bthrottl(?:ing|ed)\b|\b429\b|quota|usage[\s_-]*limit|billing|credit/i.test(message))
|
|
380
407
|
return "rate_limit";
|
|
381
408
|
if (/auth|unauthori[sz]ed|\b40[13]\b|api[_\s-]*key|token[_\s-]*(?:expired|revoked|invalidated|rejected)|forbidden|invalid[_\s-]*key/i.test(message))
|
|
382
409
|
return "auth_on_candidate_provider";
|
|
@@ -447,6 +474,8 @@ function nestedSignalPriority(signal) {
|
|
|
447
474
|
return 85;
|
|
448
475
|
case "model_unavailable":
|
|
449
476
|
return 80;
|
|
477
|
+
case "quota_exhausted":
|
|
478
|
+
return 75;
|
|
450
479
|
case "rate_limit":
|
|
451
480
|
return 70;
|
|
452
481
|
case "provider_unavailable":
|
|
@@ -506,6 +535,11 @@ function structuredSignal(value, seen, source) {
|
|
|
506
535
|
bestNestedFallbackSignal = causeSignal;
|
|
507
536
|
}
|
|
508
537
|
}
|
|
538
|
+
// This code names the exact cause, so the generic 400 status and its request-error text must not outrank it.
|
|
539
|
+
if (directRefusalSignal === undefined &&
|
|
540
|
+
directCancellationSignal === undefined &&
|
|
541
|
+
normalizeCode(codeFrom(value)) === "model_not_available_for_integrator")
|
|
542
|
+
return makeSignal("model_unavailable", value, source);
|
|
509
543
|
const directSignals = [
|
|
510
544
|
directRefusalSignal,
|
|
511
545
|
directCancellationSignal,
|