@caupulican/pi-ai 0.86.17 → 0.90.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/stream.d.ts CHANGED
@@ -1,7 +1,28 @@
1
1
  import "./providers/register-builtins.ts";
2
- import type { Api, AssistantMessage, Context, Model, ProviderStreamOptions, SimpleStreamOptions } from "./types.ts";
2
+ import type { Api, AssistantMessage, Context, Model, ProviderStreamOptions, SimpleStreamOptions, StreamOptions } from "./types.ts";
3
3
  import { AssistantMessageEventStream } from "./utils/event-stream.ts";
4
4
  export { getEnvApiKey } from "./env-api-keys.ts";
5
+ /**
6
+ * Immutable provider-input materialization. `context` is the exact Context object passed to the
7
+ * provider transport; `sourceContext` retains native tool definitions only for response parsing.
8
+ */
9
+ export interface MaterializedProviderRequest {
10
+ context: Context;
11
+ sourceContext: Context;
12
+ usesTextToolProtocol: boolean;
13
+ }
14
+ /**
15
+ * Resolve provider-visible context once, including the text-only tool primer and synthetic guard
16
+ * message. Callers may budget/admit `result.context`, then send that same object through
17
+ * {@link startMaterializedProviderStream} without re-rendering it.
18
+ */
19
+ export declare function materializeProviderRequest(context: Context, options: StreamOptions | undefined): MaterializedProviderRequest;
20
+ /**
21
+ * Send one already-admitted materialization. Its provider context has no native tool surface, so a
22
+ * nested public stream cannot render the primer again. Preserve the protocol option for provider
23
+ * history serialization; response parsing remains owned here.
24
+ */
25
+ export declare function startMaterializedProviderStream<TOptions extends StreamOptions>(model: Model<Api>, request: MaterializedProviderRequest, options: TOptions | undefined, startProviderStream: (providerContext: Context, providerOptions: TOptions | undefined) => AssistantMessageEventStream | Promise<AssistantMessageEventStream>): Promise<AssistantMessageEventStream>;
5
26
  export declare function stream<TApi extends Api>(model: Model<TApi>, context: Context, options?: ProviderStreamOptions): AssistantMessageEventStream;
6
27
  export declare function complete<TApi extends Api>(model: Model<TApi>, context: Context, options?: ProviderStreamOptions): Promise<AssistantMessage>;
7
28
  export declare function streamSimple<TApi extends Api>(model: Model<TApi>, context: Context, options?: SimpleStreamOptions): AssistantMessageEventStream;
@@ -1 +1 @@
1
- {"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../src/stream.ts"],"names":[],"mappings":"AAAA,OAAO,kCAAkC,CAAC;AAI1C,OAAO,KAAK,EACX,GAAG,EACH,gBAAgB,EAEhB,OAAO,EAEP,KAAK,EACL,qBAAqB,EACrB,mBAAmB,EAGnB,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AAQtE,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAwYjD,wBAAgB,MAAM,CAAC,IAAI,SAAS,GAAG,EACtC,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,EAClB,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,qBAAqB,GAC7B,2BAA2B,CAM7B;AAED,wBAAsB,QAAQ,CAAC,IAAI,SAAS,GAAG,EAC9C,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,EAClB,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,qBAAqB,GAC7B,OAAO,CAAC,gBAAgB,CAAC,CAG3B;AAED,wBAAgB,YAAY,CAAC,IAAI,SAAS,GAAG,EAC5C,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,EAClB,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,mBAAmB,GAC3B,2BAA2B,CAM7B;AAED,wBAAsB,cAAc,CAAC,IAAI,SAAS,GAAG,EACpD,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,EAClB,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,gBAAgB,CAAC,CAG3B"}
1
+ {"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../src/stream.ts"],"names":[],"mappings":"AAAA,OAAO,kCAAkC,CAAC;AAI1C,OAAO,KAAK,EACX,GAAG,EACH,gBAAgB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AC,EAClB,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,mBAAmB,GAC3B,2BAA2B,CAM7B;AAED,wBAAsB,cAAc,CAAC,IAAI,SAAS,GAAG,EACpD,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,EAClB,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,gBAAgB,CAAC,CAG3B"}
package/dist/stream.js CHANGED
@@ -35,20 +35,6 @@ function withEnvAuth(model, options) {
35
35
  return options;
36
36
  return { ...options, apiKey };
37
37
  }
38
- function withTextProtocolUserReminder(message) {
39
- if (message.role !== "user")
40
- return message;
41
- const reminder = "Tool-use reminder: if this request asks to read a file, call exactly one tool named read before answering; do not guess file contents.";
42
- if (typeof message.content === "string")
43
- return { ...message, content: `${message.content}\n\n${reminder}` };
44
- return { ...message, content: [...message.content, { type: "text", text: reminder }] };
45
- }
46
- function withTextProtocolUserReminders(messages) {
47
- // Apply the same transformation to historical user turns. A reminder added only
48
- // to the live turn disappears when that turn becomes history, changing the prior
49
- // request prefix and defeating provider prompt-cache reuse.
50
- return messages.map(withTextProtocolUserReminder);
51
- }
52
38
  function withTextToolProtocolContext(context, options) {
53
39
  const protocolOptions = normalizeTextToolProtocolOptions(options?.textToolCallProtocol);
54
40
  if (!protocolOptions || !context.tools?.length)
@@ -64,12 +50,12 @@ function withTextToolProtocolContext(context, options) {
64
50
  content: [
65
51
  {
66
52
  type: "text",
67
- text: "Tool-call instructions for this conversation are defined in the system prompt above. Do not answer this instruction; apply the system-prompt tool-call format to subsequent user requests. If the next user request asks to read a file, your first response must be a read tool call and nothing else.",
53
+ text: "Apply system tool protocol; never answer this message.",
68
54
  },
69
55
  ],
70
56
  timestamp: 0,
71
57
  },
72
- ...withTextProtocolUserReminders(context.messages),
58
+ ...context.messages,
73
59
  ]
74
60
  : context.messages;
75
61
  return {
@@ -78,6 +64,20 @@ function withTextToolProtocolContext(context, options) {
78
64
  messages,
79
65
  };
80
66
  }
