@buoy-gg/agent-core 7.0.34 → 7.0.36

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 (181) hide show
  1. package/README.md +10 -7
  2. package/lib/commonjs/blocks/receipts.js +83 -24
  3. package/lib/commonjs/blocks/receipts.js.map +1 -1
  4. package/lib/commonjs/blocks/runId.js +31 -0
  5. package/lib/commonjs/blocks/runId.js.map +1 -0
  6. package/lib/commonjs/blocks/types.js +23 -2
  7. package/lib/commonjs/blocks/types.js.map +1 -1
  8. package/lib/commonjs/blocks/uiTool.js +426 -12
  9. package/lib/commonjs/blocks/uiTool.js.map +1 -1
  10. package/lib/commonjs/catalog/catalog.g.js +121 -43
  11. package/lib/commonjs/catalog/catalog.g.js.map +1 -1
  12. package/lib/commonjs/catalog/catalog.source.json +121 -45
  13. package/lib/commonjs/catalog/catalog.types.g.js +44 -0
  14. package/lib/commonjs/catalog/catalog.types.g.js.map +1 -0
  15. package/lib/commonjs/catalog/normalizeParams.js +333 -0
  16. package/lib/commonjs/catalog/normalizeParams.js.map +1 -0
  17. package/lib/commonjs/catalog/signature.js +68 -0
  18. package/lib/commonjs/catalog/signature.js.map +1 -0
  19. package/lib/commonjs/catalog/snapshotReads.js +13 -6
  20. package/lib/commonjs/catalog/snapshotReads.js.map +1 -1
  21. package/lib/commonjs/catalog/toProviderTools.js +41 -5
  22. package/lib/commonjs/catalog/toProviderTools.js.map +1 -1
  23. package/lib/commonjs/context/buildContextPack.js +367 -19
  24. package/lib/commonjs/context/buildContextPack.js.map +1 -1
  25. package/lib/commonjs/effects/digest.js +34 -0
  26. package/lib/commonjs/effects/digest.js.map +1 -0
  27. package/lib/commonjs/effects/ledger.js +85 -1
  28. package/lib/commonjs/effects/ledger.js.map +1 -1
  29. package/lib/commonjs/engine/askGate.js +287 -0
  30. package/lib/commonjs/engine/askGate.js.map +1 -0
  31. package/lib/commonjs/engine/effectFor.js +82 -1
  32. package/lib/commonjs/engine/effectFor.js.map +1 -1
  33. package/lib/commonjs/engine/historyBudget.js +260 -0
  34. package/lib/commonjs/engine/historyBudget.js.map +1 -0
  35. package/lib/commonjs/engine/runAgentTurn.js +958 -88
  36. package/lib/commonjs/engine/runAgentTurn.js.map +1 -1
  37. package/lib/commonjs/engine/systemPrompt.js +72 -8
  38. package/lib/commonjs/engine/systemPrompt.js.map +1 -1
  39. package/lib/commonjs/engine/textToolCalls.js +276 -0
  40. package/lib/commonjs/engine/textToolCalls.js.map +1 -0
  41. package/lib/commonjs/index.js +81 -1
  42. package/lib/commonjs/index.js.map +1 -1
  43. package/lib/commonjs/policy/labels.js +19 -3
  44. package/lib/commonjs/policy/labels.js.map +1 -1
  45. package/lib/commonjs/policy/policy.js +6 -1
  46. package/lib/commonjs/policy/policy.js.map +1 -1
  47. package/lib/commonjs/policy/redact.js +42 -5
  48. package/lib/commonjs/policy/redact.js.map +1 -1
  49. package/lib/commonjs/providers/anthropic.js +340 -174
  50. package/lib/commonjs/providers/anthropic.js.map +1 -1
  51. package/lib/commonjs/providers/openai.js +229 -103
  52. package/lib/commonjs/providers/openai.js.map +1 -1
  53. package/lib/commonjs/providers/sse.js +164 -29
  54. package/lib/commonjs/providers/sse.js.map +1 -1
  55. package/lib/commonjs/providers/streamTimer.js +123 -0
  56. package/lib/commonjs/providers/streamTimer.js.map +1 -0
  57. package/lib/commonjs/providers/transport.js +107 -0
  58. package/lib/commonjs/providers/transport.js.map +1 -0
  59. package/lib/commonjs/providers/xhrStream.js +209 -0
  60. package/lib/commonjs/providers/xhrStream.js.map +1 -0
  61. package/lib/commonjs/session.js +245 -52
  62. package/lib/commonjs/session.js.map +1 -1
  63. package/lib/module/blocks/receipts.js +83 -24
  64. package/lib/module/blocks/receipts.js.map +1 -1
  65. package/lib/module/blocks/runId.js +26 -0
  66. package/lib/module/blocks/runId.js.map +1 -0
  67. package/lib/module/blocks/types.js +23 -2
  68. package/lib/module/blocks/types.js.map +1 -1
  69. package/lib/module/blocks/uiTool.js +424 -12
  70. package/lib/module/blocks/uiTool.js.map +1 -1
  71. package/lib/module/catalog/catalog.g.js +121 -43
  72. package/lib/module/catalog/catalog.g.js.map +1 -1
  73. package/lib/module/catalog/catalog.source.json +121 -45
  74. package/lib/module/catalog/catalog.types.g.js +40 -0
  75. package/lib/module/catalog/catalog.types.g.js.map +1 -0
  76. package/lib/module/catalog/normalizeParams.js +327 -0
  77. package/lib/module/catalog/normalizeParams.js.map +1 -0
  78. package/lib/module/catalog/signature.js +63 -0
  79. package/lib/module/catalog/signature.js.map +1 -0
  80. package/lib/module/catalog/snapshotReads.js +13 -6
  81. package/lib/module/catalog/snapshotReads.js.map +1 -1
  82. package/lib/module/catalog/toProviderTools.js +41 -5
  83. package/lib/module/catalog/toProviderTools.js.map +1 -1
  84. package/lib/module/context/buildContextPack.js +366 -19
  85. package/lib/module/context/buildContextPack.js.map +1 -1
  86. package/lib/module/effects/digest.js +29 -0
  87. package/lib/module/effects/digest.js.map +1 -0
  88. package/lib/module/effects/ledger.js +85 -1
  89. package/lib/module/effects/ledger.js.map +1 -1
  90. package/lib/module/engine/askGate.js +280 -0
  91. package/lib/module/engine/askGate.js.map +1 -0
  92. package/lib/module/engine/effectFor.js +83 -1
  93. package/lib/module/engine/effectFor.js.map +1 -1
  94. package/lib/module/engine/historyBudget.js +251 -0
  95. package/lib/module/engine/historyBudget.js.map +1 -0
  96. package/lib/module/engine/runAgentTurn.js +954 -88
  97. package/lib/module/engine/runAgentTurn.js.map +1 -1
  98. package/lib/module/engine/systemPrompt.js +71 -8
  99. package/lib/module/engine/systemPrompt.js.map +1 -1
  100. package/lib/module/engine/textToolCalls.js +270 -0
  101. package/lib/module/engine/textToolCalls.js.map +1 -0
  102. package/lib/module/index.js +7 -4
  103. package/lib/module/index.js.map +1 -1
  104. package/lib/module/policy/labels.js +19 -3
  105. package/lib/module/policy/labels.js.map +1 -1
  106. package/lib/module/policy/policy.js +6 -1
  107. package/lib/module/policy/policy.js.map +1 -1
  108. package/lib/module/policy/redact.js +42 -5
  109. package/lib/module/policy/redact.js.map +1 -1
  110. package/lib/module/providers/anthropic.js +341 -175
  111. package/lib/module/providers/anthropic.js.map +1 -1
  112. package/lib/module/providers/openai.js +230 -104
  113. package/lib/module/providers/openai.js.map +1 -1
  114. package/lib/module/providers/sse.js +160 -29
  115. package/lib/module/providers/sse.js.map +1 -1
  116. package/lib/module/providers/streamTimer.js +118 -0
  117. package/lib/module/providers/streamTimer.js.map +1 -0
  118. package/lib/module/providers/transport.js +103 -0
  119. package/lib/module/providers/transport.js.map +1 -0
  120. package/lib/module/providers/xhrStream.js +204 -0
  121. package/lib/module/providers/xhrStream.js.map +1 -0
  122. package/lib/module/session.js +228 -54
  123. package/lib/module/session.js.map +1 -1
  124. package/lib/typescript/blocks/receipts.d.ts +5 -10
  125. package/lib/typescript/blocks/receipts.d.ts.map +1 -1
  126. package/lib/typescript/blocks/runId.d.ts +20 -0
  127. package/lib/typescript/blocks/runId.d.ts.map +1 -0
  128. package/lib/typescript/blocks/types.d.ts +23 -2
  129. package/lib/typescript/blocks/types.d.ts.map +1 -1
  130. package/lib/typescript/blocks/uiTool.d.ts +11 -2
  131. package/lib/typescript/blocks/uiTool.d.ts.map +1 -1
  132. package/lib/typescript/catalog/catalog.g.d.ts.map +1 -1
  133. package/lib/typescript/catalog/catalog.types.g.d.ts +40 -0
  134. package/lib/typescript/catalog/catalog.types.g.d.ts.map +1 -0
  135. package/lib/typescript/catalog/normalizeParams.d.ts +43 -0
  136. package/lib/typescript/catalog/normalizeParams.d.ts.map +1 -0
  137. package/lib/typescript/catalog/signature.d.ts +29 -0
  138. package/lib/typescript/catalog/signature.d.ts.map +1 -0
  139. package/lib/typescript/catalog/snapshotReads.d.ts.map +1 -1
  140. package/lib/typescript/catalog/toProviderTools.d.ts +28 -15
  141. package/lib/typescript/catalog/toProviderTools.d.ts.map +1 -1
  142. package/lib/typescript/context/buildContextPack.d.ts +24 -2
  143. package/lib/typescript/context/buildContextPack.d.ts.map +1 -1
  144. package/lib/typescript/effects/digest.d.ts +10 -0
  145. package/lib/typescript/effects/digest.d.ts.map +1 -0
  146. package/lib/typescript/effects/ledger.d.ts +55 -0
  147. package/lib/typescript/effects/ledger.d.ts.map +1 -1
  148. package/lib/typescript/engine/askGate.d.ts +29 -0
  149. package/lib/typescript/engine/askGate.d.ts.map +1 -0
  150. package/lib/typescript/engine/effectFor.d.ts +6 -1
  151. package/lib/typescript/engine/effectFor.d.ts.map +1 -1
  152. package/lib/typescript/engine/historyBudget.d.ts +92 -0
  153. package/lib/typescript/engine/historyBudget.d.ts.map +1 -0
  154. package/lib/typescript/engine/runAgentTurn.d.ts +115 -1
  155. package/lib/typescript/engine/runAgentTurn.d.ts.map +1 -1
  156. package/lib/typescript/engine/systemPrompt.d.ts +41 -0
  157. package/lib/typescript/engine/systemPrompt.d.ts.map +1 -1
  158. package/lib/typescript/engine/textToolCalls.d.ts +58 -0
  159. package/lib/typescript/engine/textToolCalls.d.ts.map +1 -0
  160. package/lib/typescript/index.d.ts +8 -5
  161. package/lib/typescript/index.d.ts.map +1 -1
  162. package/lib/typescript/policy/labels.d.ts.map +1 -1
  163. package/lib/typescript/policy/policy.d.ts.map +1 -1
  164. package/lib/typescript/policy/redact.d.ts.map +1 -1
  165. package/lib/typescript/providers/anthropic.d.ts +5 -0
  166. package/lib/typescript/providers/anthropic.d.ts.map +1 -1
  167. package/lib/typescript/providers/openai.d.ts +0 -16
  168. package/lib/typescript/providers/openai.d.ts.map +1 -1
  169. package/lib/typescript/providers/sse.d.ts +82 -1
  170. package/lib/typescript/providers/sse.d.ts.map +1 -1
  171. package/lib/typescript/providers/streamTimer.d.ts +59 -0
  172. package/lib/typescript/providers/streamTimer.d.ts.map +1 -0
  173. package/lib/typescript/providers/transport.d.ts +40 -0
  174. package/lib/typescript/providers/transport.d.ts.map +1 -0
  175. package/lib/typescript/providers/types.d.ts +116 -3
  176. package/lib/typescript/providers/types.d.ts.map +1 -1
  177. package/lib/typescript/providers/xhrStream.d.ts +43 -0
  178. package/lib/typescript/providers/xhrStream.d.ts.map +1 -0
  179. package/lib/typescript/session.d.ts +63 -2
  180. package/lib/typescript/session.d.ts.map +1 -1
  181. package/package.json +2 -2
