@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.
- package/README.md +10 -7
- package/lib/commonjs/blocks/receipts.js +83 -24
- package/lib/commonjs/blocks/receipts.js.map +1 -1
- package/lib/commonjs/blocks/runId.js +31 -0
- package/lib/commonjs/blocks/runId.js.map +1 -0
- package/lib/commonjs/blocks/types.js +23 -2
- package/lib/commonjs/blocks/types.js.map +1 -1
- package/lib/commonjs/blocks/uiTool.js +426 -12
- package/lib/commonjs/blocks/uiTool.js.map +1 -1
- package/lib/commonjs/catalog/catalog.g.js +121 -43
- package/lib/commonjs/catalog/catalog.g.js.map +1 -1
- package/lib/commonjs/catalog/catalog.source.json +121 -45
- package/lib/commonjs/catalog/catalog.types.g.js +44 -0
- package/lib/commonjs/catalog/catalog.types.g.js.map +1 -0
- package/lib/commonjs/catalog/normalizeParams.js +333 -0
- package/lib/commonjs/catalog/normalizeParams.js.map +1 -0
- package/lib/commonjs/catalog/signature.js +68 -0
- package/lib/commonjs/catalog/signature.js.map +1 -0
- package/lib/commonjs/catalog/snapshotReads.js +13 -6
- package/lib/commonjs/catalog/snapshotReads.js.map +1 -1
- package/lib/commonjs/catalog/toProviderTools.js +41 -5
- package/lib/commonjs/catalog/toProviderTools.js.map +1 -1
- package/lib/commonjs/context/buildContextPack.js +367 -19
- package/lib/commonjs/context/buildContextPack.js.map +1 -1
- package/lib/commonjs/effects/digest.js +34 -0
- package/lib/commonjs/effects/digest.js.map +1 -0
- package/lib/commonjs/effects/ledger.js +85 -1
- package/lib/commonjs/effects/ledger.js.map +1 -1
- package/lib/commonjs/engine/askGate.js +287 -0
- package/lib/commonjs/engine/askGate.js.map +1 -0
- package/lib/commonjs/engine/effectFor.js +82 -1
- package/lib/commonjs/engine/effectFor.js.map +1 -1
- package/lib/commonjs/engine/historyBudget.js +260 -0
- package/lib/commonjs/engine/historyBudget.js.map +1 -0
- package/lib/commonjs/engine/runAgentTurn.js +958 -88
- package/lib/commonjs/engine/runAgentTurn.js.map +1 -1
- package/lib/commonjs/engine/systemPrompt.js +72 -8
- package/lib/commonjs/engine/systemPrompt.js.map +1 -1
- package/lib/commonjs/engine/textToolCalls.js +276 -0
- package/lib/commonjs/engine/textToolCalls.js.map +1 -0
- package/lib/commonjs/index.js +81 -1
- package/lib/commonjs/index.js.map +1 -1
- package/lib/commonjs/policy/labels.js +19 -3
- package/lib/commonjs/policy/labels.js.map +1 -1
- package/lib/commonjs/policy/policy.js +6 -1
- package/lib/commonjs/policy/policy.js.map +1 -1
- package/lib/commonjs/policy/redact.js +42 -5
- package/lib/commonjs/policy/redact.js.map +1 -1
- package/lib/commonjs/providers/anthropic.js +340 -174
- package/lib/commonjs/providers/anthropic.js.map +1 -1
- package/lib/commonjs/providers/openai.js +229 -103
- package/lib/commonjs/providers/openai.js.map +1 -1
- package/lib/commonjs/providers/sse.js +164 -29
- package/lib/commonjs/providers/sse.js.map +1 -1
- package/lib/commonjs/providers/streamTimer.js +123 -0
- package/lib/commonjs/providers/streamTimer.js.map +1 -0
- package/lib/commonjs/providers/transport.js +107 -0
- package/lib/commonjs/providers/transport.js.map +1 -0
- package/lib/commonjs/providers/xhrStream.js +209 -0
- package/lib/commonjs/providers/xhrStream.js.map +1 -0
- package/lib/commonjs/session.js +245 -52
- package/lib/commonjs/session.js.map +1 -1
- package/lib/module/blocks/receipts.js +83 -24
- package/lib/module/blocks/receipts.js.map +1 -1
- package/lib/module/blocks/runId.js +26 -0
- package/lib/module/blocks/runId.js.map +1 -0
- package/lib/module/blocks/types.js +23 -2
- package/lib/module/blocks/types.js.map +1 -1
- package/lib/module/blocks/uiTool.js +424 -12
- package/lib/module/blocks/uiTool.js.map +1 -1
- package/lib/module/catalog/catalog.g.js +121 -43
- package/lib/module/catalog/catalog.g.js.map +1 -1
- package/lib/module/catalog/catalog.source.json +121 -45
- package/lib/module/catalog/catalog.types.g.js +40 -0
- package/lib/module/catalog/catalog.types.g.js.map +1 -0
- package/lib/module/catalog/normalizeParams.js +327 -0
- package/lib/module/catalog/normalizeParams.js.map +1 -0
- package/lib/module/catalog/signature.js +63 -0
- package/lib/module/catalog/signature.js.map +1 -0
- package/lib/module/catalog/snapshotReads.js +13 -6
- package/lib/module/catalog/snapshotReads.js.map +1 -1
- package/lib/module/catalog/toProviderTools.js +41 -5
- package/lib/module/catalog/toProviderTools.js.map +1 -1
- package/lib/module/context/buildContextPack.js +366 -19
- package/lib/module/context/buildContextPack.js.map +1 -1
- package/lib/module/effects/digest.js +29 -0
- package/lib/module/effects/digest.js.map +1 -0
- package/lib/module/effects/ledger.js +85 -1
- package/lib/module/effects/ledger.js.map +1 -1
- package/lib/module/engine/askGate.js +280 -0
- package/lib/module/engine/askGate.js.map +1 -0
- package/lib/module/engine/effectFor.js +83 -1
- package/lib/module/engine/effectFor.js.map +1 -1
- package/lib/module/engine/historyBudget.js +251 -0
- package/lib/module/engine/historyBudget.js.map +1 -0
- package/lib/module/engine/runAgentTurn.js +954 -88
- package/lib/module/engine/runAgentTurn.js.map +1 -1
- package/lib/module/engine/systemPrompt.js +71 -8
- package/lib/module/engine/systemPrompt.js.map +1 -1
- package/lib/module/engine/textToolCalls.js +270 -0
- package/lib/module/engine/textToolCalls.js.map +1 -0
- package/lib/module/index.js +7 -4
- package/lib/module/index.js.map +1 -1
- package/lib/module/policy/labels.js +19 -3
- package/lib/module/policy/labels.js.map +1 -1
- package/lib/module/policy/policy.js +6 -1
- package/lib/module/policy/policy.js.map +1 -1
- package/lib/module/policy/redact.js +42 -5
- package/lib/module/policy/redact.js.map +1 -1
- package/lib/module/providers/anthropic.js +341 -175
- package/lib/module/providers/anthropic.js.map +1 -1
- package/lib/module/providers/openai.js +230 -104
- package/lib/module/providers/openai.js.map +1 -1
- package/lib/module/providers/sse.js +160 -29
- package/lib/module/providers/sse.js.map +1 -1
- package/lib/module/providers/streamTimer.js +118 -0
- package/lib/module/providers/streamTimer.js.map +1 -0
- package/lib/module/providers/transport.js +103 -0
- package/lib/module/providers/transport.js.map +1 -0
- package/lib/module/providers/xhrStream.js +204 -0
- package/lib/module/providers/xhrStream.js.map +1 -0
- package/lib/module/session.js +228 -54
- package/lib/module/session.js.map +1 -1
- package/lib/typescript/blocks/receipts.d.ts +5 -10
- package/lib/typescript/blocks/receipts.d.ts.map +1 -1
- package/lib/typescript/blocks/runId.d.ts +20 -0
- package/lib/typescript/blocks/runId.d.ts.map +1 -0
- package/lib/typescript/blocks/types.d.ts +23 -2
- package/lib/typescript/blocks/types.d.ts.map +1 -1
- package/lib/typescript/blocks/uiTool.d.ts +11 -2
- package/lib/typescript/blocks/uiTool.d.ts.map +1 -1
- package/lib/typescript/catalog/catalog.g.d.ts.map +1 -1
- package/lib/typescript/catalog/catalog.types.g.d.ts +40 -0
- package/lib/typescript/catalog/catalog.types.g.d.ts.map +1 -0
- package/lib/typescript/catalog/normalizeParams.d.ts +43 -0
- package/lib/typescript/catalog/normalizeParams.d.ts.map +1 -0
- package/lib/typescript/catalog/signature.d.ts +29 -0
- package/lib/typescript/catalog/signature.d.ts.map +1 -0
- package/lib/typescript/catalog/snapshotReads.d.ts.map +1 -1
- package/lib/typescript/catalog/toProviderTools.d.ts +28 -15
- package/lib/typescript/catalog/toProviderTools.d.ts.map +1 -1
- package/lib/typescript/context/buildContextPack.d.ts +24 -2
- package/lib/typescript/context/buildContextPack.d.ts.map +1 -1
- package/lib/typescript/effects/digest.d.ts +10 -0
- package/lib/typescript/effects/digest.d.ts.map +1 -0
- package/lib/typescript/effects/ledger.d.ts +55 -0
- package/lib/typescript/effects/ledger.d.ts.map +1 -1
- package/lib/typescript/engine/askGate.d.ts +29 -0
- package/lib/typescript/engine/askGate.d.ts.map +1 -0
- package/lib/typescript/engine/effectFor.d.ts +6 -1
- package/lib/typescript/engine/effectFor.d.ts.map +1 -1
- package/lib/typescript/engine/historyBudget.d.ts +92 -0
- package/lib/typescript/engine/historyBudget.d.ts.map +1 -0
- package/lib/typescript/engine/runAgentTurn.d.ts +115 -1
- package/lib/typescript/engine/runAgentTurn.d.ts.map +1 -1
- package/lib/typescript/engine/systemPrompt.d.ts +41 -0
- package/lib/typescript/engine/systemPrompt.d.ts.map +1 -1
- package/lib/typescript/engine/textToolCalls.d.ts +58 -0
- package/lib/typescript/engine/textToolCalls.d.ts.map +1 -0
- package/lib/typescript/index.d.ts +8 -5
- package/lib/typescript/index.d.ts.map +1 -1
- package/lib/typescript/policy/labels.d.ts.map +1 -1
- package/lib/typescript/policy/policy.d.ts.map +1 -1
- package/lib/typescript/policy/redact.d.ts.map +1 -1
- package/lib/typescript/providers/anthropic.d.ts +5 -0
- package/lib/typescript/providers/anthropic.d.ts.map +1 -1
- package/lib/typescript/providers/openai.d.ts +0 -16
- package/lib/typescript/providers/openai.d.ts.map +1 -1
- package/lib/typescript/providers/sse.d.ts +82 -1
- package/lib/typescript/providers/sse.d.ts.map +1 -1
- package/lib/typescript/providers/streamTimer.d.ts +59 -0
- package/lib/typescript/providers/streamTimer.d.ts.map +1 -0
- package/lib/typescript/providers/transport.d.ts +40 -0
- package/lib/typescript/providers/transport.d.ts.map +1 -0
- package/lib/typescript/providers/types.d.ts +116 -3
- package/lib/typescript/providers/types.d.ts.map +1 -1
- package/lib/typescript/providers/xhrStream.d.ts +43 -0
- package/lib/typescript/providers/xhrStream.d.ts.map +1 -0
- package/lib/typescript/session.d.ts +63 -2
- package/lib/typescript/session.d.ts.map +1 -1
- 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 {
|
|
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
|
|
65
|
-
|
|
66
|
-
|
|
100
|
+
const timer = createStreamTimer(req.signal, config);
|
|
101
|
+
const status = {
|
|
102
|
+
truncated: false
|
|
67
103
|
};
|
|
68
|
-
|
|
69
|
-
headers
|
|
70
|
-
|
|
71
|
-
|
|
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
|
-
|
|
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
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
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
|
-
|
|
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:
|
|
212
|
+
message: err.message ?? "Provider error",
|
|
213
|
+
kind: "provider"
|
|
118
214
|
};
|
|
119
|
-
|
|
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
|
-
|
|
141
|
-
|
|
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:
|
|
280
|
+
message: truncatedMessage(status.truncated),
|
|
281
|
+
kind: "truncated"
|
|
145
282
|
};
|
|
146
283
|
return;
|
|
147
284
|
}
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
if
|
|
158
|
-
|
|
159
|
-
if (
|
|
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: "
|
|
162
|
-
|
|
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
|
-
|
|
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":["
|
|
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,EAAiB;EAC/E,MAAMC,GAAkB,GAAG,CAAC;IAAEC,IAAI,EAAE,QAAQ;IAAEC,OAAO,EAAEJ;EAAO,CAAC,CAAC;EAChE,KAAK,MAAMK,CAAC,IAAIJ,QAAQ,EAAE;IACxB,IAAII,CAAC,CAACF,IAAI,KAAK,MAAM,EAAE;MACrBD,GAAG,CAACI,IAAI,CAAC;QAAEH,IAAI,EAAE,MAAM;QAAEC,OAAO,EAAEC,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I,CAACC,IAAI,IAAI2B,EAAE,CAAChF,SAAS;YAChE8C,OAAO,CAACoC,GAAG,CAACH,KAAK,EAAE3B,IAAI,CAAC;UAC1B;QACF;;QAEA;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;QACQ,MAAM+B,WAAW,GAAGjC,OAAO,IAAIF,UAAU,KAAKoC,SAAS;QAEvD,IAAI,CAACD,WAAW,EAAE;UAChB;UACA;UACA;UACA,MAAM;YACJtF,IAAI,EAAE,OAAO;YACb+C,OAAO,EAAElE,gBAAgB,CAAC6C,MAAM,CAACC,SAAS,CAAC;YAC3CqB,IAAI,EAAE;UACR,CAAC;UACD;QACF;QAEA,OAAOM,KAAK,CAAC,CAAC;QACd,MAAM;UACJtD,IAAI,EAAE,MAAM;UACZwF,OAAO,EAAErC,UAAU,KAAK,QAAQ,GAAG,gBAAgB,GAAG,WAAW;UACjEA,UAAU;UACVC,KAAK;UACLlB;QACF,CAAC;MACH,CAAC,CAAC,OAAOiC,GAAG,EAAE;QACZ;QACA;QACA,IAAI5C,GAAG,CAACE,MAAM,EAAEgE,OAAO,EAAE,MAAMtB,GAAG;QAClC,MAAMpB,OAAO,GAAGvB,KAAK,CAACuB,OAAO,CAAC,CAAC;QAC/B,IAAIA,OAAO,EAAE;UACX,MAAM;YAAE/C,IAAI,EAAE,OAAO;YAAE+C,OAAO;YAAEC,IAAI,EAAE;UAAU,CAAC;UACjD;QACF;QACA;QACA;QACA,MAAMmB,GAAG;MACX,CAAC,SAAS;QACR3C,KAAK,CAACkE,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
|
-
|
|
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
|
-
|
|
40
|
-
|
|
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
|
|
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
|
-
|
|
71
|
-
|
|
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
|
-
|
|
80
|
-
|
|
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
|