@h1r-ai/croche-cli 0.0.0-stage → 0.5.0

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,124 @@
1
+ import { homedir } from 'node:os';
2
+ import path from 'node:path';
3
+ import { mkdir, chmod, lstat, readFile, open, rename, unlink } from 'node:fs/promises';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { CliError } from './index.js';
6
+ export const validCredential = (key) => /^dk_[A-Za-z0-9_-]{32,256}$/.test(key) && !key.includes('\n');
7
+ export function credentialPath(env, platform = process.platform, home = env.HOME ?? homedir()) {
8
+ if (platform === 'win32') {
9
+ const profile = env.USERPROFILE, appData = env.APPDATA;
10
+ if (!profile || !appData || !path.win32.isAbsolute(profile) || !path.win32.isAbsolute(appData))
11
+ throw new CliError('invalid_configuration', 'A user-profile application-data directory is required.');
12
+ const relative = path.win32.relative(profile, appData);
13
+ if (relative === '..' || relative.startsWith('..\\') || path.win32.isAbsolute(relative))
14
+ throw new CliError('invalid_configuration', 'Credential storage must be inside the current user profile.');
15
+ return path.win32.join(appData, 'croche', 'credentials.json');
16
+ }
17
+ const root = platform === 'darwin' ? path.join(home, 'Library', 'Application Support') : env.XDG_CONFIG_HOME ?? path.join(home, '.config');
18
+ if (!path.isAbsolute(root))
19
+ throw new CliError('invalid_configuration', 'The configuration directory must be absolute.');
20
+ return path.join(root, 'croche', 'credentials.json');
21
+ }
22
+ export async function resolveCredential(env) {
23
+ // An explicit environment credential always takes precedence over disk.
24
+ if (env.CROCHE_DEVELOPER_KEY !== undefined) {
25
+ if (!validCredential(env.CROCHE_DEVELOPER_KEY))
26
+ throw new CliError('missing_credentials', 'Supply a valid developer credential.', 3);
27
+ return { key: env.CROCHE_DEVELOPER_KEY, source: 'env' };
28
+ }
29
+ const file = credentialPath(env);
30
+ try {
31
+ const info = await lstat(file), directory = await lstat(path.dirname(file));
32
+ if (!info.isFile() || info.isSymbolicLink() || directory.isSymbolicLink() || (process.platform !== 'win32' && ((info.mode & 0o077) !== 0 || (directory.mode & 0o077) !== 0)))
33
+ throw new Error('unsafe');
34
+ const data = JSON.parse(await readFile(file, 'utf8'));
35
+ if (!validCredential(data.developer_key))
36
+ throw new Error('invalid');
37
+ return { key: data.developer_key, source: 'stored' };
38
+ }
39
+ catch (error) {
40
+ if (error.code === 'ENOENT')
41
+ throw new CliError('missing_credentials', 'Ask the user to run croche login in their terminal.', 3);
42
+ throw new CliError('invalid_credentials_file', 'Stored credentials are unreadable or insecure; the user should run croche login again.', 3);
43
+ }
44
+ }
45
+ export async function storeCredential(env, key) {
46
+ const file = credentialPath(env), directory = path.dirname(file);
47
+ await mkdir(directory, { recursive: true, mode: 0o700 });
48
+ if ((await lstat(directory)).isSymbolicLink())
49
+ throw new CliError('invalid_configuration', 'Credential directory must not be a symbolic link.');
50
+ if (process.platform !== 'win32')
51
+ await chmod(directory, 0o700);
52
+ const temporary = path.join(directory, `.credentials-${randomUUID()}.tmp`);
53
+ let handle;
54
+ try {
55
+ handle = await open(temporary, 'wx', 0o600);
56
+ await handle.writeFile(JSON.stringify({ developer_key: key }) + '\n');
57
+ await handle.sync();
58
+ await handle.close();
59
+ handle = undefined;
60
+ await rename(temporary, file);
61
+ return file;
62
+ }
63
+ finally {
64
+ try {
65
+ await handle?.close();
66
+ }
67
+ finally {
68
+ await unlink(temporary).catch(() => { });
69
+ }
70
+ }
71
+ }
72
+ export async function removeCredential(env) {
73
+ try {
74
+ await unlink(credentialPath(env));
75
+ }
76
+ catch (error) {
77
+ if (error.code !== 'ENOENT')
78
+ throw error;
79
+ }
80
+ }
81
+ /** Human input only: never accept a credential in argv or echo its bytes. */
82
+ export async function readCredentialInput(input = process.stdin, prompt = text => { process.stderr.write(text); }) {
83
+ if (!input.isTTY) {
84
+ let text = '';
85
+ for await (const chunk of input) {
86
+ text += chunk.toString();
87
+ if (text.length > 512)
88
+ throw new CliError('invalid_credentials', 'Credential input is too long.', 3);
89
+ }
90
+ return text.replace(/\r?\n$/, '');
91
+ }
92
+ prompt('Developer key (hidden): ');
93
+ const wasRaw = input.isRaw, wasFlowing = input.readableFlowing;
94
+ return new Promise((resolve, reject) => {
95
+ let text = '';
96
+ const finish = (error) => { input.off('data', data); input.off('end', ended); input.setRawMode(wasRaw); if (wasFlowing !== true)
97
+ input.pause(); prompt('\n'); error ? reject(error) : resolve(text); };
98
+ const ended = () => finish(new CliError('invalid_credentials', 'Credential input ended unexpectedly.', 3));
99
+ const data = (chunk) => {
100
+ for (const char of chunk.toString()) {
101
+ if (char === '\r' || char === '\n') {
102
+ finish();
103
+ return;
104
+ }
105
+ if (char === '\u0003') {
106
+ finish(new CliError('cancelled', 'Login cancelled.', 2));
107
+ return;
108
+ }
109
+ if (char === '\u007f' || char === '\b')
110
+ text = text.slice(0, -1);
111
+ else
112
+ text += char;
113
+ if (text.length > 259) {
114
+ finish(new CliError('invalid_credentials', 'Credential input is too long.', 3));
115
+ return;
116
+ }
117
+ }
118
+ };
119
+ input.setRawMode(true);
120
+ input.on('data', data);
121
+ input.once('end', ended);
122
+ input.resume();
123
+ });
124
+ }
@@ -0,0 +1,19 @@
1
+ type Args = Record<string, string>;
2
+ type Client = {
3
+ request: (path: string, method?: string, body?: unknown) => Promise<any>;
4
+ context: {
5
+ stderr?: (text: string) => void;
6
+ };
7
+ };
8
+ type EnvTarget = {
9
+ path: string;
10
+ before: Buffer | null;
11
+ mode: number;
12
+ ignore?: {
13
+ root: string;
14
+ entry: string;
15
+ };
16
+ };
17
+ export declare function writeDebugEnv(t: EnvTarget, secret: string): Promise<void>;
18
+ export declare function debugKeys(action: string, args: Args, client: Client): Promise<unknown>;
19
+ export {};
@@ -0,0 +1,141 @@
1
+ import { appendFile, lstat, open, readFile, realpath, rename, unlink } from 'node:fs/promises';
2
+ import { execFile } from 'node:child_process';
3
+ import { promisify } from 'node:util';
4
+ import { basename, dirname, relative, resolve, sep } from 'node:path';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { CliError } from './index.js';
7
+ const exec = promisify(execFile);
8
+ const assignment = /^(?:export[ \t]+)?CROCHE_DEBUG_KEY[ \t]*=([^\r\n]*)(\r?)$/gm;
9
+ const value = (line) => line.trim().replace(/^(['"])(.*)\1$/, '$2');
10
+ async function git(root, args) {
11
+ try {
12
+ return (await exec('git', ['-C', root, ...args])).stdout.trim();
13
+ }
14
+ catch (error) {
15
+ if (error.code === 'ENOENT')
16
+ throw new CliError('git_unavailable', 'Git is required to protect the debug-key file.');
17
+ return null;
18
+ }
19
+ }
20
+ async function target(file, force, stderr) {
21
+ const requested = resolve(file), parent = await realpath(dirname(requested)).catch(() => { throw new CliError('invalid_env_file', 'The env file directory must exist.'); });
22
+ const path = resolve(parent, basename(requested));
23
+ let before = null, mode = 0o600;
24
+ try {
25
+ const info = await lstat(path);
26
+ if (!info.isFile() || info.isSymbolicLink())
27
+ throw new CliError('invalid_env_file', 'The env file must be a regular file, not a symlink.');
28
+ before = await readFile(path);
29
+ mode = info.mode & 0o7777;
30
+ }
31
+ catch (error) {
32
+ if (error.code !== 'ENOENT')
33
+ throw error;
34
+ }
35
+ const root = await git(parent, ['rev-parse', '--show-toplevel']);
36
+ let ignore;
37
+ if (root) {
38
+ const entry = relative(root, path).split(sep).join('/');
39
+ if (await git(root, ['ls-files', '--error-unmatch', '--', entry]) !== null)
40
+ throw new CliError('tracked_env_file', 'Refusing to write a debug key into a tracked file.');
41
+ if (await git(root, ['check-ignore', '--', entry]) === null)
42
+ ignore = { root, entry };
43
+ }
44
+ const existing = before ? [...before.toString('latin1').matchAll(assignment)] : [];
45
+ if (existing.length > 1)
46
+ throw new CliError('invalid_env_file', 'The env file contains multiple CROCHE_DEBUG_KEY assignments.');
47
+ if (existing.some(match => value(match[1]) !== '') && !force)
48
+ throw new CliError('debug_key_exists', 'CROCHE_DEBUG_KEY is already set; use --force to replace it. No key was issued.');
49
+ if (before && (mode & 0o077))
50
+ stderr('warning: the existing env file is group- or world-readable; its mode will be preserved.\n');
51
+ return { path, before, mode, ignore };
52
+ }
53
+ /** Protect the destination before issuing any one-time credential. */
54
+ async function ignoreFile(t) {
55
+ if (!t.ignore)
56
+ return;
57
+ const path = resolve(t.ignore.root, '.gitignore');
58
+ let before = '';
59
+ try {
60
+ before = await readFile(path, 'utf8');
61
+ }
62
+ catch (error) {
63
+ if (error.code !== 'ENOENT')
64
+ throw error;
65
+ }
66
+ // Root-anchored literal path: escape gitignore pattern metacharacters.
67
+ const entry = '/' + t.ignore.entry.replace(/[\\*?\[\]#! ]/g, '\\$&');
68
+ await appendFile(path, (before && !before.endsWith('\n') ? '\n' : '') + entry + '\n');
69
+ }
70
+ export async function writeDebugEnv(t, secret) {
71
+ const text = t.before?.toString('latin1') ?? '';
72
+ const matches = [...text.matchAll(assignment)];
73
+ if (matches.length === 1 && value(matches[0][1]) === secret)
74
+ return;
75
+ const newline = text.includes('\r\n') ? '\r\n' : '\n';
76
+ const updated = matches.length ? text.replace(assignment, (_line, _old, cr) => `CROCHE_DEBUG_KEY=${secret}${cr}`) : text + (text && !text.endsWith('\n') ? newline : '') + `CROCHE_DEBUG_KEY=${secret}${newline}`;
77
+ const temporary = resolve(dirname(t.path), `.croche-debug-${randomUUID()}.tmp`);
78
+ let handle;
79
+ try {
80
+ handle = await open(temporary, 'wx', 0o600);
81
+ await handle.writeFile(Buffer.from(updated, 'latin1'));
82
+ if (t.before)
83
+ await handle.chmod(t.mode);
84
+ await handle.sync();
85
+ await handle.close();
86
+ handle = undefined;
87
+ let current = null;
88
+ try {
89
+ current = await readFile(t.path);
90
+ }
91
+ catch (error) {
92
+ if (error.code !== 'ENOENT')
93
+ throw error;
94
+ }
95
+ if (t.before === null ? current !== null : current === null || !current.equals(t.before))
96
+ throw new Error('env file changed');
97
+ await rename(temporary, t.path);
98
+ }
99
+ finally {
100
+ try {
101
+ await handle?.close();
102
+ }
103
+ finally {
104
+ await unlink(temporary).catch(() => { });
105
+ }
106
+ }
107
+ }
108
+ export async function debugKeys(action, args, client) {
109
+ const project = args.project;
110
+ if (!project || !/^[A-Za-z0-9_.:-]{1,200}$/.test(project))
111
+ throw new CliError('missing_argument', 'Supply --project with a project id.');
112
+ const path = `/api/studio/projects/${encodeURIComponent(project)}/debug-tokens`;
113
+ const metadata = (t) => ({ id: t.id, name: t.name, prefix: typeof t.prefix === 'string' ? t.prefix.slice(0, 12) : t.prefix, created_at: t.created_at, last_used_at: t.last_used_at, revoked_at: t.revoked_at, installations: t.installations, warning: t.warning });
114
+ if (action === 'list') {
115
+ const result = await client.request(path);
116
+ return { debug_keys: result.debug_tokens.map(metadata) };
117
+ }
118
+ if (action === 'revoke') {
119
+ if (!args['key-id'] || !/^[A-Za-z0-9_.:-]{1,200}$/.test(args['key-id']))
120
+ throw new CliError('missing_argument', 'Supply a debug key id.');
121
+ const result = await client.request(path + '/' + encodeURIComponent(args['key-id']), 'DELETE');
122
+ return { debug_key: metadata(result.debug_token) };
123
+ }
124
+ const stderr = client.context.stderr ?? (text => process.stderr.write(text));
125
+ const destination = args.print === 'true' && !args['env-file'] ? undefined : await target(args['env-file'] ?? './.env', args.force === 'true', stderr);
126
+ if (destination)
127
+ await ignoreFile(destination);
128
+ const result = await client.request(path, 'POST', { name: args.name ?? 'Coding agent' });
129
+ const key = metadata(result.debug_token);
130
+ if (typeof result.secret !== 'string' || !/^cdt_[a-f0-9]{64}$/.test(result.secret))
131
+ throw new CliError('invalid_response', `Cloud returned an invalid debug credential; revoke issued key ${key.id}.`, 1);
132
+ if (destination) {
133
+ try {
134
+ await writeDebugEnv(destination, result.secret);
135
+ }
136
+ catch {
137
+ throw new CliError('env_write_failed', `Could not safely write the env file. Revoke issued key ${key.id} with debug-keys revoke.`, 1, { key_id: key.id });
138
+ }
139
+ }
140
+ return { debug_key: key, ...(destination ? { env_file: destination.path } : {}), ...(args.print === 'true' ? { secret: result.secret } : {}) };
141
+ }
@@ -0,0 +1,271 @@
1
+ 'use strict';
2
+
3
+ const $ = id => document.getElementById(id);
4
+ const state = { snapshot: null, token: '', endpoint: '', selectedTurn: '', selectedEvent: '', tab: 'calls', runtime: '', type: '', search: '', stream: null, loading: null, refreshAgain: false, connected: false };
5
+ const number = value => typeof value === 'number' && Number.isFinite(value) ? value : null;
6
+ const formatNumber = value => number(value) === null ? 'Unknown' : new Intl.NumberFormat('en-US').format(value);
7
+ const formatCost = value => number(value) === null ? 'Unknown' : value === 0 ? '$0.00' : `$${value.toFixed(9).replace(/0+$/, '').replace(/\.$/, '')}`;
8
+ const short = (value, length = 28) => String(value ?? '').length > length ? `${String(value).slice(0, length - 1)}…` : String(value ?? '');
9
+ const time = value => { const date = new Date(value); return Number.isFinite(date.getTime()) ? date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }) : 'Unknown time'; };
10
+ const key = turn => `${turn.runtimeInstanceId}\u0000${turn.id}`;
11
+ const obj = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
12
+ function el(tag, className = '', children = []) {
13
+ const node = document.createElement(tag); if (className) node.className = className;
14
+ for (const child of Array.isArray(children) ? children : [children]) if (child !== null && child !== undefined) node.append(child instanceof Node ? child : document.createTextNode(String(child)));
15
+ return node;
16
+ }
17
+ function button(text, className, handler) { const node = el('button', className, text); node.type = 'button'; node.addEventListener('click', handler); return node; }
18
+ function code(value, className = '') { const node = el('pre', `code-block ${className}`, typeof value === 'string' ? value : JSON.stringify(value, null, 2)); node.tabIndex = 0; return node; }
19
+ function badge(text, className = '') { return el('span', `badge ${className}`, text); }
20
+ function fold(title, content, open = false) {
21
+ const node = el('details', 'fold', [el('summary', '', title), el('div', 'fold-content', content)]); node.open = open; return node;
22
+ }
23
+ function notice(message = '', error = false) { $('notice').textContent = message; $('notice').hidden = !message; $('notice').classList.toggle('error', error); }
24
+ function connection(label, className) { $('connection-status').className = `connection-status ${className}`; $('connection-status').lastElementChild.textContent = label; }
25
+ async function api(path, options = {}) {
26
+ const response = await fetch(path, { credentials: 'same-origin', cache: 'no-store', ...options });
27
+ const body = await response.json();
28
+ if (!response.ok) { const error = new Error(body.error || `Request failed (${response.status})`); error.status = response.status; throw error; }
29
+ return body;
30
+ }
31
+ function post(path, body, headers = {}) { return api(path, { method: 'POST', headers: { 'Content-Type': 'application/json', ...headers }, body: JSON.stringify(body) }); }
32
+ function showConnection() { if (!$('connection-dialog').open) $('connection-dialog').showModal(); }
33
+ function connectionCommands() {
34
+ return /^[A-Za-z0-9_.:-]{1,200}$/.test(state.runtime)
35
+ ? `croche debug connect --runtime-id ${state.runtime}`
36
+ : 'croche debug';
37
+ }
38
+ function renderConnection() {
39
+ $('pair-form').hidden = Boolean(state.token); $('connection-details').hidden = !state.token;
40
+ $('connection-commands').textContent = connectionCommands();
41
+ }
42
+ async function copy(text, target) {
43
+ try { await navigator.clipboard.writeText(text); const previous = target.textContent; target.textContent = 'Copied'; setTimeout(() => { target.textContent = previous; }, 1400); }
44
+ catch { notice('Clipboard permission was unavailable. Select the displayed command to copy it.', true); }
45
+ }
46
+
47
+ async function initialize(pairingToken) {
48
+ try {
49
+ if (pairingToken) await post('/api/pair', {}, { Authorization: `Bearer ${pairingToken}` });
50
+ const bootstrap = await api('/api/bootstrap');
51
+ state.token = bootstrap.pairingToken; state.endpoint = bootstrap.endpoint; state.snapshot = bootstrap;
52
+ state.connected = true; $('pair-error').textContent = ''; $('pair-token').value = '';
53
+ renderConnection(); render(); startStream(); notice();
54
+ if ($('connection-dialog').open && pairingToken) $('connection-dialog').close();
55
+ } catch (error) {
56
+ state.connected = false; connection('Pairing required', 'error'); renderConnection();
57
+ if (pairingToken) $('pair-error').textContent = error.message;
58
+ showConnection(); render();
59
+ }
60
+ }
61
+ function startStream() {
62
+ state.stream?.close();
63
+ const stream = new EventSource('/api/stream'); state.stream = stream;
64
+ stream.onopen = () => { state.connected = true; renderCaptureStatus(); };
65
+ stream.addEventListener('change', () => void refresh());
66
+ stream.onerror = () => { state.connected = false; connection('Reconnecting', 'error'); };
67
+ }
68
+ async function refresh() {
69
+ if (state.loading) { state.refreshAgain = true; return state.loading; }
70
+ state.loading = (async () => {
71
+ try { state.snapshot = await api('/api/state'); state.connected = true; render(); }
72
+ catch (error) { connection('Connection lost', 'error'); if (error.status === 401) { state.stream?.close(); state.token = ''; renderConnection(); showConnection(); } else notice(error.message, true); }
73
+ finally { state.loading = null; if (state.refreshAgain) { state.refreshAgain = false; void refresh(); } }
74
+ })(); return state.loading;
75
+ }
76
+ function renderCaptureStatus() {
77
+ const paused = state.snapshot?.paused;
78
+ if (state.connected) connection(paused ? 'Capture paused' : 'Live capture', paused ? 'paused' : 'connected');
79
+ $('capture-toggle').textContent = paused ? 'Resume capture' : 'Pause capture';
80
+ $('capture-toggle').disabled = !state.token; $('clear-capture').disabled = !state.token;
81
+ }
82
+ function metric(label, value, foot, className = '') { return el('div', 'metric', [el('p', 'metric-label', label), el('p', `metric-value ${className}`, value), el('p', 'metric-foot', foot)]); }
83
+ function renderOverview() {
84
+ const capture = state.snapshot; const stats = capture?.stats || {}; const dropped = (stats.clientDropped || 0) + (stats.evicted || 0) + (stats.pausedDropped || 0);
85
+ const requests = (capture?.turns || []).reduce((sum, turn) => sum + (turn.requestCount || 0), 0);
86
+ $('overview').replaceChildren(
87
+ metric('CAPTURED RUNTIMES', capture?.runtimes?.length || 0, 'Instances with retained events'),
88
+ metric('CAPTURED TURNS', capture?.turns?.length || 0, `${formatNumber(stats.retained || 0)} retained events`),
89
+ metric('MODEL REQUESTS', requests, 'Requests observed in this capture'),
90
+ metric('CAPTURE HEALTH', dropped ? `${formatNumber(dropped)} lost` : capture?.paused ? 'Paused' : 'Listening', dropped ? 'Some execution details are unavailable' : `${((stats.bytes || 0) / 1024).toFixed(1)} KiB held locally`, dropped ? 'warning' : 'good'),
91
+ );
92
+ const limits = capture?.limits;
93
+ $('retention-note').textContent = limits ? `Up to ${formatNumber(limits.events)} events / ${(limits.bytes / 1024 / 1024).toFixed(0)} MiB · unknown values stay unknown` : 'Pair with your local collector to start';
94
+ }
95
+ function updateSelect(node, entries, value, placeholder) {
96
+ const signature = JSON.stringify(entries); if (node.dataset.options !== signature) {
97
+ node.replaceChildren(new Option(placeholder, ''), ...entries.map(([id, name]) => new Option(name, id))); node.dataset.options = signature;
98
+ }
99
+ node.value = value;
100
+ }
101
+ function matches(event) {
102
+ return (!state.runtime || event.runtimeInstanceId === state.runtime) && (!state.type || event.type === state.type) &&
103
+ (!state.search || JSON.stringify(event).toLowerCase().includes(state.search));
104
+ }
105
+ function currentEvents(turn) { return (state.snapshot?.events || []).filter(event => event.runtimeInstanceId === turn.runtimeInstanceId && event.turnId === turn.id); }
106
+ function filteredTurns() {
107
+ return (state.snapshot?.turns || []).filter(turn => {
108
+ if (state.runtime && turn.runtimeInstanceId !== state.runtime) return false;
109
+ if (!state.type && (!state.search || `${turn.input} ${turn.id} ${turn.appName}`.toLowerCase().includes(state.search))) return true;
110
+ return currentEvents(turn).some(matches);
111
+ });
112
+ }
113
+ function renderTurnList(turns) {
114
+ $('turn-count').textContent = String(turns.length);
115
+ const items = turns.map(turn => {
116
+ const card = button('', `turn-card${key(turn) === state.selectedTurn ? ' selected' : ''}`, () => { state.selectedTurn = key(turn); state.selectedEvent = ''; renderTurnList(turns); renderInspector(turn); });
117
+ card.setAttribute('aria-pressed', String(key(turn) === state.selectedTurn));
118
+ const status = String(turn.status || 'in progress');
119
+ card.append(el('div', 'turn-top', [el('span', 'turn-app', turn.appName || 'Unnamed app'), el('span', 'turn-time', time(turn.startedAt))]),
120
+ el('p', 'turn-title', turn.input || 'Input not captured'),
121
+ el('div', 'turn-bottom', [el('span', `state ${status.replace(/\s+/g, '-')}`, status), ...(partial(turn) ? [badge('Partial', 'warning')] : [el('span', '', `${(turn.calls || []).length} calls`)]), el('span', 'turn-cost', formatCost(turn.cost))]));
122
+ return card;
123
+ });
124
+ $('turn-list').replaceChildren(...(items.length ? items : [el('p', 'list-empty', state.search || state.type || state.runtime ? 'No turns match these filters.' : 'Your next app input will appear here.')]));
125
+ }
126
+ function partial(turn) { return Boolean(turn.partialCapture || turn.partial) || !turn.input || (turn.calls || []).some(call => !call.requestEventId || (!call.responseEventId && !call.errorEventId)); }
127
+ function tinyMetric(label, value) { return el('div', '', [el('p', 'small-metric-label', label), el('p', 'small-metric-value', value)]); }
128
+ function renderInspector(turn) {
129
+ const inspector = $('inspector'); const scroll = inspector.scrollTop;
130
+ if (!turn) {
131
+ const observed = state.snapshot?.runtimes || [];
132
+ const ready = state.runtime ? observed.some(runtime => runtime.id === state.runtime) : observed.length;
133
+ const empty = el('div', 'empty-state', [el('div', 'empty-mark', '↳'), el('h2', '', ready ? 'Runtime events received. Waiting for a turn.' : state.runtime ? 'Waiting for this Runtime.' : 'A clear view of every turn.'), el('p', '', ready ? 'Send a new message in the connected app session to capture its model calls, tool results, and costs.' : state.runtime ? 'Run croche debug, select this Runtime, and open the URL printed by the CLI.' : 'Keep your app open, run croche debug, and select its Runtime. Open the printed URL to inspect its traces here.'), ...(state.runtime ? [el('p', 'identifier', state.runtime)] : []), button('CLI connection', 'button button-primary', showConnection)]);
134
+ const ungrouped = (state.snapshot?.events || []).filter(event => !event.turnId && matches(event));
135
+ if (ungrouped.length) empty.append(el('p', '', `${ungrouped.length} Runtime lifecycle event${ungrouped.length === 1 ? '' : 's'} received.`), fold('Runtime lifecycle events', renderTimeline(ungrouped), ungrouped.some(event => event.id === state.selectedEvent)));
136
+ inspector.replaceChildren(empty); return;
137
+ }
138
+ const events = currentEvents(turn); const status = String(turn.status || 'in progress'); const usage = turn.usage || {};
139
+ const heading = el('div', 'inspection-heading', [el('div', 'inspection-topline', [el('span', 'inspection-label', 'TURN INSPECTION'), el('span', 'turn-time', `${time(turn.startedAt)} · ${turn.appName}`)]), el('h2', 'inspection-input', turn.input || 'Input is outside this capture'),
140
+ el('div', 'badges', [badge(status, ['failed', 'interrupted'].includes(status) ? 'error' : ''), ...(turn.recovered ? [badge('Reply recovery', 'warning')] : []), ...(partial(turn) ? [badge('Partial capture', 'warning')] : []), badge(`${events.length} events`)]), el('p', 'identifier', turn.id)]);
141
+ const metrics = el('div', 'turn-metrics', [tinyMetric('Model calls', String((turn.calls || []).length)), tinyMetric('Input tokens', formatNumber(usage.prompt)), tinyMetric('Output tokens', formatNumber(usage.completion)), tinyMetric('Actual cost', formatCost(turn.cost)), tinyMetric('Cost source', turn.costSource || 'unknown')]);
142
+ const subset = el('p', 'subset-note', `Cached input: ${formatNumber(usage.cached)} · Reasoning output: ${formatNumber(usage.reasoning)} · Subsets of input/output, never added again.`);
143
+ const tabs = el('div', 'tabs');
144
+ for (const [id, label] of [['calls', 'Call stack'], ['events', `Events · ${events.length}`], ['json', 'Turn JSON']]) {
145
+ const tab = button(label, `tab${state.tab === id ? ' selected' : ''}`, () => { state.tab = id; renderInspector(turn); }); tab.setAttribute('aria-pressed', String(state.tab === id)); tabs.append(tab);
146
+ }
147
+ const body = el('div', 'inspection-body');
148
+ if (turn.captureNotes?.length) body.append(el('div', 'inner-note warning', turn.captureNotes.join(' ')));
149
+ if (state.tab === 'json') body.append(code(turn));
150
+ else if (state.tab === 'events') body.append(renderTimeline(events.filter(matches)));
151
+ else renderCalls(body, turn, events);
152
+ inspector.replaceChildren(heading, metrics, subset, tabs, body); inspector.scrollTop = scroll;
153
+ }
154
+ function requestContent(event) {
155
+ if (!event?.data?.body) return [el('div', 'inner-note', 'Internal request bodies were not captured. Attach this Runtime with croche debug before starting a new turn to capture full model requests.'), code(event?.data || { status: 'Request not captured' })];
156
+ const body = event.data.body; const content = [];
157
+ content.push(el('p', 'response-label', `${body.messages?.length || 0} messages · sent in order`));
158
+ for (const [index, message] of (body.messages || []).entries()) {
159
+ const role = String(message.role || 'unknown');
160
+ const box = el('div', `message ${['system', 'user', 'assistant', 'tool'].includes(role) ? role : ''}`, [el('div', 'message-role', [el('span', '', role), el('span', '', `${index + 1}${message.tool_call_id ? ` · ${short(message.tool_call_id, 24)}` : ''}`)]), code(message.content === null ? 'null' : message.content ?? '(No content)')]);
161
+ if (message.tool_calls) box.append(fold('Tool calls in this message', code(message.tool_calls)));
162
+ content.push(box);
163
+ }
164
+ content.push(fold(`Tools · ${body.tools?.length || 0}`, code(body.tools || [])));
165
+ const settings = Object.fromEntries(Object.entries(body).filter(([name]) => !['messages', 'tools'].includes(name)));
166
+ content.push(fold('Request settings', code(settings)), fold('Complete request JSON', code(body)));
167
+ return content;
168
+ }
169
+ function responseContent(event) {
170
+ if (!event?.data?.body) return [el('div', 'inner-note', event ? 'Internal response bodies were not captured. Usage and finish metadata remain available below.' : 'No response event was captured for this operation.'), code(event?.data || { status: 'Response unknown' })];
171
+ const body = event.data.body; const content = [];
172
+ for (const [index, choice] of (body.choices || []).entries()) {
173
+ const message = obj(choice.message);
174
+ content.push(el('p', 'response-label', `Choice ${index + 1} · finish reason: ${choice.finish_reason ?? 'unknown'}`), code(message.content === null ? 'null — no visible content returned' : message.content ?? '(Content absent)'));
175
+ if (message.reasoning !== undefined) content.push(el('p', 'response-label', 'Provider reasoning · full diagnostic capture'), code(message.reasoning, 'response-reasoning'));
176
+ if (message.reasoning_details !== undefined) content.push(fold('Reasoning details', code(message.reasoning_details)));
177
+ if (message.tool_calls) content.push(el('p', 'response-label', 'Requested tool calls'), code(message.tool_calls));
178
+ }
179
+ if (body.error) content.push(code(body.error));
180
+ content.push(fold('Usage and cost', code(body.usage ?? { status: 'Usage unavailable' })), fold('Complete raw response JSON', code(body), true));
181
+ return content;
182
+ }
183
+ function renderCalls(container, turn, events) {
184
+ const calls = turn.calls || []; const byId = new Map(events.map(event => [event.id, event]));
185
+ container.append(el('div', 'section-label', [el('span', '', 'MODEL CALL STACK'), el('span', '', `${calls.length} operation${calls.length === 1 ? '' : 's'}`)]));
186
+ if (!calls.length) container.append(el('div', 'inner-note', 'No model calls are present in this capture. The turn may have been replayed, blocked before inference, or captured after its model operations.'));
187
+ for (const [index, call] of calls.entries()) {
188
+ const request = byId.get(call.requestEventId), response = byId.get(call.responseEventId), error = byId.get(call.errorEventId);
189
+ const model = response?.data?.body?.model || request?.data?.body?.model || response?.data?.model || request?.data?.model || 'Model not captured';
190
+ const usage = call.usage || {};
191
+ const card = el('article', 'call-card', [el('div', 'call-heading', [el('div', 'call-identity', [el('span', 'call-number', String(index + 1).padStart(2, '0')), el('div', '', [el('p', 'call-name', model), el('p', 'call-description', short(call.operationId, 54))])]), el('span', 'call-money', formatCost(call.cost))]),
192
+ el('div', 'call-usage', [el('span', '', ['Input ', el('strong', '', formatNumber(usage.prompt))]), el('span', '', ['Output ', el('strong', '', formatNumber(usage.completion))]), el('span', '', ['Cached ', el('strong', '', formatNumber(usage.cached))]), el('span', '', ['Reasoning ', el('strong', '', formatNumber(usage.reasoning))])])]);
193
+ if (!request || (!response && !error)) card.append(el('div', 'call-flags', badge(!request ? 'Partial capture · request unavailable' : 'Awaiting response · cost unknown', 'warning')));
194
+ if (events.some(event => event.type === 'model.recovery' && event.operationId === call.operationId)) card.append(el('div', 'call-flags', badge('Empty reply · one recovery scheduled', 'warning')));
195
+ card.append(fold('Request · prompts, messages & tools', requestContent(request), index === 0), fold('Response · raw content, markers & reasoning', responseContent(response), Boolean(response)));
196
+ if (error) card.append(fold('Request error', code(error.data), true));
197
+ const tools = events.filter(event => event.operationId === call.operationId && event.type.startsWith('tool.'));
198
+ if (tools.length) card.append(fold(`Tool events · ${tools.length}`, renderTimeline(tools), true));
199
+ container.append(card);
200
+ }
201
+ const terminal = [...events].reverse().find(event => event.type === 'turn.completed' || event.type === 'input.replayed');
202
+ if (terminal?.data?.result) {
203
+ const result = terminal.data.result;
204
+ container.append(el('p', 'section-label', 'FINAL RUNTIME RESULT'), el('div', 'call-card', [fold('Display text', code(result.text || '(No visible output)'), true), fold('Raw text and markers', code({ raw: result.raw, markers: result.markers })), fold('Complete result', code(result), Boolean(result.error))]));
205
+ }
206
+ }
207
+ function eventDescription(event) {
208
+ const data = event.data || {};
209
+ if (event.type.startsWith('input.')) return data.input?.text || event.turnId || '';
210
+ if (event.type.startsWith('tool.')) return `${data.name || ''}${data.error ? ` · ${data.error.message || data.error}` : ''}`;
211
+ if (event.type === 'marker') return `:${data.name}:`;
212
+ if (event.type === 'turn.completed') return `${data.result?.status || ''} · ${formatCost(data.result?.cost)}`;
213
+ if (event.type === 'model.response') return `${data.body?.choices?.[0]?.finish_reason || data.choices?.[0]?.finish_reason || 'Response'} · ${formatCost(data.body?.usage?.cost ?? data.usage?.cost)}`;
214
+ return event.operationId || event.runtimeInstanceId;
215
+ }
216
+ function renderTimeline(events) {
217
+ const timeline = el('div', 'timeline');
218
+ if (!events.length) { timeline.append(el('p', 'inner-note', 'No events match the current filters.')); return timeline; }
219
+ for (const event of events) {
220
+ const selected = state.selectedEvent === event.id;
221
+ const item = button('', `event-button${selected ? ' selected' : ''}`, () => {
222
+ state.selectedEvent = selected ? '' : event.id;
223
+ const turn = (state.snapshot?.turns || []).find(value => key(value) === state.selectedTurn);
224
+ renderInspector(turn);
225
+ });
226
+ item.setAttribute('aria-expanded', String(selected));
227
+ item.append(el('span', 'event-sequence', String(event.sequence).padStart(2, '0')), el('div', 'event-info', [el('p', 'event-type', event.type), el('p', 'event-description', eventDescription(event))]), el('span', 'turn-time', time(event.timestamp)));
228
+ timeline.append(item);
229
+ if (selected) timeline.append(el('div', 'event-detail', code(event)));
230
+ }
231
+ return timeline;
232
+ }
233
+ function render() {
234
+ renderCaptureStatus(); renderOverview();
235
+ const capture = state.snapshot;
236
+ const runtimes = (capture?.runtimes || []).map(runtime => [runtime.id, `${runtime.appName} · ${short(runtime.id, 16)}`]);
237
+ // Keep an explicitly selected app instance while its first events are arriving.
238
+ if (state.runtime && !runtimes.some(([id]) => id === state.runtime)) runtimes.push([state.runtime, `Waiting for runtime · ${short(state.runtime, 24)}`]);
239
+ updateSelect($('runtime-filter'), runtimes, state.runtime, 'All runtimes');
240
+ updateSelect($('type-filter'), [...new Set((capture?.events || []).map(event => event.type))].sort().map(type => [type, type]), state.type, 'All event types');
241
+ const turns = filteredTurns();
242
+ if (!turns.some(turn => key(turn) === state.selectedTurn)) { state.selectedTurn = turns[0] ? key(turns[0]) : ''; state.selectedEvent = ''; }
243
+ renderTurnList(turns); renderInspector(turns.find(turn => key(turn) === state.selectedTurn));
244
+ }
245
+
246
+ $('connect-app').addEventListener('click', showConnection);
247
+ $('close-dialog').addEventListener('click', () => $('connection-dialog').close());
248
+ $('pair-form').addEventListener('submit', event => { event.preventDefault(); void initialize($('pair-token').value.trim()); });
249
+ $('copy-command').addEventListener('click', event => void copy(connectionCommands(), event.currentTarget));
250
+ $('capture-toggle').addEventListener('click', async () => { try { state.snapshot = await post('/api/capture', { paused: !state.snapshot?.paused }); render(); } catch (error) { notice(error.message, true); } });
251
+ $('clear-capture').addEventListener('click', async () => { try { state.snapshot = await post('/api/clear', {}); state.selectedTurn = ''; state.selectedEvent = ''; notice('Local capture cleared. Application state and Runtime execution are unchanged.'); render(); } catch (error) { notice(error.message, true); } });
252
+ $('search').addEventListener('input', event => { state.search = event.target.value.trim().toLowerCase(); render(); });
253
+ $('runtime-filter').addEventListener('change', event => {
254
+ state.runtime = event.target.value;
255
+ const url = new URL(location.href);
256
+ if (state.runtime) url.searchParams.set('runtime', state.runtime); else url.searchParams.delete('runtime');
257
+ history.replaceState(null, '', `${url.pathname}${url.search}`);
258
+ renderConnection();
259
+ render();
260
+ });
261
+ $('type-filter').addEventListener('change', event => { state.type = event.target.value; if (state.type) state.tab = 'events'; render(); });
262
+ window.addEventListener('beforeunload', () => state.stream?.close());
263
+ const linkParameters = new URLSearchParams(location.hash.slice(1));
264
+ const pairingToken = linkParameters.get('token');
265
+ const pageUrl = new URL(location.href);
266
+ const requestedRuntime = linkParameters.get('runtime') ?? pageUrl.searchParams.get('runtime');
267
+ if (requestedRuntime && requestedRuntime.length <= 200 && !/[\u0000-\u001f]/.test(requestedRuntime)) {
268
+ state.runtime = requestedRuntime; pageUrl.searchParams.set('runtime', requestedRuntime);
269
+ } else pageUrl.searchParams.delete('runtime');
270
+ if (location.hash || pageUrl.search !== location.search) history.replaceState(null, '', `${pageUrl.pathname}${pageUrl.search}`);
271
+ render(); void initialize(pairingToken);
@@ -0,0 +1,71 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <meta name="color-scheme" content="dark" />
7
+ <title>Croche · Runtime debugger</title>
8
+ <link rel="stylesheet" href="/styles.css" />
9
+ <script src="/app.js" defer></script>
10
+ </head>
11
+ <body>
12
+ <header class="app-header">
13
+ <a class="brand" href="/" aria-label="Croche Runtime debugger">
14
+ <span class="brand-mark" aria-hidden="true">c</span>
15
+ <span><span class="brand-name">croche</span><span class="brand-divider">/</span><span class="brand-product">Runtime debugger</span></span>
16
+ </a>
17
+ <div class="header-actions">
18
+ <span id="connection-status" class="connection-status"><span class="status-dot"></span><span>Connecting</span></span>
19
+ <button id="connect-app" class="button button-primary">CLI connection <span aria-hidden="true">↗</span></button>
20
+ </div>
21
+ </header>
22
+
23
+ <main>
24
+ <section class="page-heading">
25
+ <div><p class="eyebrow">LOCAL DEVELOPMENT</p><h1>See what your Runtime is doing.</h1><p class="subtitle">Follow each input through the model, its tools, and the final response.</p></div>
26
+ <div class="capture-actions">
27
+ <button id="capture-toggle" class="button" disabled>Pause capture</button>
28
+ <a id="export-capture" href="/api/export" class="button" download>Export JSON</a>
29
+ <button id="clear-capture" class="button button-quiet" disabled>Clear</button>
30
+ </div>
31
+ </section>
32
+
33
+ <div id="notice" class="notice" role="status" hidden></div>
34
+ <section id="overview" class="overview" aria-label="Capture overview"></section>
35
+
36
+ <section class="trace-explorer" aria-label="Runtime trace explorer">
37
+ <div class="filters">
38
+ <label class="search-box"><span aria-hidden="true">⌕</span><input id="search" type="search" placeholder="Search inputs, tools, IDs, or content…" aria-label="Search trace" /></label>
39
+ <label><span class="sr-only">Runtime filter</span><select id="runtime-filter"><option value="">All runtimes</option></select></label>
40
+ <label><span class="sr-only">Event type filter</span><select id="type-filter"><option value="">All event types</option></select></label>
41
+ </div>
42
+ <div class="workbench">
43
+ <aside class="turn-column" aria-label="Captured turns">
44
+ <div class="column-heading"><h2>Turns</h2><span id="turn-count" class="count">0</span></div>
45
+ <div id="turn-list" class="turn-list"></div>
46
+ </aside>
47
+ <section id="inspector" class="inspector" aria-label="Selected turn inspector" aria-live="polite"></section>
48
+ </div>
49
+ </section>
50
+ <footer><span><span class="local-dot" aria-hidden="true"></span>Local capture · held in memory</span><span id="retention-note">Waiting for collector limits</span></footer>
51
+ </main>
52
+
53
+ <dialog id="connection-dialog" class="connection-dialog">
54
+ <div class="dialog-heading"><div><p class="eyebrow">CLI CONNECTION</p><h2>Inspect an attached Runtime</h2></div><button id="close-dialog" class="icon-button" aria-label="Close connection dialog">×</button></div>
55
+ <p class="dialog-description">Keep your app open. Run <code>croche debug</code>, choose its Runtime, then open the URL printed by the CLI. The CLI starts or reuses this server and attaches the selected Runtime.</p>
56
+ <div class="snippet-heading"><h3>Run in your terminal</h3><button id="copy-command" class="button button-small" type="button">Copy command</button></div>
57
+ <pre id="connection-commands" class="code-block snippet" tabindex="0">croche debug</pre>
58
+ <form id="pair-form">
59
+ <p class="dialog-description">Opened the server without its authenticated URL? Run <code>croche debug token</code> and enter that token here to authorize this viewer.</p>
60
+ <label for="pair-token">Viewer access token</label>
61
+ <div class="input-action"><input id="pair-token" type="password" autocomplete="off" placeholder="Token from croche debug token" required /><button class="button button-primary" type="submit">Authorize viewer</button></div>
62
+ <p id="pair-error" class="form-error" role="alert"></p>
63
+ </form>
64
+ <div id="connection-details" hidden>
65
+ <div class="paired-label"><span class="local-dot"></span>Viewer authorized for this local server</div>
66
+ <p class="dialog-description">Use the CLI to attach another Runtime. Select a captured Runtime above to inspect its events and turns.</p>
67
+ <p class="privacy-note">Full visibility includes system prompts, conversation content, tool data and provider reasoning. Use it in development only. Runtime authentication and provider keys are never captured.</p>
68
+ </div>
69
+ </dialog>
70
+ </body>
71
+ </html>