@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
@@ -0,0 +1,212 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.xhrAvailable = xhrAvailable;
7
+ exports.xhrStream = xhrStream;
8
+ var _sse = require("./sse");
9
+ /**
10
+ * Streaming over `XMLHttpRequest`, for the runtimes where `fetch` cannot.
11
+ *
12
+ * React Native core still has no `response.body`: its `fetch` is the whatwg
13
+ * polyfill over XHR and resolves inside `xhr.onload`, i.e. after the ENTIRE
14
+ * body. Under Expo the global is `expo/fetch`, which does stream — but
15
+ * `EXPO_PUBLIC_USE_RN_FETCH=1` reverts that, and the bare-RN CLI, TV CLI and
16
+ * NativeScript lanes never had it at all. On those, every Ask Buoy answer
17
+ * appeared in one lump, however long the model took.
18
+ *
19
+ * XHR itself has streamed the whole time. `responseText` grows as bytes arrive
20
+ * and `onprogress` fires as it does, so slicing from the last offset gives the
21
+ * same incremental text a reader would. Two conditions, both easy to miss:
22
+ * the progress handler must be installed BEFORE `send()`, and `responseType`
23
+ * must stay text — anything else stops RN emitting progress at all.
24
+ *
25
+ * WHAT THIS IS NOT. It is not a second SSE parser: framing, the truncation
26
+ * rule and the terminal-marker contract all live in `sse.ts` and are shared
27
+ * verbatim. This file only produces text chunks.
28
+ */
29
+
30
+ /** Beyond this the answer is not an answer any more; stop reading. */
31
+ const MAX_RESPONSE_CHARS = 8_000_000;
32
+ function xhrAvailable() {
33
+ return typeof XMLHttpRequest === "function";
34
+ }
35
+
36
+ /**
37
+ * Send the request and resolve once the HEADERS are in, so the caller can
38
+ * check the status and content type before deciding to read a stream — the
39
+ * same shape `fetch` offers, and the reason this can slot in beside it.
40
+ */
41
+ function xhrStream(req) {
42
+ return new Promise((resolveHeaders, rejectHeaders) => {
43
+ const xhr = new XMLHttpRequest();
44
+
45
+ /** Text seen but not yet handed to a consumer. */
46
+ const queue = [];
47
+ /** Resolvers for a consumer parked on an empty queue. */
48
+ const waiters = [];
49
+ let offset = 0;
50
+ let done = false;
51
+ let failure;
52
+ let headersSeen = false;
53
+ let capped = false;
54
+ const wake = () => {
55
+ while (waiters.length) waiters.shift()();
56
+ };
57
+ const pull = () => {
58
+ // `responseText` is the WHOLE body so far, so the delta is everything
59
+ // past what was already taken. RN keeps the full string either way;
60
+ // the offset bounds the work, not the memory.
61
+ let text;
62
+ try {
63
+ text = xhr.responseText ?? "";
64
+ } catch {
65
+ return; // Not readable yet on some runtimes; the next event will do.
66
+ }
67
+ if (text.length <= offset) return;
68
+ if (text.length > MAX_RESPONSE_CHARS) {
69
+ capped = true;
70
+ failure = new Error("The endpoint sent more than this tool will read.");
71
+ done = true;
72
+ try {
73
+ xhr.abort();
74
+ } catch {
75
+ /* already gone */
76
+ }
77
+ wake();
78
+ return;
79
+ }
80
+ queue.push(text.slice(offset));
81
+ offset = text.length;
82
+ wake();
83
+ };
84
+ const settleHeaders = () => {
85
+ if (headersSeen) return;
86
+ headersSeen = true;
87
+ let contentType = "";
88
+ let retryAfter = null;
89
+ try {
90
+ contentType = xhr.getResponseHeader("content-type") ?? "";
91
+ retryAfter = xhr.getResponseHeader("retry-after");
92
+ } catch {
93
+ contentType = "";
94
+ }
95
+ resolveHeaders({
96
+ status: xhr.status,
97
+ ok: xhr.status >= 200 && xhr.status < 300,
98
+ contentType,
99
+ retryAfter,
100
+ async text() {
101
+ // Whatever has arrived. For a non-2xx that is the error body; the
102
+ // request is over by the time anyone asks.
103
+ await new Promise(r => {
104
+ if (done) return r();
105
+ waiters.push(() => r());
106
+ });
107
+ try {
108
+ return xhr.responseText ?? "";
109
+ } catch {
110
+ return "";
111
+ }
112
+ },
113
+ frames(options) {
114
+ return (0, _sse.framesFrom)(chunks(), options);
115
+ }
116
+ });
117
+ };
118
+ async function* chunks() {
119
+ try {
120
+ for (;;) {
121
+ while (queue.length) yield queue.shift();
122
+ if (done) break;
123
+ await new Promise(r => waiters.push(r));
124
+ }
125
+ while (queue.length) yield queue.shift();
126
+ if (failure) throw failure;
127
+ } finally {
128
+ if (!done) {
129
+ // The consumer left early — a completed turn, a Stop, a timeout.
130
+ // Nothing else will read this socket.
131
+ try {
132
+ xhr.abort();
133
+ } catch {
134
+ /* already gone */
135
+ }
136
+ }
137
+ }
138
+ }
139
+ const onAbort = () => {
140
+ try {
141
+ xhr.abort();
142
+ } catch {
143
+ /* already gone */
144
+ }
145
+ };
146
+ xhr.onreadystatechange = () => {
147
+ // HEADERS_RECEIVED. Status and content type are known here, long before
148
+ // the body finishes — which is the whole point of using XHR directly.
149
+ if (xhr.readyState === 2) settleHeaders();
150
+ };
151
+ xhr.onprogress = () => {
152
+ settleHeaders();
153
+ pull();
154
+ };
155
+ xhr.onload = () => {
156
+ settleHeaders();
157
+ if (!capped) pull();
158
+ done = true;
159
+ wake();
160
+ };
161
+ xhr.onerror = () => {
162
+ failure = new Error("The request failed before it finished.");
163
+ done = true;
164
+ if (!headersSeen) {
165
+ headersSeen = true;
166
+ rejectHeaders(failure);
167
+ }
168
+ wake();
169
+ };
170
+ xhr.onabort = () => {
171
+ const err = new Error("Aborted");
172
+ err.name = "AbortError";
173
+ failure = err;
174
+ done = true;
175
+ if (!headersSeen) {
176
+ headersSeen = true;
177
+ rejectHeaders(err);
178
+ }
179
+ wake();
180
+ };
181
+ xhr.ontimeout = () => {
182
+ failure = new Error("The request timed out.");
183
+ done = true;
184
+ if (!headersSeen) {
185
+ headersSeen = true;
186
+ rejectHeaders(failure);
187
+ }
188
+ wake();
189
+ };
190
+ try {
191
+ xhr.open("POST", req.url, true);
192
+ // Text, and nothing else: RN emits no progress events for any other
193
+ // response type, which turns this back into a buffered read in silence.
194
+ xhr.responseType = "text";
195
+ for (const [k, v] of Object.entries(req.headers)) {
196
+ try {
197
+ xhr.setRequestHeader(k, v);
198
+ } catch {
199
+ /* a header the runtime forbids is not worth failing the turn over */
200
+ }
201
+ }
202
+ if (req.signal) {
203
+ if (req.signal.aborted) onAbort();else req.signal.addEventListener?.("abort", onAbort);
204
+ }
205
+ xhr.send(req.body);
206
+ } catch (err) {
207
+ headersSeen = true;
208
+ rejectHeaders(err instanceof Error ? err : new Error(String(err)));
209
+ }
210
+ });
211
+ }
212
+ //# sourceMappingURL=xhrStream.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["_sse","require","MAX_RESPONSE_CHARS","xhrAvailable","XMLHttpRequest","xhrStream","req","Promise","resolveHeaders","rejectHeaders","xhr","queue","waiters","offset","done","failure","headersSeen","capped","wake","length","shift","pull","text","responseText","Error","abort","push","slice","settleHeaders","contentType","retryAfter","getResponseHeader","status","ok","r","frames","options","framesFrom","chunks","onAbort","onreadystatechange","readyState","onprogress","onload","onerror","onabort","err","name","ontimeout","open","url","responseType","k","v","Object","entries","headers","setRequestHeader","signal","aborted","addEventListener","send","body","String"],"sourceRoot":"../../../src","sources":["providers/xhrStream.ts"],"mappings":";;;;;;;AAoBA,IAAAA,IAAA,GAAAC,OAAA;AApBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA;AACA,MAAMC,kBAAkB,GAAG,SAAS;AAoB7B,SAASC,YAAYA,CAAA,EAAY;EACtC,OAAO,OAAOC,cAAc,KAAK,UAAU;AAC7C;;AAEA;AACA;AACA;AACA;AACA;AACO,SAASC,SAASA,CAACC,GAAqB,EAA8B;EAC3E,OAAO,IAAIC,OAAO,CAAoB,CAACC,cAAc,EAAEC,aAAa,KAAK;IACvE,MAAMC,GAAG,GAAG,IAAIN,cAAc,CAAC,CAAC;;IAEhC;IACA,MAAMO,KAAe,GAAG,EAAE;IAC1B;IACA,MAAMC,OAA0B,GAAG,EAAE;IACrC,IAAIC,MAAM,GAAG,CAAC;IACd,IAAIC,IAAI,GAAG,KAAK;IAChB,IAAIC,OAA0B;IAC9B,IAAIC,WAAW,GAAG,KAAK;IACvB,IAAIC,MAAM,GAAG,KAAK;IAElB,MAAMC,IAAI,GAAGA,CAAA,KAAM;MACjB,OAAON,OAAO,CAACO,MAAM,EAAEP,OAAO,CAACQ,KAAK,CAAC,CAAC,CAAE,CAAC;IAC3C,CAAC;IAED,MAAMC,IAAI,GAAGA,CAAA,KAAM;MACjB;MACA;MACA;MACA,IAAIC,IAAY;MAChB,IAAI;QACFA,IAAI,GAAGZ,GAAG,CAACa,YAAY,IAAI,EAAE;MAC/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,CAAC,EAAEC,CAAC,CAAC;QAC5B,CAAC,CAAC,MAAM;UACN;QAAA;MAEJ;MACA,IAAI/C,GAAG,CAACoD,MAAM,EAAE;QACd,IAAIpD,GAAG,CAACoD,MAAM,CAACC,OAAO,EAAEpB,OAAO,CAAC,CAAC,CAAC,KAC7BjC,GAAG,CAACoD,MAAM,CAACE,gBAAgB,GAAG,OAAO,EAAErB,OAAO,CAAC;MACtD;MACA7B,GAAG,CAACmD,IAAI,CAACvD,GAAG,CAACwD,IAAI,CAAC;IACpB,CAAC,CAAC,OAAOhB,GAAG,EAAE;MACZ9B,WAAW,GAAG,IAAI;MAClBP,aAAa,CAACqC,GAAG,YAAYtB,KAAK,GAAGsB,GAAG,GAAG,IAAItB,KAAK,CAACuC,MAAM,CAACjB,GAAG,CAAC,CAAC,CAAC;IACpE;EACF,CAAC,CAAC;AACJ","ignoreList":[]}
@@ -3,13 +3,34 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
+ Object.defineProperty(exports, "compressConsumed", {
7
+ enumerable: true,
8
+ get: function () {
9
+ return _historyBudget.compressConsumed;
10
+ }
11
+ });
6
12
  exports.createAskBuoySession = createAskBuoySession;
