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
package/lib/plan.js
ADDED
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// zcode plan: a DAG of task sessions from one plan file, run by a supervisor.
|
|
3
|
+
//
|
|
4
|
+
// The plan file ({cwd?, decisions?, context?, files?, model?, effort?,
|
|
5
|
+
// sessions:[{id, after?, ...contract keys}]}) is validated up front
|
|
6
|
+
// (checkPlan), then a supervisor launches each session as a detached zcode
|
|
7
|
+
// session once everything it is `after` has completed. The sessions are the
|
|
8
|
+
// source of truth: a plan's status is derived from their records (plus
|
|
9
|
+
// "never started" for sessions that were not launched), so it stays accurate
|
|
10
|
+
// when the supervisor dies. <root>/plans/<name>.json only remembers the plan
|
|
11
|
+
// file, the supervisor pid and launches that failed before a session existed.
|
|
12
|
+
//
|
|
13
|
+
// No process.exit in here: lib/commands/plan.js owns the CLI.
|
|
14
|
+
const fs = require('node:fs');
|
|
15
|
+
const path = require('node:path');
|
|
16
|
+
const { spawn } = require('node:child_process');
|
|
17
|
+
const store = require('./store.js');
|
|
18
|
+
const { buildContract } = require('./taskspec.js');
|
|
19
|
+
const { ContractError } = require('./contract.js');
|
|
20
|
+
const { workspaceRoot, normalizeOwns, ownsOverlap, OwnershipError } = require('./workspace.js');
|
|
21
|
+
const { normalizeModel, normalizeEffort, effortProblem, unknownModelMessage, DEFAULT_MODEL } = require('./models.js');
|
|
22
|
+
const { buildBrief } = require('./brief.js');
|
|
23
|
+
|
|
24
|
+
const BIN = path.join(__dirname, '..', 'bin', 'zcode-agent.js');
|
|
25
|
+
const PLAN_KEYS = ['cwd', 'decisions', 'context', 'files', 'model', 'effort', 'limits', 'sessions'];
|
|
26
|
+
const POLL_MS = 500;
|
|
27
|
+
|
|
28
|
+
class PlanError extends Error {}
|
|
29
|
+
|
|
30
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
31
|
+
const toArray = (v) => (v === undefined || v === null ? [] : Array.isArray(v) ? v : [v]);
|
|
32
|
+
|
|
33
|
+
// Reads and parses the plan file. `cwdOverride` is an explicit --cwd; else the
|
|
34
|
+
// plan's "cwd" (relative to the plan file); else the process cwd.
|
|
35
|
+
function resolvePlan(file, cwdOverride) {
|
|
36
|
+
const abs = path.resolve(file);
|
|
37
|
+
let text;
|
|
38
|
+
try {
|
|
39
|
+
text = fs.readFileSync(abs, 'utf8');
|
|
40
|
+
} catch {
|
|
41
|
+
throw new PlanError(`plan file "${file}" could not be read.`);
|
|
42
|
+
}
|
|
43
|
+
let plan;
|
|
44
|
+
try {
|
|
45
|
+
plan = JSON.parse(text);
|
|
46
|
+
} catch (err) {
|
|
47
|
+
throw new PlanError(`plan file "${file}" is not valid JSON: ${err.message}`);
|
|
48
|
+
}
|
|
49
|
+
if (!plan || typeof plan !== 'object' || Array.isArray(plan)) throw new PlanError('plan must be a JSON object.');
|
|
50
|
+
const dir = path.dirname(abs);
|
|
51
|
+
const cwd = cwdOverride ? path.resolve(cwdOverride) : plan.cwd ? path.resolve(dir, String(plan.cwd)) : process.cwd();
|
|
52
|
+
return { file: abs, dir, cwd, plan };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Plan name: --id, else the plan file's basename without extension.
|
|
56
|
+
function planName(id, file) {
|
|
57
|
+
const name = id || path.basename(file, path.extname(file));
|
|
58
|
+
if (!store.validId(name)) {
|
|
59
|
+
throw new PlanError(`plan name "${name}" is not a valid id (letters, digits, ".", "_", "-"); pass --id.`);
|
|
60
|
+
}
|
|
61
|
+
return name;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const sessionList = (plan) => (Array.isArray(plan.sessions) ? plan.sessions.filter((s) => s && typeof s === 'object') : []);
|
|
65
|
+
const afterOf = (s) => toArray(s.after).map(String);
|
|
66
|
+
|
|
67
|
+
// The session's contract object: top-level decisions/context/files first,
|
|
68
|
+
// the plan's model/effort/limits as defaults (a session's own limits win per
|
|
69
|
+
// key). `id`, `after` and `label` are plan keys, not contract keys.
|
|
70
|
+
function sessionBase(r, s) {
|
|
71
|
+
const { id, after, label, ...rest } = s;
|
|
72
|
+
const top = r.plan;
|
|
73
|
+
const base = { ...rest };
|
|
74
|
+
for (const key of ['decisions', 'context', 'files']) {
|
|
75
|
+
const merged = [...toArray(top[key]), ...toArray(rest[key])];
|
|
76
|
+
if (merged.length) base[key] = merged;
|
|
77
|
+
}
|
|
78
|
+
for (const key of ['model', 'effort']) {
|
|
79
|
+
if (base[key] === undefined && top[key] !== undefined) base[key] = top[key];
|
|
80
|
+
}
|
|
81
|
+
if (top.limits && typeof top.limits === 'object' && !Array.isArray(top.limits)) {
|
|
82
|
+
base.limits = { ...top.limits, ...(rest.limits && typeof rest.limits === 'object' ? rest.limits : {}) };
|
|
83
|
+
}
|
|
84
|
+
return base;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Every problem with the plan, one string each ([] = valid). `state` is the
|
|
88
|
+
// stored plan state (sessions it already owns are not "taken").
|
|
89
|
+
function checkPlan(r, { name, state } = {}) {
|
|
90
|
+
const problems = [];
|
|
91
|
+
const { plan } = r;
|
|
92
|
+
const unknown = Object.keys(plan).filter((k) => !PLAN_KEYS.includes(k));
|
|
93
|
+
if (unknown.length) problems.push(`unknown plan key(s): ${unknown.join(', ')}. Accepted: ${PLAN_KEYS.join(', ')}`);
|
|
94
|
+
if (plan.limits !== undefined && (!plan.limits || typeof plan.limits !== 'object' || Array.isArray(plan.limits))) {
|
|
95
|
+
problems.push('plan "limits" must be an object (timeoutMs, maxRepairs, checkTimeoutMs).');
|
|
96
|
+
}
|
|
97
|
+
if (!Array.isArray(plan.sessions) || plan.sessions.length === 0) {
|
|
98
|
+
problems.push('plan needs a non-empty "sessions" array.');
|
|
99
|
+
return problems;
|
|
100
|
+
}
|
|
101
|
+
try {
|
|
102
|
+
if (!fs.statSync(r.cwd).isDirectory()) throw new Error('not a directory');
|
|
103
|
+
} catch {
|
|
104
|
+
problems.push(`cwd "${r.cwd}" is not an existing directory.`);
|
|
105
|
+
return problems;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const sessions = plan.sessions;
|
|
109
|
+
const ids = [];
|
|
110
|
+
sessions.forEach((s, i) => {
|
|
111
|
+
if (!s || typeof s !== 'object' || Array.isArray(s)) {
|
|
112
|
+
problems.push(`sessions[${i}] must be an object.`);
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
const label = typeof s.id === 'string' ? `session "${s.id}"` : `sessions[${i}]`;
|
|
116
|
+
if (!store.validId(s.id)) {
|
|
117
|
+
problems.push(`${label}: "id" must be 1-64 chars of letters, digits, ".", "_" or "-", starting with a letter or digit.`);
|
|
118
|
+
} else if (s.id.length + 4 > 64) {
|
|
119
|
+
problems.push(`${label}: id is too long (the preflight session "${s.id}.pre" must fit 64 chars).`);
|
|
120
|
+
} else if (ids.includes(s.id)) {
|
|
121
|
+
problems.push(`duplicate session id "${s.id}".`);
|
|
122
|
+
}
|
|
123
|
+
if (typeof s.id === 'string') ids.push(s.id);
|
|
124
|
+
if (s.label !== undefined && typeof s.label !== 'string') problems.push(`${label}: "label" must be a string.`);
|
|
125
|
+
if (s.after !== undefined && !toArray(s.after).every((a) => typeof a === 'string')) {
|
|
126
|
+
problems.push(`${label}: "after" must be a list of session ids.`);
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
const valid = sessionList(plan).filter((s) => typeof s.id === 'string');
|
|
130
|
+
|
|
131
|
+
// after refs and cycles
|
|
132
|
+
const known = new Set(valid.map((s) => s.id));
|
|
133
|
+
const deps = new Map(valid.map((s) => [s.id, afterOf(s)]));
|
|
134
|
+
for (const s of valid) {
|
|
135
|
+
for (const a of afterOf(s)) {
|
|
136
|
+
if (a === s.id) problems.push(`session "${s.id}" is after itself.`);
|
|
137
|
+
else if (!known.has(a)) problems.push(`session "${s.id}": after "${a}" is not a session in this plan.`);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
let cyclic = false;
|
|
141
|
+
const mark = new Map();
|
|
142
|
+
const walk = (id, trail) => {
|
|
143
|
+
if (mark.get(id) === 2) return;
|
|
144
|
+
if (mark.get(id) === 1) {
|
|
145
|
+
cyclic = true;
|
|
146
|
+
problems.push(`dependency cycle: ${[...trail.slice(trail.indexOf(id)), id].join(' -> ')}`);
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
mark.set(id, 1);
|
|
150
|
+
for (const a of deps.get(id) || []) if (known.has(a) && a !== id) walk(a, [...trail, id]);
|
|
151
|
+
mark.set(id, 2);
|
|
152
|
+
};
|
|
153
|
+
for (const id of known) if (!cyclic) walk(id, []);
|
|
154
|
+
|
|
155
|
+
// contracts, model/effort, ownership
|
|
156
|
+
const contracts = new Map();
|
|
157
|
+
for (const s of valid) {
|
|
158
|
+
let contract;
|
|
159
|
+
try {
|
|
160
|
+
contract = buildContract({ base: sessionBase(r, s), baseDir: r.dir, cwd: r.cwd });
|
|
161
|
+
} catch (err) {
|
|
162
|
+
if (err instanceof ContractError) problems.push(`session "${s.id}": ${err.message}`);
|
|
163
|
+
else throw err;
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
const model = contract.model === null ? DEFAULT_MODEL : normalizeModel(contract.model);
|
|
167
|
+
if (!model) {
|
|
168
|
+
problems.push(`session "${s.id}": ${unknownModelMessage(contract.model)}`);
|
|
169
|
+
} else {
|
|
170
|
+
const effort = contract.effort === null ? 'max' : normalizeEffort(contract.effort);
|
|
171
|
+
if (!effort) problems.push(`session "${s.id}": contract effort "${contract.effort}" is not valid.`);
|
|
172
|
+
else {
|
|
173
|
+
const p = effortProblem(model, effort, { source: `session "${s.id}" effort` });
|
|
174
|
+
if (p) problems.push(p);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
contracts.set(s.id, contract);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// Sessions that can run at the same time (neither is, transitively, after
|
|
181
|
+
// the other) must own disjoint paths.
|
|
182
|
+
if (!cyclic) {
|
|
183
|
+
const reach = new Map();
|
|
184
|
+
const closure = (id) => {
|
|
185
|
+
if (reach.has(id)) return reach.get(id);
|
|
186
|
+
const set = new Set();
|
|
187
|
+
reach.set(id, set);
|
|
188
|
+
for (const a of deps.get(id) || []) {
|
|
189
|
+
if (!known.has(a)) continue;
|
|
190
|
+
set.add(a);
|
|
191
|
+
for (const x of closure(a)) set.add(x);
|
|
192
|
+
}
|
|
193
|
+
return set;
|
|
194
|
+
};
|
|
195
|
+
for (const id of known) closure(id);
|
|
196
|
+
let root;
|
|
197
|
+
const owns = new Map();
|
|
198
|
+
for (const [id, c] of contracts) {
|
|
199
|
+
try {
|
|
200
|
+
root = root || workspaceRoot(r.cwd);
|
|
201
|
+
owns.set(id, normalizeOwns(c.owns, r.cwd, root));
|
|
202
|
+
} catch (err) {
|
|
203
|
+
if (err instanceof OwnershipError) problems.push(`session "${id}": ${err.message}`);
|
|
204
|
+
else throw err;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
const order = [...owns.keys()];
|
|
208
|
+
for (let i = 0; i < order.length; i++) {
|
|
209
|
+
for (let j = i + 1; j < order.length; j++) {
|
|
210
|
+
const [a, b] = [order[i], order[j]];
|
|
211
|
+
if (reach.get(a).has(b) || reach.get(b).has(a)) continue;
|
|
212
|
+
if (ownsOverlap(owns.get(a), owns.get(b))) {
|
|
213
|
+
const show = (id) => (contracts.get(id).owns.length ? contracts.get(id).owns.join(', ') : 'whole workspace');
|
|
214
|
+
problems.push(`sessions "${a}" and "${b}" can run concurrently but their owns overlap (${show(a)} / ${show(b)}); add "after" or make owns disjoint.`);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// Ids already taken by sessions that are not this plan's.
|
|
221
|
+
const mine = new Set(state && Array.isArray(state.sessions) ? state.sessions : []);
|
|
222
|
+
let taken = false;
|
|
223
|
+
for (const id of known) {
|
|
224
|
+
if (store.readSession(id) && !mine.has(id)) {
|
|
225
|
+
taken = true;
|
|
226
|
+
problems.push(`session "${id}" already exists (zcode-agent status ${id}).`);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
if (taken) {
|
|
230
|
+
problems.push(`hint: use a fresh id prefix for a new run (e.g. "<prefix>-<id>"), or "zcode-agent plan resume ${name || '<name>'}" to continue that plan's sessions.`);
|
|
231
|
+
}
|
|
232
|
+
return problems;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// --- status, derived from the sessions ------------------------------------------
|
|
236
|
+
|
|
237
|
+
const LIVE = new Set(['queued', 'running']);
|
|
238
|
+
const FINAL_OK = 'completed';
|
|
239
|
+
|
|
240
|
+
function launchFailure(id, message) {
|
|
241
|
+
return {
|
|
242
|
+
type: 'result', ok: false, status: 'failed', id, kind: 'task',
|
|
243
|
+
error: { kind: 'launch', message }, issues: [message],
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// {id: {status, view?}} for every session of the plan. A session that was
|
|
248
|
+
// never started is `pending`, or `skipped` when something it (transitively)
|
|
249
|
+
// depends on ended without completing.
|
|
250
|
+
function sessionStatuses(r, state) {
|
|
251
|
+
const out = new Map();
|
|
252
|
+
const sessions = sessionList(r.plan);
|
|
253
|
+
const byId = new Map(sessions.map((s) => [s.id, s]));
|
|
254
|
+
const resolve = (id) => {
|
|
255
|
+
if (out.has(id)) return out.get(id);
|
|
256
|
+
const s = byId.get(id);
|
|
257
|
+
const record = store.readSession(id);
|
|
258
|
+
let entry;
|
|
259
|
+
if (record) {
|
|
260
|
+
const view = store.viewSession(record);
|
|
261
|
+
if (LIVE.has(view.state)) entry = { status: view.state, view };
|
|
262
|
+
else if (view.state === 'interrupted') entry = { status: 'interrupted', view };
|
|
263
|
+
else entry = { status: view.status || 'failed', view };
|
|
264
|
+
} else if (state && state.launchErrors && state.launchErrors[id]) {
|
|
265
|
+
entry = { status: 'failed', launchError: state.launchErrors[id] };
|
|
266
|
+
} else {
|
|
267
|
+
const upstream = afterOf(s).filter((a) => byId.has(a)).map(resolve);
|
|
268
|
+
const dead = upstream.some((u) => !['pending', 'queued', 'running', FINAL_OK].includes(u.status));
|
|
269
|
+
entry = { status: dead ? 'skipped' : 'pending' };
|
|
270
|
+
}
|
|
271
|
+
out.set(id, entry);
|
|
272
|
+
return entry;
|
|
273
|
+
};
|
|
274
|
+
for (const s of sessions) resolve(s.id);
|
|
275
|
+
return out;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function aggregate(statuses, supervisorAlive) {
|
|
279
|
+
const all = [...statuses.values()].map((e) => e.status);
|
|
280
|
+
if (all.some((s) => LIVE.has(s))) return 'running';
|
|
281
|
+
if (all.includes('pending')) return supervisorAlive ? 'running' : 'interrupted';
|
|
282
|
+
if (all.every((s) => s === FINAL_OK)) return 'completed';
|
|
283
|
+
if (all.includes('blocked')) return 'blocked';
|
|
284
|
+
if (all.some((s) => ['failed', 'cancelled', 'interrupted'].includes(s))) return 'failed';
|
|
285
|
+
return 'partial';
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const exitCodeForPlan = (status) => (status === 'completed' ? 0 : status === 'blocked' ? 10 : status === 'running' ? 124 : 8);
|
|
289
|
+
|
|
290
|
+
function supervisorAlive(state) {
|
|
291
|
+
return Boolean(state && state.supervisor && store.pidAlive(state.supervisor.pid));
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// {type:"plan", name, status, sessions:[{id,status}], briefs:[…]}: briefs of
|
|
295
|
+
// sessions that ended without completing (never for pending/skipped).
|
|
296
|
+
function planReport(name, r, state, { briefs = true } = {}) {
|
|
297
|
+
const { finalResult } = require('./commands/sessions.js');
|
|
298
|
+
const statuses = sessionStatuses(r, state);
|
|
299
|
+
const status = aggregate(statuses, supervisorAlive(state));
|
|
300
|
+
const payload = {
|
|
301
|
+
type: 'plan',
|
|
302
|
+
name,
|
|
303
|
+
status,
|
|
304
|
+
sessions: sessionList(r.plan).map((s) => {
|
|
305
|
+
const e = statuses.get(s.id);
|
|
306
|
+
return { id: s.id, status: e.status, ...(e.view ? store.idleInfo(e.view) : null) };
|
|
307
|
+
}),
|
|
308
|
+
};
|
|
309
|
+
if (briefs) {
|
|
310
|
+
payload.briefs = [];
|
|
311
|
+
for (const s of sessionList(r.plan)) {
|
|
312
|
+
const e = statuses.get(s.id);
|
|
313
|
+
if (e.status === FINAL_OK) continue;
|
|
314
|
+
if (e.launchError) payload.briefs.push(buildBrief(launchFailure(s.id, e.launchError)));
|
|
315
|
+
else if (e.view && !LIVE.has(e.view.state)) payload.briefs.push(buildBrief(finalResult(e.view)));
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
return payload;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// --- launching --------------------------------------------------------------------
|
|
322
|
+
|
|
323
|
+
function exec() {
|
|
324
|
+
return require('./commands/exec.js');
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// Preflights run all at once on the current workspace, so a session with
|
|
328
|
+
// `after` would see none of its prerequisites' files. This paragraph tells it
|
|
329
|
+
// to assume them (ids + clipped objectives) instead of asking about them.
|
|
330
|
+
function preflightContext(r, s) {
|
|
331
|
+
const upstream = afterOf(s).map((a) => sessionList(r.plan).find((x) => x.id === a)).filter(Boolean);
|
|
332
|
+
if (!upstream.length) return null;
|
|
333
|
+
const clip = (t) => {
|
|
334
|
+
const x = String(t || '').replace(/\s+/g, ' ').trim();
|
|
335
|
+
return x.length <= 200 ? x : `${x.slice(0, 199)}…`;
|
|
336
|
+
};
|
|
337
|
+
const list = upstream.map((u) => `- ${u.id}: ${clip(sessionBase(r, u).objective) || '(no objective)'}`).join('\n');
|
|
338
|
+
return `This is a plan preflight. Sessions ${upstream.map((u) => u.id).join(', ')} run before you and have not run yet; their files will exist when you execute. Assume they deliver what the binding decisions and their objectives say:\n${list}\nDo not ask about their absence; ask only about what the decisions leave open for YOUR scope.`;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// The detached-start invocation for one plan session (id overrides the plan
|
|
342
|
+
// id: preflight uses "<id>.pre"). The label is `plan:<name>` plus the
|
|
343
|
+
// session's own `label`, if any.
|
|
344
|
+
function sessionInvocation(r, name, s, { id = s.id, preflight = false } = {}) {
|
|
345
|
+
const { parseArgv } = require('../bin/zcode-agent.js');
|
|
346
|
+
const label = `plan:${name}${typeof s.label === 'string' && s.label.trim() ? ` ${s.label.trim()}` : ''}`;
|
|
347
|
+
const argv = ['task', '--id', id, '--cwd', r.cwd, '--label', label];
|
|
348
|
+
if (preflight) argv.push('--preflight');
|
|
349
|
+
const base = sessionBase(r, s);
|
|
350
|
+
const note = preflight ? preflightContext(r, s) : null;
|
|
351
|
+
if (note) base.context = [...toArray(base.context), note];
|
|
352
|
+
return exec().buildInvocation(parseArgv(argv), { base, dir: r.dir });
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function launchSession(r, name, s) {
|
|
356
|
+
const e = exec();
|
|
357
|
+
try {
|
|
358
|
+
e.startDetached(sessionInvocation(r, name, s));
|
|
359
|
+
return null;
|
|
360
|
+
} catch (err) {
|
|
361
|
+
if (err instanceof store.SessionExistsError) return null; // already started
|
|
362
|
+
if (err instanceof e.UsageError || err instanceof ContractError || err.exitCode) return err.message;
|
|
363
|
+
throw err;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// Resume one session of the plan (detached). Returns null or the refusal.
|
|
368
|
+
function resumeSession(id, message) {
|
|
369
|
+
const { parseArgv } = require('../bin/zcode-agent.js');
|
|
370
|
+
const e = exec();
|
|
371
|
+
try {
|
|
372
|
+
e.startDetached(e.buildResume(parseArgv(['resume', id]), id, message));
|
|
373
|
+
return null;
|
|
374
|
+
} catch (err) {
|
|
375
|
+
if (err instanceof e.UsageError || err.exitCode) return err.message;
|
|
376
|
+
throw err;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// --- supervisor ---------------------------------------------------------------------
|
|
381
|
+
|
|
382
|
+
// Launches ready sessions until nothing is running or launchable. One
|
|
383
|
+
// supervisor per plan (pid lock). Returns {done:true} | {timedOut:true} |
|
|
384
|
+
// {busy:true} (another supervisor holds the plan).
|
|
385
|
+
async function supervise(name, { deadline = Infinity, signal } = {}) {
|
|
386
|
+
const release = store.claimPlan(name);
|
|
387
|
+
if (!release) return { busy: true };
|
|
388
|
+
try {
|
|
389
|
+
store.updatePlanState(name, { supervisor: { pid: process.pid } });
|
|
390
|
+
for (;;) {
|
|
391
|
+
const state = store.readPlanState(name);
|
|
392
|
+
const r = resolvePlan(state.file, state.cwd);
|
|
393
|
+
const sessions = sessionList(r.plan);
|
|
394
|
+
const byId = new Map(sessions.map((s) => [s.id, s]));
|
|
395
|
+
const statuses = sessionStatuses(r, state);
|
|
396
|
+
for (const s of sessions) {
|
|
397
|
+
if (statuses.get(s.id).status !== 'pending') continue;
|
|
398
|
+
if (!afterOf(s).every((a) => statuses.get(a) && statuses.get(a).status === FINAL_OK)) continue;
|
|
399
|
+
const failure = launchSession(r, name, byId.get(s.id));
|
|
400
|
+
if (failure) {
|
|
401
|
+
store.updatePlanState(name, (cur) => ({ launchErrors: { ...(cur.launchErrors || {}), [s.id]: failure } }));
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
const now = sessionStatuses(r, store.readPlanState(name));
|
|
405
|
+
const active = [...now.values()].some((e) => LIVE.has(e.status) || e.status === 'pending');
|
|
406
|
+
if (!active) return { done: true };
|
|
407
|
+
if (signal && signal.aborted) return { done: true };
|
|
408
|
+
if (Date.now() >= deadline) return { timedOut: true };
|
|
409
|
+
await sleep(POLL_MS);
|
|
410
|
+
}
|
|
411
|
+
} finally {
|
|
412
|
+
try {
|
|
413
|
+
store.updatePlanState(name, { supervisor: null });
|
|
414
|
+
} catch {
|
|
415
|
+
/* plan state removed */
|
|
416
|
+
}
|
|
417
|
+
release();
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// A detached supervisor process (`zcode __plan <name>`); records its pid.
|
|
422
|
+
function startSupervisor(name) {
|
|
423
|
+
const dir = store.plansDir();
|
|
424
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
425
|
+
const log = fs.openSync(path.join(dir, `${name}.log`), 'a', 0o600);
|
|
426
|
+
const child = spawn(process.execPath, [BIN, '__plan', name], {
|
|
427
|
+
detached: true,
|
|
428
|
+
stdio: ['ignore', log, log],
|
|
429
|
+
env: process.env,
|
|
430
|
+
});
|
|
431
|
+
child.unref();
|
|
432
|
+
fs.closeSync(log);
|
|
433
|
+
store.updatePlanState(name, { supervisor: { pid: child.pid } });
|
|
434
|
+
return child.pid;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
module.exports = {
|
|
438
|
+
PlanError,
|
|
439
|
+
resolvePlan,
|
|
440
|
+
planName,
|
|
441
|
+
sessionList,
|
|
442
|
+
afterOf,
|
|
443
|
+
sessionBase,
|
|
444
|
+
checkPlan,
|
|
445
|
+
sessionStatuses,
|
|
446
|
+
aggregate,
|
|
447
|
+
exitCodeForPlan,
|
|
448
|
+
supervisorAlive,
|
|
449
|
+
planReport,
|
|
450
|
+
launchFailure,
|
|
451
|
+
sessionInvocation,
|
|
452
|
+
preflightContext,
|
|
453
|
+
launchSession,
|
|
454
|
+
resumeSession,
|
|
455
|
+
supervise,
|
|
456
|
+
startSupervisor,
|
|
457
|
+
sleep,
|
|
458
|
+
POLL_MS,
|
|
459
|
+
};
|
package/lib/ports.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Per-session TCP port reservation. Parallel sessions that each start a dev
|
|
3
|
+
// or preview server must not fight over one port, so every session gets its
|
|
4
|
+
// own ($ZCODE_PORT): a lock file per port under <root>/ports/ (pid lock, so a
|
|
5
|
+
// dead session's port is reclaimed) plus a real bind probe, because the port
|
|
6
|
+
// may also be held by a process zcode knows nothing about.
|
|
7
|
+
const fs = require('node:fs');
|
|
8
|
+
const net = require('node:net');
|
|
9
|
+
const path = require('node:path');
|
|
10
|
+
const { rootDir } = require('./isolation.js');
|
|
11
|
+
const { claimLockFile } = require('./store.js');
|
|
12
|
+
|
|
13
|
+
const PORT_MIN = 41000;
|
|
14
|
+
const PORT_MAX = 48999;
|
|
15
|
+
|
|
16
|
+
// Resolves true when nothing is listening on `port` (all interfaces).
|
|
17
|
+
function portFree(port) {
|
|
18
|
+
return new Promise((resolve) => {
|
|
19
|
+
const server = net.createServer();
|
|
20
|
+
server.once('error', () => resolve(false));
|
|
21
|
+
server.listen({ port, exclusive: true }, () => server.close(() => resolve(true)));
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Reserves a free port for this process; `preferred` (a resumed session's
|
|
26
|
+
// previous port) is tried first. Returns {port, release}, or null when the
|
|
27
|
+
// whole range is taken.
|
|
28
|
+
async function reservePort({ env = process.env, preferred = null } = {}) {
|
|
29
|
+
const dir = path.join(rootDir(env), 'ports');
|
|
30
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
31
|
+
const span = PORT_MAX - PORT_MIN + 1;
|
|
32
|
+
const start = Math.floor(Math.random() * span);
|
|
33
|
+
const candidates = [];
|
|
34
|
+
if (Number.isInteger(preferred) && preferred >= PORT_MIN && preferred <= PORT_MAX) candidates.push(preferred);
|
|
35
|
+
for (let i = 0; i < span; i++) candidates.push(PORT_MIN + ((start + i) % span));
|
|
36
|
+
for (const port of candidates) {
|
|
37
|
+
const release = claimLockFile(path.join(dir, `${port}.lock`));
|
|
38
|
+
if (!release) continue;
|
|
39
|
+
if (await portFree(port)) return { port, release };
|
|
40
|
+
release();
|
|
41
|
+
}
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
module.exports = { reservePort, portFree, PORT_MIN, PORT_MAX };
|
package/lib/skills.js
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// The orchestrator skills shipped in the package, and where
|
|
3
|
+
// `zcode-agent skills` installs them:
|
|
4
|
+
//
|
|
5
|
+
// skills/claude-code/zcode-agent -> ~/.claude/skills/zcode-agent
|
|
6
|
+
// skills/codex/zcode-agent -> ${CODEX_HOME:-~/.codex}/skills/zcode-agent
|
|
7
|
+
//
|
|
8
|
+
// Only the zcode-agent skill directory is ever replaced or removed — plus
|
|
9
|
+
// the pre-1.0 `zcode` skill directory when its SKILL.md is ours (name: zcode),
|
|
10
|
+
// so an upgraded machine doesn't keep two skills for the same CLI.
|
|
11
|
+
const fs = require('node:fs');
|
|
12
|
+
const os = require('node:os');
|
|
13
|
+
const path = require('node:path');
|
|
14
|
+
|
|
15
|
+
const pkgRoot = path.join(__dirname, '..');
|
|
16
|
+
const PLATFORMS = ['claude', 'codex'];
|
|
17
|
+
const NAME = 'zcode-agent';
|
|
18
|
+
const LEGACY_NAME = 'zcode';
|
|
19
|
+
|
|
20
|
+
function targets(env = process.env) {
|
|
21
|
+
const home = env.HOME || os.homedir();
|
|
22
|
+
const claudeSkills = path.join(home, '.claude', 'skills');
|
|
23
|
+
const codexSkills = path.join(env.CODEX_HOME || path.join(home, '.codex'), 'skills');
|
|
24
|
+
return [
|
|
25
|
+
{
|
|
26
|
+
platform: 'claude',
|
|
27
|
+
name: 'Claude Code',
|
|
28
|
+
from: path.join(pkgRoot, 'skills', 'claude-code', NAME),
|
|
29
|
+
to: path.join(claudeSkills, NAME),
|
|
30
|
+
legacy: path.join(claudeSkills, LEGACY_NAME),
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
platform: 'codex',
|
|
34
|
+
name: 'Codex',
|
|
35
|
+
from: path.join(pkgRoot, 'skills', 'codex', NAME),
|
|
36
|
+
to: path.join(codexSkills, NAME),
|
|
37
|
+
legacy: path.join(codexSkills, LEGACY_NAME),
|
|
38
|
+
},
|
|
39
|
+
];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function select(platforms, env) {
|
|
43
|
+
const want = platforms && platforms.length ? new Set(platforms) : new Set(PLATFORMS);
|
|
44
|
+
return targets(env).filter((t) => want.has(t.platform));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// The pre-1.0 skill is ours only when its frontmatter says `name: zcode`.
|
|
48
|
+
function isLegacyOurs(dir) {
|
|
49
|
+
try {
|
|
50
|
+
return /^---\r?\nname:\s*zcode\s*\r?\n/.test(fs.readFileSync(path.join(dir, 'SKILL.md'), 'utf8'));
|
|
51
|
+
} catch {
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function removeLegacy(t) {
|
|
57
|
+
if (!isLegacyOurs(t.legacy)) return false;
|
|
58
|
+
fs.rmSync(t.legacy, { recursive: true, force: true });
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function installSkills({ platforms, env = process.env } = {}) {
|
|
63
|
+
const done = [];
|
|
64
|
+
for (const t of select(platforms, env)) {
|
|
65
|
+
fs.mkdirSync(path.dirname(t.to), { recursive: true });
|
|
66
|
+
fs.rmSync(t.to, { recursive: true, force: true });
|
|
67
|
+
fs.cpSync(t.from, t.to, { recursive: true });
|
|
68
|
+
done.push({ ...t, legacyRemoved: removeLegacy(t) });
|
|
69
|
+
}
|
|
70
|
+
return done;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function uninstallSkills({ platforms, env = process.env } = {}) {
|
|
74
|
+
const done = [];
|
|
75
|
+
for (const t of select(platforms, env)) {
|
|
76
|
+
const legacyRemoved = removeLegacy(t);
|
|
77
|
+
if (!fs.existsSync(t.to) && !legacyRemoved) continue;
|
|
78
|
+
fs.rmSync(t.to, { recursive: true, force: true });
|
|
79
|
+
done.push({ ...t, legacyRemoved });
|
|
80
|
+
}
|
|
81
|
+
return done;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function skillStatus({ env = process.env } = {}) {
|
|
85
|
+
return targets(env).map((t) => ({
|
|
86
|
+
...t,
|
|
87
|
+
installed: fs.existsSync(path.join(t.to, 'SKILL.md')),
|
|
88
|
+
legacy: isLegacyOurs(t.legacy) ? t.legacy : null,
|
|
89
|
+
}));
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
module.exports = { installSkills, uninstallSkills, skillStatus, targets, PLATFORMS };
|