@b3os/mcp 0.2.0 → 0.2.2

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 (48) hide show
  1. package/README.md +26 -4
  2. package/dist/handlers/_common.d.ts +14 -0
  3. package/dist/handlers/_common.js +27 -0
  4. package/dist/handlers/_common.js.map +1 -1
  5. package/dist/handlers/actions.d.ts +12 -1
  6. package/dist/handlers/actions.js +51 -2
  7. package/dist/handlers/actions.js.map +1 -1
  8. package/dist/handlers/agents.d.ts +2 -0
  9. package/dist/handlers/agents.js +41 -0
  10. package/dist/handlers/agents.js.map +1 -0
  11. package/dist/handlers/platform.d.ts +32 -0
  12. package/dist/handlers/platform.js +663 -0
  13. package/dist/handlers/platform.js.map +1 -0
  14. package/dist/handlers/render.d.ts +13 -0
  15. package/dist/handlers/render.js +145 -18
  16. package/dist/handlers/render.js.map +1 -1
  17. package/dist/handlers/routines.d.ts +8 -2
  18. package/dist/handlers/routines.js +154 -15
  19. package/dist/handlers/routines.js.map +1 -1
  20. package/dist/server.js +1 -1
  21. package/dist/table.gen.js +3312 -42
  22. package/dist/table.gen.js.map +1 -1
  23. package/dist/table.js +4 -0
  24. package/dist/table.js.map +1 -1
  25. package/dist/tools.js +3 -0
  26. package/dist/tools.js.map +1 -1
  27. package/package.json +2 -2
  28. package/src/handlers/_common.ts +37 -0
  29. package/src/handlers/actions.ts +50 -2
  30. package/src/handlers/agents.ts +50 -0
  31. package/src/handlers/platform.ts +711 -0
  32. package/src/handlers/render.ts +147 -16
  33. package/src/handlers/routines.ts +164 -14
  34. package/src/server.ts +1 -1
  35. package/src/table.gen.ts +3367 -36
  36. package/src/table.ts +4 -0
  37. package/src/tools.ts +3 -0
  38. package/table/core.mjs +13 -2
  39. package/table/node-toolsets.json +668 -0
  40. package/table/requests.json +771 -0
  41. package/table/table.json +3315 -45
  42. package/table/tools/agents.mjs +230 -0
  43. package/table/tools/listeners.mjs +124 -0
  44. package/table/tools/platform.mjs +136 -3
  45. package/table/tools/render.mjs +157 -3
  46. package/table/tools/routines.mjs +37 -0
  47. package/table/tools/sandboxes.mjs +69 -0
  48. package/table/tools.mjs +3 -1