7
13
  exports.resumableHistory = resumableHistory;
14
+ Object.defineProperty(exports, "trimHistory", {
15
+ enumerable: true,
16
+ get: function () {
17
+ return _historyBudget.trimHistory;
18
+ }
19
+ });
20
+ Object.defineProperty(exports, "trimHistoryReport", {
21
+ enumerable: true,
22
+ get: function () {
23
+ return _historyBudget.trimHistoryReport;
24
+ }
25
+ });
8
26
  var _catalog = require("./catalog/catalog.g");
9
27
  var _buildContextPack = require("./context/buildContextPack");
10
28
  var _runAgentTurn = require("./engine/runAgentTurn");
11
29
  var _systemPrompt = require("./engine/systemPrompt");
12
30
  var _ledger = require("./effects/ledger");
31
+ var _evidence = require("./engine/evidence");
32
+ var _tokenCalibration = require("./engine/tokenCalibration");
33
+ var _historyBudget = require("./engine/historyBudget");
13
34
  var _anthropic = require("./providers/anthropic");
14
35
  var _openai = require("./providers/openai");
15
36
  var _policy = require("./policy/policy");
@@ -20,43 +41,11 @@ var _redact = require("./policy/redact");
20
41
  * This is the one-call surface the UI packages use. It owns the pieces that
