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/LICENSE +21 -0
- package/README.md +468 -2
- package/assets/acp-agents.md +11 -0
- package/assets/executor-agents.md +10 -0
- package/bin/zcode-agent-acp.js +11 -0
- package/bin/zcode-agent.js +442 -0
- package/lib/acp-map.js +543 -0
- package/lib/acp.js +763 -0
- package/lib/appserver.js +546 -0
- package/lib/bootstrap.js +71 -0
- package/lib/brief.js +109 -0
- package/lib/checks.js +104 -0
- package/lib/commands/acp.js +35 -0
- package/lib/commands/cost.js +67 -0
- package/lib/commands/doctor.js +179 -0
- package/lib/commands/exec.js +394 -0
- package/lib/commands/login.js +44 -0
- package/lib/commands/mcp-list.js +12 -0
- package/lib/commands/plan.js +302 -0
- package/lib/commands/sessions.js +333 -0
- package/lib/commands/skills.js +47 -0
- package/lib/contract.js +530 -0
- package/lib/cost.js +278 -0
- package/lib/engine.js +212 -0
- package/lib/executor.js +914 -0
- package/lib/help.js +143 -0
- package/lib/isolation.js +625 -0
- package/lib/key.js +81 -0
- package/lib/models.js +179 -0
- package/lib/plan.js +459 -0
- package/lib/ports.js +45 -0
- package/lib/skills.js +92 -0
- package/lib/store.js +340 -0
- package/lib/taskspec.js +114 -0
- package/lib/ui.js +249 -0
- package/lib/verify.js +100 -0
- package/lib/workspace.js +383 -0
- package/package.json +57 -4
- package/skills/README.md +40 -0
- package/skills/claude-code/zcode-agent/SKILL.md +169 -0
- package/skills/codex/zcode-agent/SKILL.md +169 -0
- package/skills/codex/zcode-agent/agents/openai.yaml +4 -0
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// lib/commands/plan.js — plan check|run|wait|status|resume, and __plan (the
|
|
3
|
+
// detached supervisor). Logic lives in lib/plan.js.
|
|
4
|
+
//
|
|
5
|
+
// Output contract: JSON mode prints exactly one line per call (plan check:
|
|
6
|
+
// {type:"plan-check"}; run/wait/status/resume: {type:"plan",name,status,
|
|
7
|
+
// sessions:[{id,status}],briefs:[…]}; a timeout or --detach: the same
|
|
8
|
+
// without briefs). `plan run --preflight` prints one brief per session with
|
|
9
|
+
// questions. Exit codes: 0 completed · 10 blocked · 8 partial/failed ·
|
|
10
|
+
// 124 timeout · 2 usage · 7 plan exists.
|
|
11
|
+
const store = require('../store.js');
|
|
12
|
+
const plans = require('../plan.js');
|
|
13
|
+
const { buildBrief } = require('../brief.js');
|
|
14
|
+
const { exitCodeFor } = require('../executor.js');
|
|
15
|
+
const { questionText } = require('../contract.js');
|
|
16
|
+
const { formatResult, useColor } = require('../ui.js');
|
|
17
|
+
|
|
18
|
+
const out = (line) => process.stdout.write(line + '\n');
|
|
19
|
+
|
|
20
|
+
function die(code, message) {
|
|
21
|
+
process.stderr.write(`zcode-agent: ${message}\n`);
|
|
22
|
+
process.exit(code);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function load(file, parsed) {
|
|
26
|
+
if (!file) die(2, 'plan needs a plan file.');
|
|
27
|
+
try {
|
|
28
|
+
return plans.resolvePlan(file, parsed.given.has('cwd') ? parsed.flags.cwd : undefined);
|
|
29
|
+
} catch (err) {
|
|
30
|
+
if (err instanceof plans.PlanError) return die(2, err.message);
|
|
31
|
+
throw err;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function nameOf(parsed, file) {
|
|
36
|
+
try {
|
|
37
|
+
return plans.planName(parsed.flags.id, file);
|
|
38
|
+
} catch (err) {
|
|
39
|
+
if (err instanceof plans.PlanError) return die(2, err.message);
|
|
40
|
+
throw err;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// A plan by name (state + its plan file), or exit 2.
|
|
45
|
+
function open(name) {
|
|
46
|
+
const state = store.readPlanState(name);
|
|
47
|
+
if (!state) die(2, `no plan "${name}" (zcode-agent plan run <file> starts one).`);
|
|
48
|
+
try {
|
|
49
|
+
return { state, r: plans.resolvePlan(state.file, state.cwd) };
|
|
50
|
+
} catch (err) {
|
|
51
|
+
if (err instanceof plans.PlanError) return die(2, err.message);
|
|
52
|
+
throw err;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function problemsOrExit(problems, json) {
|
|
57
|
+
if (!problems.length) return;
|
|
58
|
+
if (json) out(JSON.stringify({ type: 'plan-check', ok: false, problems }));
|
|
59
|
+
for (const p of problems) process.stderr.write(`zcode-agent: ${p}\n`);
|
|
60
|
+
process.exit(2);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// One line per session; a non-completed session adds its one-line summary,
|
|
64
|
+
// a blocked one its questions.
|
|
65
|
+
function humanReport(report) {
|
|
66
|
+
const brief = new Map((report.briefs || []).map((b) => [b.id, b]));
|
|
67
|
+
const lines = [];
|
|
68
|
+
for (const s of report.sessions) {
|
|
69
|
+
const b = brief.get(s.id);
|
|
70
|
+
const note = b && (b.summary || (b.error && b.error.message) || '');
|
|
71
|
+
lines.push(`${s.id} ${s.status}${note ? ` - ${note.replace(/\s+/g, ' ').slice(0, 120)}` : ''}`);
|
|
72
|
+
if (b && b.questions) for (const q of b.questions) lines.push(` ? ${questionText(q).replace(/\n/g, '\n ')}`);
|
|
73
|
+
}
|
|
74
|
+
return lines.join('\n');
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function print(report, flags) {
|
|
78
|
+
if (flags.json) out(JSON.stringify(report));
|
|
79
|
+
else {
|
|
80
|
+
process.stderr.write(`plan ${report.name}: ${report.status}\n`);
|
|
81
|
+
out(humanReport(report));
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const reportOf = (name) => {
|
|
86
|
+
const { state, r } = open(name);
|
|
87
|
+
return plans.planReport(name, r, state);
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
function finish(report, flags) {
|
|
91
|
+
print(report, flags);
|
|
92
|
+
process.exit(plans.exitCodeForPlan(report.status));
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Timeout / detach summary: statuses only.
|
|
96
|
+
function brief(name, flags, status) {
|
|
97
|
+
const { state, r } = open(name);
|
|
98
|
+
const report = plans.planReport(name, r, state, { briefs: false });
|
|
99
|
+
if (status) report.status = status;
|
|
100
|
+
if (flags.json) return print(report, flags);
|
|
101
|
+
// Human mode: the whole timeout/detach summary is one stdout line.
|
|
102
|
+
out(`plan ${report.name}: ${report.status} (${report.sessions.map((s) => `${s.id} ${s.status}${s.stalled ? ` idle ${Math.round(s.idleMs / 60000)}m STALLED?` : ''}`).join(', ')})`);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Supervises in-process until the plan settles (or the deadline). On a
|
|
106
|
+
// deadline the supervision is handed to a detached supervisor so the plan
|
|
107
|
+
// keeps going.
|
|
108
|
+
async function superviseAndReport(name, flags, given) {
|
|
109
|
+
const deadline = given.has('timeoutMs') ? Date.now() + flags.timeoutMs : Infinity;
|
|
110
|
+
const res = await plans.supervise(name, { deadline });
|
|
111
|
+
if (res.timedOut) {
|
|
112
|
+
plans.startSupervisor(name);
|
|
113
|
+
brief(name, flags, 'running');
|
|
114
|
+
process.exit(124);
|
|
115
|
+
}
|
|
116
|
+
if (res.busy) {
|
|
117
|
+
// Another supervisor already drives it: just wait for it.
|
|
118
|
+
return waitFor(name, flags, given);
|
|
119
|
+
}
|
|
120
|
+
return finish(reportOf(name), flags);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function waitFor(name, flags, given) {
|
|
124
|
+
const deadline = given.has('timeoutMs') ? Date.now() + flags.timeoutMs : Infinity;
|
|
125
|
+
for (;;) {
|
|
126
|
+
const report = reportOf(name);
|
|
127
|
+
if (report.status !== 'running') return finish(report, flags);
|
|
128
|
+
if (Date.now() >= deadline) {
|
|
129
|
+
brief(name, flags, 'running');
|
|
130
|
+
process.exit(124);
|
|
131
|
+
}
|
|
132
|
+
await plans.sleep(plans.POLL_MS);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async function check(parsed, file) {
|
|
137
|
+
const r = load(file, parsed);
|
|
138
|
+
const name = nameOf(parsed, file);
|
|
139
|
+
const problems = plans.checkPlan(r, { name, state: store.readPlanState(name) });
|
|
140
|
+
problemsOrExit(problems, parsed.flags.json);
|
|
141
|
+
const n = plans.sessionList(r.plan).length;
|
|
142
|
+
if (parsed.flags.json) out(JSON.stringify({ type: 'plan-check', ok: true, name, sessions: n }));
|
|
143
|
+
else out(`plan ${name}: ${n} session${n === 1 ? '' : 's'}, ok`);
|
|
144
|
+
process.exit(0);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function run(parsed, file) {
|
|
148
|
+
const { flags, given } = parsed;
|
|
149
|
+
const r = load(file, parsed);
|
|
150
|
+
const name = nameOf(parsed, file);
|
|
151
|
+
const state = store.readPlanState(name);
|
|
152
|
+
if (flags.preflight) return preflight(parsed, r, name, state);
|
|
153
|
+
if (state) {
|
|
154
|
+
die(7, `plan "${name}" already exists. Continue it with "zcode-agent plan resume ${name}" (status: "zcode-agent plan status ${name}"), or run again with another --id.`);
|
|
155
|
+
}
|
|
156
|
+
problemsOrExit(plans.checkPlan(r, { name }), flags.json);
|
|
157
|
+
const ok = store.createPlanState(name, {
|
|
158
|
+
file: r.file,
|
|
159
|
+
cwd: r.cwd,
|
|
160
|
+
sessions: plans.sessionList(r.plan).map((s) => s.id),
|
|
161
|
+
supervisor: null,
|
|
162
|
+
launchErrors: {},
|
|
163
|
+
});
|
|
164
|
+
if (!ok) die(7, `plan "${name}" already exists. Continue it with "zcode-agent plan resume ${name}".`);
|
|
165
|
+
return startSupervision(name, flags, given);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async function startSupervision(name, flags, given) {
|
|
169
|
+
if (flags.detach) {
|
|
170
|
+
plans.startSupervisor(name);
|
|
171
|
+
out(JSON.stringify({ type: 'plan', name, status: 'running' }));
|
|
172
|
+
process.exit(0);
|
|
173
|
+
}
|
|
174
|
+
return superviseAndReport(name, flags, given);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Preflight every session (read-only, in parallel, as "<id>.pre"), wait for
|
|
178
|
+
// all, print one brief per session that has questions. Creates no plan state.
|
|
179
|
+
async function preflight(parsed, r, name, state) {
|
|
180
|
+
const { flags, given } = parsed;
|
|
181
|
+
problemsOrExit(plans.checkPlan(r, { name, state }), flags.json);
|
|
182
|
+
const sessions = plans.sessionList(r.plan);
|
|
183
|
+
const e = require('./exec.js');
|
|
184
|
+
const ids = [];
|
|
185
|
+
const failed = [];
|
|
186
|
+
for (const s of sessions) {
|
|
187
|
+
const pre = `${s.id}.pre`;
|
|
188
|
+
const old = store.readSession(pre);
|
|
189
|
+
if (old) {
|
|
190
|
+
if (store.viewSession(old).live) die(7, `preflight session "${pre}" is still running; cancel it first (zcode-agent cancel ${pre}).`);
|
|
191
|
+
store.deleteSession(pre);
|
|
192
|
+
}
|
|
193
|
+
try {
|
|
194
|
+
e.startDetached(plans.sessionInvocation(r, name, s, { id: pre, preflight: true }));
|
|
195
|
+
ids.push(pre);
|
|
196
|
+
} catch (err) {
|
|
197
|
+
if (err instanceof e.UsageError || err.exitCode || err instanceof store.SessionExistsError) {
|
|
198
|
+
failed.push(plans.launchFailure(pre, err.message));
|
|
199
|
+
} else throw err;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
const { finalResult } = require('./sessions.js');
|
|
203
|
+
const deadline = Date.now() + (given.has('timeoutMs') ? flags.timeoutMs : 600000);
|
|
204
|
+
const pending = new Set(ids);
|
|
205
|
+
const results = [...failed];
|
|
206
|
+
for (;;) {
|
|
207
|
+
for (const id of [...pending]) {
|
|
208
|
+
const view = store.viewSession(store.readSession(id));
|
|
209
|
+
if (view.state === 'finished' || view.state === 'interrupted') {
|
|
210
|
+
pending.delete(id);
|
|
211
|
+
results.push(finalResult(view));
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
if (!pending.size) break;
|
|
215
|
+
if (Date.now() >= deadline) {
|
|
216
|
+
for (const id of pending) {
|
|
217
|
+
const v = store.viewSession(store.readSession(id));
|
|
218
|
+
const idle = store.idleInfo(v);
|
|
219
|
+
out(flags.json ? JSON.stringify({ type: 'pending', id, state: v.state, phase: v.phase, ...idle }) : `${id} ${v.state} ${v.phase}${idle && idle.stalled ? ' STALLED?' : ''}`);
|
|
220
|
+
}
|
|
221
|
+
process.exit(124);
|
|
222
|
+
}
|
|
223
|
+
await plans.sleep(plans.POLL_MS);
|
|
224
|
+
}
|
|
225
|
+
const asked = results.filter((x) => x.questions && x.questions.length);
|
|
226
|
+
const broken = results.filter((x) => !(x.questions && x.questions.length) && x.status !== 'completed');
|
|
227
|
+
for (const x of [...asked, ...broken]) {
|
|
228
|
+
if (flags.json) out(JSON.stringify(buildBrief(x)));
|
|
229
|
+
else out(formatResult(x, { color: useColor(process.stdout) }));
|
|
230
|
+
}
|
|
231
|
+
if (!asked.length && !broken.length) {
|
|
232
|
+
if (flags.json) out(JSON.stringify({ type: 'preflight', name, status: 'completed', sessions: ids.length }));
|
|
233
|
+
else out(`plan ${name}: preflight found no open questions (${ids.length} session${ids.length === 1 ? '' : 's'})`);
|
|
234
|
+
}
|
|
235
|
+
process.exit(asked.length ? 10 : broken.length ? Math.max(...broken.map((x) => exitCodeFor(x))) : 0);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async function resume(parsed, name, words) {
|
|
239
|
+
const { flags, given } = parsed;
|
|
240
|
+
const { state, r } = open(name);
|
|
241
|
+
const text = words.join(' ').trim();
|
|
242
|
+
const statuses = plans.sessionStatuses(r, state);
|
|
243
|
+
const RESUMABLE = new Set(['failed', 'partial', 'unverified', 'blocked', 'cancelled', 'interrupted']);
|
|
244
|
+
let targets;
|
|
245
|
+
if (flags.session) {
|
|
246
|
+
const e = statuses.get(flags.session);
|
|
247
|
+
if (!e) die(2, `plan "${name}" has no session "${flags.session}".`);
|
|
248
|
+
if (!RESUMABLE.has(e.status) || !e.view) die(2, `session "${flags.session}" is ${e.status}; only failed, partial, unverified, blocked, cancelled or interrupted sessions resume.`);
|
|
249
|
+
targets = [flags.session];
|
|
250
|
+
} else {
|
|
251
|
+
targets = plans.sessionList(r.plan).map((s) => s.id).filter((id) => RESUMABLE.has(statuses.get(id).status) && statuses.get(id).view);
|
|
252
|
+
}
|
|
253
|
+
const blocked = targets.filter((id) => statuses.get(id).status === 'blocked');
|
|
254
|
+
if (blocked.length && !text) {
|
|
255
|
+
die(2, `${blocked.join(', ')} ${blocked.length === 1 ? 'is' : 'are'} blocked: answer the questions: zcode-agent plan resume ${name} "…" (or --session <id> "…" for one session)`);
|
|
256
|
+
}
|
|
257
|
+
if (!targets.length && !flags.session && ![...statuses.values()].some((x) => x.status === 'pending' || x.status === 'skipped')) {
|
|
258
|
+
// nothing to resume: report as is
|
|
259
|
+
return finish(plans.planReport(name, r, state), flags);
|
|
260
|
+
}
|
|
261
|
+
const message = text || 'Continue: fix the remaining issues.';
|
|
262
|
+
for (const id of targets) {
|
|
263
|
+
const refusal = plans.resumeSession(id, message);
|
|
264
|
+
if (refusal) die(7, refusal);
|
|
265
|
+
}
|
|
266
|
+
// Launch failures recorded earlier are retried by the supervisor.
|
|
267
|
+
if (state.launchErrors && Object.keys(state.launchErrors).length) {
|
|
268
|
+
store.updatePlanState(name, { launchErrors: {} });
|
|
269
|
+
}
|
|
270
|
+
return startSupervision(name, flags, given);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// Detached supervisor process: `zcode __plan <name>`.
|
|
274
|
+
async function supervisorWorker(name) {
|
|
275
|
+
if (!store.readPlanState(name)) die(2, `no plan "${name}".`);
|
|
276
|
+
await plans.supervise(name);
|
|
277
|
+
process.exit(0);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
module.exports = async function plan(parsed) {
|
|
281
|
+
if (parsed.command === '__plan') return supervisorWorker(parsed.prompts[0]);
|
|
282
|
+
const [sub, ...rest] = parsed.prompts;
|
|
283
|
+
switch (sub) {
|
|
284
|
+
case 'check':
|
|
285
|
+
return check(parsed, rest[0]);
|
|
286
|
+
case 'run':
|
|
287
|
+
return run(parsed, rest[0]);
|
|
288
|
+
case 'wait':
|
|
289
|
+
case 'status': {
|
|
290
|
+
if (!rest[0]) die(2, `plan ${sub} needs a plan name.`);
|
|
291
|
+
open(rest[0]);
|
|
292
|
+
if (sub === 'wait') return waitFor(rest[0], parsed.flags, parsed.given);
|
|
293
|
+
print(reportOf(rest[0]), parsed.flags);
|
|
294
|
+
process.exit(0);
|
|
295
|
+
}
|
|
296
|
+
case 'resume':
|
|
297
|
+
if (!rest[0]) die(2, 'plan resume needs a plan name.');
|
|
298
|
+
return resume(parsed, rest[0], rest.slice(1));
|
|
299
|
+
default:
|
|
300
|
+
return die(2, 'plan needs a subcommand: check | run | wait | status | resume (zcode-agent --help).');
|
|
301
|
+
}
|
|
302
|
+
};
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// lib/commands/sessions.js — status | wait | result | cancel. Read-only views over
|
|
3
|
+
// the session store (plus a signal for cancel); none of them spawns the
|
|
4
|
+
// engine or needs the API key, so they are instant and safe to poll.
|
|
5
|
+
const store = require('../store.js');
|
|
6
|
+
const cost = require('../cost.js');
|
|
7
|
+
const { buildBrief } = require('../brief.js');
|
|
8
|
+
const { formatResult, formatSessionRow, formatSessionView, phaseText, useColor } = require('../ui.js');
|
|
9
|
+
|
|
10
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
11
|
+
|
|
12
|
+
function resolveOrExit(ref, json) {
|
|
13
|
+
const id = store.resolveSessionId(ref);
|
|
14
|
+
if (!id) {
|
|
15
|
+
if (json) process.stdout.write(JSON.stringify({ type: 'error', error: 'not_found', id: ref }) + '\n');
|
|
16
|
+
process.stderr.write(`zcode-agent: no session "${ref}" (see "zcode-agent status").\n`);
|
|
17
|
+
process.exit(2);
|
|
18
|
+
}
|
|
19
|
+
return id;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// The handback for a finished session, or a synthetic one when the owning
|
|
23
|
+
// process died without writing it (or is mid-resume of an older result).
|
|
24
|
+
function finalResult(view) {
|
|
25
|
+
const result = store.readResult(view.id);
|
|
26
|
+
if (view.state === 'finished' && result) return result;
|
|
27
|
+
return {
|
|
28
|
+
type: 'result',
|
|
29
|
+
ok: false,
|
|
30
|
+
status: 'failed',
|
|
31
|
+
id: view.id,
|
|
32
|
+
kind: view.kind,
|
|
33
|
+
error: {
|
|
34
|
+
kind: 'interrupted',
|
|
35
|
+
message: `the process running this session exited without a handback; continue with "zcode-agent resume ${view.id}"`,
|
|
36
|
+
},
|
|
37
|
+
issues: ['interrupted before completion'],
|
|
38
|
+
durationMs: 0,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function statusPayload(view, { events = 10 } = {}) {
|
|
43
|
+
const payload = { type: 'status', ...view, ...store.idleInfo(view), recent: store.readEvents(view.id, { tail: events }) };
|
|
44
|
+
if (view.state === 'finished' || view.state === 'interrupted') payload.result = finalResult(view);
|
|
45
|
+
return payload;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const STATUS_RECENT = 15;
|
|
49
|
+
|
|
50
|
+
async function status(parsed) {
|
|
51
|
+
const { flags, prompts } = parsed;
|
|
52
|
+
if (prompts.length === 0) {
|
|
53
|
+
const everything = store.listSessions();
|
|
54
|
+
if (flags.json) {
|
|
55
|
+
process.stdout.write(JSON.stringify({ type: 'sessions', sessions: everything.slice(0, 50).map(summaryOf) }) + '\n');
|
|
56
|
+
} else if (everything.length === 0) {
|
|
57
|
+
process.stdout.write('no sessions\n');
|
|
58
|
+
} else {
|
|
59
|
+
// Most recent first; the rest is one line, `--all` lists everything.
|
|
60
|
+
const shown = flags.all ? everything : everything.slice(0, STATUS_RECENT);
|
|
61
|
+
for (const s of shown) process.stdout.write(formatSessionRow(s) + '\n');
|
|
62
|
+
if (shown.length < everything.length) {
|
|
63
|
+
process.stdout.write(`… ${everything.length - shown.length} more (zcode-agent status --all)\n`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
process.exit(0);
|
|
67
|
+
}
|
|
68
|
+
const id = resolveOrExit(prompts[0], flags.json);
|
|
69
|
+
const view = store.viewSession(store.readSession(id));
|
|
70
|
+
const payload = statusPayload(view);
|
|
71
|
+
Object.assign(view, store.idleInfo(view));
|
|
72
|
+
if (flags.json) {
|
|
73
|
+
process.stdout.write(JSON.stringify(payload) + '\n');
|
|
74
|
+
} else {
|
|
75
|
+
process.stdout.write(formatSessionView(view, { events: payload.recent.slice(-8) }));
|
|
76
|
+
if (payload.result) process.stdout.write('\n' + formatResult(payload.result, { color: useColor(process.stdout) }));
|
|
77
|
+
}
|
|
78
|
+
process.exit(0);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function summaryOf(s) {
|
|
82
|
+
return {
|
|
83
|
+
id: s.id,
|
|
84
|
+
kind: s.kind,
|
|
85
|
+
label: s.label,
|
|
86
|
+
state: s.state,
|
|
87
|
+
status: s.status,
|
|
88
|
+
phase: s.phase,
|
|
89
|
+
cwd: s.cwd,
|
|
90
|
+
owns: s.owns,
|
|
91
|
+
updatedAt: s.updatedAt,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const isDone = (view) => view.state === 'finished' || view.state === 'interrupted';
|
|
96
|
+
|
|
97
|
+
// `12m`, `45s`, `1h05m`: how long a session has been alive, for one-line views.
|
|
98
|
+
function formatElapsed(ms) {
|
|
99
|
+
const s = Math.max(0, Math.round(ms / 1000));
|
|
100
|
+
if (s < 60) return `${s}s`;
|
|
101
|
+
if (s < 3600) return `${Math.floor(s / 60)}m`;
|
|
102
|
+
return `${Math.floor(s / 3600)}h${String(Math.floor((s % 3600) / 60)).padStart(2, '0')}m`;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// What a still-running session costs the reader on a wait timeout: exactly
|
|
106
|
+
// one line, nothing else.
|
|
107
|
+
function pendingLine(view, json) {
|
|
108
|
+
const elapsedMs = Math.max(0, Date.now() - Date.parse(view.createdAt || view.updatedAt || Date.now()));
|
|
109
|
+
const idle = store.idleInfo(view);
|
|
110
|
+
if (json) return JSON.stringify({ type: 'pending', id: view.id, state: view.state, phase: view.phase, elapsedMs, ...idle });
|
|
111
|
+
return `${view.id} ${view.state} ${view.phase} ${formatElapsed(elapsedMs)}${idle && idle.stalled ? ` idle ${formatElapsed(idle.idleMs)} STALLED?` : ''}`;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// A finished session's handback in the requested form.
|
|
115
|
+
function printResult(result, { json, full }) {
|
|
116
|
+
if (json) process.stdout.write(JSON.stringify(full ? result : buildBrief(result)) + '\n');
|
|
117
|
+
else process.stdout.write(formatResult(result, { color: useColor(process.stdout) }));
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Blocks until every id is finished (or interrupted), printing each
|
|
121
|
+
// handback as it lands (--any: until the FIRST one finishes; the rest keep
|
|
122
|
+
// running). Exit 0 iff all completed; otherwise the exit code of the first
|
|
123
|
+
// one that did not (--any: that of the one reported). On --timeout-ms: one
|
|
124
|
+
// line per pending session and exit 124.
|
|
125
|
+
async function wait(parsed) {
|
|
126
|
+
const { flags, prompts, given } = parsed;
|
|
127
|
+
if (prompts.length === 0) {
|
|
128
|
+
process.stderr.write('zcode-agent: wait needs at least one session id.\n');
|
|
129
|
+
process.exit(2);
|
|
130
|
+
}
|
|
131
|
+
const { exitCodeFor } = require('../executor.js');
|
|
132
|
+
const ids = prompts.map((p) => resolveOrExit(p, flags.json));
|
|
133
|
+
const deadline = given.has('timeoutMs') ? Date.now() + flags.timeoutMs : Infinity;
|
|
134
|
+
const pending = new Set(ids);
|
|
135
|
+
let code = 0;
|
|
136
|
+
for (;;) {
|
|
137
|
+
for (const id of ids) {
|
|
138
|
+
if (!pending.has(id)) continue;
|
|
139
|
+
const view = store.viewSession(store.readSession(id));
|
|
140
|
+
if (!isDone(view)) continue;
|
|
141
|
+
pending.delete(id);
|
|
142
|
+
const result = finalResult(view);
|
|
143
|
+
const c = exitCodeFor(result);
|
|
144
|
+
printResult(result, { json: flags.json, full: flags.full });
|
|
145
|
+
if (flags.any) process.exit(c);
|
|
146
|
+
if (c !== 0 && code === 0) code = c;
|
|
147
|
+
}
|
|
148
|
+
if (pending.size === 0) process.exit(code);
|
|
149
|
+
if (Date.now() >= deadline) {
|
|
150
|
+
for (const id of ids) {
|
|
151
|
+
if (!pending.has(id)) continue;
|
|
152
|
+
process.stdout.write(pendingLine(store.viewSession(store.readSession(id)), flags.json) + '\n');
|
|
153
|
+
}
|
|
154
|
+
process.exit(124);
|
|
155
|
+
}
|
|
156
|
+
await sleep(500);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// result <id>: the handback of a finished session, without waiting. Brief
|
|
161
|
+
// as JSON with --json, the human view otherwise; --full prints the full
|
|
162
|
+
// record (JSON).
|
|
163
|
+
async function result(parsed) {
|
|
164
|
+
const { flags, prompts } = parsed;
|
|
165
|
+
if (prompts.length !== 1) {
|
|
166
|
+
process.stderr.write('zcode-agent: result needs exactly one session id.\n');
|
|
167
|
+
process.exit(2);
|
|
168
|
+
}
|
|
169
|
+
const id = resolveOrExit(prompts[0], flags.json);
|
|
170
|
+
const view = store.viewSession(store.readSession(id));
|
|
171
|
+
if (!isDone(view)) {
|
|
172
|
+
process.stderr.write(`zcode-agent: ${id} is still ${view.state} (phase ${view.phase}); use "zcode-agent wait ${id}".\n`);
|
|
173
|
+
process.exit(7);
|
|
174
|
+
}
|
|
175
|
+
const r = finalResult(view);
|
|
176
|
+
if (flags.full) process.stdout.write(JSON.stringify(r) + '\n');
|
|
177
|
+
else printResult(r, { json: flags.json, full: false });
|
|
178
|
+
process.exit(0);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// SIGTERM to the owning process; it stops the engine turn, kills checks,
|
|
182
|
+
// records "cancelled". Escalates to SIGKILL after 15 s and records the
|
|
183
|
+
// cancellation itself. Idempotent: cancelling a finished session is a no-op.
|
|
184
|
+
async function cancel(parsed) {
|
|
185
|
+
const { flags, prompts } = parsed;
|
|
186
|
+
if (prompts.length !== 1) {
|
|
187
|
+
process.stderr.write('zcode-agent: cancel needs exactly one session id.\n');
|
|
188
|
+
process.exit(2);
|
|
189
|
+
}
|
|
190
|
+
const id = resolveOrExit(prompts[0], flags.json);
|
|
191
|
+
let view = store.viewSession(store.readSession(id));
|
|
192
|
+
const report = (outcome) => {
|
|
193
|
+
const v = store.viewSession(store.readSession(id));
|
|
194
|
+
if (flags.json) process.stdout.write(JSON.stringify({ type: 'cancel', id, outcome, state: v.state, status: v.status }) + '\n');
|
|
195
|
+
else process.stdout.write(`${id}: ${outcome} (${v.state === 'finished' ? v.status : v.state})\n`);
|
|
196
|
+
process.exit(0);
|
|
197
|
+
};
|
|
198
|
+
if (!view.live) return report('not running');
|
|
199
|
+
// An ACP session's pid is the `zcode-agent acp` host, which serves its
|
|
200
|
+
// client's other sessions too: stop only this session's engine. The turn
|
|
201
|
+
// fails in the client; its next prompt starts a new engine.
|
|
202
|
+
const acp = view.kind === 'acp';
|
|
203
|
+
try {
|
|
204
|
+
process.kill(acp ? -view.enginePid : view.pid, 'SIGTERM');
|
|
205
|
+
} catch {
|
|
206
|
+
/* exited in between */
|
|
207
|
+
}
|
|
208
|
+
const deadline = Date.now() + 15000;
|
|
209
|
+
while (Date.now() < deadline) {
|
|
210
|
+
await sleep(250);
|
|
211
|
+
view = store.viewSession(store.readSession(id));
|
|
212
|
+
if (!view.live) return report('cancelled');
|
|
213
|
+
}
|
|
214
|
+
for (const target of [acp ? null : view.pid, -view.enginePid]) {
|
|
215
|
+
if (!target) continue;
|
|
216
|
+
try {
|
|
217
|
+
process.kill(target, 'SIGKILL'); // negative = the engine's process group
|
|
218
|
+
} catch {
|
|
219
|
+
/* gone */
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
const result = {
|
|
223
|
+
type: 'result',
|
|
224
|
+
ok: false,
|
|
225
|
+
status: 'cancelled',
|
|
226
|
+
id,
|
|
227
|
+
kind: view.kind,
|
|
228
|
+
error: { kind: 'cancelled', message: 'killed after not stopping within 15s' },
|
|
229
|
+
issues: ['cancelled (forced)'],
|
|
230
|
+
durationMs: 0,
|
|
231
|
+
};
|
|
232
|
+
store.writeResult(id, result);
|
|
233
|
+
store.updateSession(id, { state: 'finished', phase: 'done', status: 'cancelled' });
|
|
234
|
+
return report('killed');
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// One line per watched session: `id state phase[ n/m] elapsed last: <tool>
|
|
238
|
+
// <age> ago[ thinking|writing <age> <n> chars] req <n> sub <running>
|
|
239
|
+
// $cost` (+ STALLED? when running and silent). `usd`: the session's cost so
|
|
240
|
+
// far (lib/cost.js), null if unknown.
|
|
241
|
+
function watchLine(view, { stallMin, now = Date.now(), usd = null }) {
|
|
242
|
+
const done = isDone(view);
|
|
243
|
+
const state = view.state === 'finished' ? view.status || 'finished' : view.state;
|
|
244
|
+
const a = view.activity || {};
|
|
245
|
+
const idle = store.idleInfo(view, { stallMin, now });
|
|
246
|
+
const end = done ? Date.parse(view.updatedAt) : now;
|
|
247
|
+
const elapsed = formatElapsed(end - Date.parse(view.createdAt || view.updatedAt));
|
|
248
|
+
const last = a.lastTool
|
|
249
|
+
? `last: ${a.lastTool}${a.lastToolAt ? ` ${formatElapsed(now - Date.parse(a.lastToolAt))} ago` : ''}`
|
|
250
|
+
: 'last: -';
|
|
251
|
+
const phase = done ? '' : ` ${phaseText(view)}`;
|
|
252
|
+
const cur = !done && a.current && a.current.doing ? a.current : null;
|
|
253
|
+
const doing = cur
|
|
254
|
+
? ` ${cur.doing} ${formatElapsed(now - Date.parse(cur.since))}${cur.chars ? ` ${cost.formatTokens(cur.chars)} chars` : ''}`
|
|
255
|
+
: '';
|
|
256
|
+
const stalled = idle && idle.stalled ? ' STALLED?' : '';
|
|
257
|
+
const money = usd === null || usd === undefined ? '' : ` ${cost.formatUsd(usd)}`;
|
|
258
|
+
const text = `${view.id} ${state}${phase} ${elapsed} ${last}${doing} req ${a.modelRequests || 0} sub ${a.subagentsRunning || 0}${money}${stalled}`;
|
|
259
|
+
// The change signature leaves out the clocks (elapsed, ages, char counts).
|
|
260
|
+
const sig = [view.id, state, phase, a.lastTool, cur ? cur.doing : '', a.modelRequests || 0, a.subagentsRunning || 0, money, Boolean(stalled)].join('|');
|
|
261
|
+
return { text, sig, done };
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// watch [<id>… | --plan <name>] [--stall-min n]: live view, no Opus tokens.
|
|
265
|
+
// TTY: redraw every 2 s; otherwise print a session's line when it changes.
|
|
266
|
+
// No args: live sessions plus those finished in the last 10 min. Exits when
|
|
267
|
+
// every watched session is finished; Ctrl-C exits 0.
|
|
268
|
+
async function watch(parsed) {
|
|
269
|
+
const { flags, prompts } = parsed;
|
|
270
|
+
const stallMin = parsed.given.has('stallMin') ? flags.stallMin : store.STALL_MIN;
|
|
271
|
+
const poll = Number(process.env.ZCODE_WATCH_POLL_MS) || 2000;
|
|
272
|
+
const tty = Boolean(process.stdout.isTTY);
|
|
273
|
+
process.on('SIGINT', () => process.exit(0));
|
|
274
|
+
let planCtx = null;
|
|
275
|
+
if (flags.plan) {
|
|
276
|
+
const plans = require('../plan.js');
|
|
277
|
+
const state = store.readPlanState(flags.plan);
|
|
278
|
+
if (!state) {
|
|
279
|
+
process.stderr.write(`zcode-agent: no plan "${flags.plan}" (zcode-agent plan run <file> starts one).\n`);
|
|
280
|
+
process.exit(2);
|
|
281
|
+
}
|
|
282
|
+
planCtx = { plans, state, r: plans.resolvePlan(state.file, state.cwd) };
|
|
283
|
+
}
|
|
284
|
+
const ids = prompts.map((p) => resolveOrExit(p, false));
|
|
285
|
+
const pick = () => {
|
|
286
|
+
if (ids.length) return ids.map((id) => store.viewSession(store.readSession(id))).filter(Boolean);
|
|
287
|
+
if (planCtx) {
|
|
288
|
+
return planCtx.plans.sessionList(planCtx.r.plan)
|
|
289
|
+
.map((s) => store.readSession(s.id)).filter(Boolean).map((rec) => store.viewSession(rec));
|
|
290
|
+
}
|
|
291
|
+
const cutoff = Date.now() - 10 * 60000;
|
|
292
|
+
return store.listSessions().filter((v) => !isDone(v) || Date.parse(v.updatedAt) >= cutoff).reverse();
|
|
293
|
+
};
|
|
294
|
+
const planDone = () => planCtx.plans.planReport(flags.plan, planCtx.r, store.readPlanState(flags.plan), { briefs: false }).status !== 'running';
|
|
295
|
+
const seen = new Map();
|
|
296
|
+
let drawn = 0;
|
|
297
|
+
for (;;) {
|
|
298
|
+
const views = pick();
|
|
299
|
+
if (!views.length && !planCtx) {
|
|
300
|
+
process.stdout.write('no live sessions\n');
|
|
301
|
+
process.exit(0);
|
|
302
|
+
}
|
|
303
|
+
const costs = views.map((v) => cost.sessionCost(v));
|
|
304
|
+
const lines = views.map((v, i) => watchLine(v, { stallMin, usd: costs[i] ? costs[i].usd : null }));
|
|
305
|
+
const known = costs.filter(Boolean);
|
|
306
|
+
const total = lines.length > 1 && known.length ? `total ${cost.formatUsd(cost.sumCosts(known).usd)} (${known.length} session${known.length === 1 ? '' : 's'}, Z.ai list price)` : null;
|
|
307
|
+
if (tty) {
|
|
308
|
+
const shown = total ? [...lines.map((l) => l.text), total] : lines.map((l) => l.text);
|
|
309
|
+
process.stdout.write(`${drawn ? `\x1b[${drawn}F\x1b[J` : ''}${shown.join('\n')}${shown.length ? '\n' : ''}`);
|
|
310
|
+
drawn = shown.length;
|
|
311
|
+
} else {
|
|
312
|
+
for (const l of lines) {
|
|
313
|
+
const id = l.text.split(' ')[0];
|
|
314
|
+
if (seen.get(id) === l.sig) continue;
|
|
315
|
+
seen.set(id, l.sig);
|
|
316
|
+
process.stdout.write(l.text + '\n');
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
const finished = planCtx ? planDone() : lines.every((l) => l.done);
|
|
320
|
+
if (finished && (lines.length || planCtx)) process.exit(0);
|
|
321
|
+
await sleep(poll);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
module.exports = async function sessions(parsed) {
|
|
326
|
+
if (parsed.command === 'watch') return watch(parsed);
|
|
327
|
+
if (parsed.command === 'status') return status(parsed);
|
|
328
|
+
if (parsed.command === 'wait') return wait(parsed);
|
|
329
|
+
if (parsed.command === 'result') return result(parsed);
|
|
330
|
+
return cancel(parsed);
|
|
331
|
+
};
|
|
332
|
+
|
|
333
|
+
module.exports.finalResult = finalResult;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// zcode-agent skills [status|install|uninstall] [claude|codex]
|
|
3
|
+
// Copies the orchestrator skills shipped in this package into Claude Code
|
|
4
|
+
// and Codex. Nothing runs at npm install time; this command is the installer.
|
|
5
|
+
const { installSkills, uninstallSkills, skillStatus, PLATFORMS } = require('../skills.js');
|
|
6
|
+
|
|
7
|
+
const ACTIONS = new Set(['status', 'install', 'uninstall']);
|
|
8
|
+
|
|
9
|
+
module.exports = function skills({ prompts, flags }) {
|
|
10
|
+
const [action = 'status', ...platforms] = prompts;
|
|
11
|
+
const fail = (msg) => {
|
|
12
|
+
process.stderr.write(`zcode-agent: ${msg}\nusage: zcode-agent skills [status|install|uninstall] [claude|codex]\n`);
|
|
13
|
+
process.exit(2);
|
|
14
|
+
};
|
|
15
|
+
if (!ACTIONS.has(action)) fail(`unknown skills action "${action}".`);
|
|
16
|
+
for (const p of platforms) if (!PLATFORMS.includes(p)) fail(`unknown platform "${p}" (claude | codex).`);
|
|
17
|
+
|
|
18
|
+
const view = (t) => ({
|
|
19
|
+
platform: t.platform,
|
|
20
|
+
name: t.name,
|
|
21
|
+
path: t.to,
|
|
22
|
+
...(t.installed !== undefined && { installed: t.installed }),
|
|
23
|
+
...(t.legacyRemoved && { legacyRemoved: t.legacy }),
|
|
24
|
+
});
|
|
25
|
+
let rows;
|
|
26
|
+
if (action === 'install') rows = installSkills({ platforms });
|
|
27
|
+
else if (action === 'uninstall') rows = uninstallSkills({ platforms });
|
|
28
|
+
else rows = skillStatus().filter((t) => !platforms.length || platforms.includes(t.platform));
|
|
29
|
+
|
|
30
|
+
if (flags.json) {
|
|
31
|
+
process.stdout.write(JSON.stringify({ action, skills: rows.map(view) }, null, 2) + '\n');
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
if (rows.length === 0) {
|
|
35
|
+
process.stdout.write('zcode-agent: nothing to uninstall\n');
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
for (const t of rows) {
|
|
39
|
+
const what = action === 'install' ? 'installed' : action === 'uninstall' ? 'removed' : t.installed ? 'installed' : 'not installed';
|
|
40
|
+
process.stdout.write(`${t.name.padEnd(12)} ${what.padEnd(14)} ${t.to}\n`);
|
|
41
|
+
if (t.legacyRemoved) process.stdout.write(`${''.padEnd(12)} ${'removed'.padEnd(14)} ${t.legacy} (pre-1.0 zcode skill)\n`);
|
|
42
|
+
else if (action === 'status' && t.legacy) process.stdout.write(`${''.padEnd(12)} ${'outdated'.padEnd(14)} ${t.legacy} (pre-1.0; install replaces it)\n`);
|
|
43
|
+
}
|
|
44
|
+
if (action === 'status' && rows.some((t) => !t.installed)) {
|
|
45
|
+
process.stdout.write('\nrun `zcode-agent skills install` to install them\n');
|
|
46
|
+
}
|
|
47
|
+
};
|