@buoy-gg/agent-core 7.0.35 → 7.0.38

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 (208) hide show
  1. package/README.md +21 -14
  2. package/lib/commonjs/blocks/receipts.js +57 -1
  3. package/lib/commonjs/blocks/receipts.js.map +1 -1
  4. package/lib/commonjs/blocks/types.js +23 -2
  5. package/lib/commonjs/blocks/types.js.map +1 -1
  6. package/lib/commonjs/blocks/uiTool.js +423 -10
  7. package/lib/commonjs/blocks/uiTool.js.map +1 -1
  8. package/lib/commonjs/catalog/catalog.g.js +213 -48
  9. package/lib/commonjs/catalog/catalog.g.js.map +1 -1
  10. package/lib/commonjs/catalog/catalog.source.json +226 -48
  11. package/lib/commonjs/catalog/catalog.types.g.js +44 -0
  12. package/lib/commonjs/catalog/catalog.types.g.js.map +1 -0
  13. package/lib/commonjs/catalog/normalizeParams.js +333 -0
  14. package/lib/commonjs/catalog/normalizeParams.js.map +1 -0
  15. package/lib/commonjs/catalog/signature.js +68 -0
  16. package/lib/commonjs/catalog/signature.js.map +1 -0
  17. package/lib/commonjs/catalog/snapshotReads.js +13 -6
  18. package/lib/commonjs/catalog/snapshotReads.js.map +1 -1
  19. package/lib/commonjs/catalog/toProviderTools.js +44 -6
  20. package/lib/commonjs/catalog/toProviderTools.js.map +1 -1
  21. package/lib/commonjs/context/buildContextPack.js +367 -19
  22. package/lib/commonjs/context/buildContextPack.js.map +1 -1
  23. package/lib/commonjs/effects/digest.js +34 -0
  24. package/lib/commonjs/effects/digest.js.map +1 -0
  25. package/lib/commonjs/effects/ledger.js +98 -2
  26. package/lib/commonjs/effects/ledger.js.map +1 -1
  27. package/lib/commonjs/engine/askGate.js +287 -0
  28. package/lib/commonjs/engine/askGate.js.map +1 -0
  29. package/lib/commonjs/engine/effectFor.js +82 -1
  30. package/lib/commonjs/engine/effectFor.js.map +1 -1
  31. package/lib/commonjs/engine/evidence.js +113 -0
  32. package/lib/commonjs/engine/evidence.js.map +1 -0
  33. package/lib/commonjs/engine/historyBudget.js +363 -0
  34. package/lib/commonjs/engine/historyBudget.js.map +1 -0
  35. package/lib/commonjs/engine/retrieve.js +214 -0
  36. package/lib/commonjs/engine/retrieve.js.map +1 -0
  37. package/lib/commonjs/engine/runAgentTurn.js +1231 -120
  38. package/lib/commonjs/engine/runAgentTurn.js.map +1 -1
  39. package/lib/commonjs/engine/systemPrompt.js +103 -9
  40. package/lib/commonjs/engine/systemPrompt.js.map +1 -1
  41. package/lib/commonjs/engine/textToolCalls.js +276 -0
  42. package/lib/commonjs/engine/textToolCalls.js.map +1 -0
  43. package/lib/commonjs/engine/tokenCalibration.js +81 -0
  44. package/lib/commonjs/engine/tokenCalibration.js.map +1 -0
  45. package/lib/commonjs/engine/verify.js +300 -0
  46. package/lib/commonjs/engine/verify.js.map +1 -0
  47. package/lib/commonjs/index.js +74 -0
  48. package/lib/commonjs/index.js.map +1 -1
  49. package/lib/commonjs/policy/labels.js +19 -3
  50. package/lib/commonjs/policy/labels.js.map +1 -1
  51. package/lib/commonjs/policy/policy.js +6 -1
  52. package/lib/commonjs/policy/policy.js.map +1 -1
  53. package/lib/commonjs/policy/redact.js +42 -5
  54. package/lib/commonjs/policy/redact.js.map +1 -1
  55. package/lib/commonjs/providers/anthropic.js +340 -208
  56. package/lib/commonjs/providers/anthropic.js.map +1 -1
  57. package/lib/commonjs/providers/openai.js +237 -103
  58. package/lib/commonjs/providers/openai.js.map +1 -1
  59. package/lib/commonjs/providers/problem.js +98 -0
  60. package/lib/commonjs/providers/problem.js.map +1 -0
  61. package/lib/commonjs/providers/sse.js +170 -34
  62. package/lib/commonjs/providers/sse.js.map +1 -1
  63. package/lib/commonjs/providers/streamTimer.js +123 -0
  64. package/lib/commonjs/providers/streamTimer.js.map +1 -0
  65. package/lib/commonjs/providers/transport.js +123 -0
  66. package/lib/commonjs/providers/transport.js.map +1 -0
  67. package/lib/commonjs/providers/xhrStream.js +212 -0
  68. package/lib/commonjs/providers/xhrStream.js.map +1 -0
  69. package/lib/commonjs/session.js +242 -58
  70. package/lib/commonjs/session.js.map +1 -1
  71. package/lib/module/blocks/receipts.js +57 -1
  72. package/lib/module/blocks/receipts.js.map +1 -1
  73. package/lib/module/blocks/types.js +23 -2
  74. package/lib/module/blocks/types.js.map +1 -1
  75. package/lib/module/blocks/uiTool.js +421 -10
  76. package/lib/module/blocks/uiTool.js.map +1 -1
  77. package/lib/module/catalog/catalog.g.js +213 -48
  78. package/lib/module/catalog/catalog.g.js.map +1 -1
  79. package/lib/module/catalog/catalog.source.json +226 -48
  80. package/lib/module/catalog/catalog.types.g.js +40 -0
  81. package/lib/module/catalog/catalog.types.g.js.map +1 -0
  82. package/lib/module/catalog/normalizeParams.js +327 -0
  83. package/lib/module/catalog/normalizeParams.js.map +1 -0
  84. package/lib/module/catalog/signature.js +63 -0
  85. package/lib/module/catalog/signature.js.map +1 -0
  86. package/lib/module/catalog/snapshotReads.js +13 -6
  87. package/lib/module/catalog/snapshotReads.js.map +1 -1
  88. package/lib/module/catalog/toProviderTools.js +44 -6
  89. package/lib/module/catalog/toProviderTools.js.map +1 -1
  90. package/lib/module/context/buildContextPack.js +366 -19
  91. package/lib/module/context/buildContextPack.js.map +1 -1
  92. package/lib/module/effects/digest.js +29 -0
  93. package/lib/module/effects/digest.js.map +1 -0
  94. package/lib/module/effects/ledger.js +98 -2
  95. package/lib/module/effects/ledger.js.map +1 -1
  96. package/lib/module/engine/askGate.js +280 -0
  97. package/lib/module/engine/askGate.js.map +1 -0
  98. package/lib/module/engine/effectFor.js +83 -1
  99. package/lib/module/engine/effectFor.js.map +1 -1
  100. package/lib/module/engine/evidence.js +107 -0
  101. package/lib/module/engine/evidence.js.map +1 -0
  102. package/lib/module/engine/historyBudget.js +355 -0
  103. package/lib/module/engine/historyBudget.js.map +1 -0
  104. package/lib/module/engine/retrieve.js +210 -0
  105. package/lib/module/engine/retrieve.js.map +1 -0
  106. package/lib/module/engine/runAgentTurn.js +1227 -121
  107. package/lib/module/engine/runAgentTurn.js.map +1 -1
  108. package/lib/module/engine/systemPrompt.js +101 -9
  109. package/lib/module/engine/systemPrompt.js.map +1 -1
  110. package/lib/module/engine/textToolCalls.js +270 -0
  111. package/lib/module/engine/textToolCalls.js.map +1 -0
  112. package/lib/module/engine/tokenCalibration.js +75 -0
  113. package/lib/module/engine/tokenCalibration.js.map +1 -0
  114. package/lib/module/engine/verify.js +292 -0
  115. package/lib/module/engine/verify.js.map +1 -0
  116. package/lib/module/index.js +7 -3
  117. package/lib/module/index.js.map +1 -1
  118. package/lib/module/policy/labels.js +19 -3
  119. package/lib/module/policy/labels.js.map +1 -1
  120. package/lib/module/policy/policy.js +6 -1
  121. package/lib/module/policy/policy.js.map +1 -1
  122. package/lib/module/policy/redact.js +42 -5
  123. package/lib/module/policy/redact.js.map +1 -1
  124. package/lib/module/providers/anthropic.js +341 -209
  125. package/lib/module/providers/anthropic.js.map +1 -1
  126. package/lib/module/providers/openai.js +238 -104
  127. package/lib/module/providers/openai.js.map +1 -1
  128. package/lib/module/providers/problem.js +92 -0
  129. package/lib/module/providers/problem.js.map +1 -0
  130. package/lib/module/providers/sse.js +166 -34
  131. package/lib/module/providers/sse.js.map +1 -1
  132. package/lib/module/providers/streamTimer.js +118 -0
  133. package/lib/module/providers/streamTimer.js.map +1 -0
  134. package/lib/module/providers/transport.js +119 -0
  135. package/lib/module/providers/transport.js.map +1 -0
  136. package/lib/module/providers/xhrStream.js +207 -0
  137. package/lib/module/providers/xhrStream.js.map +1 -0
  138. package/lib/module/session.js +226 -60
  139. package/lib/module/session.js.map +1 -1
  140. package/lib/typescript/blocks/receipts.d.ts +5 -0
  141. package/lib/typescript/blocks/receipts.d.ts.map +1 -1
  142. package/lib/typescript/blocks/types.d.ts +23 -2
  143. package/lib/typescript/blocks/types.d.ts.map +1 -1
  144. package/lib/typescript/blocks/uiTool.d.ts +11 -2
  145. package/lib/typescript/blocks/uiTool.d.ts.map +1 -1
  146. package/lib/typescript/catalog/catalog.g.d.ts +2 -2
  147. package/lib/typescript/catalog/catalog.g.d.ts.map +1 -1
  148. package/lib/typescript/catalog/catalog.types.g.d.ts +40 -0
  149. package/lib/typescript/catalog/catalog.types.g.d.ts.map +1 -0
  150. package/lib/typescript/catalog/normalizeParams.d.ts +43 -0
  151. package/lib/typescript/catalog/normalizeParams.d.ts.map +1 -0
  152. package/lib/typescript/catalog/signature.d.ts +29 -0
  153. package/lib/typescript/catalog/signature.d.ts.map +1 -0
  154. package/lib/typescript/catalog/snapshotReads.d.ts.map +1 -1
  155. package/lib/typescript/catalog/toProviderTools.d.ts +28 -15
  156. package/lib/typescript/catalog/toProviderTools.d.ts.map +1 -1
  157. package/lib/typescript/context/buildContextPack.d.ts +24 -2
  158. package/lib/typescript/context/buildContextPack.d.ts.map +1 -1
  159. package/lib/typescript/effects/digest.d.ts +10 -0
  160. package/lib/typescript/effects/digest.d.ts.map +1 -0
  161. package/lib/typescript/effects/ledger.d.ts +73 -0
  162. package/lib/typescript/effects/ledger.d.ts.map +1 -1
  163. package/lib/typescript/engine/askGate.d.ts +29 -0
  164. package/lib/typescript/engine/askGate.d.ts.map +1 -0
  165. package/lib/typescript/engine/effectFor.d.ts +6 -1
  166. package/lib/typescript/engine/effectFor.d.ts.map +1 -1
  167. package/lib/typescript/engine/evidence.d.ts +67 -0
  168. package/lib/typescript/engine/evidence.d.ts.map +1 -0
  169. package/lib/typescript/engine/historyBudget.d.ts +115 -0
  170. package/lib/typescript/engine/historyBudget.d.ts.map +1 -0
  171. package/lib/typescript/engine/retrieve.d.ts +32 -0
  172. package/lib/typescript/engine/retrieve.d.ts.map +1 -0
  173. package/lib/typescript/engine/runAgentTurn.d.ts +179 -3
  174. package/lib/typescript/engine/runAgentTurn.d.ts.map +1 -1
  175. package/lib/typescript/engine/systemPrompt.d.ts +80 -0
  176. package/lib/typescript/engine/systemPrompt.d.ts.map +1 -1
  177. package/lib/typescript/engine/textToolCalls.d.ts +58 -0
  178. package/lib/typescript/engine/textToolCalls.d.ts.map +1 -0
  179. package/lib/typescript/engine/tokenCalibration.d.ts +46 -0
  180. package/lib/typescript/engine/tokenCalibration.d.ts.map +1 -0
  181. package/lib/typescript/engine/verify.d.ts +67 -0
  182. package/lib/typescript/engine/verify.d.ts.map +1 -0
  183. package/lib/typescript/index.d.ts +7 -3
  184. package/lib/typescript/index.d.ts.map +1 -1
  185. package/lib/typescript/policy/labels.d.ts.map +1 -1
  186. package/lib/typescript/policy/policy.d.ts.map +1 -1
  187. package/lib/typescript/policy/redact.d.ts.map +1 -1
  188. package/lib/typescript/providers/anthropic.d.ts.map +1 -1
  189. package/lib/typescript/providers/openai.d.ts +0 -16
  190. package/lib/typescript/providers/openai.d.ts.map +1 -1
  191. package/lib/typescript/providers/problem.d.ts +50 -0
  192. package/lib/typescript/providers/problem.d.ts.map +1 -0
  193. package/lib/typescript/providers/sse.d.ts +86 -2
  194. package/lib/typescript/providers/sse.d.ts.map +1 -1
  195. package/lib/typescript/providers/streamTimer.d.ts +59 -0
  196. package/lib/typescript/providers/streamTimer.d.ts.map +1 -0
  197. package/lib/typescript/providers/transport.d.ts +48 -0
  198. package/lib/typescript/providers/transport.d.ts.map +1 -0
  199. package/lib/typescript/providers/types.d.ts +105 -3
  200. package/lib/typescript/providers/types.d.ts.map +1 -1
  201. package/lib/typescript/providers/xhrStream.d.ts +45 -0
  202. package/lib/typescript/providers/xhrStream.d.ts.map +1 -0
  203. package/lib/typescript/session.d.ts +55 -4
  204. package/lib/typescript/session.d.ts.map +1 -1
  205. package/lib/typescript/types.d.ts +6 -0
  206. package/lib/typescript/types.d.ts.map +1 -1
  207. package/package.json +10 -10
  208. package/LICENSE +0 -58