21
42
  * have to agree with each other across a whole session — the provider, the
22
43
  * catalog filtered to what this device can actually do, the system prompt
23
- * (built once, after grounding), the effect ledger, and the message history —
44
+ * (the stable part built once after grounding, the RIGHT NOW part re-read every
45
+ * turn), the effect ledger, and the message history —
24
46
  * so a chat UI is a message list plus a text box rather than an orchestrator.
25
47
  */
26
48
 
27
- /**
28
- * A long QA session must not die on the provider's context limit with an
29
- * opaque error — the transcript grows without bound (tool results are the
30
- * heavy part), so the OLDEST rounds are dropped once the history passes a
31
- * budget. Rounds are dropped whole — a round starts at a user message — so
32
- * the assistant/tool-result pairing every provider requires stays intact and
33
- * the history still begins with a user message.
34
- */
35
- const MAX_HISTORY_CHARS = 150_000;
36
- const MIN_KEEP_MESSAGES = 4;
37
- function messageSize(m) {
38
- try {
39
- return JSON.stringify(m).length;
40
- } catch {
41
- return 0;
42
- }
43
- }
44
- function trimHistory(messages) {
45
- let total = 0;
46
- for (const m of messages) total += messageSize(m);
47
- if (total <= MAX_HISTORY_CHARS) return messages;
48
- const out = [...messages];
49
- while (out.length > MIN_KEEP_MESSAGES && total > MAX_HISTORY_CHARS) {
50
- total -= messageSize(out[0]);
51
- out.shift();
52
- while (out.length > MIN_KEEP_MESSAGES && out[0].role !== "user") {
53
- total -= messageSize(out[0]);
54
- out.shift();
55
- }
56
- }
57
- return out;
58
- }
59
-
60
49
  /**
61
50
  * A stored history, made safe to send as the start of a new request.
62
51
  *
@@ -73,6 +62,9 @@ function trimHistory(messages) {
73
62
  * always resumes with a fresh user message instead, so their signatures are
74
63
  * dead weight at best and a stale-signature 400 at worst.
75
64
  */
65
+ // Re-exported: these were defined here before the engine needed them too, and
66
+ // the tests and the package surface still reach them through this module.
67
+
76
68
  function resumableHistory(history) {
77
69
  let end = history.length;
78
70
  while (end > 0) {
@@ -90,8 +82,60 @@ function createAskBuoySession(config) {
90
82
  const ledger = new _ledger.EffectLedger();
91
83
  const policy = config.policy ?? {};
92
84
  let messages = [];
85
+ /**
86
+ * Image-URL provenance for the whole conversation, not one turn of it.
87
+ *
88
+ * "Show me the shop as pictures" and "no, actually render them" are two
89
+ * turns; the second has no tool calls of its own, so a per-turn set held
90
+ * nothing and every image was stripped out from under the model. It kept
91
+ * describing artwork that was not on screen. The rule is unchanged — a URL
92
+ * still has to have been READ — the window is just the conversation. Reset
93
+ * with the conversation.
94
+ */
95
+ const seenUrls = new Set();
96
+ /**
97
+ * Every result's full text, for `ask-buoy.retrieve` — see engine/evidence.ts.
98
+ * Conversation-scoped like `seenUrls`: "what were the stats in that response"
99
+ * is a normal second message. Cleared with the conversation; never persisted.
100
+ */
101
+ const evidence = new _evidence.EvidenceStore();
102
+ /** Chars-per-token as measured on THIS session's provider — see engine/tokenCalibration.ts. */
103
+ const calibration = new _tokenCalibration.TokenCalibration();
93
104
  let system;
94
105
  let primed = false;
106
+ /** See `setApprovalBypass`. Consulted per turn, never captured. */
107
+ let bypassApproval = false;
108
+ /** Actions the user waived the card for in this conversation — see RunTurnInput.trusted. */
109
+ const trusted = new Set();
110
+ /** See `setReadOnly`. */
111
+ let deviceReadOnly = false;
112
+ /**
113
+ * Rounds dropped by `restore` — reported on the first send, because there is
114
+ * no open turn to carry the event when the restore happens.
115
+ */
116
+ let trimmedOnRestore = 0;
117
+ /**
118
+ * Which conversation is live. Bumped by `reset`.
119
+ *
120
+ * A turn's history is committed when its generator drains, and a turn does
121
+ * not stop the moment Stop is pressed — an in-flight dispatch has to settle
122
+ * first, and nothing can pull a store write back out of an adapter. So the
123
+ * sequence Stop -> "New conversation" -> the write finishes used to end with
124
+ * the OLD turn assigning its whole history over the empty one: a chat the
125
+ * user had just cleared came back, carrying a change they never saw made.
126
+ * The turn still finishes and its effect still lands in the app; it simply
127
+ * no longer owns a conversation that has moved on.
128
+ */
129
+ let generation = 0;
130
+ /**
131
+ * The grounding probe's result, held past `prime`.
132
+ *
133
+ * The system prompt is a pure function of this plus the policy, and the
134
+ * approval paragraph changes when the device toggle does — holding the
135
+ * digest lets the prompt be rebuilt without re-probing the app for state it
136
+ * already read.
137
+ */
138
+ let digest = {};
95
139
  /**
96
140
  * `storage key -> the live store that owns it`, derived from the grounding.
97
141
  *
@@ -105,16 +149,63 @@ function createAskBuoySession(config) {
105
149
  // So the agent's own requests to the model endpoint never come back to it
106
150
  // out of the network tool — that would feed it its own auth headers.
107
151
  (0, _redact.registerSelfEndpoint)(config.endpoint);
108
- const provider = config.protocol === "openai" ? (0, _openai.createOpenAIProvider)(config) : (0, _anthropic.createAnthropicProvider)(config);
152
+ const provider = config.provider ?? (config.protocol === "openai" ? (0, _openai.createOpenAIProvider)(config) : (0, _anthropic.createAnthropicProvider)(config));
109
153
 
110
154
  // Mutable: the device's tool list fills in over the first frames and can
111
155
  // change while the sheet is open. See setAvailableActions.
112
156
  let availableActions = config.availableActions;
113
157
  let availableToolIds = Object.keys(availableActions);
158
+
159
+ /**
160
+ * THE policy object the engine reads, mutated in place.
161
+ *
162
+ * One object for the life of the session, not a fresh one per turn: the
163
+ * engine reads `policy.readOnly` and the approval lists at each call, so a
164
+ * toggle flipped mid-turn lands on the very next call of that turn. A new
165
+ * object per turn would leave a running turn on the old rules until it
166
+ * finished — "Read only" switched on while the agent was writing would let
167
+ * the rest of the batch through.
168
+ */
169
+ const live = {
170
+ ...policy
171
+ };
172
+ function refreshLive() {
173
+ for (const k of Object.keys(live)) delete live[k];
174
+ Object.assign(live, policy);
175
+ if (bypassApproval) {
176
+ live.requireApproval = [];
177
+ live.requireApprovalFor = [];
178
+ }
179
+ // OR, never override: the device can narrow, the app's own read-only stands.
180
+ if (deviceReadOnly) live.readOnly = true;
181
+ }
182
+ function activePolicy() {
183
+ return live;
184
+ }
185
+ function composeSystem() {
186
+ system = (0, _systemPrompt.buildSystemPrompt)({
187
+ catalog,
188
+ context: {
189
+ ...config.context,
190
+ digest: {
191
+ ...digest,
192
+ ...config.context?.digest
193
+ }
194
+ },
195
+ isRelease: config.isRelease,
196
+ readOnly: live.readOnly ?? false,
197
+ readOnlySource: policy.readOnly ? "app" : deviceReadOnly ? "device" : undefined,
198
+ requireApproval: (0, _policy.resolveRequireApproval)(live),
199
+ approvalsBypassed: bypassApproval,
200
+ appName: config.appName,
201
+ platform: config.platform,
202
+ availableToolIds
203
+ });
204
+ }
114
205
  async function prime() {
115
206
  if (primed) return;
116
207
  primed = true;
117
- let digest = {};
208
+ digest = {};
118
209
  try {
119
210
  digest = await (0, _buildContextPack.buildContextDigest)({
120
211
  dispatch: config.dispatch,
@@ -131,24 +222,16 @@ function createAskBuoySession(config) {
131
222
  const store = raw;
132
223
  if (store?.persistsTo && store.name) storeKeyOwners[store.persistsTo] = store.name;
133
224
  }
134
- system = (0, _systemPrompt.buildSystemPrompt)({
135
- catalog,
136
- context: {
137
- ...config.context,
138
- digest: {
139
- ...digest,
140
- ...config.context?.digest
141
- }
142
- },
143
- isRelease: config.isRelease,
144
- readOnly: policy.readOnly ?? false,
145
- requireApproval: (0, _policy.resolveRequireApproval)(policy),
146
- appName: config.appName,
147
- platform: config.platform
148
- });
225
+ composeSystem();
149
226
  }
150
227
  return {
151
228
  ledger,
229
+ evidence,
230
+ calibration,
231
+ trustedActions: () => [...trusted],
232
+ untrust: key => {
233
+ trusted.delete(key);
234
+ },
152
235
  get messages() {
153
236
  return messages;
154
237
  },
@@ -157,35 +240,128 @@ function createAskBuoySession(config) {
157
240
  availableActions = actions;
158
241
  availableToolIds = Object.keys(actions);
159
242
  },
243
+ setApprovalBypass(enabled) {
244
+ if (bypassApproval === enabled) return;
245
+ bypassApproval = enabled;
246
+ refreshLive();
247
+ // The prompt tells the model whether a card will appear before its
248
+ // change lands; leaving that paragraph stale would have it announce an
249
+ // approval step that no longer exists. Rebuilt from the held digest, so
250
+ // toggling mid-conversation costs nothing and re-reads nothing.
251
+ if (system) composeSystem();
252
+ },
253
+ setReadOnly(enabled) {
254
+ if (deviceReadOnly === enabled) return;
255
+ deviceReadOnly = enabled;
256
+ refreshLive();
257
+ if (system) composeSystem();
258
+ },
160
259
  restore(history) {
161
260
  // Only into a session that has not been talked to. Restoring over a live
162
261
  // conversation would drop whatever was said since the app started.
163
262
  if (messages.length > 0) return;
164
- messages = trimHistory(resumableHistory(history));
263
+ const report = (0, _historyBudget.trimHistoryReport)(resumableHistory(history), calibration.charsPerToken, ledger.liveCallIds());
264
+ messages = report.messages;
265
+ trimmedOnRestore = report.droppedRounds;
165
266
  },
166
267
  async *send(text, signal) {
268
+ /**
269
+ * Captured FIRST, before any await.
270
+ *
271
+ * Priming and the live-context probes are awaits like any other, and a
272
+ * reset can land inside them. Reading the generation after them would
273
+ * pick up the NEW conversation's value and let this turn commit into it —
274
+ * the precise bug this guards against, reintroduced one line lower.
275
+ */
276
+ const myGeneration = generation;
167
277
  await prime();
168
- messages.push({
278
+ // The RIGHT NOW block: re-read on EVERY turn, not once at open. The
279
+ // stable digest above was once the whole picture, and it was built
280
+ // before the user had navigated anywhere — so the query that owned the
281
+ // screen they were looking at was simply not in the prompt. This is the
282
+ // uncached tail of the system prompt (see ProviderRequest.systemVolatile).
283
+ let live;
284
+ try {
285
+ live = await (0, _buildContextPack.buildLiveContext)({
286
+ dispatch: config.dispatch,
287
+ readSnapshot: config.readSnapshot,
288
+ availableToolIds,
289
+ availableActions
290
+ });
291
+ } catch {
292
+ live = undefined;
293
+ }
294
+ /**
295
+ * The conversation was cleared while this turn was still getting ready.
296
+ *
297
+ * Priming and the live probes take real time, so "New conversation"
298
+ * lands here often enough to matter. Abandoning now costs nothing: the
299
+ * model has not been asked anything yet.
300
+ */
301
+ if (myGeneration !== generation) {
302
+ yield {
303
+ type: "done",
304
+ stopReason: "superseded"
305
+ };
306
+ return;
307
+ }
308
+
309
+ /**
310
+ * The turn works on its OWN array, and `messages` is assigned in exactly
311
+ * one place — the commit at the bottom.
312
+ *
313
+ * `runAgentTurn` pushes each round into the array it is handed. Handing
314
+ * it the session's own array made every push a live edit of session
315
+ * state, so a turn racing a reset wrote its whole history into the new
316
+ * conversation one push at a time and the commit guard had nothing left
317
+ * to protect. Copying makes ownership checkable in one place instead of
318
+ * spread across the loop.
319
+ */
320
+ const trimmed = (0, _historyBudget.trimHistoryReport)([...messages, {
169
321
  role: "user",
170
322
  text
171
- });
172
- messages = trimHistory(messages);
323
+ }], calibration.charsPerToken, ledger.liveCallIds());
324
+ const working = trimmed.messages;
325
+ // Said once, before the answer it affects. The screen still shows the
326
+ // rounds the model just lost; this is the only thing that tells the two
327
+ // apart. See the `history-trimmed` event.
328
+ const droppedRounds = trimmed.droppedRounds + trimmedOnRestore;
329
+ trimmedOnRestore = 0;
330
+ if (droppedRounds > 0) yield {
331
+ type: "history-trimmed",
332
+ droppedRounds,
333
+ droppedPinned: trimmed.droppedPinned
334
+ };
173
335
  const gen = (0, _runAgentTurn.runAgentTurn)({
174
336
  provider,
175
337
  catalog,
176
- messages,
338
+ messages: working,
177
339
  system: system,
340
+ systemVolatile: (0, _systemPrompt.buildLiveBlock)(live,
341
+ // What this conversation has already done to the app. See
342
+ // buildLiveBlock — without it the model answers "what have you
343
+ // changed?" from memory of its own sentences, and reports a value it
344
+ // overwrote itself as the app's own.
345
+ ledger.list().map(e => ({
346
+ label: `${e.toolId}.${e.action}${e.effect.label ? ` — ${e.effect.label}` : ""}`,
347
+ undone: e.undoneAt !== undefined
348
+ }))),
178
349
  model: config.model,
179
350
  maxTokens: config.maxTokens ?? 4096,
180
351
  dispatch: config.dispatch,
181
352
  readSnapshot: config.readSnapshot,
182
353
  storeKeyOwners,
183
354
  ledger,
184
- policy,
355
+ policy: activePolicy(),
185
356
  isRelease: config.isRelease,
186
357
  availableToolIds,
187
358
  availableActions,
188
359
  requestApproval: config.requestApproval,
360
+ seenUrls,
361
+ evidence,
362
+ calibration,
363
+ trusted,
364
+ procedures: (0, _systemPrompt.listableProcedures)(config.context?.procedures, availableToolIds),
189
365
  signal
190
366
  });
191
367
  let next = await gen.next();
@@ -194,11 +370,19 @@ function createAskBuoySession(config) {
194
370
  next = await gen.next();
195
371
  }
196
372
  // The generator's return value is the full history including tool turns.
197
- messages = next.value;
373
+ // Committed only if this turn still owns the conversation — see
374
+ // `generation`.
375
+ if (myGeneration === generation) messages = next.value;
198
376
  },
199
377
  reset() {
378
+ // Before anything else: a turn still draining must not commit over this.
379
+ generation += 1;
200
380
  messages = [];
381
+ trimmedOnRestore = 0;
201
382
  ledger.clear();
383
+ seenUrls.clear();
384
+ evidence.clear();
385
+ trusted.clear();
202
386
  // The grounding digest is a snapshot of the app AT OPEN — stores and
203
387
  // routes registered since are invisible to it. A new conversation is
204
388
  // the natural moment to re-read the world.