zcode-agent 0.0.0-stage → 1.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/lib/ui.js ADDED
@@ -0,0 +1,249 @@
1
+ 'use strict';
2
+ // Plain-mode terminal UI. stdout carries the RESULT (the answer for run,
3
+ // the handback summary for task); stderr carries the live feed. Nothing
4
+ // here writes ANSI unless stderr/stdout is a TTY and NO_COLOR / TERM=dumb
5
+ // are unset, and nothing animates — the feed is append-only lines, so a
6
+ // non-interactive log reads exactly like the terminal did.
7
+ //
8
+ // ▸ zcode zc-1a2b3c4d task GLM-5.3-Flash · effort max session header
9
+ // ● executing phase
10
+ // → Edit · ✓ Edit · ✗ Bash tools (dim)
11
+ // ⇢ subagent started / returned subagents
12
+ // ✓ npm test 3.2s · ✗ npm run lint exit 1 1.1s checks
13
+ // │ thinking … reasoning (opt-in)
14
+
15
+ const { questionText } = require('./contract.js');
16
+
17
+ function useColor(stream, env = process.env) {
18
+ return Boolean(stream && stream.isTTY) && !('NO_COLOR' in env) && env.TERM !== 'dumb';
19
+ }
20
+
21
+ function painter(enabled) {
22
+ const wrap = (code) => (t) => (enabled ? `\x1b[${code}m${t}\x1b[0m` : String(t));
23
+ return { dim: wrap(2), bold: wrap(1), red: wrap(31), green: wrap(32), yellow: wrap(33), cyan: wrap(36) };
24
+ }
25
+
26
+ const secs = (ms) => `${(ms / 1000).toFixed(1)}s`;
27
+
28
+ function makeReporter({ quiet = false, thinking = true, stream = process.stderr, env = process.env } = {}) {
29
+ const c = painter(useColor(stream, env));
30
+ const out = (s) => {
31
+ if (!quiet) stream.write(s);
32
+ };
33
+ let thinkingOpen = false;
34
+ let atLineStart = true;
35
+
36
+ const closeThinking = () => {
37
+ if (thinkingOpen) {
38
+ thinkingOpen = false;
39
+ if (!atLineStart) out('\n');
40
+ atLineStart = true;
41
+ }
42
+ };
43
+
44
+ // One write per delta (not per character): prefix each new line with the
45
+ // quote bar, dim the whole chunk once.
46
+ const writeThinking = (delta) => {
47
+ thinkingOpen = true;
48
+ let text = '';
49
+ for (const line of delta.split(/(\n)/)) {
50
+ if (line === '\n') {
51
+ text += '\n';
52
+ atLineStart = true;
53
+ } else if (line) {
54
+ text += (atLineStart ? '│ ' : '') + line;
55
+ atLineStart = false;
56
+ }
57
+ }
58
+ out(c.dim(text));
59
+ };
60
+
61
+ const line = (s) => {
62
+ closeThinking();
63
+ out(`${s}\n`);
64
+ };
65
+
66
+ const onEvent = (ev) => {
67
+ if (quiet) return;
68
+ switch (ev.type) {
69
+ case 'stream':
70
+ if (ev.kind === 'reasoning_delta' && ev.delta && thinking) writeThinking(ev.delta);
71
+ return;
72
+ case 'session': {
73
+ const head = `${c.bold('▸ zcode')} ${c.cyan(ev.id)} ${ev.kind}${ev.resumed ? ' (resumed)' : ''} ${c.dim(`${ev.model} · effort ${ev.effort}`)}`;
74
+ const scope = [
75
+ ` cwd ${ev.cwd}`,
76
+ ev.owns && ev.owns.length ? `owns ${ev.owns.join(', ')}` : null,
77
+ ev.checks && ev.checks.length ? `${ev.checks.length} check${ev.checks.length === 1 ? '' : 's'}` : null,
78
+ ].filter(Boolean);
79
+ line(head);
80
+ line(c.dim(scope.join(' · ')));
81
+ return;
82
+ }
83
+ case 'phase': {
84
+ const extra =
85
+ ev.phase === 'repairing' ? ` ${ev.attempt}/${ev.of}`
86
+ : ev.phase === 'checking' ? ` ${ev.count}`
87
+ : ev.phase === 'verifying' ? ` round ${ev.round}`
88
+ : ev.reason ? ` (${ev.reason})` : '';
89
+ line(`${c.cyan('●')} ${ev.phase}${extra}`);
90
+ return;
91
+ }
92
+ case 'tool':
93
+ if (ev.phase === 'started' && ev.name) line(c.dim(` → ${ev.name}`));
94
+ else if (ev.phase === 'error' && ev.name) line(c.dim(` ✗ ${ev.name} error`));
95
+ return;
96
+ case 'subagent':
97
+ line(c.dim(` ⇢ subagent ${ev.phase}`));
98
+ return;
99
+ case 'check':
100
+ if (ev.phase !== 'finished') return;
101
+ if (ev.ok) line(` ${c.green('✓')} ${ev.command} ${c.dim(secs(ev.durationMs))}`);
102
+ else line(` ${c.red('✗')} ${ev.command} ${c.dim(`${ev.timedOut ? 'timed out' : `exit ${ev.exitCode}`} ${secs(ev.durationMs)}`)}`);
103
+ return;
104
+ case 'mcp':
105
+ if (ev.status === 'connected') line(c.dim(` ◇ mcp ${ev.name} connected`));
106
+ else if (ev.status === 'failed' || ev.status === 'timeout') {
107
+ line(c.dim(` ✗ mcp ${ev.name} ${ev.status}${ev.error ? ` (${ev.error})` : ''}`));
108
+ }
109
+ return;
110
+ case 'retry':
111
+ line(c.yellow(` ↻ retrying ${ev.phase}: ${ev.reason}`));
112
+ return;
113
+ default:
114
+ }
115
+ };
116
+
117
+ // run-mode footer: one dim status line after the answer.
118
+ const footer = (r) => {
119
+ if (quiet) return;
120
+ closeThinking();
121
+ const parts = [
122
+ r.model,
123
+ `effort ${r.effort}`,
124
+ typeof r.toolCalls === 'number' ? `${r.toolCalls} tool call${r.toolCalls === 1 ? '' : 's'}` : null,
125
+ secs(r.durationMs),
126
+ r.id,
127
+ ].filter(Boolean);
128
+ out(c.dim(` ${parts.join(' · ')}\n`));
129
+ };
130
+
131
+ return { onEvent, closeThinking, footer };
132
+ }
133
+
134
+ const STATUS_MARK = {
135
+ completed: '✓',
136
+ unverified: '?',
137
+ partial: '◐',
138
+ blocked: '■',
139
+ failed: '✗',
140
+ cancelled: '■',
141
+ };
142
+
143
+ function statusColor(c, status) {
144
+ if (status === 'completed') return c.green;
145
+ if (status === 'failed') return c.red;
146
+ return c.yellow;
147
+ }
148
+
149
+ // The handback as a human reads it (task results, wait, resume). Ordered by
150
+ // what an orchestrator scans for: status, what changed, what was checked,
151
+ // what is wrong, how to continue.
152
+ function formatResult(r, { color = false } = {}) {
153
+ const c = painter(color);
154
+ const L = [];
155
+ const st = statusColor(c, r.status);
156
+ L.push(`${st(`${STATUS_MARK[r.status] || '•'} ${r.status}`)} ${c.bold(r.id)}${r.label ? ` ${r.label}` : ''} ${c.dim(secs(r.durationMs || 0))}`);
157
+ if (r.summary) L.push(` ${r.summary}`);
158
+ const files = (r.changes && r.changes.files) || [];
159
+ if (files.length) {
160
+ L.push(`changed ${files.length} file${files.length === 1 ? '' : 's'}`);
161
+ for (const f of files.slice(0, 30)) {
162
+ const mark = f.change === 'added' ? 'A' : f.change === 'deleted' ? 'D' : 'M';
163
+ const note = f.touched ? c.dim(' (touched)') : f.concurrentSession ? c.dim(` (session ${f.concurrentSession})`) : !f.owned ? c.red(' outside owned scope') : '';
164
+ L.push(` ${mark} ${f.path}${note}`);
165
+ }
166
+ if (files.length > 30) L.push(c.dim(` … ${files.length - 30} more`));
167
+ } else if (r.changes) {
168
+ L.push(`changed ${r.changes.tracking === 'unavailable' ? 'not tracked' : 'nothing'}`);
169
+ }
170
+ if (r.checks && r.checks.length) {
171
+ const passed = r.checks.filter((x) => x.ok).length;
172
+ L.push(`checks ${passed}/${r.checks.length} passed${r.repairs ? ` · ${r.repairs} repair turn${r.repairs === 1 ? '' : 's'}` : ''}`);
173
+ for (const x of r.checks) {
174
+ L.push(` ${x.ok ? c.green('✓') : c.red('✗')} ${x.command}${x.ok ? '' : c.dim(` ${x.timedOut ? 'timed out' : `exit ${x.exitCode}`}`)}`);
175
+ }
176
+ } else if (r.kind === 'task') {
177
+ L.push('checks none declared');
178
+ }
179
+ if (r.subagents && r.subagents.length) {
180
+ L.push(`subagents ${r.subagents.length}`);
181
+ for (const s of r.subagents) {
182
+ L.push(c.dim(` ${s.status === 'success' ? '✓' : '✗'} ${s.profileId || 'agent'}${s.title ? ` ${s.title}` : ''}${typeof s.durationMs === 'number' ? ` ${secs(s.durationMs)}` : ''}`));
183
+ }
184
+ }
185
+ for (const [label, items] of [
186
+ ['issues', r.issues],
187
+ ['questions', (r.questions || []).map(questionText)],
188
+ ['decisions', (r.decisions || []).map((d) => `${d.what}${d.why ? ` (${d.why})` : ''}`)],
189
+ ['units', (r.units || []).map((u) => `${u.name}: ${u.status || '?'}${u.note ? ` - ${u.note}` : ''}`)],
190
+ ['visual', (r.visual || []).map((v) => `${v.met === true ? 'met' : v.met === null ? 'NOT VERIFIED' : 'UNMET'} ${v.criterion || ''}${v.viewport ? ` @${v.viewport}` : ''}${v.note ? ` - ${v.note}` : ''}`)],
191
+ ['unresolved', r.unresolved],
192
+ ['not verified', r.notVerified],
193
+ ]) {
194
+ if (items && items.length) {
195
+ L.push(`${label}`);
196
+ for (const i of items) L.push(` - ${i}`);
197
+ }
198
+ }
199
+ if (r.error && r.error.message && !(r.issues || []).includes(r.error.message)) {
200
+ L.push(`error ${r.error.kind}: ${r.error.message.split('\n')[0]}`);
201
+ }
202
+ if (r.status !== 'completed' && r.status !== 'cancelled') {
203
+ L.push(c.dim(`next zcode-agent resume ${r.id} "<message>"`));
204
+ }
205
+ return L.join('\n') + '\n';
206
+ }
207
+
208
+ // One line per session for `zcode status` without an id.
209
+ function formatSessionRow(s) {
210
+ const when = s.updatedAt ? s.updatedAt.replace('T', ' ').slice(0, 19) : '';
211
+ const state = s.state === 'finished' ? s.status || 'finished' : s.state;
212
+ return `${s.id.padEnd(18)} ${String(state).padEnd(11)} ${String(s.kind || '').padEnd(5)} ${when} ${s.label || s.cwd || ''}`;
213
+ }
214
+
215
+ // `repairing 1/2`, `verifying round 2`, or the bare phase.
216
+ function phaseText(v) {
217
+ const d = v.phaseDetail;
218
+ if (d && d.attempt !== undefined) return `${v.phase} ${d.attempt}/${d.of}`;
219
+ if (d && d.round !== undefined) return `${v.phase} round ${d.round}`;
220
+ return v.phase;
221
+ }
222
+
223
+ function formatSessionView(v, { events = [] } = {}) {
224
+ const L = [];
225
+ const state = v.state === 'finished' ? `finished (${v.status})` : v.state;
226
+ L.push(`${v.id} ${v.kind}${v.label ? ` ${v.label}` : ''}`);
227
+ L.push(` state ${state}${v.live ? ` · phase ${phaseText(v)} · pid ${v.pid}` : ''}`);
228
+ L.push(` cwd ${v.cwd}`);
229
+ if (v.owns && v.owns.length) L.push(` owns ${v.owns.join(', ')}`);
230
+ L.push(` model ${v.model} · effort ${v.effort} · turns ${v.turns || 0}`);
231
+ if (v.activity) {
232
+ L.push(` activity ${v.activity.toolCalls || 0} tool calls · ${v.activity.subagentsStarted || 0} subagents${v.activity.lastTool ? ` · last ${v.activity.lastTool}` : ''} · ${v.activity.lastEventAt || ''}`);
233
+ }
234
+ if (v.idleMs !== undefined) L.push(` idle ${Math.round(v.idleMs / 1000)}s since the last engine event${v.stalled ? ' STALLED?' : ''}`);
235
+ if (v.state === 'interrupted') L.push(` the owning process is gone; continue with: zcode-agent resume ${v.id}`);
236
+ if (events.length) {
237
+ L.push(' recent');
238
+ for (const e of events) {
239
+ const what = e.type === 'phase' ? `● ${e.phase}`
240
+ : e.type === 'tool' ? `${e.phase} ${e.name}`
241
+ : e.type === 'check' ? `check ${e.command}${e.phase === 'finished' ? (e.ok ? ' ok' : ' failed') : ''}`
242
+ : e.type;
243
+ L.push(` ${String(e.t || '').slice(11, 19)} ${what}`);
244
+ }
245
+ }
246
+ return L.join('\n') + '\n';
247
+ }
248
+
249
+ module.exports = { phaseText, makeReporter, formatResult, formatSessionRow, formatSessionView, useColor };
package/lib/verify.js ADDED
@@ -0,0 +1,100 @@
1
+ 'use strict';
2
+ // The independent visual verifier (v0.6). The implementer never decides
3
+ // `visual`: after its turn zcode opens a fresh engine session on an
4
+ // image-capable model that did not build the result, has it screenshot the
5
+ // running app and LOOK at the pixels, and parses its `zcode-visual` block.
6
+ // This file is the prompt and the (lenient) parser; the orchestration is in
7
+ // lib/executor.js.
8
+ const { DEFAULT_VIEWPORTS } = require('./contract.js');
9
+
10
+ // Always judged in addition to the declared criteria.
11
+ const BUILTIN_CRITERION =
12
+ 'All text the page means to show is readable after animations finish: not clipped, hidden, transparent, off-screen or overlapped.';
13
+
14
+ const bullets = (items) => items.map((i) => `- ${i}`).join('\n');
15
+
16
+ const clip = (text, max) => {
17
+ const s = String(text ?? '').replace(/\s+/g, ' ').trim();
18
+ return s.length <= max ? s : `${s.slice(0, max - 1)}…`;
19
+ };
20
+
21
+ const WAIT_SCRIPT =
22
+ 'await document.fonts.ready; await Promise.all(document.getAnimations().map(a => a.finished.catch(() => {})))';
23
+
24
+ // contract: the task contract; session: {id, port, out, tmp}; round: 1-based.
25
+ function buildVerifierPrompt(contract, { session, round = 1 }) {
26
+ const viewports = contract.viewports && contract.viewports.length ? contract.viewports : DEFAULT_VIEWPORTS;
27
+ const dir = `${session.out}/verify/${round}`;
28
+ return [
29
+ 'You are an independent visual verifier. You did not build this and have not seen it. Assume it is broken until the pixels prove otherwise. DOM or text presence is NOT evidence: only what you can see in a screenshot counts.',
30
+ '',
31
+ `## What was built\n${clip(contract.objective, 500)}`,
32
+ '',
33
+ '## Criteria',
34
+ bullets([...contract.visual, BUILTIN_CRITERION]),
35
+ '',
36
+ '## How (be fast: few, batched tool calls)',
37
+ '- Use only Bash and the Playwright MCP tools. Do not load skills or other browser tools; everything you need is here.',
38
+ contract.serve
39
+ ? `- Serve the app with \`${contract.serve}\` on $ZCODE_PORT=${session.port} in the background (build first if it needs one; put build output under $ZCODE_OUT=${session.out}, not in the workspace).`
40
+ : `- Serve the app on $ZCODE_PORT=${session.port} in the background (pick the dev/preview command from package.json, build first if needed; put build output under $ZCODE_OUT=${session.out}, not in the workspace).`,
41
+ `- Capture EVERYTHING in ONE Playwright run-code call (browser_run_code_unsafe or browser_run_code), not one tool call per step. For each viewport (${viewports.join(', ')}): set the viewport, goto the page, \`${WAIT_SCRIPT}\` (race it against an 8 s timer), wait 500 ms; then scroll down one window height at a time to the bottom of the page (steps = ceil(scrollHeight / innerHeight), re-read after each scroll), waiting 400 ms and the same animation wait at each, saving a viewport screenshot per step to ${dir}/<viewport>-<n>.png (n from 1 at the top); also drive every state a criterion names (open a dialog, fill a step, …) and save ${dir}/<viewport>-<state>.png. Return the list of paths.`,
42
+ '- Then LOOK at the images: read every PNG in ONE batch of parallel Read calls. Judge every criterion at every viewport. For each verdict QUOTE the text you can actually read in the relevant region (`seen`); if you read none, say so.',
43
+ '- Only when a region is genuinely unclear, take a targeted extra screenshot (an element or a clip) and read it; do not re-capture everything.',
44
+ `- Make NO edits: write only files under ${session.out}. Stop any server you started.`,
45
+ '',
46
+ '## Reply',
47
+ 'End with exactly one fenced block, a JSON array with one entry per criterion per viewport:',
48
+ '```zcode-visual',
49
+ '[{"criterion": "text of the criterion", "viewport": "1440x900", "met": true, "seen": "text you read there", "note": "what is wrong, if anything", "shot": "path of the screenshot"}]',
50
+ '```',
51
+ ].join('\n');
52
+ }
53
+
54
+ const BLOCK_RE = /```zcode-visual[^\n]*\n([\s\S]*?)```/g;
55
+
56
+ function normMet(v) {
57
+ if (v === true || v === false) return v;
58
+ if (typeof v === 'string') {
59
+ const t = v.trim().toLowerCase();
60
+ if (['true', 'yes', 'met', 'pass'].includes(t)) return true;
61
+ if (['false', 'no', 'unmet', 'not met', 'fail'].includes(t)) return false;
62
+ }
63
+ return null;
64
+ }
65
+
66
+ // {entries: [{criterion, viewport?, met: true|false|null, seen, note, shot}],
67
+ // error}. The LAST block wins; an unparsable or empty block is an error.
68
+ function parseVisualBlock(text) {
69
+ const matches = [...String(text || '').matchAll(BLOCK_RE)];
70
+ if (!matches.length) return { entries: [], error: 'no zcode-visual block' };
71
+ let raw;
72
+ try {
73
+ raw = JSON.parse(matches[matches.length - 1][1]);
74
+ } catch (err) {
75
+ return { entries: [], error: `invalid JSON: ${err.message}` };
76
+ }
77
+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
78
+ raw = Array.isArray(raw.visual) ? raw.visual : Array.isArray(raw.entries) ? raw.entries : [raw];
79
+ }
80
+ if (!Array.isArray(raw)) return { entries: [], error: 'not a JSON array' };
81
+ const entries = raw
82
+ .filter((e) => e && typeof e === 'object' && !Array.isArray(e) && e.criterion !== undefined)
83
+ .map((e) => ({
84
+ criterion: String(e.criterion),
85
+ ...(e.viewport ? { viewport: String(e.viewport) } : {}),
86
+ met: normMet(e.met),
87
+ seen: e.seen === undefined || e.seen === null ? '' : String(e.seen),
88
+ note: e.note === undefined || e.note === null ? '' : String(e.note),
89
+ ...(e.shot ? { shot: String(e.shot) } : {}),
90
+ }));
91
+ return entries.length ? { entries, error: null } : { entries: [], error: 'no usable entries' };
92
+ }
93
+
94
+ // Entries for criteria that could not be judged: met:null, never met:false
95
+ // (a verifier failure is not the implementer's fault).
96
+ function notVerified(criteria, why) {
97
+ return criteria.map((criterion) => ({ criterion, met: null, seen: '', note: `not verified: ${why}` }));
98
+ }
99
+
100
+ module.exports = { buildVerifierPrompt, parseVisualBlock, notVerified, BUILTIN_CRITERION };