@@ -15,9 +15,24 @@
15
15
  * is the common shape for an internal LLM proxy. Note Anthropic's own
16
16
  * OpenAI-compatibility endpoint is explicitly not production-ready and silently
17
17
  * ignores several fields — use the native Anthropic adapter for Anthropic.
18
+ *
19
+ * THE 1024-CHAR TRAP. Azure caps a function description at 1024 chars, so
20
+ * this adapter trims to fit. The catalog renders a tool's summary FIRST and
21
+ * its `Actions:` list LAST, and every tool's full description is longer than
22
+ * the cap — so trimming `t.description` silently removed every action line
23
+ * for 23 of the 24 tools — the 24th kept one line of sixteen — measured
24
+ * against the catalog as it is. A model on this protocol (api.openai.com, Azure,
25
+ * OpenRouter, fal — every row of the model-floor sweep) saw a summary cut
26
+ * mid-sentence and a bare `action` enum: no per-action summary, no
27
+ * [DESTRUCTIVE] / [changes state] tag, no "prefer X over Y" guidance, and a
28
+ * catalog wording change could not move its score. So the description is
29
+ * the SUMMARY only, and the `Actions:` block goes into
30
+ * `parameters.properties.action.description`, which nothing caps.
18
31
  */
19
32
 
20
- import { errorBody, readSse } from "./sse";
33
+ import { truncatedMessage, unparseableMessage } from "./sse";
34
+ import { createStreamTimer } from "./streamTimer";
35
+ import { createTransport } from "./transport";
21
36
  function toWireMessages(system, messages) {
22
37
  const out = [{
23
38
  role: "system",
@@ -57,132 +72,243 @@ function toWireMessages(system, messages) {
57
72
  }
58
73
  return out;
59
74
  }
75
+
76
+ /**
77
+ * The tool's input schema with the `Actions:` block on the `action`
78
+ * property — the uncapped home for the per-action lines (header note).
79
+ */
80
+ function withActionsBlock(t) {
81
+ const action = t.inputSchema.properties.action;
82
+ return {
83
+ ...t.inputSchema,
84
+ properties: {
85
+ ...t.inputSchema.properties,
86
+ action: {
87
+ ...action,
88
+ description: `Which action to run.\n\n${t.actionsBlock}`
89
+ }
90
+ }
91
+ };
92
+ }
60
93
  export function createOpenAIProvider(config) {
94
+ // One per provider, so the `auto` transport decision is made once and not
95
+ // re-learned (and re-buffered) at the start of every turn.
96
+ const transport = createTransport(config);
61
97
  return {
62
98
  protocol: "openai",
63
99
  async *send(req) {
64
- const headers = {
65
- "content-type": "application/json",
66
- ...(await (config.headers?.() ?? {}))
100
+ const timer = createStreamTimer(req.signal, config);
101
+ const status = {
102
+ truncated: false
67
103
  };
68
- if (config.apiKey && !headers.Authorization && !headers["api-key"]) {
69
- headers.Authorization = `Bearer ${config.apiKey}`;
70
- }
71
- const response = await fetch(config.endpoint, {
72
- method: "POST",
73
- headers,
74
- signal: req.signal,
75
- body: JSON.stringify({
76
- model: req.model,
77
- max_tokens: req.maxTokens,
78
- stream: true,
79
- stream_options: {
80
- include_usage: true
81
- },
82
- messages: toWireMessages(req.system, req.messages),
83
- tools: req.tools.map(t => ({
84
- type: "function",
85
- function: {
86
- name: t.name,
87
- // Azure caps function descriptions at 1024 chars while Anthropic's
88
- // guidance asks for several sentences. Trim rather than 400.
89
- description: t.description.slice(0, 1024),
90
- parameters: t.inputSchema
91
- }
92
- })),
93
- ...config.requestOverrides
94
- })
95
- });
96
- if (!response.ok) {
97
- yield {
98
- type: "error",
99
- message: await errorBody(response)
104
+ try {
105
+ const headers = {
106
+ "content-type": "application/json",
107
+ ...(await (config.headers?.() ?? {}))
100
108
  };
101
- return;
102
- }
109
+ if (config.apiKey && !headers.Authorization && !headers["api-key"]) {
110
+ headers.Authorization = `Bearer ${config.apiKey}`;
111
+ }
112
+ const stream = await transport.open({
113
+ headers,
114
+ // The timer's signal, not the caller's: it aborts on the user's Stop
115
+ // AND on either clock running out. See providers/streamTimer.ts.
116
+ signal: timer.signal,
117
+ body: JSON.stringify({
118
+ model: req.model,
119
+ max_tokens: req.maxTokens,
120
+ stream: true,
121
+ stream_options: {
122
+ include_usage: true
123
+ },
124
+ messages: toWireMessages(req.systemVolatile ? `${req.system}\n\n---\n\n${req.systemVolatile}` : req.system, req.messages),
125
+ tools: req.tools.map(t => ({
126
+ type: "function",
127
+ function: {
128
+ name: t.name,
129
+ // Azure caps function descriptions at 1024 chars while Anthropic's
130
+ // guidance asks for several sentences. Trim rather than 400 — but
131
+ // trim the SUMMARY only: the action lines travel on `parameters`
132
+ // (withActionsBlock), where nothing is capped. See the header.
133
+ description: t.summaryDescription.slice(0, 1024),
134
+ parameters: withActionsBlock(t)
135
+ }
136
+ })),
137
+ ...config.requestOverrides
138
+ })
139
+ });
140
+
141
+ // Headers are in: the connect clock stops here and the idle one starts.
142
+ timer.connected();
143
+ if (stream.problem) {
144
+ yield {
145
+ type: "error",
146
+ message: stream.problem,
147
+ kind: "provider"
148
+ };
149
+ return;
150
+ }
103
151
 
104
- // Keyed by the stream's `index`; id and name arrive only on the first
105
- // fragment, arguments accumulate across all of them.
106
- const pending = new Map();
107
- let stopReason;
108
- let usage;
109
- const flush = function* () {
110
- for (const [, slot] of pending) {
111
- let input = {};
152
+ // Keyed by the stream's `index`; id and name arrive only on the first
153
+ // fragment, arguments accumulate across all of them.
154
+ const pending = new Map();
155
+ let stopReason;
156
+ let usage;
157
+ // The served model id, from the first chunk that names one. A gateway
158
+ // resolves `gpt-4.1` to a dated snapshot, and that is the id a cost
159
+ // table or a benchmark has to attribute a drift to.
160
+ let model;
161
+ /** The `[DONE]` sentinel; ends the read. See `sawTerminal` below. */
162
+ let sawDone = false;
163
+ const flush = function* () {
164
+ for (const [, slot] of pending) {
165
+ let input = {};
166
+ try {
167
+ input = slot.args ? JSON.parse(slot.args) : {};
168
+ } catch {
169
+ yield {
170
+ type: "error",
171
+ kind: "provider",
172
+ // Carry the evidence. Without it this error says only THAT the
173
+ // arguments were bad, and diagnosing it needs a live repro of a
174
+ // model that may not be reachable any more — a Sonnet bench run
175
+ // produced 15 of these and left nothing to read. `length` here
176
+ // means the model was cut off mid-argument and `max_tokens` is
177
+ // the fix; anything else is a genuinely malformed stream.
178
+ message: unparseableMessage(slot.name, slot.args, stopReason)
179
+ };
180
+ continue;
181
+ }
182
+ yield {
183
+ type: "tool-call",
184
+ call: {
185
+ id: slot.id,
186
+ name: slot.name,
187
+ input
188
+ }
189
+ };
190
+ }
191
+ pending.clear();
192
+ };
193
+ for await (const ev of stream.frames({
194
+ status,
195
+ onFrame: timer.activity,
196
+ signal: timer.signal
197
+ })) {
198
+ if (ev.data === "[DONE]") {
199
+ sawDone = true;
200
+ break;
201
+ }
202
+ let payload;
112
203
  try {
113
- input = slot.args ? JSON.parse(slot.args) : {};
204
+ payload = JSON.parse(ev.data);
114
205
  } catch {
206
+ continue;
207
+ }
208
+ if (payload.error) {
209
+ const err = payload.error;
115
210
  yield {
116
211
  type: "error",
117
- message: `Model sent unparseable arguments for ${slot.name}`
212
+ message: err.message ?? "Provider error",
213
+ kind: "provider"
118
214
  };
119
- continue;
215
+ return;
216
+ }
217
+ if (!model && typeof payload.model === "string" && payload.model) model = payload.model;
218
+ const u = payload.usage;
219
+ if (u) {
220
+ // `prompt_tokens_details.cached_tokens` is this protocol's cache
221
+ // counter. Unlike Anthropic's it is INCLUDED in `prompt_tokens`
222
+ // rather than reported beside it; it is still carried as
223
+ // `cacheRead` so a cost table can price that slice at the
224
+ // discounted rate.
225
+ const details = u.prompt_tokens_details;
226
+ const cached = details?.cached_tokens;
227
+ usage = {
228
+ input: typeof u.prompt_tokens === "number" ? u.prompt_tokens : 0,
229
+ output: typeof u.completion_tokens === "number" ? u.completion_tokens : 0,
230
+ ...(typeof cached === "number" ? {
231
+ cacheRead: cached
232
+ } : {})
233
+ };
234
+ }
235
+ const choice = payload.choices?.[0];
236
+ if (!choice) continue;
237
+ if (choice.finish_reason) stopReason = choice.finish_reason;
238
+ const delta = choice.delta;
239
+ if (typeof delta?.content === "string" && delta.content) {
240
+ yield {
241
+ type: "text",
242
+ delta: delta.content
243
+ };
244
+ }
245
+ const calls = delta?.tool_calls;
246
+ for (const c of calls ?? []) {
247
+ const index = c.index ?? 0;
248
+ const fn = c.function;
249
+ const slot = pending.get(index) ?? {
250
+ id: "",
251
+ name: "",
252
+ args: ""
253
+ };
254
+ if (c.id) slot.id = c.id;
255
+ if (fn?.name) slot.name = fn.name;
256
+ if (typeof fn?.arguments === "string") slot.args += fn.arguments;
257
+ pending.set(index, slot);
120
258
  }
121
- yield {
122
- type: "tool-call",
123
- call: {
124
- id: slot.id,
125
- name: slot.name,
126
- input
127
- }
128
- };
129
- }
130
- pending.clear();
131
- };
132
- for await (const ev of readSse(response)) {
133
- if (ev.data === "[DONE]") break;
134
- let payload;
135
- try {
136
- payload = JSON.parse(ev.data);
137
- } catch {
138
- continue;
139
259
  }
140
- if (payload.error) {
141
- const err = payload.error;
260
+
261
+ /**
262
+ * Did the provider actually say it was finished?
263
+ *
264
+ * `[DONE]` is the transport sentinel. `finish_reason` counts too, and is
265
+ * the stronger claim: it is the model's own statement of why it stopped,
266
+ * while `[DONE]` only says the SSE stream closed. Plenty of
267
+ * OpenAI-compatible gateways send one and not the other, and refusing
268
+ * either shape would break working endpoints for no safety gain. NEITHER
269
+ * arriving is the case that matters — bare EOF, which used to be read as
270
+ * success, and which is how a complete-looking `storage.setItem` came out
271
+ * of a cut connection and ran.
272
+ */
273
+ const sawTerminal = sawDone || stopReason !== undefined;
274
+ if (!sawTerminal) {
275
+ // Nothing is flushed: the accumulated arguments may be a whole JSON
276
+ // object and still be half a plan. Text already yielded stays on
277
+ // screen; the engine shows it and offers Continue.
142
278
  yield {
143
279
  type: "error",
144
- message: err.message ?? "Provider error"
280
+ message: truncatedMessage(status.truncated),
281
+ kind: "truncated"
145
282
  };
146
283
  return;
147
284
  }
148
- const u = payload.usage;
149
- if (u) {
150
- usage = {
151
- input: u.prompt_tokens ?? 0,
152
- output: u.completion_tokens ?? 0
153
- };
154
- }
155
- const choice = payload.choices?.[0];
156
- if (!choice) continue;
157
- if (choice.finish_reason) stopReason = choice.finish_reason;
158
- const delta = choice.delta;
159
- if (typeof delta?.content === "string" && delta.content) {
285
+ yield* flush();
286
+ yield {
287
+ type: "done",
288
+ outcome: stopReason === "length" ? "output-limited" : "completed",
289
+ stopReason,
290
+ usage,
291
+ model
292
+ };
293
+ } catch (err) {
294
+ // The user's Stop wins the label even if a clock fired in the same
295
+ // tick: they know why the turn ended, and "timed out" would be a lie.
296
+ if (req.signal?.aborted) throw err;
297
+ const message = timer.message();
298
+ if (message) {
160
299
  yield {
161
- type: "text",
162
- delta: delta.content
163
- };
164
- }
165
- const calls = delta?.tool_calls;
166
- for (const c of calls ?? []) {
167
- const index = c.index ?? 0;
168
- const fn = c.function;
169
- const slot = pending.get(index) ?? {
170
- id: "",
171
- name: "",
172
- args: ""
300
+ type: "error",
301
+ message,
302
+ kind: "timeout"
173
303
  };
174
- if (c.id) slot.id = c.id;
175
- if (fn?.name) slot.name = fn.name;
176
- if (typeof fn?.arguments === "string") slot.args += fn.arguments;
177
- pending.set(index, slot);
304
+ return;
178
305
  }
306
+ // A genuine transport failure — DNS, refused connection, TLS. It has
307
+ // always propagated to the failed-turn card, and still does.
308
+ throw err;
309
+ } finally {
310
+ timer.dispose();
179
311
  }
180
- yield* flush();
181
- yield {
182
- type: "done",
183
- stopReason,
184
- usage
185
- };
186
312
  }
187
313
  };
188
314
  }
@@ -1 +1 @@
1
- {"version":3,"names":["errorBody","readSse","toWireMessages","system","messages","out","role","content","m","push","text","toolCalls","length","tool_calls","map","c","id","type","function","name","arguments","JSON","stringify","input","r","results","tool_call_id","toolCallId","createOpenAIProvider","config","protocol","send","req","headers","apiKey","Authorization","response","fetch","endpoint","method","signal","body","model","max_tokens","maxTokens","stream","stream_options","include_usage","tools","t","description","slice","parameters","inputSchema","requestOverrides","ok","message","pending","Map","stopReason","usage","flush","slot","args","parse","call","clear","ev","data","payload","error","err","u","prompt_tokens","output","completion_tokens","choice","choices","finish_reason","delta","calls","index","fn","get","set"],"sourceRoot":"../../../src","sources":["providers/openai.ts"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAC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CAAC3C,IAAI,GAAG+D,EAAE,CAAC/D,IAAc;UAC3C,IAAI,OAAO+D,EAAE,EAAE9D,SAAS,KAAK,QAAQ,EAAE0C,IAAI,CAACC,IAAI,IAAImB,EAAE,CAAC9D,SAAS;UAChEqC,OAAO,CAAC2B,GAAG,CAACH,KAAK,EAAEnB,IAAI,CAAC;QAC1B;MACF;MAEA,OAAOD,KAAK,CAAC,CAAC;MACd,MAAM;QAAE5C,IAAI,EAAE,MAAM;QAAE0C,UAAU;QAAEC;MAAM,CAAC;IAC3C;EACF,CAAC;AACH","ignoreList":[]}
1
+ {"version":3,"names":["truncatedMessage","unparseableMessage","createStreamTimer","createTransport","toWireMessages","system","messages","out","role","content","m","push","text","toolCalls","length","tool_calls","map","c","id","type","function","name","arguments","JSON","stringify","input","r","results","tool_call_id","toolCallId","withActionsBlock","t","action","inputSchema","properties","description","actionsBlock","createOpenAIProvider","config","transport","protocol","send","req","timer","signal","status","truncated","headers","apiKey","Authorization","stream","open","body","model","max_tokens","maxTokens","stream_options","include_usage","systemVolatile","tools","summaryDescription","slice","parameters","requestOverrides","connected","problem","message","kind","pending","Map","stopReason","usage","sawDone","flush","slot","args","parse","call","clear","ev","frames","onFrame","activity","data","payload","error","err","u","details","prompt_tokens_details","cached","cached_tokens","prompt_tokens","output","completion_tokens","cacheRead","choice","choices","finish_reason","delta","calls","index","fn","get","set","sawTerminal","undefined","outcome","aborted","dispose"],"sourceRoot":"../../../src","sources":["providers/openai.ts"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAUA,SAASA,gBAAgB,EAAEC,kBAAkB,QAA4B,OAAO;AAChF,SAASC,iBAAiB,QAAQ,eAAe;AACjD,SAASC,eAAe,QAAQ,aAAa;AAa7C,SAASC,cAAcA,CAACC,MAAc,EAAEC,QAAwB,EAAi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kE,OAAO,CAAC,CAAC;MACjB;IACF;EACF,CAAC;AACH","ignoreList":[]}
@@ -9,15 +9,24 @@
9
9
  * TV-CLI lanes never had it. So `readSse` degrades to reading the whole body
10
10
  * and replaying it as events rather than failing: a non-streaming answer is a
11
11
  * slower chat, while a hard failure is no chat at all.
12
+ *
13
+ * THE TWO PATHS MUST AGREE. They did not. The buffered path appended "\n\n" to
14
+ * the body before parsing, which turns an unterminated final frame — the exact
15
+ * signature of a cut connection — into a well-formed event. The streaming path
16
+ * discarded that same frame, as the SSE spec requires. So one lane invented a
17
+ * complete answer where the other saw a broken one. Now both discard it and
18
+ * both RECORD it (`SseReadStatus.truncated`), because "was this reply whole?"
19
+ * is a question the engine has to answer before it runs anything.
12
20
  */
13
21
 
14
- function* parseChunk(buffer) {
22
+ function* parseChunk(buffer, onFrame) {
15
23
  let rest = buffer;
16
24
  let idx;
17
25
  // Frames are separated by a blank line. \r\n\r\n is legal too.
18
26
  while ((idx = rest.search(/\r?\n\r?\n/)) !== -1) {
19
27
  const raw = rest.slice(0, idx);
20
28
  rest = rest.slice(idx + (rest[idx] === "\r" ? 4 : 2));
29
+ onFrame?.();
21
30
  let event;
22
31
  const dataLines = [];
23
32
  for (const line of raw.split(/\r?\n/)) {
@@ -31,53 +40,124 @@ function* parseChunk(buffer) {
31
40
  }
32
41
  return rest;
33
42
  }
34
- export async function* readSse(response) {
43
+
44
+ /**
45
+ * Drain complete frames out of `buffer`, returning what is left over.
46
+ *
47
+ * Shared by both paths so a framing fix can only ever be made in one place.
48
+ */
49
+ function* drain(buffer, out, onFrame) {
50
+ const gen = parseChunk(buffer, onFrame);
51
+ let next = gen.next();
52
+ while (!next.done) {
53
+ yield next.value;
54
+ next = gen.next();
55
+ }
56
+ out.rest = next.value;
57
+ }
58
+
59
+ /**
60
+ * Turn a stream of TEXT chunks into SSE frames.
61
+ *
62
+ * The one place framing happens, whatever produced the bytes: a `fetch` body
63
+ * reader, an `XMLHttpRequest` progress slice, or a whole body read at once on
64
+ * a runtime that cannot stream. Splitting it out is what lets the XHR
65
+ * transport exist without a second parser to keep in step with this one.
66
+ */
67
+ export async function* framesFrom(chunks, options = {}) {
68
+ const {
69
+ status,
70
+ onFrame
71
+ } = options;
72
+ const leftover = {
73
+ rest: ""
74
+ };
75
+ let buffer = "";
76
+ for await (const chunk of chunks) {
77
+ buffer += chunk;
78
+ yield* drain(buffer, leftover, onFrame);
79
+ buffer = leftover.rest;
80
+ }
81
+ if (status && leftover.rest.trim()) status.truncated = true;
82
+ }
83
+ export async function* readSse(response, options = {}) {
84
+ const {
85
+ status,
86
+ onFrame,
87
+ signal
88
+ } = options;
35
89
  const body = response.body;
90
+ const leftover = {
91
+ rest: ""
92
+ };
36
93
  if (!body || typeof body.getReader !== "function") {
37
- // No streaming on this platform — read it all, then replay.
94
+ // No streaming on this platform — read it all, then replay. Note there is
95
+ // no "\n\n" here any more: an unterminated tail is discarded exactly as
96
+ // the streaming path discards it (see the header).
38
97
  const text = await response.text();
39
- let rest = "";
40
- const gen = parseChunk(text + "\n\n");
41
- let next = gen.next();
42
- while (!next.done) {
43
- yield next.value;
44
- next = gen.next();
45
- }
46
- rest = next.value;
47
- if (rest.trim()) {
48
- const tail = parseChunk(rest + "\n\n");
49
- let t = tail.next();
50
- while (!t.done) {
51
- yield t.value;
52
- t = tail.next();
53
- }
54
- }
98
+ yield* drain(text, leftover, onFrame);
99
+ if (status && leftover.rest.trim()) status.truncated = true;
55
100
  return;
56
101
  }
57
102
  const reader = body.getReader();
58
103
  const decoder = new TextDecoder();
59
104
  let buffer = "";
105
+ let finished = false;
106
+ /**
107
+ * One promise for the whole read, not one per chunk.
108
+ *
109
+ * It never resolves — only rejects — so racing it is free apart from the
110
+ * `Promise.race` allocation, and an answer of a few hundred frames pays far
111
+ * more for `JSON.parse` than for this.
112
+ */
113
+ const aborted = signal ? new Promise((_resolve, reject) => {
114
+ const fail = () => {
115
+ const err = new Error("Aborted");
116
+ err.name = "AbortError";
117
+ reject(err);
118
+ };
119
+ if (signal.aborted) fail();else signal.addEventListener?.("abort", fail, {
120
+ once: true
121
+ });
122
+ }) : undefined;
123
+ // Nothing awaits this until the race below, and a rejection with no handler
124
+ // is an unhandled rejection on some runtimes. This is the handler.
125
+ aborted?.catch(() => {});
60
126
  try {
61
127
  for (;;) {
128
+ const read = reader.read();
62
129
  const {
63
130
  done,
64
131
  value
65
- } = await reader.read();
132
+ } = aborted ? await Promise.race([read, aborted]) : await read;
66
133
  if (done) break;
67
134
  buffer += decoder.decode(value, {
68
135
  stream: true
69
136
  });
70
- const gen = parseChunk(buffer);
71
- let next = gen.next();
72
- while (!next.done) {
73
- yield next.value;
74
- next = gen.next();
75
- }
76
- buffer = next.value;
137
+ yield* drain(buffer, leftover, onFrame);
138
+ buffer = leftover.rest;
77
139
  }
140
+ // Flush the decoder: a multi-byte character split across the last two
141
+ // chunks is only completed here, and an INCOMPLETE one at EOF is itself
142
+ // evidence the connection was cut.
143
+ buffer += decoder.decode();
144
+ yield* drain(buffer, leftover, onFrame);
145
+ if (status && leftover.rest.trim()) status.truncated = true;
146
+ finished = true;
78
147
  } finally {
79
- // Cancelling on abort keeps the socket from lingering after the user
80
- // closes the sheet mid-answer.
148
+ if (!finished) {
149
+ // The consumer left early — an abort, a timeout, or a `break` in the
150
+ // provider. `releaseLock` alone leaves the socket open; only `cancel`
151
+ // tears the request down, and it must come first because cancelling a
152
+ // locked reader is the only way to reach the underlying stream.
153
+ try {
154
+ // Not awaited: the consumer is already leaving, and a cancel that
155
+ // rejects (an errored stream) must not become an unhandled rejection.
156
+ void Promise.resolve(reader.cancel()).catch(() => {});
157
+ } catch {
158
+ /* already cancelled or errored */
159
+ }
160
+ }
81
161
  try {
82
162
  reader.releaseLock();
83
163
  } catch {
@@ -86,6 +166,33 @@ export async function* readSse(response) {
86
166
  }
87
167
  }
88
168
 
169
+ /**
170
+ * A 200 that is not a stream at all.
171
+ *
172
+ * Gateways in front of a model do this: an auth proxy that has lost its
173
+ * upstream serves an HTML error page, a misrouted path serves an SPA shell,
174
+ * and a gateway that ignored `stream: true` serves one JSON object. Every one
175
+ * of those parses to zero SSE frames, so the old code read it as a model that
176
+ * had nothing to say and ended the turn with a blank bubble.
177
+ *
178
+ * Returns a message when the body should be treated as an error, and undefined
179
+ * when it looks like something the SSE reader can work with. Consumes the body
180
+ * only in the failing case.
181
+ */
182
+ export async function nonStreamProblem(response) {
183
+ const type = response.headers?.get?.("content-type") ?? "";
184
+ if (!type) return undefined; // No header to judge by — let the parser try.
185
+ const lowered = type.toLowerCase();
186
+ if (lowered.includes("event-stream")) return undefined;
187
+ // A JSON body is either a non-streaming reply or a structured error; both
188
+ // are worth reporting with their own text rather than guessing.
189
+ const detail = (await response.text().catch(() => "")).slice(0, 600);
190
+ if (lowered.includes("json")) {
191
+ return `The endpoint answered with JSON instead of a stream — it may not support "stream": true.${detail ? ` — ${detail}` : ""}`;
192
+ }
193
+ return `The endpoint answered with ${type} instead of an event stream.${detail ? ` — ${detail}` : ""}`;
194
+ }
195
+
89
196
  /** Body text for a failed response, trimmed to something a user can read. */
90
197
  export async function errorBody(response) {
91
198
  let detail = "";
@@ -96,4 +203,28 @@ export async function errorBody(response) {
96
203
  }
97
204
  return `HTTP ${response.status}${detail ? ` — ${detail}` : ""}`;
98
205
  }
206
+
207
+ /**
208
+ * The message for a stream that stopped before the provider said it was done.
209
+ *
210
+ * `truncated` distinguishes the two shapes: cut mid-frame (a dropped
211
+ * connection) versus a clean frame boundary with no terminal marker (a gateway
212
+ * that closes the socket instead of sending one). The second is a
213
+ * compatibility problem worth naming, because retrying it will not help.
214
+ */
215
+ export function truncatedMessage(truncated) {
216
+ return truncated ? "The connection dropped before the answer finished." : "The endpoint closed the stream without saying the answer was finished.";
217
+ }
218
+
219
+ /**
220
+ * The message for arguments that would not parse, with enough in it to act on.
221
+ * `stopReason` "length" is the common cause — a reasoning model spends its
222
+ * budget thinking and the tool call is truncated mid-JSON — and the tail of
223
+ * the raw arguments says immediately whether that is what happened.
224
+ */
225
+ export function unparseableMessage(name, args, stopReason) {
226
+ const truncated = stopReason === "length";
227
+ const tail = args.length > 160 ? `…${args.slice(-160)}` : args;
228
+ return `Model sent unparseable arguments for ${name}` + (truncated ? " (cut off at max_tokens — raise it or reduce thinking budget)" : "") + ` [stop: ${stopReason ?? "none"}, ${args.length} chars] ${tail}`;
229
+ }
99
230
  //# sourceMappingURL=sse.js.map