zcode-app-cli 3.11.2-21 → 3.11.2-23
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/package.json
CHANGED
package/vendor/extraction.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"appVersion": "3.11.2",
|
|
3
3
|
"cliVersion": "0.16.5",
|
|
4
|
-
"extractedAt": "2026-09-
|
|
4
|
+
"extractedAt": "2026-09-11T10:26:25.347Z",
|
|
5
5
|
"sha512": "4UAMZSP9ZWBrnb8wGaP39rb5dB5ikPx4aYPXKXGea1Vmd6L6vGma3rXwRxKbhBxgsCIE9jv6tmrdSL60RrzGcA==",
|
|
6
6
|
"source": "https://cdn-zcode.z.ai/zcode/electron/releases/3.11.2/linux-x64/ZCode-3.11.2-linux-x64.deb",
|
|
7
7
|
"runtimeCapabilities": {
|
|
@@ -89,6 +89,11 @@
|
|
|
89
89
|
"requirement": "required",
|
|
90
90
|
"status": "applied"
|
|
91
91
|
},
|
|
92
|
+
{
|
|
93
|
+
"id": "model-catalog-reload",
|
|
94
|
+
"requirement": "required",
|
|
95
|
+
"status": "applied"
|
|
96
|
+
},
|
|
92
97
|
{
|
|
93
98
|
"id": "goal-failure-pause",
|
|
94
99
|
"requirement": "optional",
|
|
@@ -5,8 +5,8 @@ import { constants as constants$1, homedir } from "node:os";
|
|
|
5
5
|
import { basename, dirname, extname, isAbsolute, join, posix, resolve, sep, win32 } from "node:path";
|
|
6
6
|
import { access, copyFile, link, mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
7
7
|
import { randomUUID } from "node:crypto";
|
|
8
|
-
import { Box, CombinedAutocompleteProvider, Container, Editor, Image, Input, Markdown, ProcessTerminal, ScrollView, SelectList, Spacer, Text, TuiAltScreen, TuiMainScreen, VStack, decodeKittyPrintable, getKeybindings, isKeyRelease, isViewportTUI, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
|
|
9
8
|
import { isDeepStrictEqual } from "node:util";
|
|
9
|
+
import { Box, CombinedAutocompleteProvider, Container, Editor, Image, Input, Markdown, ProcessTerminal, ScrollView, SelectList, Spacer, Text, TuiAltScreen, TuiMainScreen, VStack, decodeKittyPrintable, getKeybindings, isKeyRelease, isViewportTUI, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
|
|
10
10
|
var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
|
|
11
11
|
var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
|
|
12
12
|
//#endregion
|
|
@@ -213,7 +213,9 @@ async function readUserConfig(env = process.env) {
|
|
|
213
213
|
async function updateUserConfig(update, env = process.env) {
|
|
214
214
|
const configPath = userConfigPath(env);
|
|
215
215
|
const config = await readUserConfig(env);
|
|
216
|
+
const before = JSON.stringify(config);
|
|
216
217
|
update(config);
|
|
218
|
+
if (JSON.stringify(config) === before) return configPath;
|
|
217
219
|
const temporaryPath = join(dirname(configPath), `.${basename(configPath)}.${process.pid}.${randomUUID()}.tmp`);
|
|
218
220
|
let file;
|
|
219
221
|
try {
|
|
@@ -317,6 +319,456 @@ async function missingCodingPlanKey(options = {}) {
|
|
|
317
319
|
return `Model access is not configured for ${providerId}. Run /login or /setup in zcode, or configure its API key before sending a prompt. No model request was sent.`;
|
|
318
320
|
}
|
|
319
321
|
//#endregion
|
|
322
|
+
//#region src/model-catalog-refresh.ts
|
|
323
|
+
const MODEL_CATALOG_REFRESH_TTL_MS = 360 * 60 * 1e3;
|
|
324
|
+
const MODEL_CATALOG_URL_PATH = "/api/v1/client/configs";
|
|
325
|
+
const DEFAULT_TIMEOUT_MS = 5e3;
|
|
326
|
+
const PROVIDER_BASE_URLS = {
|
|
327
|
+
zai: "https://api.z.ai/api/anthropic",
|
|
328
|
+
bigmodel: "https://open.bigmodel.cn/api/anthropic"
|
|
329
|
+
};
|
|
330
|
+
const MODALITIES = /* @__PURE__ */ new Set([
|
|
331
|
+
"text",
|
|
332
|
+
"audio",
|
|
333
|
+
"image",
|
|
334
|
+
"video",
|
|
335
|
+
"pdf"
|
|
336
|
+
]);
|
|
337
|
+
const EFFORTS = /* @__PURE__ */ new Set([
|
|
338
|
+
"low",
|
|
339
|
+
"medium",
|
|
340
|
+
"high",
|
|
341
|
+
"xhigh",
|
|
342
|
+
"max"
|
|
343
|
+
]);
|
|
344
|
+
function enabledEnvironmentFlag$1(value) {
|
|
345
|
+
if (value === void 0) return false;
|
|
346
|
+
return ![
|
|
347
|
+
"",
|
|
348
|
+
"0",
|
|
349
|
+
"false",
|
|
350
|
+
"no",
|
|
351
|
+
"off"
|
|
352
|
+
].includes(value.trim().toLowerCase());
|
|
353
|
+
}
|
|
354
|
+
function modelCatalogRefreshDisabled(env = process.env) {
|
|
355
|
+
return enabledEnvironmentFlag$1(env.CI) || enabledEnvironmentFlag$1(env.ZCODE_DISABLE_MODEL_CATALOG_REFRESH);
|
|
356
|
+
}
|
|
357
|
+
function modelCatalogCachePath(env = process.env, platform = process.platform, fallbackHome = homedir()) {
|
|
358
|
+
const path = platform === "win32" ? win32 : posix;
|
|
359
|
+
const configuredHome = (platform === "win32" ? env.USERPROFILE : env.HOME)?.trim();
|
|
360
|
+
return path.join(configuredHome || fallbackHome, ".zcode", "cli", "model-catalog.json");
|
|
361
|
+
}
|
|
362
|
+
function resolveModelCatalogEndpoint(baseUrl, env = process.env, platform = process.platform, arch = process.arch) {
|
|
363
|
+
const url = new URL(baseUrl);
|
|
364
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error("Model catalog endpoint must use HTTP or HTTPS.");
|
|
365
|
+
url.pathname = `${url.pathname.replace(/\/+$/u, "")}${MODEL_CATALOG_URL_PATH}`;
|
|
366
|
+
url.hash = "";
|
|
367
|
+
url.searchParams.set("platform", `${platform}-${arch}`);
|
|
368
|
+
const appVersion = env.ZCODE_APP_CLI_VERSION?.trim() || "";
|
|
369
|
+
if (appVersion) url.searchParams.set("app_version", appVersion);
|
|
370
|
+
return url.toString();
|
|
371
|
+
}
|
|
372
|
+
function catalogEndpoint(options) {
|
|
373
|
+
const env = options.env ?? process.env;
|
|
374
|
+
return resolveModelCatalogEndpoint(options.baseUrl, {
|
|
375
|
+
...env,
|
|
376
|
+
ZCODE_APP_CLI_VERSION: env.ZCODE_APP_CLI_VERSION?.trim() || options.currentVersion
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
function toModelId(value) {
|
|
380
|
+
return value.trim().toLowerCase();
|
|
381
|
+
}
|
|
382
|
+
function isRecord$2(value) {
|
|
383
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
384
|
+
}
|
|
385
|
+
function modelId(value) {
|
|
386
|
+
return typeof value === "string" && /^[a-z0-9][a-z0-9._-]*$/iu.test(value.trim());
|
|
387
|
+
}
|
|
388
|
+
function positiveInteger$1(value) {
|
|
389
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
|
|
390
|
+
}
|
|
391
|
+
function parseModalities(value) {
|
|
392
|
+
if (!Array.isArray(value)) return void 0;
|
|
393
|
+
const valid = value.filter((item) => typeof item === "string" && MODALITIES.has(item));
|
|
394
|
+
return valid.length > 0 || value.length === 0 ? [...new Set(valid)] : void 0;
|
|
395
|
+
}
|
|
396
|
+
function parseCatalog(data) {
|
|
397
|
+
if (!isRecord$2(data)) return {};
|
|
398
|
+
const builtinModels = [];
|
|
399
|
+
const builtinProviders = [];
|
|
400
|
+
const candidates = Array.isArray(data.builtinModels) ? [...data.builtinModels] : [];
|
|
401
|
+
for (const provider of Array.isArray(data.providers) ? data.providers : []) {
|
|
402
|
+
if (!isRecord$2(provider) || provider.schema !== "anthropic" || !Array.isArray(provider.models)) continue;
|
|
403
|
+
const family = provider.id === "z-ai" ? "zai" : provider.id === "bigmodel" ? "bigmodel" : void 0;
|
|
404
|
+
if (!family || typeof provider.baseUrl !== "string" || provider.baseUrl.trim().replace(/\/+$/u, "") !== PROVIDER_BASE_URLS[family]) continue;
|
|
405
|
+
candidates.push(...provider.models);
|
|
406
|
+
builtinProviders.push({
|
|
407
|
+
id: `builtin:${family}-coding-plan`,
|
|
408
|
+
schema: "anthropic",
|
|
409
|
+
models: provider.models.flatMap((model) => isRecord$2(model) && modelId(model.modelId) ? [model.modelId] : [])
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
const seen = /* @__PURE__ */ new Set();
|
|
413
|
+
for (const value of candidates) {
|
|
414
|
+
if (!isRecord$2(value) || !modelId(value.modelId)) continue;
|
|
415
|
+
const id = toModelId(value.modelId);
|
|
416
|
+
if (seen.has(id)) continue;
|
|
417
|
+
seen.add(id);
|
|
418
|
+
const model = {
|
|
419
|
+
modelId: value.modelId.trim(),
|
|
420
|
+
name: typeof value.name === "string" && value.name.trim() ? value.name.trim() : value.modelId.trim()
|
|
421
|
+
};
|
|
422
|
+
if (positiveInteger$1(value.contextWindow)) model.contextWindow = value.contextWindow;
|
|
423
|
+
if (positiveInteger$1(value.maxCompletionTokens)) model.maxCompletionTokens = value.maxCompletionTokens;
|
|
424
|
+
if (isRecord$2(value.modalities)) {
|
|
425
|
+
const input = parseModalities(value.modalities.input);
|
|
426
|
+
const output = parseModalities(value.modalities.output);
|
|
427
|
+
if (input || output) model.modalities = {
|
|
428
|
+
...input ? { input } : {},
|
|
429
|
+
...output ? { output } : {}
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
if (isRecord$2(value.reasoning) && isRecord$2(value.reasoning.levels)) model.reasoning = {
|
|
433
|
+
levels: value.reasoning.levels,
|
|
434
|
+
...typeof value.reasoning.defaultLevel === "string" ? { defaultLevel: value.reasoning.defaultLevel } : {}
|
|
435
|
+
};
|
|
436
|
+
builtinModels.push(model);
|
|
437
|
+
}
|
|
438
|
+
for (const value of Array.isArray(data.builtinProviders) ? data.builtinProviders : []) {
|
|
439
|
+
if (!isRecord$2(value) || typeof value.id !== "string" || !Array.isArray(value.models)) continue;
|
|
440
|
+
builtinProviders.push({
|
|
441
|
+
id: value.id,
|
|
442
|
+
...typeof value.schema === "string" ? { schema: value.schema } : {},
|
|
443
|
+
models: value.models.filter(modelId).map((id) => id.trim())
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
return {
|
|
447
|
+
builtinModels,
|
|
448
|
+
builtinProviders
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
function usableCatalog(catalog) {
|
|
452
|
+
const ids = new Set(catalog.builtinModels?.map((model) => toModelId(model.modelId)));
|
|
453
|
+
return catalog.builtinProviders?.some((provider) => providerFamilyForBuiltinId(provider.id) !== void 0 && (provider.schema === void 0 || provider.schema === "anthropic") && provider.models.some((id) => ids.has(toModelId(id)))) ?? false;
|
|
454
|
+
}
|
|
455
|
+
function completeModelList(value) {
|
|
456
|
+
return Array.isArray(value) && value.every((model) => isRecord$2(model) && modelId(model.modelId));
|
|
457
|
+
}
|
|
458
|
+
function completeBuiltinLists(value) {
|
|
459
|
+
return completeModelList(value.builtinModels) && Array.isArray(value.builtinProviders) && value.builtinProviders.every((provider) => isRecord$2(provider) && typeof provider.id === "string" && Array.isArray(provider.models) && provider.models.every(modelId));
|
|
460
|
+
}
|
|
461
|
+
async function readCatalogCache(cachePath, endpoint) {
|
|
462
|
+
try {
|
|
463
|
+
const value = JSON.parse(await readFile(cachePath, "utf8"));
|
|
464
|
+
if (!isRecord$2(value) || value.endpoint !== endpoint) return void 0;
|
|
465
|
+
const lastFetchedAt = typeof value.lastFetchedAt === "string" ? value.lastFetchedAt : void 0;
|
|
466
|
+
if (!lastFetchedAt || !Number.isFinite(Date.parse(lastFetchedAt))) return void 0;
|
|
467
|
+
const catalog = parseCatalog(value);
|
|
468
|
+
if (!usableCatalog(catalog)) return void 0;
|
|
469
|
+
return {
|
|
470
|
+
endpoint,
|
|
471
|
+
lastFetchedAt,
|
|
472
|
+
retirementSafe: value.retirementSafe === true && completeBuiltinLists(value),
|
|
473
|
+
builtinModels: catalog.builtinModels,
|
|
474
|
+
builtinProviders: catalog.builtinProviders
|
|
475
|
+
};
|
|
476
|
+
} catch {
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
async function writePrivateJson(path, value) {
|
|
481
|
+
const directory = dirname(path);
|
|
482
|
+
const temporaryPath = join(directory, `.model-catalog.${process.pid}.${randomUUID()}.tmp`);
|
|
483
|
+
await mkdir(directory, {
|
|
484
|
+
recursive: true,
|
|
485
|
+
mode: 448
|
|
486
|
+
});
|
|
487
|
+
try {
|
|
488
|
+
await writeFile(temporaryPath, `${JSON.stringify(value, null, 2)}\n`, {
|
|
489
|
+
encoding: "utf8",
|
|
490
|
+
flag: "wx",
|
|
491
|
+
mode: 384
|
|
492
|
+
});
|
|
493
|
+
await rename(temporaryPath, path);
|
|
494
|
+
} finally {
|
|
495
|
+
await rm(temporaryPath, { force: true }).catch(() => {});
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
function parseRemoteClientConfigs(body) {
|
|
499
|
+
if (!isRecord$2(body) || body.code !== 0) return {};
|
|
500
|
+
const data = body.data;
|
|
501
|
+
const catalog = parseCatalog(data);
|
|
502
|
+
catalog.retirementSafe = isRecord$2(data) && completeBuiltinLists(data) && Array.isArray(data.providers) && data.providers.every((provider) => isRecord$2(provider) && typeof provider.id === "string" && typeof provider.schema === "string" && typeof provider.baseUrl === "string" && completeModelList(provider.models));
|
|
503
|
+
return catalog;
|
|
504
|
+
}
|
|
505
|
+
async function fetchRemoteModelCatalog(options) {
|
|
506
|
+
if (options.signal?.aborted) return {};
|
|
507
|
+
const controller = new AbortController();
|
|
508
|
+
const abort = () => controller.abort(options.signal?.reason);
|
|
509
|
+
if (options.signal?.aborted) abort();
|
|
510
|
+
else options.signal?.addEventListener("abort", abort, { once: true });
|
|
511
|
+
const timeout = setTimeout(() => controller.abort(/* @__PURE__ */ new Error("Model catalog refresh timed out.")), options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
512
|
+
try {
|
|
513
|
+
const url = catalogEndpoint(options);
|
|
514
|
+
const response = await (options.fetcher ?? ((requestUrl, init) => fetch(requestUrl, init)))(url, {
|
|
515
|
+
headers: {
|
|
516
|
+
accept: "application/json",
|
|
517
|
+
"user-agent": `zcode-app-cli/${options.currentVersion}`
|
|
518
|
+
},
|
|
519
|
+
signal: controller.signal
|
|
520
|
+
});
|
|
521
|
+
if (!response.ok) return {};
|
|
522
|
+
return parseRemoteClientConfigs(await response.json());
|
|
523
|
+
} catch {
|
|
524
|
+
return {};
|
|
525
|
+
} finally {
|
|
526
|
+
clearTimeout(timeout);
|
|
527
|
+
options.signal?.removeEventListener("abort", abort);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
async function refreshModelCatalog(options) {
|
|
531
|
+
const env = options.env ?? process.env;
|
|
532
|
+
const cachePath = modelCatalogCachePath(env);
|
|
533
|
+
const now = options.now ?? Date.now();
|
|
534
|
+
if (modelCatalogRefreshDisabled(env) || options.signal?.aborted) return {
|
|
535
|
+
cachePath,
|
|
536
|
+
refreshed: false,
|
|
537
|
+
catalog: null
|
|
538
|
+
};
|
|
539
|
+
let endpoint;
|
|
540
|
+
try {
|
|
541
|
+
endpoint = catalogEndpoint(options);
|
|
542
|
+
} catch {
|
|
543
|
+
return {
|
|
544
|
+
cachePath,
|
|
545
|
+
refreshed: false,
|
|
546
|
+
catalog: null
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
const cached = await readCatalogCache(cachePath, endpoint);
|
|
550
|
+
const existing = cached && Date.parse(cached.lastFetchedAt) <= now ? cached : void 0;
|
|
551
|
+
const age = existing ? now - Date.parse(existing.lastFetchedAt) : Infinity;
|
|
552
|
+
if (existing && age >= 0 && age < 216e5) return {
|
|
553
|
+
cachePath,
|
|
554
|
+
refreshed: false,
|
|
555
|
+
catalog: existing
|
|
556
|
+
};
|
|
557
|
+
const remote = await fetchRemoteModelCatalog(options);
|
|
558
|
+
if (options.signal?.aborted) return {
|
|
559
|
+
cachePath,
|
|
560
|
+
refreshed: false,
|
|
561
|
+
catalog: null
|
|
562
|
+
};
|
|
563
|
+
if (!usableCatalog(remote)) return {
|
|
564
|
+
cachePath,
|
|
565
|
+
refreshed: false,
|
|
566
|
+
catalog: existing ?? null
|
|
567
|
+
};
|
|
568
|
+
const cache = {
|
|
569
|
+
endpoint,
|
|
570
|
+
retirementSafe: remote.retirementSafe === true,
|
|
571
|
+
lastFetchedAt: new Date(now).toISOString(),
|
|
572
|
+
builtinModels: remote.builtinModels ?? [],
|
|
573
|
+
builtinProviders: remote.builtinProviders ?? []
|
|
574
|
+
};
|
|
575
|
+
await writePrivateJson(cachePath, cache).catch(() => {});
|
|
576
|
+
return {
|
|
577
|
+
cachePath,
|
|
578
|
+
refreshed: true,
|
|
579
|
+
catalog: cache
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
function providerFamilyForBuiltinId(builtinId) {
|
|
583
|
+
if (builtinId === "builtin:zai-coding-plan") return "zai";
|
|
584
|
+
if (builtinId === "builtin:bigmodel-coding-plan") return "bigmodel";
|
|
585
|
+
}
|
|
586
|
+
function buildReasoning(model) {
|
|
587
|
+
const options = {};
|
|
588
|
+
for (const [level, value] of Object.entries(model.reasoning?.levels ?? {})) {
|
|
589
|
+
if (!modelId(level) || !isRecord$2(value) || !isRecord$2(value.anthropic)) continue;
|
|
590
|
+
const operations = value.anthropic.set;
|
|
591
|
+
if (!Array.isArray(operations) || operations.length !== 1 || value.anthropic.unset !== void 0) continue;
|
|
592
|
+
const operation = operations[0];
|
|
593
|
+
if (!isRecord$2(operation) || !Array.isArray(operation.path) || operation.path.length !== 2 || operation.path[0] !== "output_config" || operation.path[1] !== "effort" || typeof operation.value !== "string" || !EFFORTS.has(operation.value)) continue;
|
|
594
|
+
options[level] = { anthropic: { effort: operation.value } };
|
|
595
|
+
}
|
|
596
|
+
const levels = Object.keys(options);
|
|
597
|
+
if (!levels.length) return void 0;
|
|
598
|
+
const defaultLevel = model.reasoning?.defaultLevel;
|
|
599
|
+
return {
|
|
600
|
+
enabled: true,
|
|
601
|
+
levels,
|
|
602
|
+
...defaultLevel && levels.includes(defaultLevel) ? { defaultLevel } : {},
|
|
603
|
+
providerOptionsByLevel: options
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
function buildModelEntry(model) {
|
|
607
|
+
const entry = { name: model.name };
|
|
608
|
+
if (typeof model.contextWindow === "number") entry.limit = {
|
|
609
|
+
context: model.contextWindow,
|
|
610
|
+
...typeof model.maxCompletionTokens === "number" ? { output: model.maxCompletionTokens } : {}
|
|
611
|
+
};
|
|
612
|
+
else if (typeof model.maxCompletionTokens === "number") entry.limit = { output: model.maxCompletionTokens };
|
|
613
|
+
if (model.modalities && (model.modalities.input || model.modalities.output)) entry.modalities = {
|
|
614
|
+
...model.modalities.input ? { input: model.modalities.input } : {},
|
|
615
|
+
...model.modalities.output ? { output: model.modalities.output } : {}
|
|
616
|
+
};
|
|
617
|
+
const reasoning = buildReasoning(model);
|
|
618
|
+
if (reasoning) entry.reasoning = reasoning;
|
|
619
|
+
return entry;
|
|
620
|
+
}
|
|
621
|
+
function isOfficialProvider(provider, family) {
|
|
622
|
+
if (provider.kind !== "anthropic" || !isRecord$2(provider.options)) return false;
|
|
623
|
+
const baseURL = provider.options.baseURL;
|
|
624
|
+
return typeof baseURL === "string" && baseURL.trim().replace(/\/+$/u, "") === PROVIDER_BASE_URLS[family];
|
|
625
|
+
}
|
|
626
|
+
function mergeModelEntry(entry, existing) {
|
|
627
|
+
const merged = {
|
|
628
|
+
...entry,
|
|
629
|
+
...existing
|
|
630
|
+
};
|
|
631
|
+
for (const key of ["limit", "modalities"]) if (isRecord$2(entry[key]) && isRecord$2(existing[key])) merged[key] = {
|
|
632
|
+
...entry[key],
|
|
633
|
+
...existing[key]
|
|
634
|
+
};
|
|
635
|
+
return merged;
|
|
636
|
+
}
|
|
637
|
+
function catalogSource(endpoint) {
|
|
638
|
+
if (!endpoint) return "";
|
|
639
|
+
const url = new URL(endpoint);
|
|
640
|
+
url.searchParams.delete("app_version");
|
|
641
|
+
url.searchParams.delete("platform");
|
|
642
|
+
return url.toString();
|
|
643
|
+
}
|
|
644
|
+
async function readManagedCatalog(path, endpoint) {
|
|
645
|
+
try {
|
|
646
|
+
const value = JSON.parse(await readFile(path, "utf8"));
|
|
647
|
+
if (isRecord$2(value) && value.endpoint === endpoint && isRecord$2(value.models)) return {
|
|
648
|
+
endpoint,
|
|
649
|
+
models: Object.fromEntries(Object.entries(value.models).filter((entry) => isRecord$2(entry[1])))
|
|
650
|
+
};
|
|
651
|
+
} catch {}
|
|
652
|
+
return {
|
|
653
|
+
endpoint,
|
|
654
|
+
models: {}
|
|
655
|
+
};
|
|
656
|
+
}
|
|
657
|
+
async function applyRefreshedModelsToConfig(result, env = process.env, protectedModels = []) {
|
|
658
|
+
const catalog = parseCatalog(result.catalog);
|
|
659
|
+
if (!usableCatalog(catalog)) return;
|
|
660
|
+
const age = Date.now() - Date.parse(result.catalog.lastFetchedAt);
|
|
661
|
+
const retire = result.refreshed && result.catalog?.retirementSafe === true && age >= 0 && age < 216e5;
|
|
662
|
+
const managedPath = join(dirname(modelCatalogCachePath(env)), "model-catalog-managed.json");
|
|
663
|
+
const managed = await readManagedCatalog(managedPath, catalogSource(result.catalog?.endpoint ?? ""));
|
|
664
|
+
const beforeManaged = JSON.stringify(managed);
|
|
665
|
+
const modelsByFamily = /* @__PURE__ */ new Map();
|
|
666
|
+
const incompleteFamilies = /* @__PURE__ */ new Set();
|
|
667
|
+
const models = new Map(catalog.builtinModels.map((model) => [toModelId(model.modelId), model]));
|
|
668
|
+
for (const provider of catalog.builtinProviders) {
|
|
669
|
+
const family = providerFamilyForBuiltinId(provider.id);
|
|
670
|
+
if (!family || provider.schema !== void 0 && provider.schema !== "anthropic") continue;
|
|
671
|
+
const familyModels = modelsByFamily.get(family) ?? /* @__PURE__ */ new Map();
|
|
672
|
+
if (!provider.models.length || provider.models.some((id) => !models.has(toModelId(id)))) {
|
|
673
|
+
incompleteFamilies.add(family);
|
|
674
|
+
continue;
|
|
675
|
+
}
|
|
676
|
+
for (const id of provider.models) {
|
|
677
|
+
const model = models.get(toModelId(id));
|
|
678
|
+
if (model) familyModels.set(toModelId(id), buildModelEntry(model));
|
|
679
|
+
}
|
|
680
|
+
modelsByFamily.set(family, familyModels);
|
|
681
|
+
}
|
|
682
|
+
await updateUserConfig((config) => {
|
|
683
|
+
if (!isRecord$2(config.provider)) return;
|
|
684
|
+
const providers = config.provider;
|
|
685
|
+
const selected = new Set(protectedModels.map(toModelId));
|
|
686
|
+
if (typeof config.model === "string") selected.add(toModelId(config.model));
|
|
687
|
+
if (isRecord$2(config.model)) {
|
|
688
|
+
for (const value of Object.values(config.model)) if (typeof value === "string") selected.add(toModelId(value));
|
|
689
|
+
}
|
|
690
|
+
const overrides = isRecord$2(config.modelCatalog) && isRecord$2(config.modelCatalog.overrides) ? config.modelCatalog.overrides : {};
|
|
691
|
+
for (const [providerId, familyModels] of modelsByFamily) {
|
|
692
|
+
const current = providers[providerId];
|
|
693
|
+
if (!isRecord$2(current) || !isOfficialProvider(current, providerId)) continue;
|
|
694
|
+
const currentModels = isRecord$2(current.models) ? current.models : {};
|
|
695
|
+
const merged = { ...currentModels };
|
|
696
|
+
const existingIds = new Map(Object.keys(currentModels).map((id) => [toModelId(id), id]));
|
|
697
|
+
for (const [id, existing] of Object.entries(currentModels)) {
|
|
698
|
+
const reference = `${providerId}/${id}`;
|
|
699
|
+
if (retire && !incompleteFamilies.has(providerId) && !familyModels.has(toModelId(id)) && !selected.has(toModelId(reference)) && !Object.hasOwn(overrides, reference) && isDeepStrictEqual(existing, managed.models[reference])) {
|
|
700
|
+
delete merged[id];
|
|
701
|
+
delete managed.models[reference];
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
for (const [modelId, entry] of familyModels) {
|
|
705
|
+
const id = existingIds.get(modelId) ?? modelId;
|
|
706
|
+
const existing = merged[id];
|
|
707
|
+
if (Object.hasOwn(merged, id) && !isRecord$2(existing)) continue;
|
|
708
|
+
const reference = `${providerId}/${id}`;
|
|
709
|
+
const owned = !Object.hasOwn(merged, id) || isDeepStrictEqual(existing, managed.models[reference]);
|
|
710
|
+
merged[id] = owned ? entry : mergeModelEntry(entry, existing);
|
|
711
|
+
if (owned) managed.models[reference] = entry;
|
|
712
|
+
}
|
|
713
|
+
providers[providerId] = {
|
|
714
|
+
...current,
|
|
715
|
+
models: merged
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
config.provider = providers;
|
|
719
|
+
}, env);
|
|
720
|
+
if (JSON.stringify(managed) !== beforeManaged) await writePrivateJson(managedPath, managed);
|
|
721
|
+
}
|
|
722
|
+
/** Download in the background; sync only at a model-selection boundary. */
|
|
723
|
+
var ModelCatalogRefresh = class {
|
|
724
|
+
options;
|
|
725
|
+
controller = new AbortController();
|
|
726
|
+
pending;
|
|
727
|
+
result;
|
|
728
|
+
nextRefreshAt = 0;
|
|
729
|
+
timer;
|
|
730
|
+
constructor(options) {
|
|
731
|
+
this.options = options;
|
|
732
|
+
}
|
|
733
|
+
start() {
|
|
734
|
+
if (this.controller.signal.aborted || this.pending || Date.now() < this.nextRefreshAt || modelCatalogRefreshDisabled(this.options.env)) return;
|
|
735
|
+
clearTimeout(this.timer);
|
|
736
|
+
this.pending = refreshModelCatalog({
|
|
737
|
+
...this.options,
|
|
738
|
+
signal: this.controller.signal
|
|
739
|
+
}).then((result) => {
|
|
740
|
+
if (!this.controller.signal.aborted) {
|
|
741
|
+
if (result.catalog) this.result = result;
|
|
742
|
+
else if (this.result) this.result = {
|
|
743
|
+
...this.result,
|
|
744
|
+
refreshed: false
|
|
745
|
+
};
|
|
746
|
+
}
|
|
747
|
+
this.nextRefreshAt = result.catalog ? Math.max(Date.now() + 6e4, Date.parse(result.catalog.lastFetchedAt) + MODEL_CATALOG_REFRESH_TTL_MS) : Date.now() + 6e4;
|
|
748
|
+
}).catch(() => {
|
|
749
|
+
if (this.result) this.result = {
|
|
750
|
+
...this.result,
|
|
751
|
+
refreshed: false
|
|
752
|
+
};
|
|
753
|
+
this.nextRefreshAt = Date.now() + 6e4;
|
|
754
|
+
}).finally(() => {
|
|
755
|
+
this.pending = void 0;
|
|
756
|
+
if (!this.controller.signal.aborted) {
|
|
757
|
+
this.timer = setTimeout(() => this.start(), Math.max(1, this.nextRefreshAt - Date.now()));
|
|
758
|
+
this.timer.unref?.();
|
|
759
|
+
}
|
|
760
|
+
});
|
|
761
|
+
}
|
|
762
|
+
async apply(protectedModels = []) {
|
|
763
|
+
this.start();
|
|
764
|
+
if (this.result && !this.controller.signal.aborted && !modelCatalogRefreshDisabled(this.options.env)) await applyRefreshedModelsToConfig(this.result, this.options.env, protectedModels);
|
|
765
|
+
}
|
|
766
|
+
stop() {
|
|
767
|
+
clearTimeout(this.timer);
|
|
768
|
+
this.controller.abort();
|
|
769
|
+
}
|
|
770
|
+
};
|
|
771
|
+
//#endregion
|
|
320
772
|
//#region packages/zcode-tui/src/prompt-preflight.ts
|
|
321
773
|
/** Preserve rejected input without replacing a draft typed during validation. */
|
|
322
774
|
async function preflightSubmission(options) {
|
|
@@ -157717,6 +158169,8 @@ var ChoiceDialog = class {
|
|
|
157717
158169
|
contentOffset = 0;
|
|
157718
158170
|
contentLineCount = 0;
|
|
157719
158171
|
contentPageSize = 1;
|
|
158172
|
+
/** Number of quick-selectable items; digits beyond this are ignored. */
|
|
158173
|
+
numberShortcutCount = 0;
|
|
157720
158174
|
constructor(title, prompt, help, list, theme, content, contentLabel = "Details", maxContentLines = 0, maxExpandedContentLines = 0) {
|
|
157721
158175
|
this.title = title;
|
|
157722
158176
|
this.prompt = prompt;
|
|
@@ -157767,6 +158221,14 @@ var ChoiceDialog = class {
|
|
|
157767
158221
|
this.contentExpanded = !this.contentExpanded;
|
|
157768
158222
|
return;
|
|
157769
158223
|
}
|
|
158224
|
+
if (this.numberShortcutCount > 0 && this.filter === "" && !this.contentExpanded && data.length === 1 && data >= "1" && data <= "9") {
|
|
158225
|
+
const index = data.charCodeAt(0) - "1".charCodeAt(0);
|
|
158226
|
+
if (index >= this.numberShortcutCount) return;
|
|
158227
|
+
this.list.setSelectedIndex(index);
|
|
158228
|
+
const item = this.list.getSelectedItem();
|
|
158229
|
+
if (item) this.list.onSelect?.(item);
|
|
158230
|
+
return;
|
|
158231
|
+
}
|
|
157770
158232
|
if ((this.content?.handleInput)?.call(this.content, data) === true) return;
|
|
157771
158233
|
if (this.contentExpanded) {
|
|
157772
158234
|
if (matchesKey(data, "escape")) {
|
|
@@ -157871,18 +158333,20 @@ function choose(ui, host, theme, options) {
|
|
|
157871
158333
|
return new Promise((resolve) => {
|
|
157872
158334
|
const choicesByValue = /* @__PURE__ */ new Map();
|
|
157873
158335
|
const detailsByValue = /* @__PURE__ */ new Map();
|
|
158336
|
+
const numberShortcutsEnabled = options.numberShortcuts === true && options.items.length <= 9;
|
|
157874
158337
|
const searchableItems = options.items.map((item, index) => {
|
|
157875
158338
|
const safeItem = {
|
|
157876
158339
|
...item,
|
|
157877
158340
|
label: sanitizeTerminalText(item.label, { preserveSgr: false }),
|
|
157878
158341
|
description: item.description ? sanitizeTerminalText(item.description, { preserveSgr: false }) : void 0
|
|
157879
158342
|
};
|
|
158343
|
+
const displayLabel = numberShortcutsEnabled ? `${index + 1}. ${safeItem.label}` : safeItem.label;
|
|
157880
158344
|
const value = `${safeItem.label}\u0000${index}`;
|
|
157881
158345
|
choicesByValue.set(value, safeItem);
|
|
157882
158346
|
if (options.showSelectedItemDetails) detailsByValue.set(value, new ChoiceItemDetails(safeItem, theme));
|
|
157883
158347
|
return {
|
|
157884
158348
|
value,
|
|
157885
|
-
label:
|
|
158349
|
+
label: displayLabel,
|
|
157886
158350
|
description: safeItem.description
|
|
157887
158351
|
};
|
|
157888
158352
|
});
|
|
@@ -157892,7 +158356,8 @@ function choose(ui, host, theme, options) {
|
|
|
157892
158356
|
list.setSelectedIndex(options.selectedIndex ?? 0);
|
|
157893
158357
|
const maxContentLines = Math.max(0, ui.terminal.rows - maxVisible - 9);
|
|
157894
158358
|
const maxExpandedContentLines = Math.max(2, maxContentLines, ui.terminal.rows - 8);
|
|
157895
|
-
const dialog = new ChoiceDialog(sanitizeTerminalText(options.title, { preserveSgr: false }), sanitizeTerminalText(options.prompt, { preserveSgr: false }), sanitizeTerminalText(options.help ?? (hasDetails ? "Type to filter · Up/Down choose · Ctrl+O details · ←/→ or PgUp/PgDn scroll · Enter confirm · Esc cancel" : "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);
|
|
158359
|
+
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);
|
|
158360
|
+
dialog.numberShortcutCount = numberShortcutsEnabled ? options.items.length : 0;
|
|
157896
158361
|
const previewFor = (item) => {
|
|
157897
158362
|
if (!item) return void 0;
|
|
157898
158363
|
return options.showSelectedItemDetails ? detailsByValue.get(item.value) : choicesByValue.get(item.value)?.preview;
|
|
@@ -163449,6 +163914,23 @@ function redactSecrets(message, secrets) {
|
|
|
163449
163914
|
//#endregion
|
|
163450
163915
|
//#region packages/zcode-tui/src/session-title.ts
|
|
163451
163916
|
const SESSION_TITLE_PREFIX = "ZC | ";
|
|
163917
|
+
const sessionTitleSpinnerFrames = [
|
|
163918
|
+
"⠋",
|
|
163919
|
+
"⠙",
|
|
163920
|
+
"⠹",
|
|
163921
|
+
"⠸",
|
|
163922
|
+
"⠼",
|
|
163923
|
+
"⠴",
|
|
163924
|
+
"⠦",
|
|
163925
|
+
"⠧",
|
|
163926
|
+
"⠇",
|
|
163927
|
+
"⠏"
|
|
163928
|
+
];
|
|
163929
|
+
function sessionTitleSpinnerFrame(elapsedMilliseconds, animated = true) {
|
|
163930
|
+
if (!animated) return sessionTitleSpinnerFrames[0];
|
|
163931
|
+
const frame = Math.floor(Math.max(0, elapsedMilliseconds) / 120);
|
|
163932
|
+
return sessionTitleSpinnerFrames[frame % sessionTitleSpinnerFrames.length] ?? sessionTitleSpinnerFrames[0];
|
|
163933
|
+
}
|
|
163452
163934
|
function sessionTitleFromFirstMessage(message) {
|
|
163453
163935
|
const normalized = sanitizeTerminalText(message).replace(/\s+/gu, " ").trim();
|
|
163454
163936
|
if (!normalized) return null;
|
|
@@ -166159,6 +166641,8 @@ var ZCodeTui = class {
|
|
|
166159
166641
|
turnTimingVisible = false;
|
|
166160
166642
|
turnHadWorkActivity = false;
|
|
166161
166643
|
turnTimer;
|
|
166644
|
+
sessionTitleSpinnerTimer;
|
|
166645
|
+
sessionTitleSpinnerStartedAt;
|
|
166162
166646
|
pendingTurnNotification;
|
|
166163
166647
|
pendingTurnNotificationDetail = "";
|
|
166164
166648
|
goal;
|
|
@@ -166167,6 +166651,7 @@ var ZCodeTui = class {
|
|
|
166167
166651
|
sessionId;
|
|
166168
166652
|
sessionTitleEmitted = false;
|
|
166169
166653
|
sessionTerminalTitle;
|
|
166654
|
+
emittedSessionTerminalTitle;
|
|
166170
166655
|
sessionMetrics = {};
|
|
166171
166656
|
usageRefreshInFlight = false;
|
|
166172
166657
|
usageRefreshPending = false;
|
|
@@ -166180,6 +166665,7 @@ var ZCodeTui = class {
|
|
|
166180
166665
|
backgroundDrainScheduled = false;
|
|
166181
166666
|
backgroundHandoffInterruptInFlight = false;
|
|
166182
166667
|
updateCheckAbortController;
|
|
166668
|
+
modelCatalogRefresh;
|
|
166183
166669
|
loginRequired;
|
|
166184
166670
|
removeStreamErrorGuards;
|
|
166185
166671
|
constructor(options) {
|
|
@@ -166305,6 +166791,13 @@ var ZCodeTui = class {
|
|
|
166305
166791
|
this.updateTurnStatus();
|
|
166306
166792
|
this.ui.requestRender(true);
|
|
166307
166793
|
this.startUpdateRefresh(updateCheck);
|
|
166794
|
+
if (this.options.reloadModelOptions) {
|
|
166795
|
+
this.modelCatalogRefresh = new ModelCatalogRefresh({
|
|
166796
|
+
baseUrl: process.env.ZCODE_BASE_URL?.trim() || "https://zcode.z.ai",
|
|
166797
|
+
currentVersion: this.distributionVersion || this.options.version || "0.0.0"
|
|
166798
|
+
});
|
|
166799
|
+
this.modelCatalogRefresh.start();
|
|
166800
|
+
}
|
|
166308
166801
|
if (!this.loginRequired) this.refreshGoal();
|
|
166309
166802
|
if (!this.loginRequired) this.refreshSessionUsage();
|
|
166310
166803
|
if (await readSetupPending().catch(() => false)) if (await readConfiguredModelAccess().catch(() => null)) await clearSetupPending().catch(() => {});
|
|
@@ -167028,6 +167521,7 @@ var ZCodeTui = class {
|
|
|
167028
167521
|
const explicitModel = explicitModelRequest(input);
|
|
167029
167522
|
if (explicitModel) {
|
|
167030
167523
|
this.addUserMessage(submission.displayInput);
|
|
167524
|
+
await this.refreshModelOptions();
|
|
167031
167525
|
await this.switchTransientModel(explicitModel);
|
|
167032
167526
|
return;
|
|
167033
167527
|
}
|
|
@@ -167365,6 +167859,8 @@ var ZCodeTui = class {
|
|
|
167365
167859
|
this.sessionId = void 0;
|
|
167366
167860
|
this.sessionTitleEmitted = false;
|
|
167367
167861
|
this.sessionTerminalTitle = void 0;
|
|
167862
|
+
this.stopSessionTitleSpinner();
|
|
167863
|
+
this.emittedSessionTerminalTitle = "";
|
|
167368
167864
|
emitSessionTerminalTitle(this.options.stdout ?? process.stdout, "");
|
|
167369
167865
|
this.sessionMetrics = {};
|
|
167370
167866
|
this.restoreTranscript(restoredMessages(result.restoredMessages));
|
|
@@ -168410,6 +168906,7 @@ var ZCodeTui = class {
|
|
|
168410
168906
|
prompt: asString(request.reason) ?? `${toolName} requests permission to continue.`,
|
|
168411
168907
|
items,
|
|
168412
168908
|
signal,
|
|
168909
|
+
numberShortcuts: true,
|
|
168413
168910
|
content: this.permissionPreview(toolName, request.input, asString(request.riskLevel))
|
|
168414
168911
|
});
|
|
168415
168912
|
if (!selected) return {
|
|
@@ -168725,16 +169222,13 @@ var ZCodeTui = class {
|
|
|
168725
169222
|
await this.applyModeShortcut(normalizedMode(mode));
|
|
168726
169223
|
return true;
|
|
168727
169224
|
}
|
|
168728
|
-
/**
|
|
168729
|
-
* Refresh modelOptions from the bridge. After a fresh login
|
|
168730
|
-
* (loginRequired was true) the runtime skipped model loading, so the
|
|
168731
|
-
* initial options list may be empty; all model-switch entry points share
|
|
168732
|
-
* this refresh.
|
|
168733
|
-
*/
|
|
169225
|
+
/** All model selectors re-read the catalog, including after first-run login. */
|
|
168734
169226
|
async refreshModelOptions() {
|
|
168735
|
-
|
|
168736
|
-
|
|
168737
|
-
|
|
169227
|
+
const load = this.options.reloadModelOptions ?? this.options.listModelOptions;
|
|
169228
|
+
if (load) try {
|
|
169229
|
+
await this.modelCatalogRefresh?.apply([this.model]).catch(() => {});
|
|
169230
|
+
const refreshed = await load();
|
|
169231
|
+
if (Array.isArray(refreshed)) this.modelOptions = [...refreshed];
|
|
168738
169232
|
} catch (error) {
|
|
168739
169233
|
this.addNotice(`Could not load model options: ${error instanceof Error ? error.message : String(error)}`, "warning");
|
|
168740
169234
|
}
|
|
@@ -170172,9 +170666,30 @@ var ZCodeTui = class {
|
|
|
170172
170666
|
this.updateTurnStatus(requestRender);
|
|
170173
170667
|
}
|
|
170174
170668
|
refreshSessionTerminalTitle() {
|
|
170175
|
-
if (!this.sessionTerminalTitle)
|
|
170176
|
-
|
|
170177
|
-
|
|
170669
|
+
if (!this.sessionTerminalTitle) {
|
|
170670
|
+
this.stopSessionTitleSpinner();
|
|
170671
|
+
return;
|
|
170672
|
+
}
|
|
170673
|
+
const now = performance.now();
|
|
170674
|
+
const working = this.activeSubmissions > 0 && this.activity ? `${sessionTitleSpinnerFrame(this.sessionTitleSpinnerStartedAt === void 0 ? 0 : Math.max(0, now - this.sessionTitleSpinnerStartedAt), this.animateTurnTimer)} ${this.activity}` : void 0;
|
|
170675
|
+
if (working && this.animateTurnTimer) {
|
|
170676
|
+
if (this.sessionTitleSpinnerStartedAt === void 0) this.sessionTitleSpinnerStartedAt = now;
|
|
170677
|
+
if (!this.sessionTitleSpinnerTimer) {
|
|
170678
|
+
this.sessionTitleSpinnerTimer = setInterval(() => this.refreshSessionTerminalTitle(), 120);
|
|
170679
|
+
this.sessionTitleSpinnerTimer.unref?.();
|
|
170680
|
+
}
|
|
170681
|
+
} else this.stopSessionTitleSpinner();
|
|
170682
|
+
const nextTitle = working ?? this.sessionTerminalTitle;
|
|
170683
|
+
if (nextTitle === this.emittedSessionTerminalTitle) return;
|
|
170684
|
+
this.emittedSessionTerminalTitle = nextTitle;
|
|
170685
|
+
emitSessionTerminalTitle(this.options.stdout ?? process.stdout, nextTitle);
|
|
170686
|
+
}
|
|
170687
|
+
stopSessionTitleSpinner() {
|
|
170688
|
+
if (this.sessionTitleSpinnerTimer) {
|
|
170689
|
+
clearInterval(this.sessionTitleSpinnerTimer);
|
|
170690
|
+
this.sessionTitleSpinnerTimer = void 0;
|
|
170691
|
+
}
|
|
170692
|
+
this.sessionTitleSpinnerStartedAt = void 0;
|
|
170178
170693
|
}
|
|
170179
170694
|
updateTurnStatus(requestRender = true) {
|
|
170180
170695
|
if (this.turnStartedAt !== void 0) this.turnElapsedMilliseconds = Math.max(0, performance.now() - this.turnStartedAt);
|
|
@@ -170187,6 +170702,7 @@ var ZCodeTui = class {
|
|
|
170187
170702
|
const right = goalText ? goalStyle(`[ Goal: ${goalText} ]`) : void 0;
|
|
170188
170703
|
const compactRight = goalLabel ? goalStyle(`[ Goal: ${goalLabel} ]`) : void 0;
|
|
170189
170704
|
this.turnStatus.setContent(left, right, compactRight);
|
|
170705
|
+
this.refreshSessionTerminalTitle();
|
|
170190
170706
|
this.updateRuntimeActivity(false);
|
|
170191
170707
|
if (requestRender) this.ui.requestRender();
|
|
170192
170708
|
}
|
|
@@ -170423,7 +170939,9 @@ var ZCodeTui = class {
|
|
|
170423
170939
|
for (const controller of this.steerAbortControllers) controller.abort();
|
|
170424
170940
|
this.steerAbortControllers.clear();
|
|
170425
170941
|
this.updateCheckAbortController?.abort();
|
|
170942
|
+
this.modelCatalogRefresh?.stop();
|
|
170426
170943
|
if (this.turnTimer) clearInterval(this.turnTimer);
|
|
170944
|
+
this.stopSessionTitleSpinner();
|
|
170427
170945
|
if (this.rewindEscapeTimer) clearTimeout(this.rewindEscapeTimer);
|
|
170428
170946
|
if (this.fullscreenWelcomeTransitionTimer) clearTimeout(this.fullscreenWelcomeTransitionTimer);
|
|
170429
170947
|
if (this.runtimeRefreshTimer) clearTimeout(this.runtimeRefreshTimer);
|
package/vendor/zcode.cjs
CHANGED
|
@@ -3215,7 +3215,7 @@ ${v_n}
|
|
|
3215
3215
|
`}function yUi(e,t){return e?`Uninstalled plugin ${e.id}
|
|
3216
3216
|
`:`Plugin not installed: ${t}
|
|
3217
3217
|
`}function vUi(e){return e.mcpServerNames.length>0?e.mcpServerNames.join(", "):"none"}function xUi(e,t,r){if(!(!r.verbose||t.length===0)){e.push("",`Diagnostics (${t.length})`);for(let n of t){let o=n.path?` (${n.path})`:"",i=n.pluginId?` ${n.pluginId}`:"";e.push(`- [${n.severity}]${i} ${n.code}: ${n.message}${o}`)}}}function b_n(e){return{commandRootCount:e.commandRootCount,dataPath:e.dataPath,enabled:e.enabled,id:e.id,manifestPath:e.manifestPath,marketplace:e.marketplace,declaredMcpServerNames:e.declaredMcpServerNames,mcpServerNames:e.mcpServerNames,hookDetails:(e.hookDetails??[]).map(SUi),name:e.name,rootPath:e.rootPath,skillCount:e.skillCount,skillRootCount:e.skillRootCount,source:e.source,...e.description?{description:e.description}:{},...e.version?{version:e.version}:{}}}function SUi(e){return{command:e.command,event:e.event,runnable:e.runnable,sourcePath:e.sourcePath,type:e.type,...e.args?{args:e.args}:{},...e.async!==void 0?{async:e.async}:{},...e.matcher!==void 0?{matcher:e.matcher}:{},...e.shell!==void 0?{shell:e.shell}:{},...e.statusMessage!==void 0?{statusMessage:e.statusMessage}:{},...e.timeout!==void 0?{timeout:e.timeout}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{}}}function IUi(e){return{code:e.code,message:e.message,severity:e.severity,...e.path?{path:e.path}:{},...e.pluginId?{pluginId:e.pluginId}:{}}}var y_n,v_n,bUi,wUi,kUi,w_n=T(()=>{"use strict";y_n=require("node:readline");sl();v_n="Usage: zcode plugins [list|enable <plugin-id-or-name>|disable <plugin-id-or-name>|uninstall <plugin-id-or-name> [--force]]";a(x_n,"runPluginsCommand");a(_kt,"failUsage");a(lUi,"runPluginsListCommand");a(cUi,"runPluginsSetCommand");a(dUi,"resolveListPlugins");a(pUi,"resolveSetPluginEnabled");a(mUi,"runPluginsUninstallCommand");a(fUi,"confirmUninstall");a(hUi,"resolveUninstallPlugin");a(ykt,"reportPluginsError");a(gUi,"formatHumanPluginList");a(_Ui,"formatHumanPluginSet");a(yUi,"formatHumanPluginUninstall");a(vUi,"formatMcpNames");a(xUi,"appendDiagnostics");bUi=a((e,t)=>hc({cwd:t,diagnostics:e.diagnostics.map(IUi),plugins:e.plugins.map(b_n)}),"formatPluginListJson"),wUi=a((e,t)=>hc({cwd:t,enabled:e.enabled,path:e.path,plugin:b_n(e.plugin)}),"formatPluginSetJson"),kUi=a((e,t,r)=>hc({cwd:r,pluginId:e?.id??t,removed:e!==null,...e?{plugin:{id:e.id,name:e.name,marketplace:e.marketplace,scope:e.scope}}:{}}),"formatPluginUninstallJson");a(b_n,"formatPluginJson");a(SUi,"formatHookDetailJson");a(IUi,"formatDiagnosticJson")});function CUi(e=process.env){let t=e.ZCODE_STORAGE_DIR?.trim()||(0,rB.join)((0,S_n.homedir)(),".zcode");return(0,rB.join)(t,"clipboard")}function I_n(e={}){let t=e.platform??process.platform,r=e.maxBytes??TUi,n=e.runCommand??PUi,o=e.tempDirectory??CUi(e.processEnv);return async(i={})=>t==="darwin"?await EUi({maxBytes:r,runCommand:n,signal:i.abortSignal,tempDirectory:o}):t==="linux"?await AUi({maxBytes:r,runCommand:n,signal:i.abortSignal}):t==="win32"?await RUi({maxBytes:r,runCommand:n,signal:i.abortSignal,tempDirectory:o}):null}async function EUi(e){await(0,R2.mkdir)(e.tempDirectory,{recursive:!0});let t=await(0,R2.mkdtemp)((0,rB.join)(e.tempDirectory,"zcode-clipboard-")),r=(0,rB.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 ${MUi(r)} with write permission`,"-e","write png_data to fp","-e","close access fp"],{maxBytes:e.maxBytes,signal:e.signal})).exitCode!==0?null:await T_n(r,"image/png",e.maxBytes)}finally{await(0,R2.rm)(t,{force:!0,recursive:!0})}}async function AUi(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 r of t){let n=await e.runCommand(r.file,r.args,{maxBytes:e.maxBytes,signal:e.signal}),o=C_n(n.stdout,r.mediaType,e.maxBytes);if(n.exitCode===0&&o)return o}return null}async function RUi(e){await(0,R2.mkdir)(e.tempDirectory,{recursive:!0});let t=await(0,R2.mkdtemp)((0,rB.join)(e.tempDirectory,"zcode-clipboard-")),r=(0,rB.join)(t,"clipboard.png"),n=["Add-Type -AssemblyName System.Windows.Forms;","$img = Get-Clipboard -Format Image;","if ($null -eq $img) { exit 2 }",`$img.Save(${OUi(r)}, [System.Drawing.Imaging.ImageFormat]::Png);`].join(" ");try{return(await e.runCommand("powershell.exe",["-NoProfile","-NonInteractive","-Command",n],{maxBytes:e.maxBytes,signal:e.signal})).exitCode!==0?null:await T_n(r,"image/png",e.maxBytes)}finally{await(0,R2.rm)(t,{force:!0,recursive:!0})}}async function T_n(e,t,r){let n=await(0,R2.readFile)(e);return C_n(n,t,r)}function C_n(e,t,r){return e.byteLength===0||e.byteLength>r?null:{dataUrl:`data:${t};base64,${e.toString("base64")}`,mediaType:t,sizeBytes:e.byteLength}}async function PUi(e,t,r){return await new Promise(n=>{let o;try{o=(0,k_n.spawn)(e,t,{signal:r.signal,stdio:["ignore","pipe","ignore"],windowsHide:!0})}catch{n({exitCode:-1,stdout:Buffer.alloc(0)});return}let i=[],s=0,u=!1,l=a(c=>{u||(u=!0,n(c))},"finish");o.stdout?.on("data",c=>{if(s+=c.byteLength,s>r.maxBytes){o.kill();return}i.push(c)}),o.on("error",()=>l({exitCode:-1,stdout:Buffer.alloc(0)})),o.on("close",(c,d)=>{l({exitCode:c,signal:d,stdout:Buffer.concat(i)})})})}function MUi(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function OUi(e){return`'${e.replace(/'/g,"''")}'`}var k_n,R2,S_n,rB,TUi,E_n=T(()=>{"use strict";k_n=require("node:child_process"),R2=require("node:fs/promises"),S_n=require("node:os"),rB=require("node:path"),TUi=20*1024*1024;a(CUi,"resolveDefaultClipboardDirectory");a(I_n,"createNodeClipboardImageReader");a(EUi,"readMacClipboardImage");a(AUi,"readLinuxClipboardImage");a(RUi,"readWindowsClipboardImage");a(T_n,"readImageFile");a(C_n,"bufferToClipboardImage");a(PUi,"runCommandBuffer");a(MUi,"appleScriptString");a(OUi,"powershellString")});function R_n(e={}){let t=e.maxBytes??DUi,r=e.platform??process.platform,n=e.runCommand??qUi;return async o=>{let i=$Ui(o,t);if(i.byteLength===0)return;let s=FUi(e.stdout,i),u=await zUi({input:o,platform:r,runCommand:n});if(!s&&!u)throw new Error("No text clipboard target accepted the selected text.")}}function FUi(e,t){if(!e)return!1;try{return e.write(`${LUi}${NUi};${t.toString("base64")}${BUi}`),!0}catch{return!1}}async function zUi(e){for(let t of UUi(e.platform))if((await e.runCommand(t.file,t.args,{input:e.input})).exitCode===0)return!0;return!1}function UUi(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",jUi],file:"powershell.exe"}]:[]}function $Ui(e,t){let r=Buffer.from(e,"utf8");if(r.byteLength>t)throw new Error(`Clipboard text exceeds ${t} bytes.`);return r}async function qUi(e,t,r){return await new Promise(n=>{let o;try{o=(0,A_n.spawn)(e,t,{stdio:["pipe","ignore","ignore"],windowsHide:!0})}catch{n({exitCode:-1});return}let i=!1,s=a(u=>{i||(i=!0,n(u))},"finish");o.stdin?.on("error",()=>{}),o.stdin?.end(r.input),o.on("error",()=>s({exitCode:-1})),o.on("close",(u,l)=>s({exitCode:u,signal:l}))})}var A_n,DUi,NUi,LUi,BUi,jUi,P_n=T(()=>{"use strict";A_n=require("node:child_process"),DUi=1024*1024,NUi="c",LUi="\x1B]52;",BUi="\x07",jUi="Set-Clipboard -Value ([Console]::In.ReadToEnd())";a(R_n,"createNodeClipboardTextWriter");a(FUi,"writeOsc52");a(zUi,"writeNativeClipboardText");a(UUi,"nativeClipboardCommands");a($Ui,"assertClipboardTextSize");a(qUi,"runCommandText")});async function fOe(e){let t=e.env??process.env,r=(e.cwd??process.cwd)();return e.listCustomCommands?await e.listCustomCommands({env:t,logger:e.logger,workingDirectory:r}):await(await qu()).listZCodeCustomCommands({env:t,logger:e.logger,workingDirectory:r})}async function M_n(e,t){let r=e.env??process.env,n=(e.cwd??process.cwd)();return e.loadCustomCommand?await e.loadCustomCommand({env:r,logger:e.logger,name:t,workingDirectory:n}):await(await qu()).loadZCodeCustomCommand({env:r,logger:e.logger,name:t,workingDirectory:n})}async function O_n(e){let t=e.env??process.env,r=(e.cwd??process.cwd)();return await(e.listSkills??(await qu()).listZCodeSkills)({env:t,logger:e.logger,workingDirectory:r})}async function D_n(e){let t=e.env??process.env,r=(e.cwd??process.cwd)();return(await(e.listSessions??(await qu()).listZCodeSessions)({directory:r,env:t,limit:50})).map(i=>({directory:i.directory,id:i.id,parentId:i.parentID,title:i.title,updatedAt:i.time.updated}))}async function N_n(e){try{return await e.getSessionMetadata?.()??{}}catch(t){if(VUi(t))throw t;return{}}}function VUi(e){return e instanceof Error?e.name==="SqliteSessionMigrationError":!1}var vkt=T(()=>{"use strict";K5();a(fOe,"listCustomCommandsForTui");a(M_n,"loadCustomCommandForTui");a(O_n,"listSkillsForTui");a(D_n,"listSessionsForTui");a(N_n,"loadInitialTuiSessionMetadata");a(VUi,"isStartupGateError")});async function L_n(e,t){let r=e.env??process.env,n=(e.cwd??process.cwd)(),o=(e.loadDotenv??s0)({cwd:n,env:r});if(o.error)throw new Error(`Failed to load environment file: ${o.path}`,{cause:o.error});return await(e.loginZCodeCli??(await qu()).loginZCodeCli)({abortSignal:t?.abortSignal,env:r,onAuthorizeUrl:t?.onAuthorizeUrl})}async function B_n(e,t){let r=e.env??process.env,n=(e.cwd??process.cwd)(),o=(e.loadDotenv??s0)({cwd:n,env:r});if(o.error)throw new Error(`Failed to load environment file: ${o.path}`,{cause:o.error});return await(e.loginBigmodelCodingPlan??(await qu()).loginBigmodelCodingPlan)({abortSignal:t?.abortSignal,env:r,onAuthorizeUrl:t?.onAuthorizeUrl})}async function j_n(e,t){return await(e.configureCodingPlanApiKey??(await qu()).configureCodingPlanApiKey)({apiKey:t.apiKey,providerId:t.providerId})}async function F_n(e){let t=e.env??process.env,r=(e.cwd??process.cwd)(),n=(e.loadDotenv??s0)({cwd:r,env:t});if(n.error)throw new Error(`Failed to load environment file: ${n.path}`,{cause:n.error});return await(e.logoutZCodeCli??(await qu()).logoutZCodeCli)({env:t})}var z_n=T(()=>{"use strict";K5();AP();a(L_n,"loginForTui");a(B_n,"loginBigmodelForTui");a(j_n,"configureApiKeyForTui");a(F_n,"logoutForTui")});var U_n,$_n,X5,xkt=T(()=>{"use strict";U_n={},$_n=a(e=>({current:e,override:e}),"createCliModeState"),X5=a(e=>e.current??e.override??"build","currentCliMode")});function bkt(e,t,r){return{kind:"started_turn",result:{...e,locale:e.locale??t.getLocale?.(),mode:r,model:e.model??t.getModel?.(),theme:e.theme??t.getTheme?.(),thoughtLevel:e.thoughtLevel??t.getThoughtLevel?.()}}}var q_n=T(()=>{"use strict";a(bkt,"withTuiMetadata")});function V_n(){let e=new Set;return{onWorkflowEvent:a(async t=>{for(let r of e)await Promise.resolve(r(t)).catch(()=>{})},"onWorkflowEvent"),subscribeWorkflowEvents:a(t=>(e.add(t),()=>{e.delete(t)}),"subscribeWorkflowEvents")}}function G_n(e,t,r){e.refreshWorkflowPanel=async n=>{let o=await t(),i=await uOe(o,n);if(!i)throw new Error("Workflow panel is not available in this client.");return i},e.stopWorkflow=async n=>{let o=await t(),i=o.stopWorkflow??o.stopExpertWorkflow;if(!i)throw new Error("Workflow stop is not available in this client.");let s=await i({runId:n.runId}),u=await uOe(o,{runId:s.runId??n.runId});if(!u)throw new Error("Workflow panel is not available in this client.");return u},e.subscribeWorkflowEvents=r}var W_n=T(()=>{"use strict";nkt();a(V_n,"createTuiWorkflowEventHub");a(G_n,"attachTuiWorkflowPanelHandlers")});function H_n(e,t,r,n={continueSession:!1},o,i,s=nRe,u,l=!1,c,d){let p,m=o,h,_,y,v=new WeakMap,x=new WeakMap,w,b=V_n(),k=Math.max(1,Math.trunc(e.shutdownCleanupTimeoutMs??ope)),S={requestPermission:a(async(G,K)=>{let Y=w;return Y?await Y(G,K):{decision:"deny",reason:`No interactive approval handler configured for ${G.toolName}`,resolvedAt:new Date}},"requestPermission")},I=a(async(G=p)=>{if(!G)return;let K=G,Y=v.get(K);Y||(Y=(async()=>{await ox(async()=>G.close?.(),k),await ox(async()=>x.get(K)?.close(),k)})(),v.set(K,Y)),await Y},"closeApp"),C=a(async G=>{let K=p,Y=await G();return p=Y,K&&K!==Y&&await I(K),t.current=p.getMode?.()??X5(t),p},"replaceApp"),R=a(async G=>{let K=e.env??process.env,Y=(e.cwd??process.cwd)(),Q=(e.loadDotenv??s0)({cwd:Y,env:K});if(Q.error)throw new Error(`Failed to load environment file: ${Q.path}`,{cause:Q.error});let X=await pOe(G,Y,K,e),q=e.createZCodeApp?void 0:await qu(),j=e.createZCodeApp??q?.createZCodeApp;if(!j)throw new Error("ZCode app factory is unavailable.");let ee=e.prepareZCodeTelemetryEnv??q?.prepareZCodeTelemetryEnv;ee&&(_=e.shutdownZCodeTelemetry??q?.shutdownZCodeTelemetry);let F=ee?await ee(K,{cliVersion:r,productVersion:K.ZCODE_APP_VERSION}):K,N=e.createProviderEndpointRoutingPort??q?.createDefaultProviderEndpointRoutingPort;h??=N?.({appVersion:r,env:K,projectConfigPath:e.projectConfigPath,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,workingDirectory:Y});let H=dOe({browserExecutable:d,browserUse:c},e),se;try{se=j({browserControlPort:H?.browserControlPort,env:F,projectConfigPath:e.projectConfigPath,...h?{providerEndpointRoutingPort:h}:{},resume:X!==void 0,runtimeConfig:{...t.override?{mode:t.override}:{},...u?{toolDisallowlist:u}:{},...l?{midConversationSystem:{mode:"force"}}:{},modelStreaming:"on",titleGeneration:U_n,workingDirectory:Y},permissionBroker:S,sessionId:X,skipUserConfig:e.skipUserConfig,uiDetectedLocale:i,uiLocale:m,userConfigPath:e.userConfigPath,version:r,onWorkflowEvent:b.onWorkflowEvent})}catch(le){throw await ox(async()=>H?.close(),k),le}return H&&x.set(se,H),t.current=se.getMode?.()??t.override??t.current??"build",se},"createApp"),A=a(async()=>(p??=await R(n),t.current=p.getMode?.()??X5(t),p),"getApp"),O=a(async G=>await C(async()=>await R(G?{continueSession:!1,resumeSessionId:G}:{continueSession:!0})),"resumeApp"),P=a(async()=>await C(async()=>await R({continueSession:!1})),"newApp"),D=a(async G=>{if(t.override=G,p){let K=p;if(K.setMode){let Y=await K.setMode(G);return t.current=Y.mode,Y.mode}K.runtime.updateConfig({mode:G})}return t.current=G,G},"setCliMode"),U=Wse({forkApp:a(async G=>{let Y=await(await A()).forkFromCheckpoint?.({targetCheckpointId:G});if(!Y)throw new Error("Forking is not available in this client.");return await C(async()=>await R({continueSession:!1,resumeSessionId:Y.forkedSessionId})),{copiedMessageCount:Y.copiedMessageCount,forkedSessionId:Y.forkedSessionId,response:`${Y.response}
|
|
3218
|
-
Switched to forked session ${Y.forkedSessionId}.`,restoredFileCount:Y.restoredFileCount??Y.restoredFiles?.length??0}},"forkApp"),getApp:A,getMode:a(()=>X5(t),"getMode"),getLocale:a(()=>p?.getLocale?.()??j1t(m,i)??s,"getLocale"),hasConfiguredCodingPlanApiKey:ckt(e),listCustomCommands:a(()=>fOe(e),"listCustomCommands"),listSessions:a(()=>D_n(e),"listSessions"),listSkills:a(()=>O_n(e),"listSkills"),configureApiKey:a(G=>j_n(e,G),"configureApiKey"),login:a(G=>L_n(e,G),"login"),loginBigmodel:a(G=>B_n(e,G),"loginBigmodel"),loadCustomCommand:a(G=>M_n(e,G),"loadCustomCommand"),newApp:P,recordInputHistory:a(async(G,K)=>{await p?.recordInputHistory?.(G,K)},"recordInputHistory"),resumeApp:O,logout:a(()=>F_n(e),"logout"),setLocale:a(async G=>{if(p?.setLocale){let Y=await p.setLocale(G);return m=G,Y}return m=G,{configPath:(await Lee(e.userConfigPath??tI(),G)).path,locale:j1t(G,i)??"en-US",requestedLocale:G}},"setLocale"),setMode:D}),L=a(async(G,K)=>{let Y=w;w=K.requestPermission;try{return await U(G,K)}finally{w=Y}},"submitPrompt");return L.setMode=async G=>({mode:await D(G)}),L.sendInput=async(G,K)=>{let Y=w;w=K?.requestPermission;try{let Q=await A();if(Q.sendInput){let X=await Q.sendInput(G,K);return X.kind!=="started_turn"?X:bkt(await(X.result??X.completion),Q,X5(t))}return bkt(await Q.submitPrompt(G,K),Q,X5(t))}finally{w=Y}},L.listSkills=async()=>await O_n(e),L.loadSessionTranscript=async()=>await(await A()).loadSessionTranscript?.()??[],L.loadSessionContextMessages=async()=>await(await A()).loadSessionContextMessages?.()??[],L.readGoal=async()=>await(await A()).readTarget?.()??null,L.readTodos=async()=>await(await A()).readTodos?.()??[],L.readRuntimeProjection=async()=>{let $zRuntimeProjectionBridge=await A();await L.$zRestorePersistedBackgroundTasks?.($zRuntimeProjectionBridge);let t=await $zRuntimeProjectionBridge.runtime?.getProjection?.();if(!t)return null;let r=Object.values($zRuntimeProjectionBridge.runtime?.runtimeTaskRegistry?.all?.()??{}).filter(o=>o.isBackgrounded===!0).map(o=>({taskId:o.taskId,taskKind:o.taskType??o.type,agentId:o.agentId,agentType:o.agentType,childSessionId:o.childSessionId,parentSessionId:o.parentSessionId,parentToolCallId:o.parentToolCallId,turnId:o.turnId,prompt:o.prompt,error:o.status==="running"?null:o.error instanceof Error?o.error.message:typeof o.error==="string"?o.error:void 0,outputPath:o.outputFile,status:o.status,description:o.description,startedAt:o.startedAt,completedAt:o.status==="running"?null:o.completedAt,cancelRequestedAt:o.status==="running"?null:o.cancelRequestedAt,blocked:o.status==="running"?null:o.blocked,blockedReason:o.status==="running"?null:o.blockedReason,cancellable:(o.taskType??o.type)==="local_agent"?o.status==="running":o.cancellable}));let s=Array.isArray(t.backgroundTasks)?t.backgroundTasks.slice():[];for(let $zDetail of r){let $zIndex=s.findIndex($zExisting=>$zExisting.taskId===$zDetail.taskId);if($zIndex<0)s.push($zDetail);else s[$zIndex]={...s[$zIndex],...Object.fromEntries(Object.entries($zDetail).filter(([,v])=>v!==void 0))}}return{...t,backgroundTasks:s,backgroundTaskDetails:r,restoredBackgroundTasks:Array.isArray($zRuntimeProjectionBridge.$zRestoredBackgroundTasksLog)?$zRuntimeProjectionBridge.$zRestoredBackgroundTasksLog:[]}},L.$zRestorePersistedBackgroundTasks=async $zApp=>{let $zRuntime=$zApp?.runtime,$zRegistry=$zRuntime?.runtimeTaskRegistry;if(!$zRegistry?.register||typeof $zApp?.sessionId!="string"||$zApp.sessionId===$zApp.$zRestoredBackgroundTasksSession)return;$zApp.$zRestoredBackgroundTasksSession=$zApp.sessionId,$zApp.$zRestoredBackgroundTasksLog=[];try{let $zMessages=await $zApp.loadSessionTranscript?.()??[],$zRestored=[];for(let $zMessage of $zMessages){let $zParts=Array.isArray($zMessage?.parts)?$zMessage.parts:[];for(let $zPart of $zParts){if($zPart?.type!=="tool")continue;let $zToolName=typeof $zPart.toolName==="string"?$zPart.toolName:typeof $zPart.tool==="string"?$zPart.tool:"";$zToolName=$zToolName.trim().toLowerCase();if($zToolName!=="agent"&&$zToolName!=="subagent"&&$zToolName!=="task")continue;let $zInput=$zPart.input??$zPart.state?.input,$zOutput=typeof $zPart.output==="string"?$zPart.output:$zPart.state?.output;if(typeof $zOutput!=="string"||$zOutput.trim().length===0)continue;let $zSpawn;try{$zSpawn=JSON.parse($zOutput)}catch{}if(!$zSpawn||typeof $zSpawn!=="object"||Array.isArray($zSpawn)){if(!$zOutput.includes("Async agent launched successfully."))continue;let $zAgentId=/(?:^|\n)agentId:\s*([^\s(]+)/u.exec($zOutput)?.[1],$zOutputFile=/(?:^|\n)output_file:\s*([^\r\n]+)/u.exec($zOutput)?.[1]?.trim();if(typeof $zAgentId!=="string"||$zAgentId.length===0)continue;$zSpawn={status:"async_launched",agentId:$zAgentId,agentType:typeof $zInput?.subagent_type==="string"&&$zInput.subagent_type.length>0?$zInput.subagent_type:typeof $zInput?.agentType==="string"&&$zInput.agentType.length>0?$zInput.agentType:void 0,childSessionId:"sess_subagent_"+$zAgentId,description:typeof $zInput?.description==="string"&&$zInput.description.length>0?$zInput.description:void 0,prompt:typeof $zInput?.prompt==="string"&&$zInput.prompt.length>0?$zInput.prompt:void 0,...$zOutputFile?{outputFile:$zOutputFile}:{}}}if(($zSpawn.status!=="async_launched"&&$zSpawn.status!=="backgrounded")||typeof $zSpawn.agentId!=="string"||$zSpawn.agentId.length===0)continue;let $zMetadata;if(typeof $zSpawn.outputFile==="string"&&$zSpawn.outputFile.length>0)try{let $zBuiltin=process.getBuiltinModule;if(typeof $zBuiltin==="function"){let $zFs=$zBuiltin.call(process,"node:fs"),$zPath=$zBuiltin.call(process,"node:path");$zMetadata=JSON.parse($zFs.readFileSync($zPath.join($zPath.dirname($zSpawn.outputFile),"metadata.json"),"utf8"))}}catch{}if($zMetadata&&typeof $zMetadata==="object"&&!Array.isArray($zMetadata)&&(typeof $zMetadata.agentId!=="string"||$zMetadata.agentId===$zSpawn.agentId)&&(typeof $zMetadata.parentSessionId!=="string"||$zMetadata.parentSessionId===$zApp.sessionId))$zSpawn={...$zSpawn,agentType:typeof $zMetadata.profileId==="string"&&$zMetadata.profileId.length>0?$zMetadata.profileId:$zSpawn.agentType,childSessionId:typeof $zMetadata.childSessionId==="string"&&$zMetadata.childSessionId.length>0?$zMetadata.childSessionId:$zSpawn.childSessionId,description:typeof $zMetadata.description==="string"&&$zMetadata.description.length>0?$zMetadata.description:$zSpawn.description,outputFile:typeof $zMetadata.outputFile==="string"&&$zMetadata.outputFile.length>0?$zMetadata.outputFile:$zSpawn.outputFile,prompt:typeof $zMetadata.prompt==="string"&&$zMetadata.prompt.length>0?$zMetadata.prompt:$zSpawn.prompt,error:typeof $zMetadata.error==="string"&&$zMetadata.error.length>0?$zMetadata.error:$zSpawn.error};if(typeof $zSpawn.childSessionId!=="string"||$zSpawn.childSessionId.length===0)$zSpawn.childSessionId="sess_subagent_"+$zSpawn.agentId;if($zRegistry.get?.($zSpawn.agentId))continue;let $zStatus="stopped";if($zMetadata?.status==="completed")$zStatus="completed";else if($zMetadata?.status==="failed")$zStatus="failed";let $zTask={taskId:$zSpawn.agentId,agentId:$zSpawn.agentId,agentType:typeof $zSpawn.agentType==="string"&&$zSpawn.agentType.length>0?$zSpawn.agentType:"general-purpose",childSessionId:$zSpawn.childSessionId,description:typeof $zSpawn.description==="string"&&$zSpawn.description.length>0?$zSpawn.description:void 0,error:typeof $zSpawn.error==="string"&&$zSpawn.error.length>0?$zSpawn.error:void 0,isBackgrounded:!0,outputFile:typeof $zSpawn.outputFile==="string"&&$zSpawn.outputFile.length>0?$zSpawn.outputFile:void 0,parentToolCallId:typeof $zPart.toolCallId==="string"&&$zPart.toolCallId.length>0?$zPart.toolCallId:typeof $zPart.callID==="string"&&$zPart.callID.length>0?$zPart.callID:void 0,parentSessionId:$zApp.sessionId,prompt:typeof $zSpawn.prompt==="string"&&$zSpawn.prompt.length>0?$zSpawn.prompt:void 0,startedAt:$zPart.state?.time?.start,status:$zStatus,taskType:"local_agent",type:"local_agent"};$zRegistry.register($zTask),$zRestored.push($zTask)}}if($zRestored.length>0){let $zTaskIds=$zRestored.slice(-32).map($zTask=>"- "+$zTask.taskId+" ("+$zTask.status+")").join("\n").slice(0,4e3);$zRuntime?.messageHistory?.addAttachment?.("task_status","Background agent tasks from this resumed session have been restored and are available again.\nEarlier TaskOutput errors saying \"No task found\" occurred before restoration and are stale.\nUse TaskOutput to collect results or SendMessage to continue a task. Do not assume these tasks were lost.\nRestored task IDs:\n"+$zTaskIds),$zApp.$zRestoredBackgroundTasksLog=[...($zApp.$zRestoredBackgroundTasksLog??[]),...$zRestored].slice(-64)}}catch{$zApp.$zRestoredBackgroundTasksSession=void 0}},L.readSessionUsage=async()=>await(await A()).readSessionUsage?.()??null,L.cancelBackgroundTask=async e=>await(await A()).cancelBackgroundTask?.(e)??null,L.previewFileRewind=async e=>{let t=await A();return await t.runtime?.previewWorkspaceFileRewind?.({targetMessageIds:e})??null},L.applyFileRewind=async e=>{let t=await A();return await t.runtime?.applyWorkspaceFileRewind?.({targetMessageIds:e})??null},L.setTransientModel=async e=>await(await A()).setModel?.(e,{transient:!0}),L.subscribeSessionEvents=e=>{let t=!1,r;A().then(o=>{t||(r=o.runtime?.subscribeEvents?.({onSessionEvent:e}))});return()=>{t=!0,r?.()}},L.sendBackgroundTaskMessage=async e=>{let t=await A();await L.$zRestorePersistedBackgroundTasks?.(t);let r=t.runtime,o=r?.runtimeTaskRegistry?.get?.(e?.taskId);if(!o&&typeof t.sessionId==="string"){t.$zRestoredBackgroundTasksSession=void 0;await L.$zRestorePersistedBackgroundTasks?.(t);o=r?.runtimeTaskRegistry?.get?.(e?.taskId)}if(!r?.subagentPort?.sendMessage)throw new Error("Background agent messaging is unavailable in this runtime.");if(!o||(o.type??o.taskType)!=="local_agent")throw new Error("The selected task is not a local agent.");if(typeof e?.message!=="string"||!e.message.trim())throw new Error("Enter a message for the background agent.");let n=e.message.trim().slice(0,2e4),i=(typeof e.summary==="string"?e.summary:n).replace(/\s+/g," ").trim().slice(0,200);if(e?.restart===!0&&o.status==="running"){if(!r.subagentPort.stopTask)throw new Error("Background agent restart is unavailable in this runtime.");await r.subagentPort.stopTask(e.taskId),o=r.runtimeTaskRegistry?.get?.(e.taskId);if(!o)throw new Error("The background agent stopped but could not be restored.")}return await r.subagentPort.sendMessage({sessionId:o.parentSessionId??r.getSessionId?.(),turnId:o.turnId??"tui-task-message",parentToolCallId:o.parentToolCallId??"tui-task-message",to:o.agentId??e.taskId,summary:i,message:n,workingDirectory:o.workingDirectory??r.workingDirectory,workspaceRoot:o.workspaceRoot??r.workingDirectory,trace:o.traceContext??r.rootTraceContext})},L.interruptTurn=async e=>{let t=await A(),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}},L.promoteQueuedInput=async(e,t,r)=>{let o=await A(),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 L.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 L.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)}},L.$zSendInputWithoutBackgroundRestore=L.sendInput,L.sendInput=async(...$zArgs)=>{let $zApp=await A();await L.$zRestorePersistedBackgroundTasks?.($zApp);return await L.$zSendInputWithoutBackgroundRestore.apply(L,$zArgs)},L.recallPreviousInput=async G=>await(await A()).recallPreviousInputHistory?.(G)??null,G_n(L,A,b.subscribeWorkflowEvents),L.getSessionMetadata=async()=>{let G=await A();return{locale:G.getLocale?.(),model:G.getModel?.(),theme:G.getTheme?.(),thoughtLevel:G.getThoughtLevel?.()}},L.listModelOptions=async()=>(await A()).listModels?.()??[],L.listEffortOptions=async()=>{let G=await A();return await Use(G)??[]},L.listMcpServers=async()=>(await A()).listMcpServers?.()??{},L.close=async()=>{y??=(async()=>{await I(),await ox(async()=>_?.(),k)})(),await y},L}var Z_n=T(()=>{"use strict";wl();sy();K5();cOe();aOe();AP();F1t();mkt();fkt();SK();z_n();vkt();xkt();lOe();q_n();W_n();a(H_n,"createTuiSubmitPrompt")});var K_n,J_n,Jp,eP,Mf,Y_n,Q_n,GUi,WUi,X_n,eyn,HUi,ZUi,KUi,JUi,YUi,QUi,tyn=T(()=>{"use strict";K_n=require("node:crypto"),J_n=require("node:fs"),Jp=require("node:fs/promises"),eP=require("node:os"),Mf=require("node:path"),Y_n=require("node:url"),Q_n="zcode-tui-runtime/",GUi=`${Q_n}manifest.json`,WUi="node_modules/@zcode/tui/dist/index.js",X_n="manifest.json",eyn=a(async()=>{let e=await import("node:sea");if(!e.isSea())return await import("@zcode/tui");let t=await HUi(e);return await import((0,Y_n.pathToFileURL)((0,Mf.join)(t,WUi)).href)},"loadTuiRuntime"),HUi=a(async e=>{let t=ZUi(e),r=(0,Mf.join)(JUi(),"0.16.5",t.target,t.hash),n=(0,Mf.join)(r,X_n);if(await KUi(n,t))return r;let o=`${r}.tmp-${process.pid}-${Date.now()}`;await(0,Jp.rm)(o,{force:!0,recursive:!0}),await(0,Jp.mkdir)(o,{recursive:!0});for(let i of t.files){let s=e.getRawAsset(`${Q_n}${i.path}`),u=Buffer.from(s);if((0,K_n.createHash)("sha256").update(u).digest("hex")!==i.sha256)throw new Error(`SEA TUI asset hash mismatch for ${i.path}`);let c=(0,Mf.join)(o,i.path);await(0,Jp.mkdir)((0,Mf.dirname)(c),{recursive:!0}),await(0,Jp.writeFile)(c,u),await(0,Jp.chmod)(c,i.mode??QUi(i.path))}return await(0,Jp.writeFile)(YUi(o),JSON.stringify(t,null,2)),await(0,Jp.rm)(r,{force:!0,recursive:!0}),await(0,Jp.mkdir)((0,Mf.dirname)(r),{recursive:!0}),await(0,Jp.rename)(o,r),r},"ensureSeaTuiRuntime"),ZUi=a(e=>{let t=e.getAsset(GUi,"utf8"),r=JSON.parse(t);if(r.version!==1||!r.hash||!Array.isArray(r.files))throw new Error("Invalid SEA TUI runtime manifest.");return r},"readManifest"),KUi=a(async(e,t)=>{if(!(0,J_n.existsSync)(e))return!1;try{let r=JSON.parse(await(0,Jp.readFile)(e,"utf8"));return r.hash===t.hash&&r.target===t.target}catch{return!1}},"isCacheCurrent"),JUi=a(()=>{let e=(0,eP.homedir)();return(0,eP.platform)()==="darwin"&&e?(0,Mf.join)(e,"Library","Caches","zcode","sea-assets"):(0,eP.platform)()==="win32"?(0,Mf.join)(process.env.LOCALAPPDATA??(0,Mf.join)(e||(0,eP.tmpdir)(),"AppData","Local"),"zcode","Cache","sea-assets"):(0,Mf.join)(process.env.XDG_CACHE_HOME??(0,Mf.join)(e||(0,eP.tmpdir)(),".cache"),"zcode","sea-assets")},"cacheBaseDirectory"),YUi=a(e=>(0,Mf.join)(e,X_n),"markerPathForDirectory"),QUi=a(e=>/\.(?:dll|dylib|node|so)$/i.test(e)?493:420,"modeForPath")});function ryn({deps:e,options:t,workingDirectory:r}){let n=ns({cliOverrides:XUi(t.locale),env:e.env??process.env,projectConfigPath:e.projectConfigPath,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,workingDirectory:r});return Bw(n.config.ui.locale,t.detectedLocale)}var XUi,nyn=T(()=>{"use strict";wl();sy();XUi=a(e=>e?{ui:{locale:e}}:void 0,"localeCliOverrides");a(ryn,"resolveTuiStartupLocale")});function iyn(e){let t=e.fileSystemPort??uC(),r=(0,yy.resolve)(e.workspaceDirectory);return async n=>{let o=o$i(n.token);if(!o)return{items:[],truncated:!1};let i=(0,yy.resolve)(r,o.directoryToken);if(!u$i(r,i))return{items:[],truncated:!1};try{let u=(await t.listDirectory({path:i},{signal:n.abortSignal})).entries.flatMap(c=>{if(c.kind!=="directory"&&c.kind!=="file")return[];if(c.kind==="directory"&&n$i.has(c.name))return[];if(!o.query.startsWith(".")&&c.name.startsWith("."))return[];if(!i$i(c.name,o.query))return[];let d=s$i(r,c.path);return d?[{kind:c.kind,path:c.kind==="directory"?`${d}/`:d}]:[]}).sort((c,d)=>a$i(c,d,o.query)),l=Math.max(1,Math.floor(n.limit??e$i));return{items:u.slice(0,l),truncated:u.length>l}}catch{return{items:[],truncated:!1}}}}function o$i(e){let t=e.replace(/^@/u,"");if(t.startsWith("/")||t.startsWith("\\")||(0,yy.isAbsolute)(t)||r$i.test(t))return;let r=t.replace(t$i,"/");if(r.split("/").some(o=>o===".."))return;let n=r.lastIndexOf("/");return n<0?{directoryToken:"",query:r}:{directoryToken:r.slice(0,n+1),query:r.slice(n+1)}}function i$i(e,t){return t.length===0?!0:e.toLowerCase().includes(t.toLowerCase())}function a$i(e,t,r){if(e.kind!==t.kind)return e.kind==="directory"?-1:1;let n=oyn(e.path),o=oyn(t.path),i=r.toLowerCase(),s=n.toLowerCase().startsWith(i),u=o.toLowerCase().startsWith(i);return s!==u?s?-1:1:e.path.localeCompare(t.path)}function oyn(e){let t=e.endsWith("/")?e.slice(0,-1):e,r=t.lastIndexOf("/");return r<0?t:t.slice(r+1)}function s$i(e,t){let r=(0,yy.relative)(e,t);if(!(!r||r.startsWith("..")||(0,yy.isAbsolute)(r)))return r.split(yy.sep).join("/")}function u$i(e,t){let r=(0,yy.relative)(e,t);return r===""||!r.startsWith("..")&&!(0,yy.isAbsolute)(r)}var yy,e$i,t$i,r$i,n$i,ayn=T(()=>{"use strict";dF();yy=require("node:path"),e$i=50,t$i=/[\\/]+/gu,r$i=/^[a-zA-Z]:[\\/]/u,n$i=new Set([".bzr",".git",".hg",".jj",".sl",".svn","node_modules"]);a(iyn,"createWorkspacePathSuggestionProvider");a(o$i,"parseWorkspacePathToken");a(i$i,"matchesPathQuery");a(a$i,"compareWorkspacePathSuggestion");a(oyn,"basenameFromSuggestion");a(s$i,"toWorkspaceRelativePath");a(u$i,"isPathInside")});async function uyn(e){let t=e.maxOutputBytes??p$i,r=e.timeoutMs??d$i,o=await(e.runCommand??f$i)(l$i,["-C",e.workspaceDirectory,...c$i],{maxOutputBytes:t,timeoutMs:r}).catch(()=>({exitCode:-1,stdout:""}));if(o.exitCode!==0)return;let i=o.stdout.trim().split(/\r?\n/,1)[0]?.trim();if(!(!i||i===m$i))return i}async function f$i(e,t,r){return await new Promise(n=>{let o;try{o=(0,syn.spawn)(e,t,{stdio:["ignore","pipe","ignore"],windowsHide:!0})}catch{n({exitCode:-1,stdout:""});return}let i="",s=!1,u=setTimeout(()=>{o.kill(),l({exitCode:-1,stdout:i})},r.timeoutMs),l=a(c=>{s||(s=!0,clearTimeout(u),n(c))},"finish");o.stdout?.on("data",c=>{i+=c.toString("utf8"),Buffer.byteLength(i,"utf8")>r.maxOutputBytes&&(o.kill(),l({exitCode:-1,stdout:i}))}),o.on("error",()=>l({exitCode:-1,stdout:i})),o.on("close",c=>l({exitCode:c,stdout:i}))})}var syn,l$i,c$i,d$i,p$i,m$i,lyn=T(()=>{"use strict";syn=require("node:child_process"),l$i="git",c$i=["symbolic-ref","--quiet","--short","HEAD"],d$i=750,p$i=512,m$i="HEAD";a(uyn,"resolveWorkspaceGitBranch");a(f$i,"runGitCommand")});var cyn,dyn=T(()=>{"use strict";gt();E_n();P_n();cOe();SK();vkt();lOe();Z_n();tyn();nyn();ayn();lyn();xkt();cyn=a(async(e,t,r,n,o,i,s,u=!1)=>{try{let l=$_n(o),c=r.runTui??(await eyn()).runTui,d=(r.cwd??process.cwd)(),p=r.env??process.env,m=dj(p)==="development",h=await(r.resolveWorkspaceGitBranch??uyn)({workspaceDirectory:d}).catch(()=>{}),_=ryn({deps:r,options:t,workingDirectory:d}),y=H_n(r,l,n,i,t.locale,t.detectedLocale,_,s,u,t.browserUse,t.browserExecutable),v=ipe({cleanup:a(async()=>{await y.close?.()},"cleanup"),cleanupTimeoutMs:r.shutdownCleanupTimeoutMs,exitProcess:r.exitProcess,process:r.shutdownProcess});try{let x=await e_n(r),w=x?{locale:_}:await N_n(y),b=x||!w.model?[]:await y.listModelOptions?.().catch(()=>[]),k=x||!w.model?[]:await y.listEffortOptions?.().catch(()=>[]),S=await fOe(r).catch(()=>{});return await c({initialMode:X5(l),initialModel:w.model,initialThoughtLevel:w.thoughtLevel,loginRequired:x,locale:w.locale??_,theme:w.theme??"auto",developerMode:m,version:n,workspaceDirectory:d,workspaceGitBranch:h,noColor:t.noColor,readClipboardImage:r.readClipboardImage??I_n(),effortOptions:k,modelOptions:b,listWorkspacePathSuggestions:iyn({workspaceDirectory:d}),listMcpServers:y.listMcpServers,writeClipboardText:r.writeClipboardText??R_n({stdout:e.stdout}),stderr:e.stderr,stdin:e.stdin,stdout:e.stdout,loadSessionTranscript:y.loadSessionTranscript,loadSessionContextMessages:y.loadSessionContextMessages,readGoal:y.readGoal,readTodos:y.readTodos,readRuntimeProjection:y.readRuntimeProjection,readSessionUsage:y.readSessionUsage,cancelBackgroundTask:y.cancelBackgroundTask,previewFileRewind:y.previewFileRewind,applyFileRewind:y.applyFileRewind,interruptTurn:y.interruptTurn,promoteQueuedInput:y.promoteQueuedInput,listSkills:y.listSkills,listModelOptions:y.listModelOptions,setTransientModel:y.setTransientModel,subscribeSessionEvents:y.subscribeSessionEvents,sendBackgroundTaskMessage:y.sendBackgroundTaskMessage,recallPreviousInput:y.recallPreviousInput,sendInput:y.sendInput,setMode:y.setMode,slashCommands:akt(S),submitPrompt:y,...y.refreshWorkflowPanel?{refreshWorkflowPanel:y.refreshWorkflowPanel}:{},...y.stopWorkflow?{stopWorkflow:y.stopWorkflow}:{},...y.subscribeWorkflowEvents?{subscribeWorkflowEvents:y.subscribeWorkflowEvents}:{}})}finally{v(),await y.close?.()}}catch(l){let c=l instanceof Error?l.message:String(l);return e.stderr.write(`Error: ${c}
|
|
3218
|
+
Switched to forked session ${Y.forkedSessionId}.`,restoredFileCount:Y.restoredFileCount??Y.restoredFiles?.length??0}},"forkApp"),getApp:A,getMode:a(()=>X5(t),"getMode"),getLocale:a(()=>p?.getLocale?.()??j1t(m,i)??s,"getLocale"),hasConfiguredCodingPlanApiKey:ckt(e),listCustomCommands:a(()=>fOe(e),"listCustomCommands"),listSessions:a(()=>D_n(e),"listSessions"),listSkills:a(()=>O_n(e),"listSkills"),configureApiKey:a(G=>j_n(e,G),"configureApiKey"),login:a(G=>L_n(e,G),"login"),loginBigmodel:a(G=>B_n(e,G),"loginBigmodel"),loadCustomCommand:a(G=>M_n(e,G),"loadCustomCommand"),newApp:P,recordInputHistory:a(async(G,K)=>{await p?.recordInputHistory?.(G,K)},"recordInputHistory"),resumeApp:O,logout:a(()=>F_n(e),"logout"),setLocale:a(async G=>{if(p?.setLocale){let Y=await p.setLocale(G);return m=G,Y}return m=G,{configPath:(await Lee(e.userConfigPath??tI(),G)).path,locale:j1t(G,i)??"en-US",requestedLocale:G}},"setLocale"),setMode:D}),L=a(async(G,K)=>{let Y=w;w=K.requestPermission;try{return await U(G,K)}finally{w=Y}},"submitPrompt");return L.setMode=async G=>({mode:await D(G)}),L.sendInput=async(G,K)=>{let Y=w;w=K?.requestPermission;try{let Q=await A();if(Q.sendInput){let X=await Q.sendInput(G,K);return X.kind!=="started_turn"?X:bkt(await(X.result??X.completion),Q,X5(t))}return bkt(await Q.submitPrompt(G,K),Q,X5(t))}finally{w=Y}},L.listSkills=async()=>await O_n(e),L.loadSessionTranscript=async()=>await(await A()).loadSessionTranscript?.()??[],L.loadSessionContextMessages=async()=>await(await A()).loadSessionContextMessages?.()??[],L.readGoal=async()=>await(await A()).readTarget?.()??null,L.readTodos=async()=>await(await A()).readTodos?.()??[],L.readRuntimeProjection=async()=>{let $zRuntimeProjectionBridge=await A();await L.$zRestorePersistedBackgroundTasks?.($zRuntimeProjectionBridge);let t=await $zRuntimeProjectionBridge.runtime?.getProjection?.();if(!t)return null;let r=Object.values($zRuntimeProjectionBridge.runtime?.runtimeTaskRegistry?.all?.()??{}).filter(o=>o.isBackgrounded===!0).map(o=>({taskId:o.taskId,taskKind:o.taskType??o.type,agentId:o.agentId,agentType:o.agentType,childSessionId:o.childSessionId,parentSessionId:o.parentSessionId,parentToolCallId:o.parentToolCallId,turnId:o.turnId,prompt:o.prompt,error:o.status==="running"?null:o.error instanceof Error?o.error.message:typeof o.error==="string"?o.error:void 0,outputPath:o.outputFile,status:o.status,description:o.description,startedAt:o.startedAt,completedAt:o.status==="running"?null:o.completedAt,cancelRequestedAt:o.status==="running"?null:o.cancelRequestedAt,blocked:o.status==="running"?null:o.blocked,blockedReason:o.status==="running"?null:o.blockedReason,cancellable:(o.taskType??o.type)==="local_agent"?o.status==="running":o.cancellable}));let s=Array.isArray(t.backgroundTasks)?t.backgroundTasks.slice():[];for(let $zDetail of r){let $zIndex=s.findIndex($zExisting=>$zExisting.taskId===$zDetail.taskId);if($zIndex<0)s.push($zDetail);else s[$zIndex]={...s[$zIndex],...Object.fromEntries(Object.entries($zDetail).filter(([,v])=>v!==void 0))}}return{...t,backgroundTasks:s,backgroundTaskDetails:r,restoredBackgroundTasks:Array.isArray($zRuntimeProjectionBridge.$zRestoredBackgroundTasksLog)?$zRuntimeProjectionBridge.$zRestoredBackgroundTasksLog:[]}},L.$zRestorePersistedBackgroundTasks=async $zApp=>{let $zRuntime=$zApp?.runtime,$zRegistry=$zRuntime?.runtimeTaskRegistry;if(!$zRegistry?.register||typeof $zApp?.sessionId!="string"||$zApp.sessionId===$zApp.$zRestoredBackgroundTasksSession)return;$zApp.$zRestoredBackgroundTasksSession=$zApp.sessionId,$zApp.$zRestoredBackgroundTasksLog=[];try{let $zMessages=await $zApp.loadSessionTranscript?.()??[],$zRestored=[];for(let $zMessage of $zMessages){let $zParts=Array.isArray($zMessage?.parts)?$zMessage.parts:[];for(let $zPart of $zParts){if($zPart?.type!=="tool")continue;let $zToolName=typeof $zPart.toolName==="string"?$zPart.toolName:typeof $zPart.tool==="string"?$zPart.tool:"";$zToolName=$zToolName.trim().toLowerCase();if($zToolName!=="agent"&&$zToolName!=="subagent"&&$zToolName!=="task")continue;let $zInput=$zPart.input??$zPart.state?.input,$zOutput=typeof $zPart.output==="string"?$zPart.output:$zPart.state?.output;if(typeof $zOutput!=="string"||$zOutput.trim().length===0)continue;let $zSpawn;try{$zSpawn=JSON.parse($zOutput)}catch{}if(!$zSpawn||typeof $zSpawn!=="object"||Array.isArray($zSpawn)){if(!$zOutput.includes("Async agent launched successfully."))continue;let $zAgentId=/(?:^|\n)agentId:\s*([^\s(]+)/u.exec($zOutput)?.[1],$zOutputFile=/(?:^|\n)output_file:\s*([^\r\n]+)/u.exec($zOutput)?.[1]?.trim();if(typeof $zAgentId!=="string"||$zAgentId.length===0)continue;$zSpawn={status:"async_launched",agentId:$zAgentId,agentType:typeof $zInput?.subagent_type==="string"&&$zInput.subagent_type.length>0?$zInput.subagent_type:typeof $zInput?.agentType==="string"&&$zInput.agentType.length>0?$zInput.agentType:void 0,childSessionId:"sess_subagent_"+$zAgentId,description:typeof $zInput?.description==="string"&&$zInput.description.length>0?$zInput.description:void 0,prompt:typeof $zInput?.prompt==="string"&&$zInput.prompt.length>0?$zInput.prompt:void 0,...$zOutputFile?{outputFile:$zOutputFile}:{}}}if(($zSpawn.status!=="async_launched"&&$zSpawn.status!=="backgrounded")||typeof $zSpawn.agentId!=="string"||$zSpawn.agentId.length===0)continue;let $zMetadata;if(typeof $zSpawn.outputFile==="string"&&$zSpawn.outputFile.length>0)try{let $zBuiltin=process.getBuiltinModule;if(typeof $zBuiltin==="function"){let $zFs=$zBuiltin.call(process,"node:fs"),$zPath=$zBuiltin.call(process,"node:path");$zMetadata=JSON.parse($zFs.readFileSync($zPath.join($zPath.dirname($zSpawn.outputFile),"metadata.json"),"utf8"))}}catch{}if($zMetadata&&typeof $zMetadata==="object"&&!Array.isArray($zMetadata)&&(typeof $zMetadata.agentId!=="string"||$zMetadata.agentId===$zSpawn.agentId)&&(typeof $zMetadata.parentSessionId!=="string"||$zMetadata.parentSessionId===$zApp.sessionId))$zSpawn={...$zSpawn,agentType:typeof $zMetadata.profileId==="string"&&$zMetadata.profileId.length>0?$zMetadata.profileId:$zSpawn.agentType,childSessionId:typeof $zMetadata.childSessionId==="string"&&$zMetadata.childSessionId.length>0?$zMetadata.childSessionId:$zSpawn.childSessionId,description:typeof $zMetadata.description==="string"&&$zMetadata.description.length>0?$zMetadata.description:$zSpawn.description,outputFile:typeof $zMetadata.outputFile==="string"&&$zMetadata.outputFile.length>0?$zMetadata.outputFile:$zSpawn.outputFile,prompt:typeof $zMetadata.prompt==="string"&&$zMetadata.prompt.length>0?$zMetadata.prompt:$zSpawn.prompt,error:typeof $zMetadata.error==="string"&&$zMetadata.error.length>0?$zMetadata.error:$zSpawn.error};if(typeof $zSpawn.childSessionId!=="string"||$zSpawn.childSessionId.length===0)$zSpawn.childSessionId="sess_subagent_"+$zSpawn.agentId;if($zRegistry.get?.($zSpawn.agentId))continue;let $zStatus="stopped";if($zMetadata?.status==="completed")$zStatus="completed";else if($zMetadata?.status==="failed")$zStatus="failed";let $zTask={taskId:$zSpawn.agentId,agentId:$zSpawn.agentId,agentType:typeof $zSpawn.agentType==="string"&&$zSpawn.agentType.length>0?$zSpawn.agentType:"general-purpose",childSessionId:$zSpawn.childSessionId,description:typeof $zSpawn.description==="string"&&$zSpawn.description.length>0?$zSpawn.description:void 0,error:typeof $zSpawn.error==="string"&&$zSpawn.error.length>0?$zSpawn.error:void 0,isBackgrounded:!0,outputFile:typeof $zSpawn.outputFile==="string"&&$zSpawn.outputFile.length>0?$zSpawn.outputFile:void 0,parentToolCallId:typeof $zPart.toolCallId==="string"&&$zPart.toolCallId.length>0?$zPart.toolCallId:typeof $zPart.callID==="string"&&$zPart.callID.length>0?$zPart.callID:void 0,parentSessionId:$zApp.sessionId,prompt:typeof $zSpawn.prompt==="string"&&$zSpawn.prompt.length>0?$zSpawn.prompt:void 0,startedAt:$zPart.state?.time?.start,status:$zStatus,taskType:"local_agent",type:"local_agent"};$zRegistry.register($zTask),$zRestored.push($zTask)}}if($zRestored.length>0){let $zTaskIds=$zRestored.slice(-32).map($zTask=>"- "+$zTask.taskId+" ("+$zTask.status+")").join("\n").slice(0,4e3);$zRuntime?.messageHistory?.addAttachment?.("task_status","Background agent tasks from this resumed session have been restored and are available again.\nEarlier TaskOutput errors saying \"No task found\" occurred before restoration and are stale.\nUse TaskOutput to collect results or SendMessage to continue a task. Do not assume these tasks were lost.\nRestored task IDs:\n"+$zTaskIds),$zApp.$zRestoredBackgroundTasksLog=[...($zApp.$zRestoredBackgroundTasksLog??[]),...$zRestored].slice(-64)}}catch{$zApp.$zRestoredBackgroundTasksSession=void 0}},L.readSessionUsage=async()=>await(await A()).readSessionUsage?.()??null,L.cancelBackgroundTask=async e=>await(await A()).cancelBackgroundTask?.(e)??null,L.previewFileRewind=async e=>{let t=await A();return await t.runtime?.previewWorkspaceFileRewind?.({targetMessageIds:e})??null},L.applyFileRewind=async e=>{let t=await A();return await t.runtime?.applyWorkspaceFileRewind?.({targetMessageIds:e})??null},L.setTransientModel=async e=>await(await A()).setModel?.(e,{transient:!0}),L.subscribeSessionEvents=e=>{let t=!1,r;A().then(o=>{t||(r=o.runtime?.subscribeEvents?.({onSessionEvent:e}))});return()=>{t=!0,r?.()}},L.sendBackgroundTaskMessage=async e=>{let t=await A();await L.$zRestorePersistedBackgroundTasks?.(t);let r=t.runtime,o=r?.runtimeTaskRegistry?.get?.(e?.taskId);if(!o&&typeof t.sessionId==="string"){t.$zRestoredBackgroundTasksSession=void 0;await L.$zRestorePersistedBackgroundTasks?.(t);o=r?.runtimeTaskRegistry?.get?.(e?.taskId)}if(!r?.subagentPort?.sendMessage)throw new Error("Background agent messaging is unavailable in this runtime.");if(!o||(o.type??o.taskType)!=="local_agent")throw new Error("The selected task is not a local agent.");if(typeof e?.message!=="string"||!e.message.trim())throw new Error("Enter a message for the background agent.");let n=e.message.trim().slice(0,2e4),i=(typeof e.summary==="string"?e.summary:n).replace(/\s+/g," ").trim().slice(0,200);if(e?.restart===!0&&o.status==="running"){if(!r.subagentPort.stopTask)throw new Error("Background agent restart is unavailable in this runtime.");await r.subagentPort.stopTask(e.taskId),o=r.runtimeTaskRegistry?.get?.(e.taskId);if(!o)throw new Error("The background agent stopped but could not be restored.")}return await r.subagentPort.sendMessage({sessionId:o.parentSessionId??r.getSessionId?.(),turnId:o.turnId??"tui-task-message",parentToolCallId:o.parentToolCallId??"tui-task-message",to:o.agentId??e.taskId,summary:i,message:n,workingDirectory:o.workingDirectory??r.workingDirectory,workspaceRoot:o.workspaceRoot??r.workingDirectory,trace:o.traceContext??r.rootTraceContext})},L.interruptTurn=async e=>{let t=await A(),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}},L.promoteQueuedInput=async(e,t,r)=>{let o=await A(),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 L.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 L.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)}},L.$zSendInputWithoutBackgroundRestore=L.sendInput,L.sendInput=async(...$zArgs)=>{let $zApp=await A();await L.$zRestorePersistedBackgroundTasks?.($zApp);return await L.$zSendInputWithoutBackgroundRestore.apply(L,$zArgs)},L.recallPreviousInput=async G=>await(await A()).recallPreviousInputHistory?.(G)??null,G_n(L,A,b.subscribeWorkflowEvents),L.getSessionMetadata=async()=>{let G=await A();return{locale:G.getLocale?.(),model:G.getModel?.(),theme:G.getTheme?.(),thoughtLevel:G.getThoughtLevel?.()}},L.reloadModelOptions=async()=>{let $zApp=await A(),$zConfig=ns({env:e.env??process.env,workingDirectory:(e.cwd??process.cwd)(),projectConfigPath:e.projectConfigPath,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath}).config,$zModel=$zConfig.model;if($zModel&&$zApp.setModelCatalogOverlay)await $zApp.setModelCatalogOverlay({targets:[$zModel.main,...$zModel.lite?[$zModel.lite]:[],...$zModel.available??[]],catalogOverrides:$zConfig.modelCatalog.overrides});return $zApp.listModels?.()??[]},L.listModelOptions=async()=>(await A()).listModels?.()??[],L.listEffortOptions=async()=>{let G=await A();return await Use(G)??[]},L.listMcpServers=async()=>(await A()).listMcpServers?.()??{},L.close=async()=>{y??=(async()=>{await I(),await ox(async()=>_?.(),k)})(),await y},L}var Z_n=T(()=>{"use strict";wl();sy();K5();cOe();aOe();AP();F1t();mkt();fkt();SK();z_n();vkt();xkt();lOe();q_n();W_n();a(H_n,"createTuiSubmitPrompt")});var K_n,J_n,Jp,eP,Mf,Y_n,Q_n,GUi,WUi,X_n,eyn,HUi,ZUi,KUi,JUi,YUi,QUi,tyn=T(()=>{"use strict";K_n=require("node:crypto"),J_n=require("node:fs"),Jp=require("node:fs/promises"),eP=require("node:os"),Mf=require("node:path"),Y_n=require("node:url"),Q_n="zcode-tui-runtime/",GUi=`${Q_n}manifest.json`,WUi="node_modules/@zcode/tui/dist/index.js",X_n="manifest.json",eyn=a(async()=>{let e=await import("node:sea");if(!e.isSea())return await import("@zcode/tui");let t=await HUi(e);return await import((0,Y_n.pathToFileURL)((0,Mf.join)(t,WUi)).href)},"loadTuiRuntime"),HUi=a(async e=>{let t=ZUi(e),r=(0,Mf.join)(JUi(),"0.16.5",t.target,t.hash),n=(0,Mf.join)(r,X_n);if(await KUi(n,t))return r;let o=`${r}.tmp-${process.pid}-${Date.now()}`;await(0,Jp.rm)(o,{force:!0,recursive:!0}),await(0,Jp.mkdir)(o,{recursive:!0});for(let i of t.files){let s=e.getRawAsset(`${Q_n}${i.path}`),u=Buffer.from(s);if((0,K_n.createHash)("sha256").update(u).digest("hex")!==i.sha256)throw new Error(`SEA TUI asset hash mismatch for ${i.path}`);let c=(0,Mf.join)(o,i.path);await(0,Jp.mkdir)((0,Mf.dirname)(c),{recursive:!0}),await(0,Jp.writeFile)(c,u),await(0,Jp.chmod)(c,i.mode??QUi(i.path))}return await(0,Jp.writeFile)(YUi(o),JSON.stringify(t,null,2)),await(0,Jp.rm)(r,{force:!0,recursive:!0}),await(0,Jp.mkdir)((0,Mf.dirname)(r),{recursive:!0}),await(0,Jp.rename)(o,r),r},"ensureSeaTuiRuntime"),ZUi=a(e=>{let t=e.getAsset(GUi,"utf8"),r=JSON.parse(t);if(r.version!==1||!r.hash||!Array.isArray(r.files))throw new Error("Invalid SEA TUI runtime manifest.");return r},"readManifest"),KUi=a(async(e,t)=>{if(!(0,J_n.existsSync)(e))return!1;try{let r=JSON.parse(await(0,Jp.readFile)(e,"utf8"));return r.hash===t.hash&&r.target===t.target}catch{return!1}},"isCacheCurrent"),JUi=a(()=>{let e=(0,eP.homedir)();return(0,eP.platform)()==="darwin"&&e?(0,Mf.join)(e,"Library","Caches","zcode","sea-assets"):(0,eP.platform)()==="win32"?(0,Mf.join)(process.env.LOCALAPPDATA??(0,Mf.join)(e||(0,eP.tmpdir)(),"AppData","Local"),"zcode","Cache","sea-assets"):(0,Mf.join)(process.env.XDG_CACHE_HOME??(0,Mf.join)(e||(0,eP.tmpdir)(),".cache"),"zcode","sea-assets")},"cacheBaseDirectory"),YUi=a(e=>(0,Mf.join)(e,X_n),"markerPathForDirectory"),QUi=a(e=>/\.(?:dll|dylib|node|so)$/i.test(e)?493:420,"modeForPath")});function ryn({deps:e,options:t,workingDirectory:r}){let n=ns({cliOverrides:XUi(t.locale),env:e.env??process.env,projectConfigPath:e.projectConfigPath,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,workingDirectory:r});return Bw(n.config.ui.locale,t.detectedLocale)}var XUi,nyn=T(()=>{"use strict";wl();sy();XUi=a(e=>e?{ui:{locale:e}}:void 0,"localeCliOverrides");a(ryn,"resolveTuiStartupLocale")});function iyn(e){let t=e.fileSystemPort??uC(),r=(0,yy.resolve)(e.workspaceDirectory);return async n=>{let o=o$i(n.token);if(!o)return{items:[],truncated:!1};let i=(0,yy.resolve)(r,o.directoryToken);if(!u$i(r,i))return{items:[],truncated:!1};try{let u=(await t.listDirectory({path:i},{signal:n.abortSignal})).entries.flatMap(c=>{if(c.kind!=="directory"&&c.kind!=="file")return[];if(c.kind==="directory"&&n$i.has(c.name))return[];if(!o.query.startsWith(".")&&c.name.startsWith("."))return[];if(!i$i(c.name,o.query))return[];let d=s$i(r,c.path);return d?[{kind:c.kind,path:c.kind==="directory"?`${d}/`:d}]:[]}).sort((c,d)=>a$i(c,d,o.query)),l=Math.max(1,Math.floor(n.limit??e$i));return{items:u.slice(0,l),truncated:u.length>l}}catch{return{items:[],truncated:!1}}}}function o$i(e){let t=e.replace(/^@/u,"");if(t.startsWith("/")||t.startsWith("\\")||(0,yy.isAbsolute)(t)||r$i.test(t))return;let r=t.replace(t$i,"/");if(r.split("/").some(o=>o===".."))return;let n=r.lastIndexOf("/");return n<0?{directoryToken:"",query:r}:{directoryToken:r.slice(0,n+1),query:r.slice(n+1)}}function i$i(e,t){return t.length===0?!0:e.toLowerCase().includes(t.toLowerCase())}function a$i(e,t,r){if(e.kind!==t.kind)return e.kind==="directory"?-1:1;let n=oyn(e.path),o=oyn(t.path),i=r.toLowerCase(),s=n.toLowerCase().startsWith(i),u=o.toLowerCase().startsWith(i);return s!==u?s?-1:1:e.path.localeCompare(t.path)}function oyn(e){let t=e.endsWith("/")?e.slice(0,-1):e,r=t.lastIndexOf("/");return r<0?t:t.slice(r+1)}function s$i(e,t){let r=(0,yy.relative)(e,t);if(!(!r||r.startsWith("..")||(0,yy.isAbsolute)(r)))return r.split(yy.sep).join("/")}function u$i(e,t){let r=(0,yy.relative)(e,t);return r===""||!r.startsWith("..")&&!(0,yy.isAbsolute)(r)}var yy,e$i,t$i,r$i,n$i,ayn=T(()=>{"use strict";dF();yy=require("node:path"),e$i=50,t$i=/[\\/]+/gu,r$i=/^[a-zA-Z]:[\\/]/u,n$i=new Set([".bzr",".git",".hg",".jj",".sl",".svn","node_modules"]);a(iyn,"createWorkspacePathSuggestionProvider");a(o$i,"parseWorkspacePathToken");a(i$i,"matchesPathQuery");a(a$i,"compareWorkspacePathSuggestion");a(oyn,"basenameFromSuggestion");a(s$i,"toWorkspaceRelativePath");a(u$i,"isPathInside")});async function uyn(e){let t=e.maxOutputBytes??p$i,r=e.timeoutMs??d$i,o=await(e.runCommand??f$i)(l$i,["-C",e.workspaceDirectory,...c$i],{maxOutputBytes:t,timeoutMs:r}).catch(()=>({exitCode:-1,stdout:""}));if(o.exitCode!==0)return;let i=o.stdout.trim().split(/\r?\n/,1)[0]?.trim();if(!(!i||i===m$i))return i}async function f$i(e,t,r){return await new Promise(n=>{let o;try{o=(0,syn.spawn)(e,t,{stdio:["ignore","pipe","ignore"],windowsHide:!0})}catch{n({exitCode:-1,stdout:""});return}let i="",s=!1,u=setTimeout(()=>{o.kill(),l({exitCode:-1,stdout:i})},r.timeoutMs),l=a(c=>{s||(s=!0,clearTimeout(u),n(c))},"finish");o.stdout?.on("data",c=>{i+=c.toString("utf8"),Buffer.byteLength(i,"utf8")>r.maxOutputBytes&&(o.kill(),l({exitCode:-1,stdout:i}))}),o.on("error",()=>l({exitCode:-1,stdout:i})),o.on("close",c=>l({exitCode:c,stdout:i}))})}var syn,l$i,c$i,d$i,p$i,m$i,lyn=T(()=>{"use strict";syn=require("node:child_process"),l$i="git",c$i=["symbolic-ref","--quiet","--short","HEAD"],d$i=750,p$i=512,m$i="HEAD";a(uyn,"resolveWorkspaceGitBranch");a(f$i,"runGitCommand")});var cyn,dyn=T(()=>{"use strict";gt();E_n();P_n();cOe();SK();vkt();lOe();Z_n();tyn();nyn();ayn();lyn();xkt();cyn=a(async(e,t,r,n,o,i,s,u=!1)=>{try{let l=$_n(o),c=r.runTui??(await eyn()).runTui,d=(r.cwd??process.cwd)(),p=r.env??process.env,m=dj(p)==="development",h=await(r.resolveWorkspaceGitBranch??uyn)({workspaceDirectory:d}).catch(()=>{}),_=ryn({deps:r,options:t,workingDirectory:d}),y=H_n(r,l,n,i,t.locale,t.detectedLocale,_,s,u,t.browserUse,t.browserExecutable),v=ipe({cleanup:a(async()=>{await y.close?.()},"cleanup"),cleanupTimeoutMs:r.shutdownCleanupTimeoutMs,exitProcess:r.exitProcess,process:r.shutdownProcess});try{let x=await e_n(r),w=x?{locale:_}:await N_n(y),b=x||!w.model?[]:await y.listModelOptions?.().catch(()=>[]),k=x||!w.model?[]:await y.listEffortOptions?.().catch(()=>[]),S=await fOe(r).catch(()=>{});return await c({initialMode:X5(l),initialModel:w.model,initialThoughtLevel:w.thoughtLevel,loginRequired:x,locale:w.locale??_,theme:w.theme??"auto",developerMode:m,version:n,workspaceDirectory:d,workspaceGitBranch:h,noColor:t.noColor,readClipboardImage:r.readClipboardImage??I_n(),effortOptions:k,modelOptions:b,listWorkspacePathSuggestions:iyn({workspaceDirectory:d}),listMcpServers:y.listMcpServers,writeClipboardText:r.writeClipboardText??R_n({stdout:e.stdout}),stderr:e.stderr,stdin:e.stdin,stdout:e.stdout,loadSessionTranscript:y.loadSessionTranscript,loadSessionContextMessages:y.loadSessionContextMessages,readGoal:y.readGoal,readTodos:y.readTodos,readRuntimeProjection:y.readRuntimeProjection,readSessionUsage:y.readSessionUsage,cancelBackgroundTask:y.cancelBackgroundTask,previewFileRewind:y.previewFileRewind,applyFileRewind:y.applyFileRewind,interruptTurn:y.interruptTurn,promoteQueuedInput:y.promoteQueuedInput,listSkills:y.listSkills,reloadModelOptions:y.reloadModelOptions,listModelOptions:y.listModelOptions,setTransientModel:y.setTransientModel,subscribeSessionEvents:y.subscribeSessionEvents,sendBackgroundTaskMessage:y.sendBackgroundTaskMessage,recallPreviousInput:y.recallPreviousInput,sendInput:y.sendInput,setMode:y.setMode,slashCommands:akt(S),submitPrompt:y,...y.refreshWorkflowPanel?{refreshWorkflowPanel:y.refreshWorkflowPanel}:{},...y.stopWorkflow?{stopWorkflow:y.stopWorkflow}:{},...y.subscribeWorkflowEvents?{subscribeWorkflowEvents:y.subscribeWorkflowEvents}:{}})}finally{v(),await y.close?.()}}catch(l){let c=l instanceof Error?l.message:String(l);return e.stderr.write(`Error: ${c}
|
|
3219
3219
|
`),t.verbose&&l instanceof Error&&l.stack&&e.stderr.write(`${l.stack}
|
|
3220
3220
|
`),1}},"runTuiCommand")});var hyn={};_o(hyn,{run:()=>U$i});var fyn,xT,h$i,g$i,_$i,y$i,v$i,x$i,b$i,w$i,k$i,S$i,gOe,pyn,I$i,T$i,myn,C$i,E$i,A$i,R$i,P$i,M$i,O$i,D$i,N$i,L$i,B$i,j$i,hOe,F$i,z$i,U$i,gyn=T(()=>{"use strict";fyn=require("node:util");ake();sl();sl();sy();AP();XGr();jhn();F1t();K5();Vhn();Qhn();rgn();q1t();vOe();W9e();__n();w_n();hkt();dyn();xT="0.16.5",h$i="--target requires non-empty text.",g$i="yolo",_$i="--force-mcs can only be used with --prompt, --target, or tui.",y$i="--target-replace requires --target.",v$i='--target cannot be used with --prompt. Use either --target <objective> or --prompt "/goal <objective>".',x$i=new Set(["--disallowedTools","--disallowed-tools"]),b$i="--browser-executable requires --browser-use=headless.",w$i="--browser-use=headless can only be used with --prompt, --target, or tui.",k$i="--surface can only be used with --prompt, --target, app-server, or agent-server.",S$i=a(e=>(0,fyn.parseArgs)({allowPositionals:!0,args:e,options:{help:{short:"h",type:"boolean"},json:{type:"boolean"},"output-format":{type:"string"},"no-color":{type:"boolean"},"no-browser":{type:"boolean"},"browser-use":{type:"string"},"browser-executable":{type:"string"},prompt:{short:"p",type:"string"},attach:{multiple:!0,type:"string"},cwd:{type:"string"},locale:{type:"string"},resume:{type:"string"},target:{type:"string"},"target-replace":{type:"boolean"},continue:{short:"c",type:"boolean"},force:{short:"f",type:"boolean"},"force-mcs":{type:"boolean"},mode:{type:"string"},verbose:{type:"boolean"},version:{short:"v",type:"boolean"},stdio:{type:"boolean"},surface:{type:"string"}},strict:!0}),"parseGlobalArgs"),gOe=a(e=>e[0]??"tui","commandName"),pyn=a(e=>typeof e.prompt=="string"||e.targetRequest!==void 0||gOe(e.positionals)==="tui","isForceMcsSupportedInvocation"),I$i=a(e=>{let t=gOe(e.positionals);return typeof e.prompt=="string"||e.targetRequest!==void 0||t==="app-server"||t==="agent-server"},"isPresentationSurfaceSupportedInvocation"),T$i=a((e,t,r,n,o,i)=>({browserExecutable:o,browserUse:n,detectedLocale:r,force:e.force===!0,json:e.json===!0,locale:t,noColor:e["no-color"]===!0,...i?{outputFormat:i}:{},verbose:e.verbose===!0}),"globalOptions"),myn=["text","json","stream-json"],C$i=a(e=>{if(e!==void 0){if(myn.includes(e))return e;throw new Error(`--output-format must be one of ${myn.join(", ")} (received: ${e}).`)}},"normalizeOutputFormat"),E$i=a(e=>{if(e!==void 0){if(Qie(e))return e;throw new Error(y2().cli.errors.localeUnsupported(e))}},"normalizeLocaleOption"),A$i=a(e=>{if(e===void 0)return;let t=e.toLowerCase();if(t==="build"||t==="plan"||t==="edit"||t==="yolo")return t;throw new Error(`Unsupported --mode value: ${e}. Supported modes: build, edit, plan, yolo.`)},"normalizePromptMode"),R$i=a(e=>{if(e!==void 0){if(e.toLowerCase()==="headless")return"headless";throw new Error(`Unsupported --browser-use value: ${e}. Supported value: headless.`)}},"normalizeBrowserUse"),P$i=a(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"),M$i=a(e=>{let t=[],r=[];for(let n=0;n<e.length;n+=1){let o=e[n],i=o.match(/^(--disallowedTools|--disallowed-tools)=(.*)$/);if(i){r.push(i[2]??"");continue}if(!x$i.has(o)){t.push(o);continue}let s=!1;for(;n+1<e.length&&!O$i(e[n+1]);)r.push(e[n+1]),n+=1,s=!0;if(!s)throw new Error(`${o} requires at least one tool.`)}return{args:t,toolDisallowlist:D$i(r)}},"extractDisallowedToolsArgs"),O$i=a(e=>e==="--"||/^-[^-]?|^--/.test(e),"isCliOptionToken"),D$i=a(e=>{let t=[],r=new Set;for(let n of e)for(let o of N$i(n)){let i=L$i(o);!i||r.has(i)||(r.add(i),t.push(i))}return t.length>0?t:void 0},"normalizeCliToolRuleList"),N$i=a(e=>{let t=[],r="",n=!1,o=a(()=>{let i=r.trim();i&&t.push(i),r=""},"flush");for(let i of e)switch(i){case"(":n=!0,r+=i;break;case")":n=!1,r+=i;break;case",":n?r+=i:o();break;case" ":n?r+=i:o();break;default:r+=i;break}return o(),t},"splitCliToolRules"),L$i=a(e=>e?e==="web_search"?"WebSearch":e.startsWith("web_search(")?`WebSearch${e.slice(10)}`:e:"","normalizeCliToolRule"),B$i=a(e=>{let t=e.target,r=e["target-replace"]===!0;if(t===void 0){if(r)throw new Error(y$i);return}let n=t.trim();if(n.length===0)throw new Error(h$i);return{objective:n,replaceExisting:r}},"normalizeTargetRequest"),j$i=a(e=>e.replaceExisting?`/goal replace ${e.objective}`:`/goal ${e.objective}`,"buildHeadlessTargetCommand"),hOe=a((e,t,r)=>{e.write(QGr(xT,t,r))},"writeHelp"),F$i=a((e,t,r)=>{let n=Z_t(),o={cli:{name:Rkt,processName:yOe,version:xT},runtime:{arch:n.arch,cwd:r,execPath:n.execPath,node:n.node,platform:n.platform,processTitle:process.title,sea:n.sea},packaging:{default:"node-bundle",sea:"optional"}};if(t.json)return e.stdout.write(hc(o)),0;let i=W_t(e.stdout,t.noColor);return e.stdout.write(`${H_t.bold("zcode doctor",i)}
|
|
3221
3221
|
`),e.stdout.write(`version: ${o.cli.version}
|