@@ -5,6 +5,9 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.createOpenAIProvider = createOpenAIProvider;
7
7
  var _sse = require("./sse");
8
+ var _streamTimer = require("./streamTimer");
9
+ var _transport = require("./transport");
10
+ var _problem = require("./problem");
8
11
  /**
9
12
  * OpenAI chat-completions protocol.
10
13
  *
@@ -20,6 +23,19 @@ var _sse = require("./sse");
20
23
  * is the common shape for an internal LLM proxy. Note Anthropic's own
21
24
  * OpenAI-compatibility endpoint is explicitly not production-ready and silently
22
25
  * ignores several fields — use the native Anthropic adapter for Anthropic.
26
+ *
27
+ * THE 1024-CHAR TRAP. Azure caps a function description at 1024 chars, so
28
+ * this adapter trims to fit. The catalog renders a tool's summary FIRST and
29
+ * its `Actions:` list LAST, and every tool's full description is longer than
30
+ * the cap — so trimming `t.description` silently removed every action line
31
+ * for 23 of the 24 tools — the 24th kept one line of sixteen — measured
32
+ * against the catalog as it is. A model on this protocol (api.openai.com, Azure,
33
+ * OpenRouter, fal — every row of the model-floor sweep) saw a summary cut
34
+ * mid-sentence and a bare `action` enum: no per-action summary, no
35
+ * [DESTRUCTIVE] / [changes state] tag, no "prefer X over Y" guidance, and a
36
+ * catalog wording change could not move its score. So the description is
37
+ * the SUMMARY only, and the `Actions:` block goes into
38
+ * `parameters.properties.action.description`, which nothing caps.
23
39
  */
