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.
@@ -0,0 +1,546 @@
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, interactions = null }) {
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
+ // ACP (lib/acp.js): {permission(params), userInput(params)} → the
51
+ // engine's reply, asked of a person instead of the headless policy.
52
+ this.interactions = interactions;
53
+ }
54
+
55
+ start() {
56
+ // Own process group, so kill() takes the engine's tool subprocesses and
57
+ // stdio MCP servers with it (a runaway shell command must not keep
58
+ // writing to the workspace after cancel/timeout).
59
+ this.child = spawn(this.nodeBin, [this.enginePath, 'app-server', '--stdio'], {
60
+ env: this.env,
61
+ cwd: this.cwd,
62
+ stdio: ['pipe', 'pipe', 'pipe'],
63
+ detached: true,
64
+ });
65
+ this.child.stderr.on('data', (d) => {
66
+ this.engineStderr += d;
67
+ if (this.engineStderr.length > 20000) {
68
+ this.engineStderr = this.engineStderr.slice(-20000);
69
+ }
70
+ });
71
+ // EPIPE on a dying engine and spawn failures (bad ZAI_CODE_NODE) must
72
+ // surface as a failed request, never as an uncaught 'error' event.
73
+ this.child.stdin.on('error', () => {});
74
+ this.child.on('error', (err) => {
75
+ if (this.dead) return;
76
+ this.dead = true;
77
+ const wrapped = new Error(`engine app-server failed to start: ${err.message}`);
78
+ for (const { reject, timer } of this.pending.values()) {
79
+ clearTimeout(timer);
80
+ reject(wrapped);
81
+ }
82
+ this.pending.clear();
83
+ if (this.onExit) this.onExit(wrapped);
84
+ });
85
+ this.child.on('exit', (code, signal) => {
86
+ this.dead = true;
87
+ const err = new Error(
88
+ `engine app-server exited (code=${code} signal=${signal})` +
89
+ (this.engineStderr ? `\nengine stderr tail: ${this.engineStderr.split('\n').slice(-8).join('\n')}` : '')
90
+ );
91
+ for (const { reject, timer } of this.pending.values()) {
92
+ clearTimeout(timer);
93
+ reject(err);
94
+ }
95
+ this.pending.clear();
96
+ if (this.onExit) this.onExit(err);
97
+ });
98
+ const rl = readline.createInterface({ input: this.child.stdout });
99
+ rl.on('line', (line) => this._handleLine(line));
100
+ return this;
101
+ }
102
+
103
+ _handleLine(line) {
104
+ if (!line.trim()) return;
105
+ let frame;
106
+ try {
107
+ frame = JSON.parse(line);
108
+ } catch {
109
+ return; // engine chatter we do not speak
110
+ }
111
+ if (frame && frame.method !== undefined && frame.id !== undefined) {
112
+ this._handleServerRequest(frame);
113
+ return;
114
+ }
115
+ if (frame && frame.id !== undefined && (frame.result !== undefined || frame.error !== undefined)) {
116
+ const p = this.pending.get(frame.id);
117
+ if (p) {
118
+ this.pending.delete(frame.id);
119
+ clearTimeout(p.timer);
120
+ if (frame.error) p.reject(new Error(`engine error on ${p.method}: ${JSON.stringify(frame.error)}`));
121
+ else p.resolve(frame.result);
122
+ }
123
+ return;
124
+ }
125
+ if (this.onFrame) this.onFrame(frame);
126
+ }
127
+
128
+ // Per-method policy table for server-directed requests (DESIGN §9).
129
+ _handleServerRequest(frame) {
130
+ const method = frame.method;
131
+ const id = frame.id;
132
+ const reply = (payload) =>
133
+ this.child.stdin.write(JSON.stringify({ id, result: payload }) + '\n');
134
+ const replyError = (code, message) =>
135
+ this.child.stdin.write(JSON.stringify({ id, error: { code, message } }) + '\n');
136
+
137
+ if (method === 'session/requestRuntimePreferences') {
138
+ reply(RUNTIME_PREFERENCES);
139
+ return;
140
+ }
141
+ if (this.interactions && (method === 'interaction/requestPermission' || method === 'interaction/requestUserInput')) {
142
+ const ask = method === 'interaction/requestPermission' ? this.interactions.permission : this.interactions.userInput;
143
+ Promise.resolve()
144
+ .then(() => ask(frame.params || {}))
145
+ .then(reply, (err) => replyError(-32000, `zcode-agent: ${err && err.message ? err.message : err}`));
146
+ return;
147
+ }
148
+ if (method === 'interaction/requestPermission') {
149
+ // The reply schema is strict ({decision, reason?, modifiedInput?,
150
+ // permissionUpdates?}; live-probed 1.1: an extra resolvedAt made the
151
+ // engine deny the tool). The request's own "allow once" option carries
152
+ // a reply in exactly that shape.
153
+ reply(allowOnce(frame.params) || {
154
+ decision: 'allow',
155
+ reason: 'zcode-agent: headless auto-approve (yolo mode; --cwd is the blast radius)',
156
+ });
157
+ return;
158
+ }
159
+ if (method === 'interaction/requestUserInput') {
160
+ replyError(-32000, 'zcode-agent: headless run requested user input');
161
+ if (this.onUserInputRequest) this.onUserInputRequest(frame);
162
+ return;
163
+ }
164
+ if (method === 'interaction/browserList') {
165
+ // The desktop app answers with its built-in browser panes; the CLI has
166
+ // none. An empty list lets the agent fall back to the user's own tools
167
+ // (Playwright, MCP browsers) instead of failing on a policy error.
168
+ reply({ browsers: [] });
169
+ return;
170
+ }
171
+ if (method === 'interaction/browserExecute') {
172
+ replyError(-32000, 'zcode-agent: no built-in browser in the CLI; use Playwright or a browser MCP server');
173
+ return;
174
+ }
175
+ // Everything else — incl. interaction/requestOfficialMcpAuthHeaders,
176
+ // proven non-fatal with -32601 — gets method-not-found and the run
177
+ // continues.
178
+ replyError(-32601, `zcode-agent: no policy for server request ${method}`);
179
+ if (this.onServerRequest) this.onServerRequest(frame);
180
+ }
181
+
182
+ request(method, params, { timeoutMs = 30000 } = {}) {
183
+ if (this.dead) return Promise.reject(new Error('engine app-server is dead'));
184
+ const id = this.nextId++;
185
+ return new Promise((resolve, reject) => {
186
+ this.child.stdin.write(JSON.stringify({ id, method, params }) + '\n', (err) => {
187
+ if (err && this.pending.has(id)) {
188
+ clearTimeout(this.pending.get(id).timer);
189
+ this.pending.delete(id);
190
+ reject(new Error(`engine stdin closed while sending ${method}`));
191
+ }
192
+ });
193
+ const timer = setTimeout(() => {
194
+ this.pending.delete(id);
195
+ reject(new Error(`timeout (${timeoutMs}ms) waiting for ${method}`));
196
+ }, timeoutMs);
197
+ this.pending.set(id, { resolve, reject, method, timer });
198
+ });
199
+ }
200
+
201
+ // Asks the engine to abort the active prompt (session/stop). Best-effort
202
+ // and bounded: a wedged engine must not block cancellation.
203
+ async stopSession(sessionId, { timeoutMs = 3000 } = {}) {
204
+ if (this.dead || !sessionId) return false;
205
+ try {
206
+ await this.request('session/stop', { sessionId }, { timeoutMs });
207
+ return true;
208
+ } catch {
209
+ return false;
210
+ }
211
+ }
212
+
213
+ kill() {
214
+ if (!this.child || !this.child.pid) return;
215
+ try {
216
+ process.kill(-this.child.pid, 'SIGKILL'); // the whole engine group
217
+ } catch {
218
+ if (!this.dead) {
219
+ try {
220
+ this.child.kill('SIGKILL');
221
+ } catch {
222
+ /* already gone */
223
+ }
224
+ }
225
+ }
226
+ }
227
+ }
228
+
229
+ // The engine's reply for a permission request's "allow once" option, or null.
230
+ function allowOnce(params) {
231
+ const options = (params && Array.isArray(params.options)) ? params.options : [];
232
+ const option = options.find((o) => o && o.kind === 'allow_once' && o.response);
233
+ return option ? option.response : null;
234
+ }
235
+
236
+ // --- turn orchestration -----------------------------------------------------
237
+
238
+ function workspaceKeyFor(workspacePath) {
239
+ // Deterministic; engine echoes it verbatim (semantics opaque, accepted
240
+ // live). sha256-of-realpath per DESIGN §9 risk R2.
241
+ const real = fs.realpathSync(workspacePath);
242
+ return crypto.createHash('sha256').update(real).digest('hex').slice(0, 16);
243
+ }
244
+
245
+ // MCP connections are asynchronous (stdio servers must be spawned) and —
246
+ // live-probed — only mcp/list mode:"connect" actually STARTS them;
247
+ // mode:"status" merely observes. The engine answers nothing else until the
248
+ // connect settles (1.0, live-probed: one unreachable inherited server held
249
+ // every RPC, session/send included, for its full 30 s connect timeout), so
250
+ // the connect is always awaited here, never fired and forgotten. Then poll
251
+ // until every explicitly-added server settles (connected/failed/…), so the
252
+ // first turn always sees the caller's --mcp servers. onStatuses receives
253
+ // the last status map (the caller remembers inherited servers that failed).
254
+ async function waitForMcp(client, { workspacePath, required, timeoutMs = 20000, onEvent = () => {}, onStatuses = () => {} }) {
255
+ const ws = { workspace: { workspacePath, workspaceKey: workspaceKeyFor(workspacePath) } };
256
+ try {
257
+ await client.request('mcp/list', { ...ws, mode: 'connect' }, { timeoutMs: 45000 });
258
+ } catch {
259
+ /* best-effort trigger; the status checks below still report */
260
+ }
261
+ const status = async () => {
262
+ try {
263
+ const res = await client.request('mcp/list', { ...ws, mode: 'status' }, { timeoutMs: 5000 });
264
+ return (res && res.statuses) || {};
265
+ } catch {
266
+ return null; // transient — retry
267
+ }
268
+ };
269
+ if (!required || required.length === 0) {
270
+ const statuses = await status();
271
+ if (statuses) onStatuses(statuses);
272
+ return;
273
+ }
274
+ const deadline = Date.now() + timeoutMs;
275
+ const settled = new Set();
276
+ let last = null;
277
+ while (Date.now() < deadline && settled.size < required.length) {
278
+ const statuses = await status();
279
+ if (statuses) last = statuses;
280
+ for (const name of required) {
281
+ if (settled.has(name)) continue;
282
+ const entry = (statuses || {})[name];
283
+ const state = entry && entry.status;
284
+ if (state === 'connected' || state === 'failed' || state === 'disabled' || state === 'untrusted') {
285
+ settled.add(name);
286
+ onEvent({
287
+ type: 'mcp',
288
+ name,
289
+ status: state,
290
+ toolCount: (entry && entry.toolCount) ?? null,
291
+ failureKind: (entry && entry.failureKind) ?? null,
292
+ error: (entry && entry.error) ? String(typeof entry.error === 'string' ? entry.error : JSON.stringify(entry.error)).slice(0, 300) : null,
293
+ });
294
+ }
295
+ }
296
+ if (settled.size < required.length) {
297
+ await new Promise((r) => setTimeout(r, 750));
298
+ }
299
+ }
300
+ for (const name of required) {
301
+ if (!settled.has(name)) {
302
+ onEvent({ type: 'mcp', name, status: 'timeout', toolCount: null });
303
+ }
304
+ }
305
+ if (last) onStatuses(last);
306
+ }
307
+
308
+ // Opens the engine session for an invocation: create (+setMode ladder) or
309
+ // resume a persisted one, subscribe, and wait for explicit MCP servers.
310
+ // Everything here is side-effect free on the workspace, so a failure in
311
+ // this phase is safe to retry with a fresh engine.
312
+ async function openSession(client, {
313
+ workspacePath,
314
+ modelId,
315
+ effort,
316
+ resumeSessionId = null,
317
+ requiredMcp = [],
318
+ mode = 'yolo',
319
+ onEvent = () => {},
320
+ onMcpStatuses = () => {},
321
+ }) {
322
+ const session = { sessionId: null, resumed: false, mode: null, created: null };
323
+ if (resumeSessionId) {
324
+ const resumed = await client.request(
325
+ 'session/resume',
326
+ { sessionId: resumeSessionId, thoughtLevel: effort },
327
+ { timeoutMs: 30000 }
328
+ );
329
+ const s = resumed.session || resumed.value || {};
330
+ session.sessionId = s.sessionId || resumeSessionId;
331
+ session.resumed = true;
332
+ session.mode = s.mode || null;
333
+ session.created = resumed;
334
+ await client.request('session/setMode', { sessionId: session.sessionId, mode }, { timeoutMs: 15000 });
335
+ session.mode = mode;
336
+ } else {
337
+ const created = await client.request(
338
+ 'session/create',
339
+ {
340
+ workspace: { workspacePath, workspaceKey: workspaceKeyFor(workspacePath) },
341
+ mode,
342
+ model: { providerId: 'zai-api', modelId, options: { reasoningLevel: effort } },
343
+ thoughtLevel: effort,
344
+ // Persist the session row NOW: the default (deferred) loses it to
345
+ // our SIGKILL on exit, and resume then 404s (-32004).
346
+ persistence: 'immediate',
347
+ },
348
+ { timeoutMs: 30000 }
349
+ );
350
+ const s = created.session || created.value || {};
351
+ session.sessionId = s.sessionId;
352
+ session.mode = s.mode || null;
353
+ session.created = created;
354
+ if (!session.sessionId) throw new TurnError('session/create returned no session.sessionId');
355
+ // §9.1 mode ladder: create's mode param is not honored (live-probed).
356
+ if (s.mode !== mode) {
357
+ await client.request('session/setMode', { sessionId: session.sessionId, mode }, { timeoutMs: 15000 });
358
+ session.mode = mode;
359
+ }
360
+ }
361
+ await client.request(
362
+ 'session/subscribe',
363
+ { sessionId: session.sessionId, deliveryKind: 'desktop-continuous' },
364
+ { timeoutMs: 15000 }
365
+ );
366
+ await waitForMcp(client, { workspacePath, required: requiredMcp, onEvent, onStatuses: onMcpStatuses });
367
+ return session;
368
+ }
369
+
370
+ // Sends one prompt into an open session and waits for its terminal event.
371
+ // Resolves the turn facts; rejects with TurnError (kind: timeout |
372
+ // cancelled | user_input | terminal_failed | result_type | no_completion).
373
+ // On timeout or abort the engine is told to stop the active prompt
374
+ // (session/stop) before we give up on it, so no tool keeps running behind
375
+ // our back while the caller tears the engine down.
376
+ async function runTurn(client, session, {
377
+ modelId,
378
+ effort,
379
+ prompt,
380
+ deadline,
381
+ signal = null,
382
+ keepReasoning = false,
383
+ onEvent = () => {},
384
+ onFrame = null,
385
+ }) {
386
+ const started = Date.now();
387
+ const turn = {
388
+ response: '',
389
+ usage: null,
390
+ engineModel: null,
391
+ engineProvider: null,
392
+ engineReasoningLevel: null,
393
+ terminalStatus: null,
394
+ streamingEvents: 0,
395
+ reasoningChars: 0,
396
+ reasoningText: '',
397
+ toolCallCount: null,
398
+ toolEvents: 0,
399
+ modelRequests: 0,
400
+ userInput: null,
401
+ durationMs: 0,
402
+ };
403
+
404
+ let completed = null;
405
+ let failed = null;
406
+ let completer = null;
407
+ const completion = new Promise((resolve) => { completer = resolve; });
408
+ const fail = (err) => {
409
+ if (!failed && !completed) failed = err;
410
+ completer();
411
+ };
412
+
413
+ client.onUserInputRequest = (frame) => {
414
+ const params = frame.params || {};
415
+ const question = client.scrub(
416
+ String(params.message || params.prompt || params.question || JSON.stringify(params)).slice(0, 800)
417
+ );
418
+ turn.userInput = question;
419
+ fail(new TurnError(`headless run requested user input: ${question}`, { kind: 'user_input' }));
420
+ };
421
+
422
+ client.onFrame = (frame) => {
423
+ const method = frame.method;
424
+ const params = frame.params || {};
425
+ if (onFrame) {
426
+ try {
427
+ onFrame(frame);
428
+ } catch {
429
+ /* a consumer's bug must not take down the engine reader */
430
+ }
431
+ }
432
+ if (method === 'session/event') {
433
+ const type = params.type;
434
+ const payload = params.payload;
435
+ if (type === 'model.streaming' && payload) {
436
+ turn.streamingEvents++;
437
+ if (payload.kind === 'reasoning_delta' && typeof payload.delta === 'string') {
438
+ turn.reasoningChars += payload.delta.length;
439
+ if (keepReasoning) turn.reasoningText += payload.delta;
440
+ }
441
+ onEvent({ type: 'stream', kind: payload.kind, delta: payload.delta });
442
+ } else if (type === 'tool.updated' && payload) {
443
+ // Engine tool lifecycle: scheduled|started|progress|result|error|…
444
+ turn.toolEvents++;
445
+ onEvent({
446
+ type: 'tool',
447
+ phase: payload.kind ?? null,
448
+ name: payload.toolName ?? null,
449
+ id: payload.toolCallId ?? null,
450
+ });
451
+ } else if (type === 'turn.completed' && payload) {
452
+ completed = payload;
453
+ turn.response = typeof payload.response === 'string' ? payload.response : turn.response;
454
+ turn.usage = payload.usage || turn.usage;
455
+ if (typeof payload.toolCallCount === 'number') turn.toolCallCount = payload.toolCallCount;
456
+ completer();
457
+ } else if (type === 'turn.started') {
458
+ onEvent({ type: 'turn', phase: 'started', turnId: params.turnId });
459
+ } else if (type === 'session.updated' && payload && payload.type === 'model_request_started') {
460
+ turn.modelRequests++;
461
+ turn.engineProvider = payload.providerId ?? turn.engineProvider;
462
+ turn.engineModel = payload.modelId ?? turn.engineModel;
463
+ turn.engineReasoningLevel = payload.modelCall?.reasoning?.requestedLevel ?? turn.engineReasoningLevel;
464
+ onEvent({
465
+ type: 'model_request_started',
466
+ providerId: payload.providerId,
467
+ modelId: payload.modelId,
468
+ reasoningLevel: payload.modelCall?.reasoning?.requestedLevel ?? null,
469
+ });
470
+ }
471
+ } else if (method === 'state.updated') {
472
+ const patch = params.patch || {};
473
+ if (patch.mode && patch.mode.current) onEvent({ type: 'state', mode: patch.mode.current });
474
+ } else if (method === 'v4/telemetry/event' && params.kind === 'turn.terminal') {
475
+ turn.terminalStatus = params.status ?? turn.terminalStatus;
476
+ if (params.status === 'failed') {
477
+ fail(new TurnError(
478
+ `turn.terminal failed: ${client.scrub(JSON.stringify(params.result || params).slice(0, 800))}`,
479
+ { kind: 'terminal_failed' }
480
+ ));
481
+ }
482
+ }
483
+ };
484
+ const prevOnExit = client.onExit;
485
+ client.onExit = (err) => fail(new TurnError(client.scrub(err.message), { kind: 'engine_exit' }));
486
+
487
+ const remaining = Math.max(0, deadline - Date.now());
488
+ const timer = setTimeout(
489
+ () => fail(new TurnError('run exceeded --timeout-ms', { kind: 'timeout' })),
490
+ remaining
491
+ );
492
+ const onAbort = () => fail(new TurnError('cancelled', { kind: 'cancelled' }));
493
+ if (signal) {
494
+ if (signal.aborted) onAbort();
495
+ else signal.addEventListener('abort', onAbort, { once: true });
496
+ }
497
+
498
+ try {
499
+ if (!failed) {
500
+ await Promise.race([
501
+ client.request(
502
+ 'session/send',
503
+ {
504
+ sessionId: session.sessionId,
505
+ content: prompt,
506
+ modelSelection: { providerId: 'zai-api', modelId, options: { reasoningLevel: effort } },
507
+ },
508
+ { timeoutMs: 30000 }
509
+ ),
510
+ completion,
511
+ ]);
512
+ }
513
+ await completion;
514
+ if (failed) {
515
+ if (['timeout', 'cancelled', 'user_input'].includes(failed.kind)) {
516
+ await client.stopSession(session.sessionId);
517
+ }
518
+ // The partial facts (model requests so far) survive a failed turn.
519
+ turn.durationMs = Date.now() - started;
520
+ failed.turn = turn;
521
+ throw failed;
522
+ }
523
+ if (completed.resultType && completed.resultType !== 'success') {
524
+ throw new TurnError(`turn completed with resultType "${completed.resultType}"`, { kind: 'result_type' });
525
+ }
526
+ turn.durationMs = Date.now() - started;
527
+ return turn;
528
+ } finally {
529
+ clearTimeout(timer);
530
+ if (signal) signal.removeEventListener('abort', onAbort);
531
+ client.onFrame = null;
532
+ client.onUserInputRequest = null;
533
+ client.onExit = prevOnExit;
534
+ }
535
+ }
536
+
537
+ module.exports = {
538
+ AppServerClient,
539
+ openSession,
540
+ runTurn,
541
+ TurnError,
542
+ workspaceKeyFor,
543
+ waitForMcp,
544
+ RUNTIME_PREFERENCES,
545
+ allowOnce,
546
+ };
@@ -0,0 +1,71 @@
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 = {}, interactions = null }) {
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
+ interactions,
68
+ });
69
+ }
70
+
71
+ module.exports = { resolveRuntime, makeClient, makeScrub, ConfigError };