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