@@ -0,0 +1,663 @@
1
+ // Platform tool handlers of the MCP tool runtime (owner: platform-dx, plan 1.2): the read tools for traces, the
2
+ // request log and kept model calls (B3-6853, NOTES/deploy-platform/observability.md 8.5), so an agent can look at
3
+ // what its own calls did. src/table.ts merges every product's RUNNERS.
4
+ //
5
+ // Every answer is shaped for a model to read: a header line, then one or two lines per record with the fields the
6
+ // console shows first (time, operation, status, duration, error), then how to read more (a cursor, from_span,
7
+ // max_chars). The structured content is the API's answer for one-record tools and a compact copy of what the text
8
+ // shows for the others. A kept call's prompt and answer come only from llm_calls_get_prompt_and_answer, which the
9
+ // API answers only to a key that holds platform:content:read, cut by default and with its redaction markers intact.
10
+ //
11
+ // No new API operation: a trace list is the request log grouped by trace id (the console's Traces tab does the
12
+ // same, apps/web/src/lib/traces.ts groupTraces), and a request's usage is its usage records.
13
+ import { abortError, buildRequest, clip, int, intArg, isObj, json, listOf, ms, nextCursor, requestFor, short, text, when, } from "./_common.js";
14
+ const SANDBOX_EXEC = new Set([
15
+ "sandboxesExec",
16
+ "sandboxesRunCode",
17
+ "sandboxesWriteFile",
18
+ "sandboxesReadFile",
19
+ "sandboxesListProcesses",
20
+ "sandboxesKillProcess",
21
+ ]);
22
+ export function spanKind(product, op) {
23
+ switch (product) {
24
+ case "infer":
25
+ return "model";
26
+ case "vision":
27
+ return "vision";
28
+ case "render":
29
+ return "render";
30
+ case "actions":
31
+ return "action";
32
+ case "routines":
33
+ return "routine";
34
+ case "sandboxes":
35
+ return typeof op === "string" && SANDBOX_EXEC.has(op) ? "sandbox.exec" : "request";
36
+ default:
37
+ return "request";
38
+ }
39
+ }
40
+ /** `<product>.<operation>` (`vision.scrape`), or the path when the operation is not known. */
41
+ export function spanName(product, op, path) {
42
+ if (typeof op !== "string" || !op)
43
+ return typeof path === "string" ? path : "";
44
+ const p = typeof product === "string" ? product : "";
45
+ const rest = p && op.startsWith(p) ? op.slice(p.length) : op;
46
+ return p ? `${p}.${rest.charAt(0).toLowerCase()}${rest.slice(1)}` : op;
47
+ }
48
+ /** Each kind's count in words: `2 model calls, 1 page, 1 command` (apps/web/src/lib/traces.ts turnSummary). */
49
+ const KIND_COUNT = {
50
+ model: ["model call", "model calls"],
51
+ vision: ["page", "pages"],
52
+ routine: ["routine", "routines"],
53
+ action: ["pack action", "pack actions"],
54
+ "sandbox.exec": ["command", "commands"],
55
+ render: ["render", "renders"],
56
+ request: ["other call", "other calls"],
57
+ };
58
+ function kindSummary(kinds) {
59
+ const counts = new Map();
60
+ for (const k of kinds)
61
+ counts.set(k, (counts.get(k) ?? 0) + 1);
62
+ return [...counts].map(([k, n]) => `${n} ${KIND_COUNT[k][n === 1 ? 0 : 1]}`).join(", ");
63
+ }
64
+ /**
65
+ * The last SDK versions that send no trace mark: a trace only they made is one call per trace id. A copy of
66
+ * @b3os/sdk TRACE_MARK_AFTER (this runtime imports nothing but the table; test/observability-tools.test.ts holds
67
+ * the two equal).
68
+ */
69
+ export const TRACE_MARK_AFTER = { ts: "0.1.3", python: "0.1.3" };
70
+ const SDK_UA = /^b3os-sdk-(ts|python)\/(\d+)\.(\d+)\.(\d+)/;
71
+ function unmarkedSdk(ua) {
72
+ const m = typeof ua === "string" ? SDK_UA.exec(ua) : null;
73
+ if (!m)
74
+ return false;
75
+ const max = TRACE_MARK_AFTER[m[1] === "ts" ? "ts" : "python"].split(".").map(Number);
76
+ const v = [Number(m[2]), Number(m[3]), Number(m[4])];
77
+ for (let i = 0; i < 3; i++)
78
+ if (v[i] !== max[i])
79
+ return (v[i] ?? 0) < (max[i] ?? 0);
80
+ return true;
81
+ }
82
+ /** `call` for one call and its retries, or a trace only unmarked SDKs made; else `traceparent` (a turn). */
83
+ export function originOf(rows) {
84
+ const first = rows[0];
85
+ if (!first)
86
+ return "call";
87
+ const retried = (r) => r.status_code === 429 || (typeof r.status_code === "number" && r.status_code >= 500);
88
+ if (rows.every((r) => r.operation_id === first.operation_id && r.path === first.path) &&
89
+ rows.slice(0, -1).every(retried))
90
+ return "call";
91
+ return rows.every((r) => unmarkedSdk(r.user_agent)) ? "call" : "traceparent";
92
+ }
93
+ const failed = (r) => typeof r.status_code === "number" && r.status_code >= 400;
94
+ const startMs = (r) => Date.parse(String(r.started_at ?? ""));
95
+ const endMs = (r) => startMs(r) + (typeof r.duration_ms === "number" ? r.duration_ms : 0);
96
+ /** Usage summed by unit, in unit order. */
97
+ function sumUsage(rows) {
98
+ const m = new Map();
99
+ for (const r of rows)
100
+ if (typeof r.unit === "string" && typeof r.qty === "number")
101
+ m.set(r.unit, (m.get(r.unit) ?? 0) + r.qty);
102
+ return [...m].map(([unit, qty]) => ({ unit, qty })).sort((a, b) => (a.unit < b.unit ? -1 : a.unit > b.unit ? 1 : 0));
103
+ }
104
+ const qty = (n) => (Number.isInteger(n) ? int(n) : `${+n.toPrecision(4)}`);
105
+ /** `1,830 in / 212 out tokens, vision.page 1`: model tokens first, in words, then every other unit as recorded. */
106
+ function usageText(usage) {
107
+ const of = (u) => usage.find((x) => x.unit === u)?.qty;
108
+ const tin = of("infer.input_tokens");
109
+ const tout = of("infer.output_tokens");
110
+ const parts = [];
111
+ if (tin !== undefined || tout !== undefined)
112
+ parts.push(`${qty(tin ?? 0)} in / ${qty(tout ?? 0)} out tokens`);
113
+ for (const u of usage)
114
+ if (u.unit !== "infer.input_tokens" && u.unit !== "infer.output_tokens")
115
+ parts.push(`${u.unit} ${qty(u.qty)}`);
116
+ return parts.join(", ");
117
+ }
118
+ const usageOf = (v) => sumUsage(Array.isArray(v) ? v.filter(isObj) : []);
119
+ // ---------------------------------------------------------------------------------------------------------------
120
+ // The request log
121
+ /** A request record in a line (plus its error on the next): what the console's Requests page shows first. */
122
+ function requestLines(r) {
123
+ const where = [r.source, r.sandbox_id ? `from ${r.sandbox_id}` : "", r.trace_id ? `trace ${r.trace_id}` : ""].filter(Boolean);
124
+ const head = `${r.id} ${when(r.started_at)} ${r.method} ${short(r.path, 100)} ${r.status_code} ${ms(r.duration_ms)} ${where.join(" ")}`;
125
+ const out = [head.trimEnd()];
126
+ if (failed(r))
127
+ out.push(` ${r.error_code ?? "error"}${r.error_detail ? `: ${short(r.error_detail, 200)}` : ""}`);
128
+ return out;
129
+ }
130
+ /** A secondary read that may fail without failing the tool: its answer, or the problem's code. A canceled call
131
+ * still ends the tool. */
132
+ async function maybe(ctx, read) {
133
+ try {
134
+ return await read();
135
+ }
136
+ catch (e) {
137
+ if (ctx.signal?.aborted)
138
+ throw abortError();
139
+ const code = e?.code;
140
+ return { failed: typeof code === "string" ? code : "error" };
141
+ }
142
+ }
143
+ const isFailure = (v) => isObj(v) && typeof v.failed === "string";
144
+ // ---------------------------------------------------------------------------------------------------------------
145
+ // Traces
146
+ /** Requests a trace list reads at most without `app`: the newest three pages of the log (the edge's trace cap). */
147
+ export const TRACE_SCAN = 300;
148
+ /** With `app`: the newest sandboxes of the application whose requests are read, 100 each. */
149
+ export const APP_SANDBOXES = 6;
150
+ function traceLines(t, partial) {
151
+ const kinds = t.rows.map((r) => spanKind(r.product, r.operation_id));
152
+ const sandboxes = [...new Set(t.rows.map((r) => r.sandbox_id).filter((s) => typeof s === "string"))];
153
+ const sources = [...new Set(t.rows.map((r) => String(r.source ?? "")).filter(Boolean))];
154
+ const from = sandboxes.length === 1
155
+ ? `from ${sandboxes[0]}`
156
+ : sandboxes.length
157
+ ? `from ${sandboxes.length} sandboxes`
158
+ : `via ${sources.join(", ")}`;
159
+ const status = t.errors ? `error: ${t.errors} failed` : "ok";
160
+ const calls = `${t.rows.length} call${t.rows.length === 1 ? "" : "s"} (${kindSummary(kinds)})`;
161
+ const head = `${t.id} ${when(t.rows[0]?.started_at)} ${ms(t.end - t.start)} ${calls} ${status} ${from}`;
162
+ const out = [`${head}${partial ? " (partial: it began before the requests read)" : ""}`];
163
+ const i = t.rows.findIndex(failed);
164
+ const e = t.rows[i];
165
+ if (e) {
166
+ const detail = e.error_detail ? `: ${short(e.error_detail, 160)}` : "";
167
+ out.push(` first error: #${i + 1} ${spanName(e.product, e.operation_id, e.path)} ${e.status_code} ${e.error_code ?? ""}${detail}`.trimEnd());
168
+ }
169
+ return out;
170
+ }
171
+ /** A span of a trace in a line or two: number, offset, duration, kind, operation, status, request id, then what it
172
+ * called (model, tokens, time to first token, tools chosen) and its error. */
173
+ function spanLines(s, n, call, manySandboxes) {
174
+ const off = typeof s.offset_ms === "number" ? `+${ms(s.offset_ms)}` : "";
175
+ const facts = [];
176
+ if (call && typeof call.model === "string")
177
+ facts.push(call.model);
178
+ const usage = usageOf(s.usage);
179
+ const tokens = isObj(call?.tokens) ? call.tokens : undefined;
180
+ if (!usage.some((u) => u.unit.startsWith("infer.")) && tokens && typeof tokens.input === "number")
181
+ facts.push(`${int(tokens.input)} in / ${int(Number(tokens.output ?? 0))} out tokens`);
182
+ const u = usageText(usage);
183
+ if (u)
184
+ facts.push(u);
185
+ const ttft = (Array.isArray(s.phases) ? s.phases.filter(isObj) : []).find((p) => p.name === "ttft");
186
+ if (ttft)
187
+ facts.push(`ttft ${ms(ttft.duration_ms)}`);
188
+ const chose = (Array.isArray(call?.tool_calls) ? call.tool_calls.filter(isObj) : []).map((c) => c.name);
189
+ if (chose.length)
190
+ facts.push(`chose ${chose.join(", ")}`);
191
+ if (manySandboxes && typeof s.sandbox_id === "string")
192
+ facts.push(`from ${s.sandbox_id}`);
193
+ const head = `#${n} ${off} ${ms(s.duration_ms)} ${s.kind} ${s.name} ${s.status_code} ${s.request_id}`;
194
+ const out = [`${head}${facts.length ? ` ${facts.join(", ")}` : ""}`];
195
+ if (s.status === "error" || failed(s))
196
+ out.push(` error: ${s.error_code ?? "error"} (${s.status_code})${s.error_detail ? `: ${short(s.error_detail, 200)}` : ""}`);
197
+ return out;
198
+ }
199
+ // ---------------------------------------------------------------------------------------------------------------
200
+ // Kept model calls
201
+ function callLine(c) {
202
+ const t = isObj(c.tokens) ? c.tokens : {};
203
+ const timing = isObj(c.timing) ? c.timing : {};
204
+ const facts = [
205
+ `${int(Number(t.input ?? 0))} in${t.cached ? ` (${int(Number(t.cached))} cached)` : ""} / ${int(Number(t.output ?? 0))} out tokens`,
206
+ typeof timing.ttft_ms === "number" ? `ttft ${ms(timing.ttft_ms)}` : "",
207
+ ms(timing.total_ms),
208
+ ];
209
+ const chose = (Array.isArray(c.tool_calls) ? c.tool_calls.filter(isObj) : []).map((x) => x.name);
210
+ if (chose.length)
211
+ facts.push(`chose ${chose.join(", ")}`);
212
+ const content = isObj(c.content) ? c.content : {};
213
+ facts.push(content.state === "kept" ? "content kept" : `metadata only (${content.state ?? "no content"})`);
214
+ if (c.trace_id)
215
+ facts.push(`trace ${c.trace_id}`);
216
+ const err = c.error_code ? ` ${c.error_code}` : "";
217
+ return `${c.id} ${when(c.started_at)} ${c.model} ${c.status_code}${err} ${c.finish_reason ?? "-"}: ${facts.filter(Boolean).join(", ")}`;
218
+ }
219
+ const NO_CALLS = "no kept model calls: prompt logging keeps calls only while the project's platform.capture_content setting is " +
220
+ "model (it is off by default), for 7 days";
221
+ function scalarText(v) {
222
+ return typeof v === "string" ? v : typeof v === "number" || typeof v === "boolean" ? String(v) : short(json(v), 120);
223
+ }
224
+ // The prompt and answer of a kept call: every string longer than max_field_chars is cut in the middle (as the call
225
+ // log itself cuts strings to keep a call within 256 KiB), never through a redaction marker, and the whole text stops
226
+ // at max_chars.
227
+ const REDACTION = /\[redacted:[a-z0-9_]+\]/g;
228
+ /** `s` cut to about `max` characters by removing its middle; a cut never splits a `[redacted:<kind>]` marker. */
229
+ export function cutMiddle(s, max) {
230
+ if (s.length <= max)
231
+ return { text: s, cut: 0 };
232
+ let head = Math.ceil(max / 2);
233
+ let tail = s.length - Math.floor(max / 2);
234
+ for (const m of s.matchAll(REDACTION)) {
235
+ const a = m.index ?? 0;
236
+ const b = a + m[0].length;
237
+ if (head > a && head < b)
238
+ head = a; // the marker goes into the cut, whole
239
+ if (tail > a && tail < b)
240
+ tail = a; // the marker stays in the tail, whole
241
+ }
242
+ if (tail <= head)
243
+ return { text: s, cut: 0 };
244
+ return {
245
+ text: `${s.slice(0, head)} [... ${int(tail - head)} characters cut ...] ${s.slice(tail)}`,
246
+ cut: tail - head,
247
+ };
248
+ }
249
+ /** A message's content as text: strings as they are, typed parts by their text, other parts by their type. */
250
+ function contentText(c) {
251
+ if (typeof c === "string")
252
+ return c;
253
+ if (Array.isArray(c))
254
+ return c.map(contentText).filter(Boolean).join("\n");
255
+ if (!isObj(c))
256
+ return c === undefined || c === null ? "" : String(c);
257
+ if (typeof c.text === "string")
258
+ return c.text;
259
+ if (c.type === "tool_use")
260
+ return `tool_use ${c.name ?? ""}(${json(c.input ?? {})})`;
261
+ if (c.type === "tool_result")
262
+ return `tool_result ${c.tool_use_id ?? ""}: ${contentText(c.content)}`;
263
+ return `[${typeof c.type === "string" ? c.type : "part"}]`;
264
+ }
265
+ /** The items of the request in order, as `{label, text}`: chat messages, a Responses input, Messages' system. */
266
+ function promptItems(surface, req) {
267
+ const items = [];
268
+ if (surface === "responses") {
269
+ if (typeof req.instructions === "string")
270
+ items.push({ role: "instructions", content: req.instructions });
271
+ if (typeof req.input === "string")
272
+ items.push({ role: "user", content: req.input });
273
+ else if (Array.isArray(req.input))
274
+ items.push(...req.input.filter(isObj));
275
+ }
276
+ else {
277
+ if (req.system !== undefined)
278
+ items.push({ role: "system", content: req.system });
279
+ if (Array.isArray(req.messages))
280
+ items.push(...req.messages.filter(isObj));
281
+ }
282
+ return items.map((m) => {
283
+ const label = m.role === "tool" && m.tool_call_id
284
+ ? `tool ${m.tool_call_id}`
285
+ : m.type === "function_call_output"
286
+ ? `function_call_output ${m.call_id ?? ""}`.trimEnd()
287
+ : String(m.role ?? m.type ?? "item");
288
+ const parts = [];
289
+ const body = contentText(m.content ?? m.output);
290
+ if (body)
291
+ parts.push(body);
292
+ if (m.type === "function_call")
293
+ parts.push(`${m.name ?? ""}(${typeof m.arguments === "string" ? m.arguments : json(m.arguments)})`);
294
+ for (const tc of Array.isArray(m.tool_calls) ? m.tool_calls.filter(isObj) : []) {
295
+ const fn = isObj(tc.function) ? tc.function : tc;
296
+ parts.push(`tool call ${fn.name ?? ""}(${typeof fn.arguments === "string" ? fn.arguments : json(fn.arguments ?? {})})`);
297
+ }
298
+ return { label, text: parts.join("\n") };
299
+ });
300
+ }
301
+ /** The names of the tools the request offered (chat, Responses and Messages shapes). */
302
+ function toolNames(req) {
303
+ return (Array.isArray(req.tools) ? req.tools.filter(isObj) : []).map((t) => String((isObj(t.function) ? t.function.name : t.name) ?? t.type ?? "?"));
304
+ }
305
+ const PROMPT_FIELDS = new Set(["messages", "input", "instructions", "system", "tools", "model", "stream"]);
306
+ /** The kept call as text, and how much was cut: header, answer, prompt, then media. */
307
+ export function promptAndAnswer(content, maxField) {
308
+ let cuts = 0;
309
+ const cut = (s) => {
310
+ const r = cutMiddle(s, maxField);
311
+ if (r.cut)
312
+ cuts++;
313
+ return r.text;
314
+ };
315
+ const req = isObj(content.request) ? content.request : {};
316
+ const out = isObj(content.output) ? content.output : {};
317
+ const lines = [];
318
+ lines.push(`answer (finish_reason ${out.finish_reason ?? "-"}):`);
319
+ if (typeof out.text === "string" && out.text)
320
+ lines.push(` text: ${cut(out.text)}`);
321
+ if (typeof out.reasoning === "string" && out.reasoning)
322
+ lines.push(` reasoning: ${cut(out.reasoning)}`);
323
+ for (const tc of Array.isArray(out.tool_calls) ? out.tool_calls.filter(isObj) : [])
324
+ lines.push(` tool call ${tc.name}${tc.id ? ` (${tc.id})` : ""}: ${cut(String(tc.arguments ?? ""))}`);
325
+ if (lines.length === 1)
326
+ lines.push(" (no text and no tool calls)");
327
+ const err = isObj(content.error) ? content.error : undefined;
328
+ if (err)
329
+ lines.push(`error: ${err.code ?? "error"}`);
330
+ const items = promptItems(content.surface, req);
331
+ const tools = toolNames(req);
332
+ lines.push(`prompt: ${items.length} item${items.length === 1 ? "" : "s"}${tools.length ? `; tools offered (schemas not shown): ${tools.join(", ")}` : ""}`);
333
+ const settings = Object.entries(req)
334
+ .filter(([k, v]) => !PROMPT_FIELDS.has(k) && v !== undefined && v !== null)
335
+ .map(([k, v]) => `${k} ${scalarText(v)}`);
336
+ if (settings.length)
337
+ lines.push(` settings: ${settings.join(", ")}`);
338
+ items.forEach((m, i) => {
339
+ lines.push(` [${i + 1}] ${m.label}: ${cut(m.text)}`);
340
+ });
341
+ const media = Array.isArray(content.media) ? content.media.filter(isObj) : [];
342
+ if (media.length)
343
+ lines.push(`media (references, never the bytes): ${media
344
+ .map((m) => [m.type, m.media_type ?? (m.url ? "url" : ""), typeof m.bytes === "number" ? `${int(m.bytes)} B` : ""]
345
+ .filter(Boolean)
346
+ .join(" "))
347
+ .join("; ")}`);
348
+ return { text: lines.join("\n"), cuts };
349
+ }
350
+ // ---------------------------------------------------------------------------------------------------------------
351
+ // The tools
352
+ export const RUNNERS = {
353
+ async requests_list(tool, args, io, ctx) {
354
+ const page = await io.request(buildRequest(tool, args), ctx.signal);
355
+ const rows = listOf(page);
356
+ const next = nextCursor(page);
357
+ const lines = [
358
+ rows.length
359
+ ? `${rows.length} request${rows.length === 1 ? "" : "s"}, newest first:`
360
+ : "no requests match (the log keeps 7 days; a request the edge answered itself is read by its ID with requests_get)",
361
+ ];
362
+ for (const r of rows)
363
+ lines.push(...requestLines(r));
364
+ if (next)
365
+ lines.push(`more: call again with cursor ${next}`);
366
+ return text(clip(lines.join("\n")), isObj(page) ? page : undefined);
367
+ },
368
+ async requests_get(tool, args, io, ctx) {
369
+ const r = await io.request(buildRequest(tool, args), ctx.signal);
370
+ if (!isObj(r))
371
+ return text(clip(json(r)));
372
+ const records = await maybe(ctx, () => io.request(requestFor("platformListUsageRecords", [], { query: { request_id: args.request_id, limit: 100 } }), ctx.signal));
373
+ const usage = isFailure(records) ? undefined : sumUsage(listOf(records));
374
+ const lines = [`${r.id}: ${r.method} ${short(r.path, 200)}, ${r.status_code} in ${ms(r.duration_ms)}`];
375
+ const bytes = `${int(Number(r.request_bytes ?? 0))} B in, ${int(Number(r.response_bytes ?? 0))} B out`;
376
+ const who = [
377
+ `source ${r.source}`,
378
+ r.key_id ? `key ${r.key_id}` : "",
379
+ r.sandbox_id ? `sandbox ${r.sandbox_id}` : "",
380
+ ];
381
+ const path = `connection ${r.connection}${r.node ? `, node ${r.node}` : ", answered by the edge"}`;
382
+ const op = r.operation_id ? `${r.operation_id}${r.product ? ` (${r.product})` : ""}` : "";
383
+ lines.push([`started ${r.started_at}`, op, who.filter(Boolean).join(" "), path, bytes].filter(Boolean).join("; "));
384
+ if (r.trace_id)
385
+ lines.push(`trace ${r.trace_id} (traces_get shows every call of it)`);
386
+ if (failed(r))
387
+ lines.push(`failed: ${r.error_code ?? "error"}${r.error_detail ? `: ${r.error_detail}` : ""}`);
388
+ const phases = Array.isArray(r.phases) ? r.phases.filter(isObj) : [];
389
+ if (phases.length) {
390
+ lines.push("timing:");
391
+ const w = Math.max(...phases.map((p) => String(p.name).length));
392
+ for (const p of phases)
393
+ lines.push(` ${String(p.source).padEnd(4)} ${String(p.name).padEnd(w)} ${ms(p.duration_ms)}`);
394
+ }
395
+ lines.push(isFailure(records)
396
+ ? `usage: not read (${records.failed})`
397
+ : `usage: ${usage?.length ? usageText(usage) : "none recorded (yet: nodes report usage within a minute)"}`);
398
+ if (r.product === "infer")
399
+ lines.push(`llm_calls_get ${r.id} shows the model call, if prompt logging kept it`);
400
+ return text(clip(lines.join("\n")), usage ? { ...r, usage } : r);
401
+ },
402
+ async traces_list(tool, args, io, ctx) {
403
+ const limit = intArg(args, "limit", 10, 1, 50);
404
+ const base = { since: args.since, source: args.source };
405
+ const rows = [];
406
+ let complete = true;
407
+ let sandboxes;
408
+ if (typeof args.app === "string" && args.app) {
409
+ const list = await io.request(requestFor("sandboxesListSandboxes", [], { query: { "metadata[b3os.app]": args.app, limit: APP_SANDBOXES } }), ctx.signal);
410
+ sandboxes = listOf(list)
411
+ .map((s) => s.id)
412
+ .filter((id) => typeof id === "string" && (!args.sandbox_id || id === args.sandbox_id));
413
+ const pages = await Promise.all(sandboxes.map((id) => io.request(requestFor(tool.operationId, [], { query: { ...base, sandbox_id: id, limit: 100 } }), ctx.signal)));
414
+ for (const p of pages) {
415
+ rows.push(...listOf(p));
416
+ if (nextCursor(p))
417
+ complete = false;
418
+ }
419
+ if (nextCursor(list))
420
+ complete = false;
421
+ }
422
+ else {
423
+ let cursor;
424
+ do {
425
+ const query = { ...base, sandbox_id: args.sandbox_id, limit: 100, cursor };
426
+ const page = await io.request(requestFor(tool.operationId, [], { query }), ctx.signal);
427
+ rows.push(...listOf(page));
428
+ cursor = nextCursor(page);
429
+ } while (cursor && rows.length < TRACE_SCAN);
430
+ complete = !cursor;
431
+ }
432
+ const by = new Map();
433
+ let untraced = 0;
434
+ for (const r of rows) {
435
+ if (typeof r.trace_id !== "string" || !r.trace_id)
436
+ untraced++;
437
+ else {
438
+ const list = by.get(r.trace_id);
439
+ if (list)
440
+ list.push(r);
441
+ else
442
+ by.set(r.trace_id, [r]);
443
+ }
444
+ }
445
+ const all = [...by].map(([id, list]) => {
446
+ const sorted = [...list].sort((a, b) => startMs(a) - startMs(b) || String(a.id).localeCompare(String(b.id)));
447
+ return {
448
+ id,
449
+ rows: sorted,
450
+ origin: originOf(sorted),
451
+ start: startMs(sorted[0]),
452
+ end: Math.max(...sorted.map(endMs)),
453
+ errors: sorted.filter(failed).length,
454
+ };
455
+ });
456
+ const singles = all.filter((t) => t.origin === "call").length;
457
+ const wanted = all
458
+ .filter((t) => args.single_calls === true || t.origin !== "call")
459
+ .filter((t) => !args.status || (args.status === "error" ? t.errors > 0 : t.errors === 0))
460
+ .sort((a, b) => b.start - a.start);
461
+ const shown = wanted.slice(0, limit);
462
+ const oldest = Math.min(...rows.map(startMs));
463
+ const scope = sandboxes
464
+ ? `the newest requests of ${sandboxes.length} sandbox${sandboxes.length === 1 ? "" : "es"} of ${args.app}`
465
+ : `the newest ${rows.length} requests`;
466
+ const lines = [
467
+ shown.length
468
+ ? `${shown.length} of ${wanted.length} trace${wanted.length === 1 ? "" : "s"} in ${scope}, newest first:`
469
+ : `no traces match in ${scope}`,
470
+ ];
471
+ for (const t of shown)
472
+ lines.push(...traceLines(t, !complete && t.start <= oldest));
473
+ const notes = [];
474
+ if (wanted.length > shown.length)
475
+ notes.push(`${wanted.length - shown.length} more: raise limit (at most 50)`);
476
+ if (args.single_calls !== true && singles)
477
+ notes.push(`${singles} single-call traces not listed (single_calls: true)`);
478
+ if (untraced)
479
+ notes.push(`${untraced} requests carried no trace id (requests_list lists them)`);
480
+ if (!complete)
481
+ notes.push("older requests were not read: a trace from before them is not listed");
482
+ if (sandboxes && !sandboxes.length)
483
+ notes.push(`no sandbox carries the tag b3os.app=${args.app}`);
484
+ if (notes.length)
485
+ lines.push(...notes.map((n) => `(${n})`));
486
+ if (shown.length)
487
+ lines.push("traces_get <trace id> reads one as a waterfall");
488
+ return text(clip(lines.join("\n")), {
489
+ traces: shown.map((t) => ({
490
+ id: t.id,
491
+ origin: t.origin,
492
+ started_at: t.rows[0]?.started_at ?? null,
493
+ duration_ms: Math.round((t.end - t.start) * 1000) / 1000,
494
+ calls: t.rows.length,
495
+ errors: t.errors,
496
+ status: t.errors ? "error" : "ok",
497
+ kinds: kindSummary(t.rows.map((r) => spanKind(r.product, r.operation_id))),
498
+ sandboxes: [...new Set(t.rows.map((r) => r.sandbox_id).filter((s) => typeof s === "string"))],
499
+ })),
500
+ matched: wanted.length,
501
+ requests_read: rows.length,
502
+ complete,
503
+ });
504
+ },
505
+ async traces_get(tool, args, io, ctx) {
506
+ const trace = await io.request(buildRequest(tool, args), ctx.signal);
507
+ if (!isObj(trace))
508
+ return text(clip(json(trace)));
509
+ const spans = Array.isArray(trace.spans) ? trace.spans.filter(isObj) : [];
510
+ // The model, tokens and chosen tools of the trace's kept model calls (prompt logging), when it kept any.
511
+ const calls = new Map();
512
+ if (spans.some((s) => s.kind === "model")) {
513
+ const kept = await maybe(ctx, () => io.request(requestFor("platformListLlmCalls", [], { query: { trace_id: trace.id, limit: 100 } }), ctx.signal));
514
+ for (const c of listOf(kept))
515
+ if (typeof c.id === "string")
516
+ calls.set(c.id, c);
517
+ }
518
+ const counts = isObj(trace.counts) ? trace.counts : {};
519
+ const errors = Number(counts.errors ?? spans.filter((s) => s.status === "error").length);
520
+ const firstErr = spans.findIndex((s) => s.status === "error");
521
+ const kinds = spans.map((s) => s.kind).filter((k) => k in KIND_COUNT);
522
+ const head = [
523
+ `trace ${trace.id}: ${trace.status}, ${ms(trace.duration_ms)}, ${spans.length} call${spans.length === 1 ? "" : "s"} (${kindSummary(kinds)})`,
524
+ ];
525
+ if (errors)
526
+ head.push(`${errors} failed${firstErr >= 0 ? ` (first: #${firstErr + 1})` : ""}`);
527
+ if (typeof trace.harness_ms === "number")
528
+ head.push(`${ms(trace.harness_ms)} with no B3OS call in flight`);
529
+ const lines = [head.join(", ")];
530
+ const tags = [
531
+ trace.app ? `app ${trace.app}` : "",
532
+ trace.service ? `service ${trace.service}` : "",
533
+ trace.deploy ? `deploy ${trace.deploy}` : "",
534
+ ].filter(Boolean);
535
+ const usage = usageText(usageOf(trace.usage));
536
+ lines.push([`started ${trace.started_at}`, ...tags, usage ? `usage ${usage}` : ""].filter(Boolean).join("; "));
537
+ const max = intArg(args, "max_spans", 25, 1, 300);
538
+ const from = intArg(args, "from_span", 1, 1, 300);
539
+ const window = spans.slice(from - 1, from - 1 + max);
540
+ const to = from - 1 + window.length;
541
+ const manySandboxes = new Set(spans.map((s) => s.sandbox_id).filter(Boolean)).size > 1;
542
+ if (window.length) {
543
+ lines.push(`spans ${from}-${to} of ${spans.length} in start order (offset from the first call, duration${trace.nested === false ? "; listed flat: this beta records no nesting" : ""}):`);
544
+ window.forEach((s, i) => {
545
+ lines.push(...spanLines(s, from + i, calls.get(String(s.request_id)), manySandboxes));
546
+ });
547
+ }
548
+ else
549
+ lines.push(`no spans from #${from}: the trace has ${spans.length}`);
550
+ const rest = [];
551
+ if (from > 1)
552
+ rest.push(`spans 1-${from - 1} not shown: call again with from_span 1`);
553
+ if (to < spans.length)
554
+ rest.push(`spans ${to + 1}-${spans.length} not shown: call again with from_span ${to + 1}`);
555
+ if (trace.truncated === true)
556
+ rest.push("the trace read stopped at its 300-request cap");
557
+ lines.push(...rest.map((r) => `(${r})`));
558
+ lines.push("requests_get <request id> shows a call's timing; llm_calls_get_prompt_and_answer a kept model call's prompt");
559
+ return text(clip(lines.join("\n")), {
560
+ id: trace.id,
561
+ status: trace.status,
562
+ started_at: trace.started_at,
563
+ duration_ms: trace.duration_ms,
564
+ harness_ms: trace.harness_ms,
565
+ app: trace.app ?? null,
566
+ service: trace.service ?? null,
567
+ counts: trace.counts,
568
+ usage: trace.usage,
569
+ truncated: trace.truncated,
570
+ from_span: from,
571
+ spans: window.map((s, i) => ({
572
+ n: from + i,
573
+ request_id: s.request_id,
574
+ kind: s.kind,
575
+ name: s.name,
576
+ status_code: s.status_code,
577
+ error_code: s.error_code ?? null,
578
+ offset_ms: s.offset_ms,
579
+ duration_ms: s.duration_ms,
580
+ usage: s.usage,
581
+ ...(calls.get(String(s.request_id))?.model ? { model: calls.get(String(s.request_id))?.model } : {}),
582
+ })),
583
+ });
584
+ },
585
+ async llm_calls_list(tool, args, io, ctx) {
586
+ const page = await io.request(buildRequest(tool, args), ctx.signal);
587
+ const rows = listOf(page);
588
+ const next = nextCursor(page);
589
+ const lines = [
590
+ rows.length ? `${rows.length} kept model call${rows.length === 1 ? "" : "s"}, newest first:` : NO_CALLS,
591
+ ];
592
+ for (const c of rows)
593
+ lines.push(callLine(c));
594
+ if (next)
595
+ lines.push(`more: call again with cursor ${next}`);
596
+ if (rows.length)
597
+ lines.push("llm_calls_get_prompt_and_answer <request id> reads one's prompt and answer (platform:content:read)");
598
+ return text(clip(lines.join("\n")), isObj(page) ? page : undefined);
599
+ },
600
+ async llm_calls_get(tool, args, io, ctx) {
601
+ const c = await io.request(buildRequest(tool, args), ctx.signal);
602
+ if (!isObj(c))
603
+ return text(clip(json(c)));
604
+ const t = isObj(c.tokens) ? c.tokens : {};
605
+ const timing = isObj(c.timing) ? c.timing : {};
606
+ const content = isObj(c.content) ? c.content : {};
607
+ const capture = isObj(c.capture) ? c.capture : {};
608
+ const params = isObj(c.params) ? Object.entries(c.params).map(([k, v]) => `${k} ${scalarText(v)}`) : [];
609
+ const offered = Array.isArray(c.tools) ? c.tools.map(String) : [];
610
+ const chose = (Array.isArray(c.tool_calls) ? c.tool_calls.filter(isObj) : []).map((x) => `${x.name}${x.id ? ` (${x.id})` : ""}`);
611
+ const lines = [
612
+ `model call ${c.id}: ${c.model} on ${c.surface} (${c.route}${c.stream ? ", streamed" : ""}), ${c.status_code} ${c.finish_reason ?? "-"}, started ${c.started_at}`,
613
+ `tokens ${int(Number(t.input ?? 0))} in (${int(Number(t.cached ?? 0))} cached), ${int(Number(t.output ?? 0))} out; time ${typeof timing.ttft_ms === "number" ? `ttft ${ms(timing.ttft_ms)}, ` : ""}total ${ms(timing.total_ms)}`,
614
+ ];
615
+ if (params.length)
616
+ lines.push(`settings: ${params.join(", ")}`);
617
+ if (offered.length || chose.length)
618
+ lines.push(`tools offered: ${offered.join(", ") || "none"}; chose: ${chose.join(", ") || "none"}`);
619
+ if (c.error_code)
620
+ lines.push(`error: ${c.error_code}`);
621
+ const red = isObj(content.redactions) ? Object.entries(content.redactions) : [];
622
+ const kept = content.state === "kept"
623
+ ? `content kept: ${int(Number(content.bytes ?? 0))} B${red.length ? `, redacted ${red.map(([k, n]) => `${k} ${n}`).join(", ")}` : ""}${content.truncated ? ", long strings cut to fit 256 KiB" : ""}, until ${content.expires_at}; llm_calls_get_prompt_and_answer reads it (needs platform:content:read)`
624
+ : `content not kept (${content.state ?? "unknown"}): metadata only`;
625
+ lines.push(kept);
626
+ const refs = [
627
+ `capture ${capture.value ?? "-"} (from ${capture.from ?? "-"})`,
628
+ c.trace_id ? `trace ${c.trace_id}` : "",
629
+ c.sandbox_id ? `sandbox ${c.sandbox_id}` : "",
630
+ c.key_id ? `key ${c.key_id}` : "",
631
+ c.replay_of ? `replay of ${c.replay_of}` : "",
632
+ ].filter(Boolean);
633
+ lines.push(refs.join("; "));
634
+ return text(clip(lines.join("\n")), c);
635
+ },
636
+ async llm_calls_get_prompt_and_answer(tool, args, io, ctx) {
637
+ const content = await io.request(buildRequest(tool, args), ctx.signal);
638
+ if (!isObj(content))
639
+ return text(clip(json(content), 2000));
640
+ const maxChars = intArg(args, "max_chars", 12_000, 1000, 100_000);
641
+ const maxField = intArg(args, "max_field_chars", 2000, 200, 100_000);
642
+ const body = promptAndAnswer(content, maxField);
643
+ const req = isObj(content.request) ? content.request : {};
644
+ const head = [
645
+ `model call ${content.id} (${content.surface}${typeof req.model === "string" ? `, ${req.model}` : ""}): its prompt and answer as kept; known key shapes read [redacted:<kind>]`,
646
+ ];
647
+ if (body.cuts)
648
+ head.push(`(${body.cuts} string${body.cuts === 1 ? "" : "s"} over ${int(maxField)} characters cut in the middle: raise max_field_chars to read more)`);
649
+ const whole = `${head.join("\n")}\n${body.text}`;
650
+ const out = whole.length <= maxChars
651
+ ? whole
652
+ : `${whole.slice(0, maxChars)}\n\n[stopped at ${int(maxChars)} of ${int(whole.length)} characters: call again with a larger max_chars (at most 100,000)]`;
653
+ return text(out, {
654
+ id: content.id,
655
+ surface: content.surface,
656
+ chars: whole.length,
657
+ returned_chars: Math.min(whole.length, maxChars),
658
+ fields_cut: body.cuts,
659
+ stopped: whole.length > maxChars,
660
+ });
661
+ },
662
+ };
663
+ //# sourceMappingURL=platform.js.map