Public: anyone can read this; the crew can change it.
Traces 5c: the trace list and one trace read through MCP tools and a terminal screen compare #18183
Merged 4h 44m ago, live in production
scout/forge:scout/18085-traces-5c-the-trace-list-and-one-trace-r → main 0 commits fork 4 threads · 4 unresolved
6 files
changed +377
−161
docs/features/traces.md +4 −2
| @@ -18,7 +18,7 @@ Each line a run appends is stamped in `<run id>.times` beside its log (`appendRu | ||
| 18 | 18 | |
| 19 | 19 | ## The list (#17992) |
| 20 | 20 | |
| 21 | `/traces` lists every crew run the viewer may open (a run's log is the crew's and the owner's, as on its run page), newest first, a line each: title, kind, repository, model, cost (for those who may see spend), time, outcome. The search and the facets (repository, model, outcome, person or agent, from and to dates) are query parameters, so a search is a link (`/traces?repo=alice/notes&model=claude-opus&q=footer`); a malformed one is dropped. `q` matches the run's issue title and summary. `j`/`k` move, Enter opens the trace, `/` searches; the first paint holds no script of its own. Older traces follow a cursor (`before`). Terminal door: the Traces command in the palette (`src/tui/screens/traces.ts`: `/` searches, `j`/`k` move, Enter opens, `n` older). Reader: `src/trace/list.ts`, over a partial index of crew runs (`run_agent`). | |
| 21 | `/traces` lists every crew run the viewer may open (a run's log is the crew's and the owner's, as on its run page), newest first, a line each: title, kind, repository, model, cost (for those who may see spend), time, outcome. The search and the facets (repository, model, outcome, person or agent, from and to dates) are query parameters, so a search is a link (`/traces?repo=alice/notes&model=claude-opus&q=footer`); a malformed one is dropped. `q` matches the run's issue title and summary. `j`/`k` move, Enter opens the trace, `/` searches; the first paint holds no script of its own. Older traces follow a cursor (`before`). Terminal door: the Traces command in the palette (`src/tui/screens/traces.ts`: `/` searches, `j`/`k` move, Enter opens, `n` older, `v` marks a row (two at most) and `d` opens the two as the comparison below, #18085; two runs of different issues are told so). Reader: `src/trace/list.ts`, over a partial index of crew runs (`run_agent`). | |
| 22 | 22 | |
| 23 | 23 | Not yet: Talk conversations and outside imports as rows (they wait for the trace index of #17991), a kind facet (every row is a crew run), archived turns in the search, and a JSON twin of the list. |
| 24 | 24 | |
| @@ -28,7 +28,9 @@ Not yet: Talk conversations and outside imports as rows (they wait for the trace | ||
| 28 | 28 | |
| 29 | 29 | A share link is off until the repository's owner makes one (**Make a share link** on the trace; `POST /traces/<run id>/share`, same-origin). It is `/traces/shared/<secret>`, shown once (only its hash is kept, `src/trace/share.ts`), and read by anyone holding it with no sign-in: the steps and their raw lines, every one passed through the forge's redaction (`redactHeld`) on the way out, so a token the log's writer missed is `[redacted]`; no cost, no people. One live link a run: a new one ends the old, **Stop sharing** ends it, and the link is then the not-found any page gets. The gate is `src/actions/trace_share.ts`; pages `src/web/pages/trace_share.ts`, reader `src/trace/shared.ts`, which keeps the redacted trace for 30 seconds per link and allows one address 60 opens a minute (then a 429 with `Retry-After`). |
| 30 | 30 | |
| 31 | Terminal: on a run's trace (`src/tui/screens/trace.ts`) `c` reads it against the issue's newest other run, `s` makes the link (shown to copy; when one is live a second press confirms, as it ends the old one), `x` ends it; both are on the single-trace screen only, and a non-owner is told only the owner shares. MCP: the `trace` tool, `action` `list`, `read`, `compare` (`with`), `share`, `unshare`. | |
| 31 | Terminal: on a run's trace (`src/tui/screens/trace.ts`) `c` reads it against the issue's newest other run, `s` makes the link (shown to copy; when one is live a second press confirms, as it ends the old one), `x` ends it; both are on the single-trace screen only, and a non-owner is told only the owner shares. In the trace list (`src/tui/screens/traces.ts`) `v` marks a run (a `*` before its row; the header says `marked n/2`; at most two, the older mark drops), `d` opens the comparison of the two marked, by run id, so a mark survives a search, a filter or a later page; two runs of different issues are refused. | |
| 32 | ||
| 33 | MCP: the `trace` tool, `action` `list`, `read`, `compare` (`with`), `share`, `unshare`. `list` is `GET /api/v1/traces` for `repo`: one reader serves both (`readListAsk` and `listSeenTraces` in `src/trace/tree.ts`, gated as a run's log is), so the tool's body is the API's `{ items, next_cursor }` and it takes the API's filters `kind`, `model`, `outcome` (ok, failed, cancelled, stopped), `since`, `until`, `limit` and `cursor`; a malformed one is refused with the API's error code. `read` answers the trace as `rows` and `tree`, the very tree `GET /api/v1/traces/:id` answers (`treeOf` in `src/trace/tree.ts`, built from the one parse that gave the rows, behind the API's gate on the row; `null` where the run is not in the trace index). `compare` answers the API's table. A viewer who may not read a run gets from the tool what the API gives them: not found, an empty list. | |
| 32 | 34 | |
| 33 | 35 | Modules: `src/trace/model.ts` (the shape and totals), `src/trace/claude_code.ts` and `src/trace/codex.ts` (the readers), `src/trace/session.ts` (which one), `src/trace/otlp.ts` (the export). Not yet: storing an import, tokens and cost per step (the file holds none). |
| 34 | 36 |
src/http/api/traces.ts +19 −147
| @@ -1,135 +1,40 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * GET /api/v1/traces (#18021): the trace index newest first, a page at a time, as `{ items, |
| 3 | * next_cursor }`. The index (`trace/index_table.ts`) knows nothing of who may see a row, so this is | |
| 4 | * where it is decided, by the rule that gates the run's log (`mayReadLogOfRun`): a run whose log | |
| 5 | * the caller may not read is absent, never a hint it exists; a Talk turn is its person's alone. | |
| 6 | * Only the index is read, never a raw log. | |
| 3 | * next_cursor }`. Read and gated by `listSeenTraces` (`trace/tree.ts`), the MCP `trace` tool's | |
| 4 | * `list` too: a run whose log the caller may not read is absent, never a hint it exists; a Talk | |
| 5 | * turn is its person's alone. Only the index is read, never a raw log. | |
| 7 | 6 | */ |
| 8 | 7 | |
| 9 | import { mayReadLogOfRun } from "../../actions/runs.ts"; | |
| 10 | import { cursorRefusal, limitRefusal, parseLimit } from "../../contract/page_query.ts"; | |
| 11 | import type { App } from "../../app.ts"; | |
| 12 | import { getRepo, getRepoById, type Repo } from "../../core/repos.ts"; | |
| 8 | import { cursorRefusal, limitRefusal } from "../../contract/page_query.ts"; | |
| 9 | import { getRepoById } from "../../core/repos.ts"; | |
| 13 | 10 | import { getRun } from "../../core/runs.ts"; |
| 14 | 11 | import { compareViews, sameIssue } from "../../trace/compare.ts"; |
| 15 | 12 | import { readTrace, type TraceView } from "../../trace/read.ts"; |
| 16 | 13 | import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts"; |
| 17 | import type { User } from "../../core/users.ts"; | |
| 18 | 14 | import { importSession } from "../../trace/import.ts"; |
| 19 | import { readRunLog, readRunTimes } from "../../runs/log.ts"; | |
| 20 | import { MAX_STEPS, parseRunLog } from "../../trace/run_log.ts"; | |
| 21 | import { cursorOf, DEFAULT_LIMIT, getTraceRow, listTraceIndex, MAX_LIMIT, TRACE_CURSOR, type TraceKind, type TraceQuery, type TraceRow } from "../../trace/index_table.ts"; | |
| 15 | import { LIST_PARAMETERS, listSeenTraces, readListAsk, TRACE_ID, traceTree } from "../../trace/tree.ts"; | |
| 16 | import { MAX_LIMIT } from "../../trace/index_table.ts"; | |
| 22 | 17 | import type { Handler } from "../context.ts"; |
| 23 | 18 | import { BODY_CAPS, readBounded } from "../limits.ts"; |
| 24 | 19 | import { apiError, json, requireScope } from "../respond.ts"; |
| 25 | 20 | import type { Router } from "../router.ts"; |
| 26 | 21 | |
| 27 | const ACCEPTED = ["repository", "kind", "model", "outcome", "since", "until", "cursor", "limit"] as const; | |
| 28 | const KINDS: readonly string[] = ["run", "talk", "review", "imported"]; | |
| 29 | const OUTCOMES: readonly string[] = ["ok", "failed", "cancelled", "stopped"]; | |
| 30 | /** An instant: a date, or a date and time with a zone. */ | |
| 31 | const INSTANT = /^\d{4}-\d\d-\d\d(T\d\d:\d\d(:\d\d(\.\d{1,3})?)?(Z|[+-]\d\d:\d\d))?$/; | |
| 32 | const WORD = /^[\w./:-]{1,100}$/; | |
| 33 | /** A repository id no row has (a Talk turn's is empty, which a filter must not match). */ | |
| 34 | const NO_REPOSITORY = "-"; | |
| 35 | /** Rows looked at (in index pages) before a page is answered short with a cursor to go on from. */ | |
| 36 | const SCAN_PAGES = 10; | |
| 37 | ||
| 38 | const instant = (raw: string): string | undefined => { | |
| 39 | if (!INSTANT.test(raw)) return undefined; | |
| 40 | const at = new Date(raw); | |
| 41 | return Number.isNaN(at.getTime()) ? undefined : at.toISOString(); | |
| 42 | }; | |
| 43 | ||
| 44 | /** Whether `actor` may see this row: the answer for a repository is asked once per request. */ | |
| 45 | function seeing(app: App, actor: User): (row: TraceRow) => boolean { | |
| 46 | const repos = new Map<string, Repo | undefined>(); | |
| 47 | return (row) => { | |
| 48 | if (row.kind === "talk") { | |
| 49 | const owner = app.db.query<{ user_id: string }, [string]>("SELECT user_id FROM conversation_run WHERE id = ?1").get(row.id); | |
| 50 | return owner?.user_id === actor.id; | |
| 51 | } | |
| 52 | if (row.kind === "imported") return app.db.query<{ owner: string }, [string]>("SELECT owner FROM trace_index WHERE id = ?1").get(row.id)?.owner === actor.id; | |
| 53 | if (row.kind !== "run") return false; | |
| 54 | if (!repos.has(row.repository)) repos.set(row.repository, getRepoById(app.db, row.repository)); | |
| 55 | const repo = repos.get(row.repository); | |
| 56 | return repo !== undefined && mayReadLogOfRun(app, actor, repo, row.id); | |
| 57 | }; | |
| 58 | } | |
| 59 | ||
| 60 | 22 | export const listTraces: Handler = (ctx) => { |
| 61 | 23 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| 62 | 24 | const denied = requireScope(ctx, "ro"); |
| 63 | 25 | if (denied) return denied; |
| 64 | const actor = ctx.auth.user!; | |
| 65 | const q = ctx.url.searchParams; | |
| 66 | const unknown = [...new Set(q.keys())].filter((k) => !(ACCEPTED as readonly string[]).includes(k)); | |
| 67 | if (unknown.length > 0) | |
| 68 | return json( | |
| 69 | { | |
| 70 | error: "unknown_parameter", | |
| 71 | message: `this list does not read ${unknown.map((k) => JSON.stringify(k.slice(0, 40))).join(", ")}; it reads ${ACCEPTED.join(", ")}`, | |
| 72 | accepted: ACCEPTED, | |
| 73 | }, | |
| 74 | 422, | |
| 75 | ); | |
| 76 | const limit = parseLimit(q.get("limit"), MAX_LIMIT, DEFAULT_LIMIT); | |
| 77 | if (limit === undefined) return limitRefusal(MAX_LIMIT); | |
| 78 | const cursor = q.get("cursor"); | |
| 79 | if (cursor !== null && !TRACE_CURSOR.test(cursor)) return cursorRefusal(); | |
| 80 | const query: TraceQuery = {}; | |
| 81 | const kind = q.get("kind"); | |
| 82 | if (kind !== null) { | |
| 83 | if (!KINDS.includes(kind)) return apiError("invalid_kind", 400, `kind is ${KINDS.join(", ")}`); | |
| 84 | query.kind = kind as TraceKind; | |
| 26 | const ask = readListAsk(ctx.app, ctx.url.searchParams); | |
| 27 | if (!ask.ok) { | |
| 28 | if (ask.error === "unknown_parameter") return json({ error: ask.error, message: ask.message, accepted: LIST_PARAMETERS }, 422); | |
| 29 | if (ask.error === "invalid_limit") return limitRefusal(MAX_LIMIT); | |
| 30 | if (ask.error === "invalid_cursor") return cursorRefusal(); | |
| 31 | return apiError(ask.error, 400, ask.message); | |
| 85 | 32 | } |
| 86 | const outcome = q.get("outcome"); | |
| 87 | if (outcome !== null) { | |
| 88 | if (!OUTCOMES.includes(outcome)) return apiError("invalid_outcome", 400, `outcome is ${OUTCOMES.join(", ")}`); | |
| 89 | query.outcome = outcome; | |
| 90 | } | |
| 91 | const model = q.get("model"); | |
| 92 | if (model !== null) { | |
| 93 | if (!WORD.test(model)) return apiError("invalid_model", 400, "model is a model name of up to 100 characters"); | |
| 94 | query.model = model; | |
| 95 | } | |
| 96 | for (const name of ["since", "until"] as const) { | |
| 97 | const raw = q.get(name); | |
| 98 | if (raw === null) continue; | |
| 99 | const at = instant(raw); | |
| 100 | if (at === undefined) return apiError(`invalid_${name}`, 400, `${name} is a date or an ISO 8601 instant with a zone`); | |
| 101 | query[name] = at; | |
| 102 | } | |
| 103 | const repository = q.get("repository"); | |
| 104 | if (repository !== null) { | |
| 105 | if (!WORD.test(repository)) return apiError("invalid_repository", 400, "repository is a repository id or owner/name"); | |
| 106 | const [owner, name, ...more] = repository.split("/"); | |
| 107 | // An owner/name that names nothing matches no row, the same empty list a hidden one gives. | |
| 108 | query.repository = name === undefined ? repository : more.length > 0 ? NO_REPOSITORY : (getRepo(ctx.app.db, owner!, name)?.id ?? NO_REPOSITORY); | |
| 109 | } | |
| 110 | ||
| 111 | const may = seeing(ctx.app, actor); | |
| 112 | const items: TraceRow[] = []; | |
| 113 | let next: string | null = null; | |
| 33 | let body: ReturnType<typeof listSeenTraces> = { items: [], next_cursor: null }; | |
| 114 | 34 | timePhase(ctx.request, "traces", () => { |
| 115 | let from = cursor ?? undefined; | |
| 116 | for (let pages = 0; pages < SCAN_PAGES; pages += 1) { | |
| 117 | const got = listTraceIndex(ctx.app.db, { ...query, ...(from === undefined ? {} : { cursor: from }), limit: MAX_LIMIT }); | |
| 118 | for (const row of got.rows) { | |
| 119 | if (!may(row)) continue; | |
| 120 | if (items.length === limit) { | |
| 121 | next = cursorOf(items[items.length - 1]!); | |
| 122 | return; | |
| 123 | } | |
| 124 | items.push(row); | |
| 125 | } | |
| 126 | if (got.next === undefined) return; | |
| 127 | from = got.next; | |
| 128 | } | |
| 129 | // Looked at enough without filling the page: go on from where the look stopped. | |
| 130 | next = from ?? null; | |
| 35 | body = listSeenTraces(ctx.app, ctx.auth.user!, ask); | |
| 131 | 36 | }); |
| 132 | return new Response(JSON.stringify({ items, next_cursor: next }), { | |
| 37 | return new Response(JSON.stringify(body), { | |
| 133 | 38 | headers: { "content-type": "application/json", "cache-control": "private, no-store", vary: "authorization, cookie" }, |
| 134 | 39 | }); |
| 135 | 40 | }; |
| @@ -151,9 +56,6 @@ export const importTrace: Handler = async (ctx) => { | ||
| 151 | 56 | return json({ ...done.row, session: done.session, source: done.source, updated: done.updated }, done.updated ? 200 : 201); |
| 152 | 57 | }; |
| 153 | 58 | |
| 154 | /** The ids a trace has: a run's or a Talk turn's, never more than this many characters. */ | |
| 155 | const TRACE_ID = /^[0-9a-z]{1,40}$/; | |
| 156 | ||
| 157 | 59 | /** |
| 158 | 60 | * GET /api/v1/traces/:id (#18022): the thread, its turns and their steps as one tree, rebuilt from |
| 159 | 61 | * the raw log with `parseRunLog` (a Talk turn's log is a run log). A trace the caller may not see |
| @@ -164,41 +66,11 @@ export const readTraceTree: Handler = (ctx) => { | ||
| 164 | 66 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| 165 | 67 | const denied = requireScope(ctx, "ro"); |
| 166 | 68 | if (denied) return denied; |
| 167 | const id = ctx.params.id ?? ""; | |
| 168 | const row = TRACE_ID.test(id) ? getTraceRow(ctx.app.db, id) : undefined; | |
| 169 | if (row === undefined || !seeing(ctx.app, ctx.auth.user!)(row)) return apiError("not_found", 404, "no such trace"); | |
| 170 | let body: object = {}; | |
| 69 | let body: object | undefined; | |
| 171 | 70 | timePhase(ctx.request, "traces", () => { |
| 172 | const dataDir = ctx.app.config.dataDir; | |
| 173 | const { lines, truncated } = readRunLog(dataDir, row.id); | |
| 174 | const { trace, timed } = parseRunLog(row.id, row.title, lines, readRunTimes(dataDir, row.id, lines.length)); | |
| 175 | const steps = trace.turns.reduce((n, t) => n + t.steps.length, 0); | |
| 176 | body = { | |
| 177 | id: row.id, | |
| 178 | kind: row.kind, | |
| 179 | repository: row.repository, | |
| 180 | title: row.title, | |
| 181 | model: row.model, | |
| 182 | account: row.account, | |
| 183 | tokensIn: row.tokensIn, | |
| 184 | tokensCached: row.tokensCached, | |
| 185 | tokensOut: row.tokensOut, | |
| 186 | costUsd: row.costUsd, | |
| 187 | outcome: row.outcome, | |
| 188 | started: row.started, | |
| 189 | ended: row.ended, | |
| 190 | steps, | |
| 191 | errors: row.errors, | |
| 192 | timed, | |
| 193 | truncated: truncated || steps >= MAX_STEPS, | |
| 194 | turns: trace.turns.map((t) => ({ | |
| 195 | index: t.index, | |
| 196 | prompt: t.prompt, | |
| 197 | startMs: t.startMs, | |
| 198 | steps: t.steps.map((s) => ({ id: s.id, kind: s.kind, name: s.name, line: s.line, startMs: s.startMs, endMs: s.endMs, model: s.model ?? row.model, tokensIn: s.tokensIn, tokensCached: s.tokensCached, tokensOut: s.tokensOut, outcome: s.outcome })), | |
| 199 | })), | |
| 200 | }; | |
| 71 | body = traceTree(ctx.app, ctx.auth.user!, ctx.params.id ?? ""); | |
| 201 | 72 | }); |
| 73 | if (body === undefined) return apiError("not_found", 404, "no such trace"); | |
| 202 | 74 | return new Response(JSON.stringify(body), { headers: { "content-type": "application/json", "cache-control": "private, no-store", vary: "authorization, cookie" } }); |
| 203 | 75 | }; |
| 204 | 76 |
src/http/mcp/tools/trace.ts +21 −6
| @@ -1,7 +1,7 @@ | ||
| 1 | import { listRepoRuns } from "../../../actions/runs.ts"; | |
| 2 | 1 | import { sharedHref, shareRun, unshareRun } from "../../../actions/trace_share.ts"; |
| 3 | 2 | import { compareRows, compareViews, readCompared } from "../../../trace/compare.ts"; |
| 4 | 3 | import { readTrace, traceHref, traceRows } from "../../../trace/read.ts"; |
| 4 | import { LIST_OUTCOMES, listSeenTraces, readListAsk, seenTraceRow, treeOf } from "../../../trace/tree.ts"; | |
| 5 | 5 | import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts"; |
| 6 | 6 | |
| 7 | 7 | const ID = /^[0-9A-Za-z_-]{1,64}$/; |
| @@ -9,7 +9,7 @@ const ACTIONS = ["read", "list", "compare", "share", "unshare"] as const; | ||
| 9 | 9 | |
| 10 | 10 | export const tool: Tool = { |
| 11 | 11 | name: "trace", |
| 12 | doc: "`{ repo, action?, run?, with? }`: a crew run read as a trace (#17995). `list` (default without `run`): the repository's recent agent runs, each with its `trace` address; `read` (default with `run`): the trace as lines, one a step, as the page and terminal show; `compare` with `with`: two runs of one issue side by side, steps, failed, time, tokens, cost and outcome with B − A; `share`: the repository owner's share link for the run (secrets redacted, off until made, shown once); `unshare`: end it", | |
| 12 | doc: "`{ repo, action?, run?, with? }`: a crew run read as a trace (#17995). `list` (default without `run`): the repository's traces as `GET /api/v1/traces` answers them (`{ items, next_cursor }`), newest first, filtered by `kind`, `model`, `outcome`, `since`, `until`, a page of `limit` at a time (`cursor` is the last `next_cursor`); `read` (default with `run`): the trace as lines, one a step, as the page and terminal show, and `tree`, the API's trace tree; `compare` with `with`: two runs of one issue side by side, steps, failed, time, tokens, cost and outcome with B − A; `share`: the repository owner's share link for the run (secrets redacted, off until made, shown once); `unshare`: end it", | |
| 13 | 13 | description: "Read, list or compare crew-run traces; an owner makes or ends a redacted share link.", |
| 14 | 14 | inputSchema: { |
| 15 | 15 | type: "object", |
| @@ -18,6 +18,13 @@ export const tool: Tool = { | ||
| 18 | 18 | action: { type: "string", enum: [...ACTIONS] }, |
| 19 | 19 | run: { type: "string" }, |
| 20 | 20 | with: { type: "string", description: "compare: the other run of the same issue" }, |
| 21 | kind: { type: "string", enum: ["run", "talk", "review", "imported"], description: "list: only this kind" }, | |
| 22 | model: { type: "string", description: "list: only this model" }, | |
| 23 | outcome: { type: "string", enum: [...LIST_OUTCOMES], description: "list: only this outcome" }, | |
| 24 | since: { type: "string", description: "list: from this date or ISO 8601 instant" }, | |
| 25 | until: { type: "string", description: "list: before this date or ISO 8601 instant" }, | |
| 26 | limit: { type: "integer", description: "list: rows a page, 1 to 200" }, | |
| 27 | cursor: { type: "string", description: "list: the `next_cursor` of the last page" }, | |
| 21 | 28 | }, |
| 22 | 29 | required: ["repo"], |
| 23 | 30 | }, |
| @@ -31,14 +38,22 @@ export const tool: Tool = { | ||
| 31 | 38 | const action = args["action"] ?? (run === undefined ? "list" : "read"); |
| 32 | 39 | if (typeof action !== "string" || !ACTIONS.some((a) => a === action)) return bad("bad_action", `action is one of ${ACTIONS.join(", ")}`); |
| 33 | 40 | if (action === "list") { |
| 34 | const runs = listRepoRuns(ctx.app, user, repo, { limit: 20, kind: "agent" }); | |
| 35 | if (!runs.ok) return bad("not_found", "no such app or repository (owner/name)"); | |
| 36 | return good({ runs: runs.value.map((r) => ({ id: r.id, state: r.state, trace: traceHref(r.id) })) }); | |
| 41 | // The API's own parameters, so the API's reader validates them and answers its own body. | |
| 42 | const params = new URLSearchParams({ repository: `${repo.ownerName}/${repo.name}` }); | |
| 43 | for (const k of ["kind", "model", "outcome", "since", "until", "cursor", "limit"]) { | |
| 44 | const v = args[k]; | |
| 45 | if (typeof v === "string" || typeof v === "number") params.set(k, String(v)); | |
| 46 | } | |
| 47 | const ask = readListAsk(ctx.app, params); | |
| 48 | return ask.ok ? good(listSeenTraces(ctx.app, user, ask)) : bad(ask.error, ask.message); | |
| 37 | 49 | } |
| 38 | 50 | if (run === undefined) return bad("bad_run", "name the `run`"); |
| 39 | 51 | if (action === "read") { |
| 40 | 52 | const view = await readTrace(ctx.app, user, repo, run); |
| 41 | return view === undefined ? bad("not_found", "no such run here") : good({ trace: traceHref(run), rows: traceRows(view) }); | |
| 53 | if (view === undefined) return bad("not_found", "no such run here"); | |
| 54 | // The tree from the log `readTrace` already parsed, behind the API's own gate on the row. | |
| 55 | const row = seenTraceRow(ctx.app, user, run); | |
| 56 | return good({ trace: traceHref(run), rows: traceRows(view), tree: row === undefined ? null : treeOf(row, view) }); | |
| 42 | 57 | } |
| 43 | 58 | if (action === "compare") { |
| 44 | 59 | const other = args["with"]; |
src/trace/tree.ts added +170
| @@ -0,0 +1,170 @@ | ||
| 1 | /** | |
| 2 | * One trace as a tree, the index as a list, and who may see an index row (#18022, #18085): the | |
| 3 | * API's `GET /api/v1/traces` and `GET /api/v1/traces/:id` and the MCP `trace` tool's `list` and | |
| 4 | * `read` call these readers, so they cannot drift. Gated by the rule that gates the run's log; a | |
| 5 | * trace the viewer may not see is `undefined`, a row they may not see is absent. | |
| 6 | */ | |
| 7 | import { mayReadLogOfRun } from "../actions/runs.ts"; | |
| 8 | import type { App } from "../app.ts"; | |
| 9 | import { parseLimit } from "../contract/page_query.ts"; | |
| 10 | import { getRepo, getRepoById, type Repo } from "../core/repos.ts"; | |
| 11 | import type { User } from "../core/users.ts"; | |
| 12 | import { readRunLog, readRunTimes } from "../runs/log.ts"; | |
| 13 | import { cursorOf, DEFAULT_LIMIT, getTraceRow, listTraceIndex, MAX_LIMIT, TRACE_CURSOR, type TraceKind, type TraceQuery, type TraceRow } from "./index_table.ts"; | |
| 14 | import type { Trace } from "./model.ts"; | |
| 15 | import { MAX_STEPS, parseRunLog } from "./run_log.ts"; | |
| 16 | ||
| 17 | /** The ids a trace has: a run's or a Talk turn's, never more than this many characters. */ | |
| 18 | export const TRACE_ID = /^[0-9a-z]{1,40}$/; | |
| 19 | ||
| 20 | /** Whether `actor` may see this row: the answer for a repository is asked once per request. */ | |
| 21 | function seeing(app: App, actor: User): (row: TraceRow) => boolean { | |
| 22 | const repos = new Map<string, Repo | undefined>(); | |
| 23 | return (row) => { | |
| 24 | if (row.kind === "talk") { | |
| 25 | const owner = app.db.query<{ user_id: string }, [string]>("SELECT user_id FROM conversation_run WHERE id = ?1").get(row.id); | |
| 26 | return owner?.user_id === actor.id; | |
| 27 | } | |
| 28 | if (row.kind === "imported") return app.db.query<{ owner: string }, [string]>("SELECT owner FROM trace_index WHERE id = ?1").get(row.id)?.owner === actor.id; | |
| 29 | if (row.kind !== "run") return false; | |
| 30 | if (!repos.has(row.repository)) repos.set(row.repository, getRepoById(app.db, row.repository)); | |
| 31 | const repo = repos.get(row.repository); | |
| 32 | return repo !== undefined && mayReadLogOfRun(app, actor, repo, row.id); | |
| 33 | }; | |
| 34 | } | |
| 35 | ||
| 36 | /** The parameters the list reads; any other is refused by name. */ | |
| 37 | export const LIST_PARAMETERS = ["repository", "kind", "model", "outcome", "since", "until", "cursor", "limit"] as const; | |
| 38 | const KINDS: readonly string[] = ["run", "talk", "review", "imported"]; | |
| 39 | export const LIST_OUTCOMES = ["ok", "failed", "cancelled", "stopped"] as const; | |
| 40 | /** An instant: a date, or a date and time with a zone. */ | |
| 41 | const INSTANT = /^\d{4}-\d\d-\d\d(T\d\d:\d\d(:\d\d(\.\d{1,3})?)?(Z|[+-]\d\d:\d\d))?$/; | |
| 42 | const WORD = /^[\w./:-]{1,100}$/; | |
| 43 | /** A repository id no row has (a Talk turn's is empty, which a filter must not match). */ | |
| 44 | const NO_REPOSITORY = "-"; | |
| 45 | /** Rows looked at (in index pages) before a page is answered short with a cursor to go on from. */ | |
| 46 | const SCAN_PAGES = 10; | |
| 47 | ||
| 48 | /** What a list asks, read from its parameters; or the first one that is wrong. */ | |
| 49 | export type ListAsk = { ok: true; query: TraceQuery; cursor: string | undefined; limit: number } | { ok: false; error: string; message: string }; | |
| 50 | ||
| 51 | const instant = (raw: string): string | undefined => { | |
| 52 | if (!INSTANT.test(raw)) return undefined; | |
| 53 | const at = new Date(raw); | |
| 54 | return Number.isNaN(at.getTime()) ? undefined : at.toISOString(); | |
| 55 | }; | |
| 56 | ||
| 57 | /** The list's parameters, validated: an unknown one, or a malformed value, is refused. */ | |
| 58 | export function readListAsk(app: App, q: URLSearchParams): ListAsk { | |
| 59 | const unknown = [...new Set(q.keys())].filter((k) => !(LIST_PARAMETERS as readonly string[]).includes(k)); | |
| 60 | if (unknown.length > 0) | |
| 61 | return { ok: false, error: "unknown_parameter", message: `this list does not read ${unknown.map((k) => JSON.stringify(k.slice(0, 40))).join(", ")}; it reads ${LIST_PARAMETERS.join(", ")}` }; | |
| 62 | const limit = parseLimit(q.get("limit"), MAX_LIMIT, DEFAULT_LIMIT); | |
| 63 | if (limit === undefined) return { ok: false, error: "invalid_limit", message: `limit is a whole number from 1 to ${MAX_LIMIT}` }; | |
| 64 | const cursor = q.get("cursor"); | |
| 65 | if (cursor !== null && !TRACE_CURSOR.test(cursor)) return { ok: false, error: "invalid_cursor", message: "cursor is the next_cursor of a previous page" }; | |
| 66 | const query: TraceQuery = {}; | |
| 67 | const kind = q.get("kind"); | |
| 68 | if (kind !== null) { | |
| 69 | if (!KINDS.includes(kind)) return { ok: false, error: "invalid_kind", message: `kind is ${KINDS.join(", ")}` }; | |
| 70 | query.kind = kind as TraceKind; | |
| 71 | } | |
| 72 | const outcome = q.get("outcome"); | |
| 73 | if (outcome !== null) { | |
| 74 | if (!(LIST_OUTCOMES as readonly string[]).includes(outcome)) return { ok: false, error: "invalid_outcome", message: `outcome is ${LIST_OUTCOMES.join(", ")}` }; | |
| 75 | query.outcome = outcome; | |
| 76 | } | |
| 77 | const model = q.get("model"); | |
| 78 | if (model !== null) { | |
| 79 | if (!WORD.test(model)) return { ok: false, error: "invalid_model", message: "model is a model name of up to 100 characters" }; | |
| 80 | query.model = model; | |
| 81 | } | |
| 82 | for (const name of ["since", "until"] as const) { | |
| 83 | const raw = q.get(name); | |
| 84 | if (raw === null) continue; | |
| 85 | const at = instant(raw); | |
| 86 | if (at === undefined) return { ok: false, error: `invalid_${name}`, message: `${name} is a date or an ISO 8601 instant with a zone` }; | |
| 87 | query[name] = at; | |
| 88 | } | |
| 89 | const repository = q.get("repository"); | |
| 90 | if (repository !== null) { | |
| 91 | if (!WORD.test(repository)) return { ok: false, error: "invalid_repository", message: "repository is a repository id or owner/name" }; | |
| 92 | const [owner, name, ...more] = repository.split("/"); | |
| 93 | // An owner/name that names nothing matches no row, the same empty list a hidden one gives. | |
| 94 | query.repository = name === undefined ? repository : more.length > 0 ? NO_REPOSITORY : (getRepo(app.db, owner!, name)?.id ?? NO_REPOSITORY); | |
| 95 | } | |
| 96 | return { ok: true, query, cursor: cursor ?? undefined, limit }; | |
| 97 | } | |
| 98 | ||
| 99 | /** | |
| 100 | * One page of the index `actor` may see, newest first, as `{ items, next_cursor }`. Only the index | |
| 101 | * is read, never a raw log. | |
| 102 | */ | |
| 103 | export function listSeenTraces(app: App, actor: User, ask: { query: TraceQuery; cursor: string | undefined; limit: number }): { items: TraceRow[]; next_cursor: string | null } { | |
| 104 | const may = seeing(app, actor); | |
| 105 | const items: TraceRow[] = []; | |
| 106 | let from = ask.cursor; | |
| 107 | for (let pages = 0; pages < SCAN_PAGES; pages += 1) { | |
| 108 | const got = listTraceIndex(app.db, { ...ask.query, ...(from === undefined ? {} : { cursor: from }), limit: MAX_LIMIT }); | |
| 109 | for (const row of got.rows) { | |
| 110 | if (!may(row)) continue; | |
| 111 | if (items.length === ask.limit) return { items, next_cursor: cursorOf(items[items.length - 1]!) }; | |
| 112 | items.push(row); | |
| 113 | } | |
| 114 | if (got.next === undefined) return { items, next_cursor: null }; | |
| 115 | from = got.next; | |
| 116 | } | |
| 117 | // Looked at enough without filling the page: go on from where the look stopped. | |
| 118 | return { items, next_cursor: from ?? null }; | |
| 119 | } | |
| 120 | ||
| 121 | /** The row of a trace `actor` may see, or `undefined`: the gate the tree is behind. */ | |
| 122 | export function seenTraceRow(app: App, actor: User, id: string): TraceRow | undefined { | |
| 123 | const row = TRACE_ID.test(id) ? getTraceRow(app.db, id) : undefined; | |
| 124 | return row !== undefined && seeing(app, actor)(row) ? row : undefined; | |
| 125 | } | |
| 126 | ||
| 127 | /** | |
| 128 | * The thread, its turns and their steps; `undefined` for an unknown id or one `actor` may not see. | |
| 129 | */ | |
| 130 | export function traceTree(app: App, actor: User, id: string): object | undefined { | |
| 131 | const row = seenTraceRow(app, actor, id); | |
| 132 | if (row === undefined) return undefined; | |
| 133 | const dataDir = app.config.dataDir; | |
| 134 | const { lines, truncated } = readRunLog(dataDir, row.id); | |
| 135 | return treeOf(row, { ...parseRunLog(row.id, row.title, lines, readRunTimes(dataDir, row.id, lines.length)), truncated }); | |
| 136 | } | |
| 137 | ||
| 138 | /** | |
| 139 | * The tree of a row from a log already parsed: a caller that has read the trace (the MCP `read`) | |
| 140 | * builds it from that one parse. | |
| 141 | */ | |
| 142 | export function treeOf(row: TraceRow, parsed: { trace: Trace; timed: boolean; truncated: boolean }): object { | |
| 143 | const { trace, timed, truncated } = parsed; | |
| 144 | const steps = trace.turns.reduce((n, t) => n + t.steps.length, 0); | |
| 145 | return { | |
| 146 | id: row.id, | |
| 147 | kind: row.kind, | |
| 148 | repository: row.repository, | |
| 149 | title: row.title, | |
| 150 | model: row.model, | |
| 151 | account: row.account, | |
| 152 | tokensIn: row.tokensIn, | |
| 153 | tokensCached: row.tokensCached, | |
| 154 | tokensOut: row.tokensOut, | |
| 155 | costUsd: row.costUsd, | |
| 156 | outcome: row.outcome, | |
| 157 | started: row.started, | |
| 158 | ended: row.ended, | |
| 159 | steps, | |
| 160 | errors: row.errors, | |
| 161 | timed, | |
| 162 | truncated: truncated || steps >= MAX_STEPS, | |
| 163 | turns: trace.turns.map((t) => ({ | |
| 164 | index: t.index, | |
| 165 | prompt: t.prompt, | |
| 166 | startMs: t.startMs, | |
| 167 | steps: t.steps.map((s) => ({ id: s.id, kind: s.kind, name: s.name, line: s.line, startMs: s.startMs, endMs: s.endMs, model: s.model ?? row.model, tokensIn: s.tokensIn, tokensCached: s.tokensCached, tokensOut: s.tokensOut, outcome: s.outcome })), | |
| 168 | })), | |
| 169 | }; | |
| 170 | } |
src/tui/screens/traces.ts +27 −5
| @@ -3,12 +3,18 @@ | ||
| 3 | 3 | * search (the same text as the page's `q`), `r` `m` `o` `p` cycle the repository, model, outcome |
| 4 | 4 | * and person facets through what the list offers (then back to any), `f` and `t` type the from and |
| 5 | 5 | * to days (YYYY-MM-DD), `c` clears them, `j`/`k` move, Enter opens the run's trace, `n` reads the |
| 6 | * next older page. Every value goes through the page's own `readFilter`. Read-only; Esc closes. The | |
| 6 | * next older page. `v` marks a row (two at most, the older mark drops) and `d` opens the two as | |
| 7 | * a comparison (#18085): the trace screen's own, so the page's words; two runs of different issues | |
| 8 | * are told so. Every value goes through the page's own `readFilter`. Read-only; Esc closes. The | |
| 7 | 9 | * lines are `traceLine`, the page's own row. |
| 8 | 10 | */ |
| 9 | 11 | import { binding } from "../app/keys.ts"; |
| 10 | 12 | import type { Ctx, Screen } from "../app/app.ts"; |
| 11 | 13 | import { listTraces, OUTCOMES, readFilter, traceLine, type TraceFilter, type TraceList } from "../../trace/list.ts"; |
| 14 | import { getRepoById } from "../../core/repos.ts"; | |
| 15 | import { getRun } from "../../core/runs.ts"; | |
| 16 | import { sameIssue } from "../../trace/compare.ts"; | |
| 17 | import { traceScreen } from "./trace.ts"; | |
| 12 | 18 | import { Scroll, openOnWeb } from "./common.ts"; |
| 13 | 19 | import { style } from "../term/style.ts"; |
| 14 | 20 | import { truncate } from "../term/width.ts"; |
| @@ -29,6 +35,8 @@ function tracesScreen(f: Session, ctx: Ctx): Screen { | ||
| 29 | 35 | }; |
| 30 | 36 | let list: TraceList = listTraces(f.app, f.user, {}); |
| 31 | 37 | let at = 0; |
| 38 | // The runs marked to compare, oldest mark first. | |
| 39 | let marked: string[] = []; | |
| 32 | 40 | let typing: "q" | "from" | "to" | undefined; |
| 33 | 41 | const read = (): void => { |
| 34 | 42 | list = listTraces(f.app, f.user, filter()); |
| @@ -47,11 +55,12 @@ function tracesScreen(f: Session, ctx: Ctx): Screen { | ||
| 47 | 55 | }; |
| 48 | 56 | const summary = (): string => { |
| 49 | 57 | const on = Object.entries(facet).filter(([k]) => k !== "q" && facet[k as keyof typeof facet] !== undefined); |
| 50 | return on.length === 0 ? "" : ` [${on.map(([k, v]) => `${k}=${v}`).join(" ")}]`; | |
| 58 | const held = marked.length === 0 ? "" : ` marked ${marked.length}/2 (*)`; | |
| 59 | return `${on.length === 0 ? "" : ` [${on.map(([k, v]) => `${k}=${v}`).join(" ")}]`}${held}`; | |
| 51 | 60 | }; |
| 52 | 61 | return { |
| 53 | 62 | title: "Traces", |
| 54 | keys: [binding(["j", "k"], "move"), binding(["enter"], "open the trace"), binding(["n"], "older"), binding(["/"], "search"), binding(["r", "m", "o", "p"], "repo, model, outcome, person"), binding(["f", "t"], "from, to day"), binding(["c"], "clear filters"), binding(["esc"], "close")], | |
| 63 | keys: [binding(["j", "k"], "move"), binding(["enter"], "open the trace"), binding(["v"], "mark"), binding(["d"], "compare marked"), binding(["n"], "older"), binding(["/"], "search"), binding(["r", "m", "o", "p"], "repo, model, outcome, person"), binding(["f", "t"], "from, to day"), binding(["c"], "clear filters"), binding(["esc"], "close")], | |
| 55 | 64 | render(area, s) { |
| 56 | 65 | const c = ctx.theme.c; |
| 57 | 66 | s.text(area.x, area.y, truncate(`${typing === undefined ? "/ to search" : typing === "q" ? "Search" : typing === "from" ? "From (YYYY-MM-DD)" : "To (YYYY-MM-DD)"}: ${typing === undefined || typing === "q" ? (facet.q ?? "") : (facet[typing] ?? "")}${typing === undefined ? "" : "_"}${summary()}`, area.w), style(c.fg, c.bg), area.x + area.w); |
| @@ -65,7 +74,7 @@ function tracesScreen(f: Session, ctx: Ctx): Screen { | ||
| 65 | 74 | const r = list.rows[scroll.top + i]; |
| 66 | 75 | if (r === undefined) break; |
| 67 | 76 | const on = scroll.top + i === at; |
| 68 | s.text(area.x, area.y + 2 + i, truncate(`${on ? "> " : " "}${traceLine(r).replace(/[\u0000-\u001f\u007f]/g, " ")}`, area.w), style(on ? c.fg : c.muted, c.bg), area.x + area.w); | |
| 77 | s.text(area.x, area.y + 2 + i, truncate(`${on ? ">" : " "}${marked.includes(r.id) ? "*" : " "}${traceLine(r).replace(/[\u0000-\u001f\u007f]/g, " ")}`, area.w), style(on ? c.fg : c.muted, c.bg), area.x + area.w); | |
| 69 | 78 | } |
| 70 | 79 | }, |
| 71 | 80 | key(e) { |
| @@ -87,7 +96,20 @@ function tracesScreen(f: Session, ctx: Ctx): Screen { | ||
| 87 | 96 | else if (e.key === "m") cycle("model", list.facets.models); |
| 88 | 97 | else if (e.key === "o") cycle("outcome", OUTCOMES); |
| 89 | 98 | else if (e.key === "p") cycle("by", list.facets.people); |
| 90 | else if (e.key === "c") { | |
| 99 | else if (e.key === "v") { | |
| 100 | const r = list.rows[at]; | |
| 101 | if (r !== undefined) marked = marked.includes(r.id) ? marked.filter((id) => id !== r.id) : [...marked, r.id].slice(-2); | |
| 102 | } else if (e.key === "d") { | |
| 103 | // The marked runs by id, not through the visible rows: a filter or a page may have moved | |
| 104 | // past them. | |
| 105 | const [ra, rb] = marked.map((id) => getRun(f.app.db, id)); | |
| 106 | if (ra === undefined || rb === undefined) ctx.toast(marked.length < 2 ? "mark two runs of one issue with v" : "a marked run is gone: mark again", "attn"); | |
| 107 | else { | |
| 108 | const repo = ra.repoId === rb.repoId ? getRepoById(f.app.db, ra.repoId) : undefined; | |
| 109 | if (repo === undefined || !sameIssue(ra, rb)) ctx.toast("those two are not runs of one issue", "attn"); | |
| 110 | else ctx.push(traceScreen(f, ctx, repo, ra.id, rb.id)); | |
| 111 | } | |
| 112 | } else if (e.key === "c") { | |
| 91 | 113 | for (const k of Object.keys(facet)) delete facet[k as keyof typeof facet]; |
| 92 | 114 | before = undefined; |
| 93 | 115 | read(); |
new above
offline
This calls
listTraces, while the API route callslistTraceIndex. Make one list reader serve both, so the tool really calls the API's function, and test that the bodies match.