@buoy-gg/agent-core 7.0.41 → 7.0.43

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,263 +1 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.SNAPSHOT_ACTION = void 0;
7
- exports.projectSnapshot = projectSnapshot;
8
- var _redact = require("../policy/redact");
9
- /**
10
- * The other half of Buoy's read surface.
11
- *
12
- * Every Buoy adapter answers in two ways, and only one of them is an action.
13
- * `listQueries`, `async.getAllKeys` and `getState` are actions; console
14
- * entries, network events, the route sitemap and the env table are NOT — they
15
- * exist only inside the adapter's `getSnapshot`, which the sync layer polls and
16
- * puts on the wire for MCP's `get_snapshot` / `get_console` /
17
- * `get_network_requests` / `get_routes`.
18
- *
19
- * `dispatchToolAction` reaches only the first half. So an agent driving tools
20
- * on the device could read storage, stores and the query cache, and was blind
21
- * to the app's logs, its HTTP traffic, its routes and its environment — the
22
- * four things a QA person is most likely to ask about, and two of which the
23
- * empty state advertises as suggestions. The catalog even tells the model to
24
- * "use get_console", which is an MCP tool that does not exist on this path.
25
- *
26
- * This module closes that half. `getSnapshot` is a RESERVED action name: the
27
- * engine intercepts it before dispatch and routes it to the registry's
28
- * snapshot reader instead.
29
- *
30
- * WHY THE PROJECTIONS. A raw snapshot is the heaviest payload in the system —
31
- * measured at ~1.1KB per console entry with up to 1000 retained, and network
32
- * events carry bodies. Handing that to a token-metered model truncated at 24K
33
- * chars produces a torn JSON object and a wasted turn. Each projector here
34
- * does what the matching MCP tool does: newest-first, filtered, and only the
35
- * fields worth spending tokens on. Bodies stay behind `network.getEventBody`,
36
- * which already exists.
37
- */
38
-
39
- /** Reserved action name. Not a real adapter action anywhere. */
40
- const SNAPSHOT_ACTION = exports.SNAPSHOT_ACTION = "getSnapshot";
41
- const SEVERITY = {
42
- verbose: 0,
43
- debug: 0,
44
- trace: 0,
45
- log: 1,
46
- info: 1,
47
- warn: 2,
48
- warning: 2,
49
- error: 3
50
- };
51
- function asArray(value) {
52
- return Array.isArray(value) ? value : [];
53
- }
54
- function rec(value) {
55
- return value && typeof value === "object" ? value : {};
56
- }
57
- function num(value, fallback) {
58
- return typeof value === "number" && value > 0 ? value : fallback;
59
- }
60
-
61
- /**
62
- * The newest N. Every Buoy event store (BaseEventStore, which network,
63
- * console, sentry and route events all sit on) PREPENDS, so the list arrives
64
- * newest-FIRST and the newest N are the first N. An earlier version took the
65
- * LAST N here — the oldest — so once more than N were captured, RIGHT NOW
66
- * showed the stalest requests and a crash that had just happened fell out of
67
- * the console projection. Order is preserved: newest first.
68
- */
69
- function newest(items, limit) {
70
- return items.length <= limit ? items : items.slice(0, limit);
71
- }
72
- function projectConsole(payload, params) {
73
- const entries = asArray(rec(payload).entries);
74
- const minSeverity = typeof params.level === "string" ? SEVERITY[params.level] ?? 0 : 0;
75
- const pattern = typeof params.pattern === "string" ? params.pattern.toLowerCase() : undefined;
76
- const matched = entries.filter(raw => {
77
- const e = rec(raw);
78
- const level = String(e.level ?? "log");
79
- if ((SEVERITY[level] ?? 1) < minSeverity) return false;
80
- if (!pattern) return true;
81
- return String(e.message ?? "").toLowerCase().includes(pattern);
82
- });
83
- const shown = newest(matched, num(params.limit, 40));
84
- return {
85
- totalCaptured: entries.length,
86
- shown: shown.length,
87
- // Pre-rendered message only. Full args and stacks stay on the device;
88
- // `get_snapshot('console')` is the MCP escape hatch and has no equivalent
89
- // here on purpose — it is the payload that blows the prompt.
90
- entries: shown.map(raw => {
91
- const e = rec(raw);
92
- return {
93
- at: e.timestamp,
94
- level: e.level,
95
- message: e.message
96
- };
97
- })
98
- };
99
- }
100
- function projectNetwork(payload, params) {
101
- const p = rec(payload);
102
- // The agent's own POSTs to the model endpoint are dropped HERE, not only by
103
- // the engine's later pass, so the counts the model is given match the rows
104
- // it is given. Reporting "4 requests" above a list of 3 is its own small lie.
105
- const events = asArray(p.events).filter(raw => !(0, _redact.isSelfTraffic)(rec(raw).url));
106
- const failedOnly = params.failedOnly === true;
107
- const pattern = typeof params.pattern === "string" ? params.pattern.toLowerCase() : undefined;
108
- const matched = events.filter(raw => {
109
- const e = rec(raw);
110
- const status = typeof e.status === "number" ? e.status : undefined;
111
- if (failedOnly && !(e.error || status !== undefined && status >= 400)) return false;
112
- if (!pattern) return true;
113
- return String(e.url ?? "").toLowerCase().includes(pattern);
114
- });
115
- const shown = newest(matched, num(params.limit, 25));
116
- return {
117
- totalCaptured: events.length,
118
- shown: shown.length,
119
- // No bodies. `network.getEventBody` fetches one on demand, which is the
120
- // difference between a readable list and a truncated blob.
121
- requests: shown.map(raw => {
122
- const e = rec(raw);
123
- return {
124
- id: e.id,
125
- method: e.method,
126
- url: e.url,
127
- status: e.status,
128
- durationMs: e.duration,
129
- error: e.error,
130
- // An override rule served this response. Carried through so neither
131
- // the model nor the receipt can present mocked data as live.
132
- overridden: e.override ? true : undefined
133
- };
134
- }),
135
- hint: "Read one response with network.getEventBody({ id })."
136
- };
137
- }
138
-
139
- /**
140
- * The sitemap arrives as a NESTED RouteInfo tree, not a list. A model asked
141
- * "what screens exist" needs the leaf paths, so flatten and keep the paths.
142
- */
143
- function flattenRoutes(nodes, out = [], cap = 80) {
144
- for (const raw of asArray(nodes)) {
145
- if (out.length >= cap) break;
146
- const node = rec(raw);
147
- if (node.isInternal !== true && typeof node.path === "string") out.push(node.path);
148
- flattenRoutes(node.children, out, cap);
149
- }
150
- return out;
151
- }
152
- function projectRoutes(payload, params) {
153
- const p = rec(payload);
154
- const sitemap = rec(p.sitemap);
155
-
156
- // Route events are stored newest-FIRST, and a stack item's screen path is
157
- // `pathname` (`path` does not exist on it). Getting either wrong is not a
158
- // crash, it is a confident wrong answer: an early version of this read told
159
- // the user they were on the Pokedex while the shop was on screen.
160
- const stackRaw = asArray(p.stack).map(rec);
161
- const eventsRaw = asArray(p.events).map(rec);
162
- const stack = stackRaw.map(s => ({
163
- name: s.name,
164
- path: s.pathname,
165
- focused: s.isFocused === true ? true : undefined
166
- }));
167
- const recentNavigations = eventsRaw.slice(0, num(params.limit, 15)).map(e => ({
168
- at: e.timestamp,
169
- from: e.previousPathname,
170
- to: e.pathname
171
- }));
172
-
173
- // Mirrors the adapter's own `getCurrentRoute`: the newest navigation event
174
- // wins, and with no history yet — a freshly launched app — the FOCUSED stack
175
- // item does, which is not always the last one in the array.
176
- const focused = stackRaw.find(s => s.isFocused === true) ?? stackRaw[stackRaw.length - 1];
177
- const currentRoute = eventsRaw.length ? {
178
- path: eventsRaw[0].pathname,
179
- source: "event"
180
- } : typeof focused?.pathname === "string" ? {
181
- path: focused.pathname,
182
- source: "stack"
183
- } : undefined;
184
- return {
185
- currentRoute,
186
- stack,
187
- routes: flattenRoutes(sitemap.routes),
188
- sitemapSource: sitemap.source,
189
- recentNavigations
190
- };
191
- }
192
- function projectEnv(payload) {
193
- const p = rec(payload);
194
- return {
195
- env: p.env ?? p.variables,
196
- requiredEnvVars: p.requiredEnvVars
197
- };
198
- }
199
-
200
- /**
201
- * Sentry envelopes are the fattest payloads any Buoy tool captures (a single
202
- * event with breadcrumbs is tens of KB), so only the item SUMMARIES travel —
203
- * the one-line human read the adapter already computes. The status field is
204
- * load-bearing: an empty list with "sdk-not-found" means the app has no
205
- * Sentry client, which is a different answer from "nothing errored".
206
- */
207
- function projectSentry(payload, params) {
208
- const p = rec(payload);
209
- const envelopes = asArray(p.envelopes).map(rec);
210
- const typeFilter = typeof params.type === "string" ? params.type : undefined;
211
- const pattern = typeof params.pattern === "string" ? params.pattern.toLowerCase() : undefined;
212
- const matched = envelopes.filter(e => {
213
- const items = asArray(e.items).map(rec);
214
- if (typeFilter && !items.some(i => i.type === typeFilter)) return false;
215
- if (!pattern) return true;
216
- return items.some(i => String(i.summary ?? "").toLowerCase().includes(pattern));
217
- });
218
- const shown = newest(matched, num(params.limit, 10));
219
- return {
220
- status: p.status,
221
- totalCaptured: envelopes.length,
222
- shown: shown.length,
223
- envelopes: shown.map(e => ({
224
- id: e.id,
225
- at: e.timestamp,
226
- origin: e.origin,
227
- eventId: e.eventId,
228
- totalBytes: e.totalBytes,
229
- items: asArray(e.items).map(raw => {
230
- const i = rec(raw);
231
- return {
232
- type: i.type,
233
- summary: i.summary,
234
- spanCount: i.spanCount,
235
- bytes: i.bytes
236
- };
237
- })
238
- })),
239
- hint: "For crash stack traces, console's [FATAL] entries carry the component stacks."
240
- };
241
- }
242
-
243
- /**
244
- * Trim one snapshot to something worth sending. Unknown tools pass through —
245
- * the engine's 24K truncation is still the backstop.
246
- */
247
- function projectSnapshot(toolId, payload, params = {}) {
248
- switch (toolId) {
249
- case "console":
250
- return projectConsole(payload, params);
251
- case "network":
252
- return projectNetwork(payload, params);
253
- case "route-events":
254
- return projectRoutes(payload, params);
255
- case "env":
256
- return projectEnv(payload);
257
- case "sentry":
258
- return projectSentry(payload, params);
259
- default:
260
- return payload;
261
- }
262
- }
263
- //# sourceMappingURL=snapshotReads.js.map
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SNAPSHOT_ACTION=void 0;exports.projectSnapshot=projectSnapshot;var _redact=require("../policy/redact");const SNAPSHOT_ACTION=exports.SNAPSHOT_ACTION="getSnapshot";const SEVERITY={verbose:0,debug:0,trace:0,log:1,info:1,warn:2,warning:2,error:3};function asArray(t){return Array.isArray(t)?t:[]}function rec(t){return t&&typeof t==="object"?t:{}}function num(t,e){return typeof t==="number"&&t>0?t:e}function newest(t,e){return t.length<=e?t:t.slice(0,e)}function projectConsole(t,e){const o=asArray(rec(t).entries);const u=typeof e.level==="string"?SEVERITY[e.level]??0:0;const i=typeof e.pattern==="string"?e.pattern.toLowerCase():void 0;const c=o.filter(a=>{const n=rec(a);const r=String(n.level??"log");if((SEVERITY[r]??1)<u)return false;if(!i)return true;return String(n.message??"").toLowerCase().includes(i)});const p=newest(c,num(e.limit,40));return{totalCaptured:o.length,shown:p.length,entries:p.map(a=>{const n=rec(a);return{at:n.timestamp,level:n.level,message:n.message}})}}function projectNetwork(t,e){const o=rec(t);const u=asArray(o.events).filter(n=>!(0,_redact.isSelfTraffic)(rec(n).url));const i=e.failedOnly===true;const c=typeof e.pattern==="string"?e.pattern.toLowerCase():void 0;const p=u.filter(n=>{const r=rec(n);const s=typeof r.status==="number"?r.status:void 0;if(i&&!(r.error||s!==void 0&&s>=400))return false;if(!c)return true;return String(r.url??"").toLowerCase().includes(c)});const a=newest(p,num(e.limit,25));return{totalCaptured:u.length,shown:a.length,requests:a.map(n=>{const r=rec(n);return{id:r.id,method:r.method,url:r.url,status:r.status,durationMs:r.duration,error:r.error,overridden:r.override?true:void 0}}),hint:"Read one response with network.getEventBody({ id })."}}function flattenRoutes(t,e=[],o=80){for(const u of asArray(t)){if(e.length>=o)break;const i=rec(u);if(i.isInternal!==true&&typeof i.path==="string")e.push(i.path);flattenRoutes(i.children,e,o)}return e}function projectRoutes(t,e){const o=rec(t);const u=rec(o.sitemap);const i=asArray(o.stack).map(rec);const c=asArray(o.events).map(rec);const p=i.map(s=>({name:s.name,path:s.pathname,focused:s.isFocused===true?true:void 0}));const a=c.slice(0,num(e.limit,15)).map(s=>({at:s.timestamp,from:s.previousPathname,to:s.pathname}));const n=i.find(s=>s.isFocused===true)??i[i.length-1];const r=c.length?{path:c[0].pathname,source:"event"}:typeof n?.pathname==="string"?{path:n.pathname,source:"stack"}:void 0;return{currentRoute:r,stack:p,routes:flattenRoutes(u.routes),sitemapSource:u.source,recentNavigations:a}}function projectEnv(t){const e=rec(t);return{env:e.env??e.variables,requiredEnvVars:e.requiredEnvVars}}function projectSentry(t,e){const o=rec(t);const u=asArray(o.envelopes).map(rec);const i=typeof e.type==="string"?e.type:void 0;const c=typeof e.pattern==="string"?e.pattern.toLowerCase():void 0;const p=u.filter(n=>{const r=asArray(n.items).map(rec);if(i&&!r.some(s=>s.type===i))return false;if(!c)return true;return r.some(s=>String(s.summary??"").toLowerCase().includes(c))});const a=newest(p,num(e.limit,10));return{status:o.status,totalCaptured:u.length,shown:a.length,envelopes:a.map(n=>({id:n.id,at:n.timestamp,origin:n.origin,eventId:n.eventId,totalBytes:n.totalBytes,items:asArray(n.items).map(r=>{const s=rec(r);return{type:s.type,summary:s.summary,spanCount:s.spanCount,bytes:s.bytes}})})),hint:"For crash stack traces, console's [FATAL] entries carry the component stacks."}}function projectSnapshot(t,e,o={}){switch(t){case"console":return projectConsole(e,o);case"network":return projectNetwork(e,o);case"route-events":return projectRoutes(e,o);case"env":return projectEnv(e);case"sentry":return projectSentry(e,o);default:return e}}
@@ -1,145 +1,2 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.fromProviderToolName = fromProviderToolName;
7
- exports.toProviderToolName = toProviderToolName;
8
- exports.toProviderTools = toProviderTools;
9
- var _signature = require("./signature");
10
- /**
11
- * Catalog -> provider tool definitions.
12
- *
13
- * WHY ONE TOOL PER BUOY TOOL, NOT ONE PER ACTION: tool-selection accuracy
14
- * degrades past roughly 30-50 tools. Buoy has ~179 actions across 22 tools, so
15
- * a 1:1 mapping is far past the point where the model starts picking wrong.
16
- * Each Buoy tool therefore becomes ONE provider tool whose `action` property is
17
- * an enum, with the per-action summaries folded into that enum's description.
18
- *
19
- * `params` stays an open object at the provider boundary — a discriminated
20
- * union across 179 branches is unusable by any model and unreadable by a human.
21
- * The real per-action schema is enforced one layer in, by `validateParams`,
22
- * which returns a structured error the model can correct on the next turn.
23
- * That is strictly stronger than the MCP server's `z.record(z.unknown())`,
24
- * which validates nothing.
25
- */
26
-
27
- /**
28
- * Provider-agnostic tool definition; the adapters reshape it per protocol.
29
- *
30
- * The description comes in three forms because the two protocols cap it
31
- * differently. Anthropic takes `description` whole. OpenAI (and Azure, and
32
- * every OpenAI-compatible gateway) caps a function description at 1024
33
- * chars, and the catalog renders the summary first and the `Actions:` list
34
- * LAST — so trimming `description` to fit dropped every action line for 23
35
- * of 24 tools (the 24th kept one line of sixteen), and a model on that
36
- * protocol saw a summary cut mid-sentence plus a bare `action` enum. Hence
37
- * the split: `summaryDescription` is the part that fits the cap,
38
- * `actionsBlock` goes into the `action` property's description, which
39
- * nothing caps. `description` stays their concatenation
40
- * so the Anthropic request is byte-identical to what it was.
41
- */
42
-
43
- /**
44
- * Both Anthropic and OpenAI cap tool names at `[a-zA-Z0-9_-]`, so Buoy's
45
- * dashed ids survive but the `custom:<id>` sync namespace does not. Anthropic's
46
- * docs say 64 chars while its reference schema says 128 — we code to 64.
47
- */
48
- const MAX_TOOL_NAME = 64;
49
- function toProviderToolName(toolId) {
50
- return `buoy_${toolId.replace(/[^a-zA-Z0-9_-]/g, "_")}`.slice(0, MAX_TOOL_NAME);
51
- }
52
-
53
- /** Reverse of {@link toProviderToolName}, resolved against the live catalog. */
54
- function fromProviderToolName(name, catalog) {
55
- return catalog.find(t => toProviderToolName(t.toolId) === name)?.toolId;
56
- }
57
-
58
- /**
59
- * One line per action, in the `action` enum's description. This is where the
60
- * model actually learns what each action does, so it carries the effect and
61
- * the release caveat inline rather than hiding them in a separate field the
62
- * model never sees.
63
- */
64
- function actionLine(a, isRelease) {
65
- const bits = [`${a.action} — ${a.summary}`];
66
- if (a.effect === "destructive") bits.push("[DESTRUCTIVE]");else if (a.effect === "write") bits.push("[changes state]");
67
- if (isRelease && a.release !== "works") {
68
- bits.push(`[UNAVAILABLE in this build: ${a.release}]`);
69
- }
70
- if (a.requires?.length) bits.push(`[needs: ${a.requires.join(", ")}]`);
71
- // The field names, from the SAME schema `validateParams` enforces. Without
72
- // them the model reconstructs parameter names from prose and invents one on
73
- // ~18% of param-carrying calls (measured across three agents); five of the
74
- // commonest misses are patched up by `normalizeParams`, the rest just fail.
75
- // `buoy_ui` already ships its signatures for exactly this reason — see the
76
- // note above `signature()` in catalog/signature.ts.
77
- const sig = (0, _signature.paramsLine)(a.params);
78
- return sig ? `${bits.join(" ")}\n ${sig}` : bits.join(" ");
79
- }
80
- function toProviderTools(catalog, opts = {}) {
81
- const {
82
- availableToolIds,
83
- availableActions,
84
- isRelease = false,
85
- hideUnavailable = false
86
- } = opts;
87
- const tools = [];
88
- for (const tool of catalog) {
89
- if (availableToolIds && !availableToolIds.includes(tool.toolId)) continue;
90
- const live = availableActions?.[tool.toolId];
91
- // An engine-served action needs no adapter to advertise it — the engine
92
- // is the adapter — so it rides with the tool whenever the tool is here.
93
- let actions = live ? tool.actions.filter(a => live.includes(a.action) || a.servedBy === "engine") : tool.actions;
94
- if (isRelease && hideUnavailable) {
95
- actions = actions.filter(a => a.release === "works");
96
- }
97
- if (actions.length === 0) continue;
98
-
99
- // The summary ALONE is what has to fit OpenAI's 1024-char cap (it does for
100
- // 23 of 24 tools); the availability caveat rides with the actions block,
101
- // which nothing caps. Concatenated they are the same bytes as before.
102
- const summaryDescription = tool.summary;
103
- // These prose lines look like the expensive part of the catalog and are
104
- // the CHEAPEST part of it. Measured against a real tokenizer (fal ->
105
- // gpt-4o-mini): the whole catalog is 79,601 chars but only 7,902 tokens
106
- // — 10.1 chars/token, because English prose is what BPE compresses best.
107
- // An index that replaced these lines with a bare list of action names
108
- // sent 48% fewer characters and cost MORE tokens (7,986), since dotted
109
- // camelCase identifiers tokenize at ~5 chars/token. Do not "shrink" this
110
- // by counting characters; measure tokens or leave it alone.
111
- const actionsBlock = [tool.unavailableWhen ? `Unavailable when: ${tool.unavailableWhen}` : "", "Actions:", ...actions.map(a => `- ${actionLine(a, isRelease)}`)].join("\n");
112
- // No blank line between the two: the single-list render this replaced
113
- // filtered its "" separator out, and this string is the prefix Anthropic
114
- // caches — it must not move by a byte.
115
- const desc = [summaryDescription, actionsBlock].filter(Boolean).join("\n");
116
- const inputExamples = actions.flatMap(a => a.inputExamples ?? []);
117
- tools.push({
118
- name: toProviderToolName(tool.toolId),
119
- ...(inputExamples.length ? {
120
- inputExamples
121
- } : {}),
122
- description: desc,
123
- summaryDescription,
124
- actionsBlock,
125
- inputSchema: {
126
- type: "object",
127
- properties: {
128
- action: {
129
- type: "string",
130
- enum: actions.map(a => a.action),
131
- description: "Which action to run. See the list in this tool's description."
132
- },
133
- params: {
134
- type: "object",
135
- description: "Arguments for the action. Each action's `params:` line in this tool's description lists its exact fields — `*` marks a required one. Send EXACTLY those names; a field that is not listed is rejected."
136
- }
137
- },
138
- required: ["action"],
139
- additionalProperties: false
140
- }
141
- });
142
- }
143
- return tools;
144
- }
145
- //# sourceMappingURL=toProviderTools.js.map
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.fromProviderToolName=fromProviderToolName;exports.toProviderToolName=toProviderToolName;exports.toProviderTools=toProviderTools;var _signature=require("./signature");const MAX_TOOL_NAME=64;function toProviderToolName(e){return`buoy_${e.replace(/[^a-zA-Z0-9_-]/g,"_")}`.slice(0,MAX_TOOL_NAME)}function fromProviderToolName(e,s){return s.find(o=>toProviderToolName(o.toolId)===e)?.toolId}function actionLine(e,s){const o=[`${e.action} \u2014 ${e.summary}`];if(e.effect==="destructive")o.push("[DESTRUCTIVE]");else if(e.effect==="write")o.push("[changes state]");if(s&&e.release!=="works"){o.push(`[UNAVAILABLE in this build: ${e.release}]`)}if(e.requires?.length)o.push(`[needs: ${e.requires.join(", ")}]`);const r=(0,_signature.paramsLine)(e.params);return r?`${o.join(" ")}
2
+ ${r}`:o.join(" ")}function toProviderTools(e,s={}){const{availableToolIds:o,availableActions:r,isRelease:a=false,hideUnavailable:f=false}=s;const l=[];for(const i of e){if(o&&!o.includes(i.toolId))continue;const c=r?.[i.toolId];let n=c?i.actions.filter(t=>c.includes(t.action)||t.servedBy==="engine"):i.actions;if(a&&f){n=n.filter(t=>t.release==="works")}if(n.length===0)continue;const u=i.summary;const d=[i.unavailableWhen?`Unavailable when: ${i.unavailableWhen}`:"","Actions:",...n.map(t=>`- ${actionLine(t,a)}`)].join("\n");const m=[u,d].filter(Boolean).join("\n");const p=n.flatMap(t=>t.inputExamples??[]);l.push({name:toProviderToolName(i.toolId),...p.length?{inputExamples:p}:{},description:m,summaryDescription:u,actionsBlock:d,inputSchema:{type:"object",properties:{action:{type:"string",enum:n.map(t=>t.action),description:"Which action to run. See the list in this tool's description."},params:{type:"object",description:"Arguments for the action. Each action's `params:` line in this tool's description lists its exact fields \u2014 `*` marks a required one. Send EXACTLY those names; a field that is not listed is rejected."}},required:["action"],additionalProperties:false}})}return l}
@@ -1,129 +1 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.applyDefaults = applyDefaults;
7
- exports.validateParams = validateParams;
8
- /**
9
- * A deliberately small JSON Schema validator.
10
- *
11
- * Buoy's adapters validate nothing — every handler takes `params?: unknown` and
12
- * hand-casts (`(params as { id?: string })?.id`), so a wrong shape becomes an
13
- * undefined read, and an LLM omitting an optional flag can do real damage:
14
- * `zustand.setState` defaults `replace ?? true`, so calling it without
15
- * `replace` REPLACES the entire store rather than merging it.
16
- *
17
- * So the agent validates before it dispatches. The point is not spec
18
- * compliance — it is that a rejection comes back to the model as a readable
19
- * error naming the expected schema, which it can fix on the next turn. That is
20
- * why this covers exactly the subset `JsonSchema` describes and nothing more:
21
- * a rule the validator silently skips is a rule that isn't enforced.
22
- */
23
-
24
- function typeOf(v) {
25
- if (v === null) return "null";
26
- if (Array.isArray(v)) return "array";
27
- return typeof v;
28
- }
29
- function checkType(value, type) {
30
- switch (type) {
31
- case "integer":
32
- return typeof value === "number" && Number.isInteger(value);
33
- case "number":
34
- return typeof value === "number" && Number.isFinite(value);
35
- case "null":
36
- return value === null;
37
- case "array":
38
- return Array.isArray(value);
39
- case "object":
40
- return typeOf(value) === "object";
41
- default:
42
- return typeof value === type;
43
- }
44
- }
45
- function validate(value, schema, path, errors) {
46
- if (schema.anyOf?.length) {
47
- const anyOk = schema.anyOf.some(s => {
48
- const sub = [];
49
- validate(value, s, path, sub);
50
- return sub.length === 0;
51
- });
52
- if (!anyOk) {
53
- const kinds = schema.anyOf.map(s => s.type ?? "?").join(" | ");
54
- errors.push(`${path}: expected ${kinds}, got ${typeOf(value)}`);
55
- }
56
- return;
57
- }
58
- if (schema.type && !checkType(value, schema.type)) {
59
- errors.push(`${path}: expected ${schema.type}, got ${typeOf(value)}`);
60
- return;
61
- }
62
- if (schema.enum && !schema.enum.includes(value)) {
63
- errors.push(`${path}: expected one of ${schema.enum.map(e => JSON.stringify(e)).join(", ")}, got ${JSON.stringify(value)}`);
64
- return;
65
- }
66
- if (schema.type === "array" && Array.isArray(value)) {
67
- if (schema.minItems !== undefined && value.length < schema.minItems) {
68
- errors.push(`${path}: expected at least ${schema.minItems} item(s), got ${value.length}`);
69
- }
70
- if (schema.maxItems !== undefined && value.length > schema.maxItems) {
71
- errors.push(`${path}: expected at most ${schema.maxItems} item(s), got ${value.length}`);
72
- }
73
- if (schema.items) {
74
- value.forEach((item, i) => validate(item, schema.items, `${path}[${i}]`, errors));
75
- }
76
- return;
77
- }
78
- if (schema.type === "object" && typeOf(value) === "object") {
79
- const obj = value;
80
- for (const key of schema.required ?? []) {
81
- if (obj[key] === undefined) errors.push(`${path}.${key}: required`);
82
- }
83
- if (schema.properties) {
84
- for (const [key, sub] of Object.entries(schema.properties)) {
85
- if (obj[key] !== undefined) validate(obj[key], sub, `${path}.${key}`, errors);
86
- }
87
- // Only flag unknown keys when the schema says so. Several adapters read
88
- // params they never documented, and rejecting an extra key the handler
89
- // happens to use would break a call that would have worked.
90
- if (schema.additionalProperties === false) {
91
- const known = new Set(Object.keys(schema.properties));
92
- for (const key of Object.keys(obj)) {
93
- if (!known.has(key)) errors.push(`${path}.${key}: unexpected property`);
94
- }
95
- }
96
- }
97
- }
98
- }
99
- function validateParams(params, schema) {
100
- const errors = [];
101
- // A no-param action called with nothing is the common case, not an error.
102
- const value = params === undefined || params === null ? {} : params;
103
- validate(value, schema, "params", errors);
104
- return {
105
- ok: errors.length === 0,
106
- errors
107
- };
108
- }
109
-
110
- /**
111
- * Fill in documented defaults the model left out.
112
- *
113
- * This is the counter-measure to the omitted-flag class of bug. Several Buoy
114
- * actions invert the usual assumption — `focus-inspector.setTracking` reads
115
- * `params?.enabled !== false`, so calling it with `{}` turns tracking ON — and
116
- * the catalog records the real default. Applying it explicitly means the model
117
- * omitting a flag produces the documented behaviour rather than the accidental
118
- * one.
119
- */
120
- function applyDefaults(params, schema) {
121
- const out = typeOf(params) === "object" ? {
122
- ...params
123
- } : {};
124
- for (const [key, sub] of Object.entries(schema.properties ?? {})) {
125
- if (out[key] === undefined && sub.default !== undefined) out[key] = sub.default;
126
- }
127
- return out;
128
- }
129
- //# sourceMappingURL=validateParams.js.map
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.applyDefaults=applyDefaults;exports.validateParams=validateParams;function typeOf(t){if(t===null)return"null";if(Array.isArray(t))return"array";return typeof t}function checkType(t,e){switch(e){case"integer":return typeof t==="number"&&Number.isInteger(t);case"number":return typeof t==="number"&&Number.isFinite(t);case"null":return t===null;case"array":return Array.isArray(t);case"object":return typeOf(t)==="object";default:return typeof t===e}}function validate(t,e,n,i){if(e.anyOf?.length){const f=e.anyOf.some(r=>{const o=[];validate(t,r,n,o);return o.length===0});if(!f){const r=e.anyOf.map(o=>o.type??"?").join(" | ");i.push(`${n}: expected ${r}, got ${typeOf(t)}`)}return}if(e.type&&!checkType(t,e.type)){i.push(`${n}: expected ${e.type}, got ${typeOf(t)}`);return}if(e.enum&&!e.enum.includes(t)){i.push(`${n}: expected one of ${e.enum.map(f=>JSON.stringify(f)).join(", ")}, got ${JSON.stringify(t)}`);return}if(e.type==="array"&&Array.isArray(t)){if(e.minItems!==void 0&&t.length<e.minItems){i.push(`${n}: expected at least ${e.minItems} item(s), got ${t.length}`)}if(e.maxItems!==void 0&&t.length>e.maxItems){i.push(`${n}: expected at most ${e.maxItems} item(s), got ${t.length}`)}if(e.items){t.forEach((f,r)=>validate(f,e.items,`${n}[${r}]`,i))}return}if(e.type==="object"&&typeOf(t)==="object"){const f=t;for(const r of e.required??[]){if(f[r]===void 0)i.push(`${n}.${r}: required`)}if(e.properties){for(const[r,o]of Object.entries(e.properties)){if(f[r]!==void 0)validate(f[r],o,`${n}.${r}`,i)}if(e.additionalProperties===false){const r=new Set(Object.keys(e.properties));for(const o of Object.keys(f)){if(!r.has(o))i.push(`${n}.${o}: unexpected property`)}}}}}function validateParams(t,e){const n=[];const i=t===void 0||t===null?{}:t;validate(i,e,"params",n);return{ok:n.length===0,errors:n}}function applyDefaults(t,e){const n=typeOf(t)==="object"?{...t}:{};for(const[i,f]of Object.entries(e.properties??{})){if(n[i]===void 0&&f.default!==void 0)n[i]=f.default}return n}