unfold-deploy 0.0.0-stage → 0.1.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.
- package/CHANGELOG.md +15 -0
- package/LICENSE +21 -0
- package/README.md +113 -2
- package/bin/unfold.js +14 -0
- package/demos/vercel-build-failure.json +331 -0
- package/demos/vercel-interrupted.json +271 -0
- package/demos/vercel-success.json +343 -0
- package/dist/cli.js +113 -0
- package/dist/commands/demo.js +61 -0
- package/dist/commands/observe.js +122 -0
- package/dist/commands/replay.js +61 -0
- package/dist/commands/run.js +24 -0
- package/dist/commands/show.js +44 -0
- package/dist/core/fix-prompt.js +85 -0
- package/dist/core/flow.js +200 -0
- package/dist/core/launch.js +196 -0
- package/dist/core/model.js +3 -0
- package/dist/core/redact.js +79 -0
- package/dist/core/server.js +109 -0
- package/dist/core/session.js +105 -0
- package/dist/core/store.js +52 -0
- package/dist/core/terminal.js +107 -0
- package/dist/providers/index.js +2 -0
- package/dist/providers/provider.js +1 -0
- package/dist/providers/vercel/index.js +55 -0
- package/dist/providers/vercel/parser.js +239 -0
- package/dist/providers/vercel/stages.js +51 -0
- package/dist/tui/ansi.js +71 -0
- package/dist/tui/explore.js +220 -0
- package/dist/tui/panel.js +118 -0
- package/dist/tui/render.js +133 -0
- package/dist/tui/restore.js +29 -0
- package/dist/ui/app.js +332 -0
- package/dist/ui/index.html +60 -0
- package/dist/ui/styles.css +220 -0
- package/package.json +59 -4
- package/scripts/postinstall.mjs +13 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { runDemo, DEMO_NAMES } from './commands/demo.js';
|
|
3
|
+
import { DEFAULT_FLAGS } from './commands/observe.js';
|
|
4
|
+
import { listRuns, runReplay } from './commands/replay.js';
|
|
5
|
+
import { runLive } from './commands/run.js';
|
|
6
|
+
import { runShow } from './commands/show.js';
|
|
7
|
+
import { providers } from './providers/index.js';
|
|
8
|
+
const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
9
|
+
const HELP = `unfold — Watch what happens after you hit Enter.
|
|
10
|
+
|
|
11
|
+
Usage
|
|
12
|
+
unfold vercel [vercel deploy flags] Run a Vercel preview deploy with a live flow in your terminal
|
|
13
|
+
unfold show [run] Explore a run in the terminal (defaults to the latest)
|
|
14
|
+
unfold demo <name> Play a recorded demo (${DEMO_NAMES.join(', ')})
|
|
15
|
+
unfold replay [run] Play a saved run again
|
|
16
|
+
unfold runs List saved runs
|
|
17
|
+
|
|
18
|
+
Unfold options (anywhere on the line)
|
|
19
|
+
--fix <agent> If the run fails, start "claude" or "codex" with the fix prompt
|
|
20
|
+
(a fix prompt is always saved on failure; this only launches the agent)
|
|
21
|
+
--web Also show the flow in a local browser page (off by default)
|
|
22
|
+
--no-open With --web: don't open the browser automatically
|
|
23
|
+
--once With --web: exit when the run ends instead of keeping the page served
|
|
24
|
+
--port <n> With --web: port for the page (default 4317)
|
|
25
|
+
--no-panel Don't pin the live flow panel to the bottom of the terminal
|
|
26
|
+
--speed <n> Playback speed for demo/replay (default 1)
|
|
27
|
+
|
|
28
|
+
Examples
|
|
29
|
+
unfold vercel
|
|
30
|
+
unfold vercel --fix claude
|
|
31
|
+
unfold show
|
|
32
|
+
unfold demo build-failure
|
|
33
|
+
`;
|
|
34
|
+
/** A mistake in how Unfold was invoked: printed without a stack trace. */
|
|
35
|
+
export class UsageError extends Error {
|
|
36
|
+
}
|
|
37
|
+
/** Pulls Unfold's own flags out of argv; everything else goes to the wrapped CLI. */
|
|
38
|
+
export function parseArgs(argv) {
|
|
39
|
+
const rest = [];
|
|
40
|
+
const flags = { ...DEFAULT_FLAGS };
|
|
41
|
+
let speed = 1;
|
|
42
|
+
for (let i = 0; i < argv.length; i++) {
|
|
43
|
+
const a = argv[i];
|
|
44
|
+
if (a === '--web')
|
|
45
|
+
flags.web = true;
|
|
46
|
+
else if (a === '--no-open')
|
|
47
|
+
flags.open = false;
|
|
48
|
+
else if (a === '--once')
|
|
49
|
+
flags.once = true;
|
|
50
|
+
else if (a === '--no-panel')
|
|
51
|
+
flags.panel = false;
|
|
52
|
+
else if (a === '--port')
|
|
53
|
+
flags.port = Number(argv[++i]);
|
|
54
|
+
else if (a.startsWith('--port='))
|
|
55
|
+
flags.port = Number(a.slice(7));
|
|
56
|
+
else if (a === '--fix' || a.startsWith('--fix=')) {
|
|
57
|
+
const v = a === '--fix' ? argv[++i] : a.slice(6);
|
|
58
|
+
if (v !== 'claude' && v !== 'codex')
|
|
59
|
+
throw new UsageError(`--fix expects "claude" or "codex", got "${v ?? ''}"`);
|
|
60
|
+
flags.fix = v;
|
|
61
|
+
}
|
|
62
|
+
else if (a === '--speed')
|
|
63
|
+
speed = Number(argv[++i]) || 1;
|
|
64
|
+
else if (a.startsWith('--speed='))
|
|
65
|
+
speed = Number(a.slice(8)) || 1;
|
|
66
|
+
else
|
|
67
|
+
rest.push(a);
|
|
68
|
+
}
|
|
69
|
+
return { rest, flags, speed };
|
|
70
|
+
}
|
|
71
|
+
export async function main(argv) {
|
|
72
|
+
try {
|
|
73
|
+
return await run(argv);
|
|
74
|
+
}
|
|
75
|
+
catch (err) {
|
|
76
|
+
if (!(err instanceof UsageError))
|
|
77
|
+
throw err;
|
|
78
|
+
process.stderr.write(`unfold: ${err.message}\nRun \`unfold --help\` for usage.\n`);
|
|
79
|
+
return 2;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
async function run(argv) {
|
|
83
|
+
const [cmd, ...tail] = argv;
|
|
84
|
+
if (cmd === '-v' || cmd === '--version' || cmd === 'version') {
|
|
85
|
+
process.stdout.write(VERSION + '\n');
|
|
86
|
+
return 0;
|
|
87
|
+
}
|
|
88
|
+
if (!cmd || cmd === '-h' || cmd === '--help' || cmd === 'help') {
|
|
89
|
+
process.stdout.write(HELP);
|
|
90
|
+
return 0;
|
|
91
|
+
}
|
|
92
|
+
const provider = providers[cmd];
|
|
93
|
+
if (provider) {
|
|
94
|
+
// Only strip Unfold flags; the wrapped CLI receives everything else verbatim.
|
|
95
|
+
const { rest, flags } = parseArgs(tail);
|
|
96
|
+
return runLive(provider, rest, flags);
|
|
97
|
+
}
|
|
98
|
+
const { rest, flags, speed } = parseArgs(tail);
|
|
99
|
+
switch (cmd) {
|
|
100
|
+
case 'show':
|
|
101
|
+
return runShow(rest[0], flags);
|
|
102
|
+
case 'demo':
|
|
103
|
+
return runDemo(rest[0] ?? 'success', flags, speed);
|
|
104
|
+
case 'replay':
|
|
105
|
+
return runReplay(rest[0], flags, speed);
|
|
106
|
+
case 'runs':
|
|
107
|
+
for (const r of listRuns())
|
|
108
|
+
process.stdout.write(r + '\n');
|
|
109
|
+
return 0;
|
|
110
|
+
default:
|
|
111
|
+
throw new UsageError(`unknown command "${cmd}". Supported: ${[...Object.keys(providers), 'show', 'demo', 'replay', 'runs'].join(', ')}.`);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { providers } from '../providers/index.js';
|
|
5
|
+
import { observe, say } from './observe.js';
|
|
6
|
+
export const DEMOS_DIR = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'demos');
|
|
7
|
+
export const DEMO_NAMES = ['success', 'build-failure', 'interrupted'];
|
|
8
|
+
export function loadDemo(name) {
|
|
9
|
+
return JSON.parse(readFileSync(join(DEMOS_DIR, `vercel-${name}.json`), 'utf8'));
|
|
10
|
+
}
|
|
11
|
+
export async function runDemo(name, flags, speed) {
|
|
12
|
+
if (!DEMO_NAMES.includes(name)) {
|
|
13
|
+
say(`Unknown demo "${name}". Try: ${DEMO_NAMES.join(', ')}`);
|
|
14
|
+
return 2;
|
|
15
|
+
}
|
|
16
|
+
const t = loadDemo(name);
|
|
17
|
+
const provider = providers[t.provider];
|
|
18
|
+
say(`Demo: ${t.description} Recorded output, no Vercel account or network needed.`);
|
|
19
|
+
return observe({
|
|
20
|
+
provider,
|
|
21
|
+
command: t.command,
|
|
22
|
+
cwd: t.cwd,
|
|
23
|
+
mode: 'demo',
|
|
24
|
+
flags,
|
|
25
|
+
save: true,
|
|
26
|
+
waitForBrowser: true,
|
|
27
|
+
run: (session, term) => play(t, session, speed, term),
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
/** Plays a transcript to the terminal and the session. Ctrl+C stops playback. */
|
|
31
|
+
export function play(t, session, speed, term) {
|
|
32
|
+
const write = (d) => (term ? term.write(d) : process.stdout.write(d));
|
|
33
|
+
return new Promise((resolve) => {
|
|
34
|
+
let i = 0;
|
|
35
|
+
let timer;
|
|
36
|
+
const start = Date.now();
|
|
37
|
+
const onSigint = () => {
|
|
38
|
+
if (timer)
|
|
39
|
+
clearTimeout(timer);
|
|
40
|
+
process.off('SIGINT', onSigint);
|
|
41
|
+
write('^C\r\n');
|
|
42
|
+
session.write('^C\r\n');
|
|
43
|
+
resolve({ exitCode: 130, signal: null, interrupted: true });
|
|
44
|
+
};
|
|
45
|
+
process.on('SIGINT', onSigint);
|
|
46
|
+
const step = () => {
|
|
47
|
+
while (i < t.chunks.length && t.chunks[i].t / speed <= Date.now() - start) {
|
|
48
|
+
const { d } = t.chunks[i++];
|
|
49
|
+
write(d);
|
|
50
|
+
session.write(d);
|
|
51
|
+
}
|
|
52
|
+
if (i >= t.chunks.length) {
|
|
53
|
+
process.off('SIGINT', onSigint);
|
|
54
|
+
resolve({ exitCode: t.exitCode, signal: t.signal, interrupted: t.interrupted });
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
timer = setTimeout(step, Math.max(0, t.chunks[i].t / speed - (Date.now() - start)));
|
|
58
|
+
};
|
|
59
|
+
step();
|
|
60
|
+
});
|
|
61
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { terminalMode, which } from '../core/launch.js';
|
|
3
|
+
import { Redactor } from '../core/redact.js';
|
|
4
|
+
import { startServer } from '../core/server.js';
|
|
5
|
+
import { Session } from '../core/session.js';
|
|
6
|
+
import { RunRecorder, saveFixPrompt } from '../core/store.js';
|
|
7
|
+
import { style } from '../tui/ansi.js';
|
|
8
|
+
import { LivePanel, panelSupported } from '../tui/panel.js';
|
|
9
|
+
import { summary } from '../tui/render.js';
|
|
10
|
+
export const DEFAULT_FLAGS = { web: false, open: true, once: false, panel: true };
|
|
11
|
+
const err = style(!!process.stderr.isTTY && !process.env.NO_COLOR);
|
|
12
|
+
export const say = (msg) => process.stderr.write(`${err.dim('[unfold]')} ${msg}\n`);
|
|
13
|
+
export async function observe(opts) {
|
|
14
|
+
const session = new Session({
|
|
15
|
+
provider: opts.provider,
|
|
16
|
+
command: opts.command,
|
|
17
|
+
cwd: opts.cwd,
|
|
18
|
+
mode: opts.mode,
|
|
19
|
+
// Secret-looking env values are matched in memory only; the environment is never saved.
|
|
20
|
+
redactor: new Redactor({ env: opts.mode === 'live' ? process.env : {} }),
|
|
21
|
+
// Only real runs write files; replays and `show --web` reuse what's saved.
|
|
22
|
+
saveFixPrompt: opts.save ? saveFixPrompt : undefined,
|
|
23
|
+
});
|
|
24
|
+
let recorder;
|
|
25
|
+
if (opts.save) {
|
|
26
|
+
recorder = new RunRecorder(session.runId);
|
|
27
|
+
session.subscribe((event) => recorder.write(event));
|
|
28
|
+
}
|
|
29
|
+
session.start();
|
|
30
|
+
if (recorder)
|
|
31
|
+
session.state.savedTo = recorder.path;
|
|
32
|
+
let server;
|
|
33
|
+
if (opts.flags.web) {
|
|
34
|
+
server = await startServer(session, opts.flags.port);
|
|
35
|
+
say(`Flow view in your browser: ${server.url}`);
|
|
36
|
+
if (opts.flags.open)
|
|
37
|
+
openBrowser(server.url);
|
|
38
|
+
if (opts.waitForBrowser && opts.flags.open)
|
|
39
|
+
await server.waitForClient(6000);
|
|
40
|
+
}
|
|
41
|
+
// The live flow panel, pinned below the command's own output.
|
|
42
|
+
const rowsListeners = new Set();
|
|
43
|
+
const panel =
|
|
44
|
+
// The panel needs to control the child's terminal size, which only node-pty allows.
|
|
45
|
+
opts.flags.panel && panelSupported() && (opts.mode !== 'live' || terminalMode() === 'pty')
|
|
46
|
+
? new LivePanel({ title: [opts.command[0].split('/').pop(), ...opts.command.slice(1)].join(' '), onRowsChange: (r) => rowsListeners.forEach((fn) => fn(r)) })
|
|
47
|
+
: undefined;
|
|
48
|
+
if (panel) {
|
|
49
|
+
panel.update(session.state);
|
|
50
|
+
session.subscribe((_e, state) => panel.update(state));
|
|
51
|
+
panel.start();
|
|
52
|
+
}
|
|
53
|
+
const term = {
|
|
54
|
+
write(chunk) {
|
|
55
|
+
process.stdout.write(chunk);
|
|
56
|
+
panel?.afterChildOutput(chunk);
|
|
57
|
+
},
|
|
58
|
+
rows: () => panel?.childRows ?? (process.stdout.rows || 30),
|
|
59
|
+
onRowsChange: (fn) => rowsListeners.add(fn),
|
|
60
|
+
};
|
|
61
|
+
let exit;
|
|
62
|
+
try {
|
|
63
|
+
exit = await opts.run(session, term);
|
|
64
|
+
}
|
|
65
|
+
finally {
|
|
66
|
+
panel?.stop();
|
|
67
|
+
}
|
|
68
|
+
session.end(exit.exitCode, exit.signal, exit.interrupted);
|
|
69
|
+
process.stderr.write(summary(session.state, session.logs, { cols: process.stderr.columns, s: err, webUrl: server?.url }));
|
|
70
|
+
if (session.state.fix && opts.flags.fix)
|
|
71
|
+
await startAgent(opts.flags.fix, session.state.fix.prompt, opts);
|
|
72
|
+
if (server) {
|
|
73
|
+
if (opts.flags.once) {
|
|
74
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
say(err.dim('Still serving the browser view. Press Ctrl+C to exit.'));
|
|
78
|
+
await new Promise((resolve) => {
|
|
79
|
+
process.stdin.pause();
|
|
80
|
+
process.once('SIGINT', () => resolve());
|
|
81
|
+
process.once('SIGTERM', () => resolve());
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
await server.close();
|
|
85
|
+
}
|
|
86
|
+
return exit.exitCode ?? (session.state.outcome === 'interrupted' ? 130 : 1);
|
|
87
|
+
}
|
|
88
|
+
/** Hands the terminal to a coding agent, started with the fix prompt, in the project folder. */
|
|
89
|
+
async function startAgent(agent, prompt, opts) {
|
|
90
|
+
if (opts.mode === 'demo') {
|
|
91
|
+
say(`--fix is ignored for demos: the demo project isn't on your machine. Use the command above in a real project.`);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
const bin = which(agent);
|
|
95
|
+
if (!bin) {
|
|
96
|
+
say(`Could not find "${agent}" on your PATH, so it wasn't started. The prompt is saved above.`);
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
say(`Starting ${agent === 'claude' ? 'Claude Code' : 'Codex'} with the fix prompt in ${opts.cwd}…\n`);
|
|
100
|
+
await new Promise((resolve) => {
|
|
101
|
+
const child = spawn(bin, [prompt], { cwd: opts.cwd, stdio: 'inherit' });
|
|
102
|
+
// Ctrl+C belongs to the agent while it runs.
|
|
103
|
+
const ignore = () => { };
|
|
104
|
+
process.on('SIGINT', ignore);
|
|
105
|
+
child.on('error', (e) => say(`Could not start ${agent}: ${e.message}`));
|
|
106
|
+
child.on('close', () => {
|
|
107
|
+
process.off('SIGINT', ignore);
|
|
108
|
+
resolve();
|
|
109
|
+
});
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
export function openBrowser(url) {
|
|
113
|
+
const [cmd, args] = process.platform === 'darwin' ? ['open', [url]] : process.platform === 'win32' ? ['cmd', ['/c', 'start', '', url]] : ['xdg-open', [url]];
|
|
114
|
+
try {
|
|
115
|
+
const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
|
|
116
|
+
child.on('error', () => say(`Open ${url} in your browser.`));
|
|
117
|
+
child.unref();
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
say(`Open ${url} in your browser.`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { readdirSync, statSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { readRun, runsDir } from '../core/store.js';
|
|
4
|
+
import { providers } from '../providers/index.js';
|
|
5
|
+
import { observe, say } from './observe.js';
|
|
6
|
+
/** Replays a run saved by `unfold vercel` (already-redacted events). */
|
|
7
|
+
export async function runReplay(file, flags, speed) {
|
|
8
|
+
const path = file ? ((await import('./show.js')).resolveRun(file) ?? file) : latestRun();
|
|
9
|
+
if (!path) {
|
|
10
|
+
say(`No saved runs in ${runsDir()}.`);
|
|
11
|
+
return 1;
|
|
12
|
+
}
|
|
13
|
+
const events = readRun(path);
|
|
14
|
+
const started = events.find((e) => e.type === 'run.started');
|
|
15
|
+
const ended = events.find((e) => e.type === 'run.ended');
|
|
16
|
+
const provider = started && providers[started.provider];
|
|
17
|
+
if (!started || !provider) {
|
|
18
|
+
say(`${path} is not an Unfold run file.`);
|
|
19
|
+
return 1;
|
|
20
|
+
}
|
|
21
|
+
say(`Replaying ${path}`);
|
|
22
|
+
return observe({
|
|
23
|
+
provider,
|
|
24
|
+
command: started.command,
|
|
25
|
+
cwd: started.cwd,
|
|
26
|
+
mode: 'replay',
|
|
27
|
+
flags,
|
|
28
|
+
save: false,
|
|
29
|
+
waitForBrowser: true,
|
|
30
|
+
run: async (session, term) => {
|
|
31
|
+
// Re-run the original lines through today's parser so parser fixes apply to old runs.
|
|
32
|
+
const t0 = started.at;
|
|
33
|
+
const start = Date.now();
|
|
34
|
+
for (const e of events) {
|
|
35
|
+
if (e.type !== 'log')
|
|
36
|
+
continue;
|
|
37
|
+
const wait = (e.line.at - t0) / speed - (Date.now() - start);
|
|
38
|
+
if (wait > 0)
|
|
39
|
+
await new Promise((r) => setTimeout(r, Math.min(wait, 2000)));
|
|
40
|
+
term.write(e.line.text + '\r\n');
|
|
41
|
+
session.write(e.line.text + '\n');
|
|
42
|
+
}
|
|
43
|
+
return { exitCode: ended?.exitCode ?? null, signal: ended?.signal ?? null, interrupted: ended?.interrupted ?? false };
|
|
44
|
+
},
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
export function listRuns() {
|
|
48
|
+
try {
|
|
49
|
+
const dir = runsDir();
|
|
50
|
+
return readdirSync(dir)
|
|
51
|
+
.filter((f) => f.endsWith('.jsonl'))
|
|
52
|
+
.map((f) => join(dir, f))
|
|
53
|
+
.sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return [];
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
function latestRun() {
|
|
60
|
+
return listRuns()[0];
|
|
61
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { launch, which } from '../core/launch.js';
|
|
2
|
+
import { redactArgs } from '../core/redact.js';
|
|
3
|
+
import { observe, say } from './observe.js';
|
|
4
|
+
export async function runLive(provider, userArgs, flags) {
|
|
5
|
+
const cwd = process.cwd();
|
|
6
|
+
const spec = provider.launch(userArgs);
|
|
7
|
+
const bin = which(spec.bin);
|
|
8
|
+
if (!bin) {
|
|
9
|
+
say(`Could not find "${spec.bin}" on your PATH. Install it first (for Vercel: npm i -g vercel), then run vercel login.`);
|
|
10
|
+
return 127;
|
|
11
|
+
}
|
|
12
|
+
for (const msg of provider.preflight?.(cwd) ?? [])
|
|
13
|
+
say(msg);
|
|
14
|
+
say(`Running: ${[spec.bin, ...redactArgs(spec.args)].join(' ')}`);
|
|
15
|
+
return observe({
|
|
16
|
+
provider,
|
|
17
|
+
command: [spec.bin, ...redactArgs(spec.args)],
|
|
18
|
+
cwd,
|
|
19
|
+
mode: 'live',
|
|
20
|
+
flags,
|
|
21
|
+
save: true,
|
|
22
|
+
run: (session, term) => launch({ bin, args: spec.args, cwd, term, onOutput: (d) => session.write(d) }),
|
|
23
|
+
});
|
|
24
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { FlowReducer } from '../core/flow.js';
|
|
4
|
+
import { readRun, runsDir } from '../core/store.js';
|
|
5
|
+
import { explore } from '../tui/explore.js';
|
|
6
|
+
import { style } from '../tui/ansi.js';
|
|
7
|
+
import { summary } from '../tui/render.js';
|
|
8
|
+
import { say } from './observe.js';
|
|
9
|
+
import { listRuns, runReplay } from './replay.js';
|
|
10
|
+
/** Resolves a run file from a path, a run id (or its prefix), or the latest run. */
|
|
11
|
+
export function resolveRun(ref) {
|
|
12
|
+
if (!ref)
|
|
13
|
+
return listRuns()[0];
|
|
14
|
+
if (existsSync(ref))
|
|
15
|
+
return ref;
|
|
16
|
+
const byId = join(runsDir(), ref.endsWith('.jsonl') ? ref : `${ref}.jsonl`);
|
|
17
|
+
if (existsSync(byId))
|
|
18
|
+
return byId;
|
|
19
|
+
return listRuns().find((p) => p.split('/').pop().startsWith(ref));
|
|
20
|
+
}
|
|
21
|
+
/** `unfold show`: explore a finished run in the terminal (or the browser with --web). */
|
|
22
|
+
export async function runShow(ref, flags) {
|
|
23
|
+
const path = resolveRun(ref);
|
|
24
|
+
if (!path) {
|
|
25
|
+
say(ref ? `No run matching "${ref}" in ${runsDir()}.` : `No saved runs yet in ${runsDir()}. Run \`unfold vercel\` or \`unfold demo\` first.`);
|
|
26
|
+
return 1;
|
|
27
|
+
}
|
|
28
|
+
if (flags.web)
|
|
29
|
+
return runReplay(path, { ...flags, panel: false }, 1e9);
|
|
30
|
+
const reducer = new FlowReducer();
|
|
31
|
+
for (const e of readRun(path))
|
|
32
|
+
reducer.apply(e);
|
|
33
|
+
const state = reducer.state;
|
|
34
|
+
if (!state) {
|
|
35
|
+
say(`${path} is not an Unfold run file.`);
|
|
36
|
+
return 1;
|
|
37
|
+
}
|
|
38
|
+
const logs = [...reducer.logs.values()];
|
|
39
|
+
if (process.stdout.isTTY && process.stdin.isTTY)
|
|
40
|
+
await explore(state, logs);
|
|
41
|
+
else
|
|
42
|
+
process.stdout.write(summary(state, logs, { s: style(false) }));
|
|
43
|
+
return 0;
|
|
44
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { homedir } from 'node:os';
|
|
2
|
+
export const AGENTS = ['claude', 'codex'];
|
|
3
|
+
const MAX_EXCERPT = 40;
|
|
4
|
+
const STAMP = /^\d{4}-\d{2}-\d{2}T[\d:.]+Z {0,2}/;
|
|
5
|
+
// path/to/file.ext:line[:col], as printed by compilers, bundlers and linters
|
|
6
|
+
const FILE_REF = /(?:^|[\s(])((?:\.{0,2}\/)?[\w@.-]+(?:\/[\w@.[\]-]+)*\.[A-Za-z]{1,5}):(\d+)(?::(\d+))?/g;
|
|
7
|
+
/** Most specific cause first, then by position in the output. */
|
|
8
|
+
export function rankCauses(state) {
|
|
9
|
+
const fatal = state.errors.find((e) => e.severity === 'fatal');
|
|
10
|
+
return state.errors
|
|
11
|
+
.filter((e) => e.severity === 'cause' && e.message !== fatal?.message)
|
|
12
|
+
.sort((a, b) => (b.priority ?? 1) - (a.priority ?? 1) || a.seq - b.seq);
|
|
13
|
+
}
|
|
14
|
+
function fileRefs(lines) {
|
|
15
|
+
const refs = new Set();
|
|
16
|
+
for (const line of lines) {
|
|
17
|
+
for (const m of line.replace(STAMP, '').matchAll(FILE_REF)) {
|
|
18
|
+
if (/^https?:/.test(m[1]) || m[1].includes('node_modules'))
|
|
19
|
+
continue;
|
|
20
|
+
refs.add(`${m[1]}:${m[2]}${m[3] ? `:${m[3]}` : ''}`);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return [...refs].slice(0, 8);
|
|
24
|
+
}
|
|
25
|
+
function excerpt(state, logs, anchor) {
|
|
26
|
+
const sorted = [...logs].sort((a, b) => a.seq - b.seq);
|
|
27
|
+
if (!sorted.length)
|
|
28
|
+
return { from: 0, to: 0, lines: [] };
|
|
29
|
+
const fatal = state.errors.find((e) => e.severity === 'fatal');
|
|
30
|
+
const end = fatal?.seq ?? sorted.at(-1).seq;
|
|
31
|
+
const start = anchor ? Math.max(anchor.seq - 12, end - MAX_EXCERPT + 1) : end - 30;
|
|
32
|
+
const lines = sorted.filter((l) => l.seq >= start && l.seq <= end).slice(-MAX_EXCERPT);
|
|
33
|
+
while (lines.length && lines[0].text.replace(STAMP, '').trim() === '')
|
|
34
|
+
lines.shift();
|
|
35
|
+
return { from: lines[0]?.seq ?? 0, to: lines.at(-1)?.seq ?? 0, lines };
|
|
36
|
+
}
|
|
37
|
+
const fence = (body) => '```\n' + body.replace(/```/g, '```') + '\n```';
|
|
38
|
+
/**
|
|
39
|
+
* Builds a prompt for a coding agent from a failed run. Uses only the already
|
|
40
|
+
* redacted log lines and parsed facts, so it contains nothing that isn't on the page.
|
|
41
|
+
*/
|
|
42
|
+
export function buildFixPrompt(state, logs, hints = []) {
|
|
43
|
+
if (state.outcome !== 'failure')
|
|
44
|
+
return undefined;
|
|
45
|
+
const stage = (id) => state.stages.find((s) => s.id === id)?.title;
|
|
46
|
+
const fatal = state.errors.find((e) => e.severity === 'fatal');
|
|
47
|
+
const causes = rankCauses(state);
|
|
48
|
+
const top = causes[0];
|
|
49
|
+
const ex = excerpt(state, logs, top);
|
|
50
|
+
const refs = fileRefs([...causes.map((c) => c.message), ...ex.lines.map((l) => l.text)]);
|
|
51
|
+
const facts = state.facts.filter((f) => !['inspectUrl', 'deploymentUrl', 'cliVersion', 'duration', 'region', 'machine'].includes(f.key));
|
|
52
|
+
const failedStage = stage(state.failedStage) ?? 'an unknown stage';
|
|
53
|
+
const out = [];
|
|
54
|
+
out.push(`# Fix a failed ${state.title.toLowerCase()}`, '');
|
|
55
|
+
out.push(`I ran \`${state.command.join(' ')}\` in \`${state.cwd}\` and it failed during the **${failedStage}** stage` +
|
|
56
|
+
(state.lastConfirmed ? `. The last stage that completed was **${stage(state.lastConfirmed)}**.` : ', before any stage completed.') +
|
|
57
|
+
` It exited with ${state.exitCode !== null ? `code ${state.exitCode}` : (state.exitSignal ?? 'an unknown status')}.`);
|
|
58
|
+
out.push('', '## Error', fence(fatal?.message ?? 'The command failed without printing a recognizable error. See the log excerpt.'));
|
|
59
|
+
if (causes.length) {
|
|
60
|
+
out.push('', '## Most relevant output', fence(causes.slice(0, 4).map((c) => c.message).join('\n')));
|
|
61
|
+
}
|
|
62
|
+
if (ex.lines.length) {
|
|
63
|
+
out.push('', `## Log excerpt (lines ${ex.from}–${ex.to})`, fence(ex.lines.map((l) => l.text.replace(STAMP, '')).join('\n')));
|
|
64
|
+
}
|
|
65
|
+
const context = [
|
|
66
|
+
...facts.map((f) => `- ${f.label}: ${f.value}`),
|
|
67
|
+
...(refs.length ? [`- Files mentioned in the output: ${refs.map((r) => `\`${r}\``).join(', ')}`] : []),
|
|
68
|
+
];
|
|
69
|
+
if (context.length)
|
|
70
|
+
out.push('', '## Context', ...context);
|
|
71
|
+
if (hints.length)
|
|
72
|
+
out.push('', '## Things to know about this failure', ...hints.map((h) => `- ${h}`));
|
|
73
|
+
out.push('', '## What I want', `1. Find the root cause in this repository${refs.length ? ', starting with the files mentioned above' : ''}.`, '2. Make the smallest change that fixes it, then reproduce the failing step locally to confirm the fix.', "3. Don't deploy, and don't change hosting settings or environment variables. If the fix needs that, tell me exactly what to change instead.", '4. Summarize what was wrong and what you changed.', '', 'Values shown as [REDACTED] were removed on purpose; don\'t try to recover them.');
|
|
74
|
+
return out.join('\n') + '\n';
|
|
75
|
+
}
|
|
76
|
+
const shQuote = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
|
|
77
|
+
/** One-line shell commands that start each agent with the saved prompt. */
|
|
78
|
+
export function agentCommands(promptPath, home = homedir()) {
|
|
79
|
+
// `~/…` is shorter to read and copy; only used when no quoting is needed.
|
|
80
|
+
const safe = /^[\w./-]+$/;
|
|
81
|
+
const rest = promptPath.startsWith(home + '/') ? promptPath.slice(home.length) : undefined;
|
|
82
|
+
const ref = rest && safe.test(home) && safe.test(rest) ? `~${rest}` : shQuote(promptPath);
|
|
83
|
+
const arg = `"$(cat ${ref})"`;
|
|
84
|
+
return { claude: `claude ${arg}`, codex: `codex ${arg}` };
|
|
85
|
+
}
|