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/isolation.js
ADDED
|
@@ -0,0 +1,625 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Scratch-HOME isolation (DESIGN §6, reworked in 0.4): the engine runs with
|
|
3
|
+
// HOME pointed at a directory we own so the live ~/.zcode — which the
|
|
4
|
+
// desktop app is actively using — is never written by us, and the user's
|
|
5
|
+
// OAuth credentials.json is never copied.
|
|
6
|
+
//
|
|
7
|
+
// 0.4: one engine HOME per zcode session (<root>/sessions/<id>/home) instead
|
|
8
|
+
// of one shared HOME. The shared HOME was rm -rf'd and rebuilt whenever a
|
|
9
|
+
// volatile desktop file (agents-state.json, bot-config.v3.json, …) changed
|
|
10
|
+
// mtime — which deleted the engine's session database under every other
|
|
11
|
+
// session and made --session resume 404 — and per-run MCP/skills overlays
|
|
12
|
+
// rewrote files that concurrent runs were reading. Per-session HOMEs give
|
|
13
|
+
// each session its own engine DB, config and skills; config files are
|
|
14
|
+
// refreshed in place on every invocation and engine state (cli/db,
|
|
15
|
+
// cli/agents, rollout, logs) is never deleted.
|
|
16
|
+
//
|
|
17
|
+
// Invariant (§6.4): zcode performs no writes to the live ~/.zcode, and
|
|
18
|
+
// credentials.json is never copied.
|
|
19
|
+
const fs = require('node:fs');
|
|
20
|
+
const path = require('node:path');
|
|
21
|
+
const os = require('node:os');
|
|
22
|
+
const crypto = require('node:crypto');
|
|
23
|
+
const { DEFAULT_MODEL } = require('./models.js');
|
|
24
|
+
|
|
25
|
+
// The desktop app's live directory. ZAI_CODE_LIVE_DIR points elsewhere
|
|
26
|
+
// (e.g. a second desktop profile, or a fixture in tests).
|
|
27
|
+
function liveDir(env = process.env) {
|
|
28
|
+
return env.ZAI_CODE_LIVE_DIR || path.join(os.homedir(), '.zcode');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const LIVE_ZCODE = liveDir({});
|
|
32
|
+
const LIVE_V2 = path.join(LIVE_ZCODE, 'v2');
|
|
33
|
+
|
|
34
|
+
// v2 top-level entries we deliberately never copy.
|
|
35
|
+
const V2_EXCLUDE_FILES = new Set(['credentials.json', '.DS_Store']);
|
|
36
|
+
function isV2Excluded(name) {
|
|
37
|
+
return V2_EXCLUDE_FILES.has(name) || name.startsWith('tasks-index.sqlite');
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Root of zcode-agent's own state. MUST NOT be ~/.zcode: that is the
|
|
41
|
+
// desktop app's live directory (0.3.0/0.3.1 regression — the package rename
|
|
42
|
+
// made rootDir collide with it). Ours is ~/.zcode-agent (~/.zcode-cli
|
|
43
|
+
// before 1.0, migrated by migrateRoot).
|
|
44
|
+
function rootDir(env = process.env) {
|
|
45
|
+
return env.ZAI_CODE_HOME || path.join(os.homedir(), '.zcode-agent');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function legacyRootDir() {
|
|
49
|
+
return path.join(os.homedir(), '.zcode-cli');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// --- small fs helpers ---------------------------------------------------------
|
|
53
|
+
|
|
54
|
+
function writeJson600(file, value) {
|
|
55
|
+
fs.writeFileSync(file, JSON.stringify(value, null, 2) + '\n', { mode: 0o600 });
|
|
56
|
+
fs.chmodSync(file, 0o600);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function readJson(file) {
|
|
60
|
+
try {
|
|
61
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
62
|
+
} catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function listDir(dir) {
|
|
68
|
+
try {
|
|
69
|
+
return fs.readdirSync(dir, { withFileTypes: true });
|
|
70
|
+
} catch {
|
|
71
|
+
return [];
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// --- provider/key rewriting -----------------------------------------------------
|
|
76
|
+
|
|
77
|
+
// Prune to exactly the zai-api rule and swap in the package key (§6.2 item 2).
|
|
78
|
+
function rewriteProviderConfig(target, key) {
|
|
79
|
+
const parsed = JSON.parse(fs.readFileSync(target, 'utf8'));
|
|
80
|
+
const rules =
|
|
81
|
+
parsed.config &&
|
|
82
|
+
parsed.config.providerConfigRules &&
|
|
83
|
+
parsed.config.providerConfigRules.providerRules;
|
|
84
|
+
if (!Array.isArray(rules)) {
|
|
85
|
+
throw new Error(`unexpected provider_config.json shape at ${target}`);
|
|
86
|
+
}
|
|
87
|
+
const zaiRules = rules.filter((r) => r && r.providerId === 'zai-api');
|
|
88
|
+
if (zaiRules.length === 0) {
|
|
89
|
+
throw new Error(`no zai-api rule found in provider_config.json at ${target}`);
|
|
90
|
+
}
|
|
91
|
+
const rule = zaiRules[0];
|
|
92
|
+
rule.config = rule.config || {};
|
|
93
|
+
rule.config.group = rule.config.group || 'standard-personal';
|
|
94
|
+
rule.config.access = { type: 'api-key', apiKey: key };
|
|
95
|
+
parsed.config.providerConfigRules.providerRules = [rule];
|
|
96
|
+
writeJson600(target, parsed);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Standalone (no app config to copy). modelConfigRules must be present,
|
|
100
|
+
// even empty: without it the engine registers no zai-api models and
|
|
101
|
+
// session/create fails with "Provider Registry 中不存在 Model:
|
|
102
|
+
// zai-api/GLM-5.3-Flash" (1.0, live-probed).
|
|
103
|
+
function synthesizedProviderConfig(key) {
|
|
104
|
+
return {
|
|
105
|
+
schemaVersion: 1,
|
|
106
|
+
config: {
|
|
107
|
+
modelConfigRules: { providerModelRules: [], manualProviderModelRules: [] },
|
|
108
|
+
providerConfigRules: {
|
|
109
|
+
providerRules: [
|
|
110
|
+
{
|
|
111
|
+
providerId: 'zai-api',
|
|
112
|
+
templateId: 'zai-api',
|
|
113
|
+
config: {
|
|
114
|
+
group: 'standard-personal',
|
|
115
|
+
access: { type: 'api-key', apiKey: key },
|
|
116
|
+
},
|
|
117
|
+
},
|
|
118
|
+
],
|
|
119
|
+
},
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// --- skills -------------------------------------------------------------------
|
|
125
|
+
|
|
126
|
+
// A --skills dir is either one skill (<dir>/SKILL.md) or a skills root
|
|
127
|
+
// (<dir>/<name>/SKILL.md). Returns [{name, dir}] of copyable skills.
|
|
128
|
+
function discoverSkillDirs(dir) {
|
|
129
|
+
if (fs.existsSync(path.join(dir, 'SKILL.md'))) {
|
|
130
|
+
return [{ name: path.basename(path.resolve(dir)), dir }];
|
|
131
|
+
}
|
|
132
|
+
return listDir(dir)
|
|
133
|
+
.filter((e) => e.isDirectory() && fs.existsSync(path.join(dir, e.name, 'SKILL.md')))
|
|
134
|
+
.map((e) => ({ name: e.name, dir: path.join(dir, e.name) }));
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// --- MCP ----------------------------------------------------------------------
|
|
138
|
+
|
|
139
|
+
// The live desktop MCP servers, read-only, honoring `enabled`.
|
|
140
|
+
function liveMcpServers(live = LIVE_ZCODE) {
|
|
141
|
+
const cfg = readJson(path.join(live, 'cli', 'config.json'));
|
|
142
|
+
const servers = cfg && cfg.mcp && cfg.mcp.servers;
|
|
143
|
+
if (!servers || typeof servers !== 'object') return {};
|
|
144
|
+
const out = {};
|
|
145
|
+
for (const [name, def] of Object.entries(servers)) {
|
|
146
|
+
if (!def || typeof def !== 'object' || def.enabled === false) continue;
|
|
147
|
+
out[name] = def;
|
|
148
|
+
}
|
|
149
|
+
return out;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Effective set for one invocation (1.0): the desktop's enabled servers
|
|
153
|
+
// are inherited by default, so people with the app get its MCP tools with
|
|
154
|
+
// no setup; --hermetic (inherit:false) keeps only the caller's --mcp
|
|
155
|
+
// servers. Specs always win by name. Remote servers that authenticate by
|
|
156
|
+
// OAuth are left out: their tokens live in the desktop's credentials.json,
|
|
157
|
+
// which is never copied, so they could only fail (and, live-probed in 0.4,
|
|
158
|
+
// stall the engine's connect pool) in a headless session.
|
|
159
|
+
// The desktop's local browser server (stdio, no OAuth) is inherited even
|
|
160
|
+
// when hermetic, so browser prompts open the same Playwright window the
|
|
161
|
+
// desktop opens. --no-browser drops it.
|
|
162
|
+
const BROWSER_SERVERS = ['playwright'];
|
|
163
|
+
|
|
164
|
+
// Standalone (no ZCode app, or an app without a Playwright server): the
|
|
165
|
+
// executor and the verifier still need a browser. Pinned so `zcode-agent
|
|
166
|
+
// doctor --install-browser` installs the exact Chromium build it drives.
|
|
167
|
+
const PLAYWRIGHT_MCP_VERSION = '0.0.83';
|
|
168
|
+
const DEFAULT_BROWSER_SERVER = {
|
|
169
|
+
command: 'npx',
|
|
170
|
+
args: ['-y', `@playwright/mcp@${PLAYWRIGHT_MCP_VERSION}`, '--isolated', '--headless', '--browser', 'chromium'],
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
// The inherited Playwright MCP runs --isolated (0.7.1): a fresh in-memory
|
|
174
|
+
// profile per engine. A persistent profile in the session HOME was shared by
|
|
175
|
+
// the implementer's and every verifier's browser: "Browser is already in
|
|
176
|
+
// use" errors cost retries, and the verifier judged stale cached pages.
|
|
177
|
+
// A def that already picks its profile (--isolated, --user-data-dir) is kept.
|
|
178
|
+
function isolatedBrowser(def) {
|
|
179
|
+
const args = Array.isArray(def.args) ? def.args : [];
|
|
180
|
+
const isPlaywright = [def.command, ...args].some((a) => /@playwright\/mcp|playwright-mcp/.test(String(a)));
|
|
181
|
+
if (!isPlaywright || args.some((a) => /^--(isolated|user-data-dir)\b/.test(String(a)))) return def;
|
|
182
|
+
return { ...def, args: [...args, '--isolated'] };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// A remote server is treated as OAuth unless it carries its own static
|
|
186
|
+
// credentials (headers, or a key/token in the URL) or is a known public
|
|
187
|
+
// endpoint that needs no auth. The desktop's OAuth state is keyed by an
|
|
188
|
+
// opaque id, so it can't tell which servers hold tokens.
|
|
189
|
+
const PUBLIC_MCP_HOSTS = [
|
|
190
|
+
/(^|\.)context7\.com$/,
|
|
191
|
+
/^docs\.mcp\.cloudflare\.com$/,
|
|
192
|
+
/^mcp\.exa\.ai$/,
|
|
193
|
+
/^gitmcp\.io$/,
|
|
194
|
+
];
|
|
195
|
+
|
|
196
|
+
function isRemote(def) {
|
|
197
|
+
return typeof def.url === 'string' && !def.command;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function needsOAuth(def) {
|
|
201
|
+
if (!isRemote(def)) return false;
|
|
202
|
+
if (def.headers && Object.keys(def.headers).length) return false;
|
|
203
|
+
let url;
|
|
204
|
+
try {
|
|
205
|
+
url = new URL(def.url);
|
|
206
|
+
} catch {
|
|
207
|
+
return true;
|
|
208
|
+
}
|
|
209
|
+
if (/oauth/i.test(url.pathname)) return true;
|
|
210
|
+
if ([...url.searchParams.keys()].some((k) => /key|token/i.test(k))) return false;
|
|
211
|
+
return !PUBLIC_MCP_HOSTS.some((re) => re.test(url.hostname));
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function inheritableMcpServers(live = LIVE_ZCODE) {
|
|
215
|
+
const out = {};
|
|
216
|
+
for (const [name, def] of Object.entries(liveMcpServers(live))) {
|
|
217
|
+
if (!needsOAuth(def)) out[name] = def;
|
|
218
|
+
}
|
|
219
|
+
return out;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Inherited servers that failed to connect are remembered for a while
|
|
223
|
+
// (<root>/mcp-health.json), so one dead server costs one session its
|
|
224
|
+
// connect timeout, not every session. Keyed by name + a hash of the
|
|
225
|
+
// server's definition: editing the server in the app retries it at once.
|
|
226
|
+
const MCP_RETRY_AFTER_MS = 6 * 60 * 60 * 1000;
|
|
227
|
+
|
|
228
|
+
function mcpSignature(def) {
|
|
229
|
+
return crypto.createHash('sha256').update(JSON.stringify(def)).digest('hex').slice(0, 16);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function mcpHealthFile(root) {
|
|
233
|
+
return path.join(root, 'mcp-health.json');
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function readMcpHealth(root) {
|
|
237
|
+
return (root && readJson(mcpHealthFile(root))) || {};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// Names from `health` whose failure is recent and whose definition is
|
|
241
|
+
// unchanged.
|
|
242
|
+
function unhealthyMcp(servers, health, now = Date.now()) {
|
|
243
|
+
return Object.keys(servers).filter((name) => {
|
|
244
|
+
const h = health[name];
|
|
245
|
+
return h && h.sig === mcpSignature(servers[name]) && now - h.failedAt < MCP_RETRY_AFTER_MS;
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// statuses: the engine's mcp/list status map; inherited: {name: def} of the
|
|
250
|
+
// inherited servers this session registered. Failed ones are recorded,
|
|
251
|
+
// connected ones cleared. Never throws.
|
|
252
|
+
function recordMcpHealth(root, statuses, inherited, now = Date.now()) {
|
|
253
|
+
if (!root || !statuses) return;
|
|
254
|
+
try {
|
|
255
|
+
const health = readMcpHealth(root);
|
|
256
|
+
let changed = false;
|
|
257
|
+
for (const [name, def] of Object.entries(inherited)) {
|
|
258
|
+
const state = statuses[name] && statuses[name].status;
|
|
259
|
+
if (state === 'failed') {
|
|
260
|
+
const error = statuses[name].error;
|
|
261
|
+
health[name] = {
|
|
262
|
+
sig: mcpSignature(def),
|
|
263
|
+
failedAt: now,
|
|
264
|
+
error: error ? String(typeof error === 'string' ? error : JSON.stringify(error)).slice(0, 200) : null,
|
|
265
|
+
};
|
|
266
|
+
changed = true;
|
|
267
|
+
} else if (state === 'connected' && health[name]) {
|
|
268
|
+
delete health[name];
|
|
269
|
+
changed = true;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
if (!changed) return;
|
|
273
|
+
const file = mcpHealthFile(root);
|
|
274
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
275
|
+
fs.writeFileSync(tmp, JSON.stringify(health, null, 2) + '\n');
|
|
276
|
+
fs.renameSync(tmp, file);
|
|
277
|
+
} catch {
|
|
278
|
+
/* health is an optimisation; a failed write just retries the server */
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function effectiveMcpServers({ inherit = true, browser = true, mcpSpecs = [], live = LIVE_ZCODE, health = {} } = {}) {
|
|
283
|
+
const liveSet = liveMcpServers(live);
|
|
284
|
+
const servers = inherit ? inheritableMcpServers(live) : {};
|
|
285
|
+
for (const name of unhealthyMcp(servers, health)) {
|
|
286
|
+
if (!BROWSER_SERVERS.includes(name)) delete servers[name];
|
|
287
|
+
}
|
|
288
|
+
for (const name of BROWSER_SERVERS) {
|
|
289
|
+
if (!browser) delete servers[name];
|
|
290
|
+
else if (liveSet[name]) servers[name] = isolatedBrowser(liveSet[name]);
|
|
291
|
+
}
|
|
292
|
+
if (browser && !BROWSER_SERVERS.some((n) => servers[n])) {
|
|
293
|
+
servers[BROWSER_SERVERS[0]] = DEFAULT_BROWSER_SERVER;
|
|
294
|
+
}
|
|
295
|
+
for (const spec of mcpSpecs) {
|
|
296
|
+
for (const [name, def] of Object.entries(spec)) servers[name] = def;
|
|
297
|
+
}
|
|
298
|
+
return servers;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// --- shared caches ------------------------------------------------------------
|
|
302
|
+
|
|
303
|
+
// Engine-populated caches that are expensive to recreate per session (the
|
|
304
|
+
// plugin marketplace cache is ~30 MB) are shared through symlinks into
|
|
305
|
+
// <root>/shared. A pre-0.4 shared HOME donates its caches once.
|
|
306
|
+
const SHARED_CACHES = [
|
|
307
|
+
{ name: 'plugins', rel: path.join('.zcode', 'cli', 'plugins') },
|
|
308
|
+
{ name: 'runtime', rel: path.join('.zcode', 'v2', 'runtime') },
|
|
309
|
+
];
|
|
310
|
+
|
|
311
|
+
function linkSharedCaches(home, root) {
|
|
312
|
+
for (const cache of SHARED_CACHES) {
|
|
313
|
+
const shared = path.join(root, 'shared', cache.name);
|
|
314
|
+
if (!fs.existsSync(shared)) {
|
|
315
|
+
const legacy = path.join(root, 'home', cache.rel);
|
|
316
|
+
fs.mkdirSync(path.dirname(shared), { recursive: true, mode: 0o700 });
|
|
317
|
+
try {
|
|
318
|
+
if (fs.existsSync(legacy) && !fs.lstatSync(legacy).isSymbolicLink()) {
|
|
319
|
+
fs.renameSync(legacy, shared);
|
|
320
|
+
}
|
|
321
|
+
} catch {
|
|
322
|
+
/* fall through to an empty cache */
|
|
323
|
+
}
|
|
324
|
+
fs.mkdirSync(shared, { recursive: true, mode: 0o700 });
|
|
325
|
+
}
|
|
326
|
+
const target = path.join(home, cache.rel);
|
|
327
|
+
if (fs.existsSync(target) || isDanglingLink(target)) continue;
|
|
328
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
329
|
+
try {
|
|
330
|
+
fs.symlinkSync(shared, target, 'dir');
|
|
331
|
+
} catch {
|
|
332
|
+
/* engine recreates the cache itself */
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function isDanglingLink(p) {
|
|
338
|
+
try {
|
|
339
|
+
return fs.lstatSync(p).isSymbolicLink() && !fs.existsSync(p);
|
|
340
|
+
} catch {
|
|
341
|
+
return false;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// --- build ------------------------------------------------------------------
|
|
346
|
+
|
|
347
|
+
// Creates or refreshes one engine HOME. Config is (re)written from the live
|
|
348
|
+
// sources + this invocation's flags; engine state under the HOME (cli/db,
|
|
349
|
+
// cli/agents, cli/rollout, logs, memories) is never touched, so a session
|
|
350
|
+
// stays resumable across invocations. Returns facts for reporting.
|
|
351
|
+
// Desktop skills that drive the app's own UI (the built-in browser pane):
|
|
352
|
+
// the CLI cannot serve them, and loading one steers the agent away from
|
|
353
|
+
// Playwright into a dead end.
|
|
354
|
+
// Our own orchestrator skill is never given to the executor: it would
|
|
355
|
+
// teach the executor to delegate to zcode-agent again.
|
|
356
|
+
const HOST_ONLY_SKILLS = new Set(['control-browser', 'zcode', 'zcode-agent']);
|
|
357
|
+
|
|
358
|
+
// The executor instructions every engine HOME gets as ~/.zcode/AGENTS.md.
|
|
359
|
+
// Named so that agents working on this repo don't read it as their own.
|
|
360
|
+
const EXECUTOR_AGENTS_MD = path.join(__dirname, '..', 'assets', 'executor-agents.md');
|
|
361
|
+
// `zcode-agent acp`: a person watches and approves in the client.
|
|
362
|
+
const ACP_AGENTS_MD = path.join(__dirname, '..', 'assets', 'acp-agents.md');
|
|
363
|
+
|
|
364
|
+
// Rewrites the frontmatter `model:` of an agent profile when it names
|
|
365
|
+
// GLM-5.3 / GLM-5.3-Flash (any prefix: "account:x/GLM-5.3",
|
|
366
|
+
// "custom:account%3Ax:GLM-5.3") so its model part is `model`.
|
|
367
|
+
function pinAgentModel(text, model) {
|
|
368
|
+
const m = /^(---\r?\n)([\s\S]*?)(\r?\n---)/.exec(text);
|
|
369
|
+
if (!m) return text;
|
|
370
|
+
const front = m[2].replace(/^(\s*model\s*:\s*["']?)([^\n"']*?)(?:\/|:)GLM-5\.3(?:-Flash)?(["']?\s*)$/im, (all, a, prefix, tail) => {
|
|
371
|
+
const sep = all.slice(a.length + prefix.length, a.length + prefix.length + 1);
|
|
372
|
+
return `${a}${prefix}${sep}${model}${tail}`;
|
|
373
|
+
});
|
|
374
|
+
return m[1] + front + text.slice(m[0].length - m[3].length);
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function buildEngineHome({
|
|
378
|
+
home,
|
|
379
|
+
root,
|
|
380
|
+
key,
|
|
381
|
+
live = LIVE_ZCODE,
|
|
382
|
+
mcpSpecs = [],
|
|
383
|
+
hermetic = false,
|
|
384
|
+
browser = true,
|
|
385
|
+
skillsDirs = [],
|
|
386
|
+
noSkills = false,
|
|
387
|
+
inheritDesktop = false,
|
|
388
|
+
profile = null,
|
|
389
|
+
model = DEFAULT_MODEL,
|
|
390
|
+
instructions = EXECUTOR_AGENTS_MD,
|
|
391
|
+
}) {
|
|
392
|
+
const zdir = path.join(home, '.zcode');
|
|
393
|
+
const v2 = path.join(zdir, 'v2');
|
|
394
|
+
const cliDir = path.join(zdir, 'cli');
|
|
395
|
+
fs.mkdirSync(v2, { recursive: true, mode: 0o700 });
|
|
396
|
+
fs.mkdirSync(cliDir, { recursive: true, mode: 0o700 });
|
|
397
|
+
fs.chmodSync(home, 0o700);
|
|
398
|
+
|
|
399
|
+
// v2: top-level files only, no credentials.json, no sqlite (§6.2 item 1).
|
|
400
|
+
const liveV2 = path.join(live, 'v2');
|
|
401
|
+
const v2Files = listDir(liveV2).filter((e) => e.isFile() && !isV2Excluded(e.name));
|
|
402
|
+
for (const entry of v2Files) {
|
|
403
|
+
fs.copyFileSync(path.join(liveV2, entry.name), path.join(v2, entry.name));
|
|
404
|
+
}
|
|
405
|
+
const providerConfig = path.join(v2, 'provider_config.json');
|
|
406
|
+
const mode = v2Files.some((e) => e.name === 'provider_config.json')
|
|
407
|
+
? 'copied-v2-top-level'
|
|
408
|
+
: 'synthesized';
|
|
409
|
+
if (mode === 'synthesized') writeJson600(providerConfig, synthesizedProviderConfig(key));
|
|
410
|
+
else rewriteProviderConfig(providerConfig, key);
|
|
411
|
+
|
|
412
|
+
// cli/config.json: live copy (builtin:zai key swapped) + this run's MCP set.
|
|
413
|
+
const cfg = readJson(path.join(live, 'cli', 'config.json')) || {};
|
|
414
|
+
const zai = cfg.provider && cfg.provider['builtin:zai'];
|
|
415
|
+
if (zai) {
|
|
416
|
+
zai.options = zai.options || {};
|
|
417
|
+
zai.options.apiKey = key;
|
|
418
|
+
}
|
|
419
|
+
const health = readMcpHealth(root);
|
|
420
|
+
const servers = effectiveMcpServers({ inherit: !hermetic, browser, mcpSpecs, live, health });
|
|
421
|
+
const added = mcpSpecs.flatMap((spec) => Object.keys(spec));
|
|
422
|
+
const inheritedNames = hermetic ? [] : Object.keys(inheritableMcpServers(live));
|
|
423
|
+
const inherited = Object.fromEntries(
|
|
424
|
+
Object.entries(servers).filter(([name]) => inheritedNames.includes(name) && !added.includes(name))
|
|
425
|
+
);
|
|
426
|
+
const skippedUnhealthy = hermetic ? [] : unhealthyMcp(inheritableMcpServers(live), health).filter((n) => !servers[n]);
|
|
427
|
+
cfg.mcp = { ...(cfg.mcp || {}), servers };
|
|
428
|
+
// The desktop's plugins (browser-use, computer-use, …) inject skills and
|
|
429
|
+
// tools meant for the app's own UI; the executor gets none unless
|
|
430
|
+
// --inherit-desktop.
|
|
431
|
+
if (!inheritDesktop) cfg.plugins = { ...(cfg.plugins || {}), enabled: false };
|
|
432
|
+
writeJson600(path.join(cliDir, 'config.json'), cfg);
|
|
433
|
+
|
|
434
|
+
// Agent profiles: only the profile this run names, unless
|
|
435
|
+
// --inherit-desktop mirrors the live set.
|
|
436
|
+
const agentsDir = path.join(zdir, 'agents');
|
|
437
|
+
fs.rmSync(agentsDir, { recursive: true, force: true });
|
|
438
|
+
for (const entry of listDir(path.join(live, 'agents'))) {
|
|
439
|
+
if (!entry.isFile() || !entry.name.endsWith('.md')) continue;
|
|
440
|
+
if (!inheritDesktop && entry.name !== `${profile}.md`) continue;
|
|
441
|
+
fs.mkdirSync(agentsDir, { recursive: true });
|
|
442
|
+
// Profiles pinning a GLM-5.3 id would silently run another model than
|
|
443
|
+
// the session's: the copy follows the session (the live file is never edited).
|
|
444
|
+
const text = fs.readFileSync(path.join(live, 'agents', entry.name), 'utf8');
|
|
445
|
+
fs.writeFileSync(path.join(agentsDir, entry.name), pinAgentModel(text, model));
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// AGENTS.md: the package's own executor instructions (1.0). The desktop's
|
|
449
|
+
// AGENTS.md is the user's guidance for interactive work (companion files
|
|
450
|
+
// to read, skills to load, deploy rules); handed to an executor with a
|
|
451
|
+
// binding contract it was re-litigated in the model's reasoning for
|
|
452
|
+
// minutes per session (0.7.1), so it is appended only with
|
|
453
|
+
// --inherit-desktop.
|
|
454
|
+
const agentsMd = path.join(zdir, 'AGENTS.md');
|
|
455
|
+
const parts = [fs.readFileSync(instructions, 'utf8').trim()];
|
|
456
|
+
if (inheritDesktop && fs.existsSync(path.join(live, 'AGENTS.md'))) {
|
|
457
|
+
parts.push(fs.readFileSync(path.join(live, 'AGENTS.md'), 'utf8').trim());
|
|
458
|
+
}
|
|
459
|
+
fs.writeFileSync(agentsMd, parts.join('\n\n') + '\n');
|
|
460
|
+
|
|
461
|
+
// Skills: the desktop's user skills (1.0: inherited by default; not with
|
|
462
|
+
// --hermetic or --no-skills), then this run's --skills on top.
|
|
463
|
+
// Project skills (<cwd>/.zcode/skills) need no copy — the engine reads
|
|
464
|
+
// them from the real workspace.
|
|
465
|
+
const skillsDir = path.join(zdir, 'skills');
|
|
466
|
+
fs.rmSync(skillsDir, { recursive: true, force: true });
|
|
467
|
+
fs.mkdirSync(skillsDir, { recursive: true });
|
|
468
|
+
let skillsCopied = 0;
|
|
469
|
+
if (!noSkills && !hermetic) {
|
|
470
|
+
// Most desktop skills are symlinks into ~/.claude/skills or ~/.agents:
|
|
471
|
+
// follow them, and copy the target (the session HOME must not point
|
|
472
|
+
// back into live directories).
|
|
473
|
+
const liveSkills = path.join(live, 'skills');
|
|
474
|
+
for (const entry of listDir(liveSkills)) {
|
|
475
|
+
if (HOST_ONLY_SKILLS.has(entry.name)) continue;
|
|
476
|
+
const from = path.join(liveSkills, entry.name);
|
|
477
|
+
if (!fs.existsSync(path.join(from, 'SKILL.md'))) continue;
|
|
478
|
+
fs.cpSync(from, path.join(skillsDir, entry.name), { recursive: true, dereference: true });
|
|
479
|
+
skillsCopied++;
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
const skillsInjected = [];
|
|
483
|
+
if (!noSkills) {
|
|
484
|
+
for (const dir of skillsDirs) {
|
|
485
|
+
for (const { name, dir: skillDir } of discoverSkillDirs(dir)) {
|
|
486
|
+
fs.rmSync(path.join(skillsDir, name), { recursive: true, force: true });
|
|
487
|
+
fs.cpSync(skillDir, path.join(skillsDir, name), { recursive: true });
|
|
488
|
+
skillsInjected.push(name);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
if (root) linkSharedCaches(home, root);
|
|
494
|
+
|
|
495
|
+
return {
|
|
496
|
+
home,
|
|
497
|
+
mode,
|
|
498
|
+
copiedFiles: v2Files.length,
|
|
499
|
+
skillsCopied,
|
|
500
|
+
skillsInjected,
|
|
501
|
+
mcp: {
|
|
502
|
+
servers,
|
|
503
|
+
// Names the caller explicitly added — the CLI waits for these to
|
|
504
|
+
// settle before sending the prompt. Inherited servers are best-effort.
|
|
505
|
+
added,
|
|
506
|
+
// The desktop's servers this session registered ({name: def}), and
|
|
507
|
+
// those left out because they failed recently (mcp-health.json).
|
|
508
|
+
inherited,
|
|
509
|
+
skippedUnhealthy,
|
|
510
|
+
},
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
// --- migration ----------------------------------------------------------------
|
|
515
|
+
|
|
516
|
+
// The only names pre-0.4 versions created at a root. migrateRoot moves
|
|
517
|
+
// exactly these out of legacy locations and never touches anything else.
|
|
518
|
+
const OUR_ARTIFACTS = ['credentials.json', 'build-stamp.json', 'injected-skills.json', 'home'];
|
|
519
|
+
|
|
520
|
+
// 0.3.2 migration: vacate our artifacts from (a) the live ~/.zcode, where
|
|
521
|
+
// 0.3.0/0.3.1 wrongly wrote them, and (b) the pre-rename ~/.zai-code root,
|
|
522
|
+
// into our root. Idempotent; never writes or deletes anything
|
|
523
|
+
// else in the live directory.
|
|
524
|
+
//
|
|
525
|
+
// 1.0 migration: the pre-rename ~/.zcode-cli root moves to ~/.zcode-agent
|
|
526
|
+
// whole, and a symlink is left in its place. Session records and engine
|
|
527
|
+
// HOMEs hold absolute paths under the old root; the link keeps them (and
|
|
528
|
+
// any still-running pre-1.0 process) resolving.
|
|
529
|
+
function migrateLegacyRoot(root) {
|
|
530
|
+
const legacy = legacyRootDir();
|
|
531
|
+
try {
|
|
532
|
+
if (fs.existsSync(root) || !fs.lstatSync(legacy).isDirectory()) return;
|
|
533
|
+
fs.renameSync(legacy, root);
|
|
534
|
+
fs.symlinkSync(root, legacy, 'dir');
|
|
535
|
+
} catch {
|
|
536
|
+
/* no legacy root, or it stays where it is; nothing is lost */
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
function migrateRoot(env = process.env) {
|
|
541
|
+
const root = rootDir(env);
|
|
542
|
+
if (!env.ZAI_CODE_HOME) migrateLegacyRoot(root);
|
|
543
|
+
try {
|
|
544
|
+
fs.mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
545
|
+
} catch {
|
|
546
|
+
return; // unwritable home — callers surface it
|
|
547
|
+
}
|
|
548
|
+
const sources = [liveDir(env), path.join(os.homedir(), '.zai-code')];
|
|
549
|
+
for (const dir of sources) {
|
|
550
|
+
let entries;
|
|
551
|
+
try {
|
|
552
|
+
entries = new Set(fs.readdirSync(dir));
|
|
553
|
+
} catch {
|
|
554
|
+
continue;
|
|
555
|
+
}
|
|
556
|
+
for (const name of OUR_ARTIFACTS) {
|
|
557
|
+
if (!entries.has(name)) continue;
|
|
558
|
+
const src = path.join(dir, name);
|
|
559
|
+
const dest = path.join(root, name);
|
|
560
|
+
try {
|
|
561
|
+
if (fs.existsSync(dest)) fs.rmSync(src, { recursive: true, force: true });
|
|
562
|
+
else fs.renameSync(src, dest);
|
|
563
|
+
} catch {
|
|
564
|
+
/* keep going; a missing artifact just rebuilds */
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
// Env for the engine child process (§6.3): HOME=scratch, pinned builtin
|
|
571
|
+
// config, and the uncontrolled overrides deleted. cwd is set by the caller.
|
|
572
|
+
// `sessionEnv` (ZCODE_SESSION_ID, ZCODE_PORT, …) is applied last so nothing
|
|
573
|
+
// inherited can shadow it; the engine's tools inherit it.
|
|
574
|
+
function engineEnv({ home, builtinProviderConfig, parentEnv = process.env, sessionEnv = {} }) {
|
|
575
|
+
const childEnv = { ...parentEnv };
|
|
576
|
+
const realHome = parentEnv.HOME || os.homedir();
|
|
577
|
+
// The scratch HOME hides the user's tool caches. Point Playwright and npm
|
|
578
|
+
// back at the real ones so installed browsers and packages are found.
|
|
579
|
+
if (!childEnv.PLAYWRIGHT_BROWSERS_PATH) {
|
|
580
|
+
const cache = process.platform === 'darwin'
|
|
581
|
+
? path.join(realHome, 'Library', 'Caches', 'ms-playwright')
|
|
582
|
+
: path.join(realHome, '.cache', 'ms-playwright');
|
|
583
|
+
if (fs.existsSync(cache)) childEnv.PLAYWRIGHT_BROWSERS_PATH = cache;
|
|
584
|
+
}
|
|
585
|
+
if (!childEnv.npm_config_cache && !childEnv.NPM_CONFIG_CACHE) {
|
|
586
|
+
childEnv.npm_config_cache = path.join(realHome, '.npm');
|
|
587
|
+
}
|
|
588
|
+
childEnv.HOME = home;
|
|
589
|
+
childEnv.ZCODE_BUILTIN_PROVIDER_CONFIG_FILE = builtinProviderConfig;
|
|
590
|
+
for (const name of [
|
|
591
|
+
'ZCODE_STORAGE_DIR',
|
|
592
|
+
'ZCODE_DATA_BASE_DIR',
|
|
593
|
+
'ZCODE_PERSONAL_PROVIDER_CONFIG_FILE',
|
|
594
|
+
'ANTHROPIC_API_KEY',
|
|
595
|
+
'ANTHROPIC_BASE_URL',
|
|
596
|
+
]) {
|
|
597
|
+
delete childEnv[name];
|
|
598
|
+
}
|
|
599
|
+
Object.assign(childEnv, sessionEnv);
|
|
600
|
+
return childEnv;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
module.exports = {
|
|
604
|
+
buildEngineHome,
|
|
605
|
+
pinAgentModel,
|
|
606
|
+
engineEnv,
|
|
607
|
+
rootDir,
|
|
608
|
+
liveDir,
|
|
609
|
+
migrateRoot,
|
|
610
|
+
effectiveMcpServers,
|
|
611
|
+
liveMcpServers,
|
|
612
|
+
inheritableMcpServers,
|
|
613
|
+
needsOAuth,
|
|
614
|
+
EXECUTOR_AGENTS_MD,
|
|
615
|
+
ACP_AGENTS_MD,
|
|
616
|
+
DEFAULT_BROWSER_SERVER,
|
|
617
|
+
PLAYWRIGHT_MCP_VERSION,
|
|
618
|
+
readMcpHealth,
|
|
619
|
+
recordMcpHealth,
|
|
620
|
+
unhealthyMcp,
|
|
621
|
+
mcpSignature,
|
|
622
|
+
discoverSkillDirs,
|
|
623
|
+
LIVE_ZCODE,
|
|
624
|
+
LIVE_V2,
|
|
625
|
+
};
|