zcode-app-cli 3.16.3-39 → 3.16.3-41
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/README.md +14 -4
- package/bin/zcode.js +39 -15
- package/docs/CONFIGURATION.md +1 -0
- package/docs/CONFIGURATION.zh-CN.md +1 -0
- package/package.json +2 -2
- package/vendor/cli-config.cjs +63 -0
- package/vendor/extraction.json +6 -1
- package/vendor/node_modules/@zcode/tui/dist/index.js +60 -19
- package/vendor/zcode.cjs +2 -2
package/README.md
CHANGED
|
@@ -132,8 +132,9 @@ bytes.
|
|
|
132
132
|
## Features
|
|
133
133
|
|
|
134
134
|
**Editor and input.** pi-tui differential rendering with a CJK-aware
|
|
135
|
-
multi-line editor; slash-command, unified `@` workspace/Plugin
|
|
136
|
-
|
|
135
|
+
multi-line editor; slash-command completion, unified `@` workspace/Plugin
|
|
136
|
+
references with recursive file search, and `$` Skill completion;
|
|
137
|
+
persisted prompt history through ZCode's history API;
|
|
137
138
|
`--no-color` and `NO_COLOR` support.
|
|
138
139
|
|
|
139
140
|
**Streaming and conversation.** Streamed assistant text from official ZCode
|
|
@@ -480,16 +481,25 @@ not available on `PATH`.
|
|
|
480
481
|
|
|
481
482
|
## Configuration
|
|
482
483
|
|
|
483
|
-
Select a model for one headless prompt without changing the
|
|
484
|
+
Select a model and reasoning effort for one headless prompt without changing the
|
|
485
|
+
saved default:
|
|
484
486
|
|
|
485
487
|
```bash
|
|
486
|
-
zcode --model account:zai-individual-coding-plan/GLM-5.3-Flash --prompt 'Reply with exactly: ok'
|
|
488
|
+
zcode --model account:zai-individual-coding-plan/GLM-5.3-Flash --effort high --prompt 'Reply with exactly: ok'
|
|
487
489
|
```
|
|
488
490
|
|
|
489
491
|
`--model` requires a full provider/model ID and `--prompt` (or `-p`). It also
|
|
490
492
|
overrides a resumed session's model for that run. Unknown or unavailable models
|
|
491
493
|
fail before a prompt is sent, rather than falling back to the default.
|
|
492
494
|
|
|
495
|
+
`--effort` selects the model's reasoning level for that prompt. Levels are
|
|
496
|
+
model-specific (for example `disabled`, `low`, `high` and `max`); run the TUI's
|
|
497
|
+
`/effort list` for the current model, or inspect `optionSpecs.reasoningLevel` in
|
|
498
|
+
the provider catalog. `--effort auto` keeps the current or resumed default.
|
|
499
|
+
Without `--effort`, `--model` uses the model's default level. Both flags require
|
|
500
|
+
`--prompt` (or `-p`) and leave the saved default for new sessions unchanged; the
|
|
501
|
+
run's model and effort are recorded on that session.
|
|
502
|
+
|
|
493
503
|
ZCode reads MCP servers, hooks, plugins, permissions, network, storage and display
|
|
494
504
|
settings from `~/.zcode/cli/setting.json` (or
|
|
495
505
|
`%USERPROFILE%\.zcode\cli\setting.json` on Windows). Project settings use
|
package/bin/zcode.js
CHANGED
|
@@ -1476,7 +1476,10 @@ async function missingCodingPlanKey(options = {}) {
|
|
|
1476
1476
|
}
|
|
1477
1477
|
//#endregion
|
|
1478
1478
|
//#region src/prompt-model.ts
|
|
1479
|
-
function
|
|
1479
|
+
function removalIndexes(token) {
|
|
1480
|
+
return token.inlineValue ? [token.index] : [token.index, token.index + 1];
|
|
1481
|
+
}
|
|
1482
|
+
function extractPromptOverrides(args, optionTypes) {
|
|
1480
1483
|
const parsed = parseArgs({
|
|
1481
1484
|
args,
|
|
1482
1485
|
allowPositionals: true,
|
|
@@ -1488,21 +1491,35 @@ function extractPromptModel(args, optionTypes) {
|
|
|
1488
1491
|
type: "string",
|
|
1489
1492
|
short: "p"
|
|
1490
1493
|
},
|
|
1491
|
-
model: { type: "string" }
|
|
1494
|
+
model: { type: "string" },
|
|
1495
|
+
effort: { type: "string" }
|
|
1492
1496
|
}
|
|
1493
1497
|
});
|
|
1494
|
-
const
|
|
1495
|
-
|
|
1496
|
-
if (
|
|
1497
|
-
if (
|
|
1498
|
-
|
|
1499
|
-
if (
|
|
1500
|
-
const
|
|
1501
|
-
|
|
1502
|
-
|
|
1498
|
+
const modelTokens = parsed.tokens.filter((token) => token.kind === "option" && token.name === "model");
|
|
1499
|
+
const effortTokens = parsed.tokens.filter((token) => token.kind === "option" && token.name === "effort");
|
|
1500
|
+
if (modelTokens.length === 0 && effortTokens.length === 0) return { args };
|
|
1501
|
+
if (modelTokens.length !== 0 && modelTokens.length !== 1) throw new Error("Specify --model only once.");
|
|
1502
|
+
if (effortTokens.length !== 0 && effortTokens.length !== 1) throw new Error("Specify --effort only once.");
|
|
1503
|
+
if (typeof parsed.values.prompt !== "string") throw new Error(`${modelTokens.length ? "--model" : "--effort"} requires --prompt or -p.`);
|
|
1504
|
+
const removed = /* @__PURE__ */ new Set();
|
|
1505
|
+
let model;
|
|
1506
|
+
let effort;
|
|
1507
|
+
if (modelTokens.length === 1) {
|
|
1508
|
+
if (typeof parsed.values.model !== "string") throw new Error("--model must be a provider/model ID.");
|
|
1509
|
+
model = parsed.values.model.trim();
|
|
1510
|
+
if (!/^[^/\s]+\/\S+$/u.test(model)) throw new Error("--model must be a provider/model ID.");
|
|
1511
|
+
for (const index of removalIndexes(modelTokens[0])) removed.add(index);
|
|
1512
|
+
}
|
|
1513
|
+
if (effortTokens.length === 1) {
|
|
1514
|
+
if (typeof parsed.values.effort !== "string") throw new Error("--effort requires a value.");
|
|
1515
|
+
effort = parsed.values.effort.trim();
|
|
1516
|
+
if (!effort || effort.startsWith("-") || /\s/u.test(effort)) throw new Error("--effort requires a single effort level.");
|
|
1517
|
+
for (const index of removalIndexes(effortTokens[0])) removed.add(index);
|
|
1518
|
+
}
|
|
1503
1519
|
return {
|
|
1504
1520
|
args: args.filter((_, index) => !removed.has(index)),
|
|
1505
|
-
model
|
|
1521
|
+
model,
|
|
1522
|
+
effort
|
|
1506
1523
|
};
|
|
1507
1524
|
}
|
|
1508
1525
|
//#endregion
|
|
@@ -1730,6 +1747,7 @@ function runtimeEnvironment(extra = {}, inspectConfiguration = false) {
|
|
|
1730
1747
|
delete env.ZCODE_CLI_OAUTH_CALLBACK_STDIN;
|
|
1731
1748
|
delete env.ZCODE_CLI_MIGRATE_CONFIG;
|
|
1732
1749
|
delete env.ZCODE_CLI_PROMPT_MODEL;
|
|
1750
|
+
delete env.ZCODE_CLI_PROMPT_EFFORT;
|
|
1733
1751
|
const distributionVersion = readDistributionVersion();
|
|
1734
1752
|
const appVersion = readJsonVersion(extractionMetadataPath, "appVersion");
|
|
1735
1753
|
const inherited = {
|
|
@@ -1890,10 +1908,12 @@ async function main(args) {
|
|
|
1890
1908
|
return 0;
|
|
1891
1909
|
}
|
|
1892
1910
|
let promptModel;
|
|
1911
|
+
let promptEffort;
|
|
1893
1912
|
try {
|
|
1894
|
-
const parsed =
|
|
1913
|
+
const parsed = extractPromptOverrides(args, readRuntimeCliOptionTypes());
|
|
1895
1914
|
args = parsed.args;
|
|
1896
1915
|
promptModel = parsed.model;
|
|
1916
|
+
promptEffort = parsed.effort;
|
|
1897
1917
|
} catch (error) {
|
|
1898
1918
|
console.error(`Error: ${error instanceof Error ? error.message : String(error)}`);
|
|
1899
1919
|
return 1;
|
|
@@ -2023,9 +2043,13 @@ async function main(args) {
|
|
|
2023
2043
|
const runtimeArgs = withDefaultBrowserUse(login.args);
|
|
2024
2044
|
const code = await runRuntime(node, runtimeArgs, {
|
|
2025
2045
|
...firstRunSetupEnv(setupPending, runtimeArgs),
|
|
2026
|
-
...promptModel ? { ZCODE_CLI_PROMPT_MODEL: promptModel } : {}
|
|
2046
|
+
...promptModel ? { ZCODE_CLI_PROMPT_MODEL: promptModel } : {},
|
|
2047
|
+
...promptEffort ? { ZCODE_CLI_PROMPT_EFFORT: promptEffort } : {}
|
|
2027
2048
|
});
|
|
2028
|
-
if (code === 0 && (args.includes("--help") || args.includes("-h")))
|
|
2049
|
+
if (code === 0 && (args.includes("--help") || args.includes("-h"))) {
|
|
2050
|
+
console.log("\n --model <provider/model> Select a model for this --prompt run without changing the saved default.");
|
|
2051
|
+
console.log(" --effort <level> Select the model reasoning effort for this --prompt run; auto keeps the default.");
|
|
2052
|
+
}
|
|
2029
2053
|
return code;
|
|
2030
2054
|
} catch (error) {
|
|
2031
2055
|
console.error(`Error: ${error instanceof Error ? error.message : String(error)}`);
|
package/docs/CONFIGURATION.md
CHANGED
|
@@ -101,6 +101,7 @@ reported rather than replaced by old settings.
|
|
|
101
101
|
| Providers and model metadata | Shared native `provider_config.json` |
|
|
102
102
|
| Default model in `/settings` | Writes the shared default and applies it to the current session |
|
|
103
103
|
| `/model`, model cycling and reasoning effort | Change/persist this session's native selection; shared default stays unchanged |
|
|
104
|
+
| `--model` / `--effort` on `--prompt` | Per-run model and reasoning-level override; the saved default for new sessions stays unchanged |
|
|
104
105
|
| `/new` | Reads the current shared default |
|
|
105
106
|
| Resume/restart | Restores the session's model and reasoning options |
|
|
106
107
|
| Language and memory | Reads Desktop `localePreference` / `memoryEnabled`; explicit CLI settings override these values |
|
|
@@ -84,6 +84,7 @@ CLI 专属字段迁移到 `~/.zcode/cli/setting.json`,省略 provider、main/l
|
|
|
84
84
|
| Provider 和模型元数据 | 共享的原生 `provider_config.json` |
|
|
85
85
|
| `/settings` 中的默认模型 | 写入共享默认选择,并应用到当前会话 |
|
|
86
86
|
| `/model`、模型循环切换、推理强度 | 修改并保存当前会话选择,不改共享默认值 |
|
|
87
|
+
| `--prompt` 上的 `--model`/`--effort` | 仅覆盖本次运行的模型和推理强度;不改共享默认值(会话会记录本次选择) |
|
|
87
88
|
| `/new` | 读取当前共享默认模型 |
|
|
88
89
|
| 恢复会话/重启 | 恢复该会话保存的模型和推理选项 |
|
|
89
90
|
| 语言与记忆 | 读取桌面端 `localePreference`/`memoryEnabled`,显式 CLI 设置优先 |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "zcode-app-cli",
|
|
3
|
-
"version": "3.16.3-
|
|
3
|
+
"version": "3.16.3-41",
|
|
4
4
|
"description": "Unofficial terminal client for the ZCode agent runtime",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agent",
|
|
@@ -72,7 +72,7 @@
|
|
|
72
72
|
"test:node": "node --test test/node/*.test.cjs",
|
|
73
73
|
"test:tui": "bun run test:tui:component && bun run test:tui:e2e",
|
|
74
74
|
"test:tui:component": "bun test test/tui/scenario-http.test.ts test/tui/scenario-runtime.test.ts test/tui/scenario-shell.test.ts test/tui/scenario-workspace.test.ts test/tui/terminal-screen.test.ts",
|
|
75
|
-
"test:tui:e2e": "bun test test/tui/allowlisted-shell.test.ts test/tui/dynamic-workflows.test.ts test/tui/http-mock.test.ts test/tui/input-actions.test.ts test/tui/model-resume.test.ts test/tui/model-status.test.ts test/tui/permission-request-queue.test.ts test/tui/run-scenario.test.ts test/tui/runtime-refresh.test.ts test/tui/session-lifecycle.test.ts test/tui/session-rename.test.ts test/tui/startup.test.ts test/tui/terminal-session.test.ts test/tui/write-and-diff.test.ts",
|
|
75
|
+
"test:tui:e2e": "bun test test/tui/allowlisted-shell.test.ts test/tui/dynamic-workflows.test.ts test/tui/http-mock.test.ts test/tui/input-actions.test.ts test/tui/model-resume.test.ts test/tui/model-status.test.ts test/tui/permission-request-queue.test.ts test/tui/run-scenario.test.ts test/tui/runtime-refresh.test.ts test/tui/session-lifecycle.test.ts test/tui/session-rename.test.ts test/tui/startup.test.ts test/tui/terminal-exit.test.ts test/tui/terminal-session.test.ts test/tui/write-and-diff.test.ts",
|
|
76
76
|
"test:tui:host": "bun test test/tui/scenario-mountx.test.ts",
|
|
77
77
|
"test:tui:manual": "bun scripts/tui-scenario.ts --manual",
|
|
78
78
|
"test:tui-scenario": "bun scripts/tui-scenario.ts",
|
package/vendor/cli-config.cjs
CHANGED
|
@@ -391,6 +391,68 @@ async function restoreTuiBackgroundTasks(app, queries) {
|
|
|
391
391
|
}
|
|
392
392
|
}
|
|
393
393
|
//#endregion
|
|
394
|
+
//#region src/runtime-workspace-paths.ts
|
|
395
|
+
function compare(first, second) {
|
|
396
|
+
return first.rank - second.rank || Number(first.item.kind === "file") - Number(second.item.kind === "file") || first.depth - second.depth || first.item.path.localeCompare(second.item.path);
|
|
397
|
+
}
|
|
398
|
+
/** Extend the runtime's native path completion with workspace-wide name searches. */
|
|
399
|
+
function withRecursiveWorkspacePathSuggestions(native, options) {
|
|
400
|
+
return async (request) => {
|
|
401
|
+
const empty = {
|
|
402
|
+
items: [],
|
|
403
|
+
truncated: false
|
|
404
|
+
};
|
|
405
|
+
if (request.abortSignal?.aborted) return empty;
|
|
406
|
+
const query = request.token.replace(/^@/u, "");
|
|
407
|
+
if (!query || query === ".." || /[\\/]/u.test(query)) return native(request);
|
|
408
|
+
const normalizedQuery = query.toLowerCase();
|
|
409
|
+
const includeHidden = query.startsWith(".");
|
|
410
|
+
const limit = Number.isFinite(request.limit) ? Math.max(1, Math.floor(request.limit)) : 50;
|
|
411
|
+
const pending = [options.workspaceDirectory];
|
|
412
|
+
const best = [];
|
|
413
|
+
let matches = 0;
|
|
414
|
+
while (pending.length > 0) {
|
|
415
|
+
if (request.abortSignal?.aborted) return empty;
|
|
416
|
+
const listings = await Promise.all(pending.splice(-8).map(async (path) => {
|
|
417
|
+
try {
|
|
418
|
+
return (await options.fileSystemPort.listDirectory({ path }, { signal: request.abortSignal })).entries;
|
|
419
|
+
} catch {
|
|
420
|
+
return [];
|
|
421
|
+
}
|
|
422
|
+
}));
|
|
423
|
+
if (request.abortSignal?.aborted) return empty;
|
|
424
|
+
for (const entries of listings) for (const entry of entries) {
|
|
425
|
+
if (entry.kind !== "file" && entry.kind !== "directory") continue;
|
|
426
|
+
if (entry.kind === "directory" && options.excludedDirectories.has(entry.name)) continue;
|
|
427
|
+
if (!includeHidden && entry.name.startsWith(".")) continue;
|
|
428
|
+
const path = (0, node_path.relative)(options.workspaceDirectory, entry.path);
|
|
429
|
+
if (!path || path === ".." || path.startsWith(`..${node_path.sep}`) || (0, node_path.isAbsolute)(path)) continue;
|
|
430
|
+
if (entry.kind === "directory") pending.push(entry.path);
|
|
431
|
+
const name = entry.name.toLowerCase();
|
|
432
|
+
if (!name.includes(normalizedQuery)) continue;
|
|
433
|
+
matches += 1;
|
|
434
|
+
const displayPath = path.split(node_path.sep).join("/");
|
|
435
|
+
const candidate = {
|
|
436
|
+
item: {
|
|
437
|
+
kind: entry.kind,
|
|
438
|
+
path: entry.kind === "directory" ? `${displayPath}/` : displayPath
|
|
439
|
+
},
|
|
440
|
+
rank: name === normalizedQuery ? 0 : name.startsWith(normalizedQuery) ? 1 : 2,
|
|
441
|
+
depth: displayPath.split("/").length
|
|
442
|
+
};
|
|
443
|
+
const index = best.findIndex((item) => compare(candidate, item) < 0);
|
|
444
|
+
if (index >= 0) best.splice(index, 0, candidate);
|
|
445
|
+
else if (best.length < limit) best.push(candidate);
|
|
446
|
+
if (best.length > limit) best.pop();
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
return {
|
|
450
|
+
items: best.map(({ item }) => item),
|
|
451
|
+
truncated: matches > limit
|
|
452
|
+
};
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
//#endregion
|
|
394
456
|
//#region src/runtime-sqlite-connection.ts
|
|
395
457
|
const sqliteOperationScope = new node_async_hooks.AsyncLocalStorage();
|
|
396
458
|
function isSqliteBusyError(error) {
|
|
@@ -1115,5 +1177,6 @@ exports.sendTuiBackgroundTaskMessage = sendTuiBackgroundTaskMessage;
|
|
|
1115
1177
|
exports.sharedOAuthCredentialReader = sharedOAuthCredentialReader;
|
|
1116
1178
|
exports.sqliteRecoveryStats = sqliteRecoveryStats;
|
|
1117
1179
|
exports.startTuiSavedWorkflow = startTuiSavedWorkflow;
|
|
1180
|
+
exports.withRecursiveWorkspacePathSuggestions = withRecursiveWorkspacePathSuggestions;
|
|
1118
1181
|
exports.writeConfigurationDoctor = writeConfigurationDoctor;
|
|
1119
1182
|
exports.zaiBusinessAccessToken = zaiBusinessAccessToken;
|
package/vendor/extraction.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"appVersion": "3.16.3",
|
|
3
3
|
"cliVersion": "0.17.0",
|
|
4
|
-
"extractedAt": "2026-10-
|
|
4
|
+
"extractedAt": "2026-10-27T01:30:48.815Z",
|
|
5
5
|
"sha512": "WvOb2B4NnRdNFIAKuMJ+S0vCT+uQfVfpiFPLsraG8KQCHTXQRsvC58OkTz79snfbmmCkAetXUi/RJ39bKG+T8g==",
|
|
6
6
|
"source": "https://cdn-zcode.z.ai/zcode/electron/releases/3.16.3/linux-x64/ZCode-3.16.3-linux-x64.deb",
|
|
7
7
|
"runtimeCapabilities": {
|
|
@@ -162,6 +162,11 @@
|
|
|
162
162
|
"requirement": "required",
|
|
163
163
|
"status": "applied"
|
|
164
164
|
},
|
|
165
|
+
{
|
|
166
|
+
"id": "recursive-workspace-paths",
|
|
167
|
+
"requirement": "required",
|
|
168
|
+
"status": "applied"
|
|
169
|
+
},
|
|
165
170
|
{
|
|
166
171
|
"id": "tui-bridge",
|
|
167
172
|
"requirement": "required",
|
|
@@ -406,6 +406,15 @@ function watchStreamErrors(sources, onError) {
|
|
|
406
406
|
};
|
|
407
407
|
}
|
|
408
408
|
//#endregion
|
|
409
|
+
//#region packages/zcode-tui/src/terminal-cleanup.ts
|
|
410
|
+
/** Disable enhanced keyboard reporting and consume in-flight releases before restoring the terminal. */
|
|
411
|
+
async function stopTui(ui) {
|
|
412
|
+
try {
|
|
413
|
+
await ui.terminal.drainInput();
|
|
414
|
+
} catch {}
|
|
415
|
+
ui.stop();
|
|
416
|
+
}
|
|
417
|
+
//#endregion
|
|
409
418
|
//#region packages/zcode-tui/src/startup.ts
|
|
410
419
|
async function loadTuiStartupOptions(options) {
|
|
411
420
|
const loadStartupOptions = options.loadStartupOptions;
|
|
@@ -434,15 +443,16 @@ async function loadTuiStartupOptions(options) {
|
|
|
434
443
|
return { consume: true };
|
|
435
444
|
});
|
|
436
445
|
const removeStreamErrorGuards = watchStreamErrors([process.stdout, process.stderr], () => cancel(1));
|
|
437
|
-
process.
|
|
438
|
-
process.
|
|
439
|
-
if (process.platform !== "win32") process.
|
|
446
|
+
process.on("SIGINT", onSigint);
|
|
447
|
+
process.on("SIGTERM", onSigterm);
|
|
448
|
+
if (process.platform !== "win32") process.on("SIGHUP", onSighup);
|
|
449
|
+
let readyOptions;
|
|
440
450
|
try {
|
|
441
451
|
ui.start();
|
|
442
452
|
ui.renderNow();
|
|
443
453
|
await new Promise((resolve) => setImmediate(resolve));
|
|
444
454
|
if (cancelled) return void 0;
|
|
445
|
-
|
|
455
|
+
readyOptions = await Promise.race([Promise.resolve().then(async () => {
|
|
446
456
|
if (cancelled) return void 0;
|
|
447
457
|
const startup = await loadStartupOptions();
|
|
448
458
|
return cancelled ? void 0 : {
|
|
@@ -451,21 +461,22 @@ async function loadTuiStartupOptions(options) {
|
|
|
451
461
|
};
|
|
452
462
|
}), cancellation]);
|
|
453
463
|
} finally {
|
|
454
|
-
process.off("SIGINT", onSigint);
|
|
455
|
-
process.off("SIGTERM", onSigterm);
|
|
456
|
-
if (process.platform !== "win32") process.off("SIGHUP", onSighup);
|
|
457
464
|
try {
|
|
458
465
|
ui.clear();
|
|
459
466
|
ui.renderNow();
|
|
460
467
|
} finally {
|
|
461
468
|
try {
|
|
462
|
-
ui
|
|
469
|
+
await stopTui(ui);
|
|
463
470
|
} finally {
|
|
464
471
|
await new Promise((resolve) => setImmediate(resolve));
|
|
472
|
+
process.off("SIGINT", onSigint);
|
|
473
|
+
process.off("SIGTERM", onSigterm);
|
|
474
|
+
if (process.platform !== "win32") process.off("SIGHUP", onSighup);
|
|
465
475
|
removeStreamErrorGuards();
|
|
466
476
|
}
|
|
467
477
|
}
|
|
468
478
|
}
|
|
479
|
+
return cancelled ? void 0 : readyOptions;
|
|
469
480
|
}
|
|
470
481
|
//#endregion
|
|
471
482
|
//#region packages/zcode-tui/src/prompt-preflight.ts
|
|
@@ -158170,7 +158181,7 @@ function normalizeEvent(value) {
|
|
|
158170
158181
|
partId: asString(body.partId) ?? asString(body.partID) ?? part?.partId,
|
|
158171
158182
|
sessionId: asString(value.sessionId) ?? asString(value.sessionID) ?? asString(params?.sessionId) ?? asString(params?.sessionID) ?? asString(payload?.sessionId) ?? asString(payload?.sessionID) ?? asString(body.sessionId) ?? asString(body.sessionID) ?? part?.sessionId,
|
|
158172
158183
|
turnId: envelopeString("turnId") ?? envelopeString("turnID"),
|
|
158173
|
-
eventId: asString(value.eventId) ?? (params && asString(params.eventId)) ?? asString(value.id) ?? (params && asString(params.id)) ?? asString(body.eventId)
|
|
158184
|
+
eventId: asString(value.eventId) ?? (params && asString(params.eventId)) ?? asString(value.id) ?? (params && asString(params.id)) ?? asString(body.eventId),
|
|
158174
158185
|
inputSource: envelopeString("inputSource"),
|
|
158175
158186
|
taskId: envelopeString("taskId") ?? envelopeString("taskID") ?? (originMeta && asString(originMeta.workId)),
|
|
158176
158187
|
taskIds: strings("taskIds") ?? strings("taskIDs") ?? (originMeta && (Array.isArray(originMeta.workIds) ? originMeta.workIds.filter((item) => typeof item === "string") : asString(originMeta.workId) ? [asString(originMeta.workId)] : void 0)),
|
|
@@ -158236,6 +158247,34 @@ function normalizeEvent(value) {
|
|
|
158236
158247
|
function isModelCancellationEvent(event) {
|
|
158237
158248
|
return event.type === "model_request_failed" && (event.reason?.toLowerCase() === "cancelled" || event.errorCode?.toLowerCase() === "model_request_cancelled" || event.exceptionType?.toLowerCase() === "aborterror");
|
|
158238
158249
|
}
|
|
158250
|
+
/**
|
|
158251
|
+
* The runtime forwards every session event to each live subscription (the
|
|
158252
|
+
* active prompt, steers, watchers kept open around background-task
|
|
158253
|
+
* notification turns), so one event can reach the TUI several times.
|
|
158254
|
+
* Streamed deltas are appended rather than replaced, so each redelivery
|
|
158255
|
+
* would render again — exact redeliveries of an already-seen event
|
|
158256
|
+
* (same eventId, or the same delivered object when no id is attached)
|
|
158257
|
+
* must be dropped. Distinct events never share a key: separate deliveries
|
|
158258
|
+
* are separate objects, and legitimately repeated delta content produces
|
|
158259
|
+
* new event objects each time.
|
|
158260
|
+
*/
|
|
158261
|
+
function createStreamEventRedeliveryFilter(capacity = 256) {
|
|
158262
|
+
const recent = /* @__PURE__ */ new Map();
|
|
158263
|
+
return { duplicate(value, event) {
|
|
158264
|
+
const key = event.eventId ?? value;
|
|
158265
|
+
if (recent.has(key)) {
|
|
158266
|
+
recent.delete(key);
|
|
158267
|
+
recent.set(key, true);
|
|
158268
|
+
return true;
|
|
158269
|
+
}
|
|
158270
|
+
recent.set(key, true);
|
|
158271
|
+
if (recent.size > capacity) {
|
|
158272
|
+
const oldest = recent.keys().next().value;
|
|
158273
|
+
if (oldest !== void 0) recent.delete(oldest);
|
|
158274
|
+
}
|
|
158275
|
+
return false;
|
|
158276
|
+
} };
|
|
158277
|
+
}
|
|
158239
158278
|
const toolCancellationValues = /* @__PURE__ */ new Set([
|
|
158240
158279
|
"aborterror",
|
|
158241
158280
|
"cancelled",
|
|
@@ -166708,6 +166747,7 @@ var ZCodeTui = class {
|
|
|
166708
166747
|
attachmentBar;
|
|
166709
166748
|
editor;
|
|
166710
166749
|
assistantStream;
|
|
166750
|
+
deliveredStreamEvents = createStreamEventRedeliveryFilter();
|
|
166711
166751
|
notifications;
|
|
166712
166752
|
skillCatalog;
|
|
166713
166753
|
done;
|
|
@@ -166913,9 +166953,9 @@ var ZCodeTui = class {
|
|
|
166913
166953
|
const onSigterm = () => this.handleSignal("SIGTERM");
|
|
166914
166954
|
const onSighup = () => this.handleSignal("SIGHUP");
|
|
166915
166955
|
this.installStreamErrorGuards();
|
|
166916
|
-
process.
|
|
166917
|
-
process.
|
|
166918
|
-
if (process.platform !== "win32") process.
|
|
166956
|
+
process.on("SIGINT", onSigint);
|
|
166957
|
+
process.on("SIGTERM", onSigterm);
|
|
166958
|
+
if (process.platform !== "win32") process.on("SIGHUP", onSighup);
|
|
166919
166959
|
let startAttempted = false;
|
|
166920
166960
|
try {
|
|
166921
166961
|
if (this.stopped) {
|
|
@@ -166959,16 +166999,16 @@ var ZCodeTui = class {
|
|
|
166959
166999
|
if (this.sessionModelIssue) this.recoverSessionModel();
|
|
166960
167000
|
await this.done;
|
|
166961
167001
|
} finally {
|
|
166962
|
-
process.off("SIGINT", onSigint);
|
|
166963
|
-
process.off("SIGTERM", onSigterm);
|
|
166964
|
-
if (process.platform !== "win32") process.off("SIGHUP", onSighup);
|
|
166965
167002
|
try {
|
|
166966
|
-
if (startAttempted
|
|
167003
|
+
if (startAttempted) {
|
|
166967
167004
|
this.stop();
|
|
166968
167005
|
await this.done;
|
|
166969
167006
|
}
|
|
166970
167007
|
} finally {
|
|
166971
167008
|
await new Promise((resolve) => setImmediate(resolve));
|
|
167009
|
+
process.off("SIGINT", onSigint);
|
|
167010
|
+
process.off("SIGTERM", onSigterm);
|
|
167011
|
+
if (process.platform !== "win32") process.off("SIGHUP", onSighup);
|
|
166972
167012
|
this.removeStreamErrorGuards?.();
|
|
166973
167013
|
this.removeStreamErrorGuards = void 0;
|
|
166974
167014
|
}
|
|
@@ -168164,6 +168204,7 @@ var ZCodeTui = class {
|
|
|
168164
168204
|
if (turnEpoch !== void 0 && turnEpoch !== this.activeTurnEpoch) return;
|
|
168165
168205
|
const event = normalizeEvent(value);
|
|
168166
168206
|
if (!event || this.isForeignSessionEvent(event)) return;
|
|
168207
|
+
if (this.deliveredStreamEvents.duplicate(event.raw, event)) return;
|
|
168167
168208
|
if (runtimeContextRefreshNeeded(event)) this.runtimeContextCache.invalidate();
|
|
168168
168209
|
if (this.handleDynamicWorkflowEvent(value, event.type)) return;
|
|
168169
168210
|
const taskScoped = this.backgroundTaskEvents.isTaskScoped(event);
|
|
@@ -171526,13 +171567,13 @@ var ZCodeTui = class {
|
|
|
171526
171567
|
try {
|
|
171527
171568
|
this.notifications.stop();
|
|
171528
171569
|
} catch {}
|
|
171529
|
-
try {
|
|
171530
|
-
this.ui.stop();
|
|
171531
|
-
} catch {}
|
|
171532
171570
|
this.finishStop(elapsedMilliseconds);
|
|
171533
171571
|
}
|
|
171534
171572
|
async finishStop(elapsedMilliseconds) {
|
|
171535
171573
|
try {
|
|
171574
|
+
try {
|
|
171575
|
+
await stopTui(this.ui);
|
|
171576
|
+
} catch {}
|
|
171536
171577
|
const [, resumeTarget] = await Promise.all([this.refreshExitUsage(), this.readExitResumeTarget()]);
|
|
171537
171578
|
const summary = buildExitSummary({
|
|
171538
171579
|
elapsedMilliseconds,
|
package/vendor/zcode.cjs
CHANGED
|
@@ -15580,7 +15580,7 @@ ${Nvc}${b?` (traceId: ${b})`:""}
|
|
|
15580
15580
|
`),0;if(x?.type==="known"&&x.name==="workflow"&&!YY(S))return e.stderr.write(`Error: ${Mxe}
|
|
15581
15581
|
`),1;if(x?.type==="known"&&x.name==="skill"&&!x.skillName)return await TRt(e,o,i,[]);if(x?.type==="known"&&x.name==="login")return x.args.length>0?(e.stderr.write(`Usage: /login
|
|
15582
15582
|
`),1):await lRt(e,o,i,!1);if(x?.type==="known"&&x.name==="logout")return x.args.length>0?(e.stderr.write(`Usage: /logout
|
|
15583
|
-
`),1):await uRt(e,o,i);let I=x?.type==="known"&&x.name==="skill"?eze(x.skillName,x.task):t,C,R,O,U,j,z,$=r(()=>{z?.(),z=void 0},"stopObservingEvents"),K,q=new AbortController,re=Math.max(1,Math.trunc(i.shutdownCleanupTimeoutMs??AQe)),ne=r(async()=>{let de=R;O??=(async()=>{await CF(async()=>de?.close?.(),re),await CF(async()=>U?.close(),re),await CF(async()=>j?.(),re),K?.dispose()})(),await O},"closeApp"),ke=PQe({abort:r(de=>q.abort(new Error(`CLI received ${de}`)),"abort"),cleanup:ne,cleanupTimeoutMs:i.shutdownCleanupTimeoutMs,exitProcess:i.exitProcess,process:i.shutdownProcess});try{let de=i.env??process.env,Fe=(i.cwd??process.cwd)(),Xe=(i.loadDotenv??qA)({cwd:Fe,env:de});if(Xe.error)throw new Error(`Failed to load environment file: ${Xe.path}`,{cause:Xe.error});let Ue=await xRt(u,Fe,de,i),Ct=i.createZCodeApp?void 0:await Iy(),ut=i.createZCodeApp??Ct?.createZCodeApp;if(!ut)throw new Error("ZCode app factory is unavailable.");let Ee=Pvc(o),pt;if(Ee&&(pt=i.mapSessionEvent??Ct?.mapSessionEvent,!pt))throw new Error("Event streaming is unavailable: the bootstrap module did not load.");let dt=oyi({...pt?{mapSessionEvent:pt}:{},options:o,stderr:e.stderr,stdout:e.stdout}),st=i.prepareZCodeTelemetryEnv??Ct?.prepareZCodeTelemetryEnv;st&&(j=i.shutdownZCodeTelemetry??Ct?.shutdownZCodeTelemetry);let je=st?await st(de,{cliVersion:a,productVersion:de.ZCODE_APP_VERSION}):de,Pt=i.startProcessProviderRegistryRuntime??Ct?.startProcessProviderRegistryRuntime;if(!Pt)throw new Error("Provider Registry runtime is unavailable.");K=await Pt(je,i.skipUserConfig?{}:{standalone:{...IOe(e.stderr),...i.userConfigPath?{legacyCliUserConfigFilePath:i.userConfigPath}:{}}});let We=(i.createProviderEndpointRoutingPort??Ct?.createDefaultProviderEndpointRoutingPort)?.({appVersion:a,env:de,workingDirectory:Fe});if(U=bRt(o,i),R=await ut({modelSelectionMode:"cli-default",browserControlPort:U?.browserControlPort,env:je,permissionBroker:nyi(),...We?{providerEndpointRoutingPort:We}:{},providerRegistry:K.runtime.registryService,configuredDefaultModelSelection:K.configuredDefaultModelSelection,...K.providerRuntimeHeadersPort?{providerRuntimeHeadersPort:K.providerRuntimeHeadersPort}:{},resume:Ue!==void 0,runtimeConfig:{...c?{mode:c}:{},...f?{toolDisallowlist:f}:{},toolSearch:{mode:_},...h?{midConversationSystem:{mode:"force"}}:{},...hRt(S),memory:{extractionEnabled:o.memoryBench===!0},modelStreaming:"on",presentationSurface:b,workingDirectory:Fe},sessionId:Ue,uiDetectedLocale:o.detectedLocale,uiLocale:o.locale,version:a}),q.signal.aborted){let we=R;throw R=void 0,await CF(async()=>we.close?.(),re),q.signal.reason}let $zCliDefaultPromptModel=process.env.ZCODE_CLI_PROMPT_MODEL;if($zCliDefaultPromptModel)await R.setModel($zCliDefaultPromptModel,{transient:true,cliDefault:true});if(C=R.traceId,o.memoryBench&&!R.runtime.isProjectMemoryEnabled())throw new Error(Mvc);if(x&&await jvc(x,i))return await zvc(e,o,R,t,c,C,q.signal,i,S);z=wRt(R.runtime)?.({onSessionEvent:dt.observe});let Rt=syi(R.runtime),cn=await R.submitPrompt(n.length>0?{text:I,attachments:n.map(we=>({type:Lvc(we),path:we}))}:I,{abortSignal:q.signal,...z?{}:{onEvent:dt.observe}});dt.beginWaitPhase(cn.turnId?String(cn.turnId):void 0),C=cn.traceId??C,dt.hasWorkflowActivity()&&Rt&&await iyi({runtime:Rt,signal:q.signal}),o.memoryBench&&(await R.runtime.drainMemoryExtractions(null),q.signal.throwIfAborted()),$();let dn=[cn.response,...dt.waitPhaseTurnResponses()].filter(we=>we.trim().length>0),zn=dn.at(-1)??cn.response,sn=dn.length>1,rt=await qvc({bootstrapModule:Ct,deps:i,events:cn.events,workingDirectory:Fe});return Ee?(e.stdout.write(`${JSON.stringify({type:"result",sessionId:R.sessionId,traceId:C,...cn.turnId?{turnId:cn.turnId}:{},response:zn,...sn?{turnResponses:dn}:{},...cn.usage?{usage:{...cn.usage}}:{},eventCount:cn.events.length,projection:{status:cn.projection.status,turnCount:cn.projection.turnCount,totalTokenCount:cn.projection.totalTokenCount,contextUsed:cn.projection.contextUsed??null,contextWindow:cn.projection.contextWindow??null}})}
|
|
15583
|
+
`),1):await uRt(e,o,i);let I=x?.type==="known"&&x.name==="skill"?eze(x.skillName,x.task):t,C,R,O,U,j,z,$=r(()=>{z?.(),z=void 0},"stopObservingEvents"),K,q=new AbortController,re=Math.max(1,Math.trunc(i.shutdownCleanupTimeoutMs??AQe)),ne=r(async()=>{let de=R;O??=(async()=>{await CF(async()=>de?.close?.(),re),await CF(async()=>U?.close(),re),await CF(async()=>j?.(),re),K?.dispose()})(),await O},"closeApp"),ke=PQe({abort:r(de=>q.abort(new Error(`CLI received ${de}`)),"abort"),cleanup:ne,cleanupTimeoutMs:i.shutdownCleanupTimeoutMs,exitProcess:i.exitProcess,process:i.shutdownProcess});try{let de=i.env??process.env,Fe=(i.cwd??process.cwd)(),Xe=(i.loadDotenv??qA)({cwd:Fe,env:de});if(Xe.error)throw new Error(`Failed to load environment file: ${Xe.path}`,{cause:Xe.error});let Ue=await xRt(u,Fe,de,i),Ct=i.createZCodeApp?void 0:await Iy(),ut=i.createZCodeApp??Ct?.createZCodeApp;if(!ut)throw new Error("ZCode app factory is unavailable.");let Ee=Pvc(o),pt;if(Ee&&(pt=i.mapSessionEvent??Ct?.mapSessionEvent,!pt))throw new Error("Event streaming is unavailable: the bootstrap module did not load.");let dt=oyi({...pt?{mapSessionEvent:pt}:{},options:o,stderr:e.stderr,stdout:e.stdout}),st=i.prepareZCodeTelemetryEnv??Ct?.prepareZCodeTelemetryEnv;st&&(j=i.shutdownZCodeTelemetry??Ct?.shutdownZCodeTelemetry);let je=st?await st(de,{cliVersion:a,productVersion:de.ZCODE_APP_VERSION}):de,Pt=i.startProcessProviderRegistryRuntime??Ct?.startProcessProviderRegistryRuntime;if(!Pt)throw new Error("Provider Registry runtime is unavailable.");K=await Pt(je,i.skipUserConfig?{}:{standalone:{...IOe(e.stderr),...i.userConfigPath?{legacyCliUserConfigFilePath:i.userConfigPath}:{}}});let We=(i.createProviderEndpointRoutingPort??Ct?.createDefaultProviderEndpointRoutingPort)?.({appVersion:a,env:de,workingDirectory:Fe});if(U=bRt(o,i),R=await ut({modelSelectionMode:"cli-default",browserControlPort:U?.browserControlPort,env:je,permissionBroker:nyi(),...We?{providerEndpointRoutingPort:We}:{},providerRegistry:K.runtime.registryService,configuredDefaultModelSelection:K.configuredDefaultModelSelection,...K.providerRuntimeHeadersPort?{providerRuntimeHeadersPort:K.providerRuntimeHeadersPort}:{},resume:Ue!==void 0,runtimeConfig:{...c?{mode:c}:{},...f?{toolDisallowlist:f}:{},toolSearch:{mode:_},...h?{midConversationSystem:{mode:"force"}}:{},...hRt(S),memory:{extractionEnabled:o.memoryBench===!0},modelStreaming:"on",presentationSurface:b,workingDirectory:Fe},sessionId:Ue,uiDetectedLocale:o.detectedLocale,uiLocale:o.locale,version:a}),q.signal.aborted){let we=R;throw R=void 0,await CF(async()=>we.close?.(),re),q.signal.reason}let $zCliDefaultPromptModel=process.env.ZCODE_CLI_PROMPT_MODEL;let $zCliDefaultPromptEffort=process.env.ZCODE_CLI_PROMPT_EFFORT;if($zCliDefaultPromptEffort&&$zCliDefaultPromptEffort.toLowerCase()==="auto")$zCliDefaultPromptEffort=void 0;if($zCliDefaultPromptModel&&!$zCliDefaultPromptEffort){await R.setModel($zCliDefaultPromptModel,{transient:true,cliDefault:true});}else if($zCliDefaultPromptEffort){let $zPromptSelection,$zPromptCurrent;if($zCliDefaultPromptModel){let $zPromptSlash=$zCliDefaultPromptModel.indexOf("/");if($zPromptSlash<=0||$zPromptSlash===$zCliDefaultPromptModel.length-1)throw new Error("Invalid prompt model selection.");$zPromptSelection={providerId:$zCliDefaultPromptModel.slice(0,$zPromptSlash),modelId:$zCliDefaultPromptModel.slice($zPromptSlash+1)};}else{await R.readExecutionState?.();$zPromptCurrent=R.getCurrentModelOption?.();if(!$zPromptCurrent?.ref)throw new Error("Cannot apply --effort without a current model. Pass --model or select a model first.");$zPromptSelection={...$zPromptCurrent.ref};}let $zPromptOption=R.getModelOption?.($zPromptSelection);let $zPromptLevels=($zPromptOption?.reasoning?.levels??$zPromptCurrent?.reasoning?.levels??[]).map($zLevel=>$zLevel.value);if($zPromptOption&&$zPromptLevels.length===0)throw new Error("Model "+$zPromptSelection.providerId+"/"+$zPromptSelection.modelId+" does not support reasoning effort.");let $zPromptLevel=$zPromptLevels.find($zLevel=>$zLevel===$zCliDefaultPromptEffort)??$zPromptLevels.find($zLevel=>$zLevel.toLowerCase()===$zCliDefaultPromptEffort.toLowerCase());if($zPromptLevels.length>0&&!$zPromptLevel)throw new Error("Unsupported reasoning effort: "+$zCliDefaultPromptEffort+". Available: "+$zPromptLevels.join(", ")+".");await R.setModel({...$zPromptSelection,options:{...$zPromptSelection.options,reasoningLevel:$zPromptLevel??$zCliDefaultPromptEffort}},{transient:true,cliDefault:true});}if(C=R.traceId,o.memoryBench&&!R.runtime.isProjectMemoryEnabled())throw new Error(Mvc);if(x&&await jvc(x,i))return await zvc(e,o,R,t,c,C,q.signal,i,S);z=wRt(R.runtime)?.({onSessionEvent:dt.observe});let Rt=syi(R.runtime),cn=await R.submitPrompt(n.length>0?{text:I,attachments:n.map(we=>({type:Lvc(we),path:we}))}:I,{abortSignal:q.signal,...z?{}:{onEvent:dt.observe}});dt.beginWaitPhase(cn.turnId?String(cn.turnId):void 0),C=cn.traceId??C,dt.hasWorkflowActivity()&&Rt&&await iyi({runtime:Rt,signal:q.signal}),o.memoryBench&&(await R.runtime.drainMemoryExtractions(null),q.signal.throwIfAborted()),$();let dn=[cn.response,...dt.waitPhaseTurnResponses()].filter(we=>we.trim().length>0),zn=dn.at(-1)??cn.response,sn=dn.length>1,rt=await qvc({bootstrapModule:Ct,deps:i,events:cn.events,workingDirectory:Fe});return Ee?(e.stdout.write(`${JSON.stringify({type:"result",sessionId:R.sessionId,traceId:C,...cn.turnId?{turnId:cn.turnId}:{},response:zn,...sn?{turnResponses:dn}:{},...cn.usage?{usage:{...cn.usage}}:{},eventCount:cn.events.length,projection:{status:cn.projection.status,turnCount:cn.projection.turnCount,totalTokenCount:cn.projection.totalTokenCount,contextUsed:cn.projection.contextUsed??null,contextWindow:cn.projection.contextWindow??null}})}
|
|
15584
15584
|
`),0):hyi(o)?(e.stdout.write(lg({sessionId:R.sessionId,traceId:C,...cn.turnId?{turnId:cn.turnId}:{},response:zn,...sn?{turnResponses:dn}:{},...cn.usage?{usage:{...cn.usage}}:{},eventCount:cn.events.length,...rt?{workspaceHookTrust:{workspacePath:rt.workspacePath,workspaceIdentity:rt.workspaceIdentity,bundleDigest:rt.bundleDigest,reasonCode:rt.reasonCode,items:rt.items.map(we=>({reviewItemId:we.reviewItemId,event:we.event,matcher:we.matcher,displayCommand:we.displayCommand,sourcePath:we.sourcePath,configuredEnabled:we.configuredEnabled,hookDeclarationDigest:we.hookDeclarationDigest,trustState:we.trustState}))}}:{},projection:{status:cn.projection.status,turnCount:cn.projection.turnCount,totalTokenCount:cn.projection.totalTokenCount,contextUsed:cn.projection.contextUsed??null,contextWindow:cn.projection.contextWindow??null}})),0):(rt&&Vvc(e,rt),e.stdout.write(`${dn.join(`
|
|
15585
15585
|
|
|
15586
15586
|
`)}
|
|
@@ -15639,7 +15639,7 @@ Commands:
|
|
|
15639
15639
|
marketplace update [name] Refresh one marketplace, or all when omitted
|
|
15640
15640
|
|
|
15641
15641
|
Scopes: user (default), project. \`zcode plugin\` is an alias of \`zcode plugins\`.`;r(Pyi,"runPluginsCommand");r(Zvc,"runPluginsListCommand");r(Yvc,"runPluginsInstallCommand");r(Xvc,"runPluginsUpdateCommand");r(Qvc,"reportInstallOutcome");r(Ryi,"runPluginsSetCommand");r(ebc,"runPluginsDisableCommand");r(tbc,"runPluginsUninstallCommand");r(nbc,"runPluginsValidateCommand")});function obc(e=process.env){let t=e.ZCODE_STORAGE_DIR?.trim()||(0,Bce.join)((0,Myi.homedir)(),".zcode");return(0,Bce.join)(t,"clipboard")}function Nyi(e={}){let t=e.platform??process.platform,n=e.maxBytes??rbc,o=e.runCommand??cbc,i=e.tempDirectory??obc(e.processEnv);return async(a={})=>t==="darwin"?await ibc({maxBytes:n,runCommand:o,signal:a.abortSignal,tempDirectory:i}):t==="linux"?await sbc({maxBytes:n,runCommand:o,signal:a.abortSignal}):t==="win32"?await abc({maxBytes:n,runCommand:o,signal:a.abortSignal,tempDirectory:i}):null}async function ibc(e){await(0,Fj.mkdir)(e.tempDirectory,{recursive:!0});let t=await(0,Fj.mkdtemp)((0,Bce.join)(e.tempDirectory,"zcode-clipboard-")),n=(0,Bce.join)(t,"clipboard.png");try{return(await e.runCommand("osascript",["-e","set png_data to (the clipboard as \xABclass PNGf\xBB)","-e",`set fp to open for access POSIX file ${lbc(n)} with write permission`,"-e","write png_data to fp","-e","close access fp"],{maxBytes:e.maxBytes,signal:e.signal})).exitCode!==0?null:await Lyi(n,"image/png",e.maxBytes)}finally{await(0,Fj.rm)(t,{force:!0,recursive:!0})}}async function sbc(e){let t=[{args:["--type","image/png"],file:"wl-paste",mediaType:"image/png"},{args:["--type","image/jpeg"],file:"wl-paste",mediaType:"image/jpeg"},{args:["--type","image/gif"],file:"wl-paste",mediaType:"image/gif"},{args:["--type","image/webp"],file:"wl-paste",mediaType:"image/webp"},{args:["-selection","clipboard","-t","image/png","-o"],file:"xclip",mediaType:"image/png"},{args:["-selection","clipboard","-t","image/jpeg","-o"],file:"xclip",mediaType:"image/jpeg"},{args:["-selection","clipboard","-t","image/gif","-o"],file:"xclip",mediaType:"image/gif"},{args:["-selection","clipboard","-t","image/webp","-o"],file:"xclip",mediaType:"image/webp"}];for(let n of t){let o=await e.runCommand(n.file,n.args,{maxBytes:e.maxBytes,signal:e.signal}),i=Fyi(o.stdout,n.mediaType,e.maxBytes);if(o.exitCode===0&&i)return i}return null}async function abc(e){await(0,Fj.mkdir)(e.tempDirectory,{recursive:!0});let t=await(0,Fj.mkdtemp)((0,Bce.join)(e.tempDirectory,"zcode-clipboard-")),n=(0,Bce.join)(t,"clipboard.png"),o=["Add-Type -AssemblyName System.Windows.Forms;","$img = Get-Clipboard -Format Image;","if ($null -eq $img) { exit 2 }",`$img.Save(${ubc(n)}, [System.Drawing.Imaging.ImageFormat]::Png);`].join(" ");try{return(await e.runCommand("powershell.exe",["-NoProfile","-NonInteractive","-Command",o],{maxBytes:e.maxBytes,signal:e.signal})).exitCode!==0?null:await Lyi(n,"image/png",e.maxBytes)}finally{await(0,Fj.rm)(t,{force:!0,recursive:!0})}}async function Lyi(e,t,n){let o=await(0,Fj.readFile)(e);return Fyi(o,t,n)}function Fyi(e,t,n){return e.byteLength===0||e.byteLength>n?null:{dataUrl:`data:${t};base64,${e.toString("base64")}`,mediaType:t,sizeBytes:e.byteLength}}async function cbc(e,t,n){return await new Promise(o=>{let i;try{i=(0,Oyi.spawn)(e,t,{signal:n.signal,stdio:["ignore","pipe","ignore"],windowsHide:!0})}catch{o({exitCode:-1,stdout:Buffer.alloc(0)});return}let a=[],c=0,u=!1,f=r(h=>{u||(u=!0,o(h))},"finish");i.stdout?.on("data",h=>{if(c+=h.byteLength,c>n.maxBytes){i.kill();return}a.push(h)}),i.on("error",()=>f({exitCode:-1,stdout:Buffer.alloc(0)})),i.on("close",(h,_)=>{f({exitCode:h,signal:_,stdout:Buffer.concat(a)})})})}function lbc(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function ubc(e){return`'${e.replace(/'/g,"''")}'`}var Oyi,Fj,Myi,Bce,rbc,jyi=G(()=>{"use strict";Oyi=require("node:child_process"),Fj=require("node:fs/promises"),Myi=require("node:os"),Bce=require("node:path"),rbc=20*1024*1024;r(obc,"resolveDefaultClipboardDirectory");r(Nyi,"createNodeClipboardImageReader");r(ibc,"readMacClipboardImage");r(sbc,"readLinuxClipboardImage");r(abc,"readWindowsClipboardImage");r(Lyi,"readImageFile");r(Fyi,"bufferToClipboardImage");r(cbc,"runCommandBuffer");r(lbc,"appleScriptString");r(ubc,"powershellString")});function Uyi(e={}){let t=e.maxBytes??dbc,n=e.platform??process.platform,o=e.runCommand??bbc;return async i=>{let a=vbc(i,t);if(a.byteLength===0)return;let c=gbc(e.stdout,a),u=await _bc({input:i,platform:n,runCommand:o});if(!c&&!u)throw new Error("No text clipboard target accepted the selected text.")}}function gbc(e,t){if(!e)return!1;try{return e.write(`${fbc}${pbc};${t.toString("base64")}${mbc}`),!0}catch{return!1}}async function _bc(e){for(let t of ybc(e.platform))if((await e.runCommand(t.file,t.args,{input:e.input})).exitCode===0)return!0;return!1}function ybc(e){return e==="darwin"?[{args:[],file:"pbcopy"}]:e==="linux"?[{args:[],file:"wl-copy"},{args:["-selection","clipboard"],file:"xclip"},{args:["--clipboard","--input"],file:"xsel"}]:e==="win32"?[{args:["-NoProfile","-NonInteractive","-Command",hbc],file:"powershell.exe"}]:[]}function vbc(e,t){let n=Buffer.from(e,"utf8");if(n.byteLength>t)throw new Error(`Clipboard text exceeds ${t} bytes.`);return n}async function bbc(e,t,n){return await new Promise(o=>{let i;try{i=(0,Byi.spawn)(e,t,{stdio:["pipe","ignore","ignore"],windowsHide:!0})}catch{o({exitCode:-1});return}let a=!1,c=r(u=>{a||(a=!0,o(u))},"finish");i.stdin?.on("error",()=>{}),i.stdin?.end(n.input),i.on("error",()=>c({exitCode:-1})),i.on("close",(u,f)=>c({exitCode:u,signal:f}))})}var Byi,dbc,pbc,fbc,mbc,hbc,zyi=G(()=>{"use strict";Byi=require("node:child_process"),dbc=1024*1024,pbc="c",fbc="\x1B]52;",mbc="\x07",hbc="Set-Clipboard -Value ([Console]::In.ReadToEnd())";r(Uyi,"createNodeClipboardTextWriter");r(gbc,"writeOsc52");r(_bc,"writeNativeClipboardText");r(ybc,"nativeClipboardCommands");r(vbc,"assertClipboardTextSize");r(bbc,"runCommandText")});async function PRt(e){let t=e.env??process.env,n=(e.cwd??process.cwd)();return e.listCustomCommands?await e.listCustomCommands({env:t,logger:e.logger,workingDirectory:n}):await(await Iy()).listZCodeCustomCommands({env:t,logger:e.logger,workingDirectory:n})}async function $yi(e,t){let n=e.env??process.env,o=(e.cwd??process.cwd)();return e.loadCustomCommand?await e.loadCustomCommand({env:n,logger:e.logger,name:t,workingDirectory:o}):await(await Iy()).loadZCodeCustomCommand({env:n,logger:e.logger,name:t,workingDirectory:o})}async function qyi(e){let t=e.env??process.env,n=(e.cwd??process.cwd)();return await(e.listSkills??(await Iy()).listZCodeSkills)({env:t,logger:e.logger,workingDirectory:n})}async function Wyi(e){let t=e.env??process.env,n=(e.cwd??process.cwd)();return(await(e.listSessions??(await Iy()).listZCodeSessions)({directory:n,env:t,limit:50})).map(a=>({directory:a.directory,id:a.id,parentId:a.parentID,title:a.title,updatedAt:a.time.updated}))}async function Vyi(e){try{return await e.getSessionMetadata?.()??{}}catch(t){if(Sbc(t))throw t;return{}}}function Sbc(e){return e instanceof Error?e.name==="SqliteSessionMigrationError":!1}var T3n=G(()=>{"use strict";KY();r(PRt,"listCustomCommandsForTui");r($yi,"loadCustomCommandForTui");r(qyi,"listSkillsForTui");r(Wyi,"listSessionsForTui");r(Vyi,"loadInitialTuiSessionMetadata");r(Sbc,"isStartupGateError")});function Hyi(e){let t=new Set,n,o=r(()=>{n?.(),n=void 0},"detach"),i=r(()=>{if(o(),t.size===0)return;n=e.readSubscriber(e.currentRuntime())?.({onSessionEvent:r(c=>{for(let u of t)u(c)},"onSessionEvent")})},"reattach");return{addSink:r(a=>(t.add(a),t.size===1&&i(),()=>{t.delete(a),t.size===0&&o()}),"addSink"),reattach:i,detach:o,isAttached:r(()=>n!==void 0,"isAttached")}}var Gyi=G(()=>{"use strict";r(Hyi,"createTuiSessionEventRelay")});async function I3n(e){let t=await e.listModels?.()??[];return{locale:e.getLocale?.(),model:e.getModel?.(),theme:e.getTheme?.(),thoughtLevel:e.getThoughtLevel?.(),modelOptions:t,effortOptions:await Nxe(e)??[],loginRequired:!t.some(n=>!n.disabledReason)}}var Jyi,Kyi=G(()=>{"use strict";gRt();r(I3n,"readTuiSessionMetadata");Jyi=r((e,t)=>{const $zTuiBridge=e,$zTuiGetApp=t;e.readSubagents=async n=>(await t()).readSubagents?.(n)??{revision:0,childSessionIds:[],running:[],ended:{total:0,items:[]}},e.readSubagentTranscript=async n=>{let o=await t();if(!o.readSubagentTranscript)throw new Error("Subagent transcript is unavailable.");return o.readSubagentTranscript(n)},$zTuiBridge.loadSessionTranscript=async()=>await(await $zTuiGetApp()).loadSessionTranscript?.()??[],$zTuiBridge.loadSessionContextMessages=async()=>await(await $zTuiGetApp()).loadSessionContextMessages?.()??[],$zTuiBridge.readGoal=async()=>await(await $zTuiGetApp()).readTarget?.()??null,$zTuiBridge.readTodos=async()=>await(await $zTuiGetApp()).readTodos?.()??[],$zTuiBridge.readRuntimeProjection=async()=>{let $zRuntimeProjectionBridge=await $zTuiGetApp();return await require(require("node:path").join(__dirname,"cli-config.cjs")).readTuiRuntimeProjection($zRuntimeProjectionBridge,$zTuiBridge)},$zTuiBridge.$zRestorePersistedBackgroundTasks=async $zApp=>await require(require("node:path").join(__dirname,"cli-config.cjs")).restoreTuiBackgroundTasks($zApp,(PFn(),wPr(),{collectChildSessionIds:IEt,projectSubagents:CEt,projectChildEvents:e=>new Q7().reduce(e)})),$zTuiBridge.readSessionUsage=async()=>await(await $zTuiGetApp()).readSessionUsage?.()??null,$zTuiBridge.cancelBackgroundTask=async e=>await(await $zTuiGetApp()).cancelBackgroundTask?.(e)??null,$zTuiBridge.previewFileRewind=async e=>{let t=await $zTuiGetApp();return await t.runtime?.previewWorkspaceFileRewind?.({targetMessageIds:e})??null},$zTuiBridge.applyFileRewind=async e=>{let t=await $zTuiGetApp();return await t.runtime?.applyWorkspaceFileRewind?.({targetMessageIds:e})??null},$zTuiBridge.setCustomSessionTitle=async e=>{let t=await $zTuiGetApp();let r=t.runtime?.setCustomSessionTitle?.bind(t.runtime)??t.setCustomSessionTitle?.bind(t);if(!r)throw new Error("Session renaming is unavailable in this runtime.");return await r({title:e.title,traceContext:e.traceContext??t.runtime?.rootTraceContext})},$zTuiBridge.readCustomSessionTitle=async()=>{let t=await $zTuiGetApp(),o=t.sessionStore??t.runtime?.sessionStore,r=await o?.getSession?.(t.sessionId);return r?.titleSource==="custom"&&typeof r.title==="string"?r.title:void 0},$zTuiBridge.readSessionResumeTarget=async()=>await(await $zTuiGetApp()).readSessionResumeTarget?.(),$zTuiBridge.setMode=async e=>{return await(await $zTuiGetApp()).setMode(e)},$zTuiBridge.readExecutionState=async()=>await(await $zTuiGetApp()).readExecutionState(),$zTuiBridge.setPlanEnabled=async e=>await(await $zTuiGetApp()).setPlanEnabled(e),$zTuiBridge.setTransientModel=async e=>{if(e==="main"){e=await $zTuiBridge.readDefaultModel();if(!e)throw new Error("No default model is configured.")}let t=await $zTuiGetApp(),r=await t.setModel(e);return{...r,thoughtLevel:t.getThoughtLevel(),effortOptions:t.listThoughtLevels()}},$zTuiBridge.readSessionModel=async()=>{let $zSessionModelApp=await $zTuiGetApp(),s=await $zSessionModelApp.readSessionModelState();if(s?.selection&&!s.issue)await $zSessionModelApp.setModel(s.selection,{transient:!0});return s},$zTuiBridge.sendBackgroundTaskMessage=async e=>await require(require("node:path").join(__dirname,"cli-config.cjs")).sendTuiBackgroundTaskMessage(await $zTuiGetApp(),$zTuiBridge,e),$zTuiBridge.interruptTurn=async e=>{let t=await $zTuiGetApp(),r=e?.reservationId??"tui-steer-interrupt",o=(Array.isArray(e?.pendingInputIds)?e.pendingInputIds:[]).filter(Boolean),n=[],i=async()=>{for(let a of n)await t.releaseQueueItemReservation?.(a,r);n=[]};try{if(t.reserveQueueItem&&t.releaseQueueItemReservation)for(let a of o)if(await t.reserveQueueItem(a,r))n.push(a);else{await i();break}let a=t.runtime?.stopActiveForegroundExecution?.({preserveQueueAutoDrainOnCancel:o.length>0&&n.length===o.length,reason:e?.reason??"TUI steer interrupt"})??{kind:"unsupported"};if(a.kind==="stopped"&&e?.waitForIdle===!0&&t.runtime?.getActiveForegroundExecutionId){let u=Date.now()+5e3;for(;t.runtime.getActiveForegroundExecutionId()!==void 0;){if(Date.now()>=u)throw new Error("Timed out waiting for background result processing to stop.");await new Promise(l=>setTimeout(l,25))}}return a.kind!=="stopped"&&await i(),a}catch(a){await i();throw a}},$zTuiBridge.promoteQueuedInput=async(e,t,r)=>{let o=await $zTuiGetApp(),n=r?.pendingInputReservationId??r?.queryId??r?.inputId??"tui-promotion",i=(Array.isArray(t)?t:[t]).filter(Boolean);if(i.length===0||!o.reserveQueueItem||!o.markQueueItemPromoting||!o.releaseQueueItemReservation||!o.removeQueueItem)return $zTuiBridge.sendInput(e,{...r,delivery:"start_turn"});let a=[],u=!1;try{for(let l of i){if(await o.markQueueItemPromoting(l,n)){a.push(l);continue}if(!await o.reserveQueueItem(l,n))throw new Error("TUI queued input is already reserved: "+l);a.push(l);if(!await o.markQueueItemPromoting(l,n))throw new Error("TUI queued input promotion failed: "+l)}let c=await $zTuiBridge.sendInput(e,{...r,delivery:"start_turn"});if(c?.kind==="rejected")return c;u=!0;for(let l of a)if(!await o.removeQueueItem(l,{reason:"promoted",reservationId:n}))throw new Error("TUI queued input promotion commit failed: "+l);return c}finally{if(!u)for(let l of a)await o.releaseQueueItemReservation(l,n)}},$zTuiBridge.$zSendInputWithoutBackgroundRestore=$zTuiBridge.sendInput,$zTuiBridge.sendInput=async(...$zArgs)=>{let $zApp=await $zTuiGetApp();await $zTuiBridge.$zRestorePersistedBackgroundTasks?.($zApp);return await $zTuiBridge.$zSendInputWithoutBackgroundRestore.apply($zTuiBridge,$zArgs)},e.recallPreviousInput=async n=>await(await t()).recallPreviousInputHistory?.(n)??null,e.getSessionMetadata=async()=>{let n=await t();return I3n(n)},e.reloadModelOptions=async()=>await(await t()).reloadModels(),e.readDefaultModel=async()=>{await t();let $zSelection=await(await e.$zReadProviderRegistryRuntime()).modelSelectionConfigRepository.read();return $zSelection?$zSelection.providerId+"/"+$zSelection.modelId:void 0},e.setDefaultModel=async $zModel=>{let $zApp=await t(),$zIndex=$zModel.indexOf("/"),$zSelection={providerId:$zModel.slice(0,$zIndex),modelId:$zModel.slice($zIndex+1)};if($zIndex<=0||!$zApp.getModelOption($zSelection))throw new Error("Unknown default model: "+$zModel);await(await e.$zReadProviderRegistryRuntime()).modelSelectionConfigRepository.saveConfiguredDefault($zSelection);return await e.setTransientModel($zModel)},e.listModelOptions=async()=>(await t()).listModels?.()??[],e.listEffortOptions=async()=>{let n=await t();return await Nxe(n)??[]},e.listMcpServers=async()=>(await t()).listMcpServers?.()??{},e.listWorkflowRuns=async()=>await(await t()).listDynamicWorkflowRuns?.({})??[],e.retuneWorkflowConcurrency=async $zInput=>{let $zApp=await t();if(typeof $zApp.retuneWorkflowConcurrency!=="function")throw new Error("Workflow management is unavailable in this runtime.");return await $zApp.retuneWorkflowConcurrency($zInput)},e.listSavedWorkflows=async $zInput=>{let $zApp=await t();if(typeof $zApp.listSavedWorkflows!=="function")throw new Error("Workflow management is unavailable in this runtime.");return await $zApp.listSavedWorkflows($zInput)},e.readSavedWorkflow=async $zInput=>{let $zApp=await t();if(typeof $zApp.readSavedWorkflow!=="function")throw new Error("Workflow management is unavailable in this runtime.");return await $zApp.readSavedWorkflow($zInput)},e.saveWorkflowRun=async $zInput=>{let $zApp=await t();if(typeof $zApp.saveWorkflowRun!=="function")throw new Error("Workflow management is unavailable in this runtime.");return await $zApp.saveWorkflowRun($zInput)},e.startSavedWorkflow=async $zInput=>require(require("node:path").join(__dirname,"cli-config.cjs")).startTuiSavedWorkflow(await t(),$zInput),e.replayWorkflowRuns=async n=>await(await t()).replayDynamicWorkflowRuns?.(n)??[]},"attachTuiAppQueries")});async function Yyi(e,t,n,o){let i=e.env??process.env,a=(e.cwd??process.cwd)(),c=(e.loadDotenv??qA)({cwd:a,env:i});if(c.error)throw new Error(`Failed to load environment file: ${c.path}`,{cause:c.error});let u=await xRt(n,a,i,e),f=e.createZCodeApp?void 0:await Iy(),h=e.createZCodeApp??f?.createZCodeApp;if(!h)throw new Error("ZCode app factory is unavailable.");let _=e.prepareZCodeTelemetryEnv??f?.prepareZCodeTelemetryEnv;_&&(o.shutdownTelemetry=e.shutdownZCodeTelemetry??f?.shutdownZCodeTelemetry);let b=_?await _(i,{cliVersion:t,productVersion:i.ZCODE_APP_VERSION}):i,S=e.startProcessProviderRegistryRuntime??f?.startProcessProviderRegistryRuntime;if(!S)throw new Error("Provider Registry runtime is unavailable.");o.providerRegistryRuntimePromise??=S(b,e.skipUserConfig?{}:{standalone:{...IOe(),...e.userConfigPath?{legacyCliUserConfigFilePath:e.userConfigPath}:{}}});let x=await o.providerRegistryRuntimePromise,I=x?.modelSelectionConfigRepository?await x.modelSelectionConfigRepository.read():x?.configuredDefaultModelSelection,C=e.createProviderEndpointRoutingPort??f?.createDefaultProviderEndpointRoutingPort;return o.providerEndpointRoutingPort??=C?.({appVersion:t,env:i,projectConfigPath:e.projectConfigPath,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,workingDirectory:a}),{appEnv:b,configuredDefaultModelSelection:I,createAppFactory:h,providerRegistryRuntime:x,sessionId:u,workingDirectory:a}}var Zyi,Xyi=G(()=>{"use strict";KY();ane();Krt();g3n();Zyi=r(()=>({providerEndpointRoutingPort:void 0,providerRegistryRuntimePromise:void 0,shutdownTelemetry:void 0}),"createTuiProcessRuntimeState");r(Yyi,"prepareTuiAppRuntime")});async function Qyi(e,t){let n=e.env??process.env,o=(e.cwd??process.cwd)(),i=(e.loadDotenv??qA)({cwd:o,env:n});if(i.error)throw new Error(`Failed to load environment file: ${i.path}`,{cause:i.error});return await(e.loginZCodeCli??(await Iy()).loginZCodeCli)({abortSignal:t?.abortSignal,env:n,onAuthorizeUrl:t?.onAuthorizeUrl})}async function evi(e,t){let n=e.env??process.env,o=(e.cwd??process.cwd)(),i=(e.loadDotenv??qA)({cwd:o,env:n});if(i.error)throw new Error(`Failed to load environment file: ${i.path}`,{cause:i.error});return await(e.loginBigmodelCodingPlan??(await Iy()).loginBigmodelCodingPlan)({abortSignal:t?.abortSignal,env:n,onAuthorizeUrl:t?.onAuthorizeUrl})}async function tvi(e,t){return await(e.configureCodingPlanApiKey??(await Iy()).configureCodingPlanApiKey)({apiKey:t.apiKey,env:e.env??process.env,providerId:t.providerId})}async function nvi(e){let t=e.env??process.env,n=(e.cwd??process.cwd)(),o=(e.loadDotenv??qA)({cwd:n,env:t});if(o.error)throw new Error(`Failed to load environment file: ${o.path}`,{cause:o.error});return await(e.logoutZCodeCli??(await Iy()).logoutZCodeCli)({env:t})}var rvi=G(()=>{"use strict";KY();ane();r(Qyi,"loginForTui");r(evi,"loginBigmodelForTui");r(tvi,"configureApiKeyForTui");r(nvi,"logoutForTui")});function jxe(e,t){return e.runtime?.getPlanEnabled?.()?"plan":e.getMode?.()??t}var ovi,ivi,L9,C3n=G(()=>{"use strict";ovi={},ivi=r(e=>({current:e,override:e}),"createCliModeState"),L9=r(e=>e.current??e.override??"build","currentCliMode");r(jxe,"readTuiMode")});function E3n(e,t,n){return{kind:"started_turn",result:{...e,locale:e.locale??t.getLocale?.(),mode:n,model:e.model??t.getModel?.(),theme:e.theme??t.getTheme?.(),thoughtLevel:e.thoughtLevel??t.getThoughtLevel?.()}}}var svi=G(()=>{"use strict";r(E3n,"withTuiMetadata")});function avi(e,t,n,o={continueSession:!1},i,a,c=oTt,u,f=!1,h="off",_,b,S=ZY){let x,I=i,C=Zyi(),R,O=new WeakMap,U=new WeakMap,j,z=Math.max(1,Math.trunc(e.shutdownCleanupTimeoutMs??AQe)),$={requestPermission:r(async(ut,Ee)=>{let pt=j;return pt?await pt(ut,Ee):{decision:"deny",reason:`No interactive approval handler configured for ${ut.toolName}`,resolvedAt:new Date}},"requestPermission")},K=r(async(ut=x)=>{if(!ut)return;let Ee=ut,pt=O.get(Ee);pt||(pt=(async()=>{await CF(async()=>ut.close?.(),z),await CF(async()=>U.get(Ee)?.close(),z)})(),O.set(Ee,pt)),await pt},"closeApp"),q=Hyi({currentRuntime:r(()=>x?.runtime,"currentRuntime"),readSubscriber:wRt}),re=r(async ut=>{let Ee=x,pt=await ut();try{await pt.readExecutionState()}catch($zResumeCandidateError){await K(pt);throw $zResumeCandidateError}return x=pt,Ee&&Ee!==pt&&await K(Ee),q.reattach(),t.current=jxe(x,L9(t)),x},"replaceApp"),ne=r(async ut=>{if(R)throw new Error("TUI prompt handler is closed");let{appEnv:Ee,configuredDefaultModelSelection:pt,createAppFactory:dt,providerRegistryRuntime:st,sessionId:je,workingDirectory:Pt}=await Yyi(e,n,ut,C),Ke=C.providerEndpointRoutingPort,We=bRt({browserExecutable:b,browserUse:_},e),St;try{St=await dt({modelSelectionMode:"cli-default",browserControlPort:We?.browserControlPort,env:Ee,projectConfigPath:e.projectConfigPath,...Ke?{providerEndpointRoutingPort:Ke}:{},providerRegistry:st.runtime.registryService,configuredDefaultModelSelection:pt,...st.providerRuntimeHeadersPort?{providerRuntimeHeadersPort:st.providerRuntimeHeadersPort}:{},resume:je!==void 0,runtimeConfig:{...t.override?{mode:t.override}:{},...u?{toolDisallowlist:u}:{},toolSearch:{mode:h},...f?{midConversationSystem:{mode:"force"}}:{},...hRt(S),modelStreaming:"on",titleGeneration:ovi,workingDirectory:Pt},permissionBroker:$,sessionId:je,skipUserConfig:e.skipUserConfig,uiDetectedLocale:a,uiLocale:I,userConfigPath:e.userConfigPath,version:n})}catch(Rt){throw await CF(async()=>We?.close(),z),Rt}if(We&&U.set(St,We),R)throw await K(St),new Error("TUI prompt handler is closed");return St},"createApp"),ke=r(async()=>(x??=await ne(o),t.current=jxe(x,L9(t)),x),"getApp"),de=r(async ut=>await re(async()=>await ne(ut?{continueSession:!1,resumeSessionId:ut}:{continueSession:!0})),"resumeApp"),Fe=r(async()=>await re(async()=>await ne({continueSession:!1})),"newApp"),Xe=r(async ut=>{if(t.override=ut,x){let Ee=x;if(Ee.setMode){let pt=await Ee.setMode(ut);return t.current=jxe(Ee,pt.mode),t.current}Ee.runtime.updateConfig({mode:ut})}return t.current=x?jxe(x,ut):ut,t.current},"setCliMode"),Ue=nze({forkApp:r(async ut=>{let pt=await(await ke()).forkFromCheckpoint?.({targetCheckpointId:ut});if(!pt)throw new Error("Forking is not available in this client.");return await re(async()=>await ne({continueSession:!1,resumeSessionId:pt.forkedSessionId})),{copiedMessageCount:pt.copiedMessageCount,forkedSessionId:pt.forkedSessionId,response:`${pt.response}
|
|
15642
|
-
Switched to forked session ${pt.forkedSessionId}.`,restoredFileCount:pt.restoredFileCount??pt.restoredFiles?.length??0}},"forkApp"),getApp:ke,getMode:r(()=>L9(t),"getMode"),getLocale:r(()=>x?.getLocale?.()??LBn(I,a)??c,"getLocale"),hasSelectableModels:G_i(ke),listCustomCommands:r(()=>PRt(e),"listCustomCommands"),listSessions:r(()=>Wyi(e),"listSessions"),listSkills:r(()=>qyi(e),"listSkills"),configureApiKey:r(ut=>tvi(e,ut),"configureApiKey"),login:r(ut=>Qyi(e,ut),"login"),loginBigmodel:r(ut=>evi(e,ut),"loginBigmodel"),loadCustomCommand:r(ut=>$yi(e,ut),"loadCustomCommand"),newApp:Fe,recordInputHistory:r(async(ut,Ee)=>{await x?.recordInputHistory?.(ut,Ee)},"recordInputHistory"),resumeApp:de,saveDefaultModelSelection:r(async ut=>{let Ee=await C.providerRegistryRuntimePromise;if(!Ee?.modelSelectionConfigRepository)throw new Error("Default model configuration storage is unavailable.");await Ee.modelSelectionConfigRepository.saveConfiguredDefault(ut)},"saveDefaultModelSelection"),logout:r(()=>nvi(e),"logout"),setLocale:r(async ut=>{if(x?.setLocale){let pt=await x.setLocale(ut);return I=ut,pt}return I=ut,{configPath:(await Gye(e.userConfigPath??O4(),ut)).path,locale:LBn(ut,a)??"en-US",requestedLocale:ut}},"setLocale"),setMode:Xe,workflowMode:S}),Ct=r(async(ut,Ee)=>{let pt=j;j=Ee.requestPermission;try{let dt=await Ue(ut,Ee);return x?{...dt,...await I3n(await ke())}:dt}finally{j=pt}},"submitPrompt");return Ct.setMode=async ut=>({mode:await Xe(ut)}),Ct.sendInput=async(ut,Ee)=>{let pt=j;j=Ee?.requestPermission;try{let dt=Fce(typeof ut=="string"?ut:ut.text);if(dt?.type==="known"&&(dt.name==="model"||dt.name==="effort"))return{kind:"command_result",result:await Ct(ut,{...Ee,abortSignal:Ee?.abortSignal??new AbortController().signal})};let st=await ke();if(st.sendInput){let je=await st.sendInput(ut,Ee);return je.kind!=="started_turn"?je:E3n(await(je.result??je.completion),st,L9(t))}return E3n(await st.submitPrompt(ut,Ee),st,L9(t))}finally{j=pt}},Ct.listSkills=async()=>await qyi(e),Ct.$zReadProviderRegistryRuntime=()=>C.providerRegistryRuntimePromise,Jyi(Ct,ke),Ct.subscribeSessionEvents=ut=>{let Ee=q.addSink(ut);return ke().then(()=>q.reattach(),()=>{}),Ee},Ct.getMainSessionId=()=>{let Ee=x?.runtime?.getSessionId?.();return typeof Ee=="string"&&Ee.length>0?Ee:void 0},Ct.close=async()=>{R??=(async()=>{await K(),await CF(async()=>C.shutdownTelemetry?.(),z),(await C.providerRegistryRuntimePromise)?.dispose()})(),await R},Ct}var cvi=G(()=>{"use strict";Kb();FN();vRt();FBn();f3n();kRt();Gyi();Kyi();Xyi();zme();rvi();T3n();C3n();u3n();svi();XY();r(avi,"createTuiSubmitPrompt")});var lvi,uvi,II,nX,JP,dvi,pvi,wbc,kbc,fvi,mvi,xbc,Tbc,Ibc,Cbc,Ebc,Abc,hvi=G(()=>{"use strict";lvi=require("node:crypto"),uvi=require("node:fs"),II=require("node:fs/promises"),nX=require("node:os"),JP=require("node:path"),dvi=require("node:url"),pvi="zcode-tui-runtime/",wbc=`${pvi}manifest.json`,kbc="node_modules/@zcode/tui/dist/index.js",fvi="manifest.json",mvi=r(async()=>{let e=await import("node:sea");if(!e.isSea())return await import("@zcode/tui");let t=await xbc(e);return await import((0,dvi.pathToFileURL)((0,JP.join)(t,kbc)).href)},"loadTuiRuntime"),xbc=r(async e=>{let t=Tbc(e),n=(0,JP.join)(Cbc(),"0.17.0",t.target,t.hash),o=(0,JP.join)(n,fvi);if(await Ibc(o,t))return n;let i=`${n}.tmp-${process.pid}-${Date.now()}`;await(0,II.rm)(i,{force:!0,recursive:!0}),await(0,II.mkdir)(i,{recursive:!0});for(let a of t.files){let c=e.getRawAsset(`${pvi}${a.path}`),u=Buffer.from(c);if((0,lvi.createHash)("sha256").update(u).digest("hex")!==a.sha256)throw new Error(`SEA TUI asset hash mismatch for ${a.path}`);let h=(0,JP.join)(i,a.path);await(0,II.mkdir)((0,JP.dirname)(h),{recursive:!0}),await(0,II.writeFile)(h,u),await(0,II.chmod)(h,a.mode??Abc(a.path))}return await(0,II.writeFile)(Ebc(i),JSON.stringify(t,null,2)),await(0,II.rm)(n,{force:!0,recursive:!0}),await(0,II.mkdir)((0,JP.dirname)(n),{recursive:!0}),await(0,II.rename)(i,n),n},"ensureSeaTuiRuntime"),Tbc=r(e=>{let t=e.getAsset(wbc,"utf8"),n=JSON.parse(t);if(n.version!==1||!n.hash||!Array.isArray(n.files))throw new Error("Invalid SEA TUI runtime manifest.");return n},"readManifest"),Ibc=r(async(e,t)=>{if(!(0,uvi.existsSync)(e))return!1;try{let n=JSON.parse(await(0,II.readFile)(e,"utf8"));return n.hash===t.hash&&n.target===t.target}catch{return!1}},"isCacheCurrent"),Cbc=r(()=>{let e=(0,nX.homedir)();return(0,nX.platform)()==="darwin"&&e?(0,JP.join)(e,"Library","Caches","zcode","sea-assets"):(0,nX.platform)()==="win32"?(0,JP.join)(process.env.LOCALAPPDATA??(0,JP.join)(e||(0,nX.tmpdir)(),"AppData","Local"),"zcode","Cache","sea-assets"):(0,JP.join)(process.env.XDG_CACHE_HOME??(0,JP.join)(e||(0,nX.tmpdir)(),".cache"),"zcode","sea-assets")},"cacheBaseDirectory"),Ebc=r(e=>(0,JP.join)(e,fvi),"markerPathForDirectory"),Abc=r(e=>/\.(?:dll|dylib|node|so)$/i.test(e)?493:420,"modeForPath")});function gvi({deps:e,options:t,workingDirectory:n}){let o=Dh({cliOverrides:Pbc(t.locale),env:e.env??process.env,projectConfigPath:e.projectConfigPath,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,workingDirectory:n});return aU(o.config.ui.locale,t.detectedLocale)}var Pbc,_vi=G(()=>{"use strict";Kb();FN();Pbc=r(e=>e?{ui:{locale:e}}:void 0,"localeCliOverrides");r(gvi,"resolveTuiStartupLocale")});function vvi(e){let t=e.fileSystemPort??$G(),n=(0,ZN.resolve)(e.workspaceDirectory);return async o=>{let i=Nbc(o.token);if(!i)return{items:[],truncated:!1};let a=(0,ZN.resolve)(n,i.directoryToken);if(!Bbc(n,a))return{items:[],truncated:!1};try{let u=(await t.listDirectory({path:a},{signal:o.abortSignal})).entries.flatMap(h=>{if(h.kind!=="directory"&&h.kind!=="file")return[];if(h.kind==="directory"&&Mbc.has(h.name))return[];if(!i.query.startsWith(".")&&h.name.startsWith("."))return[];if(!Lbc(h.name,i.query))return[];let _=jbc(n,h.path);return _?[{kind:h.kind,path:h.kind==="directory"?`${_}/`:_}]:[]}).sort((h,_)=>Fbc(h,_,i.query)),f=Math.max(1,Math.floor(o.limit??Rbc));return{items:u.slice(0,f),truncated:u.length>f}}catch{return{items:[],truncated:!1}}}}function Nbc(e){let t=e.replace(/^@/u,"");if(t.startsWith("/")||t.startsWith("\\")||(0,ZN.isAbsolute)(t)||Obc.test(t))return;let n=t.replace(Dbc,"/");if(n.split("/").some(i=>i===".."))return;let o=n.lastIndexOf("/");return o<0?{directoryToken:"",query:n}:{directoryToken:n.slice(0,o+1),query:n.slice(o+1)}}function Lbc(e,t){return t.length===0?!0:e.toLowerCase().includes(t.toLowerCase())}function Fbc(e,t,n){if(e.kind!==t.kind)return e.kind==="directory"?-1:1;let o=yvi(e.path),i=yvi(t.path),a=n.toLowerCase(),c=o.toLowerCase().startsWith(a),u=i.toLowerCase().startsWith(a);return c!==u?c?-1:1:e.path.localeCompare(t.path)}function yvi(e){let t=e.endsWith("/")?e.slice(0,-1):e,n=t.lastIndexOf("/");return n<0?t:t.slice(n+1)}function jbc(e,t){let n=(0,ZN.relative)(e,t);if(!(!n||n.startsWith("..")||(0,ZN.isAbsolute)(n)))return n.split(ZN.sep).join("/")}function Bbc(e,t){let n=(0,ZN.relative)(e,t);return n===""||!n.startsWith("..")&&!(0,ZN.isAbsolute)(n)}var ZN,Rbc,Dbc,Obc,Mbc,bvi=G(()=>{"use strict";u0e();ZN=require("node:path"),Rbc=50,Dbc=/[\\/]+/gu,Obc=/^[a-zA-Z]:[\\/]/u,Mbc=new Set([".bzr",".git",".hg",".jj",".sl",".svn","node_modules"]);r(vvi,"createWorkspacePathSuggestionProvider");r(Nbc,"parseWorkspacePathToken");r(Lbc,"matchesPathQuery");r(Fbc,"compareWorkspacePathSuggestion");r(yvi,"basenameFromSuggestion");r(jbc,"toWorkspaceRelativePath");r(Bbc,"isPathInside")});async function wvi(e){let t=e.maxOutputBytes??qbc,n=e.timeoutMs??$bc,i=await(e.runCommand??Vbc)(Ubc,["-C",e.workspaceDirectory,...zbc],{maxOutputBytes:t,timeoutMs:n}).catch(()=>({exitCode:-1,stdout:""}));if(i.exitCode!==0)return;let a=i.stdout.trim().split(/\r?\n/,1)[0]?.trim();if(!(!a||a===Wbc))return a}async function Vbc(e,t,n){return await new Promise(o=>{let i;try{i=(0,Svi.spawn)(e,t,{stdio:["ignore","pipe","ignore"],windowsHide:!0})}catch{o({exitCode:-1,stdout:""});return}let a="",c=!1,u=setTimeout(()=>{i.kill(),f({exitCode:-1,stdout:a})},n.timeoutMs),f=r(h=>{c||(c=!0,clearTimeout(u),o(h))},"finish");i.stdout?.on("data",h=>{a+=h.toString("utf8"),Buffer.byteLength(a,"utf8")>n.maxOutputBytes&&(i.kill(),f({exitCode:-1,stdout:a}))}),i.on("error",()=>f({exitCode:-1,stdout:a})),i.on("close",h=>f({exitCode:h,stdout:a}))})}var Svi,Ubc,zbc,$bc,qbc,Wbc,kvi=G(()=>{"use strict";Svi=require("node:child_process"),Ubc="git",zbc=["symbolic-ref","--quiet","--short","HEAD"],$bc=750,qbc=512,Wbc="HEAD";r(wvi,"resolveWorkspaceGitBranch");r(Vbc,"runGitCommand")});var xvi,Tvi=G(()=>{"use strict";yi();jyi();zyi();vRt();zme();T3n();cvi();hvi();_vi();bvi();kvi();C3n();XY();xvi=r(async(e,t,n,o,i,a,c,u=!1,f="off",h=ZY)=>{try{let _=ivi(i),b=n.runTui??(await mvi()).runTui,S=(n.cwd??process.cwd)(),x=n.env??process.env,I=S2e(x)==="development",C=gvi({deps:n,options:t,workingDirectory:S}),R=avi(n,_,o,a,t.locale,t.detectedLocale,C,c,u,f,t.browserUse,t.browserExecutable,h),O=PQe({cleanup:r(async()=>{await R.close?.()},"cleanup"),cleanupTimeoutMs:n.shutdownCleanupTimeoutMs,exitProcess:n.exitProcess,process:n.shutdownProcess});try{let $zTuiResumeOptions=a,$zTuiResumeReady=($zTuiResumeOptions.resumeSessionId||$zTuiResumeOptions.continueSession)?await R.readExecutionState?.():void 0;return await b({loadStartupOptions:r(async()=>{let[U,j,z]=await Promise.all([Vyi(R),PRt(n).catch(()=>{}),(n.resolveWorkspaceGitBranch??wvi)({workspaceDirectory:S}).catch(()=>{})]);return{initialMode:L9(_),initialModel:U.model,initialThoughtLevel:U.thoughtLevel,loginRequired:U.loginRequired,locale:U.locale??C,theme:U.theme??"auto",modelOptions:U.modelOptions,effortOptions:U.effortOptions,slashCommands:s3n(j,{workflowMode:h}),workspaceGitBranch:z}},"loadStartupOptions"),locale:C,developerMode:I,version:o,workspaceDirectory:S,noColor:t.noColor,readClipboardImage:n.readClipboardImage??Nyi(),readDefaultModel:R.readDefaultModel,setDefaultModel:R.setDefaultModel,reloadModelOptions:R.reloadModelOptions,listModelOptions:R.listModelOptions,listWorkspacePathSuggestions:vvi({workspaceDirectory:S}),listMcpServers:R.listMcpServers,readSubagents:R.readSubagents,readSubagentTranscript:R.readSubagentTranscript,listWorkflowRuns:R.listWorkflowRuns,replayWorkflowRuns:R.replayWorkflowRuns,reduceWorkflowRuns:($zState,$zEvent)=>{hCr();return yot($zState,$zEvent)},retuneWorkflowConcurrency:R.retuneWorkflowConcurrency,listSavedWorkflows:R.listSavedWorkflows,readSavedWorkflow:R.readSavedWorkflow,saveWorkflowRun:R.saveWorkflowRun,startSavedWorkflow:R.startSavedWorkflow,getMainSessionId:R.getMainSessionId,writeClipboardText:n.writeClipboardText??Uyi({stdout:e.stdout}),stderr:e.stderr,stdin:e.stdin,stdout:e.stdout,loadSessionTranscript:R.loadSessionTranscript,loadSessionContextMessages:R.loadSessionContextMessages,readGoal:R.readGoal,readTodos:R.readTodos,readRuntimeProjection:R.readRuntimeProjection,readSessionUsage:R.readSessionUsage,cancelBackgroundTask:R.cancelBackgroundTask,previewFileRewind:R.previewFileRewind,applyFileRewind:R.applyFileRewind,setCustomSessionTitle:R.setCustomSessionTitle,readCustomSessionTitle:R.readCustomSessionTitle,readSessionResumeTarget:R.readSessionResumeTarget,interruptTurn:R.interruptTurn,promoteQueuedInput:R.promoteQueuedInput,listSkills:R.listSkills,readExecutionState:R.readExecutionState,setPlanEnabled:R.setPlanEnabled,setTransientModel:R.setTransientModel,readSessionModel:R.readSessionModel,sendBackgroundTaskMessage:R.sendBackgroundTaskMessage,recallPreviousInput:R.recallPreviousInput,sendInput:R.sendInput,setMode:R.setMode,submitPrompt:R,subscribeSessionEvents:R.subscribeSessionEvents})}finally{O(),await R.close?.()}}catch(_){let b=_ instanceof Error?_.message:String(_);return e.stderr.write(`Error: ${b}
|
|
15642
|
+
Switched to forked session ${pt.forkedSessionId}.`,restoredFileCount:pt.restoredFileCount??pt.restoredFiles?.length??0}},"forkApp"),getApp:ke,getMode:r(()=>L9(t),"getMode"),getLocale:r(()=>x?.getLocale?.()??LBn(I,a)??c,"getLocale"),hasSelectableModels:G_i(ke),listCustomCommands:r(()=>PRt(e),"listCustomCommands"),listSessions:r(()=>Wyi(e),"listSessions"),listSkills:r(()=>qyi(e),"listSkills"),configureApiKey:r(ut=>tvi(e,ut),"configureApiKey"),login:r(ut=>Qyi(e,ut),"login"),loginBigmodel:r(ut=>evi(e,ut),"loginBigmodel"),loadCustomCommand:r(ut=>$yi(e,ut),"loadCustomCommand"),newApp:Fe,recordInputHistory:r(async(ut,Ee)=>{await x?.recordInputHistory?.(ut,Ee)},"recordInputHistory"),resumeApp:de,saveDefaultModelSelection:r(async ut=>{let Ee=await C.providerRegistryRuntimePromise;if(!Ee?.modelSelectionConfigRepository)throw new Error("Default model configuration storage is unavailable.");await Ee.modelSelectionConfigRepository.saveConfiguredDefault(ut)},"saveDefaultModelSelection"),logout:r(()=>nvi(e),"logout"),setLocale:r(async ut=>{if(x?.setLocale){let pt=await x.setLocale(ut);return I=ut,pt}return I=ut,{configPath:(await Gye(e.userConfigPath??O4(),ut)).path,locale:LBn(ut,a)??"en-US",requestedLocale:ut}},"setLocale"),setMode:Xe,workflowMode:S}),Ct=r(async(ut,Ee)=>{let pt=j;j=Ee.requestPermission;try{let dt=await Ue(ut,Ee);return x?{...dt,...await I3n(await ke())}:dt}finally{j=pt}},"submitPrompt");return Ct.setMode=async ut=>({mode:await Xe(ut)}),Ct.sendInput=async(ut,Ee)=>{let pt=j;j=Ee?.requestPermission;try{let dt=Fce(typeof ut=="string"?ut:ut.text);if(dt?.type==="known"&&(dt.name==="model"||dt.name==="effort"))return{kind:"command_result",result:await Ct(ut,{...Ee,abortSignal:Ee?.abortSignal??new AbortController().signal})};let st=await ke();if(st.sendInput){let je=await st.sendInput(ut,Ee);return je.kind!=="started_turn"?je:E3n(await(je.result??je.completion),st,L9(t))}return E3n(await st.submitPrompt(ut,Ee),st,L9(t))}finally{j=pt}},Ct.listSkills=async()=>await qyi(e),Ct.$zReadProviderRegistryRuntime=()=>C.providerRegistryRuntimePromise,Jyi(Ct,ke),Ct.subscribeSessionEvents=ut=>{let Ee=q.addSink(ut);return ke().then(()=>q.reattach(),()=>{}),Ee},Ct.getMainSessionId=()=>{let Ee=x?.runtime?.getSessionId?.();return typeof Ee=="string"&&Ee.length>0?Ee:void 0},Ct.close=async()=>{R??=(async()=>{await K(),await CF(async()=>C.shutdownTelemetry?.(),z),(await C.providerRegistryRuntimePromise)?.dispose()})(),await R},Ct}var cvi=G(()=>{"use strict";Kb();FN();vRt();FBn();f3n();kRt();Gyi();Kyi();Xyi();zme();rvi();T3n();C3n();u3n();svi();XY();r(avi,"createTuiSubmitPrompt")});var lvi,uvi,II,nX,JP,dvi,pvi,wbc,kbc,fvi,mvi,xbc,Tbc,Ibc,Cbc,Ebc,Abc,hvi=G(()=>{"use strict";lvi=require("node:crypto"),uvi=require("node:fs"),II=require("node:fs/promises"),nX=require("node:os"),JP=require("node:path"),dvi=require("node:url"),pvi="zcode-tui-runtime/",wbc=`${pvi}manifest.json`,kbc="node_modules/@zcode/tui/dist/index.js",fvi="manifest.json",mvi=r(async()=>{let e=await import("node:sea");if(!e.isSea())return await import("@zcode/tui");let t=await xbc(e);return await import((0,dvi.pathToFileURL)((0,JP.join)(t,kbc)).href)},"loadTuiRuntime"),xbc=r(async e=>{let t=Tbc(e),n=(0,JP.join)(Cbc(),"0.17.0",t.target,t.hash),o=(0,JP.join)(n,fvi);if(await Ibc(o,t))return n;let i=`${n}.tmp-${process.pid}-${Date.now()}`;await(0,II.rm)(i,{force:!0,recursive:!0}),await(0,II.mkdir)(i,{recursive:!0});for(let a of t.files){let c=e.getRawAsset(`${pvi}${a.path}`),u=Buffer.from(c);if((0,lvi.createHash)("sha256").update(u).digest("hex")!==a.sha256)throw new Error(`SEA TUI asset hash mismatch for ${a.path}`);let h=(0,JP.join)(i,a.path);await(0,II.mkdir)((0,JP.dirname)(h),{recursive:!0}),await(0,II.writeFile)(h,u),await(0,II.chmod)(h,a.mode??Abc(a.path))}return await(0,II.writeFile)(Ebc(i),JSON.stringify(t,null,2)),await(0,II.rm)(n,{force:!0,recursive:!0}),await(0,II.mkdir)((0,JP.dirname)(n),{recursive:!0}),await(0,II.rename)(i,n),n},"ensureSeaTuiRuntime"),Tbc=r(e=>{let t=e.getAsset(wbc,"utf8"),n=JSON.parse(t);if(n.version!==1||!n.hash||!Array.isArray(n.files))throw new Error("Invalid SEA TUI runtime manifest.");return n},"readManifest"),Ibc=r(async(e,t)=>{if(!(0,uvi.existsSync)(e))return!1;try{let n=JSON.parse(await(0,II.readFile)(e,"utf8"));return n.hash===t.hash&&n.target===t.target}catch{return!1}},"isCacheCurrent"),Cbc=r(()=>{let e=(0,nX.homedir)();return(0,nX.platform)()==="darwin"&&e?(0,JP.join)(e,"Library","Caches","zcode","sea-assets"):(0,nX.platform)()==="win32"?(0,JP.join)(process.env.LOCALAPPDATA??(0,JP.join)(e||(0,nX.tmpdir)(),"AppData","Local"),"zcode","Cache","sea-assets"):(0,JP.join)(process.env.XDG_CACHE_HOME??(0,JP.join)(e||(0,nX.tmpdir)(),".cache"),"zcode","sea-assets")},"cacheBaseDirectory"),Ebc=r(e=>(0,JP.join)(e,fvi),"markerPathForDirectory"),Abc=r(e=>/\.(?:dll|dylib|node|so)$/i.test(e)?493:420,"modeForPath")});function gvi({deps:e,options:t,workingDirectory:n}){let o=Dh({cliOverrides:Pbc(t.locale),env:e.env??process.env,projectConfigPath:e.projectConfigPath,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,workingDirectory:n});return aU(o.config.ui.locale,t.detectedLocale)}var Pbc,_vi=G(()=>{"use strict";Kb();FN();Pbc=r(e=>e?{ui:{locale:e}}:void 0,"localeCliOverrides");r(gvi,"resolveTuiStartupLocale")});function vvi(e){let t=e.fileSystemPort??$G(),n=(0,ZN.resolve)(e.workspaceDirectory);return require(require("node:path").join(__dirname,"cli-config.cjs")).withRecursiveWorkspacePathSuggestions(async o=>{let i=Nbc(o.token);if(!i)return{items:[],truncated:!1};let a=(0,ZN.resolve)(n,i.directoryToken);if(!Bbc(n,a))return{items:[],truncated:!1};try{let u=(await t.listDirectory({path:a},{signal:o.abortSignal})).entries.flatMap(h=>{if(h.kind!=="directory"&&h.kind!=="file")return[];if(h.kind==="directory"&&Mbc.has(h.name))return[];if(!i.query.startsWith(".")&&h.name.startsWith("."))return[];if(!Lbc(h.name,i.query))return[];let _=jbc(n,h.path);return _?[{kind:h.kind,path:h.kind==="directory"?`${_}/`:_}]:[]}).sort((h,_)=>Fbc(h,_,i.query)),f=Math.max(1,Math.floor(o.limit??Rbc));return{items:u.slice(0,f),truncated:u.length>f}}catch{return{items:[],truncated:!1}}},{workspaceDirectory:n,fileSystemPort:t,excludedDirectories:Mbc})}function Nbc(e){let t=e.replace(/^@/u,"");if(t.startsWith("/")||t.startsWith("\\")||(0,ZN.isAbsolute)(t)||Obc.test(t))return;let n=t.replace(Dbc,"/");if(n.split("/").some(i=>i===".."))return;let o=n.lastIndexOf("/");return o<0?{directoryToken:"",query:n}:{directoryToken:n.slice(0,o+1),query:n.slice(o+1)}}function Lbc(e,t){return t.length===0?!0:e.toLowerCase().includes(t.toLowerCase())}function Fbc(e,t,n){if(e.kind!==t.kind)return e.kind==="directory"?-1:1;let o=yvi(e.path),i=yvi(t.path),a=n.toLowerCase(),c=o.toLowerCase().startsWith(a),u=i.toLowerCase().startsWith(a);return c!==u?c?-1:1:e.path.localeCompare(t.path)}function yvi(e){let t=e.endsWith("/")?e.slice(0,-1):e,n=t.lastIndexOf("/");return n<0?t:t.slice(n+1)}function jbc(e,t){let n=(0,ZN.relative)(e,t);if(!(!n||n.startsWith("..")||(0,ZN.isAbsolute)(n)))return n.split(ZN.sep).join("/")}function Bbc(e,t){let n=(0,ZN.relative)(e,t);return n===""||!n.startsWith("..")&&!(0,ZN.isAbsolute)(n)}var ZN,Rbc,Dbc,Obc,Mbc,bvi=G(()=>{"use strict";u0e();ZN=require("node:path"),Rbc=50,Dbc=/[\\/]+/gu,Obc=/^[a-zA-Z]:[\\/]/u,Mbc=new Set([".bzr",".git",".hg",".jj",".sl",".svn","node_modules"]);r(vvi,"createWorkspacePathSuggestionProvider");r(Nbc,"parseWorkspacePathToken");r(Lbc,"matchesPathQuery");r(Fbc,"compareWorkspacePathSuggestion");r(yvi,"basenameFromSuggestion");r(jbc,"toWorkspaceRelativePath");r(Bbc,"isPathInside")});async function wvi(e){let t=e.maxOutputBytes??qbc,n=e.timeoutMs??$bc,i=await(e.runCommand??Vbc)(Ubc,["-C",e.workspaceDirectory,...zbc],{maxOutputBytes:t,timeoutMs:n}).catch(()=>({exitCode:-1,stdout:""}));if(i.exitCode!==0)return;let a=i.stdout.trim().split(/\r?\n/,1)[0]?.trim();if(!(!a||a===Wbc))return a}async function Vbc(e,t,n){return await new Promise(o=>{let i;try{i=(0,Svi.spawn)(e,t,{stdio:["ignore","pipe","ignore"],windowsHide:!0})}catch{o({exitCode:-1,stdout:""});return}let a="",c=!1,u=setTimeout(()=>{i.kill(),f({exitCode:-1,stdout:a})},n.timeoutMs),f=r(h=>{c||(c=!0,clearTimeout(u),o(h))},"finish");i.stdout?.on("data",h=>{a+=h.toString("utf8"),Buffer.byteLength(a,"utf8")>n.maxOutputBytes&&(i.kill(),f({exitCode:-1,stdout:a}))}),i.on("error",()=>f({exitCode:-1,stdout:a})),i.on("close",h=>f({exitCode:h,stdout:a}))})}var Svi,Ubc,zbc,$bc,qbc,Wbc,kvi=G(()=>{"use strict";Svi=require("node:child_process"),Ubc="git",zbc=["symbolic-ref","--quiet","--short","HEAD"],$bc=750,qbc=512,Wbc="HEAD";r(wvi,"resolveWorkspaceGitBranch");r(Vbc,"runGitCommand")});var xvi,Tvi=G(()=>{"use strict";yi();jyi();zyi();vRt();zme();T3n();cvi();hvi();_vi();bvi();kvi();C3n();XY();xvi=r(async(e,t,n,o,i,a,c,u=!1,f="off",h=ZY)=>{try{let _=ivi(i),b=n.runTui??(await mvi()).runTui,S=(n.cwd??process.cwd)(),x=n.env??process.env,I=S2e(x)==="development",C=gvi({deps:n,options:t,workingDirectory:S}),R=avi(n,_,o,a,t.locale,t.detectedLocale,C,c,u,f,t.browserUse,t.browserExecutable,h),O=PQe({cleanup:r(async()=>{await R.close?.()},"cleanup"),cleanupTimeoutMs:n.shutdownCleanupTimeoutMs,exitProcess:n.exitProcess,process:n.shutdownProcess});try{let $zTuiResumeOptions=a,$zTuiResumeReady=($zTuiResumeOptions.resumeSessionId||$zTuiResumeOptions.continueSession)?await R.readExecutionState?.():void 0;return await b({loadStartupOptions:r(async()=>{let[U,j,z]=await Promise.all([Vyi(R),PRt(n).catch(()=>{}),(n.resolveWorkspaceGitBranch??wvi)({workspaceDirectory:S}).catch(()=>{})]);return{initialMode:L9(_),initialModel:U.model,initialThoughtLevel:U.thoughtLevel,loginRequired:U.loginRequired,locale:U.locale??C,theme:U.theme??"auto",modelOptions:U.modelOptions,effortOptions:U.effortOptions,slashCommands:s3n(j,{workflowMode:h}),workspaceGitBranch:z}},"loadStartupOptions"),locale:C,developerMode:I,version:o,workspaceDirectory:S,noColor:t.noColor,readClipboardImage:n.readClipboardImage??Nyi(),readDefaultModel:R.readDefaultModel,setDefaultModel:R.setDefaultModel,reloadModelOptions:R.reloadModelOptions,listModelOptions:R.listModelOptions,listWorkspacePathSuggestions:vvi({workspaceDirectory:S}),listMcpServers:R.listMcpServers,readSubagents:R.readSubagents,readSubagentTranscript:R.readSubagentTranscript,listWorkflowRuns:R.listWorkflowRuns,replayWorkflowRuns:R.replayWorkflowRuns,reduceWorkflowRuns:($zState,$zEvent)=>{hCr();return yot($zState,$zEvent)},retuneWorkflowConcurrency:R.retuneWorkflowConcurrency,listSavedWorkflows:R.listSavedWorkflows,readSavedWorkflow:R.readSavedWorkflow,saveWorkflowRun:R.saveWorkflowRun,startSavedWorkflow:R.startSavedWorkflow,getMainSessionId:R.getMainSessionId,writeClipboardText:n.writeClipboardText??Uyi({stdout:e.stdout}),stderr:e.stderr,stdin:e.stdin,stdout:e.stdout,loadSessionTranscript:R.loadSessionTranscript,loadSessionContextMessages:R.loadSessionContextMessages,readGoal:R.readGoal,readTodos:R.readTodos,readRuntimeProjection:R.readRuntimeProjection,readSessionUsage:R.readSessionUsage,cancelBackgroundTask:R.cancelBackgroundTask,previewFileRewind:R.previewFileRewind,applyFileRewind:R.applyFileRewind,setCustomSessionTitle:R.setCustomSessionTitle,readCustomSessionTitle:R.readCustomSessionTitle,readSessionResumeTarget:R.readSessionResumeTarget,interruptTurn:R.interruptTurn,promoteQueuedInput:R.promoteQueuedInput,listSkills:R.listSkills,readExecutionState:R.readExecutionState,setPlanEnabled:R.setPlanEnabled,setTransientModel:R.setTransientModel,readSessionModel:R.readSessionModel,sendBackgroundTaskMessage:R.sendBackgroundTaskMessage,recallPreviousInput:R.recallPreviousInput,sendInput:R.sendInput,setMode:R.setMode,submitPrompt:R,subscribeSessionEvents:R.subscribeSessionEvents})}finally{O(),await R.close?.()}}catch(_){let b=_ instanceof Error?_.message:String(_);return e.stderr.write(`Error: ${b}
|
|
15643
15643
|
`),t.verbose&&_ instanceof Error&&_.stack&&e.stderr.write(`${_.stack}
|
|
15644
15644
|
`),1}},"runTuiCommand")});var Cvi={};Xg(Cvi,{run:()=>fSc});var F9,Hbc,Gbc,Jbc,Kbc,Zbc,Ybc,Xbc,Qbc,eSc,tSc,DRt,A3n,nSc,rSc,Ivi,oSc,iSc,sSc,aSc,cSc,lSc,uSc,RRt,dSc,pSc,fSc,Evi=G(()=>{"use strict";Ln();Mme();bQe();Sje();ug();ug();FN();ane();Y$o();S0i();FBn();KY();C0i();N0i();B0i();zBn();mZt();AZt();V0i();yyi();Dyi();_3n();Tvi();XY();F9="0.17.0",Hbc="--target requires non-empty text.",Gbc="yolo",Jbc="--force-mcs can only be used with --prompt, --target, or tui.",Kbc="--target-replace requires --target.",Zbc='--target cannot be used with --prompt. Use either --target <objective> or --prompt "/goal <objective>".',Ybc="--browser-executable requires --browser-use=headless.",Xbc="--browser-use=headless can only be used with --prompt, --target, or tui.",Qbc="--surface can only be used with --prompt, --target, app-server, or agent-server.",eSc="--memory-bench can only be used with -p/--prompt.",tSc=r(e=>({...e.all===!0?{all:!0}:{},...e.available===!0?{available:!0}:{},...e["keep-data"]===!0?{keepData:!0}:{},...typeof e.scope=="string"?{scope:e.scope}:{},...Array.isArray(e.sparse)?{sparse:e.sparse}:{}}),"pluginsCommandFlags"),DRt=r(e=>e[0]??"tui","commandName"),A3n=r(e=>typeof e.prompt=="string"||e.targetRequest!==void 0||DRt(e.positionals)==="tui","isForceMcsSupportedInvocation"),nSc=r(e=>{let t=DRt(e.positionals);return typeof e.prompt=="string"||e.targetRequest!==void 0||t==="app-server"||t==="agent-server"},"isPresentationSurfaceSupportedInvocation"),rSc=r((e,t,n,o,i,a)=>({browserExecutable:i,browserUse:o,detectedLocale:n,force:e.force===!0,json:e.json===!0,locale:t,...e["memory-bench"]===!0?{memoryBench:!0}:{},noColor:e["no-color"]===!0,...a?{outputFormat:a}:{},verbose:e.verbose===!0}),"globalOptions"),Ivi=["text","json","stream-json"],oSc=r(e=>{if(e!==void 0){if(Ivi.includes(e))return e;throw new Error(`--output-format must be one of ${Ivi.join(", ")} (received: ${e}).`)}},"normalizeOutputFormat"),iSc=r(e=>{if(e!==void 0){if(K8e(e))return e;throw new Error(vj().cli.errors.localeUnsupported(e))}},"normalizeLocaleOption"),sSc=r(e=>{if(e===void 0)return;let t=e.toLowerCase();if(t==="build"||t==="edit"||t==="yolo"||t==="guarded")return t;throw new Error(`Unsupported --mode value: ${e}. Supported modes: build, edit, guarded, yolo. Use /plan in the TUI to toggle planning.`)},"normalizePromptMode"),aSc=r(e=>{if(e!==void 0){if(e.toLowerCase()==="headless")return"headless";throw new Error(`Unsupported --browser-use value: ${e}. Supported value: headless.`)}},"normalizeBrowserUse"),cSc=r(e=>{if(e===void 0||e.toLowerCase()==="terminal")return"terminal";if(e.toLowerCase()==="desktop")return"zcode_desktop";throw new Error(`Unsupported --surface value: ${e}. Supported surfaces: terminal, desktop.`)},"normalizePresentationSurface"),lSc=r(e=>{let t=e.target,n=e["target-replace"]===!0;if(t===void 0){if(n)throw new Error(Kbc);return}let o=t.trim();if(o.length===0)throw new Error(Hbc);return{objective:o,replaceExisting:n}},"normalizeTargetRequest"),uSc=r(e=>e.replaceExisting?`/goal replace ${e.objective}`:`/goal ${e.objective}`,"buildHeadlessTargetCommand"),RRt=r((e,t,n)=>{e.write(Z$o(F9,t,n))},"writeHelp"),dSc=r((e,t,n)=>{let o=nOn(),i={cli:{name:mdr,processName:fZt,version:F9},runtime:{arch:o.arch,cwd:n,execPath:o.execPath,node:o.node,platform:o.platform,processTitle:process.title,sea:o.sea},packaging:{default:"node-bundle",sea:"optional"},configuration:require(require("node:path").join(__dirname,"cli-config.cjs")).inspectRuntimeConfiguration(n,$zOptions=>{tao();return Dh($zOptions)})};if(t.json)return e.stdout.write(lg(i)),i.configuration.ok?0:1;let a=eOn(e.stdout,t.noColor);return e.stdout.write(`${tOn.bold("zcode doctor",a)}
|
|
15645
15645
|
`),e.stdout.write(`version: ${i.cli.version}
|