zcode-app-cli 3.17.2-44 → 3.17.2-45
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 +8 -0
- package/bin/zcode.js +3 -2
- package/docs/CONFIGURATION.md +4 -0
- package/docs/CONFIGURATION.zh-CN.md +3 -0
- package/package.json +1 -1
- package/vendor/cli-config.cjs +59 -0
- package/vendor/extraction.json +1 -1
- package/vendor/node_modules/@zcode/tui/dist/index.js +210 -13
- package/vendor/zcode.cjs +3 -3
package/README.md
CHANGED
|
@@ -146,6 +146,14 @@ cycling (Tab also cycles effort on an empty prompt); structured session-goal sta
|
|
|
146
146
|
animated active-turn timer with a static `ZCODE_TUI_REDUCED_MOTION=1`
|
|
147
147
|
fallback; responsive context-remaining and session-token metrics.
|
|
148
148
|
|
|
149
|
+
**Session discovery.** Bare `/resume` opens a directory-scoped picker;
|
|
150
|
+
`/sessions` browses desktop and CLI sessions across directories, including forks
|
|
151
|
+
and workflow parents. Filter by title, directory or session ID, inspect details
|
|
152
|
+
with Ctrl+O, then press Enter to resume. Both pickers use the runtime's configured
|
|
153
|
+
session database, including `storage.sessionDbPath` and `ZCODE_SESSION_DB_PATH` overrides.
|
|
154
|
+
Cross-directory resumes update the displayed workspace and Git branch, file
|
|
155
|
+
completion and `/diff` to follow the restored session's working directory.
|
|
156
|
+
|
|
149
157
|
**Login and permissions.** `/login` setup choices with masked API-key entry,
|
|
150
158
|
redacted transcript/history and OAuth waiting state; suspended Z.AI browser
|
|
151
159
|
login with terminal restoration and an optional `ZCODE_TUI_LOGIN_CMD`
|
package/bin/zcode.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { spawn } from "node:child_process";
|
|
2
|
+
import { execFile, spawn } from "node:child_process";
|
|
3
3
|
import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, unlinkSync } from "node:fs";
|
|
4
4
|
import { constants, homedir, tmpdir } from "node:os";
|
|
5
5
|
import { basename, dirname, join, posix, resolve, sep, win32 } from "node:path";
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
7
7
|
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
8
8
|
import { access, chmod, link, mkdir, mkdtemp, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
9
|
+
import { parseArgs, promisify } from "node:util";
|
|
9
10
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
10
11
|
import { StringDecoder } from "node:string_decoder";
|
|
11
12
|
import { createInterface } from "node:readline/promises";
|
|
12
|
-
import { parseArgs } from "node:util";
|
|
13
13
|
//#region setting.example.json
|
|
14
14
|
var setting_example_default = {
|
|
15
15
|
modelStream: { "idleTimeoutMs": 6e4 },
|
|
@@ -339,6 +339,7 @@ async function markSetupPending(env = process.env) {
|
|
|
339
339
|
async function clearSetupPending(env = process.env) {
|
|
340
340
|
await rm(setupPendingPath(env), { force: true }).catch(() => {});
|
|
341
341
|
}
|
|
342
|
+
promisify(execFile);
|
|
342
343
|
new AsyncLocalStorage();
|
|
343
344
|
//#endregion
|
|
344
345
|
//#region src/runtime-config-bridge.ts
|
package/docs/CONFIGURATION.md
CHANGED
|
@@ -32,6 +32,10 @@ Hook trust commands use that file's `storage.dir` too. Providers, credentials an
|
|
|
32
32
|
the session database (including persisted project permissions) have separate path
|
|
33
33
|
overrides; changing only the settings file does not isolate those stores. See
|
|
34
34
|
[host integration](HOST_INTEGRATION.md#environment-and-configuration) for examples.
|
|
35
|
+
The `/resume` and `/sessions` pickers use the active runtime's session database,
|
|
36
|
+
respecting `storage.sessionDbPath` and `ZCODE_SESSION_DB_PATH` overrides.
|
|
37
|
+
Resuming a session from another directory also switches the TUI's workspace path,
|
|
38
|
+
Git branch, file completion and `/diff` to that session's working directory.
|
|
35
39
|
Desktop preferences remain in `~/.zcode/v2/setting.json`; Desktop's user hooks and
|
|
36
40
|
MCP configuration in `~/.zcode/cli/config.json` are not continuously synchronized
|
|
37
41
|
with the CLI settings file.
|
|
@@ -28,6 +28,9 @@ CLI 通用设置默认使用用户目录中的 `~/.zcode/cli/setting.json`。
|
|
|
28
28
|
旧 `config.json` 和 `migrations/` 标记使用所选文件所在目录,hook 信任命令也读取该文件的
|
|
29
29
|
`storage.dir`。Provider、凭证和会话数据库(含持久化项目权限)有各自的路径覆盖变量,
|
|
30
30
|
仅切换设置文件不会隔离这些存储,示例见[宿主集成](HOST_INTEGRATION.md#environment-and-configuration)。
|
|
31
|
+
`/resume` 和 `/sessions` 选择器读取当前 runtime 实际使用的会话数据库,遵循
|
|
32
|
+
`storage.sessionDbPath` 和 `ZCODE_SESSION_DB_PATH` 的路径覆盖。
|
|
33
|
+
跨目录恢复会话时,TUI 显示的工作区路径、Git 分支、文件补全和 `/diff` 也同步切换到该会话的工作目录。
|
|
31
34
|
Desktop 偏好仍位于 `~/.zcode/v2/setting.json`;桌面端保存在 `~/.zcode/cli/config.json`
|
|
32
35
|
中的用户 hooks 和 MCP 配置不会与 CLI 设置文件持续同步。
|
|
33
36
|
|
package/package.json
CHANGED
package/vendor/cli-config.cjs
CHANGED
|
@@ -4,6 +4,8 @@ let node_fs_promises = require("node:fs/promises");
|
|
|
4
4
|
let node_path = require("node:path");
|
|
5
5
|
let node_crypto = require("node:crypto");
|
|
6
6
|
let node_os = require("node:os");
|
|
7
|
+
let node_child_process = require("node:child_process");
|
|
8
|
+
let node_util = require("node:util");
|
|
7
9
|
let node_async_hooks = require("node:async_hooks");
|
|
8
10
|
let node_buffer = require("node:buffer");
|
|
9
11
|
//#region src/config-paths.ts
|
|
@@ -115,8 +117,38 @@ async function readSessionResumeTarget(app) {
|
|
|
115
117
|
const session = await store.getSession(sessionId);
|
|
116
118
|
return session && session.time?.deleted === void 0 ? sessionId : void 0;
|
|
117
119
|
}
|
|
120
|
+
function readSessionDatabasePath(app) {
|
|
121
|
+
return (app.sessionStore ?? app.runtime?.sessionStore)?.getDatabasePath?.();
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Back the runtime's native `/resume` picker (which renders only when the app
|
|
125
|
+
* facade exposes `listSessions`). Directory-scoped to match the runtime's own
|
|
126
|
+
* semantics; deleted sessions are excluded by the store itself.
|
|
127
|
+
*/
|
|
128
|
+
async function listSessionsForPicker(app) {
|
|
129
|
+
const store = app.sessionStore ?? app.runtime?.sessionStore;
|
|
130
|
+
if (!store?.listSessions) return [];
|
|
131
|
+
const directory = app.directory ?? app.runtime?.directory ?? process.cwd();
|
|
132
|
+
return (await store.listSessions({
|
|
133
|
+
directory,
|
|
134
|
+
limit: 50,
|
|
135
|
+
taskTypes: [
|
|
136
|
+
"interactive",
|
|
137
|
+
"fork",
|
|
138
|
+
"workflow_parent"
|
|
139
|
+
]
|
|
140
|
+
})).map((row) => ({
|
|
141
|
+
id: row.id,
|
|
142
|
+
title: row.title ?? "",
|
|
143
|
+
directory: row.directory ?? directory,
|
|
144
|
+
updatedAt: row.time?.updated ?? row.time?.created ?? 0,
|
|
145
|
+
parentId: row.parentID ?? null
|
|
146
|
+
}));
|
|
147
|
+
}
|
|
118
148
|
//#endregion
|
|
119
149
|
//#region src/runtime-tui-bridge.ts
|
|
150
|
+
const execFileAsync = (0, node_util.promisify)(node_child_process.execFile);
|
|
151
|
+
const workspaceSnapshots = /* @__PURE__ */ new WeakMap();
|
|
120
152
|
const maximumTaskMessageLength = 2e4;
|
|
121
153
|
const maximumTaskSummaryLength = 200;
|
|
122
154
|
function taskDetail(task) {
|
|
@@ -144,6 +176,30 @@ function taskDetail(task) {
|
|
|
144
176
|
cancellable: kind === "local_agent" ? running : task.cancellable
|
|
145
177
|
};
|
|
146
178
|
}
|
|
179
|
+
async function readRuntimeWorkspace(runtime) {
|
|
180
|
+
const directory = runtime?.workingDirectory;
|
|
181
|
+
if (!runtime || !directory) return void 0;
|
|
182
|
+
const cached = workspaceSnapshots.get(runtime);
|
|
183
|
+
if (cached?.directory === directory) return await cached.snapshot;
|
|
184
|
+
const snapshot = execFileAsync("git", ["branch", "--show-current"], {
|
|
185
|
+
cwd: directory,
|
|
186
|
+
timeout: 1e3,
|
|
187
|
+
maxBuffer: 16 * 1024,
|
|
188
|
+
windowsHide: true,
|
|
189
|
+
env: {
|
|
190
|
+
...process.env,
|
|
191
|
+
GIT_OPTIONAL_LOCKS: "0"
|
|
192
|
+
}
|
|
193
|
+
}).then(({ stdout }) => ({
|
|
194
|
+
directory,
|
|
195
|
+
branch: stdout.trim() || void 0
|
|
196
|
+
}), () => ({ directory }));
|
|
197
|
+
workspaceSnapshots.set(runtime, {
|
|
198
|
+
directory,
|
|
199
|
+
snapshot
|
|
200
|
+
});
|
|
201
|
+
return await snapshot;
|
|
202
|
+
}
|
|
147
203
|
async function readTuiRuntimeProjection(app, bridge) {
|
|
148
204
|
const executionState = await app.readExecutionState();
|
|
149
205
|
await bridge.$zRestorePersistedBackgroundTasks?.(app);
|
|
@@ -162,6 +218,7 @@ async function readTuiRuntimeProjection(app, bridge) {
|
|
|
162
218
|
return {
|
|
163
219
|
...projection,
|
|
164
220
|
...executionState && typeof executionState === "object" ? executionState : {},
|
|
221
|
+
workspace: await readRuntimeWorkspace(app.runtime),
|
|
165
222
|
backgroundTasks: tasks,
|
|
166
223
|
backgroundTaskDetails: details,
|
|
167
224
|
restoredBackgroundTasks: Array.isArray(app.$zRestoredBackgroundTasksLog) ? app.$zRestoredBackgroundTasksLog : []
|
|
@@ -1253,10 +1310,12 @@ exports.ensureSessionForTitle = ensureSessionForTitle;
|
|
|
1253
1310
|
exports.exchangeBigmodelOAuthCode = exchangeBigmodelOAuthCode;
|
|
1254
1311
|
exports.inspectRuntimeConfiguration = inspectRuntimeConfiguration;
|
|
1255
1312
|
exports.installSqliteWriteRecovery = installSqliteWriteRecovery;
|
|
1313
|
+
exports.listSessionsForPicker = listSessionsForPicker;
|
|
1256
1314
|
exports.mergeDesktopSettings = mergeDesktopSettings;
|
|
1257
1315
|
exports.migrateLegacyProviders = migrateLegacyProviders;
|
|
1258
1316
|
exports.providerMigrationNeeded = providerMigrationNeeded;
|
|
1259
1317
|
exports.pruneSqliteUsage = pruneSqliteUsage;
|
|
1318
|
+
exports.readSessionDatabasePath = readSessionDatabasePath;
|
|
1260
1319
|
exports.readSessionModelState = readSessionModelState;
|
|
1261
1320
|
exports.readSessionResumeTarget = readSessionResumeTarget;
|
|
1262
1321
|
exports.readStartPlanSession = readStartPlanSession;
|
package/vendor/extraction.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"appVersion": "3.17.2",
|
|
3
3
|
"cliVersion": "0.17.1",
|
|
4
|
-
"extractedAt": "2026-11-
|
|
4
|
+
"extractedAt": "2026-11-05T16:00:27.210Z",
|
|
5
5
|
"sha512": "d+0Fn/LD8C33LbxzD9jV3Er1JKg9uHii+mcSakVGd1o93WQtCNkfzrOR1DKCk6j2f26YjY5XbgWBYwCY6ROfqg==",
|
|
6
6
|
"source": "https://cdn-zcode.z.ai/zcode/electron/releases/3.17.2/linux-x64/ZCode-3.17.2-linux-x64.deb",
|
|
7
7
|
"runtimeCapabilities": {
|
|
@@ -7,6 +7,7 @@ import { basename, dirname, extname, isAbsolute, join, posix, resolve, sep, win3
|
|
|
7
7
|
import { randomUUID } from "node:crypto";
|
|
8
8
|
import { Box, CombinedAutocompleteProvider, Container, Editor, Image, Input, Markdown, ProcessTerminal, ScrollView, SelectList, Spacer, Text, TuiAltScreen, TuiMainScreen, VStack, decodeKittyPrintable, getKeybindings, isKeyRelease, isViewportTUI, matchesKey, renderFakeCursor, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
|
|
9
9
|
import { AltScreenSearchComponent } from "@earendil-works/pi-tui/dist/alt-screen-search.js";
|
|
10
|
+
import { DatabaseSync } from "node:sqlite";
|
|
10
11
|
import { StringDecoder } from "node:string_decoder";
|
|
11
12
|
import { isDeepStrictEqual } from "node:util";
|
|
12
13
|
var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
|
|
@@ -157381,6 +157382,120 @@ function deliveredBackgroundTaskIds(messages) {
|
|
|
157381
157382
|
return delivered;
|
|
157382
157383
|
}
|
|
157383
157384
|
//#endregion
|
|
157385
|
+
//#region packages/zcode-tui/src/session-picker.ts
|
|
157386
|
+
function defaultCliDbPath(home) {
|
|
157387
|
+
return join(home, ".zcode", "cli", "db", "db.sqlite");
|
|
157388
|
+
}
|
|
157389
|
+
function defaultTasksDbPath(home) {
|
|
157390
|
+
return join(home, ".zcode", "v2", "tasks-index.sqlite");
|
|
157391
|
+
}
|
|
157392
|
+
function openReadOnly(path) {
|
|
157393
|
+
try {
|
|
157394
|
+
return new DatabaseSync(path, { readOnly: true });
|
|
157395
|
+
} catch {
|
|
157396
|
+
return;
|
|
157397
|
+
}
|
|
157398
|
+
}
|
|
157399
|
+
function desktopTaskInfo(tasksDbPath) {
|
|
157400
|
+
const result = /* @__PURE__ */ new Map();
|
|
157401
|
+
const db = openReadOnly(tasksDbPath);
|
|
157402
|
+
if (!db) return result;
|
|
157403
|
+
try {
|
|
157404
|
+
const rows = db.prepare("SELECT task_id, title, pinned, archived FROM tasks WHERE deleted = 0").all();
|
|
157405
|
+
for (const row of rows) result.set(row.task_id, {
|
|
157406
|
+
title: row.title ?? "",
|
|
157407
|
+
pinned: row.pinned === 1,
|
|
157408
|
+
archived: row.archived === 1
|
|
157409
|
+
});
|
|
157410
|
+
} catch {} finally {
|
|
157411
|
+
db.close();
|
|
157412
|
+
}
|
|
157413
|
+
return result;
|
|
157414
|
+
}
|
|
157415
|
+
function firstLine(value) {
|
|
157416
|
+
return value.split("\n", 1)[0] ?? value;
|
|
157417
|
+
}
|
|
157418
|
+
/**
|
|
157419
|
+
* List recent resumable sessions from the shared ZCode session store.
|
|
157420
|
+
*
|
|
157421
|
+
* The desktop app and the CLI persist sessions in the same SQLite database,
|
|
157422
|
+
* so this surfaces desktop conversations as well as CLI ones. Desktop titles
|
|
157423
|
+
* and pinned/archived flags come from the desktop's task index when present.
|
|
157424
|
+
* All databases are opened read-only and failures degrade gracefully.
|
|
157425
|
+
*/
|
|
157426
|
+
function listRecentSessions(options = {}) {
|
|
157427
|
+
const home = options.home ?? homedir();
|
|
157428
|
+
const db = openReadOnly(options.cliDbPath ?? defaultCliDbPath(home));
|
|
157429
|
+
if (!db) return [];
|
|
157430
|
+
try {
|
|
157431
|
+
const rows = db.prepare(`SELECT s.id, s.title, s.directory, s.time_updated,
|
|
157432
|
+
(SELECT COUNT(*) FROM message m WHERE m.session_id = s.id) AS message_count
|
|
157433
|
+
FROM session s
|
|
157434
|
+
WHERE s.task_type IN ('interactive', 'fork', 'workflow_parent')
|
|
157435
|
+
AND s.time_deleted IS NULL
|
|
157436
|
+
AND s.id NOT LIKE 'sess_subagent%'
|
|
157437
|
+
ORDER BY s.time_updated DESC
|
|
157438
|
+
LIMIT ?`).all(options.limit ?? 200);
|
|
157439
|
+
const tasks = desktopTaskInfo(options.tasksDbPath ?? defaultTasksDbPath(home));
|
|
157440
|
+
const summaries = [];
|
|
157441
|
+
for (const row of rows) {
|
|
157442
|
+
if (options.excludeIds?.has(row.id)) continue;
|
|
157443
|
+
const task = tasks.get(row.id);
|
|
157444
|
+
const inDesktopWorkspace = row.directory.startsWith(join(home, ".zcode", "workspace"));
|
|
157445
|
+
summaries.push({
|
|
157446
|
+
id: row.id,
|
|
157447
|
+
title: firstLine(task?.title || row.title || "(untitled)"),
|
|
157448
|
+
directory: row.directory,
|
|
157449
|
+
timeUpdated: row.time_updated,
|
|
157450
|
+
messageCount: row.message_count,
|
|
157451
|
+
source: task !== void 0 || inDesktopWorkspace ? "desktop" : "cli",
|
|
157452
|
+
pinned: task?.pinned ?? false,
|
|
157453
|
+
archived: task?.archived ?? false
|
|
157454
|
+
});
|
|
157455
|
+
}
|
|
157456
|
+
return summaries;
|
|
157457
|
+
} catch {
|
|
157458
|
+
return [];
|
|
157459
|
+
} finally {
|
|
157460
|
+
db.close();
|
|
157461
|
+
}
|
|
157462
|
+
}
|
|
157463
|
+
function formatSessionTimestamp(timeUpdated) {
|
|
157464
|
+
const date = new Date(timeUpdated);
|
|
157465
|
+
if (Number.isNaN(date.getTime())) return "?";
|
|
157466
|
+
const pad = (value) => String(value).padStart(2, "0");
|
|
157467
|
+
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
|
|
157468
|
+
}
|
|
157469
|
+
function sessionDetail(session, currentDirectory) {
|
|
157470
|
+
const lines = [
|
|
157471
|
+
session.title,
|
|
157472
|
+
"",
|
|
157473
|
+
`Session: ${session.id}`,
|
|
157474
|
+
`Directory: ${session.directory}`,
|
|
157475
|
+
`Updated: ${formatSessionTimestamp(session.timeUpdated)} · ${session.messageCount} messages · ${session.source}${session.pinned ? " · pinned" : ""}${session.archived ? " · archived" : ""}`
|
|
157476
|
+
];
|
|
157477
|
+
if (currentDirectory && session.directory !== currentDirectory) lines.push("", "This session belongs to another directory.");
|
|
157478
|
+
return lines.join("\n");
|
|
157479
|
+
}
|
|
157480
|
+
function sessionPreview(session, currentDirectory) {
|
|
157481
|
+
return new Text(sanitizeTerminalText(sessionDetail(session, currentDirectory), { preserveSgr: false }), 1, 0);
|
|
157482
|
+
}
|
|
157483
|
+
function sessionChoiceItem(session, currentDirectory) {
|
|
157484
|
+
return {
|
|
157485
|
+
value: session.id,
|
|
157486
|
+
label: `${session.pinned ? "★ " : ""}${session.title}`,
|
|
157487
|
+
description: [
|
|
157488
|
+
formatSessionTimestamp(session.timeUpdated),
|
|
157489
|
+
`${session.messageCount} msg${session.messageCount === 1 ? "" : "s"}`,
|
|
157490
|
+
session.source,
|
|
157491
|
+
session.directory
|
|
157492
|
+
].join(" · "),
|
|
157493
|
+
keywords: [session.id],
|
|
157494
|
+
preview: sessionPreview(session, currentDirectory),
|
|
157495
|
+
payload: session
|
|
157496
|
+
};
|
|
157497
|
+
}
|
|
157498
|
+
//#endregion
|
|
157384
157499
|
//#region packages/zcode-tui/src/background-task-output.ts
|
|
157385
157500
|
const defaultMaximumBytes = 64 * 1024;
|
|
157386
157501
|
function readBackgroundTaskOutput(path, maximumBytes = defaultMaximumBytes) {
|
|
@@ -157892,7 +158007,8 @@ function choose(ui, host, theme, options) {
|
|
|
157892
158007
|
const safeItem = {
|
|
157893
158008
|
...item,
|
|
157894
158009
|
label: sanitizeTerminalText(item.label, { preserveSgr: false }),
|
|
157895
|
-
description: item.description ? sanitizeTerminalText(item.description, { preserveSgr: false }) : void 0
|
|
158010
|
+
description: item.description ? sanitizeTerminalText(item.description, { preserveSgr: false }) : void 0,
|
|
158011
|
+
keywords: item.keywords?.map((keyword) => sanitizeTerminalText(keyword, { preserveSgr: false }))
|
|
157896
158012
|
};
|
|
157897
158013
|
const displayLabel = numberShortcutsEnabled ? `${index + 1}. ${safeItem.label}` : safeItem.label;
|
|
157898
158014
|
const value = `${safeItem.label}\u0000${index}`;
|
|
@@ -157901,7 +158017,8 @@ function choose(ui, host, theme, options) {
|
|
|
157901
158017
|
return {
|
|
157902
158018
|
value,
|
|
157903
158019
|
label: displayLabel,
|
|
157904
|
-
description: safeItem.description
|
|
158020
|
+
description: safeItem.description,
|
|
158021
|
+
keywords: safeItem.keywords
|
|
157905
158022
|
};
|
|
157906
158023
|
});
|
|
157907
158024
|
const hasDetails = Boolean(options.content || options.showSelectedItemDetails || options.items.some((item) => item.preview));
|
|
@@ -157912,7 +158029,7 @@ function choose(ui, host, theme, options) {
|
|
|
157912
158029
|
const maxExpandedContentLines = Math.max(2, maxContentLines, ui.terminal.rows - 8);
|
|
157913
158030
|
const dialog = new ChoiceDialog(sanitizeTerminalText(options.title, { preserveSgr: false }), sanitizeTerminalText(options.prompt, { preserveSgr: false }), sanitizeTerminalText(options.help ?? (hasDetails ? numberShortcutsEnabled ? "Type to filter · number selects · Up/Down choose · Ctrl+O details · ←/→ or PgUp/PgDn scroll · Enter confirm · Esc cancel" : "Type to filter · Up/Down choose · Ctrl+O details · ←/→ or PgUp/PgDn scroll · Enter confirm · Esc cancel" : numberShortcutsEnabled ? "Type to filter · number selects · Up/Down choose · Enter confirm · Esc cancel · Ctrl+U clear" : "Type to filter · Up/Down choose · Enter confirm · Esc cancel · Ctrl+U clear"), { preserveSgr: false }), list, theme, options.content, sanitizeTerminalText(options.contentLabel ?? "Details", { preserveSgr: false }), maxContentLines, maxExpandedContentLines, options.filterMode === "substring" ? (filter) => {
|
|
157914
158031
|
const query = filter.toLowerCase();
|
|
157915
|
-
return new SelectList(searchableItems.filter((item) => item.label.toLowerCase().includes(query) || item.description?.toLowerCase().includes(query)), maxVisible, theme.select);
|
|
158032
|
+
return new SelectList(searchableItems.filter((item) => item.label.toLowerCase().includes(query) || item.description?.toLowerCase().includes(query) || item.keywords?.some((keyword) => keyword.toLowerCase().includes(query))), maxVisible, theme.select);
|
|
157916
158033
|
} : void 0);
|
|
157917
158034
|
dialog.numberShortcutCount = numberShortcutsEnabled ? options.items.length : 0;
|
|
157918
158035
|
const previewFor = (item) => {
|
|
@@ -163426,8 +163543,14 @@ function normalizeRuntimeProjection(value) {
|
|
|
163426
163543
|
const rawLastError = isRecord(projection.lastError) ? projection.lastError : void 0;
|
|
163427
163544
|
const lastErrorType = rawLastError && stringField(rawLastError, "type");
|
|
163428
163545
|
const lastErrorMessage = rawLastError && stringField(rawLastError, "message");
|
|
163546
|
+
const workspace = isRecord(projection.workspace) ? projection.workspace : void 0;
|
|
163547
|
+
const workspaceDirectory = workspace && asString(workspace.directory);
|
|
163429
163548
|
return {
|
|
163430
163549
|
sessionId: stringField(projection, "sessionId", "sessionID", "id"),
|
|
163550
|
+
workspace: workspaceDirectory ? {
|
|
163551
|
+
directory: workspaceDirectory,
|
|
163552
|
+
branch: stringField(workspace, "branch")
|
|
163553
|
+
} : void 0,
|
|
163431
163554
|
status: stringField(projection, "status"),
|
|
163432
163555
|
mode: stringField(projection, "mode"),
|
|
163433
163556
|
planEnabled: typeof projection.planEnabled === "boolean" ? projection.planEnabled : void 0,
|
|
@@ -166026,6 +166149,10 @@ var FullscreenHeader = class {
|
|
|
166026
166149
|
setPhase(phase) {
|
|
166027
166150
|
this.phase = phase;
|
|
166028
166151
|
}
|
|
166152
|
+
setWorkspace(workspace, branch) {
|
|
166153
|
+
this.workspace = clean(workspace) ?? "";
|
|
166154
|
+
this.branch = clean(branch);
|
|
166155
|
+
}
|
|
166029
166156
|
getPhase() {
|
|
166030
166157
|
return this.phase;
|
|
166031
166158
|
}
|
|
@@ -166783,6 +166910,8 @@ var ZCodeTui = class {
|
|
|
166783
166910
|
deliveredStreamEvents = createStreamEventRedeliveryFilter();
|
|
166784
166911
|
notifications;
|
|
166785
166912
|
skillCatalog;
|
|
166913
|
+
workspaceDirectory;
|
|
166914
|
+
workspaceGitBranch;
|
|
166786
166915
|
done;
|
|
166787
166916
|
resolveDone;
|
|
166788
166917
|
stopped = false;
|
|
@@ -166896,13 +167025,14 @@ var ZCodeTui = class {
|
|
|
166896
167025
|
this.distributionVersion = sanitizeTerminalText(process.env.ZCODE_APP_CLI_VERSION?.trim() ?? "", { preserveSgr: false }) || void 0;
|
|
166897
167026
|
this.theme = createTheme(this.colorsEnabled, initialColorScheme(this.themePreference));
|
|
166898
167027
|
this.transcript = new Transcript(this.theme.searchMatch);
|
|
166899
|
-
|
|
167028
|
+
this.workspaceDirectory = options.workspaceDirectory ?? process.cwd();
|
|
167029
|
+
this.workspaceGitBranch = options.workspaceGitBranch;
|
|
166900
167030
|
const runtimeVersion = sanitizeTerminalText(options.version ?? "unknown", { preserveSgr: false });
|
|
166901
167031
|
this.fullscreenHeader = new FullscreenHeader(this.theme, {
|
|
166902
|
-
branch:
|
|
167032
|
+
branch: this.workspaceGitBranch,
|
|
166903
167033
|
distributionVersion: this.distributionVersion,
|
|
166904
167034
|
runtimeVersion,
|
|
166905
|
-
workspace
|
|
167035
|
+
workspace: this.workspaceDirectory
|
|
166906
167036
|
});
|
|
166907
167037
|
this.sessionWelcome = new SessionWelcome(this.theme, (width) => this.fullscreenHeader.location(width), (width) => this.fullscreenHeader.identity(width), {
|
|
166908
167038
|
loginRequired: options.loginRequired === true,
|
|
@@ -167002,6 +167132,7 @@ var ZCodeTui = class {
|
|
|
167002
167132
|
return;
|
|
167003
167133
|
}
|
|
167004
167134
|
await this.resolveTerminalColorScheme();
|
|
167135
|
+
await this.refreshWorkspace();
|
|
167005
167136
|
this.buildLayout();
|
|
167006
167137
|
if (notificationConfigError) this.addNotice(`Unable to load notification settings: ${notificationConfigError}`, "warning");
|
|
167007
167138
|
await this.restoreInitialTranscript();
|
|
@@ -167261,12 +167392,34 @@ var ZCodeTui = class {
|
|
|
167261
167392
|
editor.isTerminalFocused = () => this.terminalFocus !== "unfocused";
|
|
167262
167393
|
if (this.options.locale?.startsWith("zh")) editor.planHint = "先调研与规划,再开始修改";
|
|
167263
167394
|
for (const input of [...this.editorHistory].reverse()) editor.addToHistory(input);
|
|
167264
|
-
|
|
167265
|
-
const workspaceDirectory = this.options.workspaceDirectory ?? process.cwd();
|
|
167266
|
-
editor.setAutocompleteProvider(new WorkspaceAutocompleteProvider(commands, workspaceDirectory, this.options.listWorkspacePathSuggestions, this.skillCatalog, this.options.listPluginReferences ?? createRuntimePluginReferenceLister(workspaceDirectory), (this.options.slashCommands ?? []).flatMap((command) => command.aliases ?? [])));
|
|
167395
|
+
this.configureWorkspaceAutocomplete(editor);
|
|
167267
167396
|
editor.onSubmit = (text) => void this.submit(text);
|
|
167268
167397
|
return editor;
|
|
167269
167398
|
}
|
|
167399
|
+
configureWorkspaceAutocomplete(editor) {
|
|
167400
|
+
const commands = this.autocompleteCommands();
|
|
167401
|
+
editor.setAutocompleteProvider(new WorkspaceAutocompleteProvider(commands, this.workspaceDirectory, this.options.listWorkspacePathSuggestions, this.skillCatalog, this.options.listPluginReferences ?? createRuntimePluginReferenceLister(this.workspaceDirectory), (this.options.slashCommands ?? []).flatMap((command) => command.aliases ?? [])));
|
|
167402
|
+
}
|
|
167403
|
+
applyWorkspace(workspace) {
|
|
167404
|
+
if (!workspace) return;
|
|
167405
|
+
const directoryChanged = workspace.directory !== this.workspaceDirectory;
|
|
167406
|
+
if (!directoryChanged && workspace.branch === this.workspaceGitBranch) return;
|
|
167407
|
+
this.workspaceDirectory = workspace.directory;
|
|
167408
|
+
this.workspaceGitBranch = workspace.branch;
|
|
167409
|
+
this.fullscreenHeader.setWorkspace(this.workspaceDirectory, this.workspaceGitBranch);
|
|
167410
|
+
if (directoryChanged) {
|
|
167411
|
+
this.skillCatalog = new SkillCatalog(this.options.listSkills);
|
|
167412
|
+
this.configureWorkspaceAutocomplete(this.editor);
|
|
167413
|
+
}
|
|
167414
|
+
this.ui.requestRender(true);
|
|
167415
|
+
}
|
|
167416
|
+
async refreshWorkspace() {
|
|
167417
|
+
const revision = this.executionStateRevision;
|
|
167418
|
+
try {
|
|
167419
|
+
const projection = normalizeRuntimeProjection(await this.options.readRuntimeProjection?.());
|
|
167420
|
+
if (revision === this.executionStateRevision) this.applyWorkspace(projection?.workspace);
|
|
167421
|
+
} catch {}
|
|
167422
|
+
}
|
|
167270
167423
|
focusEditor() {
|
|
167271
167424
|
this.ui.setFocus(this.editor);
|
|
167272
167425
|
}
|
|
@@ -167505,6 +167658,10 @@ var ZCodeTui = class {
|
|
|
167505
167658
|
name: "diff",
|
|
167506
167659
|
description: "Browse current and per-turn file changes"
|
|
167507
167660
|
},
|
|
167661
|
+
{
|
|
167662
|
+
name: "sessions",
|
|
167663
|
+
description: "Browse and resume past sessions (desktop and CLI)"
|
|
167664
|
+
},
|
|
167508
167665
|
{
|
|
167509
167666
|
name: "context",
|
|
167510
167667
|
description: "Inspect context usage and prompt composition"
|
|
@@ -167691,7 +167848,7 @@ var ZCodeTui = class {
|
|
|
167691
167848
|
if (!await preflightSubmission({
|
|
167692
167849
|
validate: () => this.sessionModelIssue ? Promise.resolve(`${this.sessionModelIssue} Choose a model with /model before continuing.`) : missingCodingPlanKey({
|
|
167693
167850
|
model: this.model,
|
|
167694
|
-
workingDirectory: this.
|
|
167851
|
+
workingDirectory: this.workspaceDirectory
|
|
167695
167852
|
}),
|
|
167696
167853
|
isStopped: () => this.stopped,
|
|
167697
167854
|
submission,
|
|
@@ -167797,6 +167954,10 @@ var ZCodeTui = class {
|
|
|
167797
167954
|
await this.showDiffBrowser();
|
|
167798
167955
|
return;
|
|
167799
167956
|
}
|
|
167957
|
+
if (input === "/sessions") {
|
|
167958
|
+
await this.showSessionPicker();
|
|
167959
|
+
return;
|
|
167960
|
+
}
|
|
167800
167961
|
if (input.startsWith("/") && this.activeSubmissions > 0) {
|
|
167801
167962
|
this.addNotice("Wait for the active turn or press Ctrl+C before running a slash command.", "warning");
|
|
167802
167963
|
return;
|
|
@@ -168190,6 +168351,7 @@ var ZCodeTui = class {
|
|
|
168190
168351
|
this.emittedSessionTerminalTitle = "";
|
|
168191
168352
|
emitSessionTerminalTitle(this.options.stdout ?? process.stdout, "");
|
|
168192
168353
|
this.sessionMetrics = {};
|
|
168354
|
+
await this.refreshWorkspace();
|
|
168193
168355
|
await this.restoreCustomSessionTitle();
|
|
168194
168356
|
this.restoreTranscript(restoredMessages(result.restoredMessages));
|
|
168195
168357
|
if (this.transcript.blockCount > 0) this.enterSessionRail(true);
|
|
@@ -170569,7 +170731,7 @@ var ZCodeTui = class {
|
|
|
170569
170731
|
this.addNotice("Wait for the active turn or press Ctrl+C before opening diff.", "warning");
|
|
170570
170732
|
return;
|
|
170571
170733
|
}
|
|
170572
|
-
const sources = diffBrowserSources(await readWorkspaceDiff(this.
|
|
170734
|
+
const sources = diffBrowserSources(await readWorkspaceDiff(this.workspaceDirectory), this.turnDiffs.snapshots());
|
|
170573
170735
|
while (true) {
|
|
170574
170736
|
const sourceChoice = await this.showChoice({
|
|
170575
170737
|
title: "Diff",
|
|
@@ -170729,8 +170891,8 @@ var ZCodeTui = class {
|
|
|
170729
170891
|
mode: this.mode,
|
|
170730
170892
|
planEnabled: this.planEnabled,
|
|
170731
170893
|
effort: this.thoughtLevel,
|
|
170732
|
-
workspace: this.
|
|
170733
|
-
branch: this.
|
|
170894
|
+
workspace: this.workspaceDirectory,
|
|
170895
|
+
branch: this.workspaceGitBranch,
|
|
170734
170896
|
locale: this.options.locale,
|
|
170735
170897
|
developerMode: this.options.developerMode,
|
|
170736
170898
|
projection: this.runtimeProjection,
|
|
@@ -170790,6 +170952,40 @@ var ZCodeTui = class {
|
|
|
170790
170952
|
return "unavailable";
|
|
170791
170953
|
}
|
|
170792
170954
|
}
|
|
170955
|
+
async showSessionPicker() {
|
|
170956
|
+
if (this.activeSubmissions > 0 || this.turnAbortController) {
|
|
170957
|
+
this.addNotice("Wait for the active turn or press Ctrl+C before switching sessions.", "warning");
|
|
170958
|
+
return;
|
|
170959
|
+
}
|
|
170960
|
+
const currentSessionId = this.options.getMainSessionId?.();
|
|
170961
|
+
const cliDbPath = await this.options.readSessionDatabasePath?.();
|
|
170962
|
+
if (this.options.readSessionDatabasePath && !cliDbPath) {
|
|
170963
|
+
this.addNotice("Session browsing is unavailable for this session store.", "muted");
|
|
170964
|
+
return;
|
|
170965
|
+
}
|
|
170966
|
+
const sessions = listRecentSessions({
|
|
170967
|
+
cliDbPath,
|
|
170968
|
+
excludeIds: currentSessionId ? /* @__PURE__ */ new Set([currentSessionId]) : void 0
|
|
170969
|
+
});
|
|
170970
|
+
if (sessions.length === 0) {
|
|
170971
|
+
this.addNotice("No past sessions found in the shared session store.", "muted");
|
|
170972
|
+
return;
|
|
170973
|
+
}
|
|
170974
|
+
const currentDirectory = this.workspaceDirectory;
|
|
170975
|
+
const selected = await this.showChoice({
|
|
170976
|
+
title: "Sessions",
|
|
170977
|
+
prompt: `${sessions.length} recent session${sessions.length === 1 ? "" : "s"} · Enter resumes in place`,
|
|
170978
|
+
help: "Type to filter by title, directory or id · Up/Down choose · Ctrl+O details · Enter resume · Esc cancel",
|
|
170979
|
+
filterMode: "substring",
|
|
170980
|
+
items: sessions.map((session) => sessionChoiceItem(session, currentDirectory))
|
|
170981
|
+
});
|
|
170982
|
+
if (!selected) return;
|
|
170983
|
+
if (selected.value === currentSessionId) {
|
|
170984
|
+
this.addNotice("This session is already active.", "muted");
|
|
170985
|
+
return;
|
|
170986
|
+
}
|
|
170987
|
+
await this.submit(`/resume ${selected.value}`);
|
|
170988
|
+
}
|
|
170793
170989
|
async showBackgroundTasks() {
|
|
170794
170990
|
while (true) {
|
|
170795
170991
|
await this.refreshRuntimeState();
|
|
@@ -171363,6 +171559,7 @@ var ZCodeTui = class {
|
|
|
171363
171559
|
}
|
|
171364
171560
|
applyRuntimeProjection(projection) {
|
|
171365
171561
|
if (!projection) return;
|
|
171562
|
+
this.applyWorkspace(projection.workspace);
|
|
171366
171563
|
this.runtimeProjection = projection;
|
|
171367
171564
|
if (!this.settingSwitchInFlight) this.applyExecutionState(projection);
|
|
171368
171565
|
this.noticeRestoredBackgroundTasks(projection);
|
package/vendor/zcode.cjs
CHANGED
|
@@ -14916,7 +14916,7 @@ To resolve the conflict:`,(0,MEt.getConflictResolutionRecipe)(a,t))),o=i):Fii.di
|
|
|
14916
14916
|
|
|
14917
14917
|
`)||void 0}function Bhc(e){let t=new Map;for(let n of e??[]){if(n.type!==nt.SubagentSpawned&&n.type!==nt.SubagentStopped)continue;let o=dle(n.payload),i=dv(o,"parentToolCallId");if(!i)continue;let a=t.get(i)??{};if(n.type===nt.SubagentSpawned){t.set(i,{...a,agentId:dv(o,"agentId")??a.agentId,childSessionId:dv(o,"childSessionId")??a.childSessionId,description:dv(o,"description","prompt")??a.description,startedAt:n.timestamp.getTime(),subagentType:dv(o,"agentType")??a.subagentType});continue}let c=dv(o,"status");t.set(i,{...a,agentId:dv(o,"agentId")??a.agentId,childSessionId:dv(o,"childSessionId")??a.childSessionId,stoppedAt:n.timestamp.getTime(),stoppedStatus:c==="cancelled"||c==="stopped"?"cancelled":c==="failed"||c==="error"?"failed":"success",summary:dv(o,"summaryText","result","error","description")??a.summary})}return t}function Uhc(e,t){return gP(t,{branchCutAfterMessageId:e.revert?.branchCutAfterMessageID,rewindCreatedMessageId:e.revert?.createdMessageID,rewindKeptMessageIds:e.revert?.keptMessageIDs,rewindTargetMessageId:e.revert?.targetMessageID})}function zhc(e,t){if(!Nhc.has(e.tool))return null;let n=e.state.status==="completed"?cTe(e.state.output):void 0,o=Lhc(n),i=dle(e.state.input),a="metadata"in e.state?dle(e.state.metadata):{},c={...dle(e.metadata),...a},u=dv(o??{},"agentId")??Fhc(n)??dv(c,"agentId")??t?.agentId,f=dv(o??{},"childSessionId")??dv(c,"childSessionId")??t?.childSessionId??(u?Vv(`subagent_${u}`):void 0);if(!f)return null;let h=dv(o??{},"description")??dv(i,"description")??dv(c,"description")??t?.description??dv(i,"prompt")??"Subagent";return{childSessionId:f,runInBackground:i.run_in_background===!0,part:e,output:o,agentId:u??e.callID,subagentType:dv(o??{},"agentType")??dv(c,"agentType")??t?.subagentType??dv(i,"subagent_type","agent","agentType")??"subagent",title:h,summary:jhc(o?.content)??dv(o??{},"result","summary")??(e.state.status==="error"?cTe(e.state.error):void 0)??t?.summary,...t?.startedAt!==void 0?{startedAt:t.startedAt}:{},...t?.stoppedAt!==void 0?{stoppedAt:t.stoppedAt}:{},...t?.stoppedStatus?{stoppedStatus:t.stoppedStatus}:{}}}function mdi(e,t,n){let o=new Map,i=Bhc(n);for(let a of Uhc(e,t))for(let c of a.parts){if(c.type!=="tool")continue;let u=zhc(c,i.get(c.callID));u&&o.set(u.childSessionId,u)}return[...o.values()]}function ZPt(e,t,n){return mdi(e,t,n).map(o=>o.childSessionId)}function $hc(e){if(!e||e.length===0)return{};let n=e.filter(u=>u.info.role==="assistant").at(-1);if(!n||n.info.role!=="assistant")return{};if(n.info.error&&n.info.error.name===v4)return{};let o=n.parts.flatMap(u=>u.type==="text"&&u.ignored!==!0?[u.text.trim()]:[]).filter(Boolean).join(`
|
|
14918
14918
|
|
|
14919
|
-
`),i=n.info.error?.name,a=n.info.error?dv(n.info.error.data??{},"message","error","detail")??i:void 0,c=n.parts.some(u=>u.type==="tool");return{...n.info.time.completed?{endedAt:n.info.time.completed}:{},...o||a?{summary:o||a}:{},...i?{status:fdi.test(i)?"cancelled":"failed"}:!c&&(n.info.time.completed||n.info.finish)?{status:"success"}:{}}}function qhc(e,t){return e?.backgroundTasks.find(n=>n.taskKind==="subagent"&&(n.childSessionId===t.childSessionId||n.toolCallId===t.part.callID||n.taskId===t.agentId))}function Whc(e){return e.background?.status==="running"?e.background.blocked?"blocked":"running":e.childProjection?.status==="waiting"?"waiting":e.childProjection?.status==="running"||e.candidate.runInBackground&&e.background===void 0&&e.childProjection===void 0&&e.candidate.stoppedStatus===void 0&&e.childOutcome.status===void 0||e.parentProjection?.activeToolCalls.some(t=>t.toolCallId===e.candidate.part.callID&&(t.status==="pending"||t.status==="running"))||e.parentProjection&&(e.candidate.part.state.status==="pending"||e.candidate.part.state.status==="running")?"running":void 0}function Vhc(e){switch(e?.status){case"completed":return"success";case"cancelled":return"cancelled";case"failed":case"timed_out":case"spawn_error":return"failed";case"lost":return"lost";default:return}}function Hhc(e){let t=Vhc(e.background);if(t)return t;if(e.childProjection?.status==="error")return"failed";if(e.childProjection?.status==="completed")return"success";if(e.candidate.part.state.status==="error")return fdi.test(e.candidate.part.state.error)?"cancelled":"failed";if(e.candidate.stoppedStatus)return e.candidate.stoppedStatus;let n=dv(e.candidate.output??{},"status");return n==="cancelled"||n==="stopped"?"cancelled":n==="failed"||n==="error"?"failed":n==="async_launched"?e.childOutcome.status??"lost":e.candidate.part.state.status==="completed"?"success":e.childOutcome.status??"lost"}function pdi(e,t){return t?.startedAt?t.startedAt.getTime():e.startedAt!==void 0?e.startedAt:"time"in e.part.state?e.part.state.time.start:void 0}function YPt(e){let t=[],n=[];for(let o of mdi(e.parentSession,e.messages,e.parentEvents)){let i=e.childSessionsById.get(o.childSessionId);if(!i||i.taskType!=="subagent_child")continue;let a=e.childProjectionsById.get(o.childSessionId),c=qhc(e.parentProjection,o),u=$hc(e.childMessagesById.get(o.childSessionId)),f=Whc({background:c,candidate:o,childOutcome:u,childProjection:a,parentProjection:e.parentProjection}),h={childSessionId:o.childSessionId,...o.agentId?{agentId:o.agentId}:{},toolCallId:o.part.callID,subagentType:o.subagentType,title:o.title,...pdi(o,c)!==void 0?{startedAt:pdi(o,c)}:{}};if(f){t.push({...h,status:f});continue}let _="time"in o.part.state&&"end"in o.part.state.time?o.part.state.time.end:void 0;n.push({...h,status:Hhc({background:c,candidate:o,childOutcome:u,childProjection:a}),...o.summary||u.summary?{summary:o.summary??u.summary}:{},endedAt:c?.completedAt?.getTime()??o.stoppedAt??_??u.endedAt??i.time.updated})}return t.sort((o,i)=>(i.startedAt??0)-(o.startedAt??0)||i.childSessionId.localeCompare(o.childSessionId)),n.sort((o,i)=>(i.endedAt??0)-(o.endedAt??0)||i.childSessionId.localeCompare(o.childSessionId)),{revision:e.revision,running:t,ended:n}}function Ghc(e){return yBn.Buffer.from(JSON.stringify({childSessionId:e.childSessionId,endedAt:e.endedAt??0})).toString("base64url")}function Jhc(e){if(!e)return null;try{let t=dle(JSON.parse(yBn.Buffer.from(e,"base64url").toString("utf8"))),n=cTe(t.childSessionId),o=t.endedAt;return n&&typeof o=="number"?{childSessionId:n,endedAt:o}:null}catch{return null}}function XPt(e,t){let n=Jhc(t.cursor),o=n?e.findIndex(c=>(c.endedAt??0)<n.endedAt||(c.endedAt??0)===n.endedAt&&c.childSessionId.localeCompare(n.childSessionId)<0):0;if(o<0)return{items:[]};let i=e.slice(o,o+t.limit),a=i.at(-1);return{items:i,...a&&o+i.length<e.length?{nextCursor:Ghc(a)}:{}}}var yBn,Nhc,fdi,vBn=V(()=>{"use strict";yBn=require("node:buffer");Ln();Nhc=new Set(["Agent","Task","subagent"]),fdi=/abort|cancel|interrupt|stop/i;r(dle,"asRecord");r(cTe,"nonEmptyString");r(dv,"stringField");r(Lhc,"parseJsonObject");r(Fhc,"agentIdFromLaunchAcknowledgement");r(jhc,"contentBlocksToText");r(Bhc,"subagentEventRelations");r(Uhc,"activeBranchMessages");r(zhc,"candidateFromToolPart");r(mdi,"collectCandidates");r(ZPt,"collectSubagentChildSessionIds");r($hc,"lastChildOutcome");r(qhc,"findBackgroundTask");r(Whc,"runningStatus");r(Vhc,"terminalBackgroundStatus");r(Hhc,"endedStatus");r(pdi,"startedAt");r(YPt,"projectSessionSubagents");r(Ghc,"encodeCursor");r(Jhc,"decodeCursor");r(XPt,"paginateEndedSubagents")});function hdi(e){return{async readSubagents(t={}){let n=e.runtime.getSessionEventStore(),o=await e.sessionStore.getSession(e.sessionId);if(!o)return{revision:0,childSessionIds:[],running:[],ended:{total:0,items:[]}};let i=await e.sessionStore.messages({sessionID:e.sessionId}),a=await n.getEvents(e.sessionId),c=ZPt(o,i,a),f=(await Promise.all(c.map(async v=>{let S=v,k=await e.sessionStore.getSession(S);if(!k||k.parentID!==e.sessionId||k.taskType!=="subagent_child")return null;let[I,C]=await Promise.all([e.sessionStore.messages({sessionID:S}),n.getEvents(S)]);return{session:k,messages:I,projection:C.length?new M7().reduce(C):void 0}}))).filter(v=>v!==null),h=YPt({revision:await n.getLatestSequenceNumber(e.sessionId),parentSession:o,messages:i,parentEvents:a,parentProjection:await e.runtime.getProjection(),childSessionsById:new Map(f.map(v=>[v.session.id,v.session])),childMessagesById:new Map(f.map(v=>[v.session.id,v.messages])),childProjectionsById:new Map(f.flatMap(v=>v.projection?[[v.session.id,v.projection]]:[]))}),_=XPt(h.ended,{cursor:t.endedCursor,limit:Math.min(100,Math.max(1,t.endedLimit??20))});return{revision:h.revision,childSessionIds:f.map(v=>v.session.id),running:h.running,ended:{total:h.ended.length,..._}}},async readSubagentTranscript(t){let n=e.runtime.getSessionEventStore(),o=t,i=await e.sessionStore.getSession(o);if(!i||i.parentID!==e.sessionId||i.taskType!=="subagent_child")throw new Error("Subagent does not belong to the current session.");let a=await e.sessionStore.messages({sessionID:o}),c=await n.getEvents(o),u=new Set;for(let h of c){let _=h.payload;h.type===nt.ModelStreaming&&_.kind==="start"&&typeof _.assistantMessageId=="string"&&u.add(_.assistantMessageId)}let f=a.flatMap(h=>u.has(h.info.id)?[{id:h.info.id,content:"",role:"agent"}]:fBn([h]).map(_=>({..._,id:h.info.id})));return{sessionId:o,messages:f,events:c,replayMessageIds:[...u],sequenceNumber:c.at(-1)?.sequenceNumber??0}}}}var gdi=V(()=>{"use strict";Ln();mBn();vBn();r(hdi,"createSubagentObservation")});function vdi(e){let t,n=UU(e.configResult.config.ui.locale),o=[],i=r(()=>{let u=e.providerRegistry,f=pX(e);if(!f)return{owned:!1};let{providerId:h}=f;if(!u.getProvider(h))return{owned:!1};let _=KPt(u,f);return _?{owned:!0,registry:u,selection:_}:{owned:!0,registry:u}},"currentRegistrySelection"),a=r(async()=>{let u=await e.sessionStore.readTarget({sessionID:e.sessionId});return!e.runtime.getActiveTurnInfo()&&u?.activeInputId&&u.activeRunStartedAtMs!=null&&e.sessionStore.recoverInterruptedTargetRun?await e.sessionStore.recoverInterruptedTargetRun({sessionID:e.sessionId}):u},"readTargetWithInterruptedRunRecovery"),c=r(async(u,f)=>{let h=u==="set"?(f.objective??"").trim():void 0,_=u==="set"?f.displayText?.trim()||h:void 0;await e.prepareUserExecutionBoundary({traceContext:e.traceContext}),await e.runtime.ensureSessionPersistedForExternalActivity(h??`/goal ${f.status??"clear"}`,{traceContext:e.traceContext});let v=await e.sessionStore.readTarget({sessionID:e.sessionId}),S=u==="set"?await e.sessionStore.setTarget({objective:h??"",sessionID:e.sessionId,status:f.status,tokenBudget:f.tokenBudget}):u==="status_updated"?await e.sessionStore.updateTargetStatus({sessionID:e.sessionId,status:f.status??"active"}):null;if(u==="cleared"){let k=await e.sessionStore.clearTarget({sessionID:e.sessionId});return k&&await e.runtime.recordGoalStateChangeReminder({text:ydi("cleared"),traceContext:e.traceContext}),await e.runtime.recordTargetChanged({action:u,previousTarget:v,source:"command",target:S,traceContext:e.traceContext}),k}if(S){h!==void 0&&await e.runtime.recordExternalUserPrompt(_??h,{goalSummaryTargetID:S.targetID,intent:f.intent,traceContext:e.traceContext});let k=f.status==="paused"&&v?.status!=="paused"?"paused":f.status==="active"&&v?.status==="paused"?"resumed":void 0,I=ydi(k);I&&await e.runtime.recordGoalStateChangeReminder({text:I,traceContext:e.traceContext}),await e.runtime.recordTargetChanged({action:u,previousTarget:v,source:"command",target:S,traceContext:e.traceContext})}return S},"setTargetStatus");return{close:r(async()=>(t??=Promise.resolve().then(async()=>{let u=[];e.runtime.beginShutdown();let f=[["runtime_work",()=>e.runtime.closeOwnedWork()],["dynamic_workflow",e.closeDynamicWorkflowRuns],["script_workflow",e.closeScriptWorkflowRuns]],h=await bdi(f,e.logger);for(let v of h)v.status==="rejected"&&u.push(v.reason);let _=e.ownsSessionStore&&f5e(e.sessionStore)?e.sessionStore:void 0;try{await Khc({beginShutdown:r(()=>e.runtime.beginShutdown(),"beginShutdown"),closeBrowserSession:r(()=>e.runtime.closeBrowserSession(),"closeBrowserSession"),closeExecution:e.ownsExecutionPort&&e.executionPort.close?()=>e.executionPort.close?.():void 0,closeMcp:e.ownsMcpPort&&e.mcpPort?()=>e.mcpPort?.close():void 0,closeNodeReplBrowserBroker:e.closeNodeReplBrowserBroker,closeSessionStore:_?()=>_.close():void 0,logger:e.logger})}catch(v){u.push(v)}if(u.length)throw new AggregateError(u,`Session shutdown failed: ${u.map(v=>v instanceof Error?v.message:String(v)).join("; ")}`)}),await t),"close"),getMode:r(()=>e.runtime.getMode(),"getMode"),readExecutionState:r(async()=>{await e.prepareResume();return {mode:e.runtime.getMode(),planEnabled:e.runtime.getPlanEnabled()}},"readExecutionState"),setPlanEnabled:r(async $zEnabled=>{await e.prepareResume();await e.runtime.setExecutionState({planEnabled:$zEnabled},e.traceContext);return {mode:e.runtime.getMode(),planEnabled:e.runtime.getPlanEnabled()}},"setPlanEnabled"),getModel:r(()=>bBn(pX(e)),"getModel"),getLocale:r(()=>n,"getLocale"),getTheme:r(()=>e.configResult.config.ui.theme,"getTheme"),getDefaultThoughtLevel:r(()=>{let u=i();return u.owned?_Bn(u.selection):pX(e)?.options?.reasoningLevel},"getDefaultThoughtLevel"),getThoughtLevel:r(()=>pX(e)?.options?.reasoningLevel,"getThoughtLevel"),loadSessionTranscript:r(async()=>await odi({sessionId:e.sessionId,sessionStore:e.sessionStore}),"loadSessionTranscript"),loadSessionContextMessages:r(async()=>await e.sessionStore.messages({sessionID:e.sessionId}),"loadSessionContextMessages"),readSessionUsage:r(async()=>await e.sessionStore.queryTaskUsage?.({sessionID:e.sessionId})??null,"readSessionUsage"),...hdi(e),readTodos:r(async()=>e.sessionStore.readTodos({sessionID:e.sessionId}),"readTodos"),readTarget:a,setCustomSessionTitle:r(async u=>e.runtime.setCustomSessionTitle({title:u.title,traceContext:u.traceContext??e.traceContext}),"setCustomSessionTitle"),readSessionResumeTarget:r(async()=>await require(require("node:path").join(__dirname,"cli-config.cjs")).readSessionResumeTarget(e),"readSessionResumeTarget"),setTarget:r(async u=>await c("set",u),"setTarget"),updateTargetStatus:r(async u=>await c("status_updated",{status:u}),"updateTargetStatus"),clearTarget:r(async()=>await c("cleared",{}),"clearTarget"),listModels:r(()=>adi(e.providerRegistry),"listModels"),reloadModels:r(async()=>{await e.providerRegistry.refresh("cli-model-catalog");return adi(e.providerRegistry)},"reloadModels"),getCurrentModelOption:r(()=>{let u=pX(e);return u&&hBn(e.providerRegistry,u)},"getCurrentModelOption"),getModelOption:r(u=>hBn(e.providerRegistry,u),"getModelOption"),readSessionModelState:r(async()=>await require(require("node:path").join(__dirname,"cli-config.cjs")).readSessionModelState({registry:e.providerRegistry,sessionStore:e.sessionStore,sessionId:e.sessionId}),"readSessionModelState"),listThoughtLevels:r(()=>{let u=i();return u.owned?[...u.selection?.model.config.optionSpecs.reasoningLevel.values??[]]:[]},"listThoughtLevels"),listMcpServers:r(async()=>aTe(e.mcpPort,e.configuredMcpServers,e.untrustedProjectMcpServers),"listMcpServers"),connectMcpServer:r(async u=>{let f=e.configuredMcpServers[u];if(!f)throw new Error(`MCP server is not configured: ${u}`);if(!e.mcpPort)throw new Error("MCP is disabled");return e.mcpPort.connectServer(u,f,{trace:e.traceContext,workingDirectory:e.workingDirectory})},"connectMcpServer"),readMcpResource:r(async(u,f,h)=>{if(!e.mcpPort)throw new Error("MCP is disabled");if(!e.mcpPort.readResource)throw new Error("MCP resources are not supported by this runtime");return e.mcpPort.readResource({serverName:u,uri:f,trace:e.traceContext},{signal:h?.signal})},"readMcpResource"),readMcpResourceForUi:r(async(u,f,h)=>{if(!e.mcpPort)throw new Error("MCP is disabled");if(!e.mcpPort.readResource)throw new Error("MCP resources are not supported by this runtime");return e.mcpPort.readResource({serverName:u,uri:f,trace:e.traceContext},{signal:h?.signal})},"readMcpResourceForUi"),listMcpResourcesForUi:r(async(u,f,h)=>{if(!e.mcpPort)throw new Error("MCP is disabled");if(!e.mcpPort.listResources)throw new L3(u);return e.mcpPort.listResources({serverName:u,...f?{cursor:f}:{},trace:e.traceContext},{signal:h?.signal})},"listMcpResourcesForUi"),listMcpResourceTemplatesForUi:r(async(u,f,h)=>{if(!e.mcpPort)throw new Error("MCP is disabled");if(!e.mcpPort.listResourceTemplates)throw new L3(u);return e.mcpPort.listResourceTemplates({serverName:u,...f?{cursor:f}:{},trace:e.traceContext},{signal:h?.signal})},"listMcpResourceTemplatesForUi"),subscribeMcpResourceForUi:r(async(u,f,h,_)=>{if(!e.mcpPort)throw new Error("MCP is disabled");if(!e.mcpPort.subscribeResource)throw new L3(u);await e.mcpPort.subscribeResource({serverName:u,uri:f,subscriberKey:h,trace:e.traceContext},{signal:_?.signal})},"subscribeMcpResourceForUi"),unsubscribeMcpResourceForUi:r(async(u,f,h,_)=>{e.mcpPort?.unsubscribeResource&&await e.mcpPort.unsubscribeResource({serverName:u,uri:f,subscriberKey:h,trace:e.traceContext},{signal:_?.signal})},"unsubscribeMcpResourceForUi"),unsubscribeMcpResourcesForUi:r(async u=>e.mcpPort?.unsubscribeResourcesBySubscriber?e.mcpPort.unsubscribeResourcesBySubscriber(u):0,"unsubscribeMcpResourcesForUi"),onMcpAppConnectionInvalidated:r((u,f)=>e.mcpPort?.onAppConnectionInvalidated?.(u,f)??(()=>{}),"onMcpAppConnectionInvalidated"),getMcpAppConnectionSnapshot:r(u=>e.mcpPort?.appConnectionSnapshot?.(u)??null,"getMcpAppConnectionSnapshot"),waitForMcpAppConnection:r(async u=>e.mcpPort?.waitForAppConnection?e.mcpPort.waitForAppConnection(u):e.mcpPort?.appConnectionSnapshot?.(u)??null,"waitForMcpAppConnection"),callMcpToolForUi:r(async(u,f,h,_)=>{if(!e.mcpPort)throw new Error("MCP is disabled");let v=e.mcpPort.appConnectionSnapshot?.(u);if(!v)throw new Error("MCP App connection is unavailable");let S=(await e.mcpPort.listTools()).find(F=>F.serverName===u&&F.toolName===f);if(!S||!KMe(S).includes("app"))throw new Error("Tool is not available to this App");let k=e.runtime.getToolRegistry(),C=k.list().map(F=>k.get(F)).find(F=>F?.metadata.mcpPresentation?.serverName===u&&F.metadata.mcpPresentation.toolName===f)??IOn(TD(S),S,e.mcpPort,!1),R=e.runtime.getToolExecutor();if(!R.authorizeAppTool)throw new Error("MCP App host authorization is unavailable");let D=await R.authorizeAppTool({id:crypto.randomUUID(),name:C.metadata.name,input:h??{}},C,{signal:_?.signal,traceContext:e.traceContext});_?.signal?.throwIfAborted();let B=e.mcpPort.appConnectionSnapshot?.(u);if(!B||B.identity!==v.identity||B.generation!==v.generation)throw new Error("MCP App connection changed during authorization");return e.mcpPort.callTool({serverName:u,toolName:f,arguments:D,trace:e.traceContext,runtimeScope:"main"},{signal:_?.signal,appConnection:v})},"callMcpToolForUi"),replaceMcpAppProvidedTools:r((u,f)=>{let h=e.runtime.getToolRegistry();for(let v of o)h.unregister(v);let _=[];for(let v of u)h.has(v.modelName)||_.includes(v.modelName)||(h.register(wOn(v,f),{silentDuplicateWarning:!0}),_.push(v.modelName));return o=_,e.runtime.invalidateToolCache(),_},"replaceMcpAppProvidedTools"),getMcpToolVisibility:r(async(u,f)=>{if(!e.mcpPort)return null;let h=(await e.mcpPort.listTools()).find(_=>_.serverName===u&&_.toolName===f);return h?KMe(h):null},"getMcpToolVisibility"),readBackgroundBashOutput:r((u,f)=>e.runtime.readBackgroundBashOutput(u,f),"readBackgroundBashOutput"),cancelBackgroundTask:r(async(u,f)=>e.runtime.cancelBackgroundTask(u,{traceContext:f?.traceContext??e.traceContext}),"cancelBackgroundTask"),disconnectMcpServer:r(async u=>{if(e.mcpPort)return e.mcpPort.disconnectServer(u)},"disconnectMcpServer"),listCheckpoints:r(async u=>(await e.prepareResume(),e.runtime.listWorkspaceCheckpoints(u)),"listCheckpoints"),forkFromCheckpoint:r(async u=>(await e.prepareResume(u?.traceContext),e.runtime.forkWorkspaceFromCheckpoint({targetCheckpointId:u?.targetCheckpointId,targetMessageId:u?.targetMessageId,traceContext:u?.traceContext??e.traceContext})),"forkFromCheckpoint"),sampleModel:r((u,f)=>e.runtime.sampleModel(u,{...f,traceContext:f.traceContext??e.traceContext}),"sampleModel"),generateWorkspaceText:r(async(u,f)=>{let h=snt(e.providerRegistry.getView(),u.selection)??u.selection;return await e.runtime.generateWorkspaceText({...u,selection:h},{abortSignal:f?.abortSignal,traceContext:f?.traceContext??e.traceContext})},"generateWorkspaceText"),testModelConnectivity:r(async(u,f)=>{let h=cdi(e.providerRegistry,u.selection);await e.runtime.testModelConnectivity({...u,selection:h},{abortSignal:f?.abortSignal,traceContext:f?.traceContext??e.traceContext})},"testModelConnectivity"),setMode:r(async u=>{await e.prepareResume();let f=e.runtime.getMode(),h=await e.sessionStore.getSession(e.sessionId);if(h?.permission?.scope==="session"&&await e.sessionStore.updateSession({id:e.sessionId,permission:{...h.permission,mode:u}}),await e.runtime.setExecutionState({mode:u,planEnabled:e.runtime.getPlanEnabled()},e.traceContext),e.localSettingStore&&h?.permission?.scope!=="session")try{await e.localSettingStore.saveProjectPermissionMode({mode:e.runtime.getMode(),projectID:e.projectID})}catch(_){e.logger.warn("Project mode preference write failed",{...Ma(e.traceContext),error:_ instanceof Error?_.message:String(_),event:"local_setting.permission_mode.write_failed",mode:u,module:"bootstrap",projectId:e.projectID,status:"failed"})}return e.logger.info("Session mode updated",{...Ma(e.traceContext),event:"session.mode.updated",mode:u,module:"bootstrap",previousMode:f,status:"completed"}),{mode:e.runtime.getMode(),planEnabled:e.runtime.getPlanEnabled(),previousMode:f,traceId:e.traceContext.traceId}},"setMode"),setModel:r(async(u,f)=>{let h=typeof u=="string"?ldi(e.providerRegistry,u,e.configuredDefaultModelSelection,{allowMissingReasoning:!0}):ule(e.providerRegistry,u);if(!h)throw new Error(`Provider Registry \u4E2D\u4E0D\u5B58\u5728 Model: ${u}`);let _=pX(e),v=bBn(_),S=bBn(h.selection),k={providerId:h.selection.providerId,modelId:h.selection.modelId,...typeof u!="string"&&h.selection.options?{options:{...h.selection.options}}:{}};if(!k.options?.reasoningLevel){let $zSelectedModel=dss(e.providerRegistry.getView(),k);if($zSelectedModel)k={...k,options:{...k.options,...$zSelectedModel.options}}}return e.cliDefaultSelection&&(f?.cliDefault&&await e.prepareResume(),!f?.transient||f?.cliDefault)?e.cliDefaultSelection.set(k):e.runtime.setSessionModelSelection(k),f?.transient||(e.runtime.recordPendingModelChange({fromModel:_,fromModelLabel:v,toModel:k,toModelLabel:S}),await _di(e)),e.logger.info("Session model updated",{...Ma(e.traceContext),event:"session.model.updated",model:S,module:"bootstrap",previousModel:v,status:"completed"}),{model:S,previousModel:v,traceId:e.traceContext.traceId}},"setModel"),setThoughtLevel:r(async u=>{let f=i();if(f.owned){let h=pX(e);if(!h)throw new Error("Select a model before choosing reasoning effort");let _=f.selection??ule(f.registry,{providerId:h.providerId,modelId:h.modelId}),v=_Bn(_,h.options?.reasoningLevel),S=udi(_,u),k={...h,options:{...h.options,reasoningLevel:S}};return e.cliDefaultSelection?e.cliDefaultSelection.set(k):e.runtime.setSessionModelSelection(k),await _di(e),e.logger.info("Session reasoning effort updated",{...Ma(e.traceContext),event:"session.reasoning_effort.updated",module:"bootstrap",previousThoughtLevel:v,status:"completed",thoughtLevel:S}),{previousThoughtLevel:v,thoughtLevel:S,traceId:e.traceContext.traceId}}throw new Error("\u5F53\u524D Session Model \u4E0D\u5C5E\u4E8E Provider Registry")},"setThoughtLevel"),setLocale:r(async u=>{let f=n,h=idi(e.configResult),_=await Yve(h,u);return n=e.resolveUiLocale(u),e.configResult.config.ui.locale=n,e.logger.info("Session locale updated",{...Ma(e.traceContext),event:"session.locale.updated",locale:n,module:"bootstrap",previousLocale:f,requestedLocale:u,status:"completed"}),{configPath:_.path,locale:n,previousLocale:f,requestedLocale:u,traceId:e.traceContext.traceId}},"setLocale")}}async function bdi(e,t){let n=new Set(e.filter(([,i])=>i).map(([i])=>i)),o=setTimeout(()=>{n.size&&t.warn("Session resources are still closing",{event:"session.resource_close.slow",pendingResources:[...n],elapsedMs:3e4})},3e4);o.unref();try{return await Promise.allSettled(e.flatMap(([i,a])=>a?[Promise.resolve().then(a).catch(c=>{throw t.warn("Session resource close failed",{event:"session.resource_close.failed",resource:i,error:c instanceof Error?c.message:String(c)}),new Error(`${i}: ${c instanceof Error?c.message:String(c)}`,{cause:c})}).finally(()=>n.delete(i))]:[]))}finally{clearTimeout(o)}}async function Khc(e){let t=[];try{e.beginShutdown()}catch(i){t.push(i),e.logger.warn("Failed to begin runtime shutdown",{error:i instanceof Error?i.message:String(i),event:"session.shutdown_admission.failed"})}let n=[["browser_session",e.closeBrowserSession],["execution",e.closeExecution],["mcp",e.closeMcp],["node_repl_browser_broker",e.closeNodeReplBrowserBroker]];return(async()=>{let i=await bdi(n,e.logger);for(let a of i)a.status==="rejected"&&t.push(a.reason);try{e.closeSessionStore?.()}catch(a){t.push(a)}if(t.length)throw new AggregateError(t,`Session resources could not be safely released: ${t.map(a=>a instanceof Error?a.message:String(a)).join("; ")}`)})()}async function _di(e){if(!e.sessionStore.saveSessionEntry)return;let t=pX(e);if(!t)return;let n=Date.now();try{await e.sessionStore.saveSessionEntry({id:`${e.sessionId}:runtime-model-selection`,sessionID:e.sessionId,type:HC,touchSession:!1,time:{created:n,updated:n},data:{modelId:t.modelId,providerId:t.providerId,...t.options?{options:t.options}:{}}})}catch(o){let i={...Ma(e.traceContext),error:o instanceof Error?o.message:String(o),modelId:t.modelId,module:"bootstrap",providerId:t.providerId,thoughtLevel:t.options?.reasoningLevel};if(!e.runtime.isSessionPersisted()){e.logger.debug("Session model selection persistence deferred until session is persisted",{...i,event:"session.model_selection.persist_deferred",status:"waiting"});return}e.logger.warn("Session model selection persistence failed",{...i,event:"session.model_selection.persist_failed",status:"failed"})}}function bBn(e){return e?`${e.providerId}/${e.modelId}`:""}function ydi(e){switch(e){case"paused":return"The active session goal is paused. Do not continue pursuing it unless the user resumes or replaces the goal.";case"resumed":return"The session goal is active again and will be pursued.";case"cleared":return"The session goal has been cleared. Do not continue pursuing any previous goal unless the user sets a new goal.";default:return}}function pX(e){return e.cliDefaultSelection?e.cliDefaultSelection.get():e.runtime.getSessionModelSelection()}var Sdi=V(()=>{"use strict";tb();Ln();Ff();aL();aP();JPt();mBn();sdi();dX();Qxe();gdi();r(vdi,"createSessionFacade");r(bdi,"closeNamedResources");r(Khc,"closeSessionResources");r(_di,"persistSessionModelSelection");r(bBn,"formatLegacyRuntimeModelValue");r(ydi,"goalStateChangeReminderText");r(pX,"readUserModelSelection")});function wdi(e){let t=e.env??process.env,n=t[Zhc]?.trim();if(n)return{kind:"internal-cli",command:n,args:[Yhc]};let o=Zne("bfs"),i=Zne("ripgrep"),a=Zne("ugrep");return{kind:"native-binaries",findCommand:t[o.binaryEnvVar]?.trim()||"bfs",grepCommand:t[a.binaryEnvVar]?.trim()||"ugrep",rgCommand:t[i.binaryEnvVar]?.trim()||"rg"}}var Zhc,Yhc,kdi=V(()=>{"use strict";ti();Zhc="ZCODE_EMBEDDED_SEARCH_COMMAND",Yhc="__internal-search";r(wdi,"resolveDefaultEmbeddedSearchBackend")});function xdi(e){let{cliStorageRoot:t,configResult:n,options:o,persistedMode:i,builtInMcpServers:a,pluginMcpServers:c,pluginRuntimeFeatures:u,subagentOutputRootDir:f,subagentProfiles:h=[],workingDirectory:_,workspaceIdentity:v}=e,S=o.runtimeConfig?.userInstructions??{workingDirectory:_},k=Qhc(o),I=o.resume?k?.selection:o.runtimeConfig?.modelSelection??k?.selection,C=o.runtimeConfig?.titleGeneration,R=C?.modelSelection,D=C===void 0?void 0:{...C,timeoutMs:C.timeoutMs??6e4,...R?{modelSelection:R}:{}},B={...c,...o.runtimeConfig?.mcp?.servers??n.config.mcp.servers,...a},F=HPt(B,c??{}),z=new Set(F);u?.computerUse===!0&&B.node_repl&&z.add("node_repl");let $=new Set;for(let[se,xe]of Object.entries(B))xe.source?.kind==="workspace"||!xe.source&&n.sources.mcp.serverSources[se]==="project"?(B[se]={...xe,source:{kind:"workspace"}},$.add(se)):!xe.source&&n.sources.mcp.serverSources[se]==="user"&&(B[se]={...xe,source:{kind:"user"}});let q=GPt(B,new Set,z),J=o.runtimeConfig?.subagents?.builtInModelSelectionOverrides??{},ne={...o.runtimeConfig,genUiOutputRoot:(o.env??process.env)[xQt],bashTimeoutPolicy:o.runtimeConfig?.bashTimeoutPolicy??LAn(o.env??process.env),mode:o.runtimeConfig?.mode??i??n.config.permission.mode,modelSelection:I,toolAllowlist:o.runtimeConfig?.toolAllowlist,toolDisallowlist:o.runtimeConfig?.toolDisallowlist,embeddedSearchBackend:o.runtimeConfig?.embeddedSearchBackend??wdi({env:o.env}),runtimeFeatures:u,language:o.runtimeConfig?.language,titleGeneration:D,workingDirectory:_,additionalDirectories:o.additionalDirectories,userInstructions:{...S,workingDirectory:S.workingDirectory??_},skillMetadataBudget:o.runtimeConfig?.skillMetadataBudget??n.config.skills.metadataBudget,toolConcurrency:{maxConcurrency:o.runtimeConfig?.toolConcurrency?.maxConcurrency??n.config.toolConcurrency.maxConcurrency},modelAnomalyGuard:{...n.config.modelAnomalyGuard,...o.runtimeConfig?.modelAnomalyGuard},mcp:{enabled:o.runtimeConfig?.mcp?.enabled??n.config.features.mcp,servers:q,trustedOfficialCuaServerNames:[...F]},hooks:egc(o.runtimeConfig?.hooks?Xhc(o.runtimeConfig.hooks,{kind:"internal"}):n.config.hooks,e.pluginHooks),subagents:{...o.runtimeConfig?.subagents,enabled:o.runtimeConfig?.subagents?.enabled??n.config.features.subagent,outputRootDir:o.runtimeConfig?.subagents?.outputRootDir??f,builtInModelSelectionOverrides:{...e.builtInSubagentModelSelectionOverrides??{},...J},profiles:[...o.runtimeConfig?.subagents?.profiles??[],...h]},memory:{cliStorageRoot:t,enabled:o.runtimeConfig?.memory?.enabled??n.config.features.memory,...o.runtimeConfig?.memory?.extractionEnabled===void 0?{}:{extractionEnabled:o.runtimeConfig.memory.extractionEnabled},...e.storageRoot?{storageRoot:e.storageRoot}:{},use:o.runtimeConfig?.memory?.use??n.config.memory.use,workspaceIdentity:v?.trim()||void 0}};return{configuredMcpServers:B,runtimeConfig:ne,untrustedProjectMcpServers:$}}function Xhc(e,t){return{...e,events:Object.fromEntries(Object.entries(e.events).map(([n,o])=>[n,o?.map(i=>({...i,hooks:i.hooks.map(a=>({...a,source:a.source??t}))}))]))}}function Qhc(e){let t=e.providerRegistry;if(!t)return;if(e.runtimeConfig?.modelSelection){let i=e.runtimeConfig.modelSelection;if(e.resume&&!t.validateSelection(i).ok)return;let a=ule(t,i);return a?{...a,...i.options?{selectionOptions:i.options}:{}}:void 0}if(e.resume)return;let n=int({configuredDefault:e.configuredDefaultModelSelection,registry:t.getView()});if(n.source==="none")return;let o=ule(t,n.selection);return o?{...o,...n.selection.options?{selectionOptions:n.selection.options}:{}}:void 0}function egc(e,t){if(!t||Object.values(t).every(o=>!o?.length))return e;let n={...e?.events};for(let[o,i]of Object.entries(t))i.length!==0&&(n[o]=[...n[o]??[],...i]);return{enabled:!0,events:n,maxOutputBytes:e?.maxOutputBytes??32768,timeoutMs:e?.timeoutMs??6e4}}function Tdi(e,t){let n=e.memory?.cliStorageRoot?EPt(e.memory.cliStorageRoot,t,e.memory.workspaceIdentity):void 0;return{mcpEnabled:e.mcp?.enabled!==!1,memoryEnabled:e.memory?.enabled!==!1,memoryExtractionEnabled:e.memory?.extractionEnabled!==!1,memoryRoot:n,memoryUse:e.memory?.use!==!1,mcsMode:e.midConversationSystem?.mode,mode:e.mode,model:e.modelSelection?`${e.modelSelection.providerId}/${e.modelSelection.modelId}`:void 0,runtimeFeatureBrowserUse:e.runtimeFeatures?.browserUse===!0,runtimeFeatureNodeRepl:e.runtimeFeatures?.nodeRepl===!0,workingDirectory:t}}var Idi=V(()=>{"use strict";oP();aP();Ff();JPt();kdi();uz();dX();r(xdi,"resolveAppRuntimeConfig");r(Xhc,"withHookConfigSource");r(Qhc,"resolveInitialRegistrySelection");r(egc,"mergeRuntimeHooks");r(Tdi,"runtimeConfigLogContext")});function QPt(e){let t=igc(e)??ogc();return t?[{path:(0,HE.join)(t,Edi),priority:rgc,scope:"system",source:"bundled"}]:(e.logger?.warn("Bundled skill pack unavailable",{module:"bootstrap.bundled_skills",requiredPaths:[...Adi]}),[])}function Rdi(e){return Adi.filter(t=>!(0,ak.existsSync)((0,HE.join)(e,...t.split("/"))))}function ogc(){for(let e of iBn())for(let t of tgc){let n=(0,HE.resolve)(e,t);if((0,ak.existsSync)((0,HE.join)(n,Edi))&&Rdi(n).length===0)return n}}function igc(e){let t=cgc();if(!t?.isSea())return;let n=agc(t);if(!n)return;let o=(0,HE.join)(e.cliStorageRoot,S5e),i=(0,HE.join)(o,n.hash);if(SBn(i,n.hash))return i;let a=`${i}.tmp-${process.pid}-${Date.now()}`;try{(0,ak.mkdirSync)(a,{recursive:!0});for(let c of n.files){let u=Buffer.from(t.getRawAsset(`${Pdi}${c.path}`));if(lgc(u)!==c.sha256)throw new Error(`Bundled skill asset hash mismatch: ${c.path}`);let f=(0,HE.join)(a,...c.path.split("/"));(0,ak.mkdirSync)((0,HE.dirname)(f),{recursive:!0}),(0,ak.writeFileSync)(f,u,{mode:c.mode??420})}return(0,ak.writeFileSync)((0,HE.join)(a,wBn),JSON.stringify({hash:n.hash,version:1},null,2)),(0,ak.mkdirSync)(o,{recursive:!0}),(0,ak.renameSync)(a,i),i}catch(c){if((0,ak.rmSync)(a,{force:!0,recursive:!0}),SBn(i,n.hash))return i;let u=sgc(o);return e.logger?.warn("Bundled skill pack seed degraded",{error:c instanceof Error?c.message:String(c),fallbackRoot:u,module:"bootstrap.bundled_skills",targetRoot:i}),u}}function SBn(e,t){try{if(JSON.parse((0,ak.readFileSync)((0,HE.join)(e,wBn),"utf8")).hash!==t)return!1}catch{return!1}return Rdi(e).length===0}function sgc(e){let t;try{t=(0,ak.readdirSync)(e,{withFileTypes:!0})}catch{return}return t.filter(n=>n.isDirectory()&&!n.name.includes(".tmp-")).map(n=>(0,HE.join)(e,n.name)).find(n=>{try{let o=JSON.parse((0,ak.readFileSync)((0,HE.join)(n,wBn),"utf8"));return typeof o.hash=="string"&&SBn(n,o.hash)}catch{return!1}})}function agc(e){try{let t=JSON.parse(e.getAsset(ngc,"utf8"));return t.version===1&&typeof t.hash=="string"&&Array.isArray(t.files)?t:void 0}catch{return}}function cgc(){let e=process.getBuiltinModule;try{return e?.("node:sea")}catch{return}}function lgc(e){return(0,Cdi.createHash)("sha256").update(e).digest("hex")}var Cdi,ak,HE,S5e,Edi,Adi,tgc,Pdi,ngc,wBn,rgc,w5e=V(()=>{"use strict";Cdi=require("node:crypto"),ak=require("node:fs"),HE=require("node:path");Ln();y5e();S5e="bundled-skills",Edi="skills",Adi=[`skills/${q_}/SKILL.md`,`skills/${q_}/patterns.md`,`skills/${q_}/examples.md`],tgc=[`packages/${S5e}`,`../${S5e}`,`../../${S5e}`,`../../../${S5e}`],Pdi="zcode-bundled-skills/",ngc=`${Pdi}manifest.json`,wBn=".zcode-bundled-skills-seed.json",rgc=1e6;r(QPt,"resolveBundledSkillRoots");r(Rdi,"findMissingBundledSkillPackPaths");r(ogc,"resolveFilesystemBundledSkillPackRoot");r(igc,"materializeSeaBundledSkillPack");r(SBn,"isSeedComplete");r(sgc,"findUsableSeededPack");r(agc,"readSeaManifest");r(cgc,"getSeaModule");r(lgc,"hashBytes")});function eRt(e){let t=e.runtime??pgc();if(t.electronVersion)return eTn({execPath:t.execPath,logger:e.logger,npmRootCandidates:dgc(t.baseDirs),storageRoot:e.cliStorageRoot})}function dgc(e){return[...new Set(e.map(t=>(0,Ddi.join)(t,...ugc)))]}function pgc(){return{baseDirs:sBn(),electronVersion:process.versions.electron,execPath:process.execPath}}var Ddi,ugc,kBn=V(()=>{"use strict";Ddi=require("node:path");j6e();y5e();ugc=["node-runtime","npm"];r(eRt,"resolveMcpNodeFallbackProvider");r(dgc,"bundledNpmRootCandidates");r(pgc,"currentRuntime")});function Mdi(e){return e.map(t=>(0,Odi.join)(t.path,q_,fgc))}var Odi,fgc,Ndi=V(()=>{"use strict";Odi=require("node:path");w5e();fgc="SKILL.md";r(Mdi,"collectDynamicWorkflowDisabledSkillPaths")});async function mgc(e,t,n={}){let o=(0,fX.dirname)(e);await(0,fz.mkdir)(o,{recursive:!0});let i=(0,fX.resolve)(o,`.${(0,fX.basename)(e)}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`),a;try{a=await(0,fz.open)(i,"wx",384),await a.writeFile(`${JSON.stringify(t,null,2)}
|
|
14919
|
+
`),i=n.info.error?.name,a=n.info.error?dv(n.info.error.data??{},"message","error","detail")??i:void 0,c=n.parts.some(u=>u.type==="tool");return{...n.info.time.completed?{endedAt:n.info.time.completed}:{},...o||a?{summary:o||a}:{},...i?{status:fdi.test(i)?"cancelled":"failed"}:!c&&(n.info.time.completed||n.info.finish)?{status:"success"}:{}}}function qhc(e,t){return e?.backgroundTasks.find(n=>n.taskKind==="subagent"&&(n.childSessionId===t.childSessionId||n.toolCallId===t.part.callID||n.taskId===t.agentId))}function Whc(e){return e.background?.status==="running"?e.background.blocked?"blocked":"running":e.childProjection?.status==="waiting"?"waiting":e.childProjection?.status==="running"||e.candidate.runInBackground&&e.background===void 0&&e.childProjection===void 0&&e.candidate.stoppedStatus===void 0&&e.childOutcome.status===void 0||e.parentProjection?.activeToolCalls.some(t=>t.toolCallId===e.candidate.part.callID&&(t.status==="pending"||t.status==="running"))||e.parentProjection&&(e.candidate.part.state.status==="pending"||e.candidate.part.state.status==="running")?"running":void 0}function Vhc(e){switch(e?.status){case"completed":return"success";case"cancelled":return"cancelled";case"failed":case"timed_out":case"spawn_error":return"failed";case"lost":return"lost";default:return}}function Hhc(e){let t=Vhc(e.background);if(t)return t;if(e.childProjection?.status==="error")return"failed";if(e.childProjection?.status==="completed")return"success";if(e.candidate.part.state.status==="error")return fdi.test(e.candidate.part.state.error)?"cancelled":"failed";if(e.candidate.stoppedStatus)return e.candidate.stoppedStatus;let n=dv(e.candidate.output??{},"status");return n==="cancelled"||n==="stopped"?"cancelled":n==="failed"||n==="error"?"failed":n==="async_launched"?e.childOutcome.status??"lost":e.candidate.part.state.status==="completed"?"success":e.childOutcome.status??"lost"}function pdi(e,t){return t?.startedAt?t.startedAt.getTime():e.startedAt!==void 0?e.startedAt:"time"in e.part.state?e.part.state.time.start:void 0}function YPt(e){let t=[],n=[];for(let o of mdi(e.parentSession,e.messages,e.parentEvents)){let i=e.childSessionsById.get(o.childSessionId);if(!i||i.taskType!=="subagent_child")continue;let a=e.childProjectionsById.get(o.childSessionId),c=qhc(e.parentProjection,o),u=$hc(e.childMessagesById.get(o.childSessionId)),f=Whc({background:c,candidate:o,childOutcome:u,childProjection:a,parentProjection:e.parentProjection}),h={childSessionId:o.childSessionId,...o.agentId?{agentId:o.agentId}:{},toolCallId:o.part.callID,subagentType:o.subagentType,title:o.title,...pdi(o,c)!==void 0?{startedAt:pdi(o,c)}:{}};if(f){t.push({...h,status:f});continue}let _="time"in o.part.state&&"end"in o.part.state.time?o.part.state.time.end:void 0;n.push({...h,status:Hhc({background:c,candidate:o,childOutcome:u,childProjection:a}),...o.summary||u.summary?{summary:o.summary??u.summary}:{},endedAt:c?.completedAt?.getTime()??o.stoppedAt??_??u.endedAt??i.time.updated})}return t.sort((o,i)=>(i.startedAt??0)-(o.startedAt??0)||i.childSessionId.localeCompare(o.childSessionId)),n.sort((o,i)=>(i.endedAt??0)-(o.endedAt??0)||i.childSessionId.localeCompare(o.childSessionId)),{revision:e.revision,running:t,ended:n}}function Ghc(e){return yBn.Buffer.from(JSON.stringify({childSessionId:e.childSessionId,endedAt:e.endedAt??0})).toString("base64url")}function Jhc(e){if(!e)return null;try{let t=dle(JSON.parse(yBn.Buffer.from(e,"base64url").toString("utf8"))),n=cTe(t.childSessionId),o=t.endedAt;return n&&typeof o=="number"?{childSessionId:n,endedAt:o}:null}catch{return null}}function XPt(e,t){let n=Jhc(t.cursor),o=n?e.findIndex(c=>(c.endedAt??0)<n.endedAt||(c.endedAt??0)===n.endedAt&&c.childSessionId.localeCompare(n.childSessionId)<0):0;if(o<0)return{items:[]};let i=e.slice(o,o+t.limit),a=i.at(-1);return{items:i,...a&&o+i.length<e.length?{nextCursor:Ghc(a)}:{}}}var yBn,Nhc,fdi,vBn=V(()=>{"use strict";yBn=require("node:buffer");Ln();Nhc=new Set(["Agent","Task","subagent"]),fdi=/abort|cancel|interrupt|stop/i;r(dle,"asRecord");r(cTe,"nonEmptyString");r(dv,"stringField");r(Lhc,"parseJsonObject");r(Fhc,"agentIdFromLaunchAcknowledgement");r(jhc,"contentBlocksToText");r(Bhc,"subagentEventRelations");r(Uhc,"activeBranchMessages");r(zhc,"candidateFromToolPart");r(mdi,"collectCandidates");r(ZPt,"collectSubagentChildSessionIds");r($hc,"lastChildOutcome");r(qhc,"findBackgroundTask");r(Whc,"runningStatus");r(Vhc,"terminalBackgroundStatus");r(Hhc,"endedStatus");r(pdi,"startedAt");r(YPt,"projectSessionSubagents");r(Ghc,"encodeCursor");r(Jhc,"decodeCursor");r(XPt,"paginateEndedSubagents")});function hdi(e){return{async readSubagents(t={}){let n=e.runtime.getSessionEventStore(),o=await e.sessionStore.getSession(e.sessionId);if(!o)return{revision:0,childSessionIds:[],running:[],ended:{total:0,items:[]}};let i=await e.sessionStore.messages({sessionID:e.sessionId}),a=await n.getEvents(e.sessionId),c=ZPt(o,i,a),f=(await Promise.all(c.map(async v=>{let S=v,k=await e.sessionStore.getSession(S);if(!k||k.parentID!==e.sessionId||k.taskType!=="subagent_child")return null;let[I,C]=await Promise.all([e.sessionStore.messages({sessionID:S}),n.getEvents(S)]);return{session:k,messages:I,projection:C.length?new M7().reduce(C):void 0}}))).filter(v=>v!==null),h=YPt({revision:await n.getLatestSequenceNumber(e.sessionId),parentSession:o,messages:i,parentEvents:a,parentProjection:await e.runtime.getProjection(),childSessionsById:new Map(f.map(v=>[v.session.id,v.session])),childMessagesById:new Map(f.map(v=>[v.session.id,v.messages])),childProjectionsById:new Map(f.flatMap(v=>v.projection?[[v.session.id,v.projection]]:[]))}),_=XPt(h.ended,{cursor:t.endedCursor,limit:Math.min(100,Math.max(1,t.endedLimit??20))});return{revision:h.revision,childSessionIds:f.map(v=>v.session.id),running:h.running,ended:{total:h.ended.length,..._}}},async readSubagentTranscript(t){let n=e.runtime.getSessionEventStore(),o=t,i=await e.sessionStore.getSession(o);if(!i||i.parentID!==e.sessionId||i.taskType!=="subagent_child")throw new Error("Subagent does not belong to the current session.");let a=await e.sessionStore.messages({sessionID:o}),c=await n.getEvents(o),u=new Set;for(let h of c){let _=h.payload;h.type===nt.ModelStreaming&&_.kind==="start"&&typeof _.assistantMessageId=="string"&&u.add(_.assistantMessageId)}let f=a.flatMap(h=>u.has(h.info.id)?[{id:h.info.id,content:"",role:"agent"}]:fBn([h]).map(_=>({..._,id:h.info.id})));return{sessionId:o,messages:f,events:c,replayMessageIds:[...u],sequenceNumber:c.at(-1)?.sequenceNumber??0}}}}var gdi=V(()=>{"use strict";Ln();mBn();vBn();r(hdi,"createSubagentObservation")});function vdi(e){let t,n=UU(e.configResult.config.ui.locale),o=[],i=r(()=>{let u=e.providerRegistry,f=pX(e);if(!f)return{owned:!1};let{providerId:h}=f;if(!u.getProvider(h))return{owned:!1};let _=KPt(u,f);return _?{owned:!0,registry:u,selection:_}:{owned:!0,registry:u}},"currentRegistrySelection"),a=r(async()=>{let u=await e.sessionStore.readTarget({sessionID:e.sessionId});return!e.runtime.getActiveTurnInfo()&&u?.activeInputId&&u.activeRunStartedAtMs!=null&&e.sessionStore.recoverInterruptedTargetRun?await e.sessionStore.recoverInterruptedTargetRun({sessionID:e.sessionId}):u},"readTargetWithInterruptedRunRecovery"),c=r(async(u,f)=>{let h=u==="set"?(f.objective??"").trim():void 0,_=u==="set"?f.displayText?.trim()||h:void 0;await e.prepareUserExecutionBoundary({traceContext:e.traceContext}),await e.runtime.ensureSessionPersistedForExternalActivity(h??`/goal ${f.status??"clear"}`,{traceContext:e.traceContext});let v=await e.sessionStore.readTarget({sessionID:e.sessionId}),S=u==="set"?await e.sessionStore.setTarget({objective:h??"",sessionID:e.sessionId,status:f.status,tokenBudget:f.tokenBudget}):u==="status_updated"?await e.sessionStore.updateTargetStatus({sessionID:e.sessionId,status:f.status??"active"}):null;if(u==="cleared"){let k=await e.sessionStore.clearTarget({sessionID:e.sessionId});return k&&await e.runtime.recordGoalStateChangeReminder({text:ydi("cleared"),traceContext:e.traceContext}),await e.runtime.recordTargetChanged({action:u,previousTarget:v,source:"command",target:S,traceContext:e.traceContext}),k}if(S){h!==void 0&&await e.runtime.recordExternalUserPrompt(_??h,{goalSummaryTargetID:S.targetID,intent:f.intent,traceContext:e.traceContext});let k=f.status==="paused"&&v?.status!=="paused"?"paused":f.status==="active"&&v?.status==="paused"?"resumed":void 0,I=ydi(k);I&&await e.runtime.recordGoalStateChangeReminder({text:I,traceContext:e.traceContext}),await e.runtime.recordTargetChanged({action:u,previousTarget:v,source:"command",target:S,traceContext:e.traceContext})}return S},"setTargetStatus");return{close:r(async()=>(t??=Promise.resolve().then(async()=>{let u=[];e.runtime.beginShutdown();let f=[["runtime_work",()=>e.runtime.closeOwnedWork()],["dynamic_workflow",e.closeDynamicWorkflowRuns],["script_workflow",e.closeScriptWorkflowRuns]],h=await bdi(f,e.logger);for(let v of h)v.status==="rejected"&&u.push(v.reason);let _=e.ownsSessionStore&&f5e(e.sessionStore)?e.sessionStore:void 0;try{await Khc({beginShutdown:r(()=>e.runtime.beginShutdown(),"beginShutdown"),closeBrowserSession:r(()=>e.runtime.closeBrowserSession(),"closeBrowserSession"),closeExecution:e.ownsExecutionPort&&e.executionPort.close?()=>e.executionPort.close?.():void 0,closeMcp:e.ownsMcpPort&&e.mcpPort?()=>e.mcpPort?.close():void 0,closeNodeReplBrowserBroker:e.closeNodeReplBrowserBroker,closeSessionStore:_?()=>_.close():void 0,logger:e.logger})}catch(v){u.push(v)}if(u.length)throw new AggregateError(u,`Session shutdown failed: ${u.map(v=>v instanceof Error?v.message:String(v)).join("; ")}`)}),await t),"close"),getMode:r(()=>e.runtime.getMode(),"getMode"),readExecutionState:r(async()=>{await e.prepareResume();return {mode:e.runtime.getMode(),planEnabled:e.runtime.getPlanEnabled()}},"readExecutionState"),setPlanEnabled:r(async $zEnabled=>{await e.prepareResume();await e.runtime.setExecutionState({planEnabled:$zEnabled},e.traceContext);return {mode:e.runtime.getMode(),planEnabled:e.runtime.getPlanEnabled()}},"setPlanEnabled"),getModel:r(()=>bBn(pX(e)),"getModel"),getLocale:r(()=>n,"getLocale"),getTheme:r(()=>e.configResult.config.ui.theme,"getTheme"),getDefaultThoughtLevel:r(()=>{let u=i();return u.owned?_Bn(u.selection):pX(e)?.options?.reasoningLevel},"getDefaultThoughtLevel"),getThoughtLevel:r(()=>pX(e)?.options?.reasoningLevel,"getThoughtLevel"),loadSessionTranscript:r(async()=>await odi({sessionId:e.sessionId,sessionStore:e.sessionStore}),"loadSessionTranscript"),loadSessionContextMessages:r(async()=>await e.sessionStore.messages({sessionID:e.sessionId}),"loadSessionContextMessages"),readSessionUsage:r(async()=>await e.sessionStore.queryTaskUsage?.({sessionID:e.sessionId})??null,"readSessionUsage"),...hdi(e),readTodos:r(async()=>e.sessionStore.readTodos({sessionID:e.sessionId}),"readTodos"),readTarget:a,setCustomSessionTitle:r(async u=>e.runtime.setCustomSessionTitle({title:u.title,traceContext:u.traceContext??e.traceContext}),"setCustomSessionTitle"),readSessionResumeTarget:r(async()=>await require(require("node:path").join(__dirname,"cli-config.cjs")).readSessionResumeTarget(e),"readSessionResumeTarget"),readSessionDatabasePath:r(()=>require(require("node:path").join(__dirname,"cli-config.cjs")).readSessionDatabasePath(e),"readSessionDatabasePath"),listSessions:r(async()=>await require(require("node:path").join(__dirname,"cli-config.cjs")).listSessionsForPicker(e),"listSessionsForPicker"),setTarget:r(async u=>await c("set",u),"setTarget"),updateTargetStatus:r(async u=>await c("status_updated",{status:u}),"updateTargetStatus"),clearTarget:r(async()=>await c("cleared",{}),"clearTarget"),listModels:r(()=>adi(e.providerRegistry),"listModels"),reloadModels:r(async()=>{await e.providerRegistry.refresh("cli-model-catalog");return adi(e.providerRegistry)},"reloadModels"),getCurrentModelOption:r(()=>{let u=pX(e);return u&&hBn(e.providerRegistry,u)},"getCurrentModelOption"),getModelOption:r(u=>hBn(e.providerRegistry,u),"getModelOption"),readSessionModelState:r(async()=>await require(require("node:path").join(__dirname,"cli-config.cjs")).readSessionModelState({registry:e.providerRegistry,sessionStore:e.sessionStore,sessionId:e.sessionId}),"readSessionModelState"),listThoughtLevels:r(()=>{let u=i();return u.owned?[...u.selection?.model.config.optionSpecs.reasoningLevel.values??[]]:[]},"listThoughtLevels"),listMcpServers:r(async()=>aTe(e.mcpPort,e.configuredMcpServers,e.untrustedProjectMcpServers),"listMcpServers"),connectMcpServer:r(async u=>{let f=e.configuredMcpServers[u];if(!f)throw new Error(`MCP server is not configured: ${u}`);if(!e.mcpPort)throw new Error("MCP is disabled");return e.mcpPort.connectServer(u,f,{trace:e.traceContext,workingDirectory:e.workingDirectory})},"connectMcpServer"),readMcpResource:r(async(u,f,h)=>{if(!e.mcpPort)throw new Error("MCP is disabled");if(!e.mcpPort.readResource)throw new Error("MCP resources are not supported by this runtime");return e.mcpPort.readResource({serverName:u,uri:f,trace:e.traceContext},{signal:h?.signal})},"readMcpResource"),readMcpResourceForUi:r(async(u,f,h)=>{if(!e.mcpPort)throw new Error("MCP is disabled");if(!e.mcpPort.readResource)throw new Error("MCP resources are not supported by this runtime");return e.mcpPort.readResource({serverName:u,uri:f,trace:e.traceContext},{signal:h?.signal})},"readMcpResourceForUi"),listMcpResourcesForUi:r(async(u,f,h)=>{if(!e.mcpPort)throw new Error("MCP is disabled");if(!e.mcpPort.listResources)throw new L3(u);return e.mcpPort.listResources({serverName:u,...f?{cursor:f}:{},trace:e.traceContext},{signal:h?.signal})},"listMcpResourcesForUi"),listMcpResourceTemplatesForUi:r(async(u,f,h)=>{if(!e.mcpPort)throw new Error("MCP is disabled");if(!e.mcpPort.listResourceTemplates)throw new L3(u);return e.mcpPort.listResourceTemplates({serverName:u,...f?{cursor:f}:{},trace:e.traceContext},{signal:h?.signal})},"listMcpResourceTemplatesForUi"),subscribeMcpResourceForUi:r(async(u,f,h,_)=>{if(!e.mcpPort)throw new Error("MCP is disabled");if(!e.mcpPort.subscribeResource)throw new L3(u);await e.mcpPort.subscribeResource({serverName:u,uri:f,subscriberKey:h,trace:e.traceContext},{signal:_?.signal})},"subscribeMcpResourceForUi"),unsubscribeMcpResourceForUi:r(async(u,f,h,_)=>{e.mcpPort?.unsubscribeResource&&await e.mcpPort.unsubscribeResource({serverName:u,uri:f,subscriberKey:h,trace:e.traceContext},{signal:_?.signal})},"unsubscribeMcpResourceForUi"),unsubscribeMcpResourcesForUi:r(async u=>e.mcpPort?.unsubscribeResourcesBySubscriber?e.mcpPort.unsubscribeResourcesBySubscriber(u):0,"unsubscribeMcpResourcesForUi"),onMcpAppConnectionInvalidated:r((u,f)=>e.mcpPort?.onAppConnectionInvalidated?.(u,f)??(()=>{}),"onMcpAppConnectionInvalidated"),getMcpAppConnectionSnapshot:r(u=>e.mcpPort?.appConnectionSnapshot?.(u)??null,"getMcpAppConnectionSnapshot"),waitForMcpAppConnection:r(async u=>e.mcpPort?.waitForAppConnection?e.mcpPort.waitForAppConnection(u):e.mcpPort?.appConnectionSnapshot?.(u)??null,"waitForMcpAppConnection"),callMcpToolForUi:r(async(u,f,h,_)=>{if(!e.mcpPort)throw new Error("MCP is disabled");let v=e.mcpPort.appConnectionSnapshot?.(u);if(!v)throw new Error("MCP App connection is unavailable");let S=(await e.mcpPort.listTools()).find(F=>F.serverName===u&&F.toolName===f);if(!S||!KMe(S).includes("app"))throw new Error("Tool is not available to this App");let k=e.runtime.getToolRegistry(),C=k.list().map(F=>k.get(F)).find(F=>F?.metadata.mcpPresentation?.serverName===u&&F.metadata.mcpPresentation.toolName===f)??IOn(TD(S),S,e.mcpPort,!1),R=e.runtime.getToolExecutor();if(!R.authorizeAppTool)throw new Error("MCP App host authorization is unavailable");let D=await R.authorizeAppTool({id:crypto.randomUUID(),name:C.metadata.name,input:h??{}},C,{signal:_?.signal,traceContext:e.traceContext});_?.signal?.throwIfAborted();let B=e.mcpPort.appConnectionSnapshot?.(u);if(!B||B.identity!==v.identity||B.generation!==v.generation)throw new Error("MCP App connection changed during authorization");return e.mcpPort.callTool({serverName:u,toolName:f,arguments:D,trace:e.traceContext,runtimeScope:"main"},{signal:_?.signal,appConnection:v})},"callMcpToolForUi"),replaceMcpAppProvidedTools:r((u,f)=>{let h=e.runtime.getToolRegistry();for(let v of o)h.unregister(v);let _=[];for(let v of u)h.has(v.modelName)||_.includes(v.modelName)||(h.register(wOn(v,f),{silentDuplicateWarning:!0}),_.push(v.modelName));return o=_,e.runtime.invalidateToolCache(),_},"replaceMcpAppProvidedTools"),getMcpToolVisibility:r(async(u,f)=>{if(!e.mcpPort)return null;let h=(await e.mcpPort.listTools()).find(_=>_.serverName===u&&_.toolName===f);return h?KMe(h):null},"getMcpToolVisibility"),readBackgroundBashOutput:r((u,f)=>e.runtime.readBackgroundBashOutput(u,f),"readBackgroundBashOutput"),cancelBackgroundTask:r(async(u,f)=>e.runtime.cancelBackgroundTask(u,{traceContext:f?.traceContext??e.traceContext}),"cancelBackgroundTask"),disconnectMcpServer:r(async u=>{if(e.mcpPort)return e.mcpPort.disconnectServer(u)},"disconnectMcpServer"),listCheckpoints:r(async u=>(await e.prepareResume(),e.runtime.listWorkspaceCheckpoints(u)),"listCheckpoints"),forkFromCheckpoint:r(async u=>(await e.prepareResume(u?.traceContext),e.runtime.forkWorkspaceFromCheckpoint({targetCheckpointId:u?.targetCheckpointId,targetMessageId:u?.targetMessageId,traceContext:u?.traceContext??e.traceContext})),"forkFromCheckpoint"),sampleModel:r((u,f)=>e.runtime.sampleModel(u,{...f,traceContext:f.traceContext??e.traceContext}),"sampleModel"),generateWorkspaceText:r(async(u,f)=>{let h=snt(e.providerRegistry.getView(),u.selection)??u.selection;return await e.runtime.generateWorkspaceText({...u,selection:h},{abortSignal:f?.abortSignal,traceContext:f?.traceContext??e.traceContext})},"generateWorkspaceText"),testModelConnectivity:r(async(u,f)=>{let h=cdi(e.providerRegistry,u.selection);await e.runtime.testModelConnectivity({...u,selection:h},{abortSignal:f?.abortSignal,traceContext:f?.traceContext??e.traceContext})},"testModelConnectivity"),setMode:r(async u=>{await e.prepareResume();let f=e.runtime.getMode(),h=await e.sessionStore.getSession(e.sessionId);if(h?.permission?.scope==="session"&&await e.sessionStore.updateSession({id:e.sessionId,permission:{...h.permission,mode:u}}),await e.runtime.setExecutionState({mode:u,planEnabled:e.runtime.getPlanEnabled()},e.traceContext),e.localSettingStore&&h?.permission?.scope!=="session")try{await e.localSettingStore.saveProjectPermissionMode({mode:e.runtime.getMode(),projectID:e.projectID})}catch(_){e.logger.warn("Project mode preference write failed",{...Ma(e.traceContext),error:_ instanceof Error?_.message:String(_),event:"local_setting.permission_mode.write_failed",mode:u,module:"bootstrap",projectId:e.projectID,status:"failed"})}return e.logger.info("Session mode updated",{...Ma(e.traceContext),event:"session.mode.updated",mode:u,module:"bootstrap",previousMode:f,status:"completed"}),{mode:e.runtime.getMode(),planEnabled:e.runtime.getPlanEnabled(),previousMode:f,traceId:e.traceContext.traceId}},"setMode"),setModel:r(async(u,f)=>{let h=typeof u=="string"?ldi(e.providerRegistry,u,e.configuredDefaultModelSelection,{allowMissingReasoning:!0}):ule(e.providerRegistry,u);if(!h)throw new Error(`Provider Registry \u4E2D\u4E0D\u5B58\u5728 Model: ${u}`);let _=pX(e),v=bBn(_),S=bBn(h.selection),k={providerId:h.selection.providerId,modelId:h.selection.modelId,...typeof u!="string"&&h.selection.options?{options:{...h.selection.options}}:{}};if(!k.options?.reasoningLevel){let $zSelectedModel=dss(e.providerRegistry.getView(),k);if($zSelectedModel)k={...k,options:{...k.options,...$zSelectedModel.options}}}return e.cliDefaultSelection&&(f?.cliDefault&&await e.prepareResume(),!f?.transient||f?.cliDefault)?e.cliDefaultSelection.set(k):e.runtime.setSessionModelSelection(k),f?.transient||(e.runtime.recordPendingModelChange({fromModel:_,fromModelLabel:v,toModel:k,toModelLabel:S}),await _di(e)),e.logger.info("Session model updated",{...Ma(e.traceContext),event:"session.model.updated",model:S,module:"bootstrap",previousModel:v,status:"completed"}),{model:S,previousModel:v,traceId:e.traceContext.traceId}},"setModel"),setThoughtLevel:r(async u=>{let f=i();if(f.owned){let h=pX(e);if(!h)throw new Error("Select a model before choosing reasoning effort");let _=f.selection??ule(f.registry,{providerId:h.providerId,modelId:h.modelId}),v=_Bn(_,h.options?.reasoningLevel),S=udi(_,u),k={...h,options:{...h.options,reasoningLevel:S}};return e.cliDefaultSelection?e.cliDefaultSelection.set(k):e.runtime.setSessionModelSelection(k),await _di(e),e.logger.info("Session reasoning effort updated",{...Ma(e.traceContext),event:"session.reasoning_effort.updated",module:"bootstrap",previousThoughtLevel:v,status:"completed",thoughtLevel:S}),{previousThoughtLevel:v,thoughtLevel:S,traceId:e.traceContext.traceId}}throw new Error("\u5F53\u524D Session Model \u4E0D\u5C5E\u4E8E Provider Registry")},"setThoughtLevel"),setLocale:r(async u=>{let f=n,h=idi(e.configResult),_=await Yve(h,u);return n=e.resolveUiLocale(u),e.configResult.config.ui.locale=n,e.logger.info("Session locale updated",{...Ma(e.traceContext),event:"session.locale.updated",locale:n,module:"bootstrap",previousLocale:f,requestedLocale:u,status:"completed"}),{configPath:_.path,locale:n,previousLocale:f,requestedLocale:u,traceId:e.traceContext.traceId}},"setLocale")}}async function bdi(e,t){let n=new Set(e.filter(([,i])=>i).map(([i])=>i)),o=setTimeout(()=>{n.size&&t.warn("Session resources are still closing",{event:"session.resource_close.slow",pendingResources:[...n],elapsedMs:3e4})},3e4);o.unref();try{return await Promise.allSettled(e.flatMap(([i,a])=>a?[Promise.resolve().then(a).catch(c=>{throw t.warn("Session resource close failed",{event:"session.resource_close.failed",resource:i,error:c instanceof Error?c.message:String(c)}),new Error(`${i}: ${c instanceof Error?c.message:String(c)}`,{cause:c})}).finally(()=>n.delete(i))]:[]))}finally{clearTimeout(o)}}async function Khc(e){let t=[];try{e.beginShutdown()}catch(i){t.push(i),e.logger.warn("Failed to begin runtime shutdown",{error:i instanceof Error?i.message:String(i),event:"session.shutdown_admission.failed"})}let n=[["browser_session",e.closeBrowserSession],["execution",e.closeExecution],["mcp",e.closeMcp],["node_repl_browser_broker",e.closeNodeReplBrowserBroker]];return(async()=>{let i=await bdi(n,e.logger);for(let a of i)a.status==="rejected"&&t.push(a.reason);try{e.closeSessionStore?.()}catch(a){t.push(a)}if(t.length)throw new AggregateError(t,`Session resources could not be safely released: ${t.map(a=>a instanceof Error?a.message:String(a)).join("; ")}`)})()}async function _di(e){if(!e.sessionStore.saveSessionEntry)return;let t=pX(e);if(!t)return;let n=Date.now();try{await e.sessionStore.saveSessionEntry({id:`${e.sessionId}:runtime-model-selection`,sessionID:e.sessionId,type:HC,touchSession:!1,time:{created:n,updated:n},data:{modelId:t.modelId,providerId:t.providerId,...t.options?{options:t.options}:{}}})}catch(o){let i={...Ma(e.traceContext),error:o instanceof Error?o.message:String(o),modelId:t.modelId,module:"bootstrap",providerId:t.providerId,thoughtLevel:t.options?.reasoningLevel};if(!e.runtime.isSessionPersisted()){e.logger.debug("Session model selection persistence deferred until session is persisted",{...i,event:"session.model_selection.persist_deferred",status:"waiting"});return}e.logger.warn("Session model selection persistence failed",{...i,event:"session.model_selection.persist_failed",status:"failed"})}}function bBn(e){return e?`${e.providerId}/${e.modelId}`:""}function ydi(e){switch(e){case"paused":return"The active session goal is paused. Do not continue pursuing it unless the user resumes or replaces the goal.";case"resumed":return"The session goal is active again and will be pursued.";case"cleared":return"The session goal has been cleared. Do not continue pursuing any previous goal unless the user sets a new goal.";default:return}}function pX(e){return e.cliDefaultSelection?e.cliDefaultSelection.get():e.runtime.getSessionModelSelection()}var Sdi=V(()=>{"use strict";tb();Ln();Ff();aL();aP();JPt();mBn();sdi();dX();Qxe();gdi();r(vdi,"createSessionFacade");r(bdi,"closeNamedResources");r(Khc,"closeSessionResources");r(_di,"persistSessionModelSelection");r(bBn,"formatLegacyRuntimeModelValue");r(ydi,"goalStateChangeReminderText");r(pX,"readUserModelSelection")});function wdi(e){let t=e.env??process.env,n=t[Zhc]?.trim();if(n)return{kind:"internal-cli",command:n,args:[Yhc]};let o=Zne("bfs"),i=Zne("ripgrep"),a=Zne("ugrep");return{kind:"native-binaries",findCommand:t[o.binaryEnvVar]?.trim()||"bfs",grepCommand:t[a.binaryEnvVar]?.trim()||"ugrep",rgCommand:t[i.binaryEnvVar]?.trim()||"rg"}}var Zhc,Yhc,kdi=V(()=>{"use strict";ti();Zhc="ZCODE_EMBEDDED_SEARCH_COMMAND",Yhc="__internal-search";r(wdi,"resolveDefaultEmbeddedSearchBackend")});function xdi(e){let{cliStorageRoot:t,configResult:n,options:o,persistedMode:i,builtInMcpServers:a,pluginMcpServers:c,pluginRuntimeFeatures:u,subagentOutputRootDir:f,subagentProfiles:h=[],workingDirectory:_,workspaceIdentity:v}=e,S=o.runtimeConfig?.userInstructions??{workingDirectory:_},k=Qhc(o),I=o.resume?k?.selection:o.runtimeConfig?.modelSelection??k?.selection,C=o.runtimeConfig?.titleGeneration,R=C?.modelSelection,D=C===void 0?void 0:{...C,timeoutMs:C.timeoutMs??6e4,...R?{modelSelection:R}:{}},B={...c,...o.runtimeConfig?.mcp?.servers??n.config.mcp.servers,...a},F=HPt(B,c??{}),z=new Set(F);u?.computerUse===!0&&B.node_repl&&z.add("node_repl");let $=new Set;for(let[se,xe]of Object.entries(B))xe.source?.kind==="workspace"||!xe.source&&n.sources.mcp.serverSources[se]==="project"?(B[se]={...xe,source:{kind:"workspace"}},$.add(se)):!xe.source&&n.sources.mcp.serverSources[se]==="user"&&(B[se]={...xe,source:{kind:"user"}});let q=GPt(B,new Set,z),J=o.runtimeConfig?.subagents?.builtInModelSelectionOverrides??{},ne={...o.runtimeConfig,genUiOutputRoot:(o.env??process.env)[xQt],bashTimeoutPolicy:o.runtimeConfig?.bashTimeoutPolicy??LAn(o.env??process.env),mode:o.runtimeConfig?.mode??i??n.config.permission.mode,modelSelection:I,toolAllowlist:o.runtimeConfig?.toolAllowlist,toolDisallowlist:o.runtimeConfig?.toolDisallowlist,embeddedSearchBackend:o.runtimeConfig?.embeddedSearchBackend??wdi({env:o.env}),runtimeFeatures:u,language:o.runtimeConfig?.language,titleGeneration:D,workingDirectory:_,additionalDirectories:o.additionalDirectories,userInstructions:{...S,workingDirectory:S.workingDirectory??_},skillMetadataBudget:o.runtimeConfig?.skillMetadataBudget??n.config.skills.metadataBudget,toolConcurrency:{maxConcurrency:o.runtimeConfig?.toolConcurrency?.maxConcurrency??n.config.toolConcurrency.maxConcurrency},modelAnomalyGuard:{...n.config.modelAnomalyGuard,...o.runtimeConfig?.modelAnomalyGuard},mcp:{enabled:o.runtimeConfig?.mcp?.enabled??n.config.features.mcp,servers:q,trustedOfficialCuaServerNames:[...F]},hooks:egc(o.runtimeConfig?.hooks?Xhc(o.runtimeConfig.hooks,{kind:"internal"}):n.config.hooks,e.pluginHooks),subagents:{...o.runtimeConfig?.subagents,enabled:o.runtimeConfig?.subagents?.enabled??n.config.features.subagent,outputRootDir:o.runtimeConfig?.subagents?.outputRootDir??f,builtInModelSelectionOverrides:{...e.builtInSubagentModelSelectionOverrides??{},...J},profiles:[...o.runtimeConfig?.subagents?.profiles??[],...h]},memory:{cliStorageRoot:t,enabled:o.runtimeConfig?.memory?.enabled??n.config.features.memory,...o.runtimeConfig?.memory?.extractionEnabled===void 0?{}:{extractionEnabled:o.runtimeConfig.memory.extractionEnabled},...e.storageRoot?{storageRoot:e.storageRoot}:{},use:o.runtimeConfig?.memory?.use??n.config.memory.use,workspaceIdentity:v?.trim()||void 0}};return{configuredMcpServers:B,runtimeConfig:ne,untrustedProjectMcpServers:$}}function Xhc(e,t){return{...e,events:Object.fromEntries(Object.entries(e.events).map(([n,o])=>[n,o?.map(i=>({...i,hooks:i.hooks.map(a=>({...a,source:a.source??t}))}))]))}}function Qhc(e){let t=e.providerRegistry;if(!t)return;if(e.runtimeConfig?.modelSelection){let i=e.runtimeConfig.modelSelection;if(e.resume&&!t.validateSelection(i).ok)return;let a=ule(t,i);return a?{...a,...i.options?{selectionOptions:i.options}:{}}:void 0}if(e.resume)return;let n=int({configuredDefault:e.configuredDefaultModelSelection,registry:t.getView()});if(n.source==="none")return;let o=ule(t,n.selection);return o?{...o,...n.selection.options?{selectionOptions:n.selection.options}:{}}:void 0}function egc(e,t){if(!t||Object.values(t).every(o=>!o?.length))return e;let n={...e?.events};for(let[o,i]of Object.entries(t))i.length!==0&&(n[o]=[...n[o]??[],...i]);return{enabled:!0,events:n,maxOutputBytes:e?.maxOutputBytes??32768,timeoutMs:e?.timeoutMs??6e4}}function Tdi(e,t){let n=e.memory?.cliStorageRoot?EPt(e.memory.cliStorageRoot,t,e.memory.workspaceIdentity):void 0;return{mcpEnabled:e.mcp?.enabled!==!1,memoryEnabled:e.memory?.enabled!==!1,memoryExtractionEnabled:e.memory?.extractionEnabled!==!1,memoryRoot:n,memoryUse:e.memory?.use!==!1,mcsMode:e.midConversationSystem?.mode,mode:e.mode,model:e.modelSelection?`${e.modelSelection.providerId}/${e.modelSelection.modelId}`:void 0,runtimeFeatureBrowserUse:e.runtimeFeatures?.browserUse===!0,runtimeFeatureNodeRepl:e.runtimeFeatures?.nodeRepl===!0,workingDirectory:t}}var Idi=V(()=>{"use strict";oP();aP();Ff();JPt();kdi();uz();dX();r(xdi,"resolveAppRuntimeConfig");r(Xhc,"withHookConfigSource");r(Qhc,"resolveInitialRegistrySelection");r(egc,"mergeRuntimeHooks");r(Tdi,"runtimeConfigLogContext")});function QPt(e){let t=igc(e)??ogc();return t?[{path:(0,HE.join)(t,Edi),priority:rgc,scope:"system",source:"bundled"}]:(e.logger?.warn("Bundled skill pack unavailable",{module:"bootstrap.bundled_skills",requiredPaths:[...Adi]}),[])}function Rdi(e){return Adi.filter(t=>!(0,ak.existsSync)((0,HE.join)(e,...t.split("/"))))}function ogc(){for(let e of iBn())for(let t of tgc){let n=(0,HE.resolve)(e,t);if((0,ak.existsSync)((0,HE.join)(n,Edi))&&Rdi(n).length===0)return n}}function igc(e){let t=cgc();if(!t?.isSea())return;let n=agc(t);if(!n)return;let o=(0,HE.join)(e.cliStorageRoot,S5e),i=(0,HE.join)(o,n.hash);if(SBn(i,n.hash))return i;let a=`${i}.tmp-${process.pid}-${Date.now()}`;try{(0,ak.mkdirSync)(a,{recursive:!0});for(let c of n.files){let u=Buffer.from(t.getRawAsset(`${Pdi}${c.path}`));if(lgc(u)!==c.sha256)throw new Error(`Bundled skill asset hash mismatch: ${c.path}`);let f=(0,HE.join)(a,...c.path.split("/"));(0,ak.mkdirSync)((0,HE.dirname)(f),{recursive:!0}),(0,ak.writeFileSync)(f,u,{mode:c.mode??420})}return(0,ak.writeFileSync)((0,HE.join)(a,wBn),JSON.stringify({hash:n.hash,version:1},null,2)),(0,ak.mkdirSync)(o,{recursive:!0}),(0,ak.renameSync)(a,i),i}catch(c){if((0,ak.rmSync)(a,{force:!0,recursive:!0}),SBn(i,n.hash))return i;let u=sgc(o);return e.logger?.warn("Bundled skill pack seed degraded",{error:c instanceof Error?c.message:String(c),fallbackRoot:u,module:"bootstrap.bundled_skills",targetRoot:i}),u}}function SBn(e,t){try{if(JSON.parse((0,ak.readFileSync)((0,HE.join)(e,wBn),"utf8")).hash!==t)return!1}catch{return!1}return Rdi(e).length===0}function sgc(e){let t;try{t=(0,ak.readdirSync)(e,{withFileTypes:!0})}catch{return}return t.filter(n=>n.isDirectory()&&!n.name.includes(".tmp-")).map(n=>(0,HE.join)(e,n.name)).find(n=>{try{let o=JSON.parse((0,ak.readFileSync)((0,HE.join)(n,wBn),"utf8"));return typeof o.hash=="string"&&SBn(n,o.hash)}catch{return!1}})}function agc(e){try{let t=JSON.parse(e.getAsset(ngc,"utf8"));return t.version===1&&typeof t.hash=="string"&&Array.isArray(t.files)?t:void 0}catch{return}}function cgc(){let e=process.getBuiltinModule;try{return e?.("node:sea")}catch{return}}function lgc(e){return(0,Cdi.createHash)("sha256").update(e).digest("hex")}var Cdi,ak,HE,S5e,Edi,Adi,tgc,Pdi,ngc,wBn,rgc,w5e=V(()=>{"use strict";Cdi=require("node:crypto"),ak=require("node:fs"),HE=require("node:path");Ln();y5e();S5e="bundled-skills",Edi="skills",Adi=[`skills/${q_}/SKILL.md`,`skills/${q_}/patterns.md`,`skills/${q_}/examples.md`],tgc=[`packages/${S5e}`,`../${S5e}`,`../../${S5e}`,`../../../${S5e}`],Pdi="zcode-bundled-skills/",ngc=`${Pdi}manifest.json`,wBn=".zcode-bundled-skills-seed.json",rgc=1e6;r(QPt,"resolveBundledSkillRoots");r(Rdi,"findMissingBundledSkillPackPaths");r(ogc,"resolveFilesystemBundledSkillPackRoot");r(igc,"materializeSeaBundledSkillPack");r(SBn,"isSeedComplete");r(sgc,"findUsableSeededPack");r(agc,"readSeaManifest");r(cgc,"getSeaModule");r(lgc,"hashBytes")});function eRt(e){let t=e.runtime??pgc();if(t.electronVersion)return eTn({execPath:t.execPath,logger:e.logger,npmRootCandidates:dgc(t.baseDirs),storageRoot:e.cliStorageRoot})}function dgc(e){return[...new Set(e.map(t=>(0,Ddi.join)(t,...ugc)))]}function pgc(){return{baseDirs:sBn(),electronVersion:process.versions.electron,execPath:process.execPath}}var Ddi,ugc,kBn=V(()=>{"use strict";Ddi=require("node:path");j6e();y5e();ugc=["node-runtime","npm"];r(eRt,"resolveMcpNodeFallbackProvider");r(dgc,"bundledNpmRootCandidates");r(pgc,"currentRuntime")});function Mdi(e){return e.map(t=>(0,Odi.join)(t.path,q_,fgc))}var Odi,fgc,Ndi=V(()=>{"use strict";Odi=require("node:path");w5e();fgc="SKILL.md";r(Mdi,"collectDynamicWorkflowDisabledSkillPaths")});async function mgc(e,t,n={}){let o=(0,fX.dirname)(e);await(0,fz.mkdir)(o,{recursive:!0});let i=(0,fX.resolve)(o,`.${(0,fX.basename)(e)}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`),a;try{a=await(0,fz.open)(i,"wx",384),await a.writeFile(`${JSON.stringify(t,null,2)}
|
|
14920
14920
|
`,"utf8"),await a.sync(),await a.close(),a=void 0,await n.beforeRename?.(),await(0,fz.rename)(i,e)}catch(c){throw await a?.close().catch(()=>{}),await(0,fz.rm)(i,{force:!0}).catch(()=>{}),c}}async function Ldi(e){let t=(0,fX.resolve)(e.configPath),n=e.snapshot.hooks.find(k=>k.reviewItemId===e.reviewItemId),o=n?e.snapshot.sourceFiles[n.sourceFileIndex]:void 0;if(!n||!n.editable||!o?.editable||o.configFileKind!==".zcode/config.json"||(0,fX.resolve)(o.canonicalPath)!==t)throw pz("Workspace Hook toggle target is not the current editable project config");let i;try{i=JSON.parse(await(0,fz.readFile)(t,"utf8"))}catch(k){throw new r6("workspace_hooks_config_unreadable","Workspace Hook config could not be read",{cause:k})}if(!k5e(i))throw pz("Workspace Hook config root is not an object");let a=hse.safeParse(i.hooks);if(!a.success)throw pz("Workspace Hook config no longer matches its schema");let c=i.hooks;if(!k5e(c))throw pz("Workspace Hook config has no hooks object");let u=c.events;if(!k5e(u))throw pz("Workspace Hook config has no events object");let f=u[n.event];if(!Array.isArray(f))throw pz("Workspace Hook event no longer exists");let h=f[n.matcherIndex];if(!k5e(h)||!Array.isArray(h.hooks))throw pz("Workspace Hook matcher no longer exists");let _=h.hooks[n.hookIndex];if(!k5e(_))throw pz("Workspace Hook declaration no longer exists");let v=hgc(a.data.events?.[n.event]?.[n.matcherIndex]?.hooks[n.hookIndex]);if(!v)throw pz("Workspace Hook declaration no longer matches its schema");if(dSn({sourceRelativePath:n.sourceRelativePath,sourceDiscoveryOrder:o.discoveryOrder,event:n.event,matcher:a.data.events?.[n.event]?.[n.matcherIndex]?.matcher??null,matcherIndex:n.matcherIndex,hookIndex:n.hookIndex,hook:v,defaultTimeoutMs:n.resolvedTimeoutMs,resolvedMaxOutputBytes:n.resolvedMaxOutputBytes})!==n.hookDeclarationDigest)throw pz("Workspace Hook declaration changed after review");_.enabled=e.enabled,await mgc(t,i,e.writeOptions)}function hgc(e){if(!(!e||typeof e!="object"))return e}function pz(e){return new r6("workspace_hooks_snapshot_mismatch",e)}function k5e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var fz,fX,r6,xBn=V(()=>{fz=require("node:fs/promises"),fX=require("node:path");pSn();Gmt();r6=class extends Error{constructor(n,o,i){super(o,i);this.code=n;this.name="WorkspaceHookMutationError"}static{r(this,"WorkspaceHookMutationError")}};r(mgc,"atomicWriteWorkspaceHookConfig");r(Ldi,"writeWorkspaceHookConfiguredToggle");r(hgc,"getParsedDeclaration");r(pz,"mismatch");r(k5e,"isRecord")});function Fdi(e){let t=e.now(),n=new Map(e.evaluation.items.map(i=>[i.reviewItemId,i.trustState])),o=e.snapshot.hooks.map(i=>({reviewItemId:i.reviewItemId,event:i.event,...i.matcher?{matcher:i.matcher}:{},type:i.type,displayName:i.matcher?`${i.event} \xB7 ${i.matcher}`:i.event,displayCommand:i.type==="process"?[i.command,...i.args??[]].join(" "):i.command,sourcePath:i.sourceRelativePath,resolvedTimeoutMs:i.resolvedTimeoutMs,resolvedMaxOutputBytes:i.resolvedMaxOutputBytes,executionMode:i.type==="command"&&i.async?"background":"foreground",configuredEnabled:i.configuredEnabled,editable:i.editable,trustState:n.get(i.reviewItemId)??"blocked_untrusted"}));return{kind:"workspaceHookReview",reviewFlowId:e.reviewFlowId,generation:e.generation,interactionId:`workspace-hook-interaction:${e.createId()}`,sessionId:e.sessionId,taskId:e.host.taskId,runId:e.host.runId,workspaceIdentity:e.snapshot.workspaceIdentity,workspaceLabel:e.host.workspaceLabel,...e.host.remoteSessionId?{remoteSessionId:e.host.remoteSessionId}:{},bundleDigest:e.snapshot.bundleDigest,createdAt:t,deadlineAt:t+bMr,sourceFiles:e.snapshot.sourceFiles.map(i=>({path:i.canonicalPath,displayPath:(0,tRt.relative)(i.baseDir,i.canonicalPath)||(0,tRt.basename)(i.canonicalPath),editable:i.editable})),summary:{eventCount:new Set(o.map(i=>i.event)).size,hookCount:o.length,pendingCount:o.filter(i=>["pending_trust","revoked","stale_digest"].includes(i.trustState)).length},items:o,warningCode:"workspace_hooks_execute_code"}}function jdi(e,t){let n=new Map(e.hooks.map(o=>[o.reviewItemId,o]));return[...new Set(t)].map(o=>{let i=n.get(o);if(!i)throw new Error(`Unknown Workspace Hook review item: ${o}`);return i.hookDeclarationDigest})}function TBn(e){return{sessionId:e.sessionId,taskId:e.taskId,runId:e.runId,...e.remoteSessionId?{remoteSessionId:e.remoteSessionId}:{},workspaceIdentity:e.workspaceIdentity,bundleDigest:e.bundleDigest,reviewFlowId:e.reviewFlowId,generation:e.generation,interactionId:e.interactionId}}var tRt,Bdi=V(()=>{"use strict";tRt=require("node:path");Ln();r(Fdi,"buildWorkspaceHookReviewRequest");r(jdi,"resolveWorkspaceHookReviewDigests");r(TBn,"toWorkspaceHookReviewTarget")});var nRt,Udi=V(()=>{"use strict";Ff();nRt=class{static{r(this,"WorkspaceHookReviewTelemetry")}admission;logger;constructor(t,n){this.admission=t,this.logger=n}requestCreated(t){this.emit("workspace_hook.review_request_created",{bundleDigest:t.bundleDigest,generation:t.generation,requestItemCount:t.items.length,requestEnabledCount:t.items.filter(n=>n.configuredEnabled).length})}timeout(t){this.emit("workspace_hook.review_timeout",{bundleDigest:t.bundleDigest,generation:t.generation,reasonCode:"workspace_hooks_interaction_timeout"})}responseRejected(t,n){this.emit(n==="workspace_hooks_review_superseded"?"workspace_hook.stale_response":"workspace_hook.snapshot_mismatch",{bundleDigest:t.bundleDigest,reasonCode:n})}decisionAccepted(t,n,o){this.emit("workspace_hook.trust_selected",{action:n.action,bundleDigest:t.bundleDigest,generation:t.generation,...o?.grantedRecordCount===void 0?{}:{grantedRecordCount:o.grantedRecordCount},...o?.requestEnabledCount===void 0?{}:{requestEnabledCount:o.requestEnabledCount}})}revoked(t,n){this.emit("workspace_hook.revoked",{bundleDigest:t,reasonCode:"workspace_hooks_revoked",revokedCount:n})}trustStoreFailure(t,n){this.emit("workspace_hook.trust_store_failure",{bundleDigest:t,reasonCode:"workspace_hooks_trust_store_corrupt",...n?{errorMessage:n}:{}})}toggleFailure(t,n,o){this.emit(n==="workspace_hooks_snapshot_mismatch"?"workspace_hook.snapshot_mismatch":n==="workspace_hooks_config_rebuild_failed"?"workspace_hook.config_rebuild_failure":"workspace_hook.toggle_failure",{bundleDigest:t,reasonCode:n,...o?{errorMessage:o}:{}})}superseded(t){this.emit("workspace_hook.review_superseded",{bundleDigest:t.bundleDigest,generation:t.generation,reasonCode:"workspace_hooks_review_superseded"})}emit(t,n){aSe(this.logger,t,{workspaceIdentity:this.admission.getCurrentSnapshot().workspaceIdentity,...n})}}});async function zdi(e){let t=e.flow;for(;;){let n=await t.result;if(n.reasonCode==="workspace_hooks_review_superseded"){let o=e.registry.getCurrentFlow(e.sessionId);if(!o||o===t)return;t=o;continue}n.reasonCode==="workspace_hooks_interaction_timeout"&&(e.telemetry.timeout(t.request),await e.host.emit({type:nt.WorkspaceHookReviewSettled,payload:{interactionId:t.request.interactionId,state:"timed_out",reasonCode:n.reasonCode}}));return}}var $di=V(()=>{"use strict";Ln();r(zdi,"superviseWorkspaceHookReviewFlow")});async function IBn(e){let t=e.coordinator.getPolicy(e.snapshot.workspaceIdentity);if(t.mode!=="user_decides")return{accepted:!1,reasonCode:t.mode==="allow_trusted_only"?"workspace_hooks_policy_requires_pretrust":"workspace_hooks_blocked_by_policy"};try{let n=await(await e.store).revoke({workspaceIdentity:e.snapshot.workspaceIdentity,hookDeclarationDigests:e.digests});return e.coordinator.replacePersistentTrustRecords(n.records,{status:"ok"}),e.coordinator.revoke({workspaceIdentity:e.snapshot.workspaceIdentity,hookDeclarationDigests:e.digests}),{accepted:!0,reviewItemIds:[...e.reviewItemIds]}}catch{return{accepted:!1,reasonCode:"workspace_hooks_trust_store_corrupt"}}}var qdi=V(()=>{"use strict";r(IBn,"applyWorkspaceHookRevoke")});var rRt,Wdi=V(()=>{"use strict";Ln();Ff();xBn();Bdi();Udi();$di();qdi();rRt=class{static{r(this,"WorkspaceHookReviewController")}admission;appVersion;coordinator;host;telemetry;mutation;sessionId;store;now;createId;registry=new lyt;supervisedFlows=new WeakMap;reviewFlowId;generation=0;mutationQueue=Promise.resolve();constructor(t){this.admission=t.admission,this.appVersion=t.appVersion,this.coordinator=t.coordinator,this.host=t.host,this.telemetry=new nRt(this.admission,t.logger),this.mutation=t.mutation,this.sessionId=t.sessionId,this.store=t.store,this.now=t.now??Date.now,this.createId=t.createId??(()=>crypto.randomUUID())}superviseFlow(t){let n=this.supervisedFlows.get(t);if(n)return n;let o=zdi({flow:t,host:this.host,registry:this.registry,sessionId:this.sessionId,telemetry:this.telemetry});return this.supervisedFlows.set(t,o),o}async requestReview(t){let n=this.admission.getCurrentSnapshot();if(t.workspaceIdentity!==n.workspaceIdentity||t.bundleDigest!==n.bundleDigest)return{accepted:!1,reasonCode:"workspace_hooks_snapshot_mismatch"};let o=this.coordinator.evaluateSnapshot({snapshot:n});if(!o.items.some(c=>c.admissionClass==="pending"))return o.items.some(c=>c.trustState==="blocked_policy")?{accepted:!1,reasonCode:"workspace_hooks_blocked_by_policy"}:o.storeStatus==="corrupt"?{accepted:!1,reasonCode:"workspace_hooks_trust_store_corrupt"}:{accepted:!0,reviewItemIds:[]};let a=await this.openOrReuseFlow(n,o);return this.superviseFlow(a).catch(()=>{}),{accepted:!0,reviewItemIds:[]}}respond(t,n){return this.enqueueMutation(async()=>{let o=this.registry.validate(t,n);if(!o.accepted)return this.telemetry.responseRejected(t,o.reasonCode),o;let i=this.registry.getCurrentFlow(this.sessionId);if(!i)return{accepted:!1,reasonCode:"workspace_hooks_review_superseded"};let a=this.admission.getCurrentSnapshot();if(t.workspaceIdentity!==a.workspaceIdentity||t.bundleDigest!==a.bundleDigest)return this.telemetry.responseRejected(t,"workspace_hooks_snapshot_mismatch"),{accepted:!1,reasonCode:"workspace_hooks_snapshot_mismatch"};if(!this.coordinator.canMutatePersistentTrust(a.workspaceIdentity))return this.telemetry.responseRejected(t,"workspace_hooks_blocked_by_policy"),{accepted:!1,reasonCode:"workspace_hooks_blocked_by_policy"};let c;try{c=await this.applyPersistentTrust(o.reviewItemIds)}catch(f){return this.telemetry.trustStoreFailure(t.bundleDigest,f instanceof Error?f.message:String(f)),{accepted:!1,reasonCode:"workspace_hooks_trust_store_corrupt"}}this.telemetry.decisionAccepted(t,n,{...c.grantedRecordCount===void 0?{}:{grantedRecordCount:c.grantedRecordCount},requestEnabledCount:i.request.items.filter(f=>f.configuredEnabled).length});let u=this.registry.resolve(t,n);return u.accepted||this.telemetry.responseRejected(t,u.reasonCode),await this.host.emit({type:nt.WorkspaceHookReviewSettled,payload:{interactionId:t.interactionId,state:"resolved"}}),await this.emitAdmissionUpdatedAfterMutation(),await this.refreshPendingFlow(a),u.accepted?u:{accepted:!0,reviewItemIds:[...o.reviewItemIds]}})}toggle(t,n,o){return this.enqueueMutation(async()=>{let i=this.registry.validate(t,{action:"trust_selected",reviewItemIds:[n]});if(!i.accepted)return i;let a=this.admission.getCurrentSnapshot();if(!a.hooks.find(_=>_.reviewItemId===n)?.editable)return{accepted:!1,reasonCode:"workspace_hooks_snapshot_mismatch"};let u=!1,f;try{f=await this.mutation.toggle({snapshot:a,reviewItemId:n,enabled:o},()=>{u=!0,this.admission.invalidate("workspace_hooks_config_rebuild_failed")}),this.admission.replaceSnapshot(f)}catch(_){if(!u){let S=_ instanceof r6||_ instanceof Error&&_.name==="WorkspaceHookMutationError"?_.code:"workspace_hooks_config_write_failed";return this.telemetry.toggleFailure(t.bundleDigest,S,_ instanceof Error?_.message:String(_)),{accepted:!1,reasonCode:S}}return this.telemetry.toggleFailure(t.bundleDigest,"workspace_hooks_config_rebuild_failed"),this.registry.fail(t,"workspace_hooks_config_rebuild_failed"),await this.host.emit({type:nt.WorkspaceHookReviewSettled,payload:{interactionId:t.interactionId,state:"configuration_error",reasonCode:"workspace_hooks_config_rebuild_failed"}}),{accepted:!1,reasonCode:"workspace_hooks_config_rebuild_failed"}}let h=await this.refreshPendingFlow(f);return await this.emitAdmissionUpdatedAfterMutation(),{accepted:!0,reviewItemIds:[n],...h?{request:h.request}:{}}})}revoke(t,n){return this.enqueueMutation(async()=>{let o=this.registry.validate(t,{action:"trust_selected",reviewItemIds:[...n]});if(!o.accepted)return o;let i=this.admission.getCurrentSnapshot(),a=await IBn({coordinator:this.coordinator,digests:jdi(i,o.reviewItemIds),reviewItemIds:o.reviewItemIds,snapshot:i,store:this.store});return a.accepted&&(this.telemetry.revoked(i.bundleDigest,o.reviewItemIds.length),await this.refreshPendingFlow(i),await this.emitAdmissionUpdatedAfterMutation()),a})}revokeCurrent(t){return this.enqueueMutation(async()=>{let n=this.admission.getCurrentSnapshot();if(t.sessionId!==this.sessionId||t.remoteSessionId!==this.host.remoteSessionId||t.workspaceIdentity!==n.workspaceIdentity||t.bundleDigest!==n.bundleDigest)return{accepted:!1,reasonCode:"workspace_hooks_snapshot_mismatch"};let o=[...new Set(t.hookDeclarationDigests)],i=n.hooks.filter(c=>o.includes(c.hookDeclarationDigest));if(o.length===0||new Set(i.map(c=>c.hookDeclarationDigest)).size!==o.length)return{accepted:!1,reasonCode:"workspace_hooks_snapshot_mismatch"};let a=await IBn({coordinator:this.coordinator,digests:o,reviewItemIds:i.map(c=>c.reviewItemId),snapshot:n,store:this.store});return a.accepted&&(this.telemetry.revoked(n.bundleDigest,o.length),await this.refreshPendingFlow(n),await this.emitAdmissionUpdatedAfterMutation()),a})}async refreshPendingFlow(t){let n=this.registry.getCurrentFlow(this.sessionId);if(!n||n.state.state!=="pending")return await this.openReviewFlowForNewPendingItems(t);let o=TBn(n.request),i=this.coordinator.evaluateSnapshot({snapshot:t}),a=this.buildRequest(t,i,{reviewFlowId:n.request.reviewFlowId,generation:n.request.generation+1}),c=this.registry.supersede(o,a);return this.telemetry.superseded(a),this.generation=a.generation,await this.host.emit({type:nt.WorkspaceHookReviewSuperseded,payload:{interactionId:n.request.interactionId,supersededByInteractionId:a.interactionId}}),this.telemetry.requestCreated(a),await this.host.emit({type:nt.WorkspaceHookReviewRequested,payload:{request:a}}),a.summary.pendingCount===0&&(this.registry.closeWithoutDecision(TBn(a)),await this.host.emit({type:nt.WorkspaceHookReviewSettled,payload:{interactionId:a.interactionId,state:"resolved"}})),c}async openReviewFlowForNewPendingItems(t){let n=this.coordinator.evaluateSnapshot({snapshot:t});if(!n.items.some(a=>a.admissionClass==="pending"))return;let i=await this.openOrReuseFlow(t,n);return this.superviseFlow(i).catch(()=>{}),i}async openOrReuseFlow(t,n){let o=this.registry.getCurrentFlow(this.sessionId);if(o?.state.state==="pending"&&o.request.bundleDigest===t.bundleDigest)return o;this.reviewFlowId??=`workspace-hook-review:${this.createId()}`;let i=this.buildRequest(t,n,{reviewFlowId:this.reviewFlowId,generation:this.generation+1});this.generation=i.generation;let a=this.registry.open(i);return this.telemetry.requestCreated(i),await this.host.emit({type:nt.WorkspaceHookReviewRequested,payload:{request:i}}),a}buildRequest(t,n,o){return Fdi({snapshot:t,evaluation:n,...o,sessionId:this.sessionId,host:this.host,now:this.now,createId:this.createId})}async applyPersistentTrust(t){let n=this.admission.getCurrentSnapshot();this.coordinator.assertPersistentTrustMutationAllowed(n.workspaceIdentity);let o=pwo({snapshot:n,reviewItemIds:t,grantedAt:new Date(this.now()).toISOString(),...this.appVersion?{appVersion:this.appVersion}:{}}),i=await(await this.store).grant(o);return this.coordinator.replacePersistentTrustRecords(i.records,{status:"ok"}),{grantedRecordCount:o.length}}enqueueMutation(t){let n=this.mutationQueue.then(t,t);return this.mutationQueue=n.then(()=>{},()=>{}),n}async emitAdmissionUpdatedAfterMutation(){let t=this.admission.getCurrentSnapshot(),o=this.coordinator.evaluateSnapshot({snapshot:t}).items.filter(i=>i.configuredEnabled&&i.admissionClass==="pending").length;await this.host.emit({type:nt.WorkspaceHookAdmissionUpdated,payload:{pendingCount:o,bundleDigest:t.bundleDigest,...t.workspaceIdentity?{workspaceIdentity:t.workspaceIdentity}:{}}})}}});function Hdi(e){let t=(0,x5e.resolve)(e.workingDirectory),n=(0,x5e.resolve)(t,".zcode","config.json"),o=n;return{toggle(i,a){return ggc(o,async()=>{let c=await Vdi(e);if(c.workspaceIdentity!==i.snapshot.workspaceIdentity)throw new r6("workspace_hooks_snapshot_mismatch",`Workspace Hook identity changed after review (expected ${ayt(i.snapshot.workspaceIdentity)}, got ${ayt(c.workspaceIdentity)})`);if(c.bundleDigest!==i.snapshot.bundleDigest)throw new r6("workspace_hooks_bundle_changed",`Workspace Hook bundle changed after review (expected ${Y6e(i.snapshot.bundleDigest)}, got ${Y6e(c.bundleDigest)})`);return await Ldi({configPath:n,snapshot:c,reviewItemId:i.reviewItemId,enabled:i.enabled}),await a(),Vdi(e)})}}}async function Vdi(e){let t=await Hmt({workingDirectory:e.workingDirectory,...e.projectConfigPath?{explicitProjectConfigPath:e.projectConfigPath}:{}});if(t.errors.length>0){let o=t.errors[0]?.path;throw new r6("workspace_hooks_config_unreadable",`Workspace Hook config could not be read: ${o?(0,x5e.basename)(o):"unknown"}`,{cause:t.errors[0]?.error})}let n=nbe({workspaceIdentity:e.workspaceIdentity,workspacePath:e.workingDirectory,sources:t.sources,runtimeRoot:e.runtimeRoot});if(!n)throw new r6("workspace_hooks_snapshot_mismatch","Workspace Hook bundle no longer exists");return E0e(n)}async function ggc(e,t){let n=oRt.get(e)??Promise.resolve(),o,i=new Promise(c=>{o=c}),a=n.catch(()=>{}).then(()=>i);oRt.set(e,a),await n.catch(()=>{});try{return await t()}finally{o(),oRt.get(e)===a&&oRt.delete(e)}}var x5e,oRt,Gdi=V(()=>{"use strict";x5e=require("node:path");Ln();Ff();_se();xBn();oRt=new Map;r(Hdi,"createWorkspaceHookReviewMutationPort");r(Vdi,"rebuildSnapshot");r(ggc,"withWorkspaceMutationLock")});function Kdi(e){if(!e.snapshot)return;let t=e.policyProvider??new rZ(e.policy),n=new syt({coordinatorEpoch:crypto.randomUUID(),policyProvider:t}),o=e.workspaceHookTrustEnabled===!0,i=o?Zoe({userConfigPath:e.userConfigPath,...e.homeDir?{homeDir:e.homeDir}:{}}):void 0,a=o?Jdi({coordinator:n,logger:e.logger,store:i}):Promise.resolve(),c,u=e.emitAdmissionEvent?_=>{e.emitAdmissionEvent({type:nt.WorkspaceHookAdmissionUpdated,payload:{pendingCount:_.pendingCount,bundleDigest:_.bundleDigest,..._.workspaceIdentity?{workspaceIdentity:_.workspaceIdentity}:{}}}).catch(v=>{e.logger.warn("Failed to emit WorkspaceHookAdmissionUpdated",{errorType:v instanceof Error?v.name:typeof v,event:"workspace_hook.admission_event_emit_failed",module:"bootstrap.workspace_hook_trust"})})}:void 0,f=gwo({coordinator:n,enabled:o,logger:e.logger,ready:a,...u?{onAdmissionStateChanged:u}:{},snapshot:e.snapshot});if(o&&e.reviewHost&&e.emitReviewEvent){let _={...e.reviewHost,emit:e.emitReviewEvent};c=new rRt({admission:f,appVersion:e.appVersion,coordinator:n,host:_,logger:e.logger,mutation:Hdi({workingDirectory:e.workingDirectory,workspaceIdentity:e.snapshot.workspaceIdentity,projectConfigPath:e.projectConfigPath,runtimeRoot:e.runtimeRoot}),sessionId:e.sessionId,store:i})}let h=r(()=>({accepted:!1,reasonCode:o?"workspace_hooks_require_trust_capable_host":"workspace_hooks_feature_disabled"}),"unavailable");return{admission:f,snapshot:e.snapshot,reloadTrust:r(async()=>{!o||!i||(await Jdi({coordinator:n,logger:e.logger,store:i}),await f.activate("resume"))},"reloadTrust"),requestReview:r(_=>c?c.requestReview(_):Promise.resolve(h()),"requestReview"),respond:r((_,v)=>c?c.respond(_,v):Promise.resolve(h()),"respond"),toggle:r((_,v,S)=>c?c.toggle(_,v,S):Promise.resolve(h()),"toggle"),revoke:r((_,v)=>c?c.revoke(_,v):Promise.resolve(h()),"revoke"),revokeCurrent:r(_=>c?c.revokeCurrent(_):Promise.resolve(h()),"revokeCurrent")}}async function Jdi(e){try{let t=await(await e.store).load();e.coordinator.replacePersistentTrustRecords(t.records,{status:t.status,...t.status==="corrupt"?{recoveredCorruptPath:t.recoveredCorruptPath}:{}})}catch(t){e.coordinator.replacePersistentTrustRecords([],{status:"corrupt"}),aSe(e.logger,"workspace_hook.trust_store_failure",{reasonCode:"workspace_hooks_trust_store_corrupt"}),e.logger.warn("Workspace Hook Trust store bootstrap failed closed",{errorType:t instanceof Error?t.name:typeof t,event:"workspace_hook.trust_store.bootstrap_failed",module:"bootstrap.workspace_hook_trust",reasonCode:"workspace_hooks_trust_store_corrupt",status:"completed"})}}var Zdi=V(()=>{"use strict";W2();Ff();Ln();Wdi();Gdi();r(Kdi,"createWorkspaceHookRuntimeSecurity");r(Jdi,"loadWorkspaceHookTrustStore")});async function T5e(e){let t=(0,Qdi.resolve)(e.scriptPath),n=await e.fileSystemPort.readTextFile({maxBytes:bgc,path:t,trace:e.traceContext});if(n.truncated)throw new Error(`Workflow script is too large: ${t}`);let o=Sgc(n.content),i=o.metaExpression,a=await wgc(i),c=MMr.parse(a);return{body:o.body,content:n.content,hash:lTe(n.content),meta:c,path:t}}function lTe(e){let t=typeof e=="string"?e:CBn(e);return(0,Xdi.createHash)("sha256").update(t).digest("hex")}function CBn(e){if(Array.isArray(e))return`[${e.map(CBn).join(",")}]`;if(e&&typeof e=="object"){let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${CBn(t[n])}`).join(",")}}`}return JSON.stringify(e)}function Sgc(e){let t=_gc.exec(e);if(!t)throw new Error("Workflow script must begin with `export const meta = {...}`.");let n=t.index+t[0].length;for(;/\s/.test(e[n]??"");)n+=1;if(e[n]!=="{")throw new Error("Workflow meta must be an object literal.");let o=kgc(e,n),i=o+1;for(;/\s/.test(e[i]??"");)i+=1;return e[i]===";"&&(i+=1),{body:e.slice(i).trimStart(),metaExpression:e.slice(n,o+1)}}async function wgc(e){let t=(0,Ydi.spawn)(process.execPath,["--input-type=module","--eval",Cgc],{stdio:["pipe","pipe","pipe"]}),n=[],o=[],i=0,a=setTimeout(()=>t.kill(),ygc);t.stdout.on("data",_=>{i+=_.byteLength,i<=vgc&&n.push(_)}),t.stderr.on("data",_=>{o.push(_)}),t.stdin.end(JSON.stringify({expression:e}));let c=await new Promise((_,v)=>{t.on("error",v),t.on("close",_)});clearTimeout(a);let u=Buffer.concat(n).toString("utf8"),f=Buffer.concat(o).toString("utf8").trim();if(c!==0)throw new Error(f||`Workflow meta evaluation failed with exit code ${c}`);let h=JSON.parse(u);if(!h.ok)throw new Error(h.error||"Workflow meta evaluation failed");return h.value}function kgc(e,t){let n=0;for(let o=t;o<e.length;o+=1){let i=e[o];if(i==="'"||i==='"'||i==="`"){o=xgc(e,o,i);continue}if(i==="/"&&e[o+1]==="/"){o=Tgc(e,o+2);continue}if(i==="/"&&e[o+1]==="*"){o=Igc(e,o+2);continue}if(i==="{"&&(n+=1),i==="}"&&(n-=1,n===0))return o}throw new Error("Workflow meta object literal is not closed.")}function xgc(e,t,n){for(let o=t+1;o<e.length;o+=1){let i=e[o];if(i==="\\"){o+=1;continue}if(i===n)return o}throw new Error("Workflow meta string literal is not closed.")}function Tgc(e,t){let n=e.indexOf(`
|
|
14921
14921
|
`,t);return n===-1?e.length-1:n}function Igc(e,t){let n=e.indexOf("*/",t);if(n===-1)throw new Error("Workflow meta block comment is not closed.");return n+1}var Ydi,Xdi,Qdi,_gc,ygc,vgc,bgc,Cgc,iRt=V(()=>{"use strict";Ydi=require("node:child_process"),Xdi=require("node:crypto"),Qdi=require("node:path");Ln();_gc=/export\s+const\s+meta\s*=/,ygc=5e3,vgc=1024*1024,bgc=2*1024*1024;r(T5e,"readWorkflowScriptDocument");r(lTe,"stableHash");r(CBn,"stableStringify");r(Sgc,"extractWorkflowScriptParts");r(wgc,"evaluateMetaExpression");r(kgc,"findObjectLiteralEnd");r(xgc,"scanString");r(Tgc,"scanLineComment");r(Igc,"scanBlockComment");Cgc=`
|
|
14922
14922
|
let input = "";
|
|
@@ -15694,8 +15694,8 @@ Commands:
|
|
|
15694
15694
|
marketplace remove <name> Remove a configured marketplace
|
|
15695
15695
|
marketplace update [name] Refresh one marketplace, or all when omitted
|
|
15696
15696
|
|
|
15697
|
-
Scopes: user (default), project. \`zcode plugin\` is an alias of \`zcode plugins\`.`;r(TTi,"runPluginsCommand");r(_Ac,"runPluginsListCommand");r(yAc,"runPluginsInstallCommand");r(vAc,"runPluginsUpdateCommand");r(bAc,"reportInstallOutcome");r(ITi,"runPluginsSetCommand");r(SAc,"runPluginsDisableCommand");r(wAc,"runPluginsUninstallCommand");r(kAc,"runPluginsValidateCommand")});function TAc(e=process.env){let t=e.ZCODE_STORAGE_DIR?.trim()||(0,jle.join)((0,ATi.homedir)(),".zcode");return(0,jle.join)(t,"clipboard")}function PTi(e={}){let t=e.platform??process.platform,n=e.maxBytes??xAc,o=e.runCommand??AAc,i=e.tempDirectory??TAc(e.processEnv);return async(a={})=>t==="darwin"?await IAc({maxBytes:n,runCommand:o,signal:a.abortSignal,tempDirectory:i}):t==="linux"?await CAc({maxBytes:n,runCommand:o,signal:a.abortSignal}):t==="win32"?await EAc({maxBytes:n,runCommand:o,signal:a.abortSignal,tempDirectory:i}):null}async function IAc(e){await(0,f6.mkdir)(e.tempDirectory,{recursive:!0});let t=await(0,f6.mkdtemp)((0,jle.join)(e.tempDirectory,"zcode-clipboard-")),n=(0,jle.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 ${PAc(n)} with write permission`,"-e","write png_data to fp","-e","close access fp"],{maxBytes:e.maxBytes,signal:e.signal})).exitCode!==0?null:await RTi(n,"image/png",e.maxBytes)}finally{await(0,f6.rm)(t,{force:!0,recursive:!0})}}async function CAc(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=DTi(o.stdout,n.mediaType,e.maxBytes);if(o.exitCode===0&&i)return i}return null}async function EAc(e){await(0,f6.mkdir)(e.tempDirectory,{recursive:!0});let t=await(0,f6.mkdtemp)((0,jle.join)(e.tempDirectory,"zcode-clipboard-")),n=(0,jle.join)(t,"clipboard.png"),o=["Add-Type -AssemblyName System.Windows.Forms;","$img = Get-Clipboard -Format Image;","if ($null -eq $img) { exit 2 }",`$img.Save(${RAc(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 RTi(n,"image/png",e.maxBytes)}finally{await(0,f6.rm)(t,{force:!0,recursive:!0})}}async function RTi(e,t,n){let o=await(0,f6.readFile)(e);return DTi(o,t,n)}function DTi(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 AAc(e,t,n){return await new Promise(o=>{let i;try{i=(0,ETi.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 PAc(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function RAc(e){return`'${e.replace(/'/g,"''")}'`}var ETi,f6,ATi,jle,xAc,OTi=V(()=>{"use strict";ETi=require("node:child_process"),f6=require("node:fs/promises"),ATi=require("node:os"),jle=require("node:path"),xAc=20*1024*1024;r(TAc,"resolveDefaultClipboardDirectory");r(PTi,"createNodeClipboardImageReader");r(IAc,"readMacClipboardImage");r(CAc,"readLinuxClipboardImage");r(EAc,"readWindowsClipboardImage");r(RTi,"readImageFile");r(DTi,"bufferToClipboardImage");r(AAc,"runCommandBuffer");r(PAc,"appleScriptString");r(RAc,"powershellString")});function NTi(e={}){let t=e.maxBytes??DAc,n=e.platform??process.platform,o=e.runCommand??zAc;return async i=>{let a=UAc(i,t);if(a.byteLength===0)return;let c=FAc(e.stdout,a),u=await jAc({input:i,platform:n,runCommand:o});if(!c&&!u)throw new Error("No text clipboard target accepted the selected text.")}}function FAc(e,t){if(!e)return!1;try{return e.write(`${MAc}${OAc};${t.toString("base64")}${NAc}`),!0}catch{return!1}}async function jAc(e){for(let t of BAc(e.platform))if((await e.runCommand(t.file,t.args,{input:e.input})).exitCode===0)return!0;return!1}function BAc(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",LAc],file:"powershell.exe"}]:[]}function UAc(e,t){let n=Buffer.from(e,"utf8");if(n.byteLength>t)throw new Error(`Clipboard text exceeds ${t} bytes.`);return n}async function zAc(e,t,n){return await new Promise(o=>{let i;try{i=(0,MTi.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 MTi,DAc,OAc,MAc,NAc,LAc,LTi=V(()=>{"use strict";MTi=require("node:child_process"),DAc=1024*1024,OAc="c",MAc="\x1B]52;",NAc="\x07",LAc="Set-Clipboard -Value ([Console]::In.ReadToEnd())";r(NTi,"createNodeClipboardTextWriter");r(FAc,"writeOsc52");r(jAc,"writeNativeClipboardText");r(BAc,"nativeClipboardCommands");r(UAc,"assertClipboardTextSize");r(zAc,"runCommandText")});async function pOt(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 Cy()).listZCodeCustomCommands({env:t,logger:e.logger,workingDirectory:n})}async function FTi(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 Cy()).loadZCodeCustomCommand({env:n,logger:e.logger,name:t,workingDirectory:o})}async function jTi(e){let t=e.env??process.env,n=(e.cwd??process.cwd)();return await(e.listSkills??(await Cy()).listZCodeSkills)({env:t,logger:e.logger,workingDirectory:n})}async function BTi(e){let t=e.env??process.env,n=(e.cwd??process.cwd)();return(await(e.listSessions??(await Cy()).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 UTi(e){try{return await e.getSessionMetadata?.()??{}}catch(t){if($Ac(t))throw t;return{}}}function $Ac(e){return e instanceof Error?e.name==="SqliteSessionMigrationError":!1}var S5n=V(()=>{"use strict";FX();r(pOt,"listCustomCommandsForTui");r(FTi,"loadCustomCommandForTui");r(jTi,"listSkillsForTui");r(BTi,"listSessionsForTui");r(UTi,"loadInitialTuiSessionMetadata");r($Ac,"isStartupGateError")});function zTi(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 $Ti=V(()=>{"use strict";r(zTi,"createTuiSessionEventRelay")});async function w5n(e){let t=await e.listModels?.()??[];return{locale:e.getLocale?.(),model:e.getModel?.(),theme:e.getTheme?.(),thoughtLevel:e.getThoughtLevel?.(),modelOptions:t,effortOptions:await $Te(e)??[],loginRequired:!t.some(n=>!n.disabledReason)}}var qTi,WTi=V(()=>{"use strict";XDt();r(w5n,"readTuiSessionMetadata");qTi=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,(vBn(),cMr(),{collectChildSessionIds:ZPt,projectSubagents:YPt,projectChildEvents:e=>new M7().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 w5n(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 $Te(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 HTi(e,t,n,o){let i=e.env??process.env,a=(e.cwd??process.cwd)(),c=(e.loadDotenv??nP)({cwd:a,env:i});if(c.error)throw new Error(`Failed to load environment file: ${c.path}`,{cause:c.error});let u=await sOt(n,a,i,e),f=e.createZCodeApp?void 0:await Cy(),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 v=_?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(v,e.skipUserConfig?{}:{standalone:{...UMe(),...e.userConfigPath?{legacyCliUserConfigFilePath:e.userConfigPath}:{}}});let k=await o.providerRegistryRuntimePromise,I=k?.modelSelectionConfigRepository?await k.modelSelectionConfigRepository.read():k?.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:v,configuredDefaultModelSelection:I,createAppFactory:h,providerRegistryRuntime:k,sessionId:u,workingDirectory:a}}var VTi,GTi=V(()=>{"use strict";FX();Kne();Mit();p5n();VTi=r(()=>({providerEndpointRoutingPort:void 0,providerRegistryRuntimePromise:void 0,shutdownTelemetry:void 0}),"createTuiProcessRuntimeState");r(HTi,"prepareTuiAppRuntime")});async function JTi(e,t){let n=e.env??process.env,o=(e.cwd??process.cwd)(),i=(e.loadDotenv??nP)({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 Cy()).loginZCodeCli)({abortSignal:t?.abortSignal,env:n,onAuthorizeUrl:t?.onAuthorizeUrl})}async function KTi(e,t){let n=e.env??process.env,o=(e.cwd??process.cwd)(),i=(e.loadDotenv??nP)({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 Cy()).loginBigmodelCodingPlan)({abortSignal:t?.abortSignal,env:n,onAuthorizeUrl:t?.onAuthorizeUrl})}async function ZTi(e,t){return await(e.configureCodingPlanApiKey??(await Cy()).configureCodingPlanApiKey)({apiKey:t.apiKey,env:e.env??process.env,providerId:t.providerId})}async function YTi(e){let t=e.env??process.env,n=(e.cwd??process.cwd)(),o=(e.loadDotenv??nP)({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 Cy()).logoutZCodeCli)({env:t})}var XTi=V(()=>{"use strict";FX();Kne();r(JTi,"loginForTui");r(KTi,"loginBigmodelForTui");r(ZTi,"configureApiKeyForTui");r(YTi,"logoutForTui")});function VTe(e,t){return e.runtime?.getPlanEnabled?.()?"plan":e.getMode?.()??t}var QTi,eIi,SW,k5n=V(()=>{"use strict";QTi={},eIi=r(e=>({current:e,override:e}),"createCliModeState"),SW=r(e=>e.current??e.override??"build","currentCliMode");r(VTe,"readTuiMode")});function x5n(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 tIi=V(()=>{"use strict";r(x5n,"withTuiMetadata")});function nIi(e,t,n,o={continueSession:!1},i,a,c=E1t,u,f=!1,h="off",_,v,S=jX){let k,I=i,C=VTi(),R,D=new WeakMap,B=new WeakMap,F,z=Math.max(1,Math.trunc(e.shutdownCleanupTimeoutMs??dtt)),$={requestPermission:r(async(lt,Oe)=>{let At=F;return At?await At(lt,Oe):{decision:"deny",reason:`No interactive approval handler configured for ${lt.toolName}`,resolvedAt:new Date}},"requestPermission")},q=r(async(lt=k)=>{if(!lt)return;let Oe=lt,At=D.get(Oe);At||(At=(async()=>{await e4(async()=>lt.close?.(),z),await e4(async()=>B.get(Oe)?.close(),z)})(),D.set(Oe,At)),await At},"closeApp"),J=zTi({currentRuntime:r(()=>k?.runtime,"currentRuntime"),readSubscriber:oOt}),ne=r(async lt=>{let Oe=k,At=await lt();try{await At.readExecutionState()}catch($zResumeCandidateError){await q(At);throw $zResumeCandidateError}return k=At,Oe&&Oe!==At&&await q(Oe),J.reattach(),t.current=VTe(k,SW(t)),k},"replaceApp"),se=r(async lt=>{if(R)throw new Error("TUI prompt handler is closed");let{appEnv:Oe,configuredDefaultModelSelection:At,createAppFactory:pt,providerRegistryRuntime:He,sessionId:De,workingDirectory:vt}=await HTi(e,n,lt,C),Ve=C.providerEndpointRoutingPort,We=nOt({browserExecutable:v,browserUse:_},e),ft;try{ft=await pt({modelSelectionMode:"cli-default",browserControlPort:We?.browserControlPort,env:Oe,projectConfigPath:e.projectConfigPath,...Ve?{providerEndpointRoutingPort:Ve}:{},providerRegistry:He.runtime.registryService,configuredDefaultModelSelection:At,...He.providerRuntimeHeadersPort?{providerRuntimeHeadersPort:He.providerRuntimeHeadersPort}:{},resume:De!==void 0,runtimeConfig:{...t.override?{mode:t.override}:{},...u?{toolDisallowlist:u}:{},toolSearch:{mode:h},...f?{midConversationSystem:{mode:"force"}}:{},...YDt(S),modelStreaming:"on",titleGeneration:QTi,workingDirectory:vt},permissionBroker:$,sessionId:De,skipUserConfig:e.skipUserConfig,uiDetectedLocale:a,uiLocale:I,userConfigPath:e.userConfigPath,version:n})}catch(kt){throw await e4(async()=>We?.close(),z),kt}if(We&&B.set(ft,We),R)throw await q(ft),new Error("TUI prompt handler is closed");return ft},"createApp"),xe=r(async()=>(k??=await se(o),t.current=VTe(k,SW(t)),k),"getApp"),ue=r(async lt=>await ne(async()=>await se(lt?{continueSession:!1,resumeSessionId:lt}:{continueSession:!0})),"resumeApp"),Ie=r(async()=>await ne(async()=>await se({continueSession:!1})),"newApp"),Ue=r(async lt=>{if(t.override=lt,k){let Oe=k;if(Oe.setMode){let At=await Oe.setMode(lt);return t.current=VTe(Oe,At.mode),t.current}Oe.runtime.updateConfig({mode:lt})}return t.current=k?VTe(k,lt):lt,t.current},"setCliMode"),Me=N$e({forkApp:r(async lt=>{let At=await(await xe()).forkFromCheckpoint?.({targetCheckpointId:lt});if(!At)throw new Error("Forking is not available in this client.");return await ne(async()=>await se({continueSession:!1,resumeSessionId:At.forkedSessionId})),{copiedMessageCount:At.copiedMessageCount,forkedSessionId:At.forkedSessionId,response:`${At.response}
|
|
15698
|
-
Switched to forked session ${At.forkedSessionId}.`,restoredFileCount:At.restoredFileCount??At.restoredFiles?.length??0}},"forkApp"),getApp:xe,getMode:r(()=>SW(t),"getMode"),getLocale:r(()=>k?.getLocale?.()??Dzn(I,a)??c,"getLocale"),hasSelectableModels:$xi(xe),listCustomCommands:r(()=>pOt(e),"listCustomCommands"),listSessions:r(()=>BTi(e),"listSessions"),listSkills:r(()=>jTi(e),"listSkills"),configureApiKey:r(lt=>ZTi(e,lt),"configureApiKey"),login:r(lt=>JTi(e,lt),"login"),loginBigmodel:r(lt=>KTi(e,lt),"loginBigmodel"),loadCustomCommand:r(lt=>FTi(e,lt),"loadCustomCommand"),newApp:Ie,recordInputHistory:r(async(lt,Oe)=>{await k?.recordInputHistory?.(lt,Oe)},"recordInputHistory"),resumeApp:ue,saveDefaultModelSelection:r(async lt=>{let Oe=await C.providerRegistryRuntimePromise;if(!Oe?.modelSelectionConfigRepository)throw new Error("Default model configuration storage is unavailable.");await Oe.modelSelectionConfigRepository.saveConfiguredDefault(lt)},"saveDefaultModelSelection"),logout:r(()=>YTi(e),"logout"),setLocale:r(async lt=>{if(k?.setLocale){let At=await k.setLocale(lt);return I=lt,At}return I=lt,{configPath:(await Yve(e.userConfigPath??aj(),lt)).path,locale:Dzn(lt,a)??"en-US",requestedLocale:lt}},"setLocale"),setMode:Ue,workflowMode:S}),ut=r(async(lt,Oe)=>{let At=F;F=Oe.requestPermission;try{let pt=await Me(lt,Oe);return k?{...pt,...await w5n(await xe())}:pt}finally{F=At}},"submitPrompt");return ut.setMode=async lt=>({mode:await Ue(lt)}),ut.sendInput=async(lt,Oe)=>{let At=F;F=Oe?.requestPermission;try{let pt=Lle(typeof lt=="string"?lt:lt.text);if(pt?.type==="known"&&(pt.name==="model"||pt.name==="effort"))return{kind:"command_result",result:await ut(lt,{...Oe,abortSignal:Oe?.abortSignal??new AbortController().signal})};let He=await xe();if(He.sendInput){let De=await He.sendInput(lt,Oe);return De.kind!=="started_turn"?De:x5n(await(De.result??De.completion),He,SW(t))}return x5n(await He.submitPrompt(lt,Oe),He,SW(t))}finally{F=At}},ut.listSkills=async()=>await jTi(e),ut.$zReadProviderRegistryRuntime=()=>C.providerRegistryRuntimePromise,qTi(ut,xe),ut.subscribeSessionEvents=lt=>{let Oe=J.addSink(lt);return xe().then(()=>J.reattach(),()=>{}),Oe},ut.getMainSessionId=()=>{let Oe=k?.runtime?.getSessionId?.();return typeof Oe=="string"&&Oe.length>0?Oe:void 0},ut.close=async()=>{R??=(async()=>{await q(),await e4(async()=>C.shutdownTelemetry?.(),z),(await C.providerRegistryRuntimePromise)?.dispose()})(),await R},ut}var rIi=V(()=>{"use strict";tb();aL();tOt();Ozn();l5n();iOt();$Ti();WTi();GTi();Uhe();XTi();S5n();k5n();s5n();tIi();UX();r(nIi,"createTuiSubmitPrompt")});var oIi,iIi,F1,WX,sR,sIi,aIi,qAc,WAc,cIi,lIi,VAc,HAc,GAc,JAc,KAc,ZAc,uIi=V(()=>{"use strict";oIi=require("node:crypto"),iIi=require("node:fs"),F1=require("node:fs/promises"),WX=require("node:os"),sR=require("node:path"),sIi=require("node:url"),aIi="zcode-tui-runtime/",qAc=`${aIi}manifest.json`,WAc="node_modules/@zcode/tui/dist/index.js",cIi="manifest.json",lIi=r(async()=>{let e=await import("node:sea");if(!e.isSea())return await import("@zcode/tui");let t=await VAc(e);return await import((0,sIi.pathToFileURL)((0,sR.join)(t,WAc)).href)},"loadTuiRuntime"),VAc=r(async e=>{let t=HAc(e),n=(0,sR.join)(JAc(),"0.17.1",t.target,t.hash),o=(0,sR.join)(n,cIi);if(await GAc(o,t))return n;let i=`${n}.tmp-${process.pid}-${Date.now()}`;await(0,F1.rm)(i,{force:!0,recursive:!0}),await(0,F1.mkdir)(i,{recursive:!0});for(let a of t.files){let c=e.getRawAsset(`${aIi}${a.path}`),u=Buffer.from(c);if((0,oIi.createHash)("sha256").update(u).digest("hex")!==a.sha256)throw new Error(`SEA TUI asset hash mismatch for ${a.path}`);let h=(0,sR.join)(i,a.path);await(0,F1.mkdir)((0,sR.dirname)(h),{recursive:!0}),await(0,F1.writeFile)(h,u),await(0,F1.chmod)(h,a.mode??ZAc(a.path))}return await(0,F1.writeFile)(KAc(i),JSON.stringify(t,null,2)),await(0,F1.rm)(n,{force:!0,recursive:!0}),await(0,F1.mkdir)((0,sR.dirname)(n),{recursive:!0}),await(0,F1.rename)(i,n),n},"ensureSeaTuiRuntime"),HAc=r(e=>{let t=e.getAsset(qAc,"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"),GAc=r(async(e,t)=>{if(!(0,iIi.existsSync)(e))return!1;try{let n=JSON.parse(await(0,F1.readFile)(e,"utf8"));return n.hash===t.hash&&n.target===t.target}catch{return!1}},"isCacheCurrent"),JAc=r(()=>{let e=(0,WX.homedir)();return(0,WX.platform)()==="darwin"&&e?(0,sR.join)(e,"Library","Caches","zcode","sea-assets"):(0,WX.platform)()==="win32"?(0,sR.join)(process.env.LOCALAPPDATA??(0,sR.join)(e||(0,WX.tmpdir)(),"AppData","Local"),"zcode","Cache","sea-assets"):(0,sR.join)(process.env.XDG_CACHE_HOME??(0,sR.join)(e||(0,WX.tmpdir)(),".cache"),"zcode","sea-assets")},"cacheBaseDirectory"),KAc=r(e=>(0,sR.join)(e,cIi),"markerPathForDirectory"),ZAc=r(e=>/\.(?:dll|dylib|node|so)$/i.test(e)?493:420,"modeForPath")});function dIi({deps:e,options:t,workingDirectory:n}){let o=Hm({cliOverrides:YAc(t.locale),env:e.env??process.env,projectConfigPath:e.projectConfigPath,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,workingDirectory:n});return UU(o.config.ui.locale,t.detectedLocale)}var YAc,pIi=V(()=>{"use strict";tb();aL();YAc=r(e=>e?{ui:{locale:e}}:void 0,"localeCliOverrides");r(dIi,"resolveTuiStartupLocale")});function mIi(e){let t=e.fileSystemPort??EJ(),n=(0,kL.resolve)(e.workspaceDirectory);return require(require("node:path").join(__dirname,"cli-config.cjs")).withRecursiveWorkspacePathSuggestions(async o=>{let i=nPc(o.token);if(!i)return{items:[],truncated:!1};let a=(0,kL.resolve)(n,i.directoryToken);if(!sPc(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"&&tPc.has(h.name))return[];if(!i.query.startsWith(".")&&h.name.startsWith("."))return[];if(!rPc(h.name,i.query))return[];let _=iPc(n,h.path);return _?[{kind:h.kind,path:h.kind==="directory"?`${_}/`:_}]:[]}).sort((h,_)=>oPc(h,_,i.query)),f=Math.max(1,Math.floor(o.limit??XAc));return{items:u.slice(0,f),truncated:u.length>f}}catch{return{items:[],truncated:!1}}},{workspaceDirectory:n,fileSystemPort:t,excludedDirectories:tPc})}function nPc(e){let t=e.replace(/^@/u,"");if(t.startsWith("/")||t.startsWith("\\")||(0,kL.isAbsolute)(t)||ePc.test(t))return;let n=t.replace(QAc,"/");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 rPc(e,t){return t.length===0?!0:e.toLowerCase().includes(t.toLowerCase())}function oPc(e,t,n){if(e.kind!==t.kind)return e.kind==="directory"?-1:1;let o=fIi(e.path),i=fIi(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 fIi(e){let t=e.endsWith("/")?e.slice(0,-1):e,n=t.lastIndexOf("/");return n<0?t:t.slice(n+1)}function iPc(e,t){let n=(0,kL.relative)(e,t);if(!(!n||n.startsWith("..")||(0,kL.isAbsolute)(n)))return n.split(kL.sep).join("/")}function sPc(e,t){let n=(0,kL.relative)(e,t);return n===""||!n.startsWith("..")&&!(0,kL.isAbsolute)(n)}var kL,XAc,QAc,ePc,tPc,hIi=V(()=>{"use strict";p_e();kL=require("node:path"),XAc=50,QAc=/[\\/]+/gu,ePc=/^[a-zA-Z]:[\\/]/u,tPc=new Set([".bzr",".git",".hg",".jj",".sl",".svn","node_modules"]);r(mIi,"createWorkspacePathSuggestionProvider");r(nPc,"parseWorkspacePathToken");r(rPc,"matchesPathQuery");r(oPc,"compareWorkspacePathSuggestion");r(fIi,"basenameFromSuggestion");r(iPc,"toWorkspaceRelativePath");r(sPc,"isPathInside")});async function _Ii(e){let t=e.maxOutputBytes??uPc,n=e.timeoutMs??lPc,i=await(e.runCommand??pPc)(aPc,["-C",e.workspaceDirectory,...cPc],{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===dPc))return a}async function pPc(e,t,n){return await new Promise(o=>{let i;try{i=(0,gIi.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 gIi,aPc,cPc,lPc,uPc,dPc,yIi=V(()=>{"use strict";gIi=require("node:child_process"),aPc="git",cPc=["symbolic-ref","--quiet","--short","HEAD"],lPc=750,uPc=512,dPc="HEAD";r(_Ii,"resolveWorkspaceGitBranch");r(pPc,"runGitCommand")});var vIi,bIi=V(()=>{"use strict";ti();OTi();LTi();tOt();Uhe();S5n();rIi();uIi();pIi();hIi();yIi();k5n();UX();vIi=r(async(e,t,n,o,i,a,c,u=!1,f="off",h=jX)=>{try{let _=eIi(i),v=n.runTui??(await lIi()).runTui,S=(n.cwd??process.cwd)(),k=n.env??process.env,I=PDe(k)==="development",C=dIi({deps:n,options:t,workingDirectory:S}),R=nIi(n,_,o,a,t.locale,t.detectedLocale,C,c,u,f,t.browserUse,t.browserExecutable,h),D=ptt({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 v({loadStartupOptions:r(async()=>{let[B,F,z]=await Promise.all([UTi(R),pOt(n).catch(()=>{}),(n.resolveWorkspaceGitBranch??_Ii)({workspaceDirectory:S}).catch(()=>{})]);return{initialMode:SW(_),initialModel:B.model,initialThoughtLevel:B.thoughtLevel,loginRequired:B.loginRequired,locale:B.locale??C,theme:B.theme??"auto",modelOptions:B.modelOptions,effortOptions:B.effortOptions,slashCommands:n5n(F,{workflowMode:h}),workspaceGitBranch:z}},"loadStartupOptions"),locale:C,developerMode:I,version:o,workspaceDirectory:S,noColor:t.noColor,readClipboardImage:n.readClipboardImage??PTi(),readDefaultModel:R.readDefaultModel,setDefaultModel:R.setDefaultModel,reloadModelOptions:R.reloadModelOptions,listModelOptions:R.listModelOptions,listWorkspacePathSuggestions:mIi({workspaceDirectory:S}),listMcpServers:R.listMcpServers,readSubagents:R.readSubagents,readSubagentTranscript:R.readSubagentTranscript,listWorkflowRuns:R.listWorkflowRuns,replayWorkflowRuns:R.replayWorkflowRuns,reduceWorkflowRuns:($zState,$zEvent)=>{qRr();return rst($zState,$zEvent)},retuneWorkflowConcurrency:R.retuneWorkflowConcurrency,listSavedWorkflows:R.listSavedWorkflows,readSavedWorkflow:R.readSavedWorkflow,saveWorkflowRun:R.saveWorkflowRun,startSavedWorkflow:R.startSavedWorkflow,getMainSessionId:R.getMainSessionId,writeClipboardText:n.writeClipboardText??NTi({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{D(),await R.close?.()}}catch(_){let v=_ instanceof Error?_.message:String(_);return e.stderr.write(`Error: ${v}
|
|
15697
|
+
Scopes: user (default), project. \`zcode plugin\` is an alias of \`zcode plugins\`.`;r(TTi,"runPluginsCommand");r(_Ac,"runPluginsListCommand");r(yAc,"runPluginsInstallCommand");r(vAc,"runPluginsUpdateCommand");r(bAc,"reportInstallOutcome");r(ITi,"runPluginsSetCommand");r(SAc,"runPluginsDisableCommand");r(wAc,"runPluginsUninstallCommand");r(kAc,"runPluginsValidateCommand")});function TAc(e=process.env){let t=e.ZCODE_STORAGE_DIR?.trim()||(0,jle.join)((0,ATi.homedir)(),".zcode");return(0,jle.join)(t,"clipboard")}function PTi(e={}){let t=e.platform??process.platform,n=e.maxBytes??xAc,o=e.runCommand??AAc,i=e.tempDirectory??TAc(e.processEnv);return async(a={})=>t==="darwin"?await IAc({maxBytes:n,runCommand:o,signal:a.abortSignal,tempDirectory:i}):t==="linux"?await CAc({maxBytes:n,runCommand:o,signal:a.abortSignal}):t==="win32"?await EAc({maxBytes:n,runCommand:o,signal:a.abortSignal,tempDirectory:i}):null}async function IAc(e){await(0,f6.mkdir)(e.tempDirectory,{recursive:!0});let t=await(0,f6.mkdtemp)((0,jle.join)(e.tempDirectory,"zcode-clipboard-")),n=(0,jle.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 ${PAc(n)} with write permission`,"-e","write png_data to fp","-e","close access fp"],{maxBytes:e.maxBytes,signal:e.signal})).exitCode!==0?null:await RTi(n,"image/png",e.maxBytes)}finally{await(0,f6.rm)(t,{force:!0,recursive:!0})}}async function CAc(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=DTi(o.stdout,n.mediaType,e.maxBytes);if(o.exitCode===0&&i)return i}return null}async function EAc(e){await(0,f6.mkdir)(e.tempDirectory,{recursive:!0});let t=await(0,f6.mkdtemp)((0,jle.join)(e.tempDirectory,"zcode-clipboard-")),n=(0,jle.join)(t,"clipboard.png"),o=["Add-Type -AssemblyName System.Windows.Forms;","$img = Get-Clipboard -Format Image;","if ($null -eq $img) { exit 2 }",`$img.Save(${RAc(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 RTi(n,"image/png",e.maxBytes)}finally{await(0,f6.rm)(t,{force:!0,recursive:!0})}}async function RTi(e,t,n){let o=await(0,f6.readFile)(e);return DTi(o,t,n)}function DTi(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 AAc(e,t,n){return await new Promise(o=>{let i;try{i=(0,ETi.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 PAc(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function RAc(e){return`'${e.replace(/'/g,"''")}'`}var ETi,f6,ATi,jle,xAc,OTi=V(()=>{"use strict";ETi=require("node:child_process"),f6=require("node:fs/promises"),ATi=require("node:os"),jle=require("node:path"),xAc=20*1024*1024;r(TAc,"resolveDefaultClipboardDirectory");r(PTi,"createNodeClipboardImageReader");r(IAc,"readMacClipboardImage");r(CAc,"readLinuxClipboardImage");r(EAc,"readWindowsClipboardImage");r(RTi,"readImageFile");r(DTi,"bufferToClipboardImage");r(AAc,"runCommandBuffer");r(PAc,"appleScriptString");r(RAc,"powershellString")});function NTi(e={}){let t=e.maxBytes??DAc,n=e.platform??process.platform,o=e.runCommand??zAc;return async i=>{let a=UAc(i,t);if(a.byteLength===0)return;let c=FAc(e.stdout,a),u=await jAc({input:i,platform:n,runCommand:o});if(!c&&!u)throw new Error("No text clipboard target accepted the selected text.")}}function FAc(e,t){if(!e)return!1;try{return e.write(`${MAc}${OAc};${t.toString("base64")}${NAc}`),!0}catch{return!1}}async function jAc(e){for(let t of BAc(e.platform))if((await e.runCommand(t.file,t.args,{input:e.input})).exitCode===0)return!0;return!1}function BAc(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",LAc],file:"powershell.exe"}]:[]}function UAc(e,t){let n=Buffer.from(e,"utf8");if(n.byteLength>t)throw new Error(`Clipboard text exceeds ${t} bytes.`);return n}async function zAc(e,t,n){return await new Promise(o=>{let i;try{i=(0,MTi.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 MTi,DAc,OAc,MAc,NAc,LAc,LTi=V(()=>{"use strict";MTi=require("node:child_process"),DAc=1024*1024,OAc="c",MAc="\x1B]52;",NAc="\x07",LAc="Set-Clipboard -Value ([Console]::In.ReadToEnd())";r(NTi,"createNodeClipboardTextWriter");r(FAc,"writeOsc52");r(jAc,"writeNativeClipboardText");r(BAc,"nativeClipboardCommands");r(UAc,"assertClipboardTextSize");r(zAc,"runCommandText")});async function pOt(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 Cy()).listZCodeCustomCommands({env:t,logger:e.logger,workingDirectory:n})}async function FTi(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 Cy()).loadZCodeCustomCommand({env:n,logger:e.logger,name:t,workingDirectory:o})}async function jTi(e){let t=e.env??process.env,n=(e.cwd??process.cwd)();return await(e.listSkills??(await Cy()).listZCodeSkills)({env:t,logger:e.logger,workingDirectory:n})}async function BTi(e){let t=e.env??process.env,n=(e.cwd??process.cwd)();return(await(e.listSessions??(await Cy()).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 UTi(e){try{return await e.getSessionMetadata?.()??{}}catch(t){if($Ac(t))throw t;return{}}}function $Ac(e){return e instanceof Error?e.name==="SqliteSessionMigrationError":!1}var S5n=V(()=>{"use strict";FX();r(pOt,"listCustomCommandsForTui");r(FTi,"loadCustomCommandForTui");r(jTi,"listSkillsForTui");r(BTi,"listSessionsForTui");r(UTi,"loadInitialTuiSessionMetadata");r($Ac,"isStartupGateError")});function zTi(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 $Ti=V(()=>{"use strict";r(zTi,"createTuiSessionEventRelay")});async function w5n(e){let t=await e.listModels?.()??[];return{locale:e.getLocale?.(),model:e.getModel?.(),theme:e.getTheme?.(),thoughtLevel:e.getThoughtLevel?.(),modelOptions:t,effortOptions:await $Te(e)??[],loginRequired:!t.some(n=>!n.disabledReason)}}var qTi,WTi=V(()=>{"use strict";XDt();r(w5n,"readTuiSessionMetadata");qTi=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,(vBn(),cMr(),{collectChildSessionIds:ZPt,projectSubagents:YPt,projectChildEvents:e=>new M7().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.readSessionDatabasePath=async()=>await(await $zTuiGetApp()).readSessionDatabasePath?.(),$zTuiBridge.listWorkspacePathSuggestions=async $zWorkspaceRequest=>{let $zWorkspaceApp=await $zTuiGetApp();await $zWorkspaceApp.readExecutionState();let $zWorkspaceDirectory=$zWorkspaceApp.runtime?.workingDirectory;return $zWorkspaceDirectory?await mIi({workspaceDirectory:$zWorkspaceDirectory})($zWorkspaceRequest):{items:[],truncated:!1}},$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 w5n(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 $Te(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 HTi(e,t,n,o){let i=e.env??process.env,a=(e.cwd??process.cwd)(),c=(e.loadDotenv??nP)({cwd:a,env:i});if(c.error)throw new Error(`Failed to load environment file: ${c.path}`,{cause:c.error});let u=await sOt(n,a,i,e),f=e.createZCodeApp?void 0:await Cy(),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 v=_?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(v,e.skipUserConfig?{}:{standalone:{...UMe(),...e.userConfigPath?{legacyCliUserConfigFilePath:e.userConfigPath}:{}}});let k=await o.providerRegistryRuntimePromise,I=k?.modelSelectionConfigRepository?await k.modelSelectionConfigRepository.read():k?.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:v,configuredDefaultModelSelection:I,createAppFactory:h,providerRegistryRuntime:k,sessionId:u,workingDirectory:a}}var VTi,GTi=V(()=>{"use strict";FX();Kne();Mit();p5n();VTi=r(()=>({providerEndpointRoutingPort:void 0,providerRegistryRuntimePromise:void 0,shutdownTelemetry:void 0}),"createTuiProcessRuntimeState");r(HTi,"prepareTuiAppRuntime")});async function JTi(e,t){let n=e.env??process.env,o=(e.cwd??process.cwd)(),i=(e.loadDotenv??nP)({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 Cy()).loginZCodeCli)({abortSignal:t?.abortSignal,env:n,onAuthorizeUrl:t?.onAuthorizeUrl})}async function KTi(e,t){let n=e.env??process.env,o=(e.cwd??process.cwd)(),i=(e.loadDotenv??nP)({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 Cy()).loginBigmodelCodingPlan)({abortSignal:t?.abortSignal,env:n,onAuthorizeUrl:t?.onAuthorizeUrl})}async function ZTi(e,t){return await(e.configureCodingPlanApiKey??(await Cy()).configureCodingPlanApiKey)({apiKey:t.apiKey,env:e.env??process.env,providerId:t.providerId})}async function YTi(e){let t=e.env??process.env,n=(e.cwd??process.cwd)(),o=(e.loadDotenv??nP)({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 Cy()).logoutZCodeCli)({env:t})}var XTi=V(()=>{"use strict";FX();Kne();r(JTi,"loginForTui");r(KTi,"loginBigmodelForTui");r(ZTi,"configureApiKeyForTui");r(YTi,"logoutForTui")});function VTe(e,t){return e.runtime?.getPlanEnabled?.()?"plan":e.getMode?.()??t}var QTi,eIi,SW,k5n=V(()=>{"use strict";QTi={},eIi=r(e=>({current:e,override:e}),"createCliModeState"),SW=r(e=>e.current??e.override??"build","currentCliMode");r(VTe,"readTuiMode")});function x5n(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 tIi=V(()=>{"use strict";r(x5n,"withTuiMetadata")});function nIi(e,t,n,o={continueSession:!1},i,a,c=E1t,u,f=!1,h="off",_,v,S=jX){let k,I=i,C=VTi(),R,D=new WeakMap,B=new WeakMap,F,z=Math.max(1,Math.trunc(e.shutdownCleanupTimeoutMs??dtt)),$={requestPermission:r(async(lt,Oe)=>{let At=F;return At?await At(lt,Oe):{decision:"deny",reason:`No interactive approval handler configured for ${lt.toolName}`,resolvedAt:new Date}},"requestPermission")},q=r(async(lt=k)=>{if(!lt)return;let Oe=lt,At=D.get(Oe);At||(At=(async()=>{await e4(async()=>lt.close?.(),z),await e4(async()=>B.get(Oe)?.close(),z)})(),D.set(Oe,At)),await At},"closeApp"),J=zTi({currentRuntime:r(()=>k?.runtime,"currentRuntime"),readSubscriber:oOt}),ne=r(async lt=>{let Oe=k,At=await lt();try{await At.readExecutionState()}catch($zResumeCandidateError){await q(At);throw $zResumeCandidateError}return k=At,Oe&&Oe!==At&&await q(Oe),J.reattach(),t.current=VTe(k,SW(t)),k},"replaceApp"),se=r(async lt=>{if(R)throw new Error("TUI prompt handler is closed");let{appEnv:Oe,configuredDefaultModelSelection:At,createAppFactory:pt,providerRegistryRuntime:He,sessionId:De,workingDirectory:vt}=await HTi(e,n,lt,C),Ve=C.providerEndpointRoutingPort,We=nOt({browserExecutable:v,browserUse:_},e),ft;try{ft=await pt({modelSelectionMode:"cli-default",browserControlPort:We?.browserControlPort,env:Oe,projectConfigPath:e.projectConfigPath,...Ve?{providerEndpointRoutingPort:Ve}:{},providerRegistry:He.runtime.registryService,configuredDefaultModelSelection:At,...He.providerRuntimeHeadersPort?{providerRuntimeHeadersPort:He.providerRuntimeHeadersPort}:{},resume:De!==void 0,runtimeConfig:{...t.override?{mode:t.override}:{},...u?{toolDisallowlist:u}:{},toolSearch:{mode:h},...f?{midConversationSystem:{mode:"force"}}:{},...YDt(S),modelStreaming:"on",titleGeneration:QTi,workingDirectory:vt},permissionBroker:$,sessionId:De,skipUserConfig:e.skipUserConfig,uiDetectedLocale:a,uiLocale:I,userConfigPath:e.userConfigPath,version:n})}catch(kt){throw await e4(async()=>We?.close(),z),kt}if(We&&B.set(ft,We),R)throw await q(ft),new Error("TUI prompt handler is closed");return ft},"createApp"),xe=r(async()=>(k??=await se(o),t.current=VTe(k,SW(t)),k),"getApp"),ue=r(async lt=>await ne(async()=>await se(lt?{continueSession:!1,resumeSessionId:lt}:{continueSession:!0})),"resumeApp"),Ie=r(async()=>await ne(async()=>await se({continueSession:!1})),"newApp"),Ue=r(async lt=>{if(t.override=lt,k){let Oe=k;if(Oe.setMode){let At=await Oe.setMode(lt);return t.current=VTe(Oe,At.mode),t.current}Oe.runtime.updateConfig({mode:lt})}return t.current=k?VTe(k,lt):lt,t.current},"setCliMode"),Me=N$e({forkApp:r(async lt=>{let At=await(await xe()).forkFromCheckpoint?.({targetCheckpointId:lt});if(!At)throw new Error("Forking is not available in this client.");return await ne(async()=>await se({continueSession:!1,resumeSessionId:At.forkedSessionId})),{copiedMessageCount:At.copiedMessageCount,forkedSessionId:At.forkedSessionId,response:`${At.response}
|
|
15698
|
+
Switched to forked session ${At.forkedSessionId}.`,restoredFileCount:At.restoredFileCount??At.restoredFiles?.length??0}},"forkApp"),getApp:xe,getMode:r(()=>SW(t),"getMode"),getLocale:r(()=>k?.getLocale?.()??Dzn(I,a)??c,"getLocale"),hasSelectableModels:$xi(xe),listCustomCommands:r(()=>pOt(e),"listCustomCommands"),listSessions:r(()=>BTi(e),"listSessions"),listSkills:r(()=>jTi(e),"listSkills"),configureApiKey:r(lt=>ZTi(e,lt),"configureApiKey"),login:r(lt=>JTi(e,lt),"login"),loginBigmodel:r(lt=>KTi(e,lt),"loginBigmodel"),loadCustomCommand:r(lt=>FTi(e,lt),"loadCustomCommand"),newApp:Ie,recordInputHistory:r(async(lt,Oe)=>{await k?.recordInputHistory?.(lt,Oe)},"recordInputHistory"),resumeApp:ue,saveDefaultModelSelection:r(async lt=>{let Oe=await C.providerRegistryRuntimePromise;if(!Oe?.modelSelectionConfigRepository)throw new Error("Default model configuration storage is unavailable.");await Oe.modelSelectionConfigRepository.saveConfiguredDefault(lt)},"saveDefaultModelSelection"),logout:r(()=>YTi(e),"logout"),setLocale:r(async lt=>{if(k?.setLocale){let At=await k.setLocale(lt);return I=lt,At}return I=lt,{configPath:(await Yve(e.userConfigPath??aj(),lt)).path,locale:Dzn(lt,a)??"en-US",requestedLocale:lt}},"setLocale"),setMode:Ue,workflowMode:S}),ut=r(async(lt,Oe)=>{let At=F;F=Oe.requestPermission;try{let pt=await Me(lt,Oe);return k?{...pt,...await w5n(await xe())}:pt}finally{F=At}},"submitPrompt");return ut.setMode=async lt=>({mode:await Ue(lt)}),ut.sendInput=async(lt,Oe)=>{let At=F;F=Oe?.requestPermission;try{let pt=Lle(typeof lt=="string"?lt:lt.text);if(pt?.type==="known"&&(pt.name==="model"||pt.name==="effort"))return{kind:"command_result",result:await ut(lt,{...Oe,abortSignal:Oe?.abortSignal??new AbortController().signal})};let He=await xe();if(He.sendInput){let De=await He.sendInput(lt,Oe);return De.kind!=="started_turn"?De:x5n(await(De.result??De.completion),He,SW(t))}return x5n(await He.submitPrompt(lt,Oe),He,SW(t))}finally{F=At}},ut.listSkills=async()=>await jTi(e),ut.$zReadProviderRegistryRuntime=()=>C.providerRegistryRuntimePromise,qTi(ut,xe),ut.subscribeSessionEvents=lt=>{let Oe=J.addSink(lt);return xe().then(()=>J.reattach(),()=>{}),Oe},ut.getMainSessionId=()=>{let Oe=k?.runtime?.getSessionId?.();return typeof Oe=="string"&&Oe.length>0?Oe:void 0},ut.close=async()=>{R??=(async()=>{await q(),await e4(async()=>C.shutdownTelemetry?.(),z),(await C.providerRegistryRuntimePromise)?.dispose()})(),await R},ut}var rIi=V(()=>{"use strict";tb();aL();tOt();Ozn();l5n();iOt();$Ti();WTi();GTi();Uhe();XTi();S5n();k5n();s5n();tIi();UX();r(nIi,"createTuiSubmitPrompt")});var oIi,iIi,F1,WX,sR,sIi,aIi,qAc,WAc,cIi,lIi,VAc,HAc,GAc,JAc,KAc,ZAc,uIi=V(()=>{"use strict";oIi=require("node:crypto"),iIi=require("node:fs"),F1=require("node:fs/promises"),WX=require("node:os"),sR=require("node:path"),sIi=require("node:url"),aIi="zcode-tui-runtime/",qAc=`${aIi}manifest.json`,WAc="node_modules/@zcode/tui/dist/index.js",cIi="manifest.json",lIi=r(async()=>{let e=await import("node:sea");if(!e.isSea())return await import("@zcode/tui");let t=await VAc(e);return await import((0,sIi.pathToFileURL)((0,sR.join)(t,WAc)).href)},"loadTuiRuntime"),VAc=r(async e=>{let t=HAc(e),n=(0,sR.join)(JAc(),"0.17.1",t.target,t.hash),o=(0,sR.join)(n,cIi);if(await GAc(o,t))return n;let i=`${n}.tmp-${process.pid}-${Date.now()}`;await(0,F1.rm)(i,{force:!0,recursive:!0}),await(0,F1.mkdir)(i,{recursive:!0});for(let a of t.files){let c=e.getRawAsset(`${aIi}${a.path}`),u=Buffer.from(c);if((0,oIi.createHash)("sha256").update(u).digest("hex")!==a.sha256)throw new Error(`SEA TUI asset hash mismatch for ${a.path}`);let h=(0,sR.join)(i,a.path);await(0,F1.mkdir)((0,sR.dirname)(h),{recursive:!0}),await(0,F1.writeFile)(h,u),await(0,F1.chmod)(h,a.mode??ZAc(a.path))}return await(0,F1.writeFile)(KAc(i),JSON.stringify(t,null,2)),await(0,F1.rm)(n,{force:!0,recursive:!0}),await(0,F1.mkdir)((0,sR.dirname)(n),{recursive:!0}),await(0,F1.rename)(i,n),n},"ensureSeaTuiRuntime"),HAc=r(e=>{let t=e.getAsset(qAc,"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"),GAc=r(async(e,t)=>{if(!(0,iIi.existsSync)(e))return!1;try{let n=JSON.parse(await(0,F1.readFile)(e,"utf8"));return n.hash===t.hash&&n.target===t.target}catch{return!1}},"isCacheCurrent"),JAc=r(()=>{let e=(0,WX.homedir)();return(0,WX.platform)()==="darwin"&&e?(0,sR.join)(e,"Library","Caches","zcode","sea-assets"):(0,WX.platform)()==="win32"?(0,sR.join)(process.env.LOCALAPPDATA??(0,sR.join)(e||(0,WX.tmpdir)(),"AppData","Local"),"zcode","Cache","sea-assets"):(0,sR.join)(process.env.XDG_CACHE_HOME??(0,sR.join)(e||(0,WX.tmpdir)(),".cache"),"zcode","sea-assets")},"cacheBaseDirectory"),KAc=r(e=>(0,sR.join)(e,cIi),"markerPathForDirectory"),ZAc=r(e=>/\.(?:dll|dylib|node|so)$/i.test(e)?493:420,"modeForPath")});function dIi({deps:e,options:t,workingDirectory:n}){let o=Hm({cliOverrides:YAc(t.locale),env:e.env??process.env,projectConfigPath:e.projectConfigPath,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,workingDirectory:n});return UU(o.config.ui.locale,t.detectedLocale)}var YAc,pIi=V(()=>{"use strict";tb();aL();YAc=r(e=>e?{ui:{locale:e}}:void 0,"localeCliOverrides");r(dIi,"resolveTuiStartupLocale")});function mIi(e){let t=e.fileSystemPort??EJ(),n=(0,kL.resolve)(e.workspaceDirectory);return require(require("node:path").join(__dirname,"cli-config.cjs")).withRecursiveWorkspacePathSuggestions(async o=>{let i=nPc(o.token);if(!i)return{items:[],truncated:!1};let a=(0,kL.resolve)(n,i.directoryToken);if(!sPc(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"&&tPc.has(h.name))return[];if(!i.query.startsWith(".")&&h.name.startsWith("."))return[];if(!rPc(h.name,i.query))return[];let _=iPc(n,h.path);return _?[{kind:h.kind,path:h.kind==="directory"?`${_}/`:_}]:[]}).sort((h,_)=>oPc(h,_,i.query)),f=Math.max(1,Math.floor(o.limit??XAc));return{items:u.slice(0,f),truncated:u.length>f}}catch{return{items:[],truncated:!1}}},{workspaceDirectory:n,fileSystemPort:t,excludedDirectories:tPc})}function nPc(e){let t=e.replace(/^@/u,"");if(t.startsWith("/")||t.startsWith("\\")||(0,kL.isAbsolute)(t)||ePc.test(t))return;let n=t.replace(QAc,"/");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 rPc(e,t){return t.length===0?!0:e.toLowerCase().includes(t.toLowerCase())}function oPc(e,t,n){if(e.kind!==t.kind)return e.kind==="directory"?-1:1;let o=fIi(e.path),i=fIi(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 fIi(e){let t=e.endsWith("/")?e.slice(0,-1):e,n=t.lastIndexOf("/");return n<0?t:t.slice(n+1)}function iPc(e,t){let n=(0,kL.relative)(e,t);if(!(!n||n.startsWith("..")||(0,kL.isAbsolute)(n)))return n.split(kL.sep).join("/")}function sPc(e,t){let n=(0,kL.relative)(e,t);return n===""||!n.startsWith("..")&&!(0,kL.isAbsolute)(n)}var kL,XAc,QAc,ePc,tPc,hIi=V(()=>{"use strict";p_e();kL=require("node:path"),XAc=50,QAc=/[\\/]+/gu,ePc=/^[a-zA-Z]:[\\/]/u,tPc=new Set([".bzr",".git",".hg",".jj",".sl",".svn","node_modules"]);r(mIi,"createWorkspacePathSuggestionProvider");r(nPc,"parseWorkspacePathToken");r(rPc,"matchesPathQuery");r(oPc,"compareWorkspacePathSuggestion");r(fIi,"basenameFromSuggestion");r(iPc,"toWorkspaceRelativePath");r(sPc,"isPathInside")});async function _Ii(e){let t=e.maxOutputBytes??uPc,n=e.timeoutMs??lPc,i=await(e.runCommand??pPc)(aPc,["-C",e.workspaceDirectory,...cPc],{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===dPc))return a}async function pPc(e,t,n){return await new Promise(o=>{let i;try{i=(0,gIi.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 gIi,aPc,cPc,lPc,uPc,dPc,yIi=V(()=>{"use strict";gIi=require("node:child_process"),aPc="git",cPc=["symbolic-ref","--quiet","--short","HEAD"],lPc=750,uPc=512,dPc="HEAD";r(_Ii,"resolveWorkspaceGitBranch");r(pPc,"runGitCommand")});var vIi,bIi=V(()=>{"use strict";ti();OTi();LTi();tOt();Uhe();S5n();rIi();uIi();pIi();hIi();yIi();k5n();UX();vIi=r(async(e,t,n,o,i,a,c,u=!1,f="off",h=jX)=>{try{let _=eIi(i),v=n.runTui??(await lIi()).runTui,S=(n.cwd??process.cwd)(),k=n.env??process.env,I=PDe(k)==="development",C=dIi({deps:n,options:t,workingDirectory:S}),R=nIi(n,_,o,a,t.locale,t.detectedLocale,C,c,u,f,t.browserUse,t.browserExecutable,h),D=ptt({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 v({loadStartupOptions:r(async()=>{let[B,F,z]=await Promise.all([UTi(R),pOt(n).catch(()=>{}),(n.resolveWorkspaceGitBranch??_Ii)({workspaceDirectory:S}).catch(()=>{})]);return{initialMode:SW(_),initialModel:B.model,initialThoughtLevel:B.thoughtLevel,loginRequired:B.loginRequired,locale:B.locale??C,theme:B.theme??"auto",modelOptions:B.modelOptions,effortOptions:B.effortOptions,slashCommands:n5n(F,{workflowMode:h}),workspaceGitBranch:z}},"loadStartupOptions"),locale:C,developerMode:I,version:o,workspaceDirectory:S,noColor:t.noColor,readClipboardImage:n.readClipboardImage??PTi(),readDefaultModel:R.readDefaultModel,setDefaultModel:R.setDefaultModel,reloadModelOptions:R.reloadModelOptions,listModelOptions:R.listModelOptions,listWorkspacePathSuggestions:R.listWorkspacePathSuggestions,listMcpServers:R.listMcpServers,readSubagents:R.readSubagents,readSubagentTranscript:R.readSubagentTranscript,listWorkflowRuns:R.listWorkflowRuns,replayWorkflowRuns:R.replayWorkflowRuns,reduceWorkflowRuns:($zState,$zEvent)=>{qRr();return rst($zState,$zEvent)},retuneWorkflowConcurrency:R.retuneWorkflowConcurrency,listSavedWorkflows:R.listSavedWorkflows,readSavedWorkflow:R.readSavedWorkflow,saveWorkflowRun:R.saveWorkflowRun,startSavedWorkflow:R.startSavedWorkflow,getMainSessionId:R.getMainSessionId,writeClipboardText:n.writeClipboardText??NTi({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,readSessionDatabasePath:R.readSessionDatabasePath,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{D(),await R.close?.()}}catch(_){let v=_ instanceof Error?_.message:String(_);return e.stderr.write(`Error: ${v}
|
|
15699
15699
|
`),t.verbose&&_ instanceof Error&&_.stack&&e.stderr.write(`${_.stack}
|
|
15700
15700
|
`),1}},"runTuiCommand")});var wIi={};e0(wIi,{run:()=>MPc});var wW,fPc,mPc,hPc,gPc,_Pc,yPc,vPc,bPc,SPc,wPc,mOt,T5n,kPc,xPc,SIi,TPc,IPc,CPc,EPc,APc,PPc,RPc,fOt,DPc,OPc,MPc,kIi=V(()=>{"use strict";Ln();Ohe();ttt();Zbe();Ff();Ff();aL();Kne();SJo();gki();Ozn();FX();wki();Pki();Mki();Fzn();ZXt();dQt();Uki();fTi();CTi();f5n();bIi();UX();wW="0.17.1",fPc="--target requires non-empty text.",mPc="yolo",hPc="--force-mcs can only be used with --prompt, --target, or tui.",gPc="--target-replace requires --target.",_Pc='--target cannot be used with --prompt. Use either --target <objective> or --prompt "/goal <objective>".',yPc="--browser-executable requires --browser-use=headless.",vPc="--browser-use=headless can only be used with --prompt, --target, or tui.",bPc="--surface can only be used with --prompt, --target, app-server, or agent-server.",SPc="--memory-bench can only be used with -p/--prompt.",wPc=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"),mOt=r(e=>e[0]??"tui","commandName"),T5n=r(e=>typeof e.prompt=="string"||e.targetRequest!==void 0||mOt(e.positionals)==="tui","isForceMcsSupportedInvocation"),kPc=r(e=>{let t=mOt(e.positionals);return typeof e.prompt=="string"||e.targetRequest!==void 0||t==="app-server"||t==="agent-server"},"isPresentationSurfaceSupportedInvocation"),xPc=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"),SIi=["text","json","stream-json"],TPc=r(e=>{if(e!==void 0){if(SIi.includes(e))return e;throw new Error(`--output-format must be one of ${SIi.join(", ")} (received: ${e}).`)}},"normalizeOutputFormat"),IPc=r(e=>{if(e!==void 0){if(kze(e))return e;throw new Error(Yj().cli.errors.localeUnsupported(e))}},"normalizeLocaleOption"),CPc=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"),EPc=r(e=>{if(e!==void 0){if(e.toLowerCase()==="headless")return"headless";throw new Error(`Unsupported --browser-use value: ${e}. Supported value: headless.`)}},"normalizeBrowserUse"),APc=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"),PPc=r(e=>{let t=e.target,n=e["target-replace"]===!0;if(t===void 0){if(n)throw new Error(gPc);return}let o=t.trim();if(o.length===0)throw new Error(fPc);return{objective:o,replaceExisting:n}},"normalizeTargetRequest"),RPc=r(e=>e.replaceExisting?`/goal replace ${e.objective}`:`/goal ${e.objective}`,"buildHeadlessTargetCommand"),fOt=r((e,t,n)=>{e.write(bJo(wW,t,n))},"writeHelp"),DPc=r((e,t,n)=>{let o=qLn(),i={cli:{name:uhr,processName:KXt,version:wW},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=>{Ipo();return Hm($zOptions)})};if(t.json)return e.stdout.write(pg(i)),i.configuration.ok?0:1;let a=zLn(e.stdout,t.noColor);return e.stdout.write(`${$Ln.bold("zcode doctor",a)}
|
|
15701
15701
|
`),e.stdout.write(`version: ${i.cli.version}
|