zcode-agent 0.0.0-stage → 1.0.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 +418 -2
- package/assets/executor-agents.md +10 -0
- package/bin/zcode-agent.js +418 -0
- package/lib/appserver.js +516 -0
- package/lib/bootstrap.js +70 -0
- package/lib/brief.js +109 -0
- package/lib/checks.js +104 -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 +329 -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 +128 -0
- package/lib/isolation.js +621 -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 +52 -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/appserver.js
ADDED
|
@@ -0,0 +1,516 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// NDJSON client for `zcode.cjs app-server --stdio` (DESIGN §9) plus the
|
|
3
|
+
// one-turn orchestration shared by `run` and `agent`.
|
|
4
|
+
//
|
|
5
|
+
// Wire facts (live-probed against engine v0.16.9; see DESIGN §9):
|
|
6
|
+
// - one JSON object per line, both directions; our request ids are numbers,
|
|
7
|
+
// server-directed request ids are strings ("server-2"); answers repeat
|
|
8
|
+
// THEIR id. A "jsonrpc" key must NOT be sent.
|
|
9
|
+
// - session/create result: result.session.{sessionId, mode, model, …}
|
|
10
|
+
// (mode param in create is NOT honored — session/setMode is required).
|
|
11
|
+
// - completion: session/event with params.type "turn.completed"
|
|
12
|
+
// (payload.response is the authoritative final text, payload.usage the
|
|
13
|
+
// usage); computer-use/operation-event kind "turn-completed" and
|
|
14
|
+
// v4/telemetry/event kind "turn.terminal" corroborate.
|
|
15
|
+
// - engine-reported model evidence: session/event params.type
|
|
16
|
+
// "session.updated" with payload.type "model_request_started"
|
|
17
|
+
// ({providerId, modelId, modelCall.reasoning.requestedLevel}).
|
|
18
|
+
const { spawn } = require('node:child_process');
|
|
19
|
+
const readline = require('node:readline');
|
|
20
|
+
const crypto = require('node:crypto');
|
|
21
|
+
const fs = require('node:fs');
|
|
22
|
+
|
|
23
|
+
const RUNTIME_PREFERENCES = {
|
|
24
|
+
nativeSearchEnhancementsEnabled: false,
|
|
25
|
+
memoryEnabled: false,
|
|
26
|
+
askUserQuestionAutoResolutionEnabled: true,
|
|
27
|
+
modelContextBudgetStrategy: 'preflight-v1',
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
class TurnError extends Error {
|
|
31
|
+
constructor(message, { kind = 'turn_failed' } = {}) {
|
|
32
|
+
super(message);
|
|
33
|
+
this.kind = kind;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
class AppServerClient {
|
|
38
|
+
constructor({ nodeBin, enginePath, env, cwd, scrub = (s) => s }) {
|
|
39
|
+
this.nodeBin = nodeBin;
|
|
40
|
+
this.enginePath = enginePath;
|
|
41
|
+
this.env = env;
|
|
42
|
+
this.cwd = cwd;
|
|
43
|
+
this.scrub = scrub;
|
|
44
|
+
this.child = null;
|
|
45
|
+
this.nextId = 1;
|
|
46
|
+
this.pending = new Map();
|
|
47
|
+
this.onFrame = null; // (frame) => void for every notification
|
|
48
|
+
this.dead = false;
|
|
49
|
+
this.engineStderr = '';
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
start() {
|
|
53
|
+
// Own process group, so kill() takes the engine's tool subprocesses and
|
|
54
|
+
// stdio MCP servers with it (a runaway shell command must not keep
|
|
55
|
+
// writing to the workspace after cancel/timeout).
|
|
56
|
+
this.child = spawn(this.nodeBin, [this.enginePath, 'app-server', '--stdio'], {
|
|
57
|
+
env: this.env,
|
|
58
|
+
cwd: this.cwd,
|
|
59
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
60
|
+
detached: true,
|
|
61
|
+
});
|
|
62
|
+
this.child.stderr.on('data', (d) => {
|
|
63
|
+
this.engineStderr += d;
|
|
64
|
+
if (this.engineStderr.length > 20000) {
|
|
65
|
+
this.engineStderr = this.engineStderr.slice(-20000);
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
// EPIPE on a dying engine and spawn failures (bad ZAI_CODE_NODE) must
|
|
69
|
+
// surface as a failed request, never as an uncaught 'error' event.
|
|
70
|
+
this.child.stdin.on('error', () => {});
|
|
71
|
+
this.child.on('error', (err) => {
|
|
72
|
+
if (this.dead) return;
|
|
73
|
+
this.dead = true;
|
|
74
|
+
const wrapped = new Error(`engine app-server failed to start: ${err.message}`);
|
|
75
|
+
for (const { reject, timer } of this.pending.values()) {
|
|
76
|
+
clearTimeout(timer);
|
|
77
|
+
reject(wrapped);
|
|
78
|
+
}
|
|
79
|
+
this.pending.clear();
|
|
80
|
+
if (this.onExit) this.onExit(wrapped);
|
|
81
|
+
});
|
|
82
|
+
this.child.on('exit', (code, signal) => {
|
|
83
|
+
this.dead = true;
|
|
84
|
+
const err = new Error(
|
|
85
|
+
`engine app-server exited (code=${code} signal=${signal})` +
|
|
86
|
+
(this.engineStderr ? `\nengine stderr tail: ${this.engineStderr.split('\n').slice(-8).join('\n')}` : '')
|
|
87
|
+
);
|
|
88
|
+
for (const { reject, timer } of this.pending.values()) {
|
|
89
|
+
clearTimeout(timer);
|
|
90
|
+
reject(err);
|
|
91
|
+
}
|
|
92
|
+
this.pending.clear();
|
|
93
|
+
if (this.onExit) this.onExit(err);
|
|
94
|
+
});
|
|
95
|
+
const rl = readline.createInterface({ input: this.child.stdout });
|
|
96
|
+
rl.on('line', (line) => this._handleLine(line));
|
|
97
|
+
return this;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
_handleLine(line) {
|
|
101
|
+
if (!line.trim()) return;
|
|
102
|
+
let frame;
|
|
103
|
+
try {
|
|
104
|
+
frame = JSON.parse(line);
|
|
105
|
+
} catch {
|
|
106
|
+
return; // engine chatter we do not speak
|
|
107
|
+
}
|
|
108
|
+
if (frame && frame.method !== undefined && frame.id !== undefined) {
|
|
109
|
+
this._handleServerRequest(frame);
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
if (frame && frame.id !== undefined && (frame.result !== undefined || frame.error !== undefined)) {
|
|
113
|
+
const p = this.pending.get(frame.id);
|
|
114
|
+
if (p) {
|
|
115
|
+
this.pending.delete(frame.id);
|
|
116
|
+
clearTimeout(p.timer);
|
|
117
|
+
if (frame.error) p.reject(new Error(`engine error on ${p.method}: ${JSON.stringify(frame.error)}`));
|
|
118
|
+
else p.resolve(frame.result);
|
|
119
|
+
}
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
if (this.onFrame) this.onFrame(frame);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Per-method policy table for server-directed requests (DESIGN §9).
|
|
126
|
+
_handleServerRequest(frame) {
|
|
127
|
+
const method = frame.method;
|
|
128
|
+
const id = frame.id;
|
|
129
|
+
const reply = (payload) =>
|
|
130
|
+
this.child.stdin.write(JSON.stringify({ id, result: payload }) + '\n');
|
|
131
|
+
const replyError = (code, message) =>
|
|
132
|
+
this.child.stdin.write(JSON.stringify({ id, error: { code, message } }) + '\n');
|
|
133
|
+
|
|
134
|
+
if (method === 'session/requestRuntimePreferences') {
|
|
135
|
+
reply(RUNTIME_PREFERENCES);
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
if (method === 'interaction/requestPermission') {
|
|
139
|
+
// Allow-schema pinned from the engine bundle's own headless broker:
|
|
140
|
+
// {decision:"allow", reason, resolvedAt}.
|
|
141
|
+
reply({
|
|
142
|
+
decision: 'allow',
|
|
143
|
+
reason: 'zcode-agent: headless auto-approve (yolo mode; --cwd is the blast radius)',
|
|
144
|
+
resolvedAt: new Date().toISOString(),
|
|
145
|
+
});
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
if (method === 'interaction/requestUserInput') {
|
|
149
|
+
replyError(-32000, 'zcode-agent: headless run requested user input');
|
|
150
|
+
if (this.onUserInputRequest) this.onUserInputRequest(frame);
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
if (method === 'interaction/browserList') {
|
|
154
|
+
// The desktop app answers with its built-in browser panes; the CLI has
|
|
155
|
+
// none. An empty list lets the agent fall back to the user's own tools
|
|
156
|
+
// (Playwright, MCP browsers) instead of failing on a policy error.
|
|
157
|
+
reply({ browsers: [] });
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
if (method === 'interaction/browserExecute') {
|
|
161
|
+
replyError(-32000, 'zcode-agent: no built-in browser in the CLI; use Playwright or a browser MCP server');
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
// Everything else — incl. interaction/requestOfficialMcpAuthHeaders,
|
|
165
|
+
// proven non-fatal with -32601 — gets method-not-found and the run
|
|
166
|
+
// continues.
|
|
167
|
+
replyError(-32601, `zcode-agent: no policy for server request ${method}`);
|
|
168
|
+
if (this.onServerRequest) this.onServerRequest(frame);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
request(method, params, { timeoutMs = 30000 } = {}) {
|
|
172
|
+
if (this.dead) return Promise.reject(new Error('engine app-server is dead'));
|
|
173
|
+
const id = this.nextId++;
|
|
174
|
+
return new Promise((resolve, reject) => {
|
|
175
|
+
this.child.stdin.write(JSON.stringify({ id, method, params }) + '\n', (err) => {
|
|
176
|
+
if (err && this.pending.has(id)) {
|
|
177
|
+
clearTimeout(this.pending.get(id).timer);
|
|
178
|
+
this.pending.delete(id);
|
|
179
|
+
reject(new Error(`engine stdin closed while sending ${method}`));
|
|
180
|
+
}
|
|
181
|
+
});
|
|
182
|
+
const timer = setTimeout(() => {
|
|
183
|
+
this.pending.delete(id);
|
|
184
|
+
reject(new Error(`timeout (${timeoutMs}ms) waiting for ${method}`));
|
|
185
|
+
}, timeoutMs);
|
|
186
|
+
this.pending.set(id, { resolve, reject, method, timer });
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// Asks the engine to abort the active prompt (session/stop). Best-effort
|
|
191
|
+
// and bounded: a wedged engine must not block cancellation.
|
|
192
|
+
async stopSession(sessionId, { timeoutMs = 3000 } = {}) {
|
|
193
|
+
if (this.dead || !sessionId) return false;
|
|
194
|
+
try {
|
|
195
|
+
await this.request('session/stop', { sessionId }, { timeoutMs });
|
|
196
|
+
return true;
|
|
197
|
+
} catch {
|
|
198
|
+
return false;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
kill() {
|
|
203
|
+
if (!this.child || !this.child.pid) return;
|
|
204
|
+
try {
|
|
205
|
+
process.kill(-this.child.pid, 'SIGKILL'); // the whole engine group
|
|
206
|
+
} catch {
|
|
207
|
+
if (!this.dead) {
|
|
208
|
+
try {
|
|
209
|
+
this.child.kill('SIGKILL');
|
|
210
|
+
} catch {
|
|
211
|
+
/* already gone */
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// --- turn orchestration -----------------------------------------------------
|
|
219
|
+
|
|
220
|
+
function workspaceKeyFor(workspacePath) {
|
|
221
|
+
// Deterministic; engine echoes it verbatim (semantics opaque, accepted
|
|
222
|
+
// live). sha256-of-realpath per DESIGN §9 risk R2.
|
|
223
|
+
const real = fs.realpathSync(workspacePath);
|
|
224
|
+
return crypto.createHash('sha256').update(real).digest('hex').slice(0, 16);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// MCP connections are asynchronous (stdio servers must be spawned) and —
|
|
228
|
+
// live-probed — only mcp/list mode:"connect" actually STARTS them;
|
|
229
|
+
// mode:"status" merely observes. The engine answers nothing else until the
|
|
230
|
+
// connect settles (1.0, live-probed: one unreachable inherited server held
|
|
231
|
+
// every RPC, session/send included, for its full 30 s connect timeout), so
|
|
232
|
+
// the connect is always awaited here, never fired and forgotten. Then poll
|
|
233
|
+
// until every explicitly-added server settles (connected/failed/…), so the
|
|
234
|
+
// first turn always sees the caller's --mcp servers. onStatuses receives
|
|
235
|
+
// the last status map (the caller remembers inherited servers that failed).
|
|
236
|
+
async function waitForMcp(client, { workspacePath, required, timeoutMs = 20000, onEvent = () => {}, onStatuses = () => {} }) {
|
|
237
|
+
const ws = { workspace: { workspacePath, workspaceKey: workspaceKeyFor(workspacePath) } };
|
|
238
|
+
try {
|
|
239
|
+
await client.request('mcp/list', { ...ws, mode: 'connect' }, { timeoutMs: 45000 });
|
|
240
|
+
} catch {
|
|
241
|
+
/* best-effort trigger; the status checks below still report */
|
|
242
|
+
}
|
|
243
|
+
const status = async () => {
|
|
244
|
+
try {
|
|
245
|
+
const res = await client.request('mcp/list', { ...ws, mode: 'status' }, { timeoutMs: 5000 });
|
|
246
|
+
return (res && res.statuses) || {};
|
|
247
|
+
} catch {
|
|
248
|
+
return null; // transient — retry
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
if (!required || required.length === 0) {
|
|
252
|
+
const statuses = await status();
|
|
253
|
+
if (statuses) onStatuses(statuses);
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
const deadline = Date.now() + timeoutMs;
|
|
257
|
+
const settled = new Set();
|
|
258
|
+
let last = null;
|
|
259
|
+
while (Date.now() < deadline && settled.size < required.length) {
|
|
260
|
+
const statuses = await status();
|
|
261
|
+
if (statuses) last = statuses;
|
|
262
|
+
for (const name of required) {
|
|
263
|
+
if (settled.has(name)) continue;
|
|
264
|
+
const entry = (statuses || {})[name];
|
|
265
|
+
const state = entry && entry.status;
|
|
266
|
+
if (state === 'connected' || state === 'failed' || state === 'disabled' || state === 'untrusted') {
|
|
267
|
+
settled.add(name);
|
|
268
|
+
onEvent({
|
|
269
|
+
type: 'mcp',
|
|
270
|
+
name,
|
|
271
|
+
status: state,
|
|
272
|
+
toolCount: (entry && entry.toolCount) ?? null,
|
|
273
|
+
failureKind: (entry && entry.failureKind) ?? null,
|
|
274
|
+
error: (entry && entry.error) ? String(typeof entry.error === 'string' ? entry.error : JSON.stringify(entry.error)).slice(0, 300) : null,
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
if (settled.size < required.length) {
|
|
279
|
+
await new Promise((r) => setTimeout(r, 750));
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
for (const name of required) {
|
|
283
|
+
if (!settled.has(name)) {
|
|
284
|
+
onEvent({ type: 'mcp', name, status: 'timeout', toolCount: null });
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
if (last) onStatuses(last);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// Opens the engine session for an invocation: create (+setMode ladder) or
|
|
291
|
+
// resume a persisted one, subscribe, and wait for explicit MCP servers.
|
|
292
|
+
// Everything here is side-effect free on the workspace, so a failure in
|
|
293
|
+
// this phase is safe to retry with a fresh engine.
|
|
294
|
+
async function openSession(client, {
|
|
295
|
+
workspacePath,
|
|
296
|
+
modelId,
|
|
297
|
+
effort,
|
|
298
|
+
resumeSessionId = null,
|
|
299
|
+
requiredMcp = [],
|
|
300
|
+
onEvent = () => {},
|
|
301
|
+
onMcpStatuses = () => {},
|
|
302
|
+
}) {
|
|
303
|
+
const session = { sessionId: null, resumed: false, mode: null };
|
|
304
|
+
if (resumeSessionId) {
|
|
305
|
+
const resumed = await client.request(
|
|
306
|
+
'session/resume',
|
|
307
|
+
{ sessionId: resumeSessionId, thoughtLevel: effort },
|
|
308
|
+
{ timeoutMs: 30000 }
|
|
309
|
+
);
|
|
310
|
+
const s = resumed.session || resumed.value || {};
|
|
311
|
+
session.sessionId = s.sessionId || resumeSessionId;
|
|
312
|
+
session.resumed = true;
|
|
313
|
+
session.mode = s.mode || null;
|
|
314
|
+
await client.request('session/setMode', { sessionId: session.sessionId, mode: 'yolo' }, { timeoutMs: 15000 });
|
|
315
|
+
session.mode = 'yolo';
|
|
316
|
+
} else {
|
|
317
|
+
const created = await client.request(
|
|
318
|
+
'session/create',
|
|
319
|
+
{
|
|
320
|
+
workspace: { workspacePath, workspaceKey: workspaceKeyFor(workspacePath) },
|
|
321
|
+
mode: 'yolo',
|
|
322
|
+
model: { providerId: 'zai-api', modelId, options: { reasoningLevel: effort } },
|
|
323
|
+
thoughtLevel: effort,
|
|
324
|
+
// Persist the session row NOW: the default (deferred) loses it to
|
|
325
|
+
// our SIGKILL on exit, and resume then 404s (-32004).
|
|
326
|
+
persistence: 'immediate',
|
|
327
|
+
},
|
|
328
|
+
{ timeoutMs: 30000 }
|
|
329
|
+
);
|
|
330
|
+
const s = created.session || created.value || {};
|
|
331
|
+
session.sessionId = s.sessionId;
|
|
332
|
+
session.mode = s.mode || null;
|
|
333
|
+
if (!session.sessionId) throw new TurnError('session/create returned no session.sessionId');
|
|
334
|
+
// §9.1 mode ladder: create's mode param is not honored (live-probed).
|
|
335
|
+
if (s.mode !== 'yolo') {
|
|
336
|
+
await client.request('session/setMode', { sessionId: session.sessionId, mode: 'yolo' }, { timeoutMs: 15000 });
|
|
337
|
+
session.mode = 'yolo';
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
await client.request(
|
|
341
|
+
'session/subscribe',
|
|
342
|
+
{ sessionId: session.sessionId, deliveryKind: 'desktop-continuous' },
|
|
343
|
+
{ timeoutMs: 15000 }
|
|
344
|
+
);
|
|
345
|
+
await waitForMcp(client, { workspacePath, required: requiredMcp, onEvent, onStatuses: onMcpStatuses });
|
|
346
|
+
return session;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// Sends one prompt into an open session and waits for its terminal event.
|
|
350
|
+
// Resolves the turn facts; rejects with TurnError (kind: timeout |
|
|
351
|
+
// cancelled | user_input | terminal_failed | result_type | no_completion).
|
|
352
|
+
// On timeout or abort the engine is told to stop the active prompt
|
|
353
|
+
// (session/stop) before we give up on it, so no tool keeps running behind
|
|
354
|
+
// our back while the caller tears the engine down.
|
|
355
|
+
async function runTurn(client, session, {
|
|
356
|
+
modelId,
|
|
357
|
+
effort,
|
|
358
|
+
prompt,
|
|
359
|
+
deadline,
|
|
360
|
+
signal = null,
|
|
361
|
+
keepReasoning = false,
|
|
362
|
+
onEvent = () => {},
|
|
363
|
+
}) {
|
|
364
|
+
const started = Date.now();
|
|
365
|
+
const turn = {
|
|
366
|
+
response: '',
|
|
367
|
+
usage: null,
|
|
368
|
+
engineModel: null,
|
|
369
|
+
engineProvider: null,
|
|
370
|
+
engineReasoningLevel: null,
|
|
371
|
+
terminalStatus: null,
|
|
372
|
+
streamingEvents: 0,
|
|
373
|
+
reasoningChars: 0,
|
|
374
|
+
reasoningText: '',
|
|
375
|
+
toolCallCount: null,
|
|
376
|
+
toolEvents: 0,
|
|
377
|
+
modelRequests: 0,
|
|
378
|
+
userInput: null,
|
|
379
|
+
durationMs: 0,
|
|
380
|
+
};
|
|
381
|
+
|
|
382
|
+
let completed = null;
|
|
383
|
+
let failed = null;
|
|
384
|
+
let completer = null;
|
|
385
|
+
const completion = new Promise((resolve) => { completer = resolve; });
|
|
386
|
+
const fail = (err) => {
|
|
387
|
+
if (!failed && !completed) failed = err;
|
|
388
|
+
completer();
|
|
389
|
+
};
|
|
390
|
+
|
|
391
|
+
client.onUserInputRequest = (frame) => {
|
|
392
|
+
const params = frame.params || {};
|
|
393
|
+
const question = client.scrub(
|
|
394
|
+
String(params.message || params.prompt || params.question || JSON.stringify(params)).slice(0, 800)
|
|
395
|
+
);
|
|
396
|
+
turn.userInput = question;
|
|
397
|
+
fail(new TurnError(`headless run requested user input: ${question}`, { kind: 'user_input' }));
|
|
398
|
+
};
|
|
399
|
+
|
|
400
|
+
client.onFrame = (frame) => {
|
|
401
|
+
const method = frame.method;
|
|
402
|
+
const params = frame.params || {};
|
|
403
|
+
if (method === 'session/event') {
|
|
404
|
+
const type = params.type;
|
|
405
|
+
const payload = params.payload;
|
|
406
|
+
if (type === 'model.streaming' && payload) {
|
|
407
|
+
turn.streamingEvents++;
|
|
408
|
+
if (payload.kind === 'reasoning_delta' && typeof payload.delta === 'string') {
|
|
409
|
+
turn.reasoningChars += payload.delta.length;
|
|
410
|
+
if (keepReasoning) turn.reasoningText += payload.delta;
|
|
411
|
+
}
|
|
412
|
+
onEvent({ type: 'stream', kind: payload.kind, delta: payload.delta });
|
|
413
|
+
} else if (type === 'tool.updated' && payload) {
|
|
414
|
+
// Engine tool lifecycle: scheduled|started|progress|result|error|…
|
|
415
|
+
turn.toolEvents++;
|
|
416
|
+
onEvent({
|
|
417
|
+
type: 'tool',
|
|
418
|
+
phase: payload.kind ?? null,
|
|
419
|
+
name: payload.toolName ?? null,
|
|
420
|
+
id: payload.toolCallId ?? null,
|
|
421
|
+
});
|
|
422
|
+
} else if (type === 'turn.completed' && payload) {
|
|
423
|
+
completed = payload;
|
|
424
|
+
turn.response = typeof payload.response === 'string' ? payload.response : turn.response;
|
|
425
|
+
turn.usage = payload.usage || turn.usage;
|
|
426
|
+
if (typeof payload.toolCallCount === 'number') turn.toolCallCount = payload.toolCallCount;
|
|
427
|
+
completer();
|
|
428
|
+
} else if (type === 'turn.started') {
|
|
429
|
+
onEvent({ type: 'turn', phase: 'started', turnId: params.turnId });
|
|
430
|
+
} else if (type === 'session.updated' && payload && payload.type === 'model_request_started') {
|
|
431
|
+
turn.modelRequests++;
|
|
432
|
+
turn.engineProvider = payload.providerId ?? turn.engineProvider;
|
|
433
|
+
turn.engineModel = payload.modelId ?? turn.engineModel;
|
|
434
|
+
turn.engineReasoningLevel = payload.modelCall?.reasoning?.requestedLevel ?? turn.engineReasoningLevel;
|
|
435
|
+
onEvent({
|
|
436
|
+
type: 'model_request_started',
|
|
437
|
+
providerId: payload.providerId,
|
|
438
|
+
modelId: payload.modelId,
|
|
439
|
+
reasoningLevel: payload.modelCall?.reasoning?.requestedLevel ?? null,
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
} else if (method === 'state.updated') {
|
|
443
|
+
const patch = params.patch || {};
|
|
444
|
+
if (patch.mode && patch.mode.current) onEvent({ type: 'state', mode: patch.mode.current });
|
|
445
|
+
} else if (method === 'v4/telemetry/event' && params.kind === 'turn.terminal') {
|
|
446
|
+
turn.terminalStatus = params.status ?? turn.terminalStatus;
|
|
447
|
+
if (params.status === 'failed') {
|
|
448
|
+
fail(new TurnError(
|
|
449
|
+
`turn.terminal failed: ${client.scrub(JSON.stringify(params.result || params).slice(0, 800))}`,
|
|
450
|
+
{ kind: 'terminal_failed' }
|
|
451
|
+
));
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
};
|
|
455
|
+
const prevOnExit = client.onExit;
|
|
456
|
+
client.onExit = (err) => fail(new TurnError(client.scrub(err.message), { kind: 'engine_exit' }));
|
|
457
|
+
|
|
458
|
+
const remaining = Math.max(0, deadline - Date.now());
|
|
459
|
+
const timer = setTimeout(
|
|
460
|
+
() => fail(new TurnError('run exceeded --timeout-ms', { kind: 'timeout' })),
|
|
461
|
+
remaining
|
|
462
|
+
);
|
|
463
|
+
const onAbort = () => fail(new TurnError('cancelled', { kind: 'cancelled' }));
|
|
464
|
+
if (signal) {
|
|
465
|
+
if (signal.aborted) onAbort();
|
|
466
|
+
else signal.addEventListener('abort', onAbort, { once: true });
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
try {
|
|
470
|
+
if (!failed) {
|
|
471
|
+
await Promise.race([
|
|
472
|
+
client.request(
|
|
473
|
+
'session/send',
|
|
474
|
+
{
|
|
475
|
+
sessionId: session.sessionId,
|
|
476
|
+
content: prompt,
|
|
477
|
+
modelSelection: { providerId: 'zai-api', modelId, options: { reasoningLevel: effort } },
|
|
478
|
+
},
|
|
479
|
+
{ timeoutMs: 30000 }
|
|
480
|
+
),
|
|
481
|
+
completion,
|
|
482
|
+
]);
|
|
483
|
+
}
|
|
484
|
+
await completion;
|
|
485
|
+
if (failed) {
|
|
486
|
+
if (['timeout', 'cancelled', 'user_input'].includes(failed.kind)) {
|
|
487
|
+
await client.stopSession(session.sessionId);
|
|
488
|
+
}
|
|
489
|
+
// The partial facts (model requests so far) survive a failed turn.
|
|
490
|
+
turn.durationMs = Date.now() - started;
|
|
491
|
+
failed.turn = turn;
|
|
492
|
+
throw failed;
|
|
493
|
+
}
|
|
494
|
+
if (completed.resultType && completed.resultType !== 'success') {
|
|
495
|
+
throw new TurnError(`turn completed with resultType "${completed.resultType}"`, { kind: 'result_type' });
|
|
496
|
+
}
|
|
497
|
+
turn.durationMs = Date.now() - started;
|
|
498
|
+
return turn;
|
|
499
|
+
} finally {
|
|
500
|
+
clearTimeout(timer);
|
|
501
|
+
if (signal) signal.removeEventListener('abort', onAbort);
|
|
502
|
+
client.onFrame = null;
|
|
503
|
+
client.onUserInputRequest = null;
|
|
504
|
+
client.onExit = prevOnExit;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
module.exports = {
|
|
509
|
+
AppServerClient,
|
|
510
|
+
openSession,
|
|
511
|
+
runTurn,
|
|
512
|
+
TurnError,
|
|
513
|
+
workspaceKeyFor,
|
|
514
|
+
waitForMcp,
|
|
515
|
+
RUNTIME_PREFERENCES,
|
|
516
|
+
};
|
package/lib/bootstrap.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Resolves everything an engine spawn needs — key, engine bundle, builtin
|
|
3
|
+
// provider config, node binary — and builds engine clients. Throws
|
|
4
|
+
// ConfigError carrying the documented exit code (3 no key, 4 no engine /
|
|
5
|
+
// builtin config) instead of exiting, so callers decide how to report.
|
|
6
|
+
const { resolveKeyInfo, NoKeyError } = require('./key.js');
|
|
7
|
+
const {
|
|
8
|
+
resolveEngine,
|
|
9
|
+
resolveBuiltinProviderConfig,
|
|
10
|
+
EngineNotFoundError,
|
|
11
|
+
BuiltinConfigNotFoundError,
|
|
12
|
+
} = require('./engine.js');
|
|
13
|
+
const { engineEnv } = require('./isolation.js');
|
|
14
|
+
const { AppServerClient } = require('./appserver.js');
|
|
15
|
+
|
|
16
|
+
class ConfigError extends Error {
|
|
17
|
+
constructor(message, exitCode) {
|
|
18
|
+
super(message);
|
|
19
|
+
this.exitCode = exitCode;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Replaces the API key with *** in any text that is about to be printed or
|
|
24
|
+
// stored (defense in depth — the engine never echoes the key, but error
|
|
25
|
+
// paths dump raw frames).
|
|
26
|
+
function makeScrub(key) {
|
|
27
|
+
return (text) => (key ? String(text).split(key).join('***') : String(text));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function resolveRuntime(env = process.env) {
|
|
31
|
+
let key;
|
|
32
|
+
let keySource;
|
|
33
|
+
try {
|
|
34
|
+
({ key, source: keySource } = resolveKeyInfo(env));
|
|
35
|
+
} catch (err) {
|
|
36
|
+
if (err instanceof NoKeyError) throw new ConfigError(err.message, 3);
|
|
37
|
+
throw err;
|
|
38
|
+
}
|
|
39
|
+
let enginePath;
|
|
40
|
+
let builtinConfig;
|
|
41
|
+
try {
|
|
42
|
+
enginePath = resolveEngine(env);
|
|
43
|
+
builtinConfig = resolveBuiltinProviderConfig(enginePath, env);
|
|
44
|
+
} catch (err) {
|
|
45
|
+
if (err instanceof EngineNotFoundError || err instanceof BuiltinConfigNotFoundError) {
|
|
46
|
+
throw new ConfigError(err.message, 4);
|
|
47
|
+
}
|
|
48
|
+
throw err;
|
|
49
|
+
}
|
|
50
|
+
return {
|
|
51
|
+
key,
|
|
52
|
+
keySource,
|
|
53
|
+
scrub: makeScrub(key),
|
|
54
|
+
enginePath,
|
|
55
|
+
builtinConfig,
|
|
56
|
+
nodeBin: env.ZAI_CODE_NODE || process.execPath,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function makeClient(runtime, { home, cwd, sessionEnv = {} }) {
|
|
61
|
+
return new AppServerClient({
|
|
62
|
+
nodeBin: runtime.nodeBin,
|
|
63
|
+
enginePath: runtime.enginePath,
|
|
64
|
+
env: engineEnv({ home, builtinProviderConfig: runtime.builtinConfig, sessionEnv }),
|
|
65
|
+
cwd,
|
|
66
|
+
scrub: runtime.scrub,
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
module.exports = { resolveRuntime, makeClient, makeScrub, ConfigError };
|
package/lib/brief.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// The compact handback: what an orchestrator reads by default (`--json`,
|
|
3
|
+
// `zcode result`, `zcode wait --json`). A projection of the full result
|
|
4
|
+
// record (schema zcode.result/1, still what result.json holds on disk and
|
|
5
|
+
// what `--full` prints): decision-relevant fields only, empty keys omitted,
|
|
6
|
+
// long text bounded, passing checks and met visual criteria reduced to a count
|
|
7
|
+
// (checksPassed, visualMet), decisions/files capped, and a pointer (`result`) to the full record for anything else.
|
|
8
|
+
const BRIEF_SCHEMA = 'zcode.brief/1';
|
|
9
|
+
const SUMMARY_MAX = 600;
|
|
10
|
+
const ERROR_MAX = 500;
|
|
11
|
+
const TAIL_MAX = 1500;
|
|
12
|
+
|
|
13
|
+
function clip(text, max) {
|
|
14
|
+
const s = String(text ?? '');
|
|
15
|
+
return s.length <= max ? s : `${s.slice(0, max - 1)}…`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const empty = (v) =>
|
|
19
|
+
v === undefined || v === null || v === '' || (Array.isArray(v) && v.length === 0);
|
|
20
|
+
|
|
21
|
+
function briefCheck(c) {
|
|
22
|
+
if (c.ok) return { command: c.command, ok: true };
|
|
23
|
+
const out = { command: c.command, ok: false, exitCode: c.exitCode ?? null };
|
|
24
|
+
if (c.timedOut) out.timedOut = true;
|
|
25
|
+
out.tail = String(c.output || '').slice(-TAIL_MAX);
|
|
26
|
+
return out;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const DECISIONS_MAX = 6;
|
|
30
|
+
const FILES_MAX = 40;
|
|
31
|
+
const OPTION_MAX = 300;
|
|
32
|
+
|
|
33
|
+
function briefDecision(d) {
|
|
34
|
+
if (d && typeof d === 'object') return { what: clip(d.what, 160), why: clip(d.why, 120) };
|
|
35
|
+
return clip(d, 160);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function briefVisual(v) {
|
|
39
|
+
return {
|
|
40
|
+
criterion: clip(v.criterion, 160),
|
|
41
|
+
viewport: v.viewport,
|
|
42
|
+
met: v.met === null ? null : false,
|
|
43
|
+
seen: v.seen ? clip(v.seen, 200) : undefined,
|
|
44
|
+
note: clip(v.note, 300),
|
|
45
|
+
shot: v.shot,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Questions stay whole (the decision surface); only option strings are bounded.
|
|
50
|
+
function briefQuestion(q) {
|
|
51
|
+
if (!q || typeof q !== 'object' || !Array.isArray(q.options)) return q;
|
|
52
|
+
return { ...q, options: q.options.map((o) => (typeof o === 'string' ? clip(o, OPTION_MAX) : o)) };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const ALWAYS = new Set(['type', 'schema', 'status', 'ok', 'id']);
|
|
56
|
+
|
|
57
|
+
function buildBrief(result) {
|
|
58
|
+
// checks_failed restates the failing `checks` entries below: kind only.
|
|
59
|
+
const error = result.error
|
|
60
|
+
? result.error.kind === 'checks_failed'
|
|
61
|
+
? { kind: 'checks_failed' }
|
|
62
|
+
: { kind: result.error.kind, message: clip(result.error.message, ERROR_MAX) }
|
|
63
|
+
: null;
|
|
64
|
+
// The failure message usually repeats as an issue; say it once.
|
|
65
|
+
const issues = (result.issues || []).filter((i) => !(error && i === result.error.message));
|
|
66
|
+
const checks = result.checks || [];
|
|
67
|
+
const failing = checks.filter((c) => !c.ok);
|
|
68
|
+
const passed = checks.length - failing.length;
|
|
69
|
+
const visual = Array.isArray(result.visual) ? result.visual : [];
|
|
70
|
+
const visualUnmet = visual.filter((v) => !(v && v.met === true));
|
|
71
|
+
const decisions = Array.isArray(result.decisions) ? result.decisions : [];
|
|
72
|
+
// Files a concurrent session changed are that session's, not this handback's.
|
|
73
|
+
const files = ((result.changes && result.changes.files) || [])
|
|
74
|
+
.filter((f) => !f.concurrentSession)
|
|
75
|
+
.map((f) => f.path);
|
|
76
|
+
const raw = {
|
|
77
|
+
type: 'result',
|
|
78
|
+
schema: BRIEF_SCHEMA,
|
|
79
|
+
status: result.status,
|
|
80
|
+
ok: Boolean(result.ok),
|
|
81
|
+
id: result.id,
|
|
82
|
+
label: result.label,
|
|
83
|
+
preflight: result.preflight,
|
|
84
|
+
summary: clip(result.summary, SUMMARY_MAX),
|
|
85
|
+
// run/agent: the answer is the product. task: the handback is.
|
|
86
|
+
response: result.kind === 'task' ? undefined : result.response,
|
|
87
|
+
files: files.slice(0, FILES_MAX),
|
|
88
|
+
filesMore: files.length > FILES_MAX ? files.length - FILES_MAX : undefined,
|
|
89
|
+
checks: failing.map(briefCheck),
|
|
90
|
+
checksPassed: passed > 0 ? passed : undefined,
|
|
91
|
+
questions: Array.isArray(result.questions) ? result.questions.map(briefQuestion) : result.questions,
|
|
92
|
+
issues,
|
|
93
|
+
unresolved: result.unresolved,
|
|
94
|
+
scopeViolations: result.scopeViolations,
|
|
95
|
+
touched: result.touched,
|
|
96
|
+
decisions: decisions.slice(0, DECISIONS_MAX).map(briefDecision),
|
|
97
|
+
decisionsMore: decisions.length > DECISIONS_MAX ? decisions.length - DECISIONS_MAX : undefined,
|
|
98
|
+
visual: visualUnmet.map(briefVisual),
|
|
99
|
+
visualMet: visual.length ? `${visual.length - visualUnmet.length}/${visual.length}` : undefined,
|
|
100
|
+
units: result.units,
|
|
101
|
+
error,
|
|
102
|
+
result: result.files && result.files.result,
|
|
103
|
+
};
|
|
104
|
+
const out = {};
|
|
105
|
+
for (const [k, v] of Object.entries(raw)) if (ALWAYS.has(k) || !empty(v)) out[k] = v;
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
module.exports = { buildBrief, BRIEF_SCHEMA };
|