-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathtrace.ts
More file actions
282 lines (254 loc) · 10.2 KB
/
trace.ts
File metadata and controls
282 lines (254 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
import type { Argv } from "yargs"
import { cmd } from "./cmd"
import { UI } from "../ui"
// altimate_change start — trace: session trace (recording/recap of agent sessions)
import { Trace, type TraceFile } from "../../altimate/observability/tracing"
// altimate_change end
import { renderTraceViewer } from "../../altimate/observability/viewer"
import { Config } from "../../config/config"
import fs from "fs/promises"
import path from "path"
function formatDuration(ms: number): string {
if (ms < 1000) return `${ms}ms`
if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`
const mins = Math.floor(ms / 60000)
const secs = Math.floor((ms % 60000) / 1000)
return `${mins}m${secs}s`
}
function formatCost(cost: number): string {
if (cost < 0.01) return `$${cost.toFixed(4)}`
return `$${cost.toFixed(2)}`
}
function formatTimestamp(iso: string): string {
const d = new Date(iso)
const now = new Date()
const diff = now.getTime() - d.getTime()
if (diff < 60000) return "just now"
if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`
if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`
if (diff < 604800000) return `${Math.floor(diff / 86400000)}d ago`
return d.toLocaleDateString()
}
function formatDate(iso: string): string {
const d = new Date(iso)
const month = String(d.getMonth() + 1).padStart(2, "0")
const day = String(d.getDate()).padStart(2, "0")
const hours = String(d.getHours()).padStart(2, "0")
const mins = String(d.getMinutes()).padStart(2, "0")
return `${month}/${day} ${hours}:${mins}`
}
function truncate(str: string, len: number): string {
if (str.length <= len) return str
return str.slice(0, len - 1) + "…"
}
// altimate_change start — trace: list session traces (recordings/recaps of agent sessions)
function listTraces(
traces: Array<{ sessionId: string; trace: TraceFile }>,
pagination: { total: number; offset: number; limit: number },
tracesDir?: string,
) {
if (traces.length === 0 && pagination.total === 0) {
UI.println("No traces found. Run a command with tracing enabled:")
UI.println(" altimate-code run \"your prompt here\"")
return
}
if (traces.length === 0 && pagination.total > 0) {
const totalPages = Math.ceil(pagination.total / pagination.limit)
UI.println(`No traces on this page (offset ${pagination.offset} past end of ${pagination.total} traces).`)
UI.println(UI.Style.TEXT_DIM + `Try: altimate-code trace list --page 1 (${totalPages} page(s) available)` + UI.Style.TEXT_NORMAL)
return
}
// Header
const header = [
"DATE".padEnd(13),
"WHEN".padEnd(10),
"STATUS".padEnd(10),
"DURATION".padEnd(10),
"TOKENS".padEnd(10),
"COST".padEnd(10),
"TOOLS".padEnd(7),
"TITLE",
].join("")
UI.println(UI.Style.TEXT_DIM + header + UI.Style.TEXT_NORMAL)
for (const { sessionId, trace } of traces) {
// Pad visible text first, then wrap with ANSI codes so padEnd counts correctly
const statusText = trace.summary.status === "error" || trace.summary.status === "crashed"
? UI.Style.TEXT_DANGER_BOLD + (trace.summary.status).padEnd(10) + UI.Style.TEXT_NORMAL
: trace.summary.status === "running"
? UI.Style.TEXT_WARNING_BOLD + "running".padEnd(10) + UI.Style.TEXT_NORMAL
: "ok".padEnd(10)
// Title: prefer metadata.title, fall back to truncated prompt, then session ID
const displayTitle = trace.metadata.title
|| trace.metadata.prompt
|| sessionId
const row = [
formatDate(trace.startedAt).padEnd(13),
formatTimestamp(trace.startedAt).padEnd(10),
statusText,
formatDuration(trace.summary.duration).padEnd(10),
trace.summary.totalTokens.toLocaleString().padEnd(10),
formatCost(trace.summary.totalCost).padEnd(10),
String(trace.summary.totalToolCalls).padEnd(7),
truncate(displayTitle, 50),
].join("")
UI.println(row)
}
UI.empty()
// altimate_change start — trace: session trace messages with pagination footer
const rangeStart = pagination.offset + 1
const rangeEnd = pagination.offset + traces.length
const currentPage = Math.floor(pagination.offset / pagination.limit) + 1
const totalPages = Math.ceil(pagination.total / pagination.limit)
UI.println(UI.Style.TEXT_DIM + `Showing ${rangeStart}-${rangeEnd} of ${pagination.total} trace(s) (page ${currentPage}/${totalPages}) in ${Trace.getTracesDir(tracesDir)}` + UI.Style.TEXT_NORMAL)
if (rangeEnd < pagination.total) {
const isPageAligned = pagination.offset % pagination.limit === 0
const nextHint = isPageAligned
? `altimate-code trace list --page ${currentPage + 1} --limit ${pagination.limit}`
: `altimate-code trace list --offset ${rangeEnd} --limit ${pagination.limit}`
UI.println(UI.Style.TEXT_DIM + `Next page: ${nextHint}` + UI.Style.TEXT_NORMAL)
}
UI.println(UI.Style.TEXT_DIM + "View a trace: altimate-code trace view <session-id>" + UI.Style.TEXT_NORMAL)
// altimate_change end
}
// altimate_change end
// altimate_change start — trace: session trace command (recording/recap of agent sessions)
export const TraceCommand = cmd({
command: "trace [action] [id]",
aliases: ["recap"],
describe: "list and view session traces (recordings of agent sessions)",
builder: (yargs: Argv) => {
return yargs
.positional("action", {
describe: "action to perform",
type: "string",
choices: ["list", "view"] as const,
default: "list",
})
.positional("id", {
describe: "session ID for view action",
type: "string",
})
// altimate_change start — trace: option descriptions
.option("port", {
type: "number",
describe: "port for trace viewer server",
default: 0,
})
.option("limit", {
alias: ["n"],
type: "number",
describe: "number of traces to show",
default: 20,
})
.option("offset", {
type: "number",
describe: "number of traces to skip (for pagination)",
default: 0,
})
.option("page", {
alias: ["p"],
type: "number",
describe: "page number (1-based, converts to offset automatically)",
})
.option("live", {
type: "boolean",
describe: "auto-refresh the viewer as the trace updates (for in-progress sessions)",
default: false,
})
// altimate_change end
},
// altimate_change start — trace: handler body
handler: async (args) => {
const action = args.action || "list"
const cfg = await Config.get().catch(() => ({} as Record<string, any>))
const tracesDir = (cfg as any).tracing?.dir as string | undefined
if (action === "list") {
// Use nullish coalescing so an explicit 0 is preserved and reaches
// listTracesPaginated() for clamping. `args.offset || 0` would
// treat `--offset 0` as unset (no semantic change, harmless), but
// `args.limit || 20` would promote `--limit 0` to 20 instead of
// letting the API clamp it to 1.
const limit = args.limit ?? 20
const rawPage = args.page != null ? args.page : undefined
const offset = rawPage != null && Number.isFinite(rawPage)
? (Math.max(1, Math.trunc(rawPage)) - 1) * limit
: (args.offset ?? 0)
const page = await Trace.listTracesPaginated(tracesDir, { offset, limit })
listTraces(page.traces, page, tracesDir)
return
}
if (action === "view") {
if (!args.id) {
UI.error("Usage: altimate-code trace view <session-id>")
process.exit(1)
}
// Support partial session ID matching
const traces = await Trace.listTraces(tracesDir)
const match = traces.find(
(t) => t.sessionId === args.id || t.sessionId.startsWith(args.id!) || t.file.startsWith(args.id!),
)
if (!match) {
UI.error(`Trace not found: ${args.id}`)
UI.println("Available traces:")
listTraces(traces.slice(0, 10), { total: traces.length, offset: 0, limit: 10 }, tracesDir)
process.exit(1)
}
const tracePath = path.join(Trace.getTracesDir(tracesDir), match.file)
const port = args.port || 0
const live = args.live || false
const server = Bun.serve({
port,
hostname: "127.0.0.1",
async fetch(req) {
const url = new URL(req.url)
// /api/trace — serves latest trace JSON (for live polling)
if (url.pathname === "/api/trace") {
try {
const content = await fs.readFile(tracePath, "utf-8")
return new Response(content, {
headers: {
"Content-Type": "application/json",
"Cache-Control": "no-cache",
},
})
} catch {
return new Response("{}", { status: 404 })
}
}
// / — serves the HTML viewer (new multi-view renderer)
const trace = JSON.parse(await fs.readFile(tracePath, "utf-8").catch(() => "{}")) as TraceFile
const html = renderTraceViewer(trace, { live, apiPath: "/api/trace" })
return new Response(html, {
headers: { "Content-Type": "text/html; charset=utf-8" },
})
},
})
const url = `http://localhost:${server.port}`
// altimate_change start — trace: viewer message
UI.println(`Trace viewer: ${url}`)
// altimate_change end
if (live) {
UI.println(UI.Style.TEXT_DIM + "Live mode: auto-refreshing every 2s" + UI.Style.TEXT_NORMAL)
}
UI.println(UI.Style.TEXT_DIM + "Press Ctrl+C to stop" + UI.Style.TEXT_NORMAL)
// Try to open browser
try {
const openArgs = process.platform === "darwin" ? ["open", url] : process.platform === "win32" ? ["cmd", "/c", "start", url] : ["xdg-open", url]
Bun.spawn(openArgs, { stdout: "ignore", stderr: "ignore" })
} catch {
// User can open manually
}
// Graceful shutdown on interrupt
const shutdown = async () => {
try { await server.stop() } catch {}
process.exit(0)
}
process.on("SIGINT", shutdown)
process.on("SIGTERM", shutdown)
// Keep server alive until interrupted
await new Promise(() => {})
}
},
// altimate_change end
})
// altimate_change end