67
+ /**
68
+ * Resolve provider-visible context once, including the text-only tool primer and synthetic guard
69
+ * message. Callers may budget/admit `result.context`, then send that same object through
70
+ * {@link startMaterializedProviderStream} without re-rendering it.
71
+ */
72
+ export function materializeProviderRequest(context, options) {
73
+ const protocolOptions = normalizeTextToolProtocolOptions(options?.textToolCallProtocol);
74
+ const usesTextToolProtocol = protocolOptions !== undefined && Boolean(context.tools?.length);
75
+ return {
76
+ context: usesTextToolProtocol ? withTextToolProtocolContext(context, options) : context,
77
+ sourceContext: context,
78
+ usesTextToolProtocol,
79
+ };
80
+ }
81
81
  async function notifyTextToolProtocolParse(options, event) {
82
82
  try {
83
83
  await options?.onTextToolProtocolParse?.(event);
@@ -318,14 +318,36 @@ function withTextToolProtocolResult(stream, model, context, options, control) {
318
318
  return wrapped;
319
319
  }
320
320
  function startTextToolProtocolStream(model, context, options, startProviderStream) {
321
- const protocolOptions = normalizeTextToolProtocolOptions(options?.textToolCallProtocol);
322
- if (!protocolOptions || !context.tools?.length)
323
- return startProviderStream(context, options);
321
+ const request = materializeProviderRequest(context, options);
322
+ if (!request.usesTextToolProtocol)
323
+ return startProviderStream(request.context, options);
324
324
  const abortController = new AbortController();
325
325
  const combined = combineAbortSignals([options?.signal, abortController.signal]);
326
326
  const providerOptions = { ...options, signal: combined.signal };
327
- const protocolContext = withTextToolProtocolContext(context, providerOptions);
328
- return withTextToolProtocolResult(startProviderStream(protocolContext, providerOptions), model, context, providerOptions, { abortController, cleanup: combined.cleanup });
327
+ return withTextToolProtocolResult(startProviderStream(request.context, providerOptions), model, request.sourceContext, providerOptions, { abortController, cleanup: combined.cleanup });
328
+ }
329
+ /**
330
+ * Send one already-admitted materialization. Its provider context has no native tool surface, so a
331
+ * nested public stream cannot render the primer again. Preserve the protocol option for provider
332
+ * history serialization; response parsing remains owned here.
333
+ */
334
+ export async function startMaterializedProviderStream(model, request, options, startProviderStream) {
335
+ if (!request.usesTextToolProtocol)
336
+ return await startProviderStream(request.context, options);
337
+ const abortController = new AbortController();
338
+ const combined = combineAbortSignals([options?.signal, abortController.signal]);
339
+ const providerOptions = { ...options, signal: combined.signal };
340
+ try {
341
+ const stream = await startProviderStream(request.context, providerOptions);
342
+ return withTextToolProtocolResult(stream, model, request.sourceContext, options, {
343
+ abortController,
344
+ cleanup: combined.cleanup,
345
+ });
346
+ }
347
+ catch (error) {
348
+ combined.cleanup();
349
+ throw error;
350
+ }
329
351
  }
330
352
  function resolveApiProvider(api) {
331
353
  const provider = getApiProvider(api);
@@ -1 +1 @@
1
- {"version":3,"file":"stream.js","sourceRoot":"","sources":["../src/stream.ts"],"names":[],"mappings":"AAAA,OAAO,kCAAkC,CAAC;AAE1C,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAapE,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,EAAE,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AACtE,OAAO,EACN,8BAA8B,EAC9B,gCAAgC,EAChC,kBAAkB,GAClB,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,sBAAsB,EAAE,MAAM,kDAAkD,CAAC;AAE1F,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD,IAAI,6BAA6B,GAAG,CAAC,CAAC;AAEtC,kGAAkG;AAClG,iGAAiG;AACjG,qGAAqG;AACrG,MAAM,uCAAuC,GAAG,GAAG,CAAC;AAEpD,SAAS,gCAAgC;IACxC,6BAA6B;QAC5B,6BAA6B,IAAI,MAAM,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,6BAA6B,GAAG,CAAC,CAAC;IAClG,OAAO,aAAa,6BAA6B,EAAE,CAAC;AACrD,CAAC;AAED,SAAS,iBAAiB,CAAC,MAA0B;IACpD,OAAO,OAAO,MAAM,KAAK,QAAQ,IAAI,M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AO,CAAC,CAAC;IACpD,OAAO,2BAA2B,CAAC,KAAK,EAAE,OAAO,EAAE,eAAe,EAAE,CAAC,eAAe,EAAE,eAAe,EAAE,EAAE,CACxG,QAAQ,CAAC,YAAY,CAAC,KAAK,EAAE,eAAe,EAAE,eAAe,CAAC,CAC9D,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,cAAc,CACnC,KAAkB,EAClB,OAAgB,EAChB,OAA6B;IAE7B,MAAM,CAAC,GAAG,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAChD,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC;AACnB,CAAC","sourcesContent":["import \"./providers/register-builtins.ts\";\n\nimport { getApiProvider } from \"./api-registry.ts\";\nimport { getEnvApiKey, getEnvAuthHeaders } from \"./env-api-keys.ts\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tContext,\n\tMessage,\n\tModel,\n\tProviderStreamOptions,\n\tSimpleStreamOptions,\n\tStreamOptions,\n\tTextToolProtocolParseEvent,\n} from \"./types.ts\";\nimport { combineAbortSignals } from \"./utils/abort-signals.ts\";\nimport { AssistantMessageEventStream } from \"./utils/event-stream.ts\";\nimport {\n\tgenerateTextToolProtocolPrimer,\n\tnormalizeTextToolProtocolOptions,\n\tparseTextToolCalls,\n} from \"./utils/tool-repair/text-protocol.ts\";\nimport { TextProtocolLiveFilter } from \"./utils/tool-repair/text-protocol-live-filter.ts\";\n\nexport { getEnvApiKey } from \"./env-api-keys.ts\";\n\nlet textToolProtocolBatchSequence = 0;\n\n// Once a complete call exists, a short bounded suffix preserves adjacent parallel envelopes while\n// preventing a small model from spending its remaining output budget on unusable trailing prose.\n// Envelope bodies themselves are never counted, so large write/edit arguments remain unbounded here.\nconst TEXT_TOOL_PROTOCOL_TRAILING_PROSE_LIMIT = 128;\n\nfunction nextTextToolProtocolCallIdPrefix(): string {\n\ttextToolProtocolBatchSequence =\n\t\ttextToolProtocolBatchSequence >= Number.MAX_SAFE_INTEGER ? 1 : textToolProtocolBatchSequence + 1;\n\treturn `text-tool-${textToolProtocolBatchSequence}`;\n}\n\nfunction hasExplicitApiKey(apiKey: string | undefined): apiKey is string {\n\treturn typeof apiKey === \"string\" && apiKey.trim().length > 0;\n}\n\nfunction hasAuthorizationHeader(headers: Record<string, string> | undefined): boolean {\n\treturn Object.entries(headers ?? {}).some(\n\t\t([name, value]) => name.toLowerCase() === \"authorization\" && value.trim().length > 0,\n\t);\n}\n\nfunction withEnvAuth<TOptions extends StreamOptions>(\n\tmodel: Model<Api>,\n\toptions: TOptions | undefined,\n): TOptions | undefined {\n\tif (hasExplicitApiKey(options?.apiKey)) return options;\n\tif (hasAuthorizationHeader(options?.headers)) return options;\n\tconst envHeaders = getEnvAuthHeaders(model.provider);\n\tif (envHeaders) return { ...options, headers: { ...envHeaders, ...options?.headers } } as TOptions;\n\tconst apiKey = getEnvApiKey(model.provider);\n\tif (!apiKey) return options;\n\treturn { ...options, apiKey } as TOptions;\n}\n\nfunction withTextProtocolUserReminder(message: Message): Message {\n\tif (message.role !== \"user\") return message;\n\tconst reminder =\n\t\t\"Tool-use reminder: if this request asks to read a file, call exactly one tool named read before answering; do not guess file contents.\";\n\tif (typeof message.content === \"string\") return { ...message, content: `${message.content}\\n\\n${reminder}` };\n\treturn { ...message, content: [...message.content, { type: \"text\", text: reminder }] };\n}\n\nfunction withTextProtocolUserReminders(messages: readonly Message[]): Message[] {\n\t// Apply the same transformation to historical user turns. A reminder added only\n\t// to the live turn disappears when that turn becomes history, changing the prior\n\t// request prefix and defeating provider prompt-cache reuse.\n\treturn messages.map(withTextProtocolUserReminder);\n}\n\nfunction withTextToolProtocolContext(context: Context, options: StreamOptions | undefined): Context {\n\tconst protocolOptions = normalizeTextToolProtocolOptions(options?.textToolCallProtocol);\n\tif (!protocolOptions || !context.tools?.length) return context;\n\tconst primer = generateTextToolProtocolPrimer(context.tools, protocolOptions);\n\tif (!primer) return context;\n\tconst { tools: _tools, ...providerContext } = context;\n\tconst messages = context.messages.length\n\t\t? [\n\t\t\t\t{\n\t\t\t\t\trole: \"user\" as const,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\t\ttext: \"Tool-call instructions for this conversation are defined in the system prompt above. Do not answer this instruction; apply the system-prompt tool-call format to subsequent user requests. If the next user request asks to read a file, your first response must be a read tool call and nothing else.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\ttimestamp: 0,\n\t\t\t\t},\n\t\t\t\t...withTextProtocolUserReminders(context.messages),\n\t\t\t]\n\t\t: context.messages;\n\treturn {\n\t\t...providerContext,\n\t\tsystemPrompt: context.systemPrompt ? `${context.systemPrompt}\\n\\n${primer}` : primer,\n\t\tmessages,\n\t};\n}\n\nasync function notifyTextToolProtocolParse(\n\toptions: StreamOptions | undefined,\n\tevent: TextToolProtocolParseEvent,\n): Promise<void> {\n\ttry {\n\t\tawait options?.onTextToolProtocolParse?.(event);\n\t} catch {\n\t\t// Parse telemetry must not change provider stream semantics.\n\t}\n}\n\n// Rewrites any text or thinking block whose revealed prose is still behind its true streamed\n// content so a forwarded event's `partial` snapshot never exposes held-back envelope markup. Some\n// OpenAI-compatible local servers classify the model's entire phone envelope as reasoning.\nfunction redactHeldProtocolContent(\n\tpartial: AssistantMessage,\n\trevealedContent: ReadonlyMap<number, string>,\n): AssistantMessage {\n\tif (revealedContent.size === 0) return partial;\n\tlet changed = false;\n\tconst content = partial.content.map((block, index) => {\n\t\tconst revealed = revealedContent.get(index);\n\t\tif (revealed === undefined) return block;\n\t\tif (block.type === \"text\" && block.text !== revealed) {\n\t\t\tchanged = true;\n\t\t\treturn { ...block, text: revealed };\n\t\t}\n\t\tif (block.type !== \"thinking\" || block.thinking === revealed) return block;\n\t\tchanged = true;\n\t\treturn { ...block, thinking: revealed };\n\t});\n\treturn changed ? { ...partial, content } : partial;\n}\n\n// Forwards one non-\"done\" stream event, holding back streamed text that falls inside (or\n// might still grow into) a text-protocol envelope so raw markup like \"<pi:call\" never reaches\n// a live consumer. Prose outside envelopes is forwarded as soon as it is provably safe; the\n// \"done\" event swap remains the sole authority for final content.\nfunction forwardTextProtocolStreamEvent(\n\twrapped: AssistantMessageEventStream,\n\tevent: Exclude<AssistantMessageEvent, { type: \"done\" }>,\n\trevealedContent: Map<number, string>,\n\tliveFilters: Map<number, TextProtocolLiveFilter>,\n): void {\n\tif (event.type === \"error\") {\n\t\twrapped.push(event);\n\t\treturn;\n\t}\n\tif (event.type === \"text_start\" || event.type === \"thinking_start\") {\n\t\trevealedContent.set(event.contentIndex, \"\");\n\t\tliveFilters.set(event.contentIndex, new TextProtocolLiveFilter());\n\t\twrapped.push({ ...event, partial: redactHeldProtocolContent(event.partial, revealedContent) });\n\t\treturn;\n\t}\n\tif (event.type === \"text_delta\" || event.type === \"thinking_delta\") {\n\t\tconst flushed = revealedContent.get(event.contentIndex) ?? \"\";\n\t\tconst filter = liveFilters.get(event.contentIndex) ?? new TextProtocolLiveFilter();\n\t\tliveFilters.set(event.contentIndex, filter);\n\t\tconst visible = filter.advance(event.delta);\n\t\tif (visible.length <= flushed.length) return; // held: possibly-envelope text never streams live\n\t\trevealedContent.set(event.contentIndex, visible);\n\t\twrapped.push({\n\t\t\t...event,\n\t\t\tdelta: visible.slice(flushed.length),\n\t\t\tpartial: redactHeldProtocolContent(event.partial, revealedContent),\n\t\t});\n\t\treturn;\n\t}\n\tif (event.type === \"text_end\" || event.type === \"thinking_end\") {\n\t\tconst flushed = revealedContent.get(event.contentIndex) ?? \"\";\n\t\tconst filter = liveFilters.get(event.contentIndex) ?? new TextProtocolLiveFilter();\n\t\tliveFilters.set(event.contentIndex, filter);\n\t\tconst visible = filter.finish(event.content);\n\t\tif (visible.length > flushed.length) {\n\t\t\t// Catch up any newly-provable-safe tail (e.g. a suspected opener prefix that never\n\t\t\t// completed) so the deltas actually forwarded still sum to what text_end reports.\n\t\t\trevealedContent.set(event.contentIndex, visible);\n\t\t\twrapped.push(\n\t\t\t\tevent.type === \"text_end\"\n\t\t\t\t\t? {\n\t\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\t\tcontentIndex: event.contentIndex,\n\t\t\t\t\t\t\tdelta: visible.slice(flushed.length),\n\t\t\t\t\t\t\tpartial: redactHeldProtocolContent(event.partial, revealedContent),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\t\tcontentIndex: event.contentIndex,\n\t\t\t\t\t\t\tdelta: visible.slice(flushed.length),\n\t\t\t\t\t\t\tpartial: redactHeldProtocolContent(event.partial, revealedContent),\n\t\t\t\t\t\t},\n\t\t\t);\n\t\t}\n\t\tconst finalVisible = revealedContent.get(event.contentIndex) ?? visible;\n\t\twrapped.push({\n\t\t\t...event,\n\t\t\tcontent: finalVisible,\n\t\t\tpartial: redactHeldProtocolContent(event.partial, revealedContent),\n\t\t});\n\t\treturn;\n\t}\n\twrapped.push({ ...event, partial: redactHeldProtocolContent(event.partial, revealedContent) });\n}\n\ninterface TextToolProtocolMessageProjection {\n\tmessage: AssistantMessage;\n\tcallCount: number;\n\ttextLength: number;\n\tfailure?: TextToolProtocolParseEvent[\"reason\"];\n\tprotocolAttempted: boolean;\n}\n\nfunction projectTextToolProtocolMessage(\n\tmessage: AssistantMessage,\n\tmodel: Model<Api>,\n\ttools: readonly NonNullable<Context[\"tools\"]>[number][],\n\tcallIdPrefix: string,\n): TextToolProtocolMessageProjection {\n\tconst content: AssistantMessage[\"content\"] = [];\n\tlet callCount = 0;\n\tlet textLength = 0;\n\tlet failure: TextToolProtocolParseEvent[\"reason\"] | undefined;\n\tlet protocolAttempted = false;\n\tfor (const block of message.content) {\n\t\tif (block.type !== \"text\" && (block.type !== \"thinking\" || block.redacted)) {\n\t\t\tcontent.push(block);\n\t\t\tcontinue;\n\t\t}\n\t\tconst protocolText = block.type === \"text\" ? block.text : block.thinking;\n\t\ttextLength += protocolText.length;\n\t\tconst parsed = parseTextToolCalls(protocolText, tools, {\n\t\t\tcallIdPrefix,\n\t\t\tcallIndexOffset: callCount,\n\t\t});\n\t\tprotocolAttempted ||= parsed.attempted;\n\t\tif (parsed.calls.length === 0) {\n\t\t\tif (parsed.failure) failure ??= parsed.failure;\n\t\t\tcontent.push(block);\n\t\t\tcontinue;\n\t\t}\n\t\tcallCount += parsed.calls.length;\n\t\tif (parsed.text) {\n\t\t\tcontent.push(block.type === \"text\" ? { ...block, text: parsed.text } : { ...block, thinking: parsed.text });\n\t\t}\n\t\tcontent.push(...parsed.calls);\n\t}\n\tif (callCount > 0) {\n\t\treturn {\n\t\t\tmessage: { ...message, content, stopReason: \"toolUse\" },\n\t\t\tcallCount,\n\t\t\ttextLength,\n\t\t\tfailure,\n\t\t\tprotocolAttempted,\n\t\t};\n\t}\n\tconst hasVisibleText = message.content.some((block) => block.type === \"text\" && block.text.trim().length > 0);\n\tconst promoteThinking =\n\t\tmodel.reasoning === false &&\n\t\t!protocolAttempted &&\n\t\t!hasVisibleText &&\n\t\tmessage.content.some((block) => block.type === \"thinking\" && !block.redacted);\n\treturn {\n\t\tmessage: promoteThinking\n\t\t\t? {\n\t\t\t\t\t...message,\n\t\t\t\t\tcontent: message.content.flatMap((block) => {\n\t\t\t\t\t\tif (block.type === \"thinking\" && !block.redacted) {\n\t\t\t\t\t\t\treturn [{ type: \"text\" as const, text: block.thinking }];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (block.type === \"text\" && block.text.length === 0) return [];\n\t\t\t\t\t\treturn [block];\n\t\t\t\t\t}),\n\t\t\t\t}\n\t\t\t: message,\n\t\tcallCount,\n\t\ttextLength,\n\t\tfailure,\n\t\tprotocolAttempted,\n\t};\n}\n\ninterface TextToolProtocolStreamControl {\n\tabortController: AbortController;\n\tcleanup(): void;\n}\n\nfunction withTextToolProtocolResult(\n\tstream: AssistantMessageEventStream,\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions: StreamOptions | undefined,\n\tcontrol?: TextToolProtocolStreamControl,\n): AssistantMessageEventStream {\n\tconst protocolOptions = normalizeTextToolProtocolOptions(options?.textToolCallProtocol);\n\tconst tools = context.tools ?? [];\n\tif (!protocolOptions || tools.length === 0) return stream;\n\tconst wrapped = new AssistantMessageEventStream();\n\tconst callIdPrefix = nextTextToolProtocolCallIdPrefix();\n\tvoid (async () => {\n\t\tconst revealedContent = new Map<number, string>();\n\t\tconst liveFilters = new Map<number, TextProtocolLiveFilter>();\n\t\tlet completedEnvelopeCount = 0;\n\t\tlet trailingProseLength = 0;\n\t\tlet completedProjection: TextToolProtocolMessageProjection | undefined;\n\t\ttry {\n\t\t\tfor await (const event of stream) {\n\t\t\t\tif (event.type !== \"done\") {\n\t\t\t\t\tif (event.type === \"text_delta\" || event.type === \"thinking_delta\") {\n\t\t\t\t\t\tif (completedProjection) trailingProseLength += event.delta.length;\n\t\t\t\t\t}\n\t\t\t\t\tforwardTextProtocolStreamEvent(wrapped, event, revealedContent, liveFilters);\n\t\t\t\t\tconst observedEnvelopeCount = [...liveFilters.values()].reduce(\n\t\t\t\t\t\t(total, filter) => total + filter.completedEnvelopeCount,\n\t\t\t\t\t\t0,\n\t\t\t\t\t);\n\t\t\t\t\tif (observedEnvelopeCount > completedEnvelopeCount && \"partial\" in event) {\n\t\t\t\t\t\tcompletedEnvelopeCount = observedEnvelopeCount;\n\t\t\t\t\t\tconst projection = projectTextToolProtocolMessage(event.partial, model, tools, callIdPrefix);\n\t\t\t\t\t\tif (projection.callCount > 0) {\n\t\t\t\t\t\t\tcompletedProjection = projection;\n\t\t\t\t\t\t\ttrailingProseLength = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconst holdingPotentialEnvelope = [...liveFilters.values()].some(\n\t\t\t\t\t\t(filter) => filter.holdingPotentialEnvelope,\n\t\t\t\t\t);\n\t\t\t\t\tif (\n\t\t\t\t\t\tcompletedProjection &&\n\t\t\t\t\t\ttrailingProseLength > TEXT_TOOL_PROTOCOL_TRAILING_PROSE_LIMIT &&\n\t\t\t\t\t\t!holdingPotentialEnvelope &&\n\t\t\t\t\t\tcontrol\n\t\t\t\t\t) {\n\t\t\t\t\t\tcontrol.abortController.abort(\"text-tool-protocol-call-complete\");\n\t\t\t\t\t\tawait notifyTextToolProtocolParse(options, {\n\t\t\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\t\t\tmodel: model.id,\n\t\t\t\t\t\t\tvariant: protocolOptions.variant ?? \"tool-tag\",\n\t\t\t\t\t\t\tstatus: \"parsed\",\n\t\t\t\t\t\t\tcallCount: completedProjection.callCount,\n\t\t\t\t\t\t\ttextLength: completedProjection.textLength,\n\t\t\t\t\t\t});\n\t\t\t\t\t\twrapped.push({ type: \"done\", reason: \"toolUse\", message: completedProjection.message });\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst projection = projectTextToolProtocolMessage(event.message, model, tools, callIdPrefix);\n\t\t\t\tif (projection.callCount === 0) {\n\t\t\t\t\tif (projection.failure) {\n\t\t\t\t\t\tawait notifyTextToolProtocolParse(options, {\n\t\t\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\t\t\tmodel: model.id,\n\t\t\t\t\t\t\tvariant: protocolOptions.variant ?? \"tool-tag\",\n\t\t\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\t\t\tcallCount: 0,\n\t\t\t\t\t\t\ttextLength: projection.textLength,\n\t\t\t\t\t\t\treason: projection.failure,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\twrapped.push({ ...event, message: projection.message });\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tawait notifyTextToolProtocolParse(options, {\n\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\tmodel: model.id,\n\t\t\t\t\tvariant: protocolOptions.variant ?? \"tool-tag\",\n\t\t\t\t\tstatus: \"parsed\",\n\t\t\t\t\tcallCount: projection.callCount,\n\t\t\t\t\ttextLength: projection.textLength,\n\t\t\t\t});\n\t\t\t\twrapped.push({ type: \"done\", reason: \"toolUse\", message: projection.message });\n\t\t\t}\n\t\t} finally {\n\t\t\tcontrol?.cleanup();\n\t\t}\n\t})();\n\treturn wrapped;\n}\n\nfunction startTextToolProtocolStream<TOptions extends StreamOptions>(\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions: TOptions | undefined,\n\tstartProviderStream: (\n\t\tproviderContext: Context,\n\t\tproviderOptions: TOptions | undefined,\n\t) => AssistantMessageEventStream,\n): AssistantMessageEventStream {\n\tconst protocolOptions = normalizeTextToolProtocolOptions(options?.textToolCallProtocol);\n\tif (!protocolOptions || !context.tools?.length) return startProviderStream(context, options);\n\tconst abortController = new AbortController();\n\tconst combined = combineAbortSignals([options?.signal, abortController.signal]);\n\tconst providerOptions = { ...options, signal: combined.signal } as TOptions;\n\tconst protocolContext = withTextToolProtocolContext(context, providerOptions);\n\treturn withTextToolProtocolResult(\n\t\tstartProviderStream(protocolContext, providerOptions),\n\t\tmodel,\n\t\tcontext,\n\t\tproviderOptions,\n\t\t{ abortController, cleanup: combined.cleanup },\n\t);\n}\n\nfunction resolveApiProvider(api: Api) {\n\tconst provider = getApiProvider(api);\n\tif (!provider) {\n\t\tthrow new Error(`No API provider registered for api: ${api}`);\n\t}\n\treturn provider;\n}\n\nexport function stream<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: ProviderStreamOptions,\n): AssistantMessageEventStream {\n\tconst provider = resolveApiProvider(model.api);\n\tconst resolvedOptions = withEnvAuth(model, options);\n\treturn startTextToolProtocolStream(model, context, resolvedOptions, (providerContext, providerOptions) =>\n\t\tprovider.stream(model, providerContext, providerOptions),\n\t);\n}\n\nexport async function complete<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: ProviderStreamOptions,\n): Promise<AssistantMessage> {\n\tconst s = stream(model, context, options);\n\treturn s.result();\n}\n\nexport function streamSimple<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream {\n\tconst provider = resolveApiProvider(model.api);\n\tconst resolvedOptions = withEnvAuth(model, options);\n\treturn startTextToolProtocolStream(model, context, resolvedOptions, (providerContext, providerOptions) =>\n\t\tprovider.streamSimple(model, providerContext, providerOptions),\n\t);\n}\n\nexport async function completeSimple<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): Promise<AssistantMessage> {\n\tconst s = streamSimple(model, context, options);\n\treturn s.result();\n}\n"]}
1
+ {"version":3,"file":"stream.js","sourceRoot":"","sources":["../src/stream.ts"],"names":[],"mappings":"AAAA,OAAO,kCAAkC,CAAC;AAE1C,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAYpE,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,EAAE,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AACtE,OAAO,EACN,8BAA8B,EAC9B,gCAAgC,EAChC,kBAAkB,GAClB,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,sBAAsB,EAAE,MAAM,kDAAkD,CAAC;AAE1F,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD,IAAI,6BAA6B,GAAG,CAAC,CAAC;AAEtC,kGAAkG;AAClG,iGAAiG;AACjG,qGAAqG;AACrG,MAAM,uCAAuC,GAAG,GAAG,CAAC;AAEpD,SAAS,gCAAgC;IACxC,6BAA6B;QAC5B,6BAA6B,IAAI,MAAM,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,6BAA6B,GAAG,CAAC,CAAC;IAClG,OAAO,aAAa,6BAA6B,EAAE,CAAC;AACrD,CA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AAC,CAAC;IAC/C,MAAM,eAAe,GAAG,WAAW,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IACpD,OAAO,2BAA2B,CAAC,KAAK,EAAE,OAAO,EAAE,eAAe,EAAE,CAAC,eAAe,EAAE,eAAe,EAAE,EAAE,CACxG,QAAQ,CAAC,MAAM,CAAC,KAAK,EAAE,eAAe,EAAE,eAAe,CAAC,CACxD,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,QAAQ,CAC7B,KAAkB,EAClB,OAAgB,EAChB,OAA+B;IAE/B,MAAM,CAAC,GAAG,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAC1C,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC;AACnB,CAAC;AAED,MAAM,UAAU,YAAY,CAC3B,KAAkB,EAClB,OAAgB,EAChB,OAA6B;IAE7B,MAAM,QAAQ,GAAG,kBAAkB,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC/C,MAAM,eAAe,GAAG,WAAW,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IACpD,OAAO,2BAA2B,CAAC,KAAK,EAAE,OAAO,EAAE,eAAe,EAAE,CAAC,eAAe,EAAE,eAAe,EAAE,EAAE,CACxG,QAAQ,CAAC,YAAY,CAAC,KAAK,EAAE,eAAe,EAAE,eAAe,CAAC,CAC9D,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,cAAc,CACnC,KAAkB,EAClB,OAAgB,EAChB,OAA6B;IAE7B,MAAM,CAAC,GAAG,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAChD,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC;AACnB,CAAC","sourcesContent":["import \"./providers/register-builtins.ts\";\n\nimport { getApiProvider } from \"./api-registry.ts\";\nimport { getEnvApiKey, getEnvAuthHeaders } from \"./env-api-keys.ts\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tContext,\n\tModel,\n\tProviderStreamOptions,\n\tSimpleStreamOptions,\n\tStreamOptions,\n\tTextToolProtocolParseEvent,\n} from \"./types.ts\";\nimport { combineAbortSignals } from \"./utils/abort-signals.ts\";\nimport { AssistantMessageEventStream } from \"./utils/event-stream.ts\";\nimport {\n\tgenerateTextToolProtocolPrimer,\n\tnormalizeTextToolProtocolOptions,\n\tparseTextToolCalls,\n} from \"./utils/tool-repair/text-protocol.ts\";\nimport { TextProtocolLiveFilter } from \"./utils/tool-repair/text-protocol-live-filter.ts\";\n\nexport { getEnvApiKey } from \"./env-api-keys.ts\";\n\nlet textToolProtocolBatchSequence = 0;\n\n// Once a complete call exists, a short bounded suffix preserves adjacent parallel envelopes while\n// preventing a small model from spending its remaining output budget on unusable trailing prose.\n// Envelope bodies themselves are never counted, so large write/edit arguments remain unbounded here.\nconst TEXT_TOOL_PROTOCOL_TRAILING_PROSE_LIMIT = 128;\n\nfunction nextTextToolProtocolCallIdPrefix(): string {\n\ttextToolProtocolBatchSequence =\n\t\ttextToolProtocolBatchSequence >= Number.MAX_SAFE_INTEGER ? 1 : textToolProtocolBatchSequence + 1;\n\treturn `text-tool-${textToolProtocolBatchSequence}`;\n}\n\nfunction hasExplicitApiKey(apiKey: string | undefined): apiKey is string {\n\treturn typeof apiKey === \"string\" && apiKey.trim().length > 0;\n}\n\nfunction hasAuthorizationHeader(headers: Record<string, string> | undefined): boolean {\n\treturn Object.entries(headers ?? {}).some(\n\t\t([name, value]) => name.toLowerCase() === \"authorization\" && value.trim().length > 0,\n\t);\n}\n\nfunction withEnvAuth<TOptions extends StreamOptions>(\n\tmodel: Model<Api>,\n\toptions: TOptions | undefined,\n): TOptions | undefined {\n\tif (hasExplicitApiKey(options?.apiKey)) return options;\n\tif (hasAuthorizationHeader(options?.headers)) return options;\n\tconst envHeaders = getEnvAuthHeaders(model.provider);\n\tif (envHeaders) return { ...options, headers: { ...envHeaders, ...options?.headers } } as TOptions;\n\tconst apiKey = getEnvApiKey(model.provider);\n\tif (!apiKey) return options;\n\treturn { ...options, apiKey } as TOptions;\n}\n\nfunction withTextToolProtocolContext(context: Context, options: StreamOptions | undefined): Context {\n\tconst protocolOptions = normalizeTextToolProtocolOptions(options?.textToolCallProtocol);\n\tif (!protocolOptions || !context.tools?.length) return context;\n\tconst primer = generateTextToolProtocolPrimer(context.tools, protocolOptions);\n\tif (!primer) return context;\n\tconst { tools: _tools, ...providerContext } = context;\n\tconst messages = context.messages.length\n\t\t? [\n\t\t\t\t{\n\t\t\t\t\trole: \"user\" as const,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\t\ttext: \"Apply system tool protocol; never answer this message.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\ttimestamp: 0,\n\t\t\t\t},\n\t\t\t\t...context.messages,\n\t\t\t]\n\t\t: context.messages;\n\treturn {\n\t\t...providerContext,\n\t\tsystemPrompt: context.systemPrompt ? `${context.systemPrompt}\\n\\n${primer}` : primer,\n\t\tmessages,\n\t};\n}\n\n/**\n * Immutable provider-input materialization. `context` is the exact Context object passed to the\n * provider transport; `sourceContext` retains native tool definitions only for response parsing.\n */\nexport interface MaterializedProviderRequest {\n\tcontext: Context;\n\tsourceContext: Context;\n\tusesTextToolProtocol: boolean;\n}\n\n/**\n * Resolve provider-visible context once, including the text-only tool primer and synthetic guard\n * message. Callers may budget/admit `result.context`, then send that same object through\n * {@link startMaterializedProviderStream} without re-rendering it.\n */\nexport function materializeProviderRequest(\n\tcontext: Context,\n\toptions: StreamOptions | undefined,\n): MaterializedProviderRequest {\n\tconst protocolOptions = normalizeTextToolProtocolOptions(options?.textToolCallProtocol);\n\tconst usesTextToolProtocol = protocolOptions !== undefined && Boolean(context.tools?.length);\n\treturn {\n\t\tcontext: usesTextToolProtocol ? withTextToolProtocolContext(context, options) : context,\n\t\tsourceContext: context,\n\t\tusesTextToolProtocol,\n\t};\n}\n\nasync function notifyTextToolProtocolParse(\n\toptions: StreamOptions | undefined,\n\tevent: TextToolProtocolParseEvent,\n): Promise<void> {\n\ttry {\n\t\tawait options?.onTextToolProtocolParse?.(event);\n\t} catch {\n\t\t// Parse telemetry must not change provider stream semantics.\n\t}\n}\n\n// Rewrites any text or thinking block whose revealed prose is still behind its true streamed\n// content so a forwarded event's `partial` snapshot never exposes held-back envelope markup. Some\n// OpenAI-compatible local servers classify the model's entire phone envelope as reasoning.\nfunction redactHeldProtocolContent(\n\tpartial: AssistantMessage,\n\trevealedContent: ReadonlyMap<number, string>,\n): AssistantMessage {\n\tif (revealedContent.size === 0) return partial;\n\tlet changed = false;\n\tconst content = partial.content.map((block, index) => {\n\t\tconst revealed = revealedContent.get(index);\n\t\tif (revealed === undefined) return block;\n\t\tif (block.type === \"text\" && block.text !== revealed) {\n\t\t\tchanged = true;\n\t\t\treturn { ...block, text: revealed };\n\t\t}\n\t\tif (block.type !== \"thinking\" || block.thinking === revealed) return block;\n\t\tchanged = true;\n\t\treturn { ...block, thinking: revealed };\n\t});\n\treturn changed ? { ...partial, content } : partial;\n}\n\n// Forwards one non-\"done\" stream event, holding back streamed text that falls inside (or\n// might still grow into) a text-protocol envelope so raw markup like \"<pi:call\" never reaches\n// a live consumer. Prose outside envelopes is forwarded as soon as it is provably safe; the\n// \"done\" event swap remains the sole authority for final content.\nfunction forwardTextProtocolStreamEvent(\n\twrapped: AssistantMessageEventStream,\n\tevent: Exclude<AssistantMessageEvent, { type: \"done\" }>,\n\trevealedContent: Map<number, string>,\n\tliveFilters: Map<number, TextProtocolLiveFilter>,\n): void {\n\tif (event.type === \"error\") {\n\t\twrapped.push(event);\n\t\treturn;\n\t}\n\tif (event.type === \"text_start\" || event.type === \"thinking_start\") {\n\t\trevealedContent.set(event.contentIndex, \"\");\n\t\tliveFilters.set(event.contentIndex, new TextProtocolLiveFilter());\n\t\twrapped.push({ ...event, partial: redactHeldProtocolContent(event.partial, revealedContent) });\n\t\treturn;\n\t}\n\tif (event.type === \"text_delta\" || event.type === \"thinking_delta\") {\n\t\tconst flushed = revealedContent.get(event.contentIndex) ?? \"\";\n\t\tconst filter = liveFilters.get(event.contentIndex) ?? new TextProtocolLiveFilter();\n\t\tliveFilters.set(event.contentIndex, filter);\n\t\tconst visible = filter.advance(event.delta);\n\t\tif (visible.length <= flushed.length) return; // held: possibly-envelope text never streams live\n\t\trevealedContent.set(event.contentIndex, visible);\n\t\twrapped.push({\n\t\t\t...event,\n\t\t\tdelta: visible.slice(flushed.length),\n\t\t\tpartial: redactHeldProtocolContent(event.partial, revealedContent),\n\t\t});\n\t\treturn;\n\t}\n\tif (event.type === \"text_end\" || event.type === \"thinking_end\") {\n\t\tconst flushed = revealedContent.get(event.contentIndex) ?? \"\";\n\t\tconst filter = liveFilters.get(event.contentIndex) ?? new TextProtocolLiveFilter();\n\t\tliveFilters.set(event.contentIndex, filter);\n\t\tconst visible = filter.finish(event.content);\n\t\tif (visible.length > flushed.length) {\n\t\t\t// Catch up any newly-provable-safe tail (e.g. a suspected opener prefix that never\n\t\t\t// completed) so the deltas actually forwarded still sum to what text_end reports.\n\t\t\trevealedContent.set(event.contentIndex, visible);\n\t\t\twrapped.push(\n\t\t\t\tevent.type === \"text_end\"\n\t\t\t\t\t? {\n\t\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\t\tcontentIndex: event.contentIndex,\n\t\t\t\t\t\t\tdelta: visible.slice(flushed.length),\n\t\t\t\t\t\t\tpartial: redactHeldProtocolContent(event.partial, revealedContent),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\t\tcontentIndex: event.contentIndex,\n\t\t\t\t\t\t\tdelta: visible.slice(flushed.length),\n\t\t\t\t\t\t\tpartial: redactHeldProtocolContent(event.partial, revealedContent),\n\t\t\t\t\t\t},\n\t\t\t);\n\t\t}\n\t\tconst finalVisible = revealedContent.get(event.contentIndex) ?? visible;\n\t\twrapped.push({\n\t\t\t...event,\n\t\t\tcontent: finalVisible,\n\t\t\tpartial: redactHeldProtocolContent(event.partial, revealedContent),\n\t\t});\n\t\treturn;\n\t}\n\twrapped.push({ ...event, partial: redactHeldProtocolContent(event.partial, revealedContent) });\n}\n\ninterface TextToolProtocolMessageProjection {\n\tmessage: AssistantMessage;\n\tcallCount: number;\n\ttextLength: number;\n\tfailure?: TextToolProtocolParseEvent[\"reason\"];\n\tprotocolAttempted: boolean;\n}\n\nfunction projectTextToolProtocolMessage(\n\tmessage: AssistantMessage,\n\tmodel: Model<Api>,\n\ttools: readonly NonNullable<Context[\"tools\"]>[number][],\n\tcallIdPrefix: string,\n): TextToolProtocolMessageProjection {\n\tconst content: AssistantMessage[\"content\"] = [];\n\tlet callCount = 0;\n\tlet textLength = 0;\n\tlet failure: TextToolProtocolParseEvent[\"reason\"] | undefined;\n\tlet protocolAttempted = false;\n\tfor (const block of message.content) {\n\t\tif (block.type !== \"text\" && (block.type !== \"thinking\" || block.redacted)) {\n\t\t\tcontent.push(block);\n\t\t\tcontinue;\n\t\t}\n\t\tconst protocolText = block.type === \"text\" ? block.text : block.thinking;\n\t\ttextLength += protocolText.length;\n\t\tconst parsed = parseTextToolCalls(protocolText, tools, {\n\t\t\tcallIdPrefix,\n\t\t\tcallIndexOffset: callCount,\n\t\t});\n\t\tprotocolAttempted ||= parsed.attempted;\n\t\tif (parsed.calls.length === 0) {\n\t\t\tif (parsed.failure) failure ??= parsed.failure;\n\t\t\tcontent.push(block);\n\t\t\tcontinue;\n\t\t}\n\t\tcallCount += parsed.calls.length;\n\t\tif (parsed.text) {\n\t\t\tcontent.push(block.type === \"text\" ? { ...block, text: parsed.text } : { ...block, thinking: parsed.text });\n\t\t}\n\t\tcontent.push(...parsed.calls);\n\t}\n\tif (callCount > 0) {\n\t\treturn {\n\t\t\tmessage: { ...message, content, stopReason: \"toolUse\" },\n\t\t\tcallCount,\n\t\t\ttextLength,\n\t\t\tfailure,\n\t\t\tprotocolAttempted,\n\t\t};\n\t}\n\tconst hasVisibleText = message.content.some((block) => block.type === \"text\" && block.text.trim().length > 0);\n\tconst promoteThinking =\n\t\tmodel.reasoning === false &&\n\t\t!protocolAttempted &&\n\t\t!hasVisibleText &&\n\t\tmessage.content.some((block) => block.type === \"thinking\" && !block.redacted);\n\treturn {\n\t\tmessage: promoteThinking\n\t\t\t? {\n\t\t\t\t\t...message,\n\t\t\t\t\tcontent: message.content.flatMap((block) => {\n\t\t\t\t\t\tif (block.type === \"thinking\" && !block.redacted) {\n\t\t\t\t\t\t\treturn [{ type: \"text\" as const, text: block.thinking }];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (block.type === \"text\" && block.text.length === 0) return [];\n\t\t\t\t\t\treturn [block];\n\t\t\t\t\t}),\n\t\t\t\t}\n\t\t\t: message,\n\t\tcallCount,\n\t\ttextLength,\n\t\tfailure,\n\t\tprotocolAttempted,\n\t};\n}\n\ninterface TextToolProtocolStreamControl {\n\tabortController: AbortController;\n\tcleanup(): void;\n}\n\nfunction withTextToolProtocolResult(\n\tstream: AssistantMessageEventStream,\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions: StreamOptions | undefined,\n\tcontrol?: TextToolProtocolStreamControl,\n): AssistantMessageEventStream {\n\tconst protocolOptions = normalizeTextToolProtocolOptions(options?.textToolCallProtocol);\n\tconst tools = context.tools ?? [];\n\tif (!protocolOptions || tools.length === 0) return stream;\n\tconst wrapped = new AssistantMessageEventStream();\n\tconst callIdPrefix = nextTextToolProtocolCallIdPrefix();\n\tvoid (async () => {\n\t\tconst revealedContent = new Map<number, string>();\n\t\tconst liveFilters = new Map<number, TextProtocolLiveFilter>();\n\t\tlet completedEnvelopeCount = 0;\n\t\tlet trailingProseLength = 0;\n\t\tlet completedProjection: TextToolProtocolMessageProjection | undefined;\n\t\ttry {\n\t\t\tfor await (const event of stream) {\n\t\t\t\tif (event.type !== \"done\") {\n\t\t\t\t\tif (event.type === \"text_delta\" || event.type === \"thinking_delta\") {\n\t\t\t\t\t\tif (completedProjection) trailingProseLength += event.delta.length;\n\t\t\t\t\t}\n\t\t\t\t\tforwardTextProtocolStreamEvent(wrapped, event, revealedContent, liveFilters);\n\t\t\t\t\tconst observedEnvelopeCount = [...liveFilters.values()].reduce(\n\t\t\t\t\t\t(total, filter) => total + filter.completedEnvelopeCount,\n\t\t\t\t\t\t0,\n\t\t\t\t\t);\n\t\t\t\t\tif (observedEnvelopeCount > completedEnvelopeCount && \"partial\" in event) {\n\t\t\t\t\t\tcompletedEnvelopeCount = observedEnvelopeCount;\n\t\t\t\t\t\tconst projection = projectTextToolProtocolMessage(event.partial, model, tools, callIdPrefix);\n\t\t\t\t\t\tif (projection.callCount > 0) {\n\t\t\t\t\t\t\tcompletedProjection = projection;\n\t\t\t\t\t\t\ttrailingProseLength = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconst holdingPotentialEnvelope = [...liveFilters.values()].some(\n\t\t\t\t\t\t(filter) => filter.holdingPotentialEnvelope,\n\t\t\t\t\t);\n\t\t\t\t\tif (\n\t\t\t\t\t\tcompletedProjection &&\n\t\t\t\t\t\ttrailingProseLength > TEXT_TOOL_PROTOCOL_TRAILING_PROSE_LIMIT &&\n\t\t\t\t\t\t!holdingPotentialEnvelope &&\n\t\t\t\t\t\tcontrol\n\t\t\t\t\t) {\n\t\t\t\t\t\tcontrol.abortController.abort(\"text-tool-protocol-call-complete\");\n\t\t\t\t\t\tawait notifyTextToolProtocolParse(options, {\n\t\t\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\t\t\tmodel: model.id,\n\t\t\t\t\t\t\tvariant: protocolOptions.variant ?? \"tool-tag\",\n\t\t\t\t\t\t\tstatus: \"parsed\",\n\t\t\t\t\t\t\tcallCount: completedProjection.callCount,\n\t\t\t\t\t\t\ttextLength: completedProjection.textLength,\n\t\t\t\t\t\t});\n\t\t\t\t\t\twrapped.push({ type: \"done\", reason: \"toolUse\", message: completedProjection.message });\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst projection = projectTextToolProtocolMessage(event.message, model, tools, callIdPrefix);\n\t\t\t\tif (projection.callCount === 0) {\n\t\t\t\t\tif (projection.failure) {\n\t\t\t\t\t\tawait notifyTextToolProtocolParse(options, {\n\t\t\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\t\t\tmodel: model.id,\n\t\t\t\t\t\t\tvariant: protocolOptions.variant ?? \"tool-tag\",\n\t\t\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\t\t\tcallCount: 0,\n\t\t\t\t\t\t\ttextLength: projection.textLength,\n\t\t\t\t\t\t\treason: projection.failure,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\twrapped.push({ ...event, message: projection.message });\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tawait notifyTextToolProtocolParse(options, {\n\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\tmodel: model.id,\n\t\t\t\t\tvariant: protocolOptions.variant ?? \"tool-tag\",\n\t\t\t\t\tstatus: \"parsed\",\n\t\t\t\t\tcallCount: projection.callCount,\n\t\t\t\t\ttextLength: projection.textLength,\n\t\t\t\t});\n\t\t\t\twrapped.push({ type: \"done\", reason: \"toolUse\", message: projection.message });\n\t\t\t}\n\t\t} finally {\n\t\t\tcontrol?.cleanup();\n\t\t}\n\t})();\n\treturn wrapped;\n}\n\nfunction startTextToolProtocolStream<TOptions extends StreamOptions>(\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions: TOptions | undefined,\n\tstartProviderStream: (\n\t\tproviderContext: Context,\n\t\tproviderOptions: TOptions | undefined,\n\t) => AssistantMessageEventStream,\n): AssistantMessageEventStream {\n\tconst request = materializeProviderRequest(context, options);\n\tif (!request.usesTextToolProtocol) return startProviderStream(request.context, options);\n\tconst abortController = new AbortController();\n\tconst combined = combineAbortSignals([options?.signal, abortController.signal]);\n\tconst providerOptions = { ...options, signal: combined.signal } as TOptions;\n\treturn withTextToolProtocolResult(\n\t\tstartProviderStream(request.context, providerOptions),\n\t\tmodel,\n\t\trequest.sourceContext,\n\t\tproviderOptions,\n\t\t{ abortController, cleanup: combined.cleanup },\n\t);\n}\n\n/**\n * Send one already-admitted materialization. Its provider context has no native tool surface, so a\n * nested public stream cannot render the primer again. Preserve the protocol option for provider\n * history serialization; response parsing remains owned here.\n */\nexport async function startMaterializedProviderStream<TOptions extends StreamOptions>(\n\tmodel: Model<Api>,\n\trequest: MaterializedProviderRequest,\n\toptions: TOptions | undefined,\n\tstartProviderStream: (\n\t\tproviderContext: Context,\n\t\tproviderOptions: TOptions | undefined,\n\t) => AssistantMessageEventStream | Promise<AssistantMessageEventStream>,\n): Promise<AssistantMessageEventStream> {\n\tif (!request.usesTextToolProtocol) return await startProviderStream(request.context, options);\n\n\tconst abortController = new AbortController();\n\tconst combined = combineAbortSignals([options?.signal, abortController.signal]);\n\tconst providerOptions = { ...options, signal: combined.signal } as TOptions;\n\ttry {\n\t\tconst stream = await startProviderStream(request.context, providerOptions);\n\t\treturn withTextToolProtocolResult(stream, model, request.sourceContext, options, {\n\t\t\tabortController,\n\t\t\tcleanup: combined.cleanup,\n\t\t});\n\t} catch (error) {\n\t\tcombined.cleanup();\n\t\tthrow error;\n\t}\n}\n\nfunction resolveApiProvider(api: Api) {\n\tconst provider = getApiProvider(api);\n\tif (!provider) {\n\t\tthrow new Error(`No API provider registered for api: ${api}`);\n\t}\n\treturn provider;\n}\n\nexport function stream<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: ProviderStreamOptions,\n): AssistantMessageEventStream {\n\tconst provider = resolveApiProvider(model.api);\n\tconst resolvedOptions = withEnvAuth(model, options);\n\treturn startTextToolProtocolStream(model, context, resolvedOptions, (providerContext, providerOptions) =>\n\t\tprovider.stream(model, providerContext, providerOptions),\n\t);\n}\n\nexport async function complete<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: ProviderStreamOptions,\n): Promise<AssistantMessage> {\n\tconst s = stream(model, context, options);\n\treturn s.result();\n}\n\nexport function streamSimple<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream {\n\tconst provider = resolveApiProvider(model.api);\n\tconst resolvedOptions = withEnvAuth(model, options);\n\treturn startTextToolProtocolStream(model, context, resolvedOptions, (providerContext, providerOptions) =>\n\t\tprovider.streamSimple(model, providerContext, providerOptions),\n\t);\n}\n\nexport async function completeSimple<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): Promise<AssistantMessage> {\n\tconst s = streamSimple(model, context, options);\n\treturn s.result();\n}\n"]}
@@ -15,51 +15,51 @@ export type ToolFailurePhase = "validation" | "policy" | "preflight" | "executio
15
15
  export declare const REPEATED_SUCCESSFUL_TOOL_CALL_FAILURE: {
16
16
  readonly failureCode: "repeated_successful_call";
17
17
  readonly diagnostic: "The identical phone tool call already succeeded and was not executed again.";
18
- readonly guidance: "Use the previous successful result and continue; it is quoted in the diagnostic. Answer the user if the task is complete, or call a different required tool. Do not retry the same call unchanged.";
18
+ readonly guidance: "Use prior successful result; continue. Task complete: answer user. Otherwise call different required tool. Never retry unchanged.";
19
19
  };
20
20
  export declare const TOOL_EXECUTION_ERROR_CATALOGUE: readonly [{
21
21
  readonly name: "provisioningFailed";
22
22
  readonly phase: "provisioning";
23
23
  readonly failureCode: "provisioning_failed";
24
24
  readonly retainDiagnostic: true;
25
- readonly guidance: "Provisioning failed; use the exact diagnostic, repair that cause, and retry only after the environment changes.";
25
+ readonly guidance: "Provisioning failed. Use exact diagnostic, fix cause; retry only after environment changes.";
26
26
  readonly matches: (message: string) => boolean;
27
27
  }, {
28
28
  readonly name: "commandNotFound";
29
29
  readonly phase: "provisioning";
30
- readonly guidance: "Command was not found; check the command name or available tools before retrying.";
30
+ readonly guidance: "Command not found. Check exact name/available tools before retry.";
31
31
  readonly matches: (message: string) => boolean;
32
32
  }, {
33
33
  readonly name: "bashNoOutput";
34
34
  readonly phase: "execution";
35
- readonly guidance: "The command exited with an error but returned no output; verify the command syntax and check its specific documentation before retrying.";
35
+ readonly guidance: "Command failed without output. Verify syntax, exact command documentation before retry.";
36
36
  readonly matches: (message: string) => boolean;
37
37
  }, {
38
38
  readonly name: "bashPosixNotSupported";
39
39
  readonly phase: "execution";
40
- readonly guidance: "POSIX shell scripts (.sh) are not supported on this Windows host; use a PowerShell equivalent or invoke the executable directly.";
40
+ readonly guidance: "Windows host rejects POSIX .sh scripts. Use PowerShell equivalent or invoke executable directly.";
41
41
  readonly matches: (message: string) => boolean;
42
42
  }, {
43
43
  readonly name: "bashNestedShell";
44
44
  readonly phase: "execution";
45
- readonly guidance: "Do not wrap commands in powershell.exe or pwsh. Invoke the .ps1 script or command directly.";
45
+ readonly guidance: "Never wrap command in powershell.exe/pwsh. Invoke .ps1 or command directly.";
46
46
  readonly matches: (message: string) => boolean;
47
47
  }, {
48
48
  readonly name: "bashMissingCommandWord";
49
49
  readonly phase: "execution";
50
- readonly guidance: "The shell command was malformed (missing command word). Check for empty pipeline elements or incorrect string quoting before retrying.";
50
+ readonly guidance: "Missing shell command word. Fix empty pipeline element or string quoting before retry.";
51
51
  readonly matches: (message: string) => boolean;
52
52
  }, {
53
53
  readonly name: "bashEmptyRedirectTarget";
54
54
  readonly phase: "execution";
55
- readonly guidance: "The shell redirect target was empty; provide a valid file path for the redirect before retrying.";
55
+ readonly guidance: "Empty redirect target. Supply valid file path before retry.";
56
56
  readonly matches: (message: string) => boolean;
57
57
  }, {
58
58
  readonly name: "encodingCorruption";
59
59
  readonly phase: "execution";
60
60
  readonly failureCode: "encoding_corruption";
61
61
  readonly attemptMemory: "discard";
62
- readonly guidance: "Change approach: exact UTF-8 text replacement is unsafe for this file. Use an encoding-aware or byte-safe tool/workflow instead; do not replay the text edit.";
62
+ readonly guidance: "Change approach: exact UTF-8 replacement unsafe. Use encoding-aware/byte-safe tool; never replay text edit.";
63
63
  readonly matches: (message: string) => boolean;
64
64
  }, {
65
65
  readonly name: "repeatedSuccessfulCall";
@@ -67,7 +67,7 @@ export declare const TOOL_EXECUTION_ERROR_CATALOGUE: readonly [{
67
67
  readonly failureCode: "repeated_successful_call";
68
68
  readonly attemptMemory: "discard";
69
69
  readonly retainDiagnostic: true;
70
- readonly guidance: "Use the previous successful result and continue; it is quoted in the diagnostic. Answer the user if the task is complete, or call a different required tool. Do not retry the same call unchanged.";
70
+ readonly guidance: "Use prior successful result; continue. Task complete: answer user. Otherwise call different required tool. Never retry unchanged.";
71
71
  readonly matches: (message: string) => boolean;
72
72
  }, {
73
73
  readonly name: "fileMutationRetarget";
@@ -75,64 +75,64 @@ export declare const TOOL_EXECUTION_ERROR_CATALOGUE: readonly [{
75
75
  readonly failureCode: "mutation_retarget_required";
76
76
  readonly attemptMemory: "discard";
77
77
  readonly retainDiagnostic: true;
78
- readonly guidance: "The mutation payload is already retained by the harness. Choose only the corrected target path and reuse the exact payloadRef from the diagnostic; do not regenerate content or edits.";
78
+ readonly guidance: "Harness retained mutation. Choose corrected target path, reuse exact diagnostic payloadRef; never regenerate content/edits.";
79
79
  readonly matches: (message: string) => boolean;
80
80
  }, {
81
81
  readonly name: "fileNotFound";
82
82
  readonly phase: "execution";
83
83
  readonly failureCode: "file_not_found";
84
- readonly guidance: "Path was not found; list the parent directory or re-read the path before retrying.";
84
+ readonly guidance: "Path not found. List parent directory or re-read path before retry.";
85
85
  readonly matches: (message: string) => boolean;
86
86
  }, {
87
87
  readonly name: "editOldTextNotFound";
88
88
  readonly phase: "execution";
89
89
  readonly failureCode: "edit_old_text_not_found";
90
- readonly guidance: "Re-read the target file and use the exact current text before retrying.";
90
+ readonly guidance: "Re-read target; use exact current text before retry.";
91
91
  readonly matches: (message: string) => boolean;
92
92
  }, {
93
93
  readonly name: "pathOutsideCwd";
94
94
  readonly phase: "policy";
95
- readonly guidance: "Choose a path inside the current working directory, or ask before changing scope.";
95
+ readonly guidance: "Choose path inside current working directory; ask before scope change.";
96
96
  readonly matches: (message: string) => boolean;
97
97
  }, {
98
98
  readonly name: "permissionDenied";
99
99
  readonly phase: "policy";
100
100
  readonly failureCode: "permission_denied";
101
101
  readonly retainDiagnostic: true;
102
- readonly guidance: "Access was denied; verify the target path and current authority, then request or change permissions before retrying.";
102
+ readonly guidance: "Access denied. Verify target/current authority; obtain permissions before retry.";
103
103
  readonly matches: (message: string) => boolean;
104
104
  }, {
105
105
  readonly name: "invalidOption";
106
106
  readonly phase: "execution";
107
107
  readonly failureCode: "invalid_option";
108
108
  readonly retainDiagnostic: true;
109
- readonly guidance: "Option rejected; re-read command help and remove or replace it before retrying.";
109
+ readonly guidance: "Option rejected. Read command help; remove/replace option before retry.";
110
110
  readonly matches: (message: string) => boolean;
111
111
  }, {
112
112
  readonly name: "invalidPattern";
113
113
  readonly phase: "execution";
114
114
  readonly failureCode: "invalid_pattern";
115
115
  readonly retainDiagnostic: true;
116
- readonly guidance: "The search pattern was invalid; simplify it or correct its regex/glob escaping before retrying.";
116
+ readonly guidance: "Invalid search pattern. Simplify or fix regex/glob escaping before retry.";
117
117
  readonly matches: (message: string) => boolean;
118
118
  }, {
119
119
  readonly name: "outputLimit";
120
120
  readonly phase: "execution";
121
121
  readonly failureCode: "output_limit";
122
- readonly guidance: "Output exceeded its bound; narrow the scope, page the request, or use the retained artifact before retrying.";
122
+ readonly guidance: "Output exceeded bound. Narrow scope, page request, or use retained artifact before retry.";
123
123
  readonly matches: (message: string) => boolean;
124
124
  }, {
125
125
  readonly name: "timedOut";
126
126
  readonly phase: "timeout";
127
127
  readonly failureCode: "timeout";
128
128
  readonly unchangedRetryLimit: 1;
129
- readonly guidance: "The operation timed out; narrow or split the work, then retry once only when repeating it is safe and still required.";
129
+ readonly guidance: "Operation timed out. Narrow/split work; one unchanged retry only when safe, still required.";
130
130
  readonly matches: (message: string) => boolean;
131
131
  }, {
132
132
  readonly name: "cancelled";
133
133
  readonly phase: "cancelled";
134
134
  readonly failureCode: "cancelled";
135
- readonly guidance: "The operation was cancelled; retry only if it is still required and the cancellation condition has cleared.";
135
+ readonly guidance: "Operation cancelled. Retry only when still required, cancellation condition cleared.";
136
136
  readonly matches: (message: string) => boolean;
137
137
  }];
138
138
  export type ToolExecutionErrorClass = (typeof TOOL_EXECUTION_ERROR_CATALOGUE)[number]["name"];
@@ -1 +1 @@
1
- {"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../../src/utils/tool-repair/registry.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,sBAAsB,YAClC,kBAAkB,EAClB,oBAAoB,EACpB,iBAAiB,EACjB,2BAA2B,EAC3B,kBAAkB,EAClB,gBAAgB,EAChB,wBAAwB,EACxB,kBAAkB,EAClB,gBAAgB,EAChB,mBAAmB,EACnB,uBAAuB,EACvB,qBAAqB,EACrB,0BAA0B,EAC1B,qBAAqB,EACrB,mBAAmB,CACV,CAAC;AAEX,MAAM,MAAM,kBAAkB,GAAG,CAAC,OAAO,sBAAsB,CAAC,CAAC,MAAM,CAAC,CAAC;AACzE,MAAM,MAAM,yBAAyB,GAAG,kBAAkB,GAAG,OAAO,CAAC;AAErE,MAAM,WAAW,uBAAuB;IACvC,IAAI,EAAE,kBAAkB,CAAC;IACzB,YAAY,EAAE,MAAM,CAAC;IACrB,YAAY,EAAE,MAAM,CAAC;CACrB;AAED,eAAO,MAAM,oBAAoB,EAAE,SAAS,uBAAuB,EAgFzD,CAAC;AAIX,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,kBAAkB,GAAG,uBAAuB,CAI5F;AAED,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,kBAAkB,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAEnF;AAED,wBAAgB,4BAA4B,CAAC,IAAI,EAAE,kBAAkB,GAAG,MAAM,CAE7E;AAED,MAAM,MAAM,0BAA0B,GAAG,QAAQ,GAAG,SAAS,CAAC;AAC9D,MAAM,MA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