@onbox/cli 0.3.0 → 0.3.1

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 (3) hide show
  1. package/README.md +33 -1
  2. package/dist/onbox.js +331 -13
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -108,9 +108,41 @@ onbox api PATCH /v1/drafts/<id> -d '{"subject":"Re: lunch"}'
108
108
  - `onbox api <GET|POST|PUT|PATCH|DELETE> <path>` calls any route: `-q key=value` for query parameters, `-d <json|@file|@->` for the body.
109
109
  - Shell completion: `source <(onbox completion bash)`, or `onbox completion zsh|fish`.
110
110
 
111
+ ### Agent run traces
112
+
113
+ ```bash
114
+ onbox agent-runs trace get <agentRunId>
115
+ onbox agent-runs trace get <agentRunId> --turns 40-45 --include reasoning,content
116
+ onbox agent-runs trace get <agentRunId> --include tool-results
117
+ onbox agent-runs trace get <agentRunId> --summary --json
118
+ onbox agent-runs trace get <agentRunId> --full
119
+ ```
120
+
121
+ The default output is a text summary, including when piped.
122
+ It follows every cursor, requesting 1 MB per page, and joins split messages before rendering.
123
+ Each row shows the trace step, tool names, short arguments, recorded statuses and errors, and the reasoning size in UTF-8 bytes.
124
+ The result-size column appears when a displayed tool has a recorded size.
125
+ `--turns a-b` selects an inclusive range of 1-based positions in the stored trace.
126
+ Retry notices keep their original positions and are skipped in the summary.
127
+
128
+ - Plain `--json` still prints one unmodified API page.
129
+ Pass its `nextCursor` back as `--cursor` to continue manually.
130
+ An optional `--page-size-bytes` sets the API message budget for each request.
131
+ - `--summary --json` returns `agentRunId`, `conversationId`, `status`, `type`, `totalMessages`, an optional run `error` preview, and `turns`.
132
+ Each turn has `step`, `reasoningBytes`, and a `tools` array.
133
+ Turns may have an `error` preview or `superseded: true` when recorded.
134
+ Tools have a `name` and may have `arguments`, `status`, `error`, `refusal`, and `resultBytes`.
135
+ `--include reasoning,content` adds the selected fields to each turn when present.
136
+ Organisation admins can use `--include tool-results` to print up to 20 KB of stored JSON per result.
137
+ The output marks previews that were cut.
138
+ Add `--full` to read the complete stored results, up to 1 MiB per call.
139
+ `--json` with `--include` or `--turns` also selects the summary shape.
140
+ - `--full` prints JSON with the run metadata, the original `fields`, `nextCursor: null`, and `messages` as an array of reassembled trace values.
141
+ Pair it with `--turns` to select a range of messages.
142
+
111
143
  ## Output and safety
112
144
 
113
- - On a terminal, results are tables.
145
+ - API results are generally tables on a terminal.
114
146
  Piped, or with `--json`, they are the API's JSON, unchanged apart from paging (`--all` merges the list and keeps the last page's `nextCursor` or `hasMore`).
115
147
  - With `--json`, errors are `{"error":{"code","message","use?"}}` on stderr.
116
148
  `use` names the route to call instead, when the API says so.
package/dist/onbox.js CHANGED
@@ -441,7 +441,8 @@ function boolFlag(parsed, name) {
441
441
  // src/arguments.ts
442
442
  import { readFileSync as readFileSync4 } from "fs";
443
443
 
444
- // ../../packages/openapi/dist/public-api.mjs
444
+ // ../../packages/openapi/dist/chunk-U4WLFL2S.mjs
445
+ var AGENT_RUN_TRACE_MAX_PAGE_BYTES = 1e6;
445
446
  var conversationIds = { arg: "conversationIds", list: true };
446
447
  var conversationPick = { from: "conversations", param: "conversationId" };
447
448
  var PUBLIC_API_ROUTES = [
@@ -6161,7 +6162,7 @@ var openapi_default = {
6161
6162
  operationId: "get_agent_run_trace",
6162
6163
  tags: ["agent-runs"],
6163
6164
  summary: "Read Agent Run Trace",
6164
- description: "Read a run's trace (messages, tool calls) in 50KB pages; pass `nextCursor` as `cursor` until null. Join partial message parts.",
6165
+ description: "Read a run's trace (messages, tool calls) in 50KB pages by default, or request up to 1MB. Pass `nextCursor` as `cursor` until null. Join partial message parts. Organisation admins can set includeToolResults for stored tool results.",
6165
6166
  security: [
6166
6167
  {
6167
6168
  bearerAuth: []
@@ -6187,6 +6188,59 @@ var openapi_default = {
6187
6188
  schema: {
6188
6189
  type: "string"
6189
6190
  }
6191
+ },
6192
+ {
6193
+ name: "pageSizeBytes",
6194
+ in: "query",
6195
+ required: false,
6196
+ description: "Trace page budget in UTF-8 bytes. Defaults to 50000.",
6197
+ schema: {
6198
+ type: "integer",
6199
+ minimum: 4,
6200
+ maximum: 1e6
6201
+ }
6202
+ },
6203
+ {
6204
+ name: "includeToolResults",
6205
+ in: "query",
6206
+ required: false,
6207
+ description: "Include the stored tool result parts. Organisation admins only.",
6208
+ schema: {
6209
+ type: "boolean"
6210
+ }
6211
+ },
6212
+ {
6213
+ name: "toolResultLimitBytes",
6214
+ in: "query",
6215
+ required: false,
6216
+ description: "Optional UTF-8 byte limit for each tool result. Requires includeToolResults.",
6217
+ schema: {
6218
+ type: "integer",
6219
+ minimum: 4,
6220
+ maximum: 1048576
6221
+ }
6222
+ },
6223
+ {
6224
+ name: "toolResultRange",
6225
+ in: "query",
6226
+ required: false,
6227
+ description: "Inclusive zero-based message index range for results. Requires includeToolResults.",
6228
+ schema: {
6229
+ type: "object",
6230
+ properties: {
6231
+ from: {
6232
+ type: "integer",
6233
+ minimum: 0,
6234
+ maximum: 9007199254740991
6235
+ },
6236
+ to: {
6237
+ type: "integer",
6238
+ minimum: 0,
6239
+ maximum: 9007199254740991
6240
+ }
6241
+ },
6242
+ required: ["from", "to"]
6243
+ }
6190
6244
  }
6191
6245
  ],
6192
6246
  responses: {
@@ -13070,6 +13124,256 @@ function encodeQuery(args) {
13070
13124
  return pairs;
13071
13125
  }
13072
13126
 
13127
+ // src/trace-results.ts
13128
+ var PREVIEW_BYTES = 2e4;
13129
+ function resultRequest({ full, from, to }) {
13130
+ return {
13131
+ includeToolResults: true,
13132
+ ...!full && { toolResultLimitBytes: PREVIEW_BYTES },
13133
+ ...Number.isFinite(to) && { toolResultRange: { from: from - 1, to: to - 1 } }
13134
+ };
13135
+ }
13136
+ function appendTraceResult(results, part, messageCount, incomplete) {
13137
+ if (part.messageIndex >= messageCount) throw incomplete();
13138
+ const calls = results.get(part.messageIndex) ?? /* @__PURE__ */ new Map();
13139
+ const previous = calls.get(part.toolCallId);
13140
+ const offset = previous?.part === null ? 0 : Buffer.byteLength(previous?.part ?? "");
13141
+ if (previous?.last || part.offset !== offset) throw incomplete();
13142
+ calls.set(part.toolCallId, {
13143
+ ...part,
13144
+ offset: 0,
13145
+ part: part.part === null ? null : (previous?.part ?? "") + part.part
13146
+ });
13147
+ results.set(part.messageIndex, calls);
13148
+ }
13149
+ function hasIncompleteResults(results) {
13150
+ for (const calls of results.values()) {
13151
+ for (const result of calls.values()) {
13152
+ if (!result.last) return true;
13153
+ }
13154
+ }
13155
+ return false;
13156
+ }
13157
+
13158
+ // src/trace.ts
13159
+ var TRACE_TOOL = "get_agent_run_trace";
13160
+ var TRACE_FLAGS = [
13161
+ ["summary", "", "Print the turn summary, including when paired with --json"],
13162
+ ["full", "", "Print all stored trace fields and reassembled messages as JSON"],
13163
+ [
13164
+ "include",
13165
+ "reasoning,content,tool-results",
13166
+ "Add the requested details. Tool results show 20KB each unless paired with --full"
13167
+ ],
13168
+ ["turns", "a-b", "Print an inclusive range of 1-based trace steps"]
13169
+ ];
13170
+ var INCLUDE_SECTIONS = ["reasoning", "content", "tool-results"];
13171
+ function parseTurnRange(range) {
13172
+ if (range === void 0) return { from: 1, to: Infinity };
13173
+ const match = range.match(/^([1-9]\d*)-([1-9]\d*)$/);
13174
+ const from = Number(match?.[1]);
13175
+ const to = Number(match?.[2]);
13176
+ if (!Number.isSafeInteger(to) || from > to) {
13177
+ throw new UsageError("--turns needs an inclusive range of positive steps, such as 40-45");
13178
+ }
13179
+ return { from, to };
13180
+ }
13181
+ function traceOptions(parsed) {
13182
+ const json = boolFlag(parsed, "json");
13183
+ const full = boolFlag(parsed, "full");
13184
+ const summary = boolFlag(parsed, "summary");
13185
+ const sections = (parsed.flags.get("include") ?? []).flatMap(
13186
+ (flag) => flag.split(",").map((part) => part.trim())
13187
+ );
13188
+ const includes = /* @__PURE__ */ new Set();
13189
+ for (const section of sections) {
13190
+ const known = INCLUDE_SECTIONS.find((name) => name === section);
13191
+ if (!known) throw new UsageError(`--include accepts ${INCLUDE_SECTIONS.join(", ")}`);
13192
+ includes.add(known);
13193
+ }
13194
+ if (full && (summary || includes.has("reasoning") || includes.has("content"))) {
13195
+ throw new UsageError(
13196
+ "--full accepts --include tool-results only, and cannot be combined with --summary"
13197
+ );
13198
+ }
13199
+ const range = lastFlag(parsed, "turns");
13200
+ const raw = json && !full && !summary && !includes.size && range === void 0;
13201
+ return { json, full, raw, includes, ...parseTurnRange(range) };
13202
+ }
13203
+ async function collectTrace(args, call) {
13204
+ const request = { pageSizeBytes: AGENT_RUN_TRACE_MAX_PAGE_BYTES, ...args };
13205
+ const first = await call(request);
13206
+ const messages = [];
13207
+ const results = /* @__PURE__ */ new Map();
13208
+ const seen = /* @__PURE__ */ new Set();
13209
+ const parts = [];
13210
+ const incomplete = () => new CliError("The trace is incomplete or changed while paging. Retry from the first page.");
13211
+ let page = first;
13212
+ for (; ; ) {
13213
+ for (const item of page.messages) {
13214
+ if (item.index !== messages.length) throw incomplete();
13215
+ if (item.partial) {
13216
+ parts.push(item.part);
13217
+ if (item.last) {
13218
+ try {
13219
+ messages.push(JSON.parse(parts.join("")));
13220
+ } catch {
13221
+ throw incomplete();
13222
+ }
13223
+ parts.length = 0;
13224
+ }
13225
+ } else {
13226
+ if (parts.length) throw incomplete();
13227
+ messages.push(item.message);
13228
+ }
13229
+ }
13230
+ for (const result of page.toolResults ?? []) {
13231
+ appendTraceResult(results, result, messages.length, incomplete);
13232
+ }
13233
+ if (page.nextCursor === null) break;
13234
+ if (isEmptyPage(page) || seen.has(page.nextCursor)) throw incomplete();
13235
+ seen.add(page.nextCursor);
13236
+ page = await call({ ...request, cursor: page.nextCursor });
13237
+ }
13238
+ if (parts.length || messages.length !== page.totalMessages || hasIncompleteResults(results)) {
13239
+ throw incomplete();
13240
+ }
13241
+ const { toolResults: _parts, ...head } = first;
13242
+ return {
13243
+ ...head,
13244
+ results,
13245
+ status: page.status,
13246
+ totalMessages: page.totalMessages,
13247
+ messages,
13248
+ nextCursor: null
13249
+ };
13250
+ }
13251
+ function isEmptyPage(page) {
13252
+ return page.messages.length === 0 && !page.toolResults?.length;
13253
+ }
13254
+ function record(value) {
13255
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
13256
+ }
13257
+ function preview(value, maxLength) {
13258
+ if (value === void 0) return void 0;
13259
+ const text = (typeof value === "string" ? value : JSON.stringify(value)).replace(new RegExp("\\p{Cc}", "gu"), " ").trim();
13260
+ if (text.length <= maxLength) return text;
13261
+ const characters = Array.from(text);
13262
+ return characters.length > maxLength ? `${characters.slice(0, maxLength - 1).join("")}\u2026` : text;
13263
+ }
13264
+ function summarizeTool(value, results, wantsResults) {
13265
+ const tool = record(value);
13266
+ if (typeof tool?.name !== "string") return [];
13267
+ const metadata = record(tool.result);
13268
+ const part = results?.get(String(tool.id));
13269
+ const size = metadata?.sizeBytes ?? tool.resultBytes;
13270
+ return [
13271
+ {
13272
+ name: tool.name,
13273
+ arguments: preview(tool.args, 80),
13274
+ status: typeof tool.status === "string" ? tool.status : void 0,
13275
+ error: preview(tool.error, 160),
13276
+ refusal: preview(tool.refusal, 160),
13277
+ resultBytes: typeof size === "number" ? size : void 0,
13278
+ durationMs: typeof metadata?.durationMs === "number" ? metadata.durationMs : void 0,
13279
+ ...wantsResults && {
13280
+ result: {
13281
+ part: part?.part ?? null,
13282
+ ...Boolean(part?.truncated || metadata?.truncated) && { truncated: true }
13283
+ }
13284
+ }
13285
+ }
13286
+ ];
13287
+ }
13288
+ function summarizeTurn(value, step, includes, results) {
13289
+ const message = record(value);
13290
+ const reasoning = typeof message?.reasoning === "string" ? message.reasoning : "";
13291
+ const content = message ? message.content : value;
13292
+ return {
13293
+ step,
13294
+ tools: Array.isArray(message?.toolCalls) ? message.toolCalls.flatMap(
13295
+ (tool) => summarizeTool(tool, results, includes.has("tool-results"))
13296
+ ) : [],
13297
+ reasoningBytes: Buffer.byteLength(reasoning),
13298
+ ...message?.superseded === true && { superseded: true },
13299
+ error: preview(message?.error, 160),
13300
+ ...includes.has("reasoning") && reasoning && { reasoning },
13301
+ ...includes.has("content") && content !== void 0 && { content }
13302
+ };
13303
+ }
13304
+ function formatSummary(status, error, turns) {
13305
+ const hasResultBytes = turns.some(
13306
+ (turn) => turn.tools.some((tool) => tool.resultBytes !== void 0)
13307
+ );
13308
+ const lines = [
13309
+ [preview(status, 40), preview(error, 160)].filter(Boolean).join(" "),
13310
+ ["STEP", "TOOLS", "REASONING BYTES", ...hasResultBytes ? ["RESULT BYTES"] : []].join(" ")
13311
+ ];
13312
+ for (const turn of turns) {
13313
+ const tools = turn.tools.map(
13314
+ (tool) => [
13315
+ `${preview(tool.name, 80)}${tool.arguments ? `(${tool.arguments})` : ""}`,
13316
+ tool.status ? `[${preview(tool.status, 40)}]` : "",
13317
+ tool.durationMs === void 0 ? "" : `${tool.durationMs}ms`,
13318
+ tool.error,
13319
+ tool.refusal
13320
+ ].filter(Boolean).join(" ")
13321
+ ).join(", ");
13322
+ const sizes = turn.tools.flatMap(
13323
+ (tool) => tool.resultBytes === void 0 ? [] : [`${preview(tool.name, 80)} ${tool.resultBytes}`]
13324
+ );
13325
+ lines.push(
13326
+ [
13327
+ turn.step,
13328
+ [tools, turn.superseded ? "[superseded]" : "", turn.error].filter(Boolean).join(" "),
13329
+ turn.reasoningBytes,
13330
+ ...hasResultBytes ? [sizes.join(", ")] : []
13331
+ ].join(" ")
13332
+ );
13333
+ if (turn.reasoning !== void 0) lines.push(` reasoning ${JSON.stringify(turn.reasoning)}`);
13334
+ if (turn.content !== void 0) lines.push(` content ${JSON.stringify(turn.content)}`);
13335
+ for (const tool of turn.tools) {
13336
+ if (tool.result) lines.push(formatResult(tool.name, tool.result));
13337
+ }
13338
+ }
13339
+ return `${lines.join("\n")}
13340
+ `;
13341
+ }
13342
+ function formatResult(name, result) {
13343
+ const content = result.part === null ? "unavailable" : JSON.stringify(result.part);
13344
+ return ` result ${preview(name, 80)} ${content}${result.truncated ? " [truncated]" : ""}`;
13345
+ }
13346
+ async function renderTrace(args, options, call) {
13347
+ if (options.raw) return `${JSON.stringify(await call(args), null, 2)}
13348
+ `;
13349
+ if (args.cursor !== void 0)
13350
+ throw new UsageError("--cursor requires the original --json page output");
13351
+ const wantResults = options.includes.has("tool-results");
13352
+ const request = wantResults ? { ...args, ...resultRequest(options) } : args;
13353
+ const { messages, fields, nextCursor, results, ...run3 } = await collectTrace(request, call);
13354
+ const selected = messages.slice(options.from - 1, options.to);
13355
+ if (options.full) {
13356
+ const toolResults = wantResults ? [...results].flatMap(
13357
+ ([index, calls]) => index >= options.from - 1 && index < options.to ? [...calls.values()] : []
13358
+ ) : void 0;
13359
+ return `${JSON.stringify({ ...run3, messages: selected, fields, toolResults, nextCursor }, null, 2)}
13360
+ `;
13361
+ }
13362
+ const turns = selected.flatMap(
13363
+ (message, i) => record(message)?.retry ? [] : [
13364
+ summarizeTurn(
13365
+ message,
13366
+ options.from + i,
13367
+ options.includes,
13368
+ results.get(options.from + i - 1)
13369
+ )
13370
+ ]
13371
+ );
13372
+ const error = preview(fields?.error, 160);
13373
+ return options.json ? `${JSON.stringify({ ...run3, error, turns }, null, 2)}
13374
+ ` : formatSummary(run3.status, error, turns);
13375
+ }
13376
+
13073
13377
  // src/completion.ts
13074
13378
  var GLOBAL = ["--profile", "--json", "--yes", "--limit", "--all", "--help"];
13075
13379
  function entries(commands, builtins) {
@@ -13079,6 +13383,7 @@ function entries(commands, builtins) {
13079
13383
  flags: [
13080
13384
  ...GLOBAL,
13081
13385
  ...command.params.map((param) => `--${param.flag}`),
13386
+ ...command.tool === TRACE_TOOL ? TRACE_FLAGS.map(([name]) => `--${name}`) : [],
13082
13387
  `--${envelopeFlag(command)}`
13083
13388
  ]
13084
13389
  })),
@@ -13292,7 +13597,7 @@ function callbackPage(ok) {
13292
13597
  // package.json
13293
13598
  var package_default = {
13294
13599
  name: "@onbox/cli",
13295
- version: "0.3.0",
13600
+ version: "0.3.1",
13296
13601
  description: "The onbox command line: the Onbox public API (/v1) from a terminal.",
13297
13602
  keywords: [
13298
13603
  "onbox",
@@ -13895,6 +14200,7 @@ function parseLimit(parsed) {
13895
14200
  }
13896
14201
  async function runCommand(ctx2, command, parsed) {
13897
14202
  const { variant, path, args } = buildInvocation(command, parsed);
14203
+ const trace = command.tool === TRACE_TOOL ? traceOptions(parsed) : void 0;
13898
14204
  const limit = parseLimit(parsed);
13899
14205
  const all = boolFlag(parsed, "all");
13900
14206
  if (limit !== void 0 && all) throw new UsageError("Use --limit or --all, not both");
@@ -13907,8 +14213,8 @@ async function runCommand(ctx2, command, parsed) {
13907
14213
  path,
13908
14214
  ...variant.readsQuery ? { query: encodeQuery(callArgs) } : { body: callArgs }
13909
14215
  });
13910
- const result = await fetchPages(variant, args, { limit, all }, call);
13911
- emit(ctx2, result, boolFlag(parsed, "json"));
14216
+ if (trace) ctx2.stdout(await renderTrace(args, trace, call));
14217
+ else emit(ctx2, await fetchPages(variant, args, { limit, all }, call), boolFlag(parsed, "json"));
13912
14218
  return EXIT.OK;
13913
14219
  }
13914
14220
 
@@ -14347,10 +14653,16 @@ function commandHelp(command) {
14347
14653
  const choices = param.enum ? ` One of: ${param.enum.join(", ")}.` : "";
14348
14654
  return [`--${param.flag}${kind}`, `${firstLine(param.description)}${choices}${required}`];
14349
14655
  });
14656
+ if (command.tool === TRACE_TOOL) {
14657
+ for (const [name2, argument, description] of TRACE_FLAGS) {
14658
+ flags.push([`--${name2}${argument ? ` <${argument}>` : ""}`, description]);
14659
+ }
14660
+ }
14350
14661
  const notes = [
14351
14662
  command.scope === "write" ? "Needs the write scope." : "Needs the read scope.",
14352
14663
  command.destructive ? "Changes or removes data: asks first, or needs --yes without a terminal." : "",
14353
- command.variants.some((variant) => variant.paging) ? "Follows pages with --limit <n> or --all." : ""
14664
+ command.variants.some((variant) => variant.paging) ? "Follows pages with --limit <n> or --all." : "",
14665
+ command.tool === TRACE_TOOL ? "Follows all trace pages and summarizes by default. Plain --json returns one API page with its cursor." : ""
14354
14666
  ].filter(Boolean);
14355
14667
  const name = command.path.join(" ");
14356
14668
  const usage = command.variants.map((variant, index) => {
@@ -14402,18 +14714,24 @@ function childrenOf(path) {
14402
14714
  if (path.length === 0) words.add("help");
14403
14715
  return words;
14404
14716
  }
14717
+ function commandFlags(command) {
14718
+ const booleans = command.params.filter((p) => p.type === "boolean").map((p) => p.flag);
14719
+ const values = command.params.filter((p) => p.type !== "boolean").map((p) => p.flag);
14720
+ values.push(envelopeFlag(command));
14721
+ if (command.tool === TRACE_TOOL) {
14722
+ for (const [name, argument] of TRACE_FLAGS) {
14723
+ const flags = argument ? values : booleans;
14724
+ flags.push(name);
14725
+ }
14726
+ }
14727
+ return flagSpec(booleans, values);
14728
+ }
14405
14729
  async function dispatch(argv2, ctx2) {
14406
14730
  const { path, rest } = splitCommand(argv2, childrenOf);
14407
14731
  if (path[0] === "help") return dispatch([...path.slice(1), ...rest, "--help"], ctx2);
14408
14732
  const builtin = BUILTINS.find((b) => b.path.join(" ") === path.join(" "));
14409
14733
  const command = builtin ? void 0 : commandTree.find(path);
14410
- const spec = builtin ? flagSpec(builtin.booleans, builtin.values) : command ? flagSpec(
14411
- command.params.filter((p) => p.type === "boolean").map((p) => p.flag),
14412
- [
14413
- ...command.params.filter((p) => p.type !== "boolean").map((p) => p.flag),
14414
- envelopeFlag(command)
14415
- ]
14416
- ) : flagSpec(path.length === 0 ? ["version"] : [], []);
14734
+ const spec = builtin ? flagSpec(builtin.booleans, builtin.values) : command ? commandFlags(command) : flagSpec(path.length === 0 ? ["version"] : [], []);
14417
14735
  const parsed = parseFlags(rest, spec);
14418
14736
  if (path.length === 0) {
14419
14737
  if (boolFlag(parsed, "version")) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onbox/cli",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "The onbox command line: the Onbox public API (/v1) from a terminal.",
5
5
  "keywords": [
6
6
  "onbox",