@buoy-gg/agent-core 7.0.41 → 7.0.42

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 (201) hide show
  1. package/lib/commonjs/blocks/receipts.js +1 -761
  2. package/lib/commonjs/blocks/runId.js +1 -31
  3. package/lib/commonjs/blocks/types.js +1 -140
  4. package/lib/commonjs/blocks/uiTool.js +6 -1405
  5. package/lib/commonjs/catalog/catalog.g.js +5 -4556
  6. package/lib/commonjs/catalog/catalog.source.json +249 -0
  7. package/lib/commonjs/catalog/catalog.types.g.js +1 -46
  8. package/lib/commonjs/catalog/normalizeParams.js +2 -332
  9. package/lib/commonjs/catalog/signature.js +1 -68
  10. package/lib/commonjs/catalog/snapshotReads.js +1 -263
  11. package/lib/commonjs/catalog/toProviderTools.js +2 -145
  12. package/lib/commonjs/catalog/validateParams.js +1 -129
  13. package/lib/commonjs/context/buildContextPack.js +1 -489
  14. package/lib/commonjs/effects/digest.js +1 -34
  15. package/lib/commonjs/effects/ledger.js +1 -345
  16. package/lib/commonjs/engine/askGate.js +1 -287
  17. package/lib/commonjs/engine/effectFor.js +1 -223
  18. package/lib/commonjs/engine/evidence.js +3 -111
  19. package/lib/commonjs/engine/historyBudget.js +1 -363
  20. package/lib/commonjs/engine/retrieve.js +1 -214
  21. package/lib/commonjs/engine/runAgentTurn.js +8 -1836
  22. package/lib/commonjs/engine/systemPrompt.js +54 -163
  23. package/lib/commonjs/engine/textToolCalls.js +1 -276
  24. package/lib/commonjs/engine/tokenCalibration.js +1 -81
  25. package/lib/commonjs/engine/verify.js +4 -297
  26. package/lib/commonjs/index.js +1 -384
  27. package/lib/commonjs/policy/labels.js +1 -319
  28. package/lib/commonjs/policy/policy.js +1 -148
  29. package/lib/commonjs/policy/redact.js +1 -172
  30. package/lib/commonjs/providers/anthropic.js +3 -445
  31. package/lib/commonjs/providers/openai.js +4 -324
  32. package/lib/commonjs/providers/problem.js +1 -98
  33. package/lib/commonjs/providers/sse.js +1 -240
  34. package/lib/commonjs/providers/streamTimer.js +1 -123
  35. package/lib/commonjs/providers/transport.js +1 -123
  36. package/lib/commonjs/providers/types.js +1 -6
  37. package/lib/commonjs/providers/xhrStream.js +1 -212
  38. package/lib/commonjs/realNow.js +1 -0
  39. package/lib/commonjs/session.js +1 -393
  40. package/lib/commonjs/types.js +0 -1
  41. package/lib/module/blocks/receipts.js +1 -755
  42. package/lib/module/blocks/runId.js +1 -26
  43. package/lib/module/blocks/types.js +1 -134
  44. package/lib/module/blocks/uiTool.js +6 -1396
  45. package/lib/module/catalog/catalog.g.js +5 -4552
  46. package/lib/module/catalog/catalog.source.json +249 -0
  47. package/lib/module/catalog/catalog.types.g.js +1 -42
  48. package/lib/module/catalog/normalizeParams.js +2 -326
  49. package/lib/module/catalog/signature.js +1 -63
  50. package/lib/module/catalog/snapshotReads.js +1 -259
  51. package/lib/module/catalog/toProviderTools.js +2 -139
  52. package/lib/module/catalog/validateParams.js +1 -124
  53. package/lib/module/context/buildContextPack.js +1 -485
  54. package/lib/module/effects/digest.js +1 -29
  55. package/lib/module/effects/ledger.js +1 -339
  56. package/lib/module/engine/askGate.js +1 -280
  57. package/lib/module/engine/effectFor.js +1 -220
  58. package/lib/module/engine/evidence.js +3 -105
  59. package/lib/module/engine/historyBudget.js +1 -355
  60. package/lib/module/engine/retrieve.js +1 -210
  61. package/lib/module/engine/runAgentTurn.js +8 -1827
  62. package/lib/module/engine/systemPrompt.js +54 -157
  63. package/lib/module/engine/textToolCalls.js +1 -270
  64. package/lib/module/engine/tokenCalibration.js +1 -75
  65. package/lib/module/engine/verify.js +4 -289
  66. package/lib/module/index.js +1 -35
  67. package/lib/module/policy/labels.js +1 -312
  68. package/lib/module/policy/policy.js +1 -142
  69. package/lib/module/policy/redact.js +1 -165
  70. package/lib/module/providers/anthropic.js +3 -441
  71. package/lib/module/providers/openai.js +4 -320
  72. package/lib/module/providers/problem.js +1 -92
  73. package/lib/module/providers/sse.js +1 -231
  74. package/lib/module/providers/streamTimer.js +1 -118
  75. package/lib/module/providers/transport.js +1 -119
  76. package/lib/module/providers/types.js +1 -4
  77. package/lib/module/providers/xhrStream.js +1 -207
  78. package/lib/module/realNow.js +1 -0
  79. package/lib/module/session.js +1 -369
  80. package/lib/module/types.js +0 -1
  81. package/lib/typescript/catalog/catalog.g.d.ts +3 -3
  82. package/lib/typescript/catalog/catalog.types.g.d.ts +3 -2
  83. package/lib/typescript/providers/problem.d.ts +0 -20
  84. package/lib/typescript/providers/streamTimer.d.ts +0 -24
  85. package/lib/typescript/realNow.d.ts +18 -0
  86. package/lib/web/index.mjs +52 -53
  87. package/package.json +1 -1
  88. package/lib/commonjs/blocks/receipts.js.map +0 -1
  89. package/lib/commonjs/blocks/runId.js.map +0 -1
  90. package/lib/commonjs/blocks/types.js.map +0 -1
  91. package/lib/commonjs/blocks/uiTool.js.map +0 -1
  92. package/lib/commonjs/catalog/catalog.g.js.map +0 -1
  93. package/lib/commonjs/catalog/catalog.types.g.js.map +0 -1
  94. package/lib/commonjs/catalog/normalizeParams.js.map +0 -1
  95. package/lib/commonjs/catalog/signature.js.map +0 -1
  96. package/lib/commonjs/catalog/snapshotReads.js.map +0 -1
  97. package/lib/commonjs/catalog/toProviderTools.js.map +0 -1
  98. package/lib/commonjs/catalog/validateParams.js.map +0 -1
  99. package/lib/commonjs/context/buildContextPack.js.map +0 -1
  100. package/lib/commonjs/effects/digest.js.map +0 -1
  101. package/lib/commonjs/effects/ledger.js.map +0 -1
  102. package/lib/commonjs/engine/askGate.js.map +0 -1
  103. package/lib/commonjs/engine/effectFor.js.map +0 -1
  104. package/lib/commonjs/engine/evidence.js.map +0 -1
  105. package/lib/commonjs/engine/historyBudget.js.map +0 -1
  106. package/lib/commonjs/engine/retrieve.js.map +0 -1
  107. package/lib/commonjs/engine/runAgentTurn.js.map +0 -1
  108. package/lib/commonjs/engine/systemPrompt.js.map +0 -1
  109. package/lib/commonjs/engine/textToolCalls.js.map +0 -1
  110. package/lib/commonjs/engine/tokenCalibration.js.map +0 -1
  111. package/lib/commonjs/engine/verify.js.map +0 -1
  112. package/lib/commonjs/index.js.map +0 -1
  113. package/lib/commonjs/policy/labels.js.map +0 -1
  114. package/lib/commonjs/policy/policy.js.map +0 -1
  115. package/lib/commonjs/policy/redact.js.map +0 -1
  116. package/lib/commonjs/providers/anthropic.js.map +0 -1
  117. package/lib/commonjs/providers/openai.js.map +0 -1
  118. package/lib/commonjs/providers/problem.js.map +0 -1
  119. package/lib/commonjs/providers/sse.js.map +0 -1
  120. package/lib/commonjs/providers/streamTimer.js.map +0 -1
  121. package/lib/commonjs/providers/transport.js.map +0 -1
  122. package/lib/commonjs/providers/types.js.map +0 -1
  123. package/lib/commonjs/providers/xhrStream.js.map +0 -1
  124. package/lib/commonjs/session.js.map +0 -1
  125. package/lib/commonjs/types.js.map +0 -1
  126. package/lib/module/blocks/receipts.js.map +0 -1
  127. package/lib/module/blocks/runId.js.map +0 -1
  128. package/lib/module/blocks/types.js.map +0 -1
  129. package/lib/module/blocks/uiTool.js.map +0 -1
  130. package/lib/module/catalog/catalog.g.js.map +0 -1
  131. package/lib/module/catalog/catalog.types.g.js.map +0 -1
  132. package/lib/module/catalog/normalizeParams.js.map +0 -1
  133. package/lib/module/catalog/signature.js.map +0 -1
  134. package/lib/module/catalog/snapshotReads.js.map +0 -1
  135. package/lib/module/catalog/toProviderTools.js.map +0 -1
  136. package/lib/module/catalog/validateParams.js.map +0 -1
  137. package/lib/module/context/buildContextPack.js.map +0 -1
  138. package/lib/module/effects/digest.js.map +0 -1
  139. package/lib/module/effects/ledger.js.map +0 -1
  140. package/lib/module/engine/askGate.js.map +0 -1
  141. package/lib/module/engine/effectFor.js.map +0 -1
  142. package/lib/module/engine/evidence.js.map +0 -1
  143. package/lib/module/engine/historyBudget.js.map +0 -1
  144. package/lib/module/engine/retrieve.js.map +0 -1
  145. package/lib/module/engine/runAgentTurn.js.map +0 -1
  146. package/lib/module/engine/systemPrompt.js.map +0 -1
  147. package/lib/module/engine/textToolCalls.js.map +0 -1
  148. package/lib/module/engine/tokenCalibration.js.map +0 -1
  149. package/lib/module/engine/verify.js.map +0 -1
  150. package/lib/module/index.js.map +0 -1
  151. package/lib/module/policy/labels.js.map +0 -1
  152. package/lib/module/policy/policy.js.map +0 -1
  153. package/lib/module/policy/redact.js.map +0 -1
  154. package/lib/module/providers/anthropic.js.map +0 -1
  155. package/lib/module/providers/openai.js.map +0 -1
  156. package/lib/module/providers/problem.js.map +0 -1
  157. package/lib/module/providers/sse.js.map +0 -1
  158. package/lib/module/providers/streamTimer.js.map +0 -1
  159. package/lib/module/providers/transport.js.map +0 -1
  160. package/lib/module/providers/types.js.map +0 -1
  161. package/lib/module/providers/xhrStream.js.map +0 -1
  162. package/lib/module/session.js.map +0 -1
  163. package/lib/module/types.js.map +0 -1
  164. package/lib/typescript/blocks/receipts.d.ts.map +0 -1
  165. package/lib/typescript/blocks/runId.d.ts.map +0 -1
  166. package/lib/typescript/blocks/types.d.ts.map +0 -1
  167. package/lib/typescript/blocks/uiTool.d.ts.map +0 -1
  168. package/lib/typescript/catalog/catalog.g.d.ts.map +0 -1
  169. package/lib/typescript/catalog/catalog.types.g.d.ts.map +0 -1
  170. package/lib/typescript/catalog/normalizeParams.d.ts.map +0 -1
  171. package/lib/typescript/catalog/signature.d.ts.map +0 -1
  172. package/lib/typescript/catalog/snapshotReads.d.ts.map +0 -1
  173. package/lib/typescript/catalog/toProviderTools.d.ts.map +0 -1
  174. package/lib/typescript/catalog/validateParams.d.ts.map +0 -1
  175. package/lib/typescript/context/buildContextPack.d.ts.map +0 -1
  176. package/lib/typescript/effects/digest.d.ts.map +0 -1
  177. package/lib/typescript/effects/ledger.d.ts.map +0 -1
  178. package/lib/typescript/engine/askGate.d.ts.map +0 -1
  179. package/lib/typescript/engine/effectFor.d.ts.map +0 -1
  180. package/lib/typescript/engine/evidence.d.ts.map +0 -1
  181. package/lib/typescript/engine/historyBudget.d.ts.map +0 -1
  182. package/lib/typescript/engine/retrieve.d.ts.map +0 -1
  183. package/lib/typescript/engine/runAgentTurn.d.ts.map +0 -1
  184. package/lib/typescript/engine/systemPrompt.d.ts.map +0 -1
  185. package/lib/typescript/engine/textToolCalls.d.ts.map +0 -1
  186. package/lib/typescript/engine/tokenCalibration.d.ts.map +0 -1
  187. package/lib/typescript/engine/verify.d.ts.map +0 -1
  188. package/lib/typescript/index.d.ts.map +0 -1
  189. package/lib/typescript/policy/labels.d.ts.map +0 -1
  190. package/lib/typescript/policy/policy.d.ts.map +0 -1
  191. package/lib/typescript/policy/redact.d.ts.map +0 -1
  192. package/lib/typescript/providers/anthropic.d.ts.map +0 -1
  193. package/lib/typescript/providers/openai.d.ts.map +0 -1
  194. package/lib/typescript/providers/problem.d.ts.map +0 -1
  195. package/lib/typescript/providers/sse.d.ts.map +0 -1
  196. package/lib/typescript/providers/streamTimer.d.ts.map +0 -1
  197. package/lib/typescript/providers/transport.d.ts.map +0 -1
  198. package/lib/typescript/providers/types.d.ts.map +0 -1
  199. package/lib/typescript/providers/xhrStream.d.ts.map +0 -1
  200. package/lib/typescript/session.d.ts.map +0 -1
  201. package/lib/typescript/types.d.ts.map +0 -1
@@ -1,443 +1,5 @@
1
- "use strict";
1
+ "use strict";import{truncatedMessage as w,unparseableMessage as v}from"./sse";import{createStreamTimer as j}from"./streamTimer";import{createTransport as S}from"./transport";import{classifyProblem as M}from"./problem";const V="2023-06-01";function E(a){const i=a[a.length-1];const s=i?.content[i.content.length-1];if(s){s.cache_control={type:"ephemeral"}}return a}function f(a){const i=[];for(const s of a){if(s.role==="user"){i.push({role:"user",content:[{type:"text",text:s.text}]})}else if(s.role==="assistant"){const o=[];for(const r of s.thinking??[])o.push(r);if(s.text)o.push({type:"text",text:s.text});for(const r of s.toolCalls??[]){o.push({type:"tool_use",id:r.id,name:r.name,input:r.input})}if(o.length)i.push({role:"assistant",content:o})}else{i.push({role:"user",content:s.results.map(o=>({type:"tool_result",tool_use_id:o.toolCallId,content:o.content,...o.isError?{is_error:true}:{}}))})}}return i}export function createAnthropicProvider(a){const i=S(a);return{protocol:"anthropic",async*send(s){const o=j(s.signal,a);const r={truncated:false};try{const l={"content-type":"application/json","anthropic-version":a.anthropicVersion??V,...await(a.headers?.()??{})};if(a.apiKey&&!l["x-api-key"]&&!l.Authorization){l["x-api-key"]=a.apiKey;l["anthropic-dangerous-direct-browser-access"]="true"}const p=await i.open({headers:l,signal:o.signal,body:JSON.stringify({model:s.model,max_tokens:s.maxTokens,stream:true,system:a.cache===false?s.systemVolatile?`${s.system}
2
2
 
3
- /**
4
- * Anthropic Messages protocol.
5
- *
6
- * Four things here are not obvious and each one is a silent failure if missed:
7
- *
8
- * 1. `content_block_start` for a `tool_use` carries `"input": {}` — an EMPTY
9
- * object, never the real arguments. The arguments only exist after
10
- * concatenating every `input_json_delta.partial_json` and parsing at
11
- * `content_block_stop`. Reading `.input` at start yields a tool call with no
12
- * arguments and no error.
13
- * 2. There is NO `data: [DONE]` sentinel (removed in the 2023-06-01 version).
14
- * The stream ends at `message_stop`.
15
- * 3. `error` events arrive MID-STREAM on an already-committed HTTP 200 —
16
- * `overloaded_error` being the common one. A 200 is not success.
17
- * 4. Ordering is 400-level strict: `tool_result` blocks must come FIRST in the
18
- * user content array with any text after, and that user message must
19
- * immediately follow the assistant turn. "Here are the results:" placed
20
- * before the blocks is an instant 400.
21
- * 5. Every current Claude model thinks by DEFAULT, and a `thinking` block must
22
- * be replayed VERBATIM (signature and all) at the FRONT of the assistant
23
- * turn it came from whenever that turn's tool results are sent back. An
24
- * adapter that keeps only text and tool_use 400s on the second request of
25
- * every tool-using turn — which is every turn Ask Buoy actually makes.
26
- */
3
+ ---
27
4
 
28
- import { truncatedMessage, unparseableMessage } from "./sse";
29
- import { createStreamTimer } from "./streamTimer";
30
- import { createTransport } from "./transport";
31
- import { classifyProblem } from "./problem";
32
- const DEFAULT_VERSION = "2023-06-01";
33
- /**
34
- * Mark the last content block of the last message as a cache breakpoint.
35
- *
36
- * WHY THERE IS A SECOND BREAKPOINT AT ALL. The first one, at the end of
37
- * `system`, caches the tools and the system prompt — the big fixed prefix. It
38
- * does nothing for the messages, which were left uncached on the reasoning
39
- * that they grow every turn and so would pay the write multiplier for a prefix
40
- * never read back. That is true of a turn with ONE request. It is false of the
41
- * turns this tool actually makes: a turn runs 3 to 8 model requests, each
42
- * re-sending the whole conversation plus everything the previous steps read,
43
- * and steps 2..N are exactly a re-read of what step 1 already sent.
44
- *
45
- * So the breakpoint MOVES: each request marks its own last block, and the next
46
- * request hits it (Anthropic looks back ~20 blocks for a match). Step 1 writes
47
- * the messages at 1.25x, every later step reads them at 0.1x and writes only
48
- * its own delta.
49
- *
50
- * What it does NOT buy is cross-TURN caching, because the volatile "right now"
51
- * block sits at the end of `system` and changes every turn, invalidating
52
- * anything after it. Within a turn is where the multiplier lives, and that is
53
- * what this collects.
54
- */
55
- function markLastBlock(out) {
56
- const lastMessage = out[out.length - 1];
57
- const lastBlock = lastMessage?.content[lastMessage.content.length - 1];
58
- if (lastBlock) {
59
- lastBlock.cache_control = {
60
- type: "ephemeral"
61
- };
62
- }
63
- return out;
64
- }
65
- function toWireMessages(messages) {
66
- const out = [];
67
- for (const m of messages) {
68
- if (m.role === "user") {
69
- out.push({
70
- role: "user",
71
- content: [{
72
- type: "text",
73
- text: m.text
74
- }]
75
- });
76
- } else if (m.role === "assistant") {
77
- const content = [];
78
- // Thinking FIRST — see note 5. Signatures are opaque; never edit them.
79
- for (const t of m.thinking ?? []) content.push(t);
80
- if (m.text) content.push({
81
- type: "text",
82
- text: m.text
83
- });
84
- for (const c of m.toolCalls ?? []) {
85
- content.push({
86
- type: "tool_use",
87
- id: c.id,
88
- name: c.name,
89
- input: c.input
90
- });
91
- }
92
- if (content.length) out.push({
93
- role: "assistant",
94
- content
95
- });
96
- } else {
97
- // tool_result blocks FIRST — see note 4. No preamble text, ever.
98
- out.push({
99
- role: "user",
100
- content: m.results.map(r => ({
101
- type: "tool_result",
102
- tool_use_id: r.toolCallId,
103
- content: r.content,
104
- ...(r.isError ? {
105
- is_error: true
106
- } : {})
107
- }))
108
- });
109
- }
110
- }
111
- return out;
112
- }
113
- export function createAnthropicProvider(config) {
114
- // One per provider, so the `auto` transport decision is made once and not
115
- // re-learned (and re-buffered) at the start of every turn.
116
- const transport = createTransport(config);
117
- return {
118
- protocol: "anthropic",
119
- async *send(req) {
120
- const timer = createStreamTimer(req.signal, config);
121
- const status = {
122
- truncated: false
123
- };
124
- try {
125
- const headers = {
126
- "content-type": "application/json",
127
- "anthropic-version": config.anthropicVersion ?? DEFAULT_VERSION,
128
- ...(await (config.headers?.() ?? {}))
129
- };
130
- // Dev-only direct mode. A distributed build uses `headers` against the
131
- // org's own gateway and never carries a provider key at all.
132
- if (config.apiKey && !headers["x-api-key"] && !headers.Authorization) {
133
- headers["x-api-key"] = config.apiKey;
134
- // Without this the POST comes back with no access-control-allow-origin
135
- // and a browser/Electron renderer silently discards an otherwise fine
136
- // response — a 200 in the network log and "Failed to fetch" in JS.
137
- headers["anthropic-dangerous-direct-browser-access"] = "true";
138
- }
139
- const stream = await transport.open({
140
- headers,
141
- // The timer's signal, not the caller's: it aborts on the user's Stop
142
- // AND on either clock running out. See providers/streamTimer.ts.
143
- signal: timer.signal,
144
- body: JSON.stringify({
145
- model: req.model,
146
- max_tokens: req.maxTokens,
147
- stream: true,
148
- // ONE cache breakpoint, at the end of `system`.
149
- //
150
- // Anthropic caches the prefix in a fixed order — tools, then system,
151
- // then messages — up to and including the block carrying
152
- // `cache_control`. So marking the end of the system prompt caches
153
- // the tool definitions with it, which is the point: the tools are
154
- // ~20k tokens and by far the larger half. A second breakpoint on the
155
- // last tool would buy nothing and spend one of the four available.
156
- //
157
- // Messages stay uncached on purpose. They grow every turn, so they
158
- // would invalidate on each request and pay the write multiplier for
159
- // a prefix that is never read back.
160
- //
161
- // The volatile block (what is on screen right now) goes in a SECOND
162
- // text block after the breakpoint. It changes every turn; inside the
163
- // cached block it would invalidate the whole prefix each time.
164
- system: config.cache === false ? req.systemVolatile ? `${req.system}\n\n---\n\n${req.systemVolatile}` : req.system : [{
165
- type: "text",
166
- text: req.system,
167
- cache_control: {
168
- type: "ephemeral"
169
- }
170
- }, ...(req.systemVolatile ? [{
171
- type: "text",
172
- text: req.systemVolatile
173
- }] : [])],
174
- tools: req.tools.map(t => ({
175
- name: t.name,
176
- description: t.description,
177
- input_schema: t.inputSchema,
178
- // Anthropic-only. Each example must validate against input_schema
179
- // or the API 400s, so these are generated from the catalog rather
180
- // than written by hand.
181
- ...(t.inputExamples?.length ? {
182
- input_examples: t.inputExamples
183
- } : {})
184
- })),
185
- messages: config.cache === false ? toWireMessages(req.messages) : markLastBlock(toWireMessages(req.messages)),
186
- ...config.requestOverrides
187
- })
188
- });
189
-
190
- // Headers are in: the connect clock stops here and the idle one starts.
191
- timer.connected();
192
- if (stream.problem) {
193
- yield {
194
- type: "error",
195
- message: stream.problem,
196
- kind: "provider",
197
- problem: stream.problemInfo
198
- };
199
- return;
200
- }
201
-
202
- // Partial tool_use args accumulate here, keyed by content-block index.
203
- const pending = new Map();
204
- // Partial thinking blocks, same keying. `thinking_delta` carries the
205
- // text and `signature_delta` the signature, and the signature usually
206
- // arrives in ONE delta right at the end — a reader that stops at
207
- // thinking_delta replays an unsigned block, which the API rejects.
208
- const thinking = new Map();
209
- let stopReason;
210
- let usage;
211
- let model;
212
- /** The protocol's end marker; ends the read. See `sawTerminal` below. */
213
- let sawStop = false;
214
- for await (const ev of stream.frames({
215
- status,
216
- onFrame: timer.activity,
217
- signal: timer.signal
218
- })) {
219
- let payload;
220
- try {
221
- payload = JSON.parse(ev.data);
222
- } catch {
223
- continue;
224
- }
225
- const kind = payload.type ?? ev.event;
226
- switch (kind) {
227
- case "content_block_start":
228
- {
229
- const block = payload.content_block;
230
- if (block?.type === "thinking") {
231
- thinking.set(payload.index, {
232
- thinking: block.thinking ?? "",
233
- signature: block.signature ?? ""
234
- });
235
- } else if (block?.type === "redacted_thinking") {
236
- // No deltas for these — the whole (encrypted) payload is here.
237
- yield {
238
- type: "thinking",
239
- block: {
240
- type: "redacted_thinking",
241
- data: block.data
242
- }
243
- };
244
- } else if (block?.type === "tool_use") {
245
- // NOT block.input — see note 1.
246
- pending.set(payload.index, {
247
- id: block.id,
248
- name: block.name,
249
- json: ""
250
- });
251
- }
252
- break;
253
- }
254
- case "content_block_delta":
255
- {
256
- const delta = payload.delta;
257
- if (delta?.type === "text_delta") {
258
- yield {
259
- type: "text",
260
- delta: delta.text
261
- };
262
- } else if (delta?.type === "input_json_delta") {
263
- const slot = pending.get(payload.index);
264
- if (slot) slot.json += delta.partial_json ?? "";
265
- } else if (delta?.type === "thinking_delta") {
266
- const slot = thinking.get(payload.index);
267
- if (slot) slot.thinking += delta.thinking ?? "";
268
- } else if (delta?.type === "signature_delta") {
269
- const slot = thinking.get(payload.index);
270
- if (slot) slot.signature += delta.signature ?? "";
271
- }
272
- break;
273
- }
274
- case "content_block_stop":
275
- {
276
- const thought = thinking.get(payload.index);
277
- if (thought) {
278
- thinking.delete(payload.index);
279
- yield {
280
- type: "thinking",
281
- block: {
282
- type: "thinking",
283
- ...thought
284
- }
285
- };
286
- }
287
- const slot = pending.get(payload.index);
288
- if (slot) {
289
- pending.delete(payload.index);
290
- let input = {};
291
- try {
292
- input = slot.json ? JSON.parse(slot.json) : {};
293
- } catch {
294
- yield {
295
- type: "error",
296
- kind: "provider",
297
- // Same evidence as the OpenAI path. The stop reason is not
298
- // known yet here — it rides on `message_delta`, which comes
299
- // after this block closes — so only the raw tail is carried.
300
- message: unparseableMessage(slot.name, slot.json)
301
- };
302
- break;
303
- }
304
- const call = {
305
- id: slot.id,
306
- name: slot.name,
307
- input
308
- };
309
- yield {
310
- type: "tool-call",
311
- call
312
- };
313
- }
314
- break;
315
- }
316
- case "message_start":
317
- {
318
- // The cache counters arrive HERE, not on message_delta — the
319
- // prefix is accounted for before a single token is generated. A
320
- // reader that only watches message_delta sees cacheRead 0 on
321
- // every request and concludes caching is not working.
322
- const m = payload.message;
323
- // The served model id is named here and nowhere else — a gateway
324
- // resolves an alias to a dated snapshot, and this is that id.
325
- if (typeof m?.model === "string" && m.model) model = m.model;
326
- const u = m?.usage;
327
- if (u) {
328
- usage = {
329
- input: u.input_tokens ?? 0,
330
- output: u.output_tokens ?? 0,
331
- ...(u.cache_read_input_tokens !== undefined ? {
332
- cacheRead: u.cache_read_input_tokens
333
- } : {}),
334
- ...(u.cache_creation_input_tokens !== undefined ? {
335
- cacheWrite: u.cache_creation_input_tokens
336
- } : {})
337
- };
338
- }
339
- break;
340
- }
341
- case "message_delta":
342
- {
343
- const delta = payload.delta;
344
- // `stop_reason` is the model's own statement that it finished,
345
- // and counts as terminal on its own (see `sawTerminal`). It does
346
- // NOT end the read: `message_stop` is one frame away and there is
347
- // no reason to cancel a stream that is about to close itself.
348
- if (delta?.stop_reason) stopReason = delta.stop_reason;
349
- // Cumulative, not incremental — assign, never add. Output tokens
350
- // are only final here, so keep whatever message_start reported
351
- // about the cache rather than replacing the whole record.
352
- const u = payload.usage;
353
- if (u) {
354
- usage = {
355
- ...usage,
356
- input: u.input_tokens ?? usage?.input ?? 0,
357
- output: u.output_tokens ?? 0
358
- };
359
- }
360
- break;
361
- }
362
- case "error":
363
- {
364
- const err = payload.error;
365
- const message = err?.message ?? "Provider error";
366
- yield {
367
- type: "error",
368
- message,
369
- kind: "provider",
370
- // `overloaded_error` on a committed 200 is the common shape —
371
- // classified so the engine can retry it when nothing came first.
372
- problem: classifyProblem({
373
- type: typeof err?.type === "string" ? err.type : undefined,
374
- message
375
- })
376
- };
377
- return;
378
- }
379
- case "message_stop":
380
- // The end. There is no [DONE] — see note 2.
381
- sawStop = true;
382
- break;
383
- default:
384
- break;
385
- }
386
- // `break` inside the switch leaves the switch, not the loop.
387
- if (sawStop) break;
388
- }
389
-
390
- /**
391
- * Did the provider actually say it was finished?
392
- *
393
- * `message_stop` is the protocol's end marker. `stop_reason` counts
394
- * too: it is the model's own statement of why it stopped, which is the
395
- * stronger claim — `message_stop` only says the SSE stream closed. A
396
- * proxy that forwards the delta and drops the final frame has still
397
- * delivered a whole answer, and refusing it would break working
398
- * gateways for no safety gain. NEITHER arriving is the case that
399
- * matters: bare EOF, which used to be read as success.
400
- */
401
- const sawTerminal = sawStop || stopReason !== undefined;
402
- if (!sawTerminal) {
403
- // Bare EOF. Whatever text arrived is real and the engine will show it,
404
- // but the plan behind it is half-written: a connection cut after
405
- // `{"key":"cart","value":[]}` leaves valid JSON that reads exactly like
406
- // a finished thought. Nothing here is admitted for execution.
407
- yield {
408
- type: "error",
409
- message: truncatedMessage(status.truncated),
410
- kind: "truncated"
411
- };
412
- return;
413
- }
414
- yield {
415
- type: "done",
416
- outcome: stopReason === "max_tokens" ? "output-limited" : "completed",
417
- stopReason,
418
- usage,
419
- model
420
- };
421
- } catch (err) {
422
- // The user's Stop wins the label even if a clock fired in the same
423
- // tick: they know why the turn ended, and "timed out" would be a lie.
424
- if (req.signal?.aborted) throw err;
425
- const message = timer.message();
426
- if (message) {
427
- yield {
428
- type: "error",
429
- message,
430
- kind: "timeout"
431
- };
432
- return;
433
- }
434
- // A genuine transport failure — DNS, refused connection, TLS. It has
435
- // always propagated to the failed-turn card, and still does.
436
- throw err;
437
- } finally {
438
- timer.dispose();
439
- }
440
- }
441
- };
442
- }
443
- //# sourceMappingURL=anthropic.js.map
5
+ ${s.systemVolatile}`:s.system:[{type:"text",text:s.system,cache_control:{type:"ephemeral"}},...s.systemVolatile?[{type:"text",text:s.systemVolatile}]:[]],tools:s.tools.map(c=>({name:c.name,description:c.description,input_schema:c.inputSchema,...c.inputExamples?.length?{input_examples:c.inputExamples}:{}})),messages:a.cache===false?f(s.messages):E(f(s.messages)),...a.requestOverrides})});o.connected();if(p.problem){yield{type:"error",message:p.problem,kind:"provider",problem:p.problemInfo};return}const m=new Map;const d=new Map;let y;let u;let g;let h=false;for await(const c of p.frames({status:r,onFrame:o.activity,signal:o.signal})){let n;try{n=JSON.parse(c.data)}catch{continue}const x=n.type??c.event;switch(x){case"content_block_start":{const e=n.content_block;if(e?.type==="thinking"){d.set(n.index,{thinking:e.thinking??"",signature:e.signature??""})}else if(e?.type==="redacted_thinking"){yield{type:"thinking",block:{type:"redacted_thinking",data:e.data}}}else if(e?.type==="tool_use"){m.set(n.index,{id:e.id,name:e.name,json:""})}break}case"content_block_delta":{const e=n.delta;if(e?.type==="text_delta"){yield{type:"text",delta:e.text}}else if(e?.type==="input_json_delta"){const t=m.get(n.index);if(t)t.json+=e.partial_json??""}else if(e?.type==="thinking_delta"){const t=d.get(n.index);if(t)t.thinking+=e.thinking??""}else if(e?.type==="signature_delta"){const t=d.get(n.index);if(t)t.signature+=e.signature??""}break}case"content_block_stop":{const e=d.get(n.index);if(e){d.delete(n.index);yield{type:"thinking",block:{type:"thinking",...e}}}const t=m.get(n.index);if(t){m.delete(n.index);let k={};try{k=t.json?JSON.parse(t.json):{}}catch{yield{type:"error",kind:"provider",message:v(t.name,t.json)};break}const b={id:t.id,name:t.name,input:k};yield{type:"tool-call",call:b}}break}case"message_start":{const e=n.message;if(typeof e?.model==="string"&&e.model)g=e.model;const t=e?.usage;if(t){u={input:t.input_tokens??0,output:t.output_tokens??0,...t.cache_read_input_tokens!==void 0?{cacheRead:t.cache_read_input_tokens}:{},...t.cache_creation_input_tokens!==void 0?{cacheWrite:t.cache_creation_input_tokens}:{}}}break}case"message_delta":{const e=n.delta;if(e?.stop_reason)y=e.stop_reason;const t=n.usage;if(t){u={...u,input:t.input_tokens??u?.input??0,output:t.output_tokens??0}}break}case"error":{const e=n.error;const t=e?.message??"Provider error";yield{type:"error",message:t,kind:"provider",problem:M({type:typeof e?.type==="string"?e.type:void 0,message:t})};return}case"message_stop":h=true;break;default:break}if(h)break}const _=h||y!==void 0;if(!_){yield{type:"error",message:w(r.truncated),kind:"truncated"};return}yield{type:"done",outcome:y==="max_tokens"?"output-limited":"completed",stopReason:y,usage:u,model:g}}catch(l){if(s.signal?.aborted)throw l;const p=o.message();if(p){yield{type:"error",message:p,kind:"timeout"};return}throw l}finally{o.dispose()}}}}