@h1r-ai/croche-cli 0.0.0-stage → 0.5.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.
@@ -0,0 +1,286 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ /**
3
+ * Studio observation of a local collector (docs/DEBUG-PAIRING.md, #253 §2a): one-time codes,
4
+ * observe-only bearer tokens, and the cursor-ordered SSE stream of `runtime`-visibility events.
5
+ * Observe credentials are memory-only and never accepted by ingest, pause or clear.
6
+ */
7
+ export class ObserveError extends Error {
8
+ status;
9
+ code;
10
+ constructor(status, code, message) {
11
+ super(message);
12
+ this.status = status;
13
+ this.code = code;
14
+ }
15
+ }
16
+ const fail = (status, code, message) => { throw new ObserveError(status, code, message); };
17
+ export const STUDIO_ORIGIN = 'https://studio.croche.ai';
18
+ const CODE_MS = 10 * 60_000, TOKEN_MS = 6 * 3600_000;
19
+ const LIMITS = { codes: 8, tokens: 8, streamsPerToken: 4, streams: 16, slowFrames: 1000, slowBytes: 4 * 1024 * 1024, queuedFrames: 32 };
20
+ const digest = (secret) => createHash('sha256').update(secret).digest('hex');
21
+ /** Public is decided per event by its own Core stamp; missing or any other value is withheld (P5). */
22
+ export const isPublic = (event) => Object.hasOwn(event, 'visibility') && event.visibility === 'runtime';
23
+ const frame = (type, data) => `event: ${type}\ndata: ${JSON.stringify({ v: 1, ...data })}\n\n`;
24
+ export class ObserveHub {
25
+ source;
26
+ broker;
27
+ instance = randomBytes(16).toString('hex');
28
+ origins;
29
+ codes = new Map();
30
+ used = new Set();
31
+ tokens = new Map();
32
+ streams = new Set();
33
+ constructor(source, origins = [], broker = 'http://127.0.0.1:8790') {
34
+ this.source = source;
35
+ this.broker = broker;
36
+ for (const origin of origins)
37
+ if (new URL(origin).origin !== origin)
38
+ throw new Error(`Studio origin must be an origin, like ${STUDIO_ORIGIN}: ${origin}`);
39
+ this.origins = new Set([STUDIO_ORIGIN, ...origins]);
40
+ this.link = origins.at(-1) ?? STUDIO_ORIGIN;
41
+ }
42
+ link;
43
+ /** A one-time code for a Studio link. The oldest unused code lapses past the limit. */
44
+ issueCode() {
45
+ const now = this.source.now();
46
+ for (const [key, expires] of this.codes)
47
+ if (expires <= now)
48
+ this.codes.delete(key);
49
+ while (this.codes.size >= LIMITS.codes)
50
+ this.codes.delete(this.codes.keys().next().value);
51
+ const code = randomBytes(16).toString('base64url'), expires = now + CODE_MS;
52
+ this.codes.set(digest(code), expires);
53
+ return { code, expires_at: new Date(expires).toISOString(), studioUrl: `${this.link}/studio#pair=${code}&broker=${this.broker}` };
54
+ }
55
+ /** The configured Studio origin of a request, checked before anything else it carries. */
56
+ origin(request) {
57
+ const origin = request.headers.get('Origin');
58
+ if (!origin || !this.origins.has(origin))
59
+ fail(403, 'origin_forbidden', 'This origin may not observe the local debugger.');
60
+ return origin;
61
+ }
62
+ /** Exchange a code (once) for an observe token. The caller has checked the origin. */
63
+ pair(code) {
64
+ if (typeof code !== 'string' || !/^[A-Za-z0-9_-]{16,64}$/.test(code))
65
+ fail(400, 'bad_request', 'A pairing code is required.');
66
+ const key = digest(code), expires = this.codes.get(key), now = this.source.now();
67
+ if (expires === undefined)
68
+ fail(410, this.used.has(key) ? 'code_used' : 'code_expired', 'This pairing code is no longer valid. Issue a new Studio link.');
69
+ this.codes.delete(key);
70
+ if (expires <= now)
71
+ fail(410, 'code_expired', 'This pairing code expired. Issue a new Studio link.');
72
+ this.used.add(key);
73
+ if (this.used.size > 64)
74
+ this.used.delete(this.used.values().next().value);
75
+ for (const [hash, token] of this.tokens)
76
+ if (token.expires <= now - TOKEN_MS)
77
+ this.tokens.delete(hash);
78
+ const live = [...this.tokens].filter(([, token]) => token.expires > now);
79
+ if (live.length >= LIMITS.tokens) {
80
+ const [hash, oldest] = live[0];
81
+ this.tokens.delete(hash);
82
+ for (const stream of [...oldest.streams])
83
+ stream.end('token_expired');
84
+ }
85
+ const token = randomBytes(32).toString('hex'), record = { expires: now + TOKEN_MS, streams: new Set() };
86
+ this.tokens.set(digest(token), record);
87
+ return { v: 1, token, expires_at: new Date(record.expires).toISOString(), runtimes: this.runtimes().map(({ runtimeInstanceId, projectId, agentId }) => ({ runtimeInstanceId, projectId, agentId })) };
88
+ }
89
+ /** The Runtimes in the retained capture, with their agent as last stamped (null if never). */
90
+ runtimes() {
91
+ // Stored events never change and cursors only grow, so the bounds identify the capture.
92
+ const low = this.source.low(), high = this.source.high();
93
+ if (this.cached?.low === low && this.cached.high === high)
94
+ return this.cached.value.map(r => ({ ...r }));
95
+ const seen = new Map();
96
+ for (const { event } of this.source.entries()) {
97
+ const runtime = seen.get(event.runtimeInstanceId) ?? { runtimeInstanceId: event.runtimeInstanceId, projectId: event.projectId, agentId: null, public_events: 0, withheld_events: 0 };
98
+ runtime.projectId = event.projectId;
99
+ if (Object.hasOwn(event, 'agentId') && (event.agentId === null || typeof event.agentId === 'string'))
100
+ runtime.agentId = event.agentId;
101
+ if (isPublic(event))
102
+ runtime.public_events++;
103
+ else
104
+ runtime.withheld_events++;
105
+ seen.set(event.runtimeInstanceId, runtime);
106
+ }
107
+ this.cached = { low, high, value: [...seen.values()] };
108
+ return this.cached.value.map(r => ({ ...r }));
109
+ }
110
+ cached;
111
+ wake() { for (const stream of this.streams)
112
+ stream.wake(); }
113
+ end(reason) { for (const stream of [...this.streams])
114
+ stream.end(reason); }
115
+ /** `GET /api/debug/events`. The caller has checked the origin. */
116
+ open(request) {
117
+ const header = request.headers.get('Authorization') ?? '';
118
+ const token = header.startsWith('Bearer ') ? this.tokens.get(digest(header.slice(7))) : undefined;
119
+ if (!token)
120
+ fail(401, 'token_invalid', 'Pair again from a new Studio link.');
121
+ if (token.expires <= this.source.now())
122
+ fail(401, 'token_expired', 'This observation expired. Pair again from a new Studio link.');
123
+ const url = new URL(request.url), after = url.searchParams.get('after'), instance = url.searchParams.get('instance');
124
+ if ((after === null) !== (instance === null) || (after !== null && !/^\d{1,16}$/.test(after)))
125
+ fail(400, 'bad_cursor', 'Give both after and instance, or neither.');
126
+ // Registration and the cursor snapshot are one synchronous step: nothing is stored between them.
127
+ const snapshot = this.source.high();
128
+ if (after !== null && (instance !== this.instance || Number(after) > snapshot))
129
+ fail(409, 'cursor_unknown', 'This collector does not know that cursor. Reconnect without after.');
130
+ // An expired observation holds no slot, even if no event or timer has ended it yet.
131
+ for (const stream of [...this.streams])
132
+ if (stream.token.expires <= this.source.now())
133
+ stream.end('token_expired');
134
+ if (token.streams.size >= LIMITS.streamsPerToken || this.streams.size >= LIMITS.streams)
135
+ fail(429, 'too_many_streams', 'Too many debugger streams.');
136
+ const source = this.source, hub = this, encoder = new TextEncoder();
137
+ let position = after === null ? source.low() - 1 : Number(after), started = false, closed = false;
138
+ let ending, ready = false, sentRuntimes = '', sentCapture = '', captureAt = -Infinity;
139
+ let captureTimer, controller;
140
+ const identity = (runtimes) => JSON.stringify(runtimes.map(r => [r.runtimeInstanceId, r.projectId, r.agentId]));
141
+ function next() {
142
+ if (!ready) {
143
+ ready = true;
144
+ const runtimes = hub.runtimes(), capture = source.capture();
145
+ sentRuntimes = identity(runtimes);
146
+ sentCapture = JSON.stringify(capture);
147
+ captureAt = source.now();
148
+ // Eviction since registration shows as the gap that follows, never as low > high + 1.
149
+ return frame('ready', { instance: hub.instance, cursor_low: Math.min(source.low(), snapshot + 1), cursor_high: snapshot, token_expires_at: new Date(token.expires).toISOString(), capture, runtimes });
150
+ }
151
+ if (!ending && token.expires <= source.now())
152
+ ending = 'token_expired';
153
+ if (ending)
154
+ return frame('end', { reason: ending });
155
+ const low = source.low(), high = source.high();
156
+ // Retained cursors this stream has not covered are gone: before its first frame that is
157
+ // eviction it resumed into; afterwards the client did not keep up.
158
+ if (position < low - 1) {
159
+ const from = position + 1;
160
+ position = low - 1;
161
+ const reason = started ? 'client_slow' : 'evicted';
162
+ started = true;
163
+ return frame('gap', { cursor_from: from, cursor_to: low - 1, reason });
164
+ }
165
+ if (high > Math.max(position, snapshot)) {
166
+ const first = Math.max(position, snapshot) + 1, lagBytes = source.storedBytes() - (source.at(first)?.offset ?? source.storedBytes());
167
+ if (high - first + 1 > LIMITS.slowFrames || lagBytes > LIMITS.slowBytes) {
168
+ const from = position + 1;
169
+ position = high;
170
+ started = true;
171
+ return frame('gap', { cursor_from: from, cursor_to: high, reason: 'client_slow' });
172
+ }
173
+ }
174
+ const runtimes = hub.runtimes();
175
+ if (identity(runtimes) !== sentRuntimes) {
176
+ sentRuntimes = identity(runtimes);
177
+ return frame('runtimes', { runtimes });
178
+ }
179
+ const capture = JSON.stringify(source.capture());
180
+ if (capture !== sentCapture) {
181
+ const wait = captureAt + 1000 - source.now();
182
+ if (wait <= 0) {
183
+ sentCapture = capture;
184
+ captureAt = source.now();
185
+ return frame('capture', JSON.parse(capture));
186
+ }
187
+ if (!captureTimer) {
188
+ captureTimer = setTimeout(() => { captureTimer = undefined; pump(); }, wait);
189
+ captureTimer.unref?.();
190
+ }
191
+ }
192
+ if (position >= high)
193
+ return undefined;
194
+ const from = position + 1, entry = source.at(from);
195
+ started = true;
196
+ if (isPublic(entry.event)) {
197
+ position = from;
198
+ return frame('event', { cursor: from, event: entry.event });
199
+ }
200
+ // A withheld run is reported as soon as it ends or the retained capture ends: never held.
201
+ let to = from;
202
+ while (to < high && !isPublic(source.at(to + 1).event))
203
+ to++;
204
+ position = to;
205
+ return frame('skip', { cursor_from: from, cursor_to: to, withheld: to - from + 1 });
206
+ }
207
+ // `enqueue` can call `pull` synchronously; the outer loop already runs while there is room.
208
+ let pumping = false;
209
+ function pump() {
210
+ if (closed || pumping)
211
+ return;
212
+ pumping = true;
213
+ try {
214
+ while ((controller.desiredSize ?? 0) > 0) {
215
+ const text = next();
216
+ if (text === undefined)
217
+ break;
218
+ controller.enqueue(encoder.encode(text));
219
+ if (text.startsWith('event: end\n')) {
220
+ cleanup();
221
+ controller.close();
222
+ return;
223
+ }
224
+ }
225
+ }
226
+ catch {
227
+ cleanup();
228
+ }
229
+ finally {
230
+ pumping = false;
231
+ }
232
+ }
233
+ const keepAlive = setInterval(() => { if (!closed && (controller.desiredSize ?? 0) > 0)
234
+ controller.enqueue(encoder.encode(': keep-alive\n\n')); }, 20_000);
235
+ keepAlive.unref?.();
236
+ const expiry = setTimeout(() => stream.end('token_expired'), Math.min(2_147_483_647, Math.max(0, token.expires - source.now())));
237
+ expiry.unref?.();
238
+ // A terminal end releases the slot and timers at once, whatever the reader's progress: the end
239
+ // frame goes after what is queued (one frame past the bound), never behind a stalled reader.
240
+ function finish(reason) {
241
+ if (closed)
242
+ return;
243
+ if (!ending)
244
+ ending = reason;
245
+ pump();
246
+ if (closed)
247
+ return;
248
+ try {
249
+ controller.enqueue(encoder.encode(frame('end', { reason: ending })));
250
+ controller.close();
251
+ }
252
+ catch { }
253
+ cleanup();
254
+ }
255
+ const stream = {
256
+ token: token,
257
+ wake: () => { if (!closed && token.expires <= source.now())
258
+ finish('token_expired');
259
+ else
260
+ pump(); },
261
+ end: finish,
262
+ };
263
+ function cleanup() {
264
+ if (closed)
265
+ return;
266
+ closed = true;
267
+ clearInterval(keepAlive);
268
+ clearTimeout(expiry);
269
+ if (captureTimer)
270
+ clearTimeout(captureTimer);
271
+ hub.streams.delete(stream);
272
+ token.streams.delete(stream);
273
+ request.signal.removeEventListener('abort', cleanup);
274
+ // An aborted request also ends its body, so a reader waiting on it is released.
275
+ try {
276
+ controller.close();
277
+ }
278
+ catch { }
279
+ }
280
+ hub.streams.add(stream);
281
+ token.streams.add(stream);
282
+ request.signal.addEventListener('abort', cleanup, { once: true });
283
+ const body = new ReadableStream({ start: c => { controller = c; }, pull: () => pump(), cancel: () => cleanup() }, new CountQueuingStrategy({ highWaterMark: LIMITS.queuedFrames }));
284
+ return new Response(body, { headers: { 'Content-Type': 'text/event-stream; charset=utf-8', 'X-Accel-Buffering': 'no' } });
285
+ }
286
+ }
@@ -0,0 +1,89 @@
1
+ import { createServer } from 'node:http';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { Readable } from 'node:stream';
4
+ import { DebugCollector } from './collector.js';
5
+ const port = Number(process.env.CROCHE_DEBUGGER_PORT ?? 8790);
6
+ // Dev Studio origins (comma-separated) beside https://studio.croche.ai: `croche debug start --studio-origin`.
7
+ const studioOrigins = (process.env.CROCHE_DEBUGGER_STUDIO_ORIGINS ?? '').split(',').map(origin => origin.trim()).filter(Boolean);
8
+ // `croche debug stop` asks over HTTP (POST /api/shutdown) and stops it as SIGINT/SIGTERM do.
9
+ let stopping = false;
10
+ function shutdown() {
11
+ if (stopping)
12
+ return;
13
+ stopping = true;
14
+ collector.stop();
15
+ setTimeout(() => { server.closeAllConnections(); server.close(() => process.exit(0)); }, 100).unref();
16
+ // Exit even if a connection outlives close.
17
+ setTimeout(() => process.exit(0), 3000).unref();
18
+ }
19
+ const collector = new DebugCollector({ port, token: process.env.DEBUG_TOKEN ?? process.env.CROCHE_DEBUGGER_TOKEN, studioOrigins, pid: process.pid, onShutdown: shutdown });
20
+ const files = { '/': ['index.html', 'text/html; charset=utf-8'], '/app.js': ['app.js', 'text/javascript; charset=utf-8'], '/styles.css': ['styles.css', 'text/css; charset=utf-8'] };
21
+ const securityHeaders = { 'Content-Security-Policy': "default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'none'; form-action 'self'", 'X-Content-Type-Options': 'nosniff', 'X-Frame-Options': 'DENY', 'Referrer-Policy': 'no-referrer', 'Cache-Control': 'no-store' };
22
+ const server = createServer(async (incoming, outgoing) => {
23
+ const abort = new AbortController();
24
+ outgoing.on('close', () => abort.abort());
25
+ try {
26
+ const headers = new Headers();
27
+ for (const [name, value] of Object.entries(incoming.headers))
28
+ if (Array.isArray(value))
29
+ value.forEach(item => headers.append(name, item));
30
+ else if (value !== undefined)
31
+ headers.set(name, value);
32
+ const init = { method: incoming.method, headers, signal: abort.signal };
33
+ if (!['GET', 'HEAD'].includes(incoming.method ?? 'GET')) {
34
+ init.body = Readable.toWeb(incoming);
35
+ init.duplex = 'half';
36
+ }
37
+ const request = new Request(`http://${incoming.headers.host ?? `127.0.0.1:${port}`}${incoming.url}`, init);
38
+ const path = new URL(request.url).pathname;
39
+ if (!path.startsWith('/api/')) {
40
+ if (!collector.checkStaticRequest(request)) {
41
+ outgoing.writeHead(403, securityHeaders);
42
+ outgoing.end('Only the local debugger host is allowed.');
43
+ return;
44
+ }
45
+ const file = files[path];
46
+ if (!file || !['GET', 'HEAD'].includes(request.method)) {
47
+ outgoing.writeHead(404, securityHeaders);
48
+ outgoing.end('Not found.');
49
+ return;
50
+ }
51
+ const content = await readFile(new URL(`../public/${file[0]}`, import.meta.url));
52
+ outgoing.writeHead(200, { ...securityHeaders, 'Content-Type': file[1] });
53
+ outgoing.end(request.method === 'HEAD' ? undefined : content);
54
+ return;
55
+ }
56
+ const response = await collector.handle(request);
57
+ outgoing.writeHead(response.status, { ...securityHeaders, ...Object.fromEntries(response.headers) });
58
+ if (!response.body) {
59
+ outgoing.end();
60
+ return;
61
+ }
62
+ const reader = response.body.getReader();
63
+ try {
64
+ while (!abort.signal.aborted) {
65
+ const chunk = await reader.read();
66
+ if (chunk.done)
67
+ break;
68
+ if (!outgoing.write(chunk.value))
69
+ await new Promise(resolve => { const finish = () => { outgoing.removeListener('drain', finish); outgoing.removeListener('close', finish); resolve(); }; outgoing.once('drain', finish); outgoing.once('close', finish); });
70
+ }
71
+ }
72
+ finally {
73
+ await reader.cancel();
74
+ outgoing.end();
75
+ }
76
+ }
77
+ catch {
78
+ if (!outgoing.headersSent)
79
+ outgoing.writeHead(500, { ...securityHeaders, 'Content-Type': 'application/json' });
80
+ outgoing.end(JSON.stringify({ error: 'The local debugger request failed.' }));
81
+ }
82
+ });
83
+ server.on('error', error => { process.stderr.write(`Debugger could not listen on 127.0.0.1:${port}: ${error.message}\n`); process.exitCode = 1; });
84
+ server.listen(port, '127.0.0.1', () => {
85
+ process.stdout.write(`\nCroche Runtime Debugger\nLocal UI: ${collector.connectionUrl}\nPairing token: ${collector.token}\nEvent endpoint: http://127.0.0.1:${port}/api/events\nStudio (one use, 10 minutes): ${collector.observe.issueCode().studioUrl}\nCapture stays in memory. Stop the process to discard it.\n\n`);
86
+ });
87
+ // Studio streams get `end {collector_stopping}` before the connections close.
88
+ for (const signal of ['SIGINT', 'SIGTERM'])
89
+ process.on(signal, shutdown);
@@ -0,0 +1,94 @@
1
+ const record = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
2
+ const number = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;
3
+ const empty = () => ({ prompt: null, completion: null, cached: null, reasoning: null });
4
+ export function summarizeTurns(events) {
5
+ const turns = new Map();
6
+ const callMaps = new Map();
7
+ const inputs = new Set();
8
+ const completed = new Set();
9
+ for (const event of events) {
10
+ if (!event.turnId)
11
+ continue;
12
+ const key = `${event.runtimeInstanceId}\u0000${event.turnId}`;
13
+ let turn = turns.get(key);
14
+ if (!turn) {
15
+ turn = { id: event.turnId, runtimeInstanceId: event.runtimeInstanceId, appName: event.appName ?? 'Unnamed app', startedAt: event.timestamp, input: '', status: 'unknown', events: 0, calls: [], requestCount: 0, cost: null, costSource: 'unknown', usage: empty(), recovered: false, partialCapture: false, captureNotes: [] };
16
+ turns.set(key, turn);
17
+ callMaps.set(key, new Map());
18
+ }
19
+ turn.events++;
20
+ if (event.appName)
21
+ turn.appName = event.appName;
22
+ if (event.type === 'input.received' || event.type === 'input.replayed') {
23
+ turn.input = String(record(event.data.input).text ?? '');
24
+ inputs.add(key);
25
+ if (!completed.has(key))
26
+ turn.status = 'in progress';
27
+ }
28
+ if (event.type === 'model.recovery')
29
+ turn.recovered = true;
30
+ if (['model.request', 'model.response', 'model.error'].includes(event.type)) {
31
+ const calls = callMaps.get(key);
32
+ const id = event.operationId ?? `unattributed:${event.id}`;
33
+ let call = calls.get(id);
34
+ if (!call) {
35
+ call = { operationId: id, cost: null, usage: empty() };
36
+ calls.set(id, call);
37
+ }
38
+ if (event.type === 'model.request') {
39
+ call.requestEventId = event.id;
40
+ if (!completed.has(key))
41
+ turn.status = 'in progress';
42
+ }
43
+ if (event.type === 'model.error')
44
+ call.errorEventId = event.id;
45
+ if (event.type === 'model.response') {
46
+ call.responseEventId = event.id;
47
+ const body = record(event.data.body ?? event.data);
48
+ const usage = record(body.usage);
49
+ call.cost = number(usage.cost);
50
+ call.usage = { prompt: number(usage.prompt_tokens ?? usage.input_tokens), completion: number(usage.completion_tokens ?? usage.output_tokens), cached: number(record(usage.prompt_tokens_details).cached_tokens ?? usage.cached_tokens ?? usage.cache_read_input_tokens), reasoning: number(record(usage.completion_tokens_details).reasoning_tokens ?? usage.reasoning_tokens) };
51
+ }
52
+ }
53
+ if (event.type === 'turn.completed' || event.type === 'input.replayed') {
54
+ const result = record(event.data.result);
55
+ if (typeof result.status === 'string') {
56
+ turn.status = result.status;
57
+ completed.add(key);
58
+ }
59
+ // null is an authoritative unknown cost, not permission to substitute the
60
+ // sum of whichever provider responses happened to reach this capture.
61
+ if (Object.hasOwn(result, 'cost')) {
62
+ turn.cost = number(result.cost);
63
+ turn.costSource = 'turn result';
64
+ }
65
+ }
66
+ }
67
+ for (const [key, turn] of turns) {
68
+ turn.calls = [...callMaps.get(key).values()];
69
+ turn.requestCount = turn.calls.filter(call => call.requestEventId).length;
70
+ // A failed call's cost stays unknown: the retired Cloud relay's no-dispatch proof was the only
71
+ // thing that ever priced one at zero (removed in keel/remove-grants); a gateway sends none.
72
+ const responses = turn.calls.filter(call => call.responseEventId);
73
+ const missingRequests = turn.calls.some(call => !call.requestEventId);
74
+ const missingResponses = responses.length !== turn.calls.length;
75
+ if (!inputs.has(key))
76
+ turn.captureNotes.push('Input was not captured.');
77
+ if (missingRequests)
78
+ turn.captureNotes.push('One or more model requests were not captured.');
79
+ if (completed.has(key) && turn.calls.some(call => !call.responseEventId && !call.errorEventId))
80
+ turn.captureNotes.push('A model outcome was not captured.');
81
+ if (!completed.has(key) && missingRequests)
82
+ turn.captureNotes.push('Turn completion was not captured; final status and whole-turn cost are unknown.');
83
+ turn.partialCapture = turn.captureNotes.length > 0;
84
+ for (const type of ['prompt', 'completion', 'cached', 'reasoning']) {
85
+ const known = responses.map(call => call.usage[type]);
86
+ turn.usage[type] = !missingRequests && !missingResponses && known.length && known.every(value => value !== null) ? known.reduce((sum, value) => sum + value, 0) : null;
87
+ }
88
+ if (turn.costSource !== 'turn result' && !missingRequests && turn.calls.length && turn.calls.every(call => call.cost !== null)) {
89
+ turn.cost = turn.calls.reduce((sum, call) => sum + call.cost, 0);
90
+ turn.costSource = turn.calls.some(call => !call.responseEventId) ? 'captured operation evidence' : 'provider usage';
91
+ }
92
+ }
93
+ return [...turns.values()].reverse();
94
+ }
@@ -0,0 +1,21 @@
1
+ type Env = Record<string, string | undefined>;
2
+ type Kind = 'debugger' | 'control';
3
+ export interface DebuggerContext {
4
+ env: Env;
5
+ fetch?: typeof fetch;
6
+ /** Interactive selection is supplied only by the real TTY binary. */
7
+ selectRuntime?: (runtimes: {
8
+ id: string;
9
+ label: string;
10
+ }[]) => Promise<string | undefined>;
11
+ /** Embeddings/tests may supply a process launcher; credentials are never argv. */
12
+ launch?: (kind: Kind, connection: {
13
+ url: string;
14
+ token: string;
15
+ }, options?: {
16
+ studioOrigins?: string[];
17
+ }) => Promise<number | void>;
18
+ }
19
+ export declare function defaultConnectionFile(kind: Kind, env?: Env, port?: number): string;
20
+ export declare function debugCommand(action: string, args: Record<string, string>, context: DebuggerContext): Promise<any>;
21
+ export {};