24
40
 
25
41
  function toWireMessages(system, messages) {
@@ -61,132 +77,250 @@ function toWireMessages(system, messages) {
61
77
  }
62
78
  return out;
63
79
  }
80
+
81
+ /**
82
+ * The tool's input schema with the `Actions:` block on the `action`
83
+ * property — the uncapped home for the per-action lines (header note).
84
+ */
85
+ function withActionsBlock(t) {
86
+ const action = t.inputSchema.properties.action;
87
+ return {
88
+ ...t.inputSchema,
89
+ properties: {
90
+ ...t.inputSchema.properties,
91
+ action: {
92
+ ...action,
93
+ description: `Which action to run.\n\n${t.actionsBlock}`
94
+ }
95
+ }
96
+ };
97
+ }
64
98
  function createOpenAIProvider(config) {
99
+ // One per provider, so the `auto` transport decision is made once and not
100
+ // re-learned (and re-buffered) at the start of every turn.
101
+ const transport = (0, _transport.createTransport)(config);
65
102
  return {
66
103
  protocol: "openai",
67
104
  async *send(req) {
68
- const headers = {
69
- "content-type": "application/json",
70
- ...(await (config.headers?.() ?? {}))
105
+ const timer = (0, _streamTimer.createStreamTimer)(req.signal, config);
106
+ const status = {
107
+ truncated: false
71
108
  };
72
- if (config.apiKey && !headers.Authorization && !headers["api-key"]) {
73
- headers.Authorization = `Bearer ${config.apiKey}`;
74
- }
75
- const response = await fetch(config.endpoint, {
76
- method: "POST",
77
- headers,
78
- signal: req.signal,
79
- body: JSON.stringify({
80
- model: req.model,
81
- max_tokens: req.maxTokens,
82
- stream: true,
83
- stream_options: {
84
- include_usage: true
85
- },
86
- messages: toWireMessages(req.system, req.messages),
87
- tools: req.tools.map(t => ({
88
- type: "function",
89
- function: {
90
- name: t.name,
91
- // Azure caps function descriptions at 1024 chars while Anthropic's
92
- // guidance asks for several sentences. Trim rather than 400.
93
- description: t.description.slice(0, 1024),
94
- parameters: t.inputSchema
95
- }
96
- })),
97
- ...config.requestOverrides
98
- })
99
- });
100
- if (!response.ok) {
101
- yield {
102
- type: "error",
103
- message: await (0, _sse.errorBody)(response)
109
+ try {
110
+ const headers = {
111
+ "content-type": "application/json",
112
+ ...(await (config.headers?.() ?? {}))
104
113
  };
105
- return;
106
- }
114
+ if (config.apiKey && !headers.Authorization && !headers["api-key"]) {
115
+ headers.Authorization = `Bearer ${config.apiKey}`;
116
+ }
117
+ const stream = await transport.open({
118
+ headers,
119
+ // The timer's signal, not the caller's: it aborts on the user's Stop
120
+ // AND on either clock running out. See providers/streamTimer.ts.
121
+ signal: timer.signal,
122
+ body: JSON.stringify({
123
+ model: req.model,
124
+ max_tokens: req.maxTokens,
125
+ stream: true,
126
+ stream_options: {
127
+ include_usage: true
128
+ },
129
+ messages: toWireMessages(req.systemVolatile ? `${req.system}\n\n---\n\n${req.systemVolatile}` : req.system, req.messages),
130
+ tools: req.tools.map(t => ({
131
+ type: "function",
132
+ function: {
133
+ name: t.name,
134
+ // Azure caps function descriptions at 1024 chars while Anthropic's
135
+ // guidance asks for several sentences. Trim rather than 400 — but
136
+ // trim the SUMMARY only: the action lines travel on `parameters`
137
+ // (withActionsBlock), where nothing is capped. See the header.
138
+ description: t.summaryDescription.slice(0, 1024),
139
+ parameters: withActionsBlock(t)
140
+ }
141
+ })),
142
+ ...config.requestOverrides
143
+ })
144
+ });
145
+
146
+ // Headers are in: the connect clock stops here and the idle one starts.
147
+ timer.connected();
148
+ if (stream.problem) {
149
+ yield {
150
+ type: "error",
151
+ message: stream.problem,
152
+ kind: "provider",
153
+ problem: stream.problemInfo
154
+ };
155
+ return;
156
+ }
107
157
 
108
- // Keyed by the stream's `index`; id and name arrive only on the first
109
- // fragment, arguments accumulate across all of them.
110
- const pending = new Map();
111
- let stopReason;
112
- let usage;
113
- const flush = function* () {
114
- for (const [, slot] of pending) {
115
- let input = {};
158
+ // Keyed by the stream's `index`; id and name arrive only on the first
159
+ // fragment, arguments accumulate across all of them.
160
+ const pending = new Map();
161
+ let stopReason;
162
+ let usage;
163
+ // The served model id, from the first chunk that names one. A gateway
164
+ // resolves `gpt-4.1` to a dated snapshot, and that is the id a cost
165
+ // table or a benchmark has to attribute a drift to.
166
+ let model;
167
+ /** The `[DONE]` sentinel; ends the read. See `sawTerminal` below. */
168
+ let sawDone = false;
169
+ const flush = function* () {
170
+ for (const [, slot] of pending) {
171
+ let input = {};
172
+ try {
173
+ input = slot.args ? JSON.parse(slot.args) : {};
174
+ } catch {
175
+ yield {
176
+ type: "error",
177
+ kind: "provider",
178
+ // Carry the evidence. Without it this error says only THAT the
179
+ // arguments were bad, and diagnosing it needs a live repro of a
180
+ // model that may not be reachable any more — a Sonnet bench run
181
+ // produced 15 of these and left nothing to read. `length` here
182
+ // means the model was cut off mid-argument and `max_tokens` is
183
+ // the fix; anything else is a genuinely malformed stream.
184
+ message: (0, _sse.unparseableMessage)(slot.name, slot.args, stopReason)
185
+ };
186
+ continue;
187
+ }
188
+ yield {
189
+ type: "tool-call",
190
+ call: {
191
+ id: slot.id,
192
+ name: slot.name,
193
+ input
194
+ }
195
+ };
196
+ }
197
+ pending.clear();
198
+ };
199
+ for await (const ev of stream.frames({
200
+ status,
201
+ onFrame: timer.activity,
202
+ signal: timer.signal
203
+ })) {
204
+ if (ev.data === "[DONE]") {
205
+ sawDone = true;
206
+ break;
207
+ }
208
+ let payload;
116
209
  try {
117
- input = slot.args ? JSON.parse(slot.args) : {};
210
+ payload = JSON.parse(ev.data);
118
211
  } catch {
212
+ continue;
213
+ }
214
+ if (payload.error) {
215
+ const err = payload.error;
216
+ const message = err.message ?? "Provider error";
217
+ const type = typeof err.code === "string" ? err.code : typeof err.type === "string" ? err.type : undefined;
119
218
  yield {
120
219
  type: "error",
121
- message: `Model sent unparseable arguments for ${slot.name}`
220
+ message,
221
+ kind: "provider",
222
+ problem: (0, _problem.classifyProblem)({
223
+ type,
224
+ message
225
+ })
122
226
  };
123
- continue;
227
+ return;
228
+ }
229
+ if (!model && typeof payload.model === "string" && payload.model) model = payload.model;
230
+ const u = payload.usage;
231
+ if (u) {
232
+ // `prompt_tokens_details.cached_tokens` is this protocol's cache
233
+ // counter. Unlike Anthropic's it is INCLUDED in `prompt_tokens`
234
+ // rather than reported beside it; it is still carried as
235
+ // `cacheRead` so a cost table can price that slice at the
236
+ // discounted rate.
237
+ const details = u.prompt_tokens_details;
238
+ const cached = details?.cached_tokens;
239
+ usage = {
240
+ input: typeof u.prompt_tokens === "number" ? u.prompt_tokens : 0,
241
+ output: typeof u.completion_tokens === "number" ? u.completion_tokens : 0,
242
+ ...(typeof cached === "number" ? {
243
+ cacheRead: cached
244
+ } : {})
245
+ };
246
+ }
247
+ const choice = payload.choices?.[0];
248
+ if (!choice) continue;
249
+ if (choice.finish_reason) stopReason = choice.finish_reason;
250
+ const delta = choice.delta;
251
+ if (typeof delta?.content === "string" && delta.content) {
252
+ yield {
253
+ type: "text",
254
+ delta: delta.content
255
+ };
256
+ }
257
+ const calls = delta?.tool_calls;
258
+ for (const c of calls ?? []) {
259
+ const index = c.index ?? 0;
260
+ const fn = c.function;
261
+ const slot = pending.get(index) ?? {
262
+ id: "",
263
+ name: "",
264
+ args: ""
265
+ };
266
+ if (c.id) slot.id = c.id;
267
+ if (fn?.name) slot.name = fn.name;
268
+ if (typeof fn?.arguments === "string") slot.args += fn.arguments;
269
+ pending.set(index, slot);
124
270
  }
125
- yield {
126
- type: "tool-call",
127
- call: {
128
- id: slot.id,
129
- name: slot.name,
130
- input
131
- }
132
- };
133
- }
134
- pending.clear();
135
- };
136
- for await (const ev of (0, _sse.readSse)(response)) {
137
- if (ev.data === "[DONE]") break;
138
- let payload;
139
- try {
140
- payload = JSON.parse(ev.data);
141
- } catch {
142
- continue;
143
271
  }
144
- if (payload.error) {
145
- const err = payload.error;
272
+
273
+ /**
274
+ * Did the provider actually say it was finished?
275
+ *
276
+ * `[DONE]` is the transport sentinel. `finish_reason` counts too, and is
277
+ * the stronger claim: it is the model's own statement of why it stopped,
278
+ * while `[DONE]` only says the SSE stream closed. Plenty of
279
+ * OpenAI-compatible gateways send one and not the other, and refusing
280
+ * either shape would break working endpoints for no safety gain. NEITHER
281
+ * arriving is the case that matters — bare EOF, which used to be read as
282
+ * success, and which is how a complete-looking `storage.setItem` came out
283
+ * of a cut connection and ran.
284
+ */
285
+ const sawTerminal = sawDone || stopReason !== undefined;
286
+ if (!sawTerminal) {
287
+ // Nothing is flushed: the accumulated arguments may be a whole JSON
288
+ // object and still be half a plan. Text already yielded stays on
289
+ // screen; the engine shows it and offers Continue.
146
290
  yield {
147
291
  type: "error",
148
- message: err.message ?? "Provider error"
292
+ message: (0, _sse.truncatedMessage)(status.truncated),
293
+ kind: "truncated"
149
294
  };
150
295
  return;
151
296
  }
152
- const u = payload.usage;
153
- if (u) {
154
- usage = {
155
- input: u.prompt_tokens ?? 0,
156
- output: u.completion_tokens ?? 0
157
- };
158
- }
159
- const choice = payload.choices?.[0];
160
- if (!choice) continue;
161
- if (choice.finish_reason) stopReason = choice.finish_reason;
162
- const delta = choice.delta;
163
- if (typeof delta?.content === "string" && delta.content) {
297
+ yield* flush();
298
+ yield {
299
+ type: "done",
300
+ outcome: stopReason === "length" ? "output-limited" : "completed",
301
+ stopReason,
302
+ usage,
303
+ model
304
+ };
305
+ } catch (err) {
306
+ // The user's Stop wins the label even if a clock fired in the same
307
+ // tick: they know why the turn ended, and "timed out" would be a lie.
308
+ if (req.signal?.aborted) throw err;
309
+ const message = timer.message();
310
+ if (message) {
164
311
  yield {
165
- type: "text",
166
- delta: delta.content
167
- };
168
- }
169
- const calls = delta?.tool_calls;
170
- for (const c of calls ?? []) {
171
- const index = c.index ?? 0;
172
- const fn = c.function;
173
- const slot = pending.get(index) ?? {
174
- id: "",
175
- name: "",
176
- args: ""
312
+ type: "error",
313
+ message,
314
+ kind: "timeout"
177
315
  };
178
- if (c.id) slot.id = c.id;
179
- if (fn?.name) slot.name = fn.name;
180
- if (typeof fn?.arguments === "string") slot.args += fn.arguments;
181
- pending.set(index, slot);
316
+ return;
182
317
  }
318
+ // A genuine transport failure — DNS, refused connection, TLS. It has
319
+ // always propagated to the failed-turn card, and still does.
320
+ throw err;
321
+ } finally {
322
+ timer.dispose();
183
323
  }
184
- yield* flush();
185
- yield {
186
- type: "done",
187
- stopReason,
188
- usage
189
- };
190
324
  }
191
325
  };
192
326
  }
@@ -1 +1 @@
1
- {"version":3,"names":["_sse","require","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","errorBody","pending","Map","stopReason","usage","flush","slot","args","parse","call","clear","ev","readSse","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":";;;;;;AAuBA,IAAAA,IAAA,GAAAC,OAAA;AAvBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAC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ACjE,IAAc;UAC3C,IAAI,OAAOiE,EAAE,EAAEhE,SAAS,KAAK,QAAQ,EAAE2C,IAAI,CAACC,IAAI,IAAIoB,EAAE,CAAChE,SAAS;UAChEsC,OAAO,CAAC4B,GAAG,CAACH,KAAK,EAAEpB,IAAI,CAAC;QAC1B;MACF;MAEA,OAAOD,KAAK,CAAC,CAAC;MACd,MAAM;QAAE7C,IAAI,EAAE,MAAM;QAAE2C,UAAU;QAAEC;MAAM,CAAC;IAC3C;EACF,CAAC;AACH","ignoreList":[]}
1
+ {"version":3,"names":["_sse","require","_streamTimer","_transport","_problem","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","createTransport","protocol","send","req","timer","createStreamTimer","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","problemInfo","pending","Map","stopReason","usage","sawDone","flush","slot","args","parse","unparseableMessage","call","clear","ev","frames","onFrame","activity","data","payload","error","err","code","undefined","classifyProblem","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","truncatedMessage","outcome","aborted","dispose"],"sourceRoot":"../../../src","sources":["providers/openai.ts"],"mappings":";;;;;;AAsCA,IAAAA,IAAA,GAAAC,OAAA;AACA,IAAAC,YAAA,GAAAD,OAAA;AACA,IAAAE,UAAA,GAAAF,OAAA;AACA,IAAAG,QAAA,GAAAH,OAAA;AAzCA;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;;AA0BA,SAASI,cAAcA,C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UACLnB;QACF,CAAC;MACH,CAAC,CAAC,OAAOmC,GAAG,EAAE;QACZ;QACA;QACA,IAAI/C,GAAG,CAACG,MAAM,EAAEqE,OAAO,EAAE,MAAMzB,GAAG;QAClC,MAAMtB,OAAO,GAAGxB,KAAK,CAACwB,OAAO,CAAC,CAAC;QAC/B,IAAIA,OAAO,EAAE;UACX,MAAM;YAAEjD,IAAI,EAAE,OAAO;YAAEiD,OAAO;YAAEC,IAAI,EAAE;UAAU,CAAC;UACjD;QACF;QACA;QACA;QACA,MAAMqB,GAAG;MACX,CAAC,SAAS;QACR9C,KAAK,CAACwE,OAAO,CAAC,CAAC;MACjB;IACF;EACF,CAAC;AACH","ignoreList":[]}
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.classifyProblem = classifyProblem;
7
+ exports.errorTypeOf = errorTypeOf;
8
+ exports.parseRetryAfter = parseRetryAfter;
9
+ /**
10
+ * What kind of failure a provider reported — decided once, from the status,
11
+ * the error type and the message, so the engine can act on the KIND rather
12
+ * than grep a string.
13
+ *
14
+ * Only two kinds are acted on, and both only when nothing has been generated:
15
+ *
16
+ * - `throttled` — 429 / 529 / 503, a `rate_limit_error` or `overloaded_error`
17
+ * frame, or a body that says so. Waiting and asking again is the right move;
18
+ * the request never reached a model.
19
+ * - `overflow` — the provider refused the request as too big. Trimming older
20
+ * history and asking once more is the right move; the proactive budget is
21
+ * an estimate (chars ÷ 4) and JSON tokenizes worse than prose.
22
+ *
23
+ * Everything else — auth, a bad schema, an unknown model, a mid-answer
24
+ * `api_error` — is reported and NOT retried. The phrase lists are the union
25
+ * observed across provider responses by the Strands SDK (harness-sdk
26
+ * `381ab48`, `models/anthropic.ts` + `models/openai/errors.ts`, Apache-2.0),
27
+ * matched case-insensitively on the lowered message.
28
+ */
29
+
30
+ const THROTTLE_STATUSES = new Set([429, 503, 529]);
31
+ const AUTH_STATUSES = new Set([401, 403]);
32
+
33
+ /** Provider error `type` values (Anthropic frames, OpenAI `error.type` / `code`). */
34
+ const THROTTLE_TYPES = new Set(["overloaded_error", "rate_limit_error", "rate_limit_exceeded", "insufficient_quota", "server_overloaded"]);
35
+ const AUTH_TYPES = new Set(["authentication_error", "permission_error", "invalid_api_key"]);
36
+ const OVERFLOW_TYPES = new Set(["request_too_large", "context_length_exceeded"]);
37
+ const THROTTLE_PHRASES = ["rate_limit_exceeded", "rate limit", "too many requests", "overloaded", "capacity", "try again later"];
38
+ const OVERFLOW_PHRASES = [
39
+ // Anthropic
40
+ "prompt is too long", "input too long", "input is too long", "input length exceeds context window", "input and output tokens exceed your context limit",
41
+ // OpenAI and compatible gateways
42
+ "maximum context length", "context_length_exceeded", "too many tokens", "context length", "input is too long for requested model", "input length and `max_tokens` exceed context limit", "too many total text bytes", "exceed customer model maximum"];
43
+ function classifyProblem(input) {
44
+ const lowered = input.message.toLowerCase();
45
+ const type = input.type?.toLowerCase();
46
+ const retryAfterMs = parseRetryAfter(input.retryAfter);
47
+ const withStatus = kind => ({
48
+ kind,
49
+ ...(input.status !== undefined ? {
50
+ status: input.status
51
+ } : {}),
52
+ ...(retryAfterMs !== undefined ? {
53
+ retryAfterMs
54
+ } : {})
55
+ });
56
+ if (input.status !== undefined && AUTH_STATUSES.has(input.status)) return withStatus("auth");
57
+ if (type && AUTH_TYPES.has(type)) return withStatus("auth");
58
+ if (input.status !== undefined && THROTTLE_STATUSES.has(input.status)) return withStatus("throttled");
59
+ if (type && THROTTLE_TYPES.has(type)) return withStatus("throttled");
60
+ if (type && OVERFLOW_TYPES.has(type)) return withStatus("overflow");
61
+ // Overflow before throttling on phrases: "context length" is more specific
62
+ // than "capacity", and a 400 that says both is about the size.
63
+ if (OVERFLOW_PHRASES.some(p => lowered.includes(p))) return withStatus("overflow");
64
+ if (THROTTLE_PHRASES.some(p => lowered.includes(p))) return withStatus("throttled");
65
+ return withStatus("other");
66
+ }
67
+
68
+ /**
69
+ * `Retry-After` is either delay-seconds or an HTTP-date. Anything unparseable
70
+ * or in the past is undefined, so the caller falls back to its own backoff.
71
+ */
72
+ function parseRetryAfter(value) {
73
+ if (!value) return undefined;
74
+ const trimmed = value.trim();
75
+ if (/^\d+$/.test(trimmed)) return Number(trimmed) * 1000;
76
+ const at = Date.parse(trimmed);
77
+ if (Number.isNaN(at)) return undefined;
78
+ const ms = at - Date.now();
79
+ return ms > 0 ? ms : undefined;
80
+ }
81
+
82
+ /**
83
+ * Pull the provider's error `type` out of an error body, for the HTTP path
84
+ * where the body is JSON like `{"error":{"type":"overloaded_error",…}}` or
85
+ * `{"error":{"code":"context_length_exceeded",…}}`. Returns undefined for
86
+ * anything that is not that shape; the message phrases still apply.
87
+ */
88
+ function errorTypeOf(body) {
89
+ try {
90
+ const parsed = JSON.parse(body);
91
+ const err = typeof parsed.error === "object" && parsed.error ? parsed.error : undefined;
92
+ const type = err?.type ?? err?.code ?? parsed.type;
93
+ return typeof type === "string" ? type : undefined;
94
+ } catch {
95
+ return undefined;
96
+ }
97
+ }
98
+ //# sourceMappingURL=problem.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["THROTTLE_STATUSES","Set","AUTH_STATUSES","THROTTLE_TYPES","AUTH_TYPES","OVERFLOW_TYPES","THROTTLE_PHRASES","OVERFLOW_PHRASES","classifyProblem","input","lowered","message","toLowerCase","type","retryAfterMs","parseRetryAfter","retryAfter","withStatus","kind","status","undefined","has","some","p","includes","value","trimmed","trim","test","Number","at","Date","parse","isNaN","ms","now","errorTypeOf","body","parsed","JSON","err","error","code"],"sourceRoot":"../../../src","sources":["providers/problem.ts"],"mappings":";;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAYA,MAAMA,iBAAiB,GAAG,IAAIC,GAAG,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;AAClD,MAAMC,aAAa,GAAG,IAA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