-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathrun.ts
More file actions
587 lines (535 loc) · 18.9 KB
/
Copy pathrun.ts
File metadata and controls
587 lines (535 loc) · 18.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
import { extractDisallowedToolsArgs, parseGlobalArgs } from "./arguments.js";
import { createNodeLoggerFactory } from "@zcode/adapters";
import { getRuntimeInfo, type PresentationSurface } from "@zcode/core";
import { color, formatJson, supportsColor } from "@zcode/core";
import { getZCodeCopy, isUiLocale, type UiLocale } from "@zcode/i18n";
import type { RunContext, GlobalOptions, GlobalOutputFormat } from "@zcode/shared-types";
import {
applyCliRuntimeEnvSanitization,
loadCliDotenv,
prepareCliRuntimeEnv,
shouldLoadCliDotenvForProtocolServer,
} from "./env.js";
import { formatCliHelp } from "./help.js";
import { runHooksCommand } from "./hooks-trust-command.js";
import { detectCliLocale } from "./locale.js";
import { loadBootstrapModule } from "./bootstrap-loader.js";
import { runEmbeddedSearchCli } from "./internal-search/embedded-search-cli.js";
import { runCommandsCommand } from "./commands-command.js";
import { resolveCliCwd } from "./cwd.js";
import { runLoginCommand, runLogoutCommand } from "./login-command.js";
import { CLI_COMMAND_NAME, CLI_PROCESS_NAME } from "./process-name.js";
import { isPluginHostInvocation, runPluginHostCommand } from "./plugin-host-command.js";
import { isDwfChildInvocation, runDwfChildCommand } from "./dwf-child-command.js";
import { runPrompt } from "./prompt-command.js";
import { runPluginsCommand, type PluginsCommandFlags } from "./plugins-command.js";
import { runSkillsCommand } from "./skills-command.js";
import { runTuiCommand } from "./tui-command.js";
import type {
CliPermissionMode,
CliResumeRequest,
CliTargetRequest,
RunDependencies,
} from "./cli-types.js";
export type { RunDependencies } from "./cli-types.js";
declare const __CLI_VERSION__: string | undefined;
const version = typeof __CLI_VERSION__ === "string" ? __CLI_VERSION__ : "0.0.0";
const EMPTY_TARGET_ERROR = "--target requires non-empty text.";
const DEFAULT_HEADLESS_PROMPT_MODE: CliPermissionMode = "yolo";
const FORCE_MCS_SCOPE_ERROR = "--force-mcs can only be used with --prompt, --target, or tui.";
const TARGET_REPLACE_REQUIRES_TARGET_ERROR = "--target-replace requires --target.";
const TARGET_CONFLICTS_WITH_PROMPT_ERROR =
'--target cannot be used with --prompt. Use either --target <objective> or --prompt "/goal <objective>".';
const BROWSER_EXECUTABLE_REQUIRES_HEADLESS_ERROR =
"--browser-executable requires --browser-use=headless.";
const BROWSER_USE_SCOPE_ERROR =
"--browser-use=headless can only be used with --prompt, --target, or tui.";
const SURFACE_SCOPE_ERROR =
"--surface can only be used with --prompt, --target, app-server, or agent-server.";
const MEMORY_BENCH_SCOPE_ERROR = "--memory-bench can only be used with -p/--prompt.";
const ENABLE_WORKFLOW_SCOPE_ERROR =
"--enable-workflow can only be used with -p/--prompt or --target.";
const pluginsCommandFlags = (
values: ReturnType<typeof parseGlobalArgs>["values"],
): PluginsCommandFlags => ({
...(values.all === true ? { all: true } : {}),
...(values.available === true ? { available: true } : {}),
...(values["keep-data"] === true ? { keepData: true } : {}),
...(typeof values.scope === "string" ? { scope: values.scope } : {}),
...(Array.isArray(values.sparse) ? { sparse: values.sparse as string[] } : {}),
});
const commandName = (positionals: string[]): string => positionals[0] ?? "tui";
const isForceMcsSupportedInvocation = (input: {
positionals: string[];
prompt?: string;
targetRequest?: CliTargetRequest;
}): boolean =>
typeof input.prompt === "string" ||
input.targetRequest !== undefined ||
commandName(input.positionals) === "tui";
const isPresentationSurfaceSupportedInvocation = (input: {
positionals: string[];
prompt?: string;
targetRequest?: CliTargetRequest;
}): boolean => {
const command = commandName(input.positionals);
return (
typeof input.prompt === "string" ||
input.targetRequest !== undefined ||
command === "app-server" ||
command === "agent-server"
);
};
const globalOptions = (
values: ReturnType<typeof parseGlobalArgs>["values"],
locale: UiLocale | undefined,
detectedLocale: GlobalOptions["detectedLocale"],
browserUse: GlobalOptions["browserUse"],
browserExecutable: GlobalOptions["browserExecutable"],
outputFormat: GlobalOptions["outputFormat"],
): GlobalOptions => {
return {
browserExecutable,
browserUse,
detectedLocale,
...(values["enable-workflow"] === true ? { enableWorkflow: true } : {}),
force: values.force === true,
json: values.json === true,
locale,
...(values["memory-bench"] === true ? { memoryBench: true } : {}),
noColor: values["no-color"] === true,
...(outputFormat ? { outputFormat } : {}),
verbose: values.verbose === true,
};
};
const OUTPUT_FORMATS: readonly GlobalOutputFormat[] = ["text", "json", "stream-json"];
/**
* Validate --output-format. Rejecting an unknown value matters more than it
* looks: a caller that misspells it would otherwise get plain text back and
* silently parse nothing.
*/
const normalizeOutputFormat = (value: string | undefined): GlobalOutputFormat | undefined => {
if (value === undefined) return undefined;
if ((OUTPUT_FORMATS as readonly string[]).includes(value)) return value as GlobalOutputFormat;
throw new Error(
`--output-format must be one of ${OUTPUT_FORMATS.join(", ")} (received: ${value}).`,
);
};
const normalizeLocaleOption = (value: string | undefined): UiLocale | undefined => {
if (value === undefined) return undefined;
if (isUiLocale(value)) return value;
throw new Error(getZCodeCopy().cli.errors.localeUnsupported(value));
};
const normalizePromptMode = (value: string | undefined): CliPermissionMode | undefined => {
if (value === undefined) return undefined;
const mode = value.toLowerCase();
if (mode === "build" || mode === "plan" || mode === "edit" || mode === "yolo") return mode;
throw new Error(`Unsupported --mode value: ${value}. Supported modes: build, edit, plan, yolo.`);
};
const normalizeBrowserUse = (value: string | undefined): GlobalOptions["browserUse"] => {
if (value === undefined) return undefined;
if (value.toLowerCase() === "headless") return "headless";
throw new Error(`Unsupported --browser-use value: ${value}. Supported value: headless.`);
};
const normalizePresentationSurface = (value: string | undefined): PresentationSurface => {
if (value === undefined || value.toLowerCase() === "terminal") return "terminal";
if (value.toLowerCase() === "desktop") return "zcode_desktop";
throw new Error(`Unsupported --surface value: ${value}. Supported surfaces: terminal, desktop.`);
};
const normalizeTargetRequest = (
values: ReturnType<typeof parseGlobalArgs>["values"],
): CliTargetRequest | undefined => {
const rawTarget = values.target as string | undefined;
const replaceExisting = values["target-replace"] === true;
if (rawTarget === undefined) {
if (replaceExisting) {
throw new Error(TARGET_REPLACE_REQUIRES_TARGET_ERROR);
}
return undefined;
}
const objective = rawTarget.trim();
if (objective.length === 0) {
throw new Error(EMPTY_TARGET_ERROR);
}
return {
objective,
replaceExisting,
};
};
const buildHeadlessTargetCommand = (targetRequest: CliTargetRequest): string =>
targetRequest.replaceExisting
? `/goal replace ${targetRequest.objective}`
: `/goal ${targetRequest.objective}`;
const writeHelp = (
stdout: NodeJS.WriteStream,
locale?: UiLocale,
detectedLocale?: GlobalOptions["detectedLocale"],
): void => {
stdout.write(formatCliHelp(version, locale, detectedLocale));
};
const runDoctor = (ctx: RunContext, options: GlobalOptions, workingDirectory: string): number => {
const runtime = getRuntimeInfo();
const payload = {
cli: {
name: CLI_COMMAND_NAME,
processName: CLI_PROCESS_NAME,
version,
},
runtime: {
arch: runtime.arch,
cwd: workingDirectory,
execPath: runtime.execPath,
node: runtime.node,
platform: runtime.platform,
processTitle: process.title,
sea: runtime.sea,
},
packaging: {
default: "node-bundle",
sea: "optional",
},
};
if (options.json) {
ctx.stdout.write(formatJson(payload));
return 0;
}
const colors = supportsColor(ctx.stdout, options.noColor);
ctx.stdout.write(`${color.bold("zcode doctor", colors)}\n`);
ctx.stdout.write(`version: ${payload.cli.version}\n`);
ctx.stdout.write(`process: ${payload.runtime.processTitle}\n`);
ctx.stdout.write(`node: ${payload.runtime.node}\n`);
ctx.stdout.write(`platform: ${payload.runtime.platform}/${payload.runtime.arch}\n`);
ctx.stdout.write(`sea: ${payload.runtime.sea ? "yes" : "no"} (${payload.packaging.sea})\n`);
ctx.stdout.write(`default artifact: ${payload.packaging.default}\n`);
if (options.verbose) {
ctx.stdout.write(`execPath: ${payload.runtime.execPath}\n`);
ctx.stdout.write(`cwd: ${payload.runtime.cwd}\n`);
}
return 0;
};
const runZCodeProtocolCommand = async (
ctx: RunContext,
options: GlobalOptions,
deps: RunDependencies,
presentationSurface: PresentationSurface,
prepareStorageOnly = false,
): Promise<number> => {
try {
const env = prepareCliRuntimeEnv(deps.env ?? process.env);
const workingDirectory = (deps.cwd ?? process.cwd)();
// 打包态 app-server 是 desktop host 的内部协议子进程。
// 如果这里继续从 workspace 向上读取用户 .env,读文件失败或环境污染会在协议建立前
// 直接退出,外层只能看到 ZCode agent transport closed。
const dotenvResult = shouldLoadCliDotenvForProtocolServer(env)
? (deps.loadDotenv ?? loadCliDotenv)({
cwd: workingDirectory,
env,
})
: {
keys: [],
loaded: false,
};
applyCliRuntimeEnvSanitization(env);
if (dotenvResult.error) {
throw new Error(`Failed to load environment file: ${dotenvResult.path}`, {
cause: dotenvResult.error,
});
}
const runProtocolAgent =
deps.runZCodeProtocolAgent ?? (await loadBootstrapModule()).runZCodeProtocolAgent;
await runProtocolAgent({
lifecycle: deps.protocolLifecycle,
cwd: workingDirectory,
env,
input: deps.protocolInput ?? ctx.stdin,
output: ctx.stdout,
presentationSurface,
prepareStorageOnly,
version,
});
return 0;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
ctx.stderr.write(`Error: ${message}\n`);
if (options.verbose && error instanceof Error && error.stack) {
ctx.stderr.write(`${error.stack}\n`);
}
return 1;
}
};
export const run = async (ctx: RunContext, deps: RunDependencies = {}): Promise<number> => {
if (ctx.argv[0] === "__internal-search") {
return runEmbeddedSearchCli(ctx.argv.slice(1), {
cwd: (deps.cwd ?? process.cwd)(),
stderr: ctx.stderr,
stdin: ctx.stdin,
stdout: ctx.stdout,
});
}
if (isPluginHostInvocation(ctx.argv)) {
return await runPluginHostCommand(ctx, ctx.argv.slice(1));
}
// 与 plugin host 同理,且必须同样在 parseArgs 之前:SEA 下 dwf 的沙箱子进程是本二进制的
// 自 re-exec,argv 末位是入口文件路径——交给严格 parseArgs 只会报未知参数。
if (isDwfChildInvocation(ctx.argv)) {
return await runDwfChildCommand(ctx, ctx.argv.slice(1));
}
if (ctx.argv[0] === "hooks") {
return await runHooksCommand(ctx, deps, version);
}
let parsed: ReturnType<typeof parseGlobalArgs>;
let toolDisallowlist: readonly string[] | undefined;
try {
const extracted = extractDisallowedToolsArgs(ctx.argv);
parsed = parseGlobalArgs(extracted.args);
toolDisallowlist = extracted.toolDisallowlist;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
ctx.stderr.write(`${message}\n\n`);
writeHelp(ctx.stderr);
return 1;
}
let locale: UiLocale | undefined;
try {
locale = normalizeLocaleOption(parsed.values.locale as string | undefined);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
ctx.stderr.write(`${message}\n`);
return 1;
}
let mode: CliPermissionMode | undefined;
let browserUse: GlobalOptions["browserUse"];
let presentationSurface: PresentationSurface;
try {
mode = normalizePromptMode(parsed.values.mode as string | undefined);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
ctx.stderr.write(`${message}\n`);
return 1;
}
try {
browserUse = normalizeBrowserUse(parsed.values["browser-use"] as string | undefined);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
ctx.stderr.write(`${message}\n`);
return 1;
}
try {
presentationSurface = normalizePresentationSurface(parsed.values.surface as string | undefined);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
ctx.stderr.write(`${message}\n`);
return 1;
}
const browserExecutable = parsed.values["browser-executable"] as string | undefined;
if (browserExecutable !== undefined && browserUse !== "headless") {
ctx.stderr.write(`${BROWSER_EXECUTABLE_REQUIRES_HEADLESS_ERROR}\n`);
return 1;
}
const resumeRequest: CliResumeRequest = {
continueSession: parsed.values.continue === true,
resumeSessionId: parsed.values.resume as string | undefined,
};
if (resumeRequest.continueSession && resumeRequest.resumeSessionId) {
ctx.stderr.write("--resume and --continue cannot be used together.\n");
return 1;
}
const env = prepareCliRuntimeEnv(deps.env ?? process.env);
const detectedLocale = detectCliLocale(env);
let outputFormat: GlobalOptions["outputFormat"];
try {
outputFormat = normalizeOutputFormat(parsed.values["output-format"] as string | undefined);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
ctx.stderr.write(`${message}\n`);
return 1;
}
const options = globalOptions(
parsed.values,
locale,
detectedLocale,
browserUse,
browserExecutable,
outputFormat,
);
const forceMcs = parsed.values["force-mcs"] === true;
let targetRequest: CliTargetRequest | undefined;
try {
targetRequest = normalizeTargetRequest(parsed.values);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
ctx.stderr.write(`${message}\n`);
return 1;
}
if (targetRequest && typeof parsed.values.prompt === "string") {
ctx.stderr.write(`${TARGET_CONFLICTS_WITH_PROMPT_ERROR}\n`);
return 1;
}
if (
parsed.values.surface !== undefined &&
!isPresentationSurfaceSupportedInvocation({
positionals: parsed.positionals,
prompt: parsed.values.prompt as string | undefined,
targetRequest,
})
) {
ctx.stderr.write(`${SURFACE_SCOPE_ERROR}\n`);
return 1;
}
if (parsed.values.help === true) {
writeHelp(ctx.stdout, options.locale, options.detectedLocale);
return 0;
}
if (parsed.values.version === true) {
ctx.stdout.write(`${version}\n`);
return 0;
}
if (
options.enableWorkflow &&
(parsed.positionals.length > 0 ||
(typeof parsed.values.prompt !== "string" && targetRequest === undefined))
) {
ctx.stderr.write(`${ENABLE_WORKFLOW_SCOPE_ERROR}\n`);
return 1;
}
if (
options.memoryBench &&
(typeof parsed.values.prompt !== "string" || parsed.positionals.length > 0)
) {
ctx.stderr.write(`${MEMORY_BENCH_SCOPE_ERROR}\n`);
return 1;
}
if (
browserUse === "headless" &&
!isForceMcsSupportedInvocation({
positionals: parsed.positionals,
prompt: parsed.values.prompt as string | undefined,
targetRequest,
})
) {
ctx.stderr.write(`${BROWSER_USE_SCOPE_ERROR}\n`);
return 1;
}
if (
forceMcs &&
!isForceMcsSupportedInvocation({
positionals: parsed.positionals,
prompt: parsed.values.prompt as string | undefined,
targetRequest,
})
) {
ctx.stderr.write(`${FORCE_MCS_SCOPE_ERROR}\n`);
return 1;
}
let workingDirectory: string;
try {
workingDirectory = resolveCliCwd({
cwd: deps.cwd ?? process.cwd,
requestedCwd: parsed.values.cwd as string | undefined,
});
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
ctx.stderr.write(`${message}\n`);
return 1;
}
const commandDeps: RunDependencies = {
...deps,
cwd: () => workingDirectory,
env,
logger:
deps.logger ??
createNodeLoggerFactory({ env }).createLogger("zcode").child({ module: "cli" }),
loadDotenv: (dotenvOptions = {}) => {
const dotenvResult = (deps.loadDotenv ?? loadCliDotenv)(dotenvOptions);
applyCliRuntimeEnvSanitization(dotenvOptions.env ?? env);
return dotenvResult;
},
};
if (typeof parsed.values.prompt === "string") {
return await runPrompt(
ctx,
parsed.values.prompt,
parsed.values.attach ?? [],
options,
commandDeps,
version,
mode ?? DEFAULT_HEADLESS_PROMPT_MODE,
resumeRequest,
toolDisallowlist,
forceMcs,
presentationSurface,
);
}
if (targetRequest) {
return await runPrompt(
ctx,
buildHeadlessTargetCommand(targetRequest),
[],
options,
commandDeps,
version,
mode,
resumeRequest,
toolDisallowlist,
forceMcs,
presentationSurface,
);
}
switch (commandName(parsed.positionals)) {
case "help":
writeHelp(ctx.stdout, options.locale, options.detectedLocale);
return 0;
case "version":
ctx.stdout.write(`${version}\n`);
return 0;
case "agent-server":
case "app-server":
return await runZCodeProtocolCommand(
ctx,
options,
commandDeps,
presentationSurface,
parsed.values["prepare-storage"] === true,
);
case "doctor":
return runDoctor(ctx, options, workingDirectory);
case "login":
return await runLoginCommand(
ctx,
options,
commandDeps,
parsed.values["no-browser"] === true,
parsed.positionals.slice(1),
);
case "logout":
return await runLogoutCommand(ctx, options, commandDeps);
case "commands":
return await runCommandsCommand(ctx, options, commandDeps, parsed.positionals.slice(1));
case "plugin":
case "plugins":
return await runPluginsCommand(
ctx,
options,
commandDeps,
parsed.positionals.slice(1),
pluginsCommandFlags(parsed.values),
);
case "skills":
return await runSkillsCommand(ctx, options, commandDeps, parsed.positionals.slice(1));
case "tui":
return await runTuiCommand(
ctx,
options,
commandDeps,
version,
mode,
resumeRequest,
toolDisallowlist,
forceMcs,
);
default:
ctx.stderr.write(`Unknown command: ${commandName(parsed.positionals)}\n\n`);
writeHelp(ctx.stderr, options.locale, options.detectedLocale);
return 1;
}
};