@fabric-harness/sdk 6.4.0 → 6.6.0
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/connector-spec/voice-telephony.md +120 -104
- package/dist/agent-route.d.ts +20 -2
- package/dist/agent-route.d.ts.map +1 -1
- package/dist/agent-route.js +31 -1
- package/dist/agent-route.js.map +1 -1
- package/dist/agent-router.d.ts +42 -0
- package/dist/agent-router.d.ts.map +1 -1
- package/dist/agent-router.js +49 -1
- package/dist/agent-router.js.map +1 -1
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +7 -2
- package/dist/agent.js.map +1 -1
- package/dist/attachment-store.d.ts +69 -0
- package/dist/attachment-store.d.ts.map +1 -1
- package/dist/attachment-store.js +183 -14
- package/dist/attachment-store.js.map +1 -1
- package/dist/attachments.d.ts +136 -0
- package/dist/attachments.d.ts.map +1 -0
- package/dist/attachments.js +332 -0
- package/dist/attachments.js.map +1 -0
- package/dist/channel.d.ts.map +1 -1
- package/dist/channel.js +26 -3
- package/dist/channel.js.map +1 -1
- package/dist/conversation-history.d.ts +186 -0
- package/dist/conversation-history.d.ts.map +1 -0
- package/dist/conversation-history.js +481 -0
- package/dist/conversation-history.js.map +1 -0
- package/dist/conversation-ui.d.ts +43 -2
- package/dist/conversation-ui.d.ts.map +1 -1
- package/dist/conversation-ui.js +44 -14
- package/dist/conversation-ui.js.map +1 -1
- package/dist/cost-budget.d.ts +50 -0
- package/dist/cost-budget.d.ts.map +1 -1
- package/dist/cost-budget.js +74 -4
- package/dist/cost-budget.js.map +1 -1
- package/dist/cost-enforcement.d.ts +32 -0
- package/dist/cost-enforcement.d.ts.map +1 -0
- package/dist/cost-enforcement.js +116 -0
- package/dist/cost-enforcement.js.map +1 -0
- package/dist/delivered-message.d.ts +20 -6
- package/dist/delivered-message.d.ts.map +1 -1
- package/dist/delivered-message.js +37 -8
- package/dist/delivered-message.js.map +1 -1
- package/dist/events.d.ts +13 -1
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js.map +1 -1
- package/dist/experimental.d.ts +2 -2
- package/dist/experimental.d.ts.map +1 -1
- package/dist/experimental.js +1 -1
- package/dist/experimental.js.map +1 -1
- package/dist/governed-voice.d.ts +6 -0
- package/dist/governed-voice.d.ts.map +1 -1
- package/dist/governed-voice.js +142 -35
- package/dist/governed-voice.js.map +1 -1
- package/dist/history.d.ts +3 -2
- package/dist/history.d.ts.map +1 -1
- package/dist/history.js +57 -23
- package/dist/history.js.map +1 -1
- package/dist/index.d.ts +21 -14
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +11 -7
- package/dist/index.js.map +1 -1
- package/dist/loop.d.ts +25 -2
- package/dist/loop.d.ts.map +1 -1
- package/dist/loop.js +409 -60
- package/dist/loop.js.map +1 -1
- package/dist/model-pricing.d.ts +77 -4
- package/dist/model-pricing.d.ts.map +1 -1
- package/dist/model-pricing.js +259 -18
- package/dist/model-pricing.js.map +1 -1
- package/dist/model.d.ts +115 -3
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +487 -75
- package/dist/model.js.map +1 -1
- package/dist/pi-document-attachments.d.ts +43 -0
- package/dist/pi-document-attachments.d.ts.map +1 -0
- package/dist/pi-document-attachments.js +155 -0
- package/dist/pi-document-attachments.js.map +1 -0
- package/dist/pi-loop-runtime.d.ts +103 -1
- package/dist/pi-loop-runtime.d.ts.map +1 -1
- package/dist/pi-loop-runtime.js +907 -114
- package/dist/pi-loop-runtime.js.map +1 -1
- package/dist/prompt-attachments.d.ts +98 -0
- package/dist/prompt-attachments.d.ts.map +1 -0
- package/dist/prompt-attachments.js +279 -0
- package/dist/prompt-attachments.js.map +1 -0
- package/dist/session.d.ts +55 -0
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +443 -41
- package/dist/session.js.map +1 -1
- package/dist/stream-chunks.d.ts +15 -1
- package/dist/stream-chunks.d.ts.map +1 -1
- package/dist/stream-chunks.js +39 -18
- package/dist/stream-chunks.js.map +1 -1
- package/dist/strict.d.ts +23 -16
- package/dist/strict.d.ts.map +1 -1
- package/dist/strict.js +12 -8
- package/dist/strict.js.map +1 -1
- package/dist/submission-context.d.ts +7 -0
- package/dist/submission-context.d.ts.map +1 -1
- package/dist/submission-context.js.map +1 -1
- package/dist/submission-runner.d.ts +5 -0
- package/dist/submission-runner.d.ts.map +1 -1
- package/dist/submission-runner.js +11 -2
- package/dist/submission-runner.js.map +1 -1
- package/dist/tools.d.ts +9 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +1 -0
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +26 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/usage-completeness.d.ts +39 -0
- package/dist/usage-completeness.d.ts.map +1 -0
- package/dist/usage-completeness.js +135 -0
- package/dist/usage-completeness.js.map +1 -0
- package/dist/voice-openai-realtime.d.ts +24 -2
- package/dist/voice-openai-realtime.d.ts.map +1 -1
- package/dist/voice-openai-realtime.js +266 -49
- package/dist/voice-openai-realtime.js.map +1 -1
- package/dist/voice-pipeline.d.ts +81 -3
- package/dist/voice-pipeline.d.ts.map +1 -1
- package/dist/voice-pipeline.js +429 -60
- package/dist/voice-pipeline.js.map +1 -1
- package/dist/voice-stt-cartesia.d.ts +8 -0
- package/dist/voice-stt-cartesia.d.ts.map +1 -1
- package/dist/voice-stt-cartesia.js +77 -17
- package/dist/voice-stt-cartesia.js.map +1 -1
- package/dist/voice-stt-deepgram.d.ts +10 -2
- package/dist/voice-stt-deepgram.d.ts.map +1 -1
- package/dist/voice-stt-deepgram.js +78 -18
- package/dist/voice-stt-deepgram.js.map +1 -1
- package/dist/voice-stt.d.ts +13 -3
- package/dist/voice-stt.d.ts.map +1 -1
- package/dist/voice-tts-cartesia.d.ts +8 -0
- package/dist/voice-tts-cartesia.d.ts.map +1 -1
- package/dist/voice-tts-cartesia.js +48 -105
- package/dist/voice-tts-cartesia.js.map +1 -1
- package/dist/voice-tts-elevenlabs.d.ts +10 -1
- package/dist/voice-tts-elevenlabs.d.ts.map +1 -1
- package/dist/voice-tts-elevenlabs.js +50 -113
- package/dist/voice-tts-elevenlabs.js.map +1 -1
- package/dist/voice-ws-client.js +16 -3
- package/dist/voice-ws-client.js.map +1 -1
- package/dist/voice-ws-shared.d.ts +205 -6
- package/dist/voice-ws-shared.d.ts.map +1 -1
- package/dist/voice-ws-shared.js +510 -15
- package/dist/voice-ws-shared.js.map +1 -1
- package/dist/voice.d.ts +98 -4
- package/dist/voice.d.ts.map +1 -1
- package/dist/voice.js +71 -1
- package/dist/voice.js.map +1 -1
- package/package.json +3 -3
package/dist/loop.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type CostBudgetTracker, type CostLimitContext } from "./cost-budget.js";
|
|
2
|
+
import { FabricError } from "./error.js";
|
|
2
3
|
import type { ModelMessage, ModelProvider, ModelUsage, ThinkingLevel } from "./model.js";
|
|
3
4
|
import type { DeliveredMessage } from "./delivered-message.js";
|
|
4
5
|
import type { CapabilityPolicy } from "./policy.js";
|
|
@@ -51,8 +52,9 @@ export interface PromptRunInput {
|
|
|
51
52
|
journal?: JournalCallbacks;
|
|
52
53
|
/**
|
|
53
54
|
* Optional durable store for stream chunk segments. When provided, the
|
|
54
|
-
* streaming path
|
|
55
|
-
*
|
|
55
|
+
* streaming path persists each model attempt's chunks under its own key: the
|
|
56
|
+
* first chunk after a quiet period is flushed immediately and later chunks
|
|
57
|
+
* coalesce for up to 3s. Sessions do not wire this yet; custom runtimes may.
|
|
56
58
|
*/
|
|
57
59
|
streamChunkStore?: StreamChunkStore;
|
|
58
60
|
/** Optional result validator. When set, the loop injects `finish`/`give_up` tools. */
|
|
@@ -90,11 +92,32 @@ export interface PromptRunResult {
|
|
|
90
92
|
usage?: ModelUsage;
|
|
91
93
|
/** Populated when the `finish` tool was used to produce a validated result. */
|
|
92
94
|
validatedResult?: unknown;
|
|
95
|
+
/**
|
|
96
|
+
* True when the run ended because every tool call in the final batch asked
|
|
97
|
+
* to terminate the loop. Sessions use it to compact after termination so the
|
|
98
|
+
* next turn starts from a manageable context.
|
|
99
|
+
*/
|
|
100
|
+
terminatedByTool?: boolean;
|
|
93
101
|
}
|
|
102
|
+
/**
|
|
103
|
+
* Error text recorded for each tool call in a response the output token limit
|
|
104
|
+
* truncated. The calls are never executed; the model is asked to re-issue them.
|
|
105
|
+
*/
|
|
106
|
+
export declare function truncatedToolCallError(toolName: string): string;
|
|
94
107
|
export declare class NativeLoopRuntime implements AgentLoopRuntime {
|
|
95
108
|
readonly name = "native";
|
|
96
109
|
runPrompt(input: PromptRunInput): Promise<PromptRunResult>;
|
|
110
|
+
private failTruncatedToolCalls;
|
|
97
111
|
private executeModelToolCalls;
|
|
98
112
|
}
|
|
113
|
+
/**
|
|
114
|
+
* @internal Shared with the Pi loop so provider failures classify identically.
|
|
115
|
+
*
|
|
116
|
+
* `payloads` are the attachment payloads submitted in the failing request
|
|
117
|
+
* (see `collectAttachmentPayloads`); they are redacted from the mapped
|
|
118
|
+
* error's text by exact match regardless of length, on top of the generic
|
|
119
|
+
* data-URL and long-base64 rules.
|
|
120
|
+
*/
|
|
121
|
+
export declare function mapModelError(error: unknown, payloads?: readonly string[]): FabricError;
|
|
99
122
|
export declare const defaultLoopRuntime: NativeLoopRuntime;
|
|
100
123
|
//# sourceMappingURL=loop.d.ts.map
|
package/dist/loop.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loop.d.ts","sourceRoot":"","sources":["../src/loop.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,iBAAiB,EAEtB,KAAK,gBAAgB,EACtB,MAAM,kBAAkB,CAAC;
|
|
1
|
+
{"version":3,"file":"loop.d.ts","sourceRoot":"","sources":["../src/loop.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,iBAAiB,EAEtB,KAAK,gBAAgB,EACtB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,WAAW,EAAE,MAAM,Y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
3
|
-
import {
|
|
3
|
+
import { collectAttachmentPayloads, redactAttachmentPayloads, redactErrorAttachmentPayloads, } from "./attachments.js";
|
|
4
|
+
import { calculateRetryDelay, defaultModelProvider, generateWithRuntime, isRetryableModelError, MAX_TRANSIENT_MODEL_RETRIES, ProviderHttpError, sleepWithAbort, toolsToModelSchemas, TRANSIENT_MODEL_RETRY_BASE_DELAY_MS, } from "./model.js";
|
|
4
5
|
import { buildResultFollowUpPrompt, buildResultFooter, ResultUnavailableError } from "./result.js";
|
|
5
6
|
import { createResultTools } from "./tools.js";
|
|
6
7
|
import { isContextOverflowError } from "./context-budget.js";
|
|
7
8
|
import { StreamChunkWriter } from "./stream-chunks.js";
|
|
9
|
+
import { enforceUnknownCost } from "./cost-enforcement.js";
|
|
10
|
+
/**
|
|
11
|
+
* Error text recorded for each tool call in a response the output token limit
|
|
12
|
+
* truncated. The calls are never executed; the model is asked to re-issue them.
|
|
13
|
+
*/
|
|
14
|
+
export function truncatedToolCallError(toolName) {
|
|
15
|
+
return `Tool call "${toolName}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments, splitting large inputs across smaller calls.`;
|
|
16
|
+
}
|
|
8
17
|
export class NativeLoopRuntime {
|
|
9
18
|
name = "native";
|
|
10
19
|
async runPrompt(input) {
|
|
@@ -37,6 +46,10 @@ export class NativeLoopRuntime {
|
|
|
37
46
|
}
|
|
38
47
|
}
|
|
39
48
|
for (let iteration = 0; iteration < maxIterations; iteration += 1) {
|
|
49
|
+
// A cancelled prompt never starts another provider turn (for example
|
|
50
|
+
// after a tool batch that settled its remaining calls as interrupted).
|
|
51
|
+
if (input.signal?.aborted)
|
|
52
|
+
throw abortErrorFor(input.signal);
|
|
40
53
|
const steering = await input.takeSteeringMessages?.();
|
|
41
54
|
if (steering?.length)
|
|
42
55
|
input.messages.push(...steering);
|
|
@@ -116,52 +129,17 @@ export class NativeLoopRuntime {
|
|
|
116
129
|
const streamFn = provider.stream;
|
|
117
130
|
if (typeof streamFn === "function") {
|
|
118
131
|
streamedFinalText = true;
|
|
119
|
-
// Streaming path: emit text_delta as tokens arrive; the loop's
|
|
120
|
-
// resilience wrapper (timeout/retry) is skipped because partial
|
|
121
|
-
// stream state can't be safely re-applied on mid-stream failure.
|
|
122
|
-
const streamRequest = {
|
|
123
|
-
...request,
|
|
124
|
-
...(input.signal !== undefined ? { signal: input.signal } : {}),
|
|
125
|
-
};
|
|
126
|
-
await input.recordEntry("model_attempt", {
|
|
127
|
-
provider: provider.name,
|
|
128
|
-
status: "start",
|
|
129
|
-
...(input.model !== undefined ? { model: input.model } : {}),
|
|
130
|
-
});
|
|
131
|
-
await turnEmit("model_attempt", {
|
|
132
|
-
provider: provider.name,
|
|
133
|
-
status: "start",
|
|
134
|
-
...(input.model !== undefined ? { model: input.model } : {}),
|
|
135
|
-
});
|
|
136
132
|
await input.journal?.providerStarted?.({ operationId, turnId });
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
for await (const chunk of streamFn.call(provider, streamRequest)) {
|
|
144
|
-
chunkWriter?.write(chunk);
|
|
145
|
-
if (chunk.textDelta)
|
|
146
|
-
await turnEmit("text_delta", { delta: chunk.textDelta });
|
|
147
|
-
if (chunk.thinkingDelta)
|
|
148
|
-
await turnEmit("text_delta", { delta: chunk.thinkingDelta, kind: "thinking" });
|
|
149
|
-
if (chunk.toolCallDelta) {
|
|
150
|
-
await turnEmit("toolcall_delta", chunk.toolCallDelta);
|
|
151
|
-
}
|
|
152
|
-
if (chunk.done)
|
|
153
|
-
aggregated = chunk.done;
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
finally {
|
|
157
|
-
await chunkWriter?.close();
|
|
158
|
-
}
|
|
159
|
-
if (!aggregated)
|
|
160
|
-
throw new Error(`${provider.name}: stream ended without a final response.`);
|
|
161
|
-
response = aggregated;
|
|
133
|
+
response = await streamModelWithRetry(provider, streamFn, request, {
|
|
134
|
+
input,
|
|
135
|
+
operationId,
|
|
136
|
+
turnId,
|
|
137
|
+
emit: turnEmit,
|
|
138
|
+
});
|
|
162
139
|
}
|
|
163
140
|
else {
|
|
164
141
|
await input.journal?.providerStarted?.({ operationId, turnId });
|
|
142
|
+
const attemptIds = new Map();
|
|
165
143
|
response = await generateWithRuntime(provider, request, {
|
|
166
144
|
...(input.modelTimeoutMs !== undefined ? { timeoutMs: input.modelTimeoutMs } : {}),
|
|
167
145
|
...(input.modelRetries !== undefined ? { retries: input.modelRetries } : {}),
|
|
@@ -170,14 +148,23 @@ export class NativeLoopRuntime {
|
|
|
170
148
|
: {}),
|
|
171
149
|
...(input.signal !== undefined ? { signal: input.signal } : {}),
|
|
172
150
|
onAttempt: async (event) => {
|
|
173
|
-
|
|
174
|
-
|
|
151
|
+
let attemptId = attemptIds.get(event.attempt);
|
|
152
|
+
if (!attemptId) {
|
|
153
|
+
attemptId = generateId();
|
|
154
|
+
attemptIds.set(event.attempt, attemptId);
|
|
155
|
+
}
|
|
156
|
+
const payload = { ...event, attemptId };
|
|
157
|
+
await input.recordEntry("model_attempt", payload);
|
|
158
|
+
await turnEmit("model_attempt", payload);
|
|
175
159
|
},
|
|
176
160
|
});
|
|
177
161
|
}
|
|
178
162
|
}
|
|
179
163
|
catch (error) {
|
|
180
|
-
|
|
164
|
+
if (input.signal?.aborted)
|
|
165
|
+
throw abortErrorFor(input.signal, error);
|
|
166
|
+
// Redact the exact attachment payloads this request submitted.
|
|
167
|
+
throw mapModelError(error, collectAttachmentPayloads(request.messages));
|
|
181
168
|
}
|
|
182
169
|
if (response.usage) {
|
|
183
170
|
latestUsage = response.usage;
|
|
@@ -246,9 +233,18 @@ export class NativeLoopRuntime {
|
|
|
246
233
|
}
|
|
247
234
|
}
|
|
248
235
|
}
|
|
236
|
+
await enforceUnknownCost({ ...input, emit: turnEmit }, response.usage, input.model);
|
|
249
237
|
if (response.thinking && !streamedFinalText) {
|
|
250
238
|
await turnEmit("text_delta", { delta: response.thinking, kind: "thinking" });
|
|
251
239
|
}
|
|
240
|
+
if (response.toolCalls?.length && response.stopReason === "length") {
|
|
241
|
+
// The output token limit cut this response off, so every tool call in
|
|
242
|
+
// it may carry truncated arguments. None are safe to execute: record
|
|
243
|
+
// each as an error result and let the model re-issue smaller calls
|
|
244
|
+
// within the remaining turn budget.
|
|
245
|
+
await this.failTruncatedToolCalls(response.toolCalls, input, turnEmit);
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
252
248
|
if (response.toolCalls?.length) {
|
|
253
249
|
await input.journal?.toolRequestRecorded?.({
|
|
254
250
|
operationId,
|
|
@@ -294,6 +290,7 @@ export class NativeLoopRuntime {
|
|
|
294
290
|
return {
|
|
295
291
|
text: typeof outcome.value === "string" ? outcome.value : JSON.stringify(outcome.value),
|
|
296
292
|
raw: outcome.value,
|
|
293
|
+
terminatedByTool: true,
|
|
297
294
|
...(latestUsage ? { usage: latestUsage } : {}),
|
|
298
295
|
};
|
|
299
296
|
}
|
|
@@ -328,6 +325,43 @@ export class NativeLoopRuntime {
|
|
|
328
325
|
retryable: true,
|
|
329
326
|
});
|
|
330
327
|
}
|
|
328
|
+
async failTruncatedToolCalls(calls, input, emit) {
|
|
329
|
+
input.messages.push({ role: "assistant", content: "", toolCalls: calls });
|
|
330
|
+
// Record the requested calls before their error outcomes so a history
|
|
331
|
+
// replay projects the same assistant tool-use message the in-memory
|
|
332
|
+
// context holds. Without these entries the error results replay as
|
|
333
|
+
// orphaned tool messages, which providers reject on every later prompt.
|
|
334
|
+
// `executed: false` marks calls that never ran (compaction's file
|
|
335
|
+
// references skip them); they carry no `durable` flag, so dangling-call
|
|
336
|
+
// recovery never re-executes them.
|
|
337
|
+
for (const call of calls) {
|
|
338
|
+
await input.recordEntry("tool_call", {
|
|
339
|
+
tool: call.name,
|
|
340
|
+
input: (call.input ?? null),
|
|
341
|
+
toolCallId: call.id,
|
|
342
|
+
stopReason: "length",
|
|
343
|
+
executed: false,
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
for (const call of calls) {
|
|
347
|
+
const error = truncatedToolCallError(call.name);
|
|
348
|
+
await input.recordEntry("error", {
|
|
349
|
+
tool: call.name,
|
|
350
|
+
toolCallId: call.id,
|
|
351
|
+
error,
|
|
352
|
+
stopReason: "length",
|
|
353
|
+
approvalRequired: false,
|
|
354
|
+
});
|
|
355
|
+
await emit("error", { tool: call.name, toolCallId: call.id, error, stopReason: "length" });
|
|
356
|
+
input.messages.push({
|
|
357
|
+
role: "tool",
|
|
358
|
+
name: call.name,
|
|
359
|
+
toolCallId: call.id,
|
|
360
|
+
content: error,
|
|
361
|
+
isError: true,
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
}
|
|
331
365
|
async executeModelToolCalls(calls, input, resultToolBundle, attribution) {
|
|
332
366
|
// Push the assistant message with tool calls so the model sees the full round-trip
|
|
333
367
|
input.messages.push({ role: "assistant", content: "", toolCalls: calls });
|
|
@@ -341,6 +375,7 @@ export class NativeLoopRuntime {
|
|
|
341
375
|
role: "tool",
|
|
342
376
|
name: result.tool,
|
|
343
377
|
content: result.error ?? JSON.stringify(result.output ?? null),
|
|
378
|
+
...(result.error ? { isError: true } : {}),
|
|
344
379
|
};
|
|
345
380
|
if (callId !== undefined)
|
|
346
381
|
message.toolCallId = callId;
|
|
@@ -359,15 +394,81 @@ export class NativeLoopRuntime {
|
|
|
359
394
|
return undefined;
|
|
360
395
|
}
|
|
361
396
|
}
|
|
362
|
-
|
|
363
|
-
|
|
397
|
+
/**
|
|
398
|
+
* A copy of a provider error whose text is safe to keep as a
|
|
399
|
+
* `cause`: the message (and a {@link ProviderHttpError} body) with attachment
|
|
400
|
+
* payloads redacted. The original is returned when nothing was redacted.
|
|
401
|
+
* Error `cause` chains are formatted by CLIs and loggers, so a raw provider
|
|
402
|
+
* error that echoed attachment bytes must not ride along on the mapped error.
|
|
403
|
+
*/
|
|
404
|
+
function redactProviderErrorCause(error, payloads) {
|
|
405
|
+
if (!(error instanceof Error) || error instanceof FabricError)
|
|
406
|
+
return error;
|
|
407
|
+
const message = redactAttachmentPayloads(error.message, payloads);
|
|
408
|
+
if (error instanceof ProviderHttpError) {
|
|
409
|
+
const body = redactAttachmentPayloads(error.body, payloads);
|
|
410
|
+
if (message === error.message && body === error.body)
|
|
411
|
+
return error;
|
|
412
|
+
return new ProviderHttpError(message, error.provider, error.status, error.statusText, body, error.retryAfterMs);
|
|
413
|
+
}
|
|
414
|
+
if (message === error.message)
|
|
364
415
|
return error;
|
|
365
|
-
const
|
|
416
|
+
const copy = new Error(message);
|
|
417
|
+
copy.name = error.name;
|
|
418
|
+
for (const key of ["status", "statusCode", "code", "type"]) {
|
|
419
|
+
const value = error[key];
|
|
420
|
+
if (typeof value === "string" || typeof value === "number") {
|
|
421
|
+
copy[key] = value;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
return copy;
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* @internal Shared with the Pi loop so provider failures classify identically.
|
|
428
|
+
*
|
|
429
|
+
* `payloads` are the attachment payloads submitted in the failing request
|
|
430
|
+
* (see `collectAttachmentPayloads`); they are redacted from the mapped
|
|
431
|
+
* error's text by exact match regardless of length, on top of the generic
|
|
432
|
+
* data-URL and long-base64 rules.
|
|
433
|
+
*/
|
|
434
|
+
export function mapModelError(error, payloads) {
|
|
435
|
+
// Scrub the whole error graph first (nested `cause` chains,
|
|
436
|
+
// `AggregateError.errors`, own string fields): the mapped error keeps the
|
|
437
|
+
// provider error as its `cause`, and `util.inspect` and loggers print the
|
|
438
|
+
// full chain, so a clean outer message is not enough. Redaction is in place;
|
|
439
|
+
// a frozen error comes back as a plain redacted copy with no cause chain.
|
|
440
|
+
if (error instanceof Error) {
|
|
441
|
+
const scrubbed = redactErrorAttachmentPayloads(error, payloads);
|
|
442
|
+
if (scrubbed !== error)
|
|
443
|
+
return mapModelError(scrubbed, payloads);
|
|
444
|
+
}
|
|
445
|
+
if (error instanceof FabricError) {
|
|
446
|
+
// A provider that throws FabricError directly can still echo payloads.
|
|
447
|
+
const redacted = redactAttachmentPayloads(error.message, payloads);
|
|
448
|
+
const publicMessage = redactAttachmentPayloads(error.publicMessage, payloads);
|
|
449
|
+
if (redacted === error.message && publicMessage === error.publicMessage)
|
|
450
|
+
return error;
|
|
451
|
+
const cause = redactProviderErrorCause(error.cause, payloads);
|
|
452
|
+
return new FabricError({
|
|
453
|
+
code: error.code,
|
|
454
|
+
message: redacted,
|
|
455
|
+
publicMessage,
|
|
456
|
+
...(error.details !== undefined ? { details: error.details } : {}),
|
|
457
|
+
...(error.publicDetails !== undefined ? { publicDetails: error.publicDetails } : {}),
|
|
458
|
+
...(cause !== undefined ? { cause } : {}),
|
|
459
|
+
retryable: error.retryable,
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
// Provider error text can echo submitted attachment bytes (data URLs or raw
|
|
463
|
+
// base64); the mapped error is what callers, submission records and task
|
|
464
|
+
// entries persist, so it carries the redacted text only.
|
|
465
|
+
const message = redactAttachmentPayloads(error instanceof Error ? error.message : String(error), payloads);
|
|
466
|
+
const cause = redactProviderErrorCause(error, payloads);
|
|
366
467
|
if (isContextOverflowError(error)) {
|
|
367
468
|
return new FabricError({
|
|
368
469
|
code: "MODEL_CONTEXT_OVERFLOW",
|
|
369
470
|
message,
|
|
370
|
-
cause
|
|
471
|
+
cause,
|
|
371
472
|
retryable: true,
|
|
372
473
|
});
|
|
373
474
|
}
|
|
@@ -376,28 +477,276 @@ function mapModelError(error) {
|
|
|
376
477
|
return new FabricError({
|
|
377
478
|
code: "MODEL_RATE_LIMITED",
|
|
378
479
|
message,
|
|
379
|
-
cause
|
|
480
|
+
cause,
|
|
380
481
|
retryable: true,
|
|
381
482
|
});
|
|
382
483
|
if (error.status >= 500)
|
|
383
|
-
return new FabricError({ code: "UNKNOWN", message, cause
|
|
484
|
+
return new FabricError({ code: "UNKNOWN", message, cause, retryable: true });
|
|
384
485
|
if (error.status === 401 || error.status === 403)
|
|
385
|
-
return new FabricError({ code: "MODEL_AUTH_FAILED", message, cause
|
|
486
|
+
return new FabricError({ code: "MODEL_AUTH_FAILED", message, cause });
|
|
386
487
|
if (error.status === 400)
|
|
387
|
-
return new FabricError({ code: "UNKNOWN", message, cause
|
|
488
|
+
return new FabricError({ code: "UNKNOWN", message, cause });
|
|
388
489
|
}
|
|
389
490
|
if (/rate.?limit|429|too many requests/i.test(message))
|
|
390
|
-
return new FabricError({ code: "MODEL_RATE_LIMITED", message, cause
|
|
491
|
+
return new FabricError({ code: "MODEL_RATE_LIMITED", message, cause, retryable: true });
|
|
391
492
|
if (/timeout|timed out|aborted/i.test(message))
|
|
392
|
-
return new FabricError({ code: "MODEL_TIMEOUT", message, cause
|
|
493
|
+
return new FabricError({ code: "MODEL_TIMEOUT", message, cause, retryable: true });
|
|
393
494
|
if (/overloaded|500|502|503|504|service.?unavailable|server.?error|network.?error|connection.?(?:reset|refused|lost)|socket hang up|fetch failed|terminated/i.test(message)) {
|
|
394
|
-
return new FabricError({ code: "UNKNOWN", message, cause
|
|
495
|
+
return new FabricError({ code: "UNKNOWN", message, cause, retryable: true });
|
|
395
496
|
}
|
|
396
497
|
if (/auth|unauthorized|forbidden|401|403|api key/i.test(message))
|
|
397
|
-
return new FabricError({ code: "MODEL_AUTH_FAILED", message, cause
|
|
498
|
+
return new FabricError({ code: "MODEL_AUTH_FAILED", message, cause });
|
|
398
499
|
if (/bad request|400|invalid/i.test(message))
|
|
399
|
-
return new FabricError({ code: "UNKNOWN", message, cause
|
|
400
|
-
return new FabricError({ code: "UNKNOWN", message, cause
|
|
500
|
+
return new FabricError({ code: "UNKNOWN", message, cause });
|
|
501
|
+
return new FabricError({ code: "UNKNOWN", message, cause, retryable: true });
|
|
502
|
+
}
|
|
503
|
+
/**
|
|
504
|
+
* Stream one model turn with bounded, replacement-semantics retries.
|
|
505
|
+
*
|
|
506
|
+
* Every attempt has its own `attemptId`, stamped on each live `text_delta` and
|
|
507
|
+
* `toolcall_delta`. When an attempt fails with a transient provider error and
|
|
508
|
+
* retries remain, the loop retries it with the same backoff bounds as
|
|
509
|
+
* `generateWithRuntime`. If the failed attempt already emitted live output, a
|
|
510
|
+
* `model_attempt` event with `status: "superseded"` is emitted first so
|
|
511
|
+
* consumers discard that attempt's partial text and tool-call fragments. Only
|
|
512
|
+
* the successful attempt's aggregated `done` response is returned, so the
|
|
513
|
+
* durable record never contains superseded text and tool calls from a failed
|
|
514
|
+
* attempt are never executed. Cancellation, authentication, validation, and
|
|
515
|
+
* context-overflow failures are never retried. `modelTimeoutMs` bounds each
|
|
516
|
+
* attempt the same way it bounds a non-streaming call; an elapsed attempt is a
|
|
517
|
+
* retryable `MODEL_TIMEOUT`. Only failures raised by the provider stream are
|
|
518
|
+
* retried: a failure to emit, persist, or record locally propagates at once,
|
|
519
|
+
* so it never buys another paid provider call.
|
|
520
|
+
*/
|
|
521
|
+
async function streamModelWithRetry(provider, streamFn, request, context) {
|
|
522
|
+
const { input, operationId, turnId, emit } = context;
|
|
523
|
+
const retries = Math.max(0, input.modelRetries ?? MAX_TRANSIENT_MODEL_RETRIES);
|
|
524
|
+
const maxAttempts = retries + 1;
|
|
525
|
+
const baseDelayMs = input.modelRetryDelayMs ?? TRANSIENT_MODEL_RETRY_BASE_DELAY_MS;
|
|
526
|
+
const model = input.model !== undefined ? { model: input.model } : {};
|
|
527
|
+
let lastError;
|
|
528
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
|
|
529
|
+
if (input.signal?.aborted)
|
|
530
|
+
throw abortErrorFor(input.signal);
|
|
531
|
+
const attemptId = generateId();
|
|
532
|
+
const startedAt = Date.now();
|
|
533
|
+
const base = {
|
|
534
|
+
provider: provider.name,
|
|
535
|
+
...model,
|
|
536
|
+
attempt,
|
|
537
|
+
maxAttempts,
|
|
538
|
+
attemptId,
|
|
539
|
+
};
|
|
540
|
+
await input.recordEntry("model_attempt", { ...base, status: "start" });
|
|
541
|
+
await emit("model_attempt", { ...base, status: "start" });
|
|
542
|
+
// One durable recovery key per attempt so a retried attempt never
|
|
543
|
+
// collides with the superseded attempt's segment indices.
|
|
544
|
+
const chunkWriter = input.streamChunkStore
|
|
545
|
+
? new StreamChunkWriter(input.streamChunkStore, `${operationId}:${turnId}:${attemptId}`)
|
|
546
|
+
: undefined;
|
|
547
|
+
let emittedOutput = false;
|
|
548
|
+
const outcome = await consumeProviderStream(provider, streamFn, request, input, {
|
|
549
|
+
onChunk: async (chunk) => {
|
|
550
|
+
chunkWriter?.write(chunk);
|
|
551
|
+
if (chunk.textDelta) {
|
|
552
|
+
emittedOutput = true;
|
|
553
|
+
await emit("text_delta", { delta: chunk.textDelta, attemptId });
|
|
554
|
+
}
|
|
555
|
+
if (chunk.thinkingDelta) {
|
|
556
|
+
emittedOutput = true;
|
|
557
|
+
await emit("text_delta", { delta: chunk.thinkingDelta, kind: "thinking", attemptId });
|
|
558
|
+
}
|
|
559
|
+
if (chunk.toolCallDelta) {
|
|
560
|
+
emittedOutput = true;
|
|
561
|
+
await emit("toolcall_delta", { ...chunk.toolCallDelta, attemptId });
|
|
562
|
+
}
|
|
563
|
+
},
|
|
564
|
+
close: async () => {
|
|
565
|
+
await chunkWriter?.close();
|
|
566
|
+
},
|
|
567
|
+
});
|
|
568
|
+
// Local failures (event emission, chunk persistence, success recording)
|
|
569
|
+
// propagate from here unchanged. Only a failure raised while advancing the
|
|
570
|
+
// provider stream is classified and possibly retried as a provider error.
|
|
571
|
+
if (outcome.ok) {
|
|
572
|
+
const success = {
|
|
573
|
+
...base,
|
|
574
|
+
status: "success",
|
|
575
|
+
durationMs: Date.now() - startedAt,
|
|
576
|
+
};
|
|
577
|
+
await input.recordEntry("model_attempt", success);
|
|
578
|
+
await emit("model_attempt", success);
|
|
579
|
+
return outcome.response;
|
|
580
|
+
}
|
|
581
|
+
const rawError = outcome.error;
|
|
582
|
+
const aborted = input.signal?.aborted === true;
|
|
583
|
+
const canRetry = !aborted &&
|
|
584
|
+
attempt < maxAttempts &&
|
|
585
|
+
!isContextOverflowError(rawError) &&
|
|
586
|
+
isRetryableModelError(rawError);
|
|
587
|
+
// Provider errors can echo this request's attachment payloads verbatim,
|
|
588
|
+
// however short, in the message and anywhere in the error graph (a nested
|
|
589
|
+
// `cause`, `AggregateError.errors`, custom string fields). Scrub the whole
|
|
590
|
+
// graph in place before the error is recorded, rethrown or kept as a
|
|
591
|
+
// cause; retry classification above used the untouched error.
|
|
592
|
+
const payloads = collectAttachmentPayloads(request.messages);
|
|
593
|
+
const error = redactErrorAttachmentPayloads(rawError, payloads);
|
|
594
|
+
lastError = error;
|
|
595
|
+
const message = redactAttachmentPayloads(error.message, payloads);
|
|
596
|
+
if (canRetry && emittedOutput) {
|
|
597
|
+
await emit("model_attempt", {
|
|
598
|
+
...base,
|
|
599
|
+
status: "superseded",
|
|
600
|
+
supersededAttemptId: attemptId,
|
|
601
|
+
reason: message,
|
|
602
|
+
});
|
|
603
|
+
}
|
|
604
|
+
const failure = {
|
|
605
|
+
...base,
|
|
606
|
+
status: canRetry ? "retry" : "error",
|
|
607
|
+
durationMs: Date.now() - startedAt,
|
|
608
|
+
error: message,
|
|
609
|
+
...(canRetry && emittedOutput ? { supersededPartialOutput: true } : {}),
|
|
610
|
+
};
|
|
611
|
+
await input.recordEntry("model_attempt", failure);
|
|
612
|
+
await emit("model_attempt", failure);
|
|
613
|
+
if (aborted && input.signal)
|
|
614
|
+
throw abortErrorFor(input.signal, error);
|
|
615
|
+
if (!canRetry)
|
|
616
|
+
throw error;
|
|
617
|
+
const retryAfterMs = error instanceof ProviderHttpError ? error.retryAfterMs : undefined;
|
|
618
|
+
const waitMs = retryAfterMs && retryAfterMs > 0
|
|
619
|
+
? Math.min(retryAfterMs, 60_000)
|
|
620
|
+
: calculateRetryDelay(baseDelayMs, attempt);
|
|
621
|
+
if (input.signal) {
|
|
622
|
+
try {
|
|
623
|
+
await sleepWithAbort(waitMs, input.signal);
|
|
624
|
+
}
|
|
625
|
+
catch {
|
|
626
|
+
throw abortErrorFor(input.signal);
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
else {
|
|
630
|
+
await new Promise((resolve) => setTimeout(resolve, waitMs));
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
throw lastError instanceof Error ? lastError : new Error(String(lastError));
|
|
634
|
+
}
|
|
635
|
+
/**
|
|
636
|
+
* Drain one provider stream attempt under a per-attempt timeout.
|
|
637
|
+
*
|
|
638
|
+
* The provider receives an attempt signal that aborts when the caller's signal
|
|
639
|
+
* aborts or when `modelTimeoutMs` elapses, and every `next()` also races that
|
|
640
|
+
* signal so a stream that ignores it (never yields, or stalls mid-stream)
|
|
641
|
+
* still settles. Failures raised by the provider stream come back as
|
|
642
|
+
* `{ ok: false }` for retry classification, with a timeout reported as a
|
|
643
|
+
* retryable `MODEL_TIMEOUT`. Failures raised by `onChunk` or `close` are
|
|
644
|
+
* local and are thrown unchanged.
|
|
645
|
+
*/
|
|
646
|
+
async function consumeProviderStream(provider, streamFn, request, input, handlers) {
|
|
647
|
+
const controller = new AbortController();
|
|
648
|
+
const onCallerAbort = () => controller.abort(input.signal?.reason);
|
|
649
|
+
if (input.signal?.aborted)
|
|
650
|
+
onCallerAbort();
|
|
651
|
+
else
|
|
652
|
+
input.signal?.addEventListener("abort", onCallerAbort, { once: true });
|
|
653
|
+
const timeoutMs = input.modelTimeoutMs;
|
|
654
|
+
let timeoutError;
|
|
655
|
+
const timer = timeoutMs !== undefined && timeoutMs > 0
|
|
656
|
+
? setTimeout(() => {
|
|
657
|
+
timeoutError = new FabricError({
|
|
658
|
+
code: "MODEL_TIMEOUT",
|
|
659
|
+
message: `Model call timed out after ${timeoutMs}ms`,
|
|
660
|
+
retryable: true,
|
|
661
|
+
});
|
|
662
|
+
controller.abort(timeoutError);
|
|
663
|
+
}, timeoutMs)
|
|
664
|
+
: undefined;
|
|
665
|
+
let rejectOnAbort;
|
|
666
|
+
const aborted = new Promise((_, reject) => {
|
|
667
|
+
rejectOnAbort = reject;
|
|
668
|
+
});
|
|
669
|
+
// Never an unhandled rejection when nothing is awaiting the race.
|
|
670
|
+
aborted.catch(() => undefined);
|
|
671
|
+
const onAttemptAbort = () => rejectOnAbort?.(controller.signal.reason);
|
|
672
|
+
if (controller.signal.aborted)
|
|
673
|
+
onAttemptAbort();
|
|
674
|
+
else
|
|
675
|
+
controller.signal.addEventListener("abort", onAttemptAbort, { once: true });
|
|
676
|
+
let iterator;
|
|
677
|
+
let finished = false;
|
|
678
|
+
const providerFailure = (error) => ({
|
|
679
|
+
ok: false,
|
|
680
|
+
error: timeoutError ?? error,
|
|
681
|
+
});
|
|
682
|
+
try {
|
|
683
|
+
let aggregated;
|
|
684
|
+
try {
|
|
685
|
+
const stream = streamFn.call(provider, {
|
|
686
|
+
...request,
|
|
687
|
+
signal: controller.signal,
|
|
688
|
+
});
|
|
689
|
+
iterator = stream[Symbol.asyncIterator]();
|
|
690
|
+
}
|
|
691
|
+
catch (error) {
|
|
692
|
+
return providerFailure(error);
|
|
693
|
+
}
|
|
694
|
+
for (;;) {
|
|
695
|
+
let next;
|
|
696
|
+
try {
|
|
697
|
+
next = await Promise.race([iterator.next(), aborted]);
|
|
698
|
+
}
|
|
699
|
+
catch (error) {
|
|
700
|
+
return providerFailure(error);
|
|
701
|
+
}
|
|
702
|
+
if (next.done) {
|
|
703
|
+
finished = true;
|
|
704
|
+
break;
|
|
705
|
+
}
|
|
706
|
+
await handlers.onChunk(next.value);
|
|
707
|
+
if (next.value.done)
|
|
708
|
+
aggregated = next.value.done;
|
|
709
|
+
}
|
|
710
|
+
if (!aggregated) {
|
|
711
|
+
return providerFailure(new Error(`${provider.name}: stream ended without a final response.`));
|
|
712
|
+
}
|
|
713
|
+
return { ok: true, response: aggregated };
|
|
714
|
+
}
|
|
715
|
+
finally {
|
|
716
|
+
if (timer)
|
|
717
|
+
clearTimeout(timer);
|
|
718
|
+
input.signal?.removeEventListener("abort", onCallerAbort);
|
|
719
|
+
controller.signal.removeEventListener("abort", onAttemptAbort);
|
|
720
|
+
if (!finished && iterator?.return) {
|
|
721
|
+
// Release the provider stream without waiting on one that ignores
|
|
722
|
+
// cancellation; its settlement no longer affects this attempt.
|
|
723
|
+
if (!controller.signal.aborted)
|
|
724
|
+
controller.abort();
|
|
725
|
+
Promise.resolve()
|
|
726
|
+
.then(() => iterator?.return?.())
|
|
727
|
+
.catch(() => undefined);
|
|
728
|
+
}
|
|
729
|
+
await handlers.close();
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
/** Cancellation stays a distinguishable AbortError; it is never mapped to a retryable model error. */
|
|
733
|
+
function abortErrorFor(signal, cause) {
|
|
734
|
+
if (cause instanceof Error && cause.name === "AbortError")
|
|
735
|
+
return cause;
|
|
736
|
+
const reason = signal.reason;
|
|
737
|
+
const message = reason instanceof Error && reason.message
|
|
738
|
+
? reason.message
|
|
739
|
+
: typeof reason === "string" && reason
|
|
740
|
+
? reason
|
|
741
|
+
: "The operation was aborted.";
|
|
742
|
+
const error = new DOMException(message, "AbortError");
|
|
743
|
+
try {
|
|
744
|
+
Object.defineProperty(error, "cause", { value: reason, configurable: true });
|
|
745
|
+
}
|
|
746
|
+
catch {
|
|
747
|
+
// `cause` is read-only on DOMException in some runtimes.
|
|
748
|
+
}
|
|
749
|
+
return error;
|
|
401
750
|
}
|
|
402
751
|
function generateId() {
|
|
403
752
|
if (typeof globalThis !== "undefined" && globalThis.crypto?.randomUUID) {
|