@caupulican/pi-ai 0.85.3 → 0.85.4

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.
Files changed (36) hide show
  1. package/dist/bedrock-provider.d.ts +1 -0
  2. package/dist/bedrock-provider.d.ts.map +1 -1
  3. package/dist/bedrock-provider.js +1 -0
  4. package/dist/bedrock-provider.js.map +1 -1
  5. package/dist/bedrock-scope.d.ts +35 -0
  6. package/dist/bedrock-scope.d.ts.map +1 -0
  7. package/dist/bedrock-scope.js +141 -0
  8. package/dist/bedrock-scope.js.map +1 -0
  9. package/dist/env-api-keys.d.ts.map +1 -1
  10. package/dist/env-api-keys.js +4 -1
  11. package/dist/env-api-keys.js.map +1 -1
  12. package/dist/image-models.generated.js +1 -1
  13. package/dist/image-models.generated.js.map +1 -1
  14. package/dist/models.generated.d.ts +217 -30
  15. package/dist/models.generated.d.ts.map +1 -1
  16. package/dist/models.generated.js +225 -80
  17. package/dist/models.generated.js.map +1 -1
  18. package/dist/stream.d.ts.map +1 -1
  19. package/dist/stream.js +193 -87
  20. package/dist/stream.js.map +1 -1
  21. package/dist/utils/tool-repair/registry.d.ts +21 -0
  22. package/dist/utils/tool-repair/registry.d.ts.map +1 -1
  23. package/dist/utils/tool-repair/registry.js +27 -0
  24. package/dist/utils/tool-repair/registry.js.map +1 -1
  25. package/dist/utils/tool-repair/text-protocol-history.d.ts.map +1 -1
  26. package/dist/utils/tool-repair/text-protocol-history.js +4 -1
  27. package/dist/utils/tool-repair/text-protocol-history.js.map +1 -1
  28. package/dist/utils/tool-repair/text-protocol-live-filter.d.ts +5 -0
  29. package/dist/utils/tool-repair/text-protocol-live-filter.d.ts.map +1 -1
  30. package/dist/utils/tool-repair/text-protocol-live-filter.js +11 -0
  31. package/dist/utils/tool-repair/text-protocol-live-filter.js.map +1 -1
  32. package/dist/utils/tool-repair/text-protocol.d.ts +5 -1
  33. package/dist/utils/tool-repair/text-protocol.d.ts.map +1 -1
  34. package/dist/utils/tool-repair/text-protocol.js +49 -27
  35. package/dist/utils/tool-repair/text-protocol.js.map +1 -1
  36. package/package.json +3 -1
@@ -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;AACpB,OAAO,EAAE,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AAQtE,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AA6OjD,wBAAgB,MAAM,CAAC,IAAI,SAAS,GAAG,EACtC,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,EAClB,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,qBAAqB,GAC7B,2BAA2B,CAU7B;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,CAU7B;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,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"}
package/dist/stream.js CHANGED
@@ -1,10 +1,21 @@
1
1
  import "./providers/register-builtins.js";
2
2
  import { getApiProvider } from "./api-registry.js";
3
3
  import { getEnvApiKey, getEnvAuthHeaders } from "./env-api-keys.js";
4
+ import { combineAbortSignals } from "./utils/abort-signals.js";
4
5
  import { AssistantMessageEventStream } from "./utils/event-stream.js";
5
6
  import { generateTextToolProtocolPrimer, normalizeTextToolProtocolOptions, parseTextToolCalls, } from "./utils/tool-repair/text-protocol.js";
6
7
  import { TextProtocolLiveFilter } from "./utils/tool-repair/text-protocol-live-filter.js";
7
8
  export { getEnvApiKey } from "./env-api-keys.js";
9
+ let textToolProtocolBatchSequence = 0;
10
+ // Once a complete call exists, a short bounded suffix preserves adjacent parallel envelopes while
11
+ // preventing a small model from spending its remaining output budget on unusable trailing prose.
12
+ // Envelope bodies themselves are never counted, so large write/edit arguments remain unbounded here.
13
+ const TEXT_TOOL_PROTOCOL_TRAILING_PROSE_LIMIT = 128;
14
+ function nextTextToolProtocolCallIdPrefix() {
15
+ textToolProtocolBatchSequence =
16
+ textToolProtocolBatchSequence >= Number.MAX_SAFE_INTEGER ? 1 : textToolProtocolBatchSequence + 1;
17
+ return `text-tool-${textToolProtocolBatchSequence}`;
18
+ }
8
19
  function hasExplicitApiKey(apiKey) {
9
20
  return typeof apiKey === "string" && apiKey.trim().length > 0;
10
21
  }
@@ -75,22 +86,25 @@ async function notifyTextToolProtocolParse(options, event) {
75
86
  // Parse telemetry must not change provider stream semantics.
76
87
  }
77
88
  }
78
- // Rewrites any text content block whose revealed prose is still behind its true streamed text
79
- // so a forwarded event's `partial` snapshot never exposes held-back or suppressed envelope
80
- // markup, even on events unrelated to the block being held (e.g. a later thinking/toolcall
81
- // event still carries the earlier text block in its `partial.content`).
82
- function redactHeldText(partial, revealedText) {
83
- if (revealedText.size === 0)
89
+ // Rewrites any text or thinking block whose revealed prose is still behind its true streamed
90
+ // content so a forwarded event's `partial` snapshot never exposes held-back envelope markup. Some
91
+ // OpenAI-compatible local servers classify the model's entire phone envelope as reasoning.
92
+ function redactHeldProtocolContent(partial, revealedContent) {
93
+ if (revealedContent.size === 0)
84
94
  return partial;
85
95
  let changed = false;
86
96
  const content = partial.content.map((block, index) => {
87
- if (block.type !== "text")
97
+ const revealed = revealedContent.get(index);
98
+ if (revealed === undefined)
88
99
  return block;
89
- const revealed = revealedText.get(index);
90
- if (revealed === undefined || block.text === revealed)
100
+ if (block.type === "text" && block.text !== revealed) {
101
+ changed = true;
102
+ return { ...block, text: revealed };
103
+ }
104
+ if (block.type !== "thinking" || block.thinking === revealed)
91
105
  return block;
92
106
  changed = true;
93
- return { ...block, text: revealed };
107
+ return { ...block, thinking: revealed };
94
108
  });
95
109
  return changed ? { ...partial, content } : partial;
96
110
  }
@@ -98,127 +112,221 @@ function redactHeldText(partial, revealedText) {
98
112
  // might still grow into) a text-protocol envelope so raw markup like "<pi:call" never reaches
99
113
  // a live consumer. Prose outside envelopes is forwarded as soon as it is provably safe; the
100
114
  // "done" event swap remains the sole authority for final content.
101
- function forwardTextProtocolStreamEvent(wrapped, event, revealedText, liveFilters) {
115
+ function forwardTextProtocolStreamEvent(wrapped, event, revealedContent, liveFilters) {
102
116
  if (event.type === "error") {
103
117
  wrapped.push(event);
104
118
  return;
105
119
  }
106
- if (event.type === "text_start") {
107
- revealedText.set(event.contentIndex, "");
120
+ if (event.type === "text_start" || event.type === "thinking_start") {
121
+ revealedContent.set(event.contentIndex, "");
108
122
  liveFilters.set(event.contentIndex, new TextProtocolLiveFilter());
109
- wrapped.push({ ...event, partial: redactHeldText(event.partial, revealedText) });
123
+ wrapped.push({ ...event, partial: redactHeldProtocolContent(event.partial, revealedContent) });
110
124
  return;
111
125
  }
112
- if (event.type === "text_delta") {
113
- const flushed = revealedText.get(event.contentIndex) ?? "";
126
+ if (event.type === "text_delta" || event.type === "thinking_delta") {
127
+ const flushed = revealedContent.get(event.contentIndex) ?? "";
114
128
  const filter = liveFilters.get(event.contentIndex) ?? new TextProtocolLiveFilter();
115
129
  liveFilters.set(event.contentIndex, filter);
116
130
  const visible = filter.advance(event.delta);
117
131
  if (visible.length <= flushed.length)
118
132
  return; // held: possibly-envelope text never streams live
119
- revealedText.set(event.contentIndex, visible);
133
+ revealedContent.set(event.contentIndex, visible);
120
134
  wrapped.push({
121
135
  ...event,
122
136
  delta: visible.slice(flushed.length),
123
- partial: redactHeldText(event.partial, revealedText),
137
+ partial: redactHeldProtocolContent(event.partial, revealedContent),
124
138
  });
125
139
  return;
126
140
  }
127
- if (event.type === "text_end") {
128
- const flushed = revealedText.get(event.contentIndex) ?? "";
141
+ if (event.type === "text_end" || event.type === "thinking_end") {
142
+ const flushed = revealedContent.get(event.contentIndex) ?? "";
129
143
  const filter = liveFilters.get(event.contentIndex) ?? new TextProtocolLiveFilter();
130
144
  liveFilters.set(event.contentIndex, filter);
131
145
  const visible = filter.finish(event.content);
132
146
  if (visible.length > flushed.length) {
133
147
  // Catch up any newly-provable-safe tail (e.g. a suspected opener prefix that never
134
148
  // completed) so the deltas actually forwarded still sum to what text_end reports.
135
- revealedText.set(event.contentIndex, visible);
136
- wrapped.push({
137
- type: "text_delta",
138
- contentIndex: event.contentIndex,
139
- delta: visible.slice(flushed.length),
140
- partial: redactHeldText(event.partial, revealedText),
141
- });
149
+ revealedContent.set(event.contentIndex, visible);
150
+ wrapped.push(event.type === "text_end"
151
+ ? {
152
+ type: "text_delta",
153
+ contentIndex: event.contentIndex,
154
+ delta: visible.slice(flushed.length),
155
+ partial: redactHeldProtocolContent(event.partial, revealedContent),
156
+ }
157
+ : {
158
+ type: "thinking_delta",
159
+ contentIndex: event.contentIndex,
160
+ delta: visible.slice(flushed.length),
161
+ partial: redactHeldProtocolContent(event.partial, revealedContent),
162
+ });
142
163
  }
143
- const finalVisible = revealedText.get(event.contentIndex) ?? visible;
164
+ const finalVisible = revealedContent.get(event.contentIndex) ?? visible;
144
165
  wrapped.push({
145
166
  ...event,
146
167
  content: finalVisible,
147
- partial: redactHeldText(event.partial, revealedText),
168
+ partial: redactHeldProtocolContent(event.partial, revealedContent),
148
169
  });
149
170
  return;
150
171
  }
151
- wrapped.push({ ...event, partial: redactHeldText(event.partial, revealedText) });
172
+ wrapped.push({ ...event, partial: redactHeldProtocolContent(event.partial, revealedContent) });
173
+ }
174
+ function projectTextToolProtocolMessage(message, model, tools, callIdPrefix) {
175
+ const content = [];
176
+ let callCount = 0;
177
+ let textLength = 0;
178
+ let failure;
179
+ let protocolAttempted = false;
180
+ for (const block of message.content) {
181
+ if (block.type !== "text" && (block.type !== "thinking" || block.redacted)) {
182
+ content.push(block);
183
+ continue;
184
+ }
185
+ const protocolText = block.type === "text" ? block.text : block.thinking;
186
+ textLength += protocolText.length;
187
+ const parsed = parseTextToolCalls(protocolText, tools, {
188
+ callIdPrefix,
189
+ callIndexOffset: callCount,
190
+ });
191
+ protocolAttempted ||= parsed.attempted;
192
+ if (parsed.calls.length === 0) {
193
+ if (parsed.failure)
194
+ failure ??= parsed.failure;
195
+ content.push(block);
196
+ continue;
197
+ }
198
+ callCount += parsed.calls.length;
199
+ if (parsed.text) {
200
+ content.push(block.type === "text" ? { ...block, text: parsed.text } : { ...block, thinking: parsed.text });
201
+ }
202
+ content.push(...parsed.calls);
203
+ }
204
+ if (callCount > 0) {
205
+ return {
206
+ message: { ...message, content, stopReason: "toolUse" },
207
+ callCount,
208
+ textLength,
209
+ failure,
210
+ protocolAttempted,
211
+ };
212
+ }
213
+ const hasVisibleText = message.content.some((block) => block.type === "text" && block.text.trim().length > 0);
214
+ const promoteThinking = model.reasoning === false &&
215
+ !protocolAttempted &&
216
+ !hasVisibleText &&
217
+ message.content.some((block) => block.type === "thinking" && !block.redacted);
218
+ return {
219
+ message: promoteThinking
220
+ ? {
221
+ ...message,
222
+ content: message.content.flatMap((block) => {
223
+ if (block.type === "thinking" && !block.redacted) {
224
+ return [{ type: "text", text: block.thinking }];
225
+ }
226
+ if (block.type === "text" && block.text.length === 0)
227
+ return [];
228
+ return [block];
229
+ }),
230
+ }
231
+ : message,
232
+ callCount,
233
+ textLength,
234
+ failure,
235
+ protocolAttempted,
236
+ };
152
237
  }
153
- function withTextToolProtocolResult(stream, model, context, options) {
238
+ function withTextToolProtocolResult(stream, model, context, options, control) {
154
239
  const protocolOptions = normalizeTextToolProtocolOptions(options?.textToolCallProtocol);
155
240
  const tools = context.tools ?? [];
156
241
  if (!protocolOptions || tools.length === 0)
157
242
  return stream;
158
243
  const wrapped = new AssistantMessageEventStream();
244
+ const callIdPrefix = nextTextToolProtocolCallIdPrefix();
159
245
  void (async () => {
160
- const revealedText = new Map();
246
+ const revealedContent = new Map();
161
247
  const liveFilters = new Map();
162
- for await (const event of stream) {
163
- if (event.type !== "done") {
164
- forwardTextProtocolStreamEvent(wrapped, event, revealedText, liveFilters);
165
- continue;
166
- }
167
- const message = event.message;
168
- const content = [];
169
- let callCount = 0;
170
- let textLength = 0;
171
- let failure;
172
- for (const block of message.content) {
173
- if (block.type !== "text") {
174
- content.push(block);
248
+ let completedEnvelopeCount = 0;
249
+ let trailingProseLength = 0;
250
+ let completedProjection;
251
+ try {
252
+ for await (const event of stream) {
253
+ if (event.type !== "done") {
254
+ if (event.type === "text_delta" || event.type === "thinking_delta") {
255
+ if (completedProjection)
256
+ trailingProseLength += event.delta.length;
257
+ }
258
+ forwardTextProtocolStreamEvent(wrapped, event, revealedContent, liveFilters);
259
+ const observedEnvelopeCount = [...liveFilters.values()].reduce((total, filter) => total + filter.completedEnvelopeCount, 0);
260
+ if (observedEnvelopeCount > completedEnvelopeCount && "partial" in event) {
261
+ completedEnvelopeCount = observedEnvelopeCount;
262
+ const projection = projectTextToolProtocolMessage(event.partial, model, tools, callIdPrefix);
263
+ if (projection.callCount > 0) {
264
+ completedProjection = projection;
265
+ trailingProseLength = 0;
266
+ }
267
+ }
268
+ const holdingPotentialEnvelope = [...liveFilters.values()].some((filter) => filter.holdingPotentialEnvelope);
269
+ if (completedProjection &&
270
+ trailingProseLength > TEXT_TOOL_PROTOCOL_TRAILING_PROSE_LIMIT &&
271
+ !holdingPotentialEnvelope &&
272
+ control) {
273
+ control.abortController.abort("text-tool-protocol-call-complete");
274
+ await notifyTextToolProtocolParse(options, {
275
+ provider: model.provider,
276
+ model: model.id,
277
+ variant: protocolOptions.variant ?? "tool-tag",
278
+ status: "parsed",
279
+ callCount: completedProjection.callCount,
280
+ textLength: completedProjection.textLength,
281
+ });
282
+ wrapped.push({ type: "done", reason: "toolUse", message: completedProjection.message });
283
+ return;
284
+ }
175
285
  continue;
176
286
  }
177
- textLength += block.text.length;
178
- const parsed = parseTextToolCalls(block.text, tools);
179
- if (parsed.calls.length === 0) {
180
- if (parsed.failure)
181
- failure ??= parsed.failure;
182
- content.push(block);
287
+ const projection = projectTextToolProtocolMessage(event.message, model, tools, callIdPrefix);
288
+ if (projection.callCount === 0) {
289
+ if (projection.failure) {
290
+ await notifyTextToolProtocolParse(options, {
291
+ provider: model.provider,
292
+ model: model.id,
293
+ variant: protocolOptions.variant ?? "tool-tag",
294
+ status: "failed",
295
+ callCount: 0,
296
+ textLength: projection.textLength,
297
+ reason: projection.failure,
298
+ });
299
+ }
300
+ wrapped.push({ ...event, message: projection.message });
183
301
  continue;
184
302
  }
185
- callCount += parsed.calls.length;
186
- if (parsed.text)
187
- content.push({ ...block, text: parsed.text });
188
- content.push(...parsed.calls);
189
- }
190
- if (callCount === 0) {
191
- if (failure) {
192
- await notifyTextToolProtocolParse(options, {
193
- provider: model.provider,
194
- model: model.id,
195
- variant: protocolOptions.variant ?? "tool-tag",
196
- status: "failed",
197
- callCount: 0,
198
- textLength,
199
- reason: failure,
200
- });
201
- }
202
- wrapped.push(event);
203
- continue;
303
+ await notifyTextToolProtocolParse(options, {
304
+ provider: model.provider,
305
+ model: model.id,
306
+ variant: protocolOptions.variant ?? "tool-tag",
307
+ status: "parsed",
308
+ callCount: projection.callCount,
309
+ textLength: projection.textLength,
310
+ });
311
+ wrapped.push({ type: "done", reason: "toolUse", message: projection.message });
204
312
  }
205
- await notifyTextToolProtocolParse(options, {
206
- provider: model.provider,
207
- model: model.id,
208
- variant: protocolOptions.variant ?? "tool-tag",
209
- status: "parsed",
210
- callCount,
211
- textLength,
212
- });
213
- wrapped.push({
214
- type: "done",
215
- reason: "toolUse",
216
- message: { ...message, content, stopReason: "toolUse" },
217
- });
313
+ }
314
+ finally {
315
+ control?.cleanup();
218
316
  }
219
317
  })();
220
318
  return wrapped;
221
319
  }
320
+ function startTextToolProtocolStream(model, context, options, startProviderStream) {
321
+ const protocolOptions = normalizeTextToolProtocolOptions(options?.textToolCallProtocol);
322
+ if (!protocolOptions || !context.tools?.length)
323
+ return startProviderStream(context, options);
324
+ const abortController = new AbortController();
325
+ const combined = combineAbortSignals([options?.signal, abortController.signal]);
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 });
329
+ }
222
330
  function resolveApiProvider(api) {
223
331
  const provider = getApiProvider(api);
224
332
  if (!provider) {
@@ -229,8 +337,7 @@ function resolveApiProvider(api) {
229
337
  export function stream(model, context, options) {
230
338
  const provider = resolveApiProvider(model.api);
231
339
  const resolvedOptions = withEnvAuth(model, options);
232
- const protocolContext = withTextToolProtocolContext(context, resolvedOptions);
233
- return withTextToolProtocolResult(provider.stream(model, protocolContext, resolvedOptions), model, context, resolvedOptions);
340
+ return startTextToolProtocolStream(model, context, resolvedOptions, (providerContext, providerOptions) => provider.stream(model, providerContext, providerOptions));
234
341
  }
235
342
  export async function complete(model, context, options) {
236
343
  const s = stream(model, context, options);
@@ -239,8 +346,7 @@ export async function complete(model, context, options) {
239
346
  export function streamSimple(model, context, options) {
240
347
  const provider = resolveApiProvider(model.api);
241
348
  const resolvedOptions = withEnvAuth(model, options);
242
- const protocolContext = withTextToolProtocolContext(context, resolvedOptions);
243
- return withTextToolProtocolResult(provider.streamSimple(model, protocolContext, resolvedOptions), model, context, resolvedOptions);
349
+ return startTextToolProtocolStream(model, context, resolvedOptions, (providerContext, providerOptions) => provider.streamSimple(model, providerContext, providerOptions));
244
350
  }
245
351
  export async function completeSimple(model, context, options) {
246
352
  const s = streamSimple(model, context, options);
@@ -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,OA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,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,MAAM,eAAe,GAAG,2BAA2B,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;IAC9E,OAAO,0BAA0B,CAChC,QAAQ,CAAC,YAAY,CAAC,KAAK,EAAE,eAAe,EAAE,eAAe,CAAC,EAC9D,KAAK,EACL,OAAO,EACP,eAAe,CACf,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 { 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\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 content block whose revealed prose is still behind its true streamed text\n// so a forwarded event's `partial` snapshot never exposes held-back or suppressed envelope\n// markup, even on events unrelated to the block being held (e.g. a later thinking/toolcall\n// event still carries the earlier text block in its `partial.content`).\nfunction redactHeldText(partial: AssistantMessage, revealedText: ReadonlyMap<number, string>): AssistantMessage {\n\tif (revealedText.size === 0) return partial;\n\tlet changed = false;\n\tconst content = partial.content.map((block, index) => {\n\t\tif (block.type !== \"text\") return block;\n\t\tconst revealed = revealedText.get(index);\n\t\tif (revealed === undefined || block.text === revealed) return block;\n\t\tchanged = true;\n\t\treturn { ...block, text: 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\trevealedText: 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\") {\n\t\trevealedText.set(event.contentIndex, \"\");\n\t\tliveFilters.set(event.contentIndex, new TextProtocolLiveFilter());\n\t\twrapped.push({ ...event, partial: redactHeldText(event.partial, revealedText) });\n\t\treturn;\n\t}\n\tif (event.type === \"text_delta\") {\n\t\tconst flushed = revealedText.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\trevealedText.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: redactHeldText(event.partial, revealedText),\n\t\t});\n\t\treturn;\n\t}\n\tif (event.type === \"text_end\") {\n\t\tconst flushed = revealedText.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\trevealedText.set(event.contentIndex, visible);\n\t\t\twrapped.push({\n\t\t\t\ttype: \"text_delta\",\n\t\t\t\tcontentIndex: event.contentIndex,\n\t\t\t\tdelta: visible.slice(flushed.length),\n\t\t\t\tpartial: redactHeldText(event.partial, revealedText),\n\t\t\t});\n\t\t}\n\t\tconst finalVisible = revealedText.get(event.contentIndex) ?? visible;\n\t\twrapped.push({\n\t\t\t...event,\n\t\t\tcontent: finalVisible,\n\t\t\tpartial: redactHeldText(event.partial, revealedText),\n\t\t});\n\t\treturn;\n\t}\n\twrapped.push({ ...event, partial: redactHeldText(event.partial, revealedText) });\n}\n\nfunction withTextToolProtocolResult(\n\tstream: AssistantMessageEventStream,\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions: StreamOptions | undefined,\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\tvoid (async () => {\n\t\tconst revealedText = new Map<number, string>();\n\t\tconst liveFilters = new Map<number, TextProtocolLiveFilter>();\n\t\tfor await (const event of stream) {\n\t\t\tif (event.type !== \"done\") {\n\t\t\t\tforwardTextProtocolStreamEvent(wrapped, event, revealedText, liveFilters);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst message = event.message;\n\t\t\tconst content: AssistantMessage[\"content\"] = [];\n\t\t\tlet callCount = 0;\n\t\t\tlet textLength = 0;\n\t\t\tlet failure: TextToolProtocolParseEvent[\"reason\"] | undefined;\n\t\t\tfor (const block of message.content) {\n\t\t\t\tif (block.type !== \"text\") {\n\t\t\t\t\tcontent.push(block);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\ttextLength += block.text.length;\n\t\t\t\tconst parsed = parseTextToolCalls(block.text, tools);\n\t\t\t\tif (parsed.calls.length === 0) {\n\t\t\t\t\tif (parsed.failure) failure ??= parsed.failure;\n\t\t\t\t\tcontent.push(block);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tcallCount += parsed.calls.length;\n\t\t\t\tif (parsed.text) content.push({ ...block, text: parsed.text });\n\t\t\t\tcontent.push(...parsed.calls);\n\t\t\t}\n\t\t\tif (callCount === 0) {\n\t\t\t\tif (failure) {\n\t\t\t\t\tawait notifyTextToolProtocolParse(options, {\n\t\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\t\tmodel: model.id,\n\t\t\t\t\t\tvariant: protocolOptions.variant ?? \"tool-tag\",\n\t\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\t\tcallCount: 0,\n\t\t\t\t\t\ttextLength,\n\t\t\t\t\t\treason: failure,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\twrapped.push(event);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tawait notifyTextToolProtocolParse(options, {\n\t\t\t\tprovider: model.provider,\n\t\t\t\tmodel: model.id,\n\t\t\t\tvariant: protocolOptions.variant ?? \"tool-tag\",\n\t\t\t\tstatus: \"parsed\",\n\t\t\t\tcallCount,\n\t\t\t\ttextLength,\n\t\t\t});\n\t\t\twrapped.push({\n\t\t\t\ttype: \"done\",\n\t\t\t\treason: \"toolUse\",\n\t\t\t\tmessage: { ...message, content, stopReason: \"toolUse\" },\n\t\t\t});\n\t\t}\n\t})();\n\treturn wrapped;\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) as StreamOptions;\n\tconst protocolContext = withTextToolProtocolContext(context, resolvedOptions);\n\treturn withTextToolProtocolResult(\n\t\tprovider.stream(model, protocolContext, resolvedOptions),\n\t\tmodel,\n\t\tcontext,\n\t\tresolvedOptions,\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\tconst protocolContext = withTextToolProtocolContext(context, resolvedOptions);\n\treturn withTextToolProtocolResult(\n\t\tprovider.streamSimple(model, protocolContext, resolvedOptions),\n\t\tmodel,\n\t\tcontext,\n\t\tresolvedOptions,\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;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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,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\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"]}
@@ -12,6 +12,11 @@ export declare function formatToolRepairNote(name: ToolRepairModeName, path: str
12
12
  export declare function formatToolRepairStandingRule(name: ToolRepairModeName): string;
13
13
  export type ToolExecutionAttemptMemory = "retain" | "discard";
14
14
  export type ToolFailurePhase = "validation" | "policy" | "preflight" | "execution" | "timeout" | "cancelled" | "provisioning";
15
+ export declare const REPEATED_SUCCESSFUL_TOOL_CALL_FAILURE: {
16
+ readonly failureCode: "repeated_successful_call";
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.";
19
+ };
15
20
  export declare const TOOL_EXECUTION_ERROR_CATALOGUE: readonly [{
16
21
  readonly name: "provisioningFailed";
17
22
  readonly phase: "provisioning";
@@ -31,6 +36,22 @@ export declare const TOOL_EXECUTION_ERROR_CATALOGUE: readonly [{
31
36
  readonly attemptMemory: "discard";
32
37
  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.";
33
38
  readonly matches: (message: string) => boolean;
39
+ }, {
40
+ readonly name: "repeatedSuccessfulCall";
41
+ readonly phase: "execution";
42
+ readonly failureCode: "repeated_successful_call";
43
+ readonly attemptMemory: "discard";
44
+ readonly retainDiagnostic: true;
45
+ 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.";
46
+ readonly matches: (message: string) => boolean;
47
+ }, {
48
+ readonly name: "fileMutationRetarget";
49
+ readonly phase: "execution";
50
+ readonly failureCode: "mutation_retarget_required";
51
+ readonly attemptMemory: "discard";
52
+ readonly retainDiagnostic: true;
53
+ 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.";
54
+ readonly matches: (message: string) => boolean;
34
55
  }, {
35
56
  readonly name: "fileNotFound";
36
57
  readonly phase: "execution";
@@ -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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QAAQ;uBACL,mFAAmF;gCAC5E,MAAM,KAAG,OAAO;;mBAK3B,kBAAkB;oBACjB,QAAQ;0BACF,mBAAmB;;uBAG/B,sHAAsH;gCACtG,MAAM,KAAG,OAAO;;mBAK3B,eAAe;oBACd,WAAW;0BACL,gBAAgB;;uBAEnB,iFAAiF;gCAC1E,MAAM,KAAG,OAAO;;mBAK3B,gBAAgB;oBACf,WAAW;0BACL,iBAAiB;;uBAEpB,iGAAiG;gCAC1F,MAAM,KAAG,OAAO;;mBAQ3B,aAAa;oBACZ,WAAW;0BACL,cAAc;uBAE1B,8GAA8G;gCAC9F,MAAM,KAAG,OAAO;;mBAK3B,UAAU;oBACT,SAAS;0BACH,SAAS;uBAErB,uHAAuH;gCACvG,MAAM,KAAG,OAAO;;mBAQ3B,WAAW;oBACV,WAAW;0BACL,WAAW;uBAEvB,6GAA6G;gCAC7F,MAAM,KAAG,OAAO;EAO6B,CAAC;AAEjE,MAAM,MAAM,uBAAuB,GAAG,CAAC,OAAO,8BAA8B,CAAC,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC;AAG9F,MAAM,WAAW,wBAAwB;IACxC,IAAI,EAAE,uBAAuB,CAAC;IAC9B,KAAK,EAAE,gBAAgB,CAAC;IACxB,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,0BAA0B,CAAC;IAC1C,gBAAgB,EAAE,OAAO,CAAC;CAC1B;AAED,wBAAgB,2BAA2B,CAAC,YAAY,EAAE,MAAM,GAAG,wBAAwB,GAAG,SAAS,CAWtG;AAED,wBAAgB,6BAA6B,CAAC,WAAW,EAAE,MAAM,GAAG,0BAA0B,CAG7F;AAED,wBAAgB,6BAA6B,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAEtF"}
@@ -105,6 +105,11 @@ export function formatToolRepairNote(name, path) {
105
105
  export function formatToolRepairStandingRule(name) {
106
106
  return getToolRepairRegistryEntry(name).standingRule;
107
107
  }
108
+ export const REPEATED_SUCCESSFUL_TOOL_CALL_FAILURE = {
109
+ failureCode: "repeated_successful_call",
110
+ diagnostic: "The identical phone tool call already succeeded and was not executed again.",
111
+ 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.",
112
+ };
108
113
  export const TOOL_EXECUTION_ERROR_CATALOGUE = [
109
114
  {
110
115
  name: "provisioningFailed",
@@ -134,6 +139,28 @@ export const TOOL_EXECUTION_ERROR_CATALOGUE = [
134
139
  return /\bPI_FILE_ENCODING_CORRUPTION\b/i.test(message);
135
140
  },
136
141
  },
142
+ {
143
+ name: "repeatedSuccessfulCall",
144
+ phase: "execution",
145
+ failureCode: REPEATED_SUCCESSFUL_TOOL_CALL_FAILURE.failureCode,
146
+ attemptMemory: "discard",
147
+ retainDiagnostic: true,
148
+ guidance: REPEATED_SUCCESSFUL_TOOL_CALL_FAILURE.guidance,
149
+ matches(message) {
150
+ return message === REPEATED_SUCCESSFUL_TOOL_CALL_FAILURE.diagnostic;
151
+ },
152
+ },
153
+ {
154
+ name: "fileMutationRetarget",
155
+ phase: "execution",
156
+ failureCode: "mutation_retarget_required",
157
+ attemptMemory: "discard",
158
+ retainDiagnostic: true,
159
+ 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.",
160
+ matches(message) {
161
+ return /\bPI_FILE_MUTATION_RETARGET\b/i.test(message);
162
+ },
163
+ },
137
164
  {
138
165
  name: "fileNotFound",
139
166
  phase: "execution",