zcode-app-cli 4.0.0-49 → 4.0.0-51

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.
@@ -1,16 +1,16 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { execFile, spawn } from "node:child_process";
3
3
  import { accessSync, appendFileSync, closeSync, constants, fstatSync, openSync, readFileSync, readSync, writeSync } from "node:fs";
4
- import { constants as constants$1, homedir } from "node:os";
4
+ import { constants as constants$1, homedir, release, userInfo } from "node:os";
5
5
  import { access, link, mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
6
6
  import { basename, dirname, extname, isAbsolute, join, posix, resolve, sep, win32 } from "node:path";
7
- import { randomUUID } from "node:crypto";
7
+ import { createDecipheriv, createHash, randomUUID } from "node:crypto";
8
8
  import { isDeepStrictEqual, promisify } from "node:util";
9
9
  import { AsyncLocalStorage } from "node:async_hooks";
10
+ import { DatabaseSync } from "node:sqlite";
10
11
  import { isatty } from "node:tty";
11
12
  import { Box, CombinedAutocompleteProvider, Container, Editor, Image, Input, Markdown, ProcessTerminal, ScrollView, SelectList, Spacer, Text, TuiAltScreen, TuiMainScreen, VStack, decodeKittyPrintable, getKeybindings, isKeyRelease, isViewportTUI, matchesKey, renderFakeCursor, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
12
13
  import { AltScreenSearchComponent } from "@earendil-works/pi-tui/dist/alt-screen-search.js";
13
- import { DatabaseSync } from "node:sqlite";
14
14
  import { StringDecoder } from "node:string_decoder";
15
15
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
16
16
  var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
@@ -66,6 +66,7 @@ var setting_example_default = {
66
66
  "theme": "auto",
67
67
  "tuiMode": "regular",
68
68
  "toolCallStyle": "regular",
69
+ "quotaStatusline": false,
69
70
  "copyOnSelect": true,
70
71
  "notifications": {
71
72
  "method": "auto",
@@ -278,7 +279,7 @@ async function updateCliSettings(update, env = process.env) {
278
279
  await rm(temporaryPath, { force: true }).catch(() => {});
279
280
  }
280
281
  }
281
- function record$7(value) {
282
+ function record$8(value) {
282
283
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
283
284
  }
284
285
  /**
@@ -307,9 +308,9 @@ async function readConfiguredModelAccess(env = process.env) {
307
308
  } catch (error) {
308
309
  return null;
309
310
  }
310
- const root = record$7(value), config = record$7(root?.config);
311
+ const root = record$8(value), config = record$8(root?.config);
311
312
  if (root?.schemaVersion !== 1 || !config) return null;
312
- const selection = record$7(config.defaultModelSelection);
313
+ const selection = record$8(config.defaultModelSelection);
313
314
  const providerId = typeof selection?.providerId === "string" ? selection.providerId.trim() : "";
314
315
  const modelId = typeof selection?.modelId === "string" ? selection.modelId.trim() : "";
315
316
  if (!providerId || !modelId) return null;
@@ -319,23 +320,23 @@ async function readConfiguredModelAccess(env = process.env) {
319
320
  providerId
320
321
  };
321
322
  if (providerId.startsWith("account:")) try {
322
- return accountProviderConfigured(record$7(JSON.parse(await readFile(credentialsPath(env), "utf8"))) ?? {}, providerId) ? result : null;
323
+ return accountProviderConfigured(record$8(JSON.parse(await readFile(credentialsPath(env), "utf8"))) ?? {}, providerId) ? result : null;
323
324
  } catch {
324
325
  return null;
325
326
  }
326
- const rules = record$7(config.providerConfigRules)?.providerRules;
327
+ const rules = record$8(config.providerConfigRules)?.providerRules;
327
328
  if (!Array.isArray(rules)) return null;
328
- const settings = record$7(rules.map(record$7).find((rule) => rule?.providerId === providerId)?.config), access = record$7(settings?.access);
329
+ const settings = record$8(rules.map(record$8).find((rule) => rule?.providerId === providerId)?.config), access = record$8(settings?.access);
329
330
  return settings?.visibility !== "hidden" && typeof access?.apiKey === "string" && access.apiKey.trim() && (!Array.isArray(settings?.personalModelIds) || settings.personalModelIds.includes(modelId)) ? result : null;
330
331
  }
331
332
  /** A native personal provider can be usable without a saved default selection. */
332
333
  async function hasConfiguredProviderAccess(env = process.env) {
333
334
  if (await readConfiguredModelAccess(env)) return true;
334
335
  try {
335
- const value = record$7(JSON.parse(await readFile(providerConfigPath(env), "utf8")));
336
- const rules = record$7(record$7(value?.config)?.providerConfigRules)?.providerRules;
336
+ const value = record$8(JSON.parse(await readFile(providerConfigPath(env), "utf8")));
337
+ const rules = record$8(record$8(value?.config)?.providerConfigRules)?.providerRules;
337
338
  return value?.schemaVersion === 1 && Array.isArray(rules) && rules.some((raw) => {
338
- const rule = record$7(raw), config = record$7(rule?.config), access = record$7(config?.access);
339
+ const rule = record$8(raw), config = record$8(rule?.config), access = record$8(config?.access);
339
340
  return rule?.enabled !== false && config?.visibility !== "hidden" && typeof access?.apiKey === "string" && access.apiKey.trim().length > 0 && (typeof rule?.templateId === "string" || Array.isArray(config?.personalModelIds) && config.personalModelIds.length > 0);
340
341
  });
341
342
  } catch {
@@ -363,7 +364,7 @@ async function clearSetupPending(env = process.env) {
363
364
  }
364
365
  //#endregion
365
366
  //#region src/prompt-preflight.ts
366
- function record$6(value) {
367
+ function record$7(value) {
367
368
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
368
369
  }
369
370
  async function exists(path) {
@@ -392,29 +393,85 @@ async function missingCodingPlanKey(options = {}) {
392
393
  const message = (providerId) => `Model access is not configured${providerId ? ` for ${providerId}` : ""}. Run /login or /setup in zcode, or configure its API key before sending a prompt. No model request was sent.`;
393
394
  let root;
394
395
  try {
395
- root = record$6(JSON.parse(await readFile(providerConfigPath(env), "utf8")));
396
+ root = record$7(JSON.parse(await readFile(providerConfigPath(env), "utf8")));
396
397
  } catch (error) {
397
398
  return error.code === "ENOENT" && !options.model ? message() : void 0;
398
399
  }
399
- const config = record$6(root?.config);
400
+ const config = record$7(root?.config);
400
401
  if (root?.schemaVersion !== 1 || !config) return void 0;
401
- const selection = record$6(config.defaultModelSelection);
402
+ const selection = record$7(config.defaultModelSelection);
402
403
  const model = options.model ?? (typeof selection?.providerId === "string" && typeof selection.modelId === "string" ? `${selection.providerId}/${selection.modelId}` : void 0);
403
404
  if (!model) return await hasConfiguredProviderAccess(env) ? void 0 : message();
404
405
  const separator = model.indexOf("/");
405
406
  if (separator <= 0) return void 0;
406
407
  const providerId = model.slice(0, separator), modelId = model.slice(separator + 1);
407
408
  if (providerId.startsWith("account:")) return void 0;
408
- const rules = record$6(config.providerConfigRules)?.providerRules;
409
+ const rules = record$7(config.providerConfigRules)?.providerRules;
409
410
  if (!Array.isArray(rules)) return void 0;
410
- const settings = record$6(rules.map(record$6).find((rule) => rule?.providerId === providerId)?.config), auth = record$6(settings?.access), api = record$6(settings?.api);
411
- if (!settings || !["api-key", "zhipu-coding-plan-api-key"].includes(String(auth?.type)) || typeof auth?.apiKey === "string" && auth.apiKey.trim() || auth?.apiKey !== void 0 && typeof auth.apiKey !== "string" || Object.keys(record$6(api?.headers) ?? {}).length > 0 || Array.isArray(settings.personalModelIds) && !settings.personalModelIds.includes(modelId)) return void 0;
411
+ const settings = record$7(rules.map(record$7).find((rule) => rule?.providerId === providerId)?.config), auth = record$7(settings?.access), api = record$7(settings?.api);
412
+ if (!settings || !["api-key", "zhipu-coding-plan-api-key"].includes(String(auth?.type)) || typeof auth?.apiKey === "string" && auth.apiKey.trim() || auth?.apiKey !== void 0 && typeof auth.apiKey !== "string" || Object.keys(record$7(api?.headers) ?? {}).length > 0 || Array.isArray(settings.personalModelIds) && !settings.personalModelIds.includes(modelId)) return void 0;
412
413
  return message(providerId);
413
414
  }
415
+ new AsyncLocalStorage();
414
416
  promisify(execFile);
415
417
  promisify(execFile);
416
418
  new AsyncLocalStorage();
417
419
  //#endregion
420
+ //#region src/shared-oauth.ts
421
+ function profileIdentity(value) {
422
+ if (!value) return null;
423
+ try {
424
+ const profile = JSON.parse(value);
425
+ const id = profile?.user_id ?? profile?.id ?? profile?.rawProfile?.user_id;
426
+ return typeof id === "string" && id.trim() ? id.trim() : null;
427
+ } catch {
428
+ return null;
429
+ }
430
+ }
431
+ //#endregion
432
+ //#region src/start-plan.ts
433
+ function usableToken(value) {
434
+ const token = value?.trim().replace(/^Bearer\s+/iu, "").trim();
435
+ const parts = token?.split(".");
436
+ if (!parts || parts.length !== 3 || parts.some((part) => !part)) return void 0;
437
+ try {
438
+ const claims = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
439
+ if (!claims || typeof claims !== "object" || Array.isArray(claims)) return void 0;
440
+ const now = Date.now() / 1e3;
441
+ if (claims.exp !== void 0 && (typeof claims.exp !== "number" || !Number.isFinite(claims.exp) || claims.exp <= now)) return void 0;
442
+ if (claims.nbf !== void 0 && (typeof claims.nbf !== "number" || !Number.isFinite(claims.nbf) || claims.nbf > now)) return void 0;
443
+ return token;
444
+ } catch {
445
+ return;
446
+ }
447
+ }
448
+ async function readStartPlanSession(store, signal) {
449
+ signal?.throwIfAborted();
450
+ const activeKey = "oauth:active_provider", tokenKey = "zcodejwttoken";
451
+ const active = await store.loadMany([activeKey]);
452
+ signal?.throwIfAborted();
453
+ const family = active[activeKey];
454
+ if (family !== "zai" && family !== "bigmodel") return void 0;
455
+ const profileKey = `oauth:${family}:user_info`;
456
+ const keys = [
457
+ activeKey,
458
+ tokenKey,
459
+ profileKey
460
+ ];
461
+ const values = await store.loadMany(keys);
462
+ signal?.throwIfAborted();
463
+ const identity = profileIdentity(values[profileKey]), token = usableToken(values[tokenKey]);
464
+ if (values[activeKey] !== family || !identity || !token) return void 0;
465
+ const current = await store.loadMany(keys);
466
+ signal?.throwIfAborted();
467
+ if (keys.some((key) => current[key] !== values[key])) return void 0;
468
+ return {
469
+ family,
470
+ identity,
471
+ token
472
+ };
473
+ }
474
+ //#endregion
418
475
  //#region src/runtime-keychain-recovery.ts
419
476
  function recoveryError(message, cause) {
420
477
  return Object.assign(new Error(message, { cause }), { code: "CREDENTIAL_SECURE_STORAGE_UNAVAILABLE" });
@@ -515,14 +572,14 @@ function createKeychainRecovery(options = {}) {
515
572
  createKeychainRecovery();
516
573
  //#endregion
517
574
  //#region src/runtime-config-bridge.ts
518
- function record$5(value) {
575
+ function record$6(value) {
519
576
  return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
520
577
  }
521
578
  async function writeTuiShowReasoning(value, env = process.env) {
522
579
  const filePath = desktopSettingsPath(env);
523
580
  let settings = {};
524
581
  try {
525
- const existing = record$5(JSON.parse(await readFile(filePath, "utf8")));
582
+ const existing = record$6(JSON.parse(await readFile(filePath, "utf8")));
526
583
  if (!existing) throw new Error("Desktop setting.json must contain an object.");
527
584
  settings = existing;
528
585
  } catch (error) {
@@ -157338,18 +157395,18 @@ function taskFailure(status) {
157338
157395
  function bounded(value) {
157339
157396
  return value.length <= maximumEntryCharacters ? value : value.slice(0, maximumEntryCharacters) + "\n[truncated]";
157340
157397
  }
157341
- function record$4(value) {
157398
+ function record$5(value) {
157342
157399
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
157343
157400
  }
157344
157401
  function explicitlyBackgroundAgentInput(value) {
157345
- return record$4(value)?.run_in_background === true;
157402
+ return record$5(value)?.run_in_background === true;
157346
157403
  }
157347
157404
  function asyncAgentResult(value) {
157348
- const root = record$4(value);
157405
+ const root = record$5(value);
157349
157406
  return [
157350
157407
  root,
157351
- record$4(root?.output),
157352
- record$4(root?.result)
157408
+ record$5(root?.output),
157409
+ record$5(root?.result)
157353
157410
  ].some((candidate) => candidate?.isAsync === true || candidate?.status === "async_launched" || candidate?.status === "backgrounded" || typeof candidate?.backgroundTaskId === "string");
157354
157411
  }
157355
157412
  function toolScope(event) {
@@ -162164,6 +162221,7 @@ function permissionRequestSignal(context) {
162164
162221
  //#region src/app-server-client.ts
162165
162222
  const maximumOutputBytes = 16 * 1024 * 1024;
162166
162223
  const forceTerminationDelayMilliseconds = 500;
162224
+ const cooperativeCancellationDelayMilliseconds = 3e3;
162167
162225
  var AppServerRequestError = class extends Error {
162168
162226
  code;
162169
162227
  data;
@@ -162190,6 +162248,14 @@ var AppServerCancellationError = class extends Error {
162190
162248
  this.name = "AbortError";
162191
162249
  }
162192
162250
  };
162251
+ var AppServerTimeoutError = class extends Error {
162252
+ timeoutMs;
162253
+ constructor(timeoutMs) {
162254
+ super(`App-server request timed out after ${timeoutMs}ms.`);
162255
+ this.timeoutMs = timeoutMs;
162256
+ this.name = "TimeoutError";
162257
+ }
162258
+ };
162193
162259
  function signalExitCode$1(signal) {
162194
162260
  if (!signal) return 1;
162195
162261
  const number = constants$1.signals[signal];
@@ -162240,6 +162306,7 @@ function responseEnvelope(stdout) {
162240
162306
  }
162241
162307
  async function requestAppServer(request) {
162242
162308
  if (request.signal?.aborted) throw cancellationError(request.signal);
162309
+ if (request.timeoutMs !== void 0 && (!Number.isInteger(request.timeoutMs) || request.timeoutMs <= 0 || request.timeoutMs > 2147483647)) throw new Error("App-server timeoutMs must be an integer between 1 and 2147483647.");
162243
162310
  const child = spawn(request.transport.command, request.transport.args, {
162244
162311
  cwd: request.transport.cwd,
162245
162312
  env: request.transport.env,
@@ -162253,6 +162320,9 @@ async function requestAppServer(request) {
162253
162320
  let launchError;
162254
162321
  let overflow = false;
162255
162322
  let forceTerminationTimer;
162323
+ let requestTimeoutTimer;
162324
+ let timedOut = false;
162325
+ let cancelling = false;
162256
162326
  const exited = new Promise((resolve) => {
162257
162327
  let settled = false;
162258
162328
  const finish = (code) => {
@@ -162270,7 +162340,7 @@ async function requestAppServer(request) {
162270
162340
  overflow = true;
162271
162341
  child.kill("SIGKILL");
162272
162342
  };
162273
- const onAbort = () => {
162343
+ const terminate = () => {
162274
162344
  if (child.exitCode !== null || child.signalCode !== null) return;
162275
162345
  child.kill(terminationSignal(request.signal));
162276
162346
  forceTerminationTimer = setTimeout(() => {
@@ -162278,8 +162348,19 @@ async function requestAppServer(request) {
162278
162348
  }, forceTerminationDelayMilliseconds);
162279
162349
  forceTerminationTimer.unref();
162280
162350
  };
162281
- request.signal?.addEventListener("abort", onAbort, { once: true });
162282
- if (request.signal?.aborted) onAbort();
162351
+ const onAbort = () => {
162352
+ if (cancelling || child.exitCode !== null || child.signalCode !== null) return;
162353
+ cancelling = true;
162354
+ if (requestTimeoutTimer) clearTimeout(requestTimeoutTimer);
162355
+ if (request.cancellation && !child.stdin.writableEnded && !child.stdin.destroyed) {
162356
+ child.stdin.end(`${JSON.stringify({
162357
+ id: 2,
162358
+ ...request.cancellation
162359
+ })}\n`);
162360
+ forceTerminationTimer = setTimeout(terminate, cooperativeCancellationDelayMilliseconds);
162361
+ forceTerminationTimer.unref();
162362
+ } else terminate();
162363
+ };
162283
162364
  child.stdin.on("error", () => {});
162284
162365
  const decoder = new StringDecoder("utf8");
162285
162366
  let pending = "";
@@ -162297,12 +162378,22 @@ async function requestAppServer(request) {
162297
162378
  method: request.method,
162298
162379
  params: request.params
162299
162380
  })}\n`);
162381
+ request.signal?.addEventListener("abort", onAbort, { once: true });
162382
+ if (request.signal?.aborted) onAbort();
162383
+ else if (request.timeoutMs !== void 0) {
162384
+ requestTimeoutTimer = setTimeout(() => {
162385
+ timedOut = true;
162386
+ onAbort();
162387
+ }, request.timeoutMs);
162388
+ requestTimeoutTimer.unref();
162389
+ }
162300
162390
  try {
162301
162391
  const [code, stdout, stderr] = await Promise.all([
162302
162392
  exited,
162303
162393
  stdoutPromise,
162304
162394
  readBounded(child.stderr, terminateForOverflow)
162305
162395
  ]);
162396
+ if (timedOut) throw new AppServerTimeoutError(request.timeoutMs);
162306
162397
  if (request.signal?.aborted) throw cancellationError(request.signal);
162307
162398
  if (overflow) throw new Error(`App-server output exceeded ${maximumOutputBytes} bytes.`);
162308
162399
  if (launchError) throw launchError;
@@ -162313,6 +162404,7 @@ async function requestAppServer(request) {
162313
162404
  if (stderr) request.onStderr?.(stderr);
162314
162405
  return envelope.result;
162315
162406
  } finally {
162407
+ if (requestTimeoutTimer) clearTimeout(requestTimeoutTimer);
162316
162408
  if (forceTerminationTimer) clearTimeout(forceTerminationTimer);
162317
162409
  request.signal?.removeEventListener("abort", onAbort);
162318
162410
  }
@@ -162624,11 +162716,11 @@ function findExecutable(name, env = process.env, platform = process.platform) {
162624
162716
  }
162625
162717
  return null;
162626
162718
  }
162627
- function record$3(value) {
162719
+ function record$4(value) {
162628
162720
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
162629
162721
  }
162630
162722
  function configuredNotifications(config) {
162631
- return record$3(record$3(record$3(config)?.ui)?.notifications);
162723
+ return record$4(record$4(record$4(config)?.ui)?.notifications);
162632
162724
  }
162633
162725
  function notificationSettings(env = process.env, config) {
162634
162726
  const configured = configuredNotifications(config);
@@ -162647,7 +162739,7 @@ async function readStoredNotificationSettings(env = process.env) {
162647
162739
  }
162648
162740
  async function writeNotificationSettings(settings, env = process.env) {
162649
162741
  return await updateCliSettings((config) => {
162650
- const ui = record$3(config.ui) ?? {};
162742
+ const ui = record$4(config.ui) ?? {};
162651
162743
  ui.notifications = { ...settings };
162652
162744
  config.ui = ui;
162653
162745
  }, env);
@@ -162884,11 +162976,11 @@ var TurnNotifier = class {
162884
162976
  };
162885
162977
  //#endregion
162886
162978
  //#region packages/zcode-tui/src/tui-mode.ts
162887
- function record$2(value) {
162979
+ function record$3(value) {
162888
162980
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
162889
162981
  }
162890
162982
  function configuredTuiMode(config) {
162891
- const value = record$2(record$2(config)?.ui)?.tuiMode;
162983
+ const value = record$3(record$3(config)?.ui)?.tuiMode;
162892
162984
  return typeof value === "string" ? value : void 0;
162893
162985
  }
162894
162986
  function tuiMode(value) {
@@ -162904,18 +162996,18 @@ async function readTuiMode(env = process.env) {
162904
162996
  }
162905
162997
  async function writeTuiMode(mode, env = process.env) {
162906
162998
  return await updateCliSettings((config) => {
162907
- const ui = record$2(config.ui) ?? {};
162999
+ const ui = record$3(config.ui) ?? {};
162908
163000
  ui.tuiMode = mode;
162909
163001
  config.ui = ui;
162910
163002
  }, env);
162911
163003
  }
162912
163004
  //#endregion
162913
163005
  //#region packages/zcode-tui/src/copy-on-select.ts
162914
- function record$1(value) {
163006
+ function record$2(value) {
162915
163007
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
162916
163008
  }
162917
163009
  function configuredCopyOnSelect(config) {
162918
- const value = record$1(record$1(config)?.ui)?.copyOnSelect;
163010
+ const value = record$2(record$2(config)?.ui)?.copyOnSelect;
162919
163011
  return typeof value === "boolean" ? value : void 0;
162920
163012
  }
162921
163013
  async function readCopyOnSelect(env = process.env) {
@@ -162923,25 +163015,25 @@ async function readCopyOnSelect(env = process.env) {
162923
163015
  }
162924
163016
  async function writeCopyOnSelect(enabled, env = process.env) {
162925
163017
  return await updateCliSettings((config) => {
162926
- const ui = record$1(config.ui) ?? {};
163018
+ const ui = record$2(config.ui) ?? {};
162927
163019
  ui.copyOnSelect = enabled;
162928
163020
  config.ui = ui;
162929
163021
  }, env);
162930
163022
  }
162931
163023
  //#endregion
162932
163024
  //#region packages/zcode-tui/src/tool-call-style.ts
162933
- function record(value) {
163025
+ function record$1(value) {
162934
163026
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
162935
163027
  }
162936
163028
  function resolveToolCallStyle(config) {
162937
- return record(record(config)?.ui)?.toolCallStyle === "compact" ? "compact" : "regular";
163029
+ return record$1(record$1(config)?.ui)?.toolCallStyle === "compact" ? "compact" : "regular";
162938
163030
  }
162939
163031
  async function readToolCallStyle(env = process.env) {
162940
163032
  return resolveToolCallStyle(await readCliSettings(env));
162941
163033
  }
162942
163034
  async function writeToolCallStyle(style, env = process.env) {
162943
163035
  return await updateCliSettings((config) => {
162944
- const ui = record(config.ui) ?? {};
163036
+ const ui = record$1(config.ui) ?? {};
162945
163037
  ui.toolCallStyle = style;
162946
163038
  config.ui = ui;
162947
163039
  }, env);
@@ -163065,6 +163157,9 @@ function explicitModelRequest(input) {
163065
163157
  if (separator <= 0 || separator === argument.length - 1) return void 0;
163066
163158
  return argument;
163067
163159
  }
163160
+ function isModelDefaultRequest(input) {
163161
+ return /^\/model\s+default$/iu.test(input.trim());
163162
+ }
163068
163163
  function isEffortPickerRequest(input) {
163069
163164
  return pickerRequest(input, /* @__PURE__ */ new Set(["effort", "variant"]));
163070
163165
  }
@@ -163606,7 +163701,9 @@ const backgroundStatuses = /* @__PURE__ */ new Set([
163606
163701
  "killed",
163607
163702
  "stopped",
163608
163703
  "spawn_error",
163609
- "lost"
163704
+ "lost",
163705
+ "owner_unknown",
163706
+ "running_elsewhere"
163610
163707
  ]);
163611
163708
  const todoStatuses$1 = /* @__PURE__ */ new Set([
163612
163709
  "pending",
@@ -163717,6 +163814,7 @@ function backgroundJobFrom(value) {
163717
163814
  const rawError = isRecord(value.error) ? value.error : void 0;
163718
163815
  return {
163719
163816
  taskId,
163817
+ executionId: stringField(value, "executionId"),
163720
163818
  taskKind,
163721
163819
  toolCallId: stringField(value, "toolCallId", "toolCallID"),
163722
163820
  toolName,
@@ -164695,6 +164793,439 @@ var StatusLine = class {
164695
164793
  }
164696
164794
  };
164697
164795
  //#endregion
164796
+ //#region packages/zcode-tui/src/quota-statusline.ts
164797
+ /**
164798
+ * `ui.quotaStatusline` (default **off**): when enabled, the compact statusline
164799
+ * gains a `quota <percent>%` segment showing the lowest remaining balance of
164800
+ * the signed-in account's plan slots. Configured in `setting.json` only — the
164801
+ * statusline stays minimal unless the user opts in.
164802
+ */
164803
+ function record(value) {
164804
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
164805
+ }
164806
+ function resolveQuotaStatusline(config) {
164807
+ return record(record(config)?.ui)?.quotaStatusline === true;
164808
+ }
164809
+ async function readQuotaStatusline(env = process.env) {
164810
+ try {
164811
+ return resolveQuotaStatusline(await readCliSettings(env));
164812
+ } catch {
164813
+ return false;
164814
+ }
164815
+ }
164816
+ //#endregion
164817
+ //#region packages/zcode-tui/src/help-summary-view.ts
164818
+ /**
164819
+ * Bare `/help` content: the merged command list (runtime-provided commands via
164820
+ * the host + TUI-local commands like /status and /quota). Width-safe: every
164821
+ * line truncates to the dialog width, never wraps.
164822
+ */
164823
+ var HelpSummaryView = class {
164824
+ theme;
164825
+ lines;
164826
+ footnote;
164827
+ constructor(theme, lines, footnote = void 0) {
164828
+ this.theme = theme;
164829
+ this.lines = lines;
164830
+ this.footnote = footnote;
164831
+ }
164832
+ render(width) {
164833
+ const safeWidth = Math.max(1, width);
164834
+ const rendered = this.lines.map((line) => truncateToWidth(line, safeWidth, "…"));
164835
+ if (this.footnote) rendered.push("", this.theme.muted(truncateToWidth(this.footnote, safeWidth, "…")));
164836
+ return rendered;
164837
+ }
164838
+ invalidate() {}
164839
+ };
164840
+ //#endregion
164841
+ //#region packages/zcode-tui/src/quota-view.ts
164842
+ /**
164843
+ * `/quota` card: plan header + one bar per model slot the plan carries.
164844
+ *
164845
+ * Width-safe by contract: every component implements `render(width)` and
164846
+ * re-renders at the new size on resize/zoom; bars clamp to the viewport
164847
+ * (8–40 chars, the same formula `context-status-view.ts` uses) and every
164848
+ * line is truncated so nothing wraps or breaks. Renders whatever model
164849
+ * slots `billing/balance` returns — plans with one, two or many models
164850
+ * all work without hardcoded rows.
164851
+ */
164852
+ const MAX_RENDERED_SLOTS = 8;
164853
+ const BAR_MIN = 8;
164854
+ const BAR_MAX = 40;
164855
+ function formatUnits(value) {
164856
+ return value === void 0 ? "—" : value.toLocaleString("en-US");
164857
+ }
164858
+ function formatExpiry(seconds) {
164859
+ if (seconds === void 0) return void 0;
164860
+ const date = /* @__PURE__ */ new Date(seconds * 1e3);
164861
+ if (Number.isNaN(date.getTime())) return void 0;
164862
+ return date.toLocaleString("en-US", {
164863
+ month: "short",
164864
+ day: "numeric",
164865
+ hour: "2-digit",
164866
+ minute: "2-digit"
164867
+ });
164868
+ }
164869
+ var QuotaView = class {
164870
+ theme;
164871
+ overview;
164872
+ updatedAt;
164873
+ constructor(theme, overview, updatedAt = void 0) {
164874
+ this.theme = theme;
164875
+ this.overview = overview;
164876
+ this.updatedAt = updatedAt;
164877
+ }
164878
+ render(width) {
164879
+ const safeWidth = Math.max(1, width);
164880
+ const lines = [];
164881
+ const plan = this.overview.plans[0];
164882
+ if (plan?.name) {
164883
+ const status = plan.status && plan.status !== "active" ? ` (${plan.status})` : "";
164884
+ lines.push(this.theme.accent(`${plan.name}${status}`));
164885
+ }
164886
+ const expiry = formatExpiry(plan?.endsAt);
164887
+ if (expiry) lines.push(this.theme.muted(`Expires ${expiry}`));
164888
+ if (plan?.name || expiry) lines.push("");
164889
+ const slots = this.overview.balances.slice(0, MAX_RENDERED_SLOTS);
164890
+ if (slots.length === 0) {
164891
+ lines.push(this.theme.muted("No plan balances on this account."));
164892
+ if (!plan) lines.push(this.theme.muted("Sign in with /login to use Start Plan and Coding Plan providers."));
164893
+ }
164894
+ for (const slot of slots) {
164895
+ lines.push(this.slotTitle(slot, safeWidth));
164896
+ lines.push(this.slotBar(slot, safeWidth));
164897
+ lines.push(this.theme.muted(this.slotDetail(slot)));
164898
+ lines.push("");
164899
+ }
164900
+ const hidden = this.overview.balances.length - slots.length;
164901
+ if (hidden > 0) lines.push(this.theme.muted(`+${hidden} more…`));
164902
+ const footnote = this.updatedAt ? `updated ${this.updatedAt} · billing/balance · /quota refreshes` : "billing/balance · /quota refreshes";
164903
+ lines.push(this.theme.muted(footnote));
164904
+ return lines.map((line) => truncateToWidth(line, safeWidth, "…"));
164905
+ }
164906
+ invalidate() {}
164907
+ slotTint(slot) {
164908
+ const percentLeft = slot.percentLeft;
164909
+ if (percentLeft === void 0) return this.theme.muted;
164910
+ if (percentLeft <= 0) return this.theme.error;
164911
+ if (percentLeft <= 20) return this.theme.warning;
164912
+ return this.theme.accent;
164913
+ }
164914
+ slotTitle(slot, safeWidth) {
164915
+ const name = slot.name ?? "model";
164916
+ const tint = this.slotTint(slot);
164917
+ const percent = slot.percentLeft === void 0 ? void 0 : `${Math.round(slot.percentLeft)}%`;
164918
+ if (percent === void 0) return truncateToWidth(name, safeWidth, "…");
164919
+ const gap = Math.max(2, Math.min(6, safeWidth - visibleWidth(name) - visibleWidth(percent) - 1));
164920
+ return truncateToWidth(name + " ".repeat(gap) + tint(percent), safeWidth, "…");
164921
+ }
164922
+ slotBar(slot, safeWidth) {
164923
+ const safe = Math.max(1, safeWidth);
164924
+ const barWidth = Math.max(BAR_MIN, Math.min(BAR_MAX, safe - 2));
164925
+ const total = slot.totalUnits;
164926
+ const remaining = slot.remainingUnits ?? 0;
164927
+ const filled = total && total > 0 ? Math.max(0, Math.min(barWidth, Math.round(remaining / total * barWidth))) : 0;
164928
+ return truncateToWidth(this.slotTint(slot)("█".repeat(filled)) + this.theme.muted("░".repeat(Math.max(0, barWidth - filled))), safe, "…");
164929
+ }
164930
+ slotDetail(slot) {
164931
+ const reset = formatExpiry(slot.expiresAt);
164932
+ const exhausted = slot.remainingUnits !== void 0 && slot.remainingUnits <= 0;
164933
+ const totals = `${formatUnits(slot.remainingUnits)} / ${formatUnits(slot.totalUnits)}`;
164934
+ if (exhausted) return `${totals} · exhausted`;
164935
+ return reset ? `${totals} · resets ${reset}` : totals;
164936
+ }
164937
+ };
164938
+ //#endregion
164939
+ //#region src/quota.ts
164940
+ /**
164941
+ * Plan-quota service for the standalone CLI/TUI.
164942
+ *
164943
+ * Reads the shared OAuth session (`readStartPlanSession`) from the runtime-owned
164944
+ * credentials file, queries the Start Plan billing/balance endpoint with the
164945
+ * same device identity the runtime already uses, and parses the per-model
164946
+ * balance slots shown by the desktop's Start Plan panel.
164947
+ *
164948
+ * Read-only: this module never writes credentials and never creates identities.
164949
+ */
164950
+ const BILLING_BALANCE_URL = "https://zcode.z.ai/api/v1/zcode-plan/billing/balance";
164951
+ const DEFAULT_APP_VERSION = "3.18.2";
164952
+ const IV_BYTES = 12;
164953
+ const TAG_BYTES = 16;
164954
+ const SECRET_MIN_BYTES = 32;
164955
+ const SECRET_MAX_BYTES = 4096;
164956
+ const OS_KEYRING_SERVICE = "ZCode Credential Encryption";
164957
+ const BILLING_REQUEST_TIMEOUT_MS = 1e4;
164958
+ function digest(value) {
164959
+ return createHash("sha256").update(value).digest();
164960
+ }
164961
+ function keyFingerprint(key) {
164962
+ return digest(key).toString("hex").slice(0, 24);
164963
+ }
164964
+ function isPrintableBase64Url(part) {
164965
+ return /^[A-Za-z0-9_-]*$/.test(part);
164966
+ }
164967
+ function tryOpenV2Key(body, key) {
164968
+ const colon = body.indexOf(":");
164969
+ const fingerprint = colon >= 0 ? body.slice(0, colon) : void 0;
164970
+ const parts = (colon >= 0 ? body.slice(colon + 1) : body).split(".");
164971
+ if (parts.length !== 3 || parts.some((part) => !isPrintableBase64Url(part))) return void 0;
164972
+ const [iv, tag, bytes] = parts.map((part) => Buffer.from(part, "base64url"));
164973
+ if (iv.length !== IV_BYTES || tag.length !== TAG_BYTES) return void 0;
164974
+ if (fingerprint && fingerprint !== keyFingerprint(key)) return void 0;
164975
+ try {
164976
+ const decipher = createDecipheriv("aes-256-gcm", key, iv);
164977
+ decipher.setAuthTag(tag);
164978
+ return Buffer.concat([decipher.update(bytes), decipher.final()]).toString("utf8");
164979
+ } catch {
164980
+ return;
164981
+ }
164982
+ }
164983
+ /** `enc:v2:env:<keyFingerprint>:<iv>.<tag>.<ct>` — base64url, AES-256-GCM, no AAD. */
164984
+ function tryOpenV2Env(body, secretCandidates) {
164985
+ for (const candidate of secretCandidates) {
164986
+ const opened = tryOpenV2Key(body, digest(candidate));
164987
+ if (opened !== void 0) return opened;
164988
+ }
164989
+ }
164990
+ /** `enc:v1:<iv>.<tag>.<ct>` — legacy records; key candidates mirror the runtime. */
164991
+ function tryOpenLegacy(record, env) {
164992
+ const parts = record.replace(/^enc:v1:/, "").split(".");
164993
+ if (parts.length !== 3 || parts.some((part) => !isPrintableBase64Url(part))) return void 0;
164994
+ const [iv, tag, bytes] = parts.map((part) => Buffer.from(part, "base64url"));
164995
+ if (!iv || !tag || !bytes || iv.length !== IV_BYTES || tag.length !== TAG_BYTES) return void 0;
164996
+ const fallback = legacyFallbackSecret(env);
164997
+ const secret = resolveCredentialSecret(env);
164998
+ const candidates = secret ? [.../* @__PURE__ */ new Set([
164999
+ secret,
165000
+ secret.trim(),
165001
+ fallback
165002
+ ])] : [fallback];
165003
+ for (const key of candidates.map(digest)) try {
165004
+ const decipher = createDecipheriv("aes-256-gcm", key, iv);
165005
+ decipher.setAuthTag(tag);
165006
+ return Buffer.concat([decipher.update(bytes), decipher.final()]).toString("utf8");
165007
+ } catch {}
165008
+ }
165009
+ function legacyFallbackSecret(env) {
165010
+ let username = "unknown";
165011
+ try {
165012
+ username = userInfo().username;
165013
+ } catch {}
165014
+ return `zcode-credential-fallback:${process.platform}:${homedir()}:${username}`;
165015
+ }
165016
+ /**
165017
+ * Mirrors the runtime's managed-secret resolution: the env variable wins, then
165018
+ * the secret file whose content is used verbatim (no trim — the runtime derives
165019
+ * its key from the raw file content, trailing newline included).
165020
+ */
165021
+ function resolveCredentialSecret(env) {
165022
+ if (env.ZCODE_CREDENTIAL_SECRET && env.ZCODE_CREDENTIAL_SECRET_FILE) return void 0;
165023
+ if (env.ZCODE_CREDENTIAL_SECRET) return env.ZCODE_CREDENTIAL_SECRET;
165024
+ const explicit = env.ZCODE_CREDENTIAL_SECRET_FILE;
165025
+ if (!explicit) return void 0;
165026
+ try {
165027
+ const value = readFileSync(explicit, "utf8");
165028
+ const bytes = Buffer.byteLength(value, "utf8");
165029
+ if (bytes < SECRET_MIN_BYTES || bytes > SECRET_MAX_BYTES) return void 0;
165030
+ return value;
165031
+ } catch {
165032
+ return;
165033
+ }
165034
+ }
165035
+ function decryptRecord(value, env) {
165036
+ if (value.startsWith("enc:v2:env:")) {
165037
+ const secret = resolveCredentialSecret(env);
165038
+ const candidates = secret ? [.../* @__PURE__ */ new Set([secret, secret.trim()])] : [];
165039
+ return tryOpenV2Env(value.slice(11), candidates) ?? null;
165040
+ }
165041
+ if (value.startsWith("enc:v1:")) return tryOpenLegacy(value, env) ?? null;
165042
+ return value;
165043
+ }
165044
+ function secureStorageError(message = "System credential storage is unavailable.") {
165045
+ return Object.assign(new Error(message), { code: "CREDENTIAL_SECURE_STORAGE_UNAVAILABLE" });
165046
+ }
165047
+ async function readOsCredentialKey(filePath) {
165048
+ const { AsyncEntry } = await import("@napi-rs/keyring");
165049
+ const account = digest(resolve(filePath)).toString("hex");
165050
+ const entry = new AsyncEntry(OS_KEYRING_SERVICE, account, { linux: { store: "secret-service" } });
165051
+ let encoded;
165052
+ try {
165053
+ encoded = await createKeychainRecovery()(async () => await entry.getPassword());
165054
+ } catch (cause) {
165055
+ throw Object.assign(secureStorageError(), { cause });
165056
+ }
165057
+ if (!encoded || !/^[A-Za-z0-9_-]{43}$/u.test(encoded)) throw secureStorageError("The system credential key for this account is unavailable.");
165058
+ const key = Buffer.from(encoded, "base64url");
165059
+ if (key.length !== 32) throw secureStorageError("The system credential key for this account is invalid.");
165060
+ return key;
165061
+ }
165062
+ /**
165063
+ * Read-only CredentialReader over the runtime-owned credentials file.
165064
+ * Follows the same path resolution as the runtime (config-paths helpers),
165065
+ * so an isolated `ZCODE_DATA_BASE_DIR` yields that account's records only.
165066
+ */
165067
+ function createFileCredentialReader(env = process.env, options = {}) {
165068
+ let osKeyPromise;
165069
+ return { async loadMany(keys) {
165070
+ let parsed;
165071
+ try {
165072
+ parsed = JSON.parse(readFileSync(credentialsPath(env), "utf8"));
165073
+ } catch {
165074
+ return Object.fromEntries(keys.map((key) => [key, null]));
165075
+ }
165076
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return Object.fromEntries(keys.map((key) => [key, null]));
165077
+ const records = parsed;
165078
+ const needsOsKey = keys.map((key) => records[key]).some((value) => typeof value === "string" && value.startsWith("enc:v2:os:"));
165079
+ if (needsOsKey && !osKeyPromise) osKeyPromise = (options.readOsKey ?? readOsCredentialKey)(credentialsPath(env));
165080
+ const osKey = needsOsKey ? await osKeyPromise : void 0;
165081
+ return Object.fromEntries(keys.map((key) => {
165082
+ const value = records[key];
165083
+ let plain = null;
165084
+ if (typeof value === "string") if (value.startsWith("enc:v2:os:")) plain = tryOpenV2Key(value.slice(10), osKey) ?? null;
165085
+ else plain = decryptRecord(value, env);
165086
+ return [key, plain && plain.length > 0 ? plain : null];
165087
+ }));
165088
+ } };
165089
+ }
165090
+ /** DeviceMid from the isolated telemetry state — the runtime creates it on first model request. */
165091
+ function readDeviceMid(env = process.env) {
165092
+ try {
165093
+ const stateFile = join(sharedDataBaseDir(env), ".zcode", "v2", "telemetry-state.json");
165094
+ const mid = JSON.parse(readFileSync(stateFile, "utf8")).deviceMid;
165095
+ return typeof mid === "string" && mid.trim() ? mid.trim() : void 0;
165096
+ } catch {
165097
+ return;
165098
+ }
165099
+ }
165100
+ /**
165101
+ * Billing-plane headers, mirroring the desktop's Start Plan request shape
165102
+ * (User-Agent/Referer/Title/Version/Platform/Channel/Language/Timezone/OS/
165103
+ * Device-Mid/Authorization + a fresh x-request-id per call).
165104
+ */
165105
+ function billingHeaders(session, options = {}) {
165106
+ const version = options.appVersion ?? DEFAULT_APP_VERSION;
165107
+ const headers = {
165108
+ "User-Agent": `ZCode/${version}`,
165109
+ "HTTP-Referer": "https://zcode.z.ai",
165110
+ "X-Title": "Z Code@electron",
165111
+ "X-ZCode-App-Version": version,
165112
+ "X-Platform": process.platform,
165113
+ "X-Release-Channel": "stable",
165114
+ "X-Client-Language": Intl.DateTimeFormat().resolvedOptions().locale || "unknown",
165115
+ "X-Client-Timezone": Intl.DateTimeFormat().resolvedOptions().timeZone || "unknown",
165116
+ "X-Os-Category": process.platform,
165117
+ "X-Os-Version": release(),
165118
+ "Authorization": `Bearer ${session.token}`,
165119
+ "x-request-id": randomUUID()
165120
+ };
165121
+ if (options.deviceMid) headers["X-Device-Mid"] = options.deviceMid;
165122
+ return headers;
165123
+ }
165124
+ function asNumber(value) {
165125
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
165126
+ }
165127
+ function asText(value) {
165128
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
165129
+ }
165130
+ function asRecord(value) {
165131
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
165132
+ }
165133
+ /** Pure parser for the billing/balance payload (accepts the `{code, data}` envelope or bare data). */
165134
+ function parseBillingBalance(payload) {
165135
+ const envelope = asRecord(payload);
165136
+ const root = envelope && "data" in envelope ? asRecord(envelope.data) : envelope;
165137
+ if (!root) return {
165138
+ serverTime: void 0,
165139
+ plans: [],
165140
+ balances: []
165141
+ };
165142
+ const plans = Array.isArray(root.plans) ? root.plans.map((plan) => {
165143
+ const record = asRecord(plan) ?? {};
165144
+ return {
165145
+ planId: asText(record.plan_id),
165146
+ name: asText(record.name),
165147
+ status: asText(record.status),
165148
+ startsAt: asNumber(record.starts_at),
165149
+ endsAt: asNumber(record.ends_at)
165150
+ };
165151
+ }) : [];
165152
+ const balances = Array.isArray(root.balances) ? root.balances.map((balance) => {
165153
+ const record = asRecord(balance) ?? {};
165154
+ const totalUnits = asNumber(record.total_units);
165155
+ const remainingUnits = asNumber(record.remaining_units);
165156
+ const percentLeft = totalUnits !== void 0 && totalUnits > 0 && remainingUnits !== void 0 ? Math.max(0, Math.min(100, remainingUnits / totalUnits * 100)) : void 0;
165157
+ return {
165158
+ name: asText(record.show_name),
165159
+ meter: asText(record.meter),
165160
+ totalUnits,
165161
+ usedUnits: asNumber(record.used_units),
165162
+ remainingUnits,
165163
+ availableUnits: asNumber(record.available_units),
165164
+ percentLeft,
165165
+ expiresAt: asNumber(record.expires_at)
165166
+ };
165167
+ }) : [];
165168
+ return {
165169
+ serverTime: asNumber(root.server_time),
165170
+ plans,
165171
+ balances
165172
+ };
165173
+ }
165174
+ var QuotaRequestError = class extends Error {};
165175
+ async function fetchQuotaOverview(session, options = {}) {
165176
+ const doFetch = options.fetchImpl ?? fetch;
165177
+ const timeout = AbortSignal.timeout(options.timeoutMs ?? BILLING_REQUEST_TIMEOUT_MS);
165178
+ const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
165179
+ let response;
165180
+ try {
165181
+ response = await doFetch(BILLING_BALANCE_URL, {
165182
+ headers: billingHeaders(session, options),
165183
+ signal
165184
+ });
165185
+ } catch (error) {
165186
+ throw new QuotaRequestError(error instanceof Error ? error.message : String(error));
165187
+ }
165188
+ let payload;
165189
+ try {
165190
+ payload = await response.json();
165191
+ } catch {
165192
+ throw new QuotaRequestError(`billing/balance returned non-JSON response (HTTP ${response.status})`);
165193
+ }
165194
+ const envelope = asRecord(payload);
165195
+ if (response.status !== 200 || envelope && envelope.code !== void 0 && envelope.code !== 0) throw new QuotaRequestError(`billing/balance rejected the request: ${envelope && typeof envelope.msg === "string" ? envelope.msg : `HTTP ${response.status}`}`);
165196
+ return parseBillingBalance(payload);
165197
+ }
165198
+ /**
165199
+ * One-shot read for the TUI: shared OAuth session → billing/balance → parsed overview.
165200
+ * Fails soft with a reason the UI can present.
165201
+ */
165202
+ async function loadCurrentQuotaOverview(options = {}) {
165203
+ const env = options.env ?? process.env;
165204
+ try {
165205
+ const session = await readStartPlanSession(createFileCredentialReader(env), options.signal);
165206
+ if (!session) return {
165207
+ ok: false,
165208
+ reason: "no-oauth-session"
165209
+ };
165210
+ return {
165211
+ ok: true,
165212
+ overview: await fetchQuotaOverview(session, {
165213
+ deviceMid: readDeviceMid(env),
165214
+ appVersion: options.appVersion ?? env.ZCODE_APP_VERSION,
165215
+ signal: options.signal,
165216
+ fetchImpl: options.fetchImpl
165217
+ })
165218
+ };
165219
+ } catch (error) {
165220
+ const detail = error instanceof Error ? error.message : String(error);
165221
+ return {
165222
+ ok: false,
165223
+ reason: (error && typeof error === "object" && "code" in error ? error.code : void 0) === "CREDENTIAL_SECURE_STORAGE_UNAVAILABLE" || detail.includes("Secure credential storage") || detail.includes("System credential storage") ? "secure-storage-unavailable" : "request-failed",
165224
+ detail
165225
+ };
165226
+ }
165227
+ }
165228
+ //#endregion
164698
165229
  //#region packages/zcode-tui/src/system-event-view.ts
164699
165230
  var SystemEventView = class {
164700
165231
  theme;
@@ -166506,7 +167037,7 @@ var SessionWelcome = class {
166506
167037
  const innerWidth = Math.max(1, frameWidth - 4);
166507
167038
  const content = [frameRule("top", this.includeIdentity ? this.identity(Math.max(1, frameWidth - 8)) : this.theme.bold("Workspace"), frameWidth, this.theme), frameContent(this.theme.muted(this.location(innerWidth)), frameWidth, this.theme)];
166508
167039
  if (this.loginRequired) content.push(frameContent(this.theme.warning("Model access is not configured · Run /login."), frameWidth, this.theme));
166509
- content.push(frameContent(this.theme.bold("Ask a task about this workspace"), frameWidth, this.theme), frameRule("bottom", this.theme.muted("/help commands · /status details"), frameWidth, this.theme));
167040
+ content.push(frameContent(this.theme.bold("Ask a task about this workspace"), frameWidth, this.theme), frameRule("bottom", this.theme.muted("/help commands · /status details · /quota balances"), frameWidth, this.theme));
166510
167041
  const lines = content.map((line) => truncateToWidth(line, safeWidth, "…"));
166511
167042
  return this.transitioning ? lines.map((line) => this.theme.muted(sanitizeTerminalText(line, { preserveSgr: false }))) : lines;
166512
167043
  }
@@ -167260,6 +167791,7 @@ var ZCodeTui = class {
167260
167791
  terminalFocus = "unknown";
167261
167792
  copyOnSelect = true;
167262
167793
  toolCallStyle = "regular";
167794
+ quotaStatusPercent = void 0;
167263
167795
  thoughtLevel;
167264
167796
  showReasoning;
167265
167797
  modelOptions;
@@ -168018,6 +168550,10 @@ var ZCodeTui = class {
168018
168550
  name: "status",
168019
168551
  description: "Inspect detailed runtime and session status"
168020
168552
  },
168553
+ {
168554
+ name: "quota",
168555
+ description: "Inspect plan quota and balances for the signed-in account"
168556
+ },
168021
168557
  {
168022
168558
  name: "rename",
168023
168559
  description: "Rename the current session",
@@ -168352,6 +168888,14 @@ var ZCodeTui = class {
168352
168888
  await this.showStatusDetails();
168353
168889
  return;
168354
168890
  }
168891
+ if (input === "/help") {
168892
+ await this.showHelpSummary();
168893
+ return;
168894
+ }
168895
+ if (input === "/quota") {
168896
+ await this.showQuotaDetails();
168897
+ return;
168898
+ }
168355
168899
  const renameRequest = sessionRenameRequest(input);
168356
168900
  if (renameRequest !== void 0) {
168357
168901
  await this.handleSessionRename(renameRequest);
@@ -168380,6 +168924,11 @@ var ZCodeTui = class {
168380
168924
  else await this.switchPlan(argument === "on" ? true : argument === "off" ? false : void 0);
168381
168925
  return;
168382
168926
  }
168927
+ if (isModelDefaultRequest(input)) {
168928
+ this.addUserMessage(submission.displayInput);
168929
+ await this.showModelProviderSettings();
168930
+ return;
168931
+ }
168383
168932
  const explicitModel = explicitModelRequest(input);
168384
168933
  if (explicitModel) {
168385
168934
  this.addUserMessage(submission.displayInput);
@@ -168664,7 +169213,7 @@ var ZCodeTui = class {
168664
169213
  const stopped = [];
168665
169214
  const failed = [];
168666
169215
  for (const job of active) try {
168667
- const failure = backgroundCancellationFailure(await cancelBackgroundTask(job.taskId));
169216
+ const failure = backgroundCancellationFailure(await cancelBackgroundTask(job.taskId, job.executionId));
168668
169217
  if (failure) {
168669
169218
  failed.push({
168670
169219
  detail: failure,
@@ -170502,7 +171051,7 @@ var ZCodeTui = class {
170502
171051
  const result = await this.options.setTransientModel(modelId);
170503
171052
  await this.handleResult(result, false);
170504
171053
  const status = !recovering && this.model === previousModel ? "already active" : "now";
170505
- this.addNotice(`Session model ${status}: ${this.model} · saved defaults unchanged.`, "muted");
171054
+ this.addNotice(`Session model ${status}: ${this.model} · saved defaults unchanged · /model default saves it for new sessions.`, "muted");
170506
171055
  } catch (error) {
170507
171056
  this.addNotice(`Could not switch model: ${error instanceof Error ? error.message : String(error)}`, "error");
170508
171057
  } finally {
@@ -171436,6 +171985,49 @@ var ZCodeTui = class {
171436
171985
  });
171437
171986
  }
171438
171987
  /**
171988
+ * Bare `/help` renders the merged command list (runtime-provided + TUI-local).
171989
+ * `/help <command>` still forwards to the runtime, which owns per-command details.
171990
+ */
171991
+ async showHelpSummary() {
171992
+ const lines = this.autocompleteCommands().slice().sort((a, b) => a.name.localeCompare(b.name)).map((command) => {
171993
+ const rawHint = command.argumentHint?.trim() ?? "";
171994
+ const hint = rawHint ? ` ${rawHint.startsWith("[") ? rawHint : `[${rawHint}]`}` : "";
171995
+ return `- /${command.name}${hint}: ${command.description}`;
171996
+ });
171997
+ await this.showChoice({
171998
+ title: "Help",
171999
+ prompt: "All slash commands — runtime-provided and TUI-local.",
172000
+ content: new HelpSummaryView(this.theme, lines, "Use /help <command> for runtime command details. Custom plugin commands live under /plugins."),
172001
+ items: [{
172002
+ value: "close",
172003
+ label: "Close"
172004
+ }]
172005
+ });
172006
+ }
172007
+ async showQuotaDetails() {
172008
+ const result = await loadCurrentQuotaOverview();
172009
+ if (!result.ok) {
172010
+ if (result.reason === "no-oauth-session") this.addNotice("No shared OAuth session for quota — sign in with /login first.", "warning");
172011
+ else if (result.reason === "secure-storage-unavailable") this.addNotice("Could not read the existing sign-in from secure credential storage. Check that the system keychain is available; signing in again is not required.", "warning");
172012
+ else this.addNotice(`Quota request failed: ${result.detail ?? "unknown error"}`, "warning");
172013
+ return;
172014
+ }
172015
+ const overview = result.overview;
172016
+ if (overview.plans.length === 0 && overview.balances.length === 0) {
172017
+ this.addNotice("No plan balances on this account for the signed-in session.", "warning");
172018
+ return;
172019
+ }
172020
+ await this.showChoice({
172021
+ title: "Quota",
172022
+ prompt: "Live plan balances for the signed-in account. The compact statusline stays minimal.",
172023
+ content: new QuotaView(this.theme, overview, (/* @__PURE__ */ new Date()).toLocaleTimeString("en-US")),
172024
+ items: [{
172025
+ value: "close",
172026
+ label: "Close"
172027
+ }]
172028
+ });
172029
+ }
172030
+ /**
171439
172031
  * `/rename <title>`: persists a user-owned session title through the
171440
172032
  * runtime's setCustomSessionTitle capability, so the runtime's own title
171441
172033
  * generator will not replace it later. Older runtimes without the bridge
@@ -171593,7 +172185,7 @@ var ZCodeTui = class {
171593
172185
  return "back";
171594
172186
  }
171595
172187
  const active = isActiveBackgroundJob(job);
171596
- const canMessage = job.taskKind === "local_agent" && Boolean(this.options.sendBackgroundTaskMessage);
172188
+ const canMessage = job.taskKind === "local_agent" && job.status !== "running_elsewhere" && job.status !== "owner_unknown" && Boolean(this.options.sendBackgroundTaskMessage);
171597
172189
  const canStop = active && job.cancellable !== false && Boolean(this.options.cancelBackgroundTask);
171598
172190
  const items = [
171599
172191
  ...canMessage ? active ? [{
@@ -171656,7 +172248,7 @@ var ZCodeTui = class {
171656
172248
  if (action.value === "close") return "close";
171657
172249
  if (action.value === "refresh") continue;
171658
172250
  if (action.value === "stop") {
171659
- await this.stopBackgroundTask(job.taskId);
172251
+ await this.stopBackgroundTask(job.taskId, job);
171660
172252
  continue;
171661
172253
  }
171662
172254
  if (action.value === "resume" && !active) {
@@ -171786,6 +172378,10 @@ var ZCodeTui = class {
171786
172378
  this.addNotice(`${backgroundTaskKindLabel(job)} tasks cannot receive messages.`, "warning");
171787
172379
  return;
171788
172380
  }
172381
+ if (job.status === "running_elsewhere" || job.status === "owner_unknown") {
172382
+ this.addNotice(`Cannot message this agent: ${job.status.replaceAll("_", " ")}.`, "warning");
172383
+ return;
172384
+ }
171789
172385
  if (!this.options.sendBackgroundTaskMessage) {
171790
172386
  this.addNotice("Background agent messaging is unavailable in this runtime.", "warning");
171791
172387
  return;
@@ -171797,7 +172393,8 @@ var ZCodeTui = class {
171797
172393
  taskId: job.taskId,
171798
172394
  message,
171799
172395
  summary: message.replace(/\s+/gu, " ").trim().slice(0, 200),
171800
- restart
172396
+ restart,
172397
+ executionId: job.executionId
171801
172398
  });
171802
172399
  const record = isRecord(result) ? result : void 0;
171803
172400
  const status = asString(record?.status);
@@ -171832,7 +172429,7 @@ var ZCodeTui = class {
171832
172429
  this.backgroundTaskEvents.recordSystemMessage(job.taskId, detail, true);
171833
172430
  this.addNotice(detail, "warning");
171834
172431
  }
171835
- async stopBackgroundTask(taskId) {
172432
+ async stopBackgroundTask(taskId, selected) {
171836
172433
  if (!taskId) {
171837
172434
  this.addNotice("Usage: /tasks stop <task-id>", "muted");
171838
172435
  return;
@@ -171841,7 +172438,7 @@ var ZCodeTui = class {
171841
172438
  this.addNotice("Background task cancellation is unavailable in this runtime.", "warning");
171842
172439
  return;
171843
172440
  }
171844
- const job = this.runtimeProjection?.backgroundJobs.find((candidate) => candidate.taskId === taskId);
172441
+ const job = selected ?? this.runtimeProjection?.backgroundJobs.find((candidate) => candidate.taskId === taskId);
171845
172442
  if (job && !isActiveBackgroundJob(job)) {
171846
172443
  this.addNotice(`Background task ${taskId} is already ${job.status}.`, "muted");
171847
172444
  return;
@@ -171861,7 +172458,7 @@ var ZCodeTui = class {
171861
172458
  this.updateRuntimeActivity();
171862
172459
  }
171863
172460
  try {
171864
- await this.options.cancelBackgroundTask(taskId);
172461
+ await this.options.cancelBackgroundTask(taskId, job?.executionId);
171865
172462
  await this.refreshRuntimeState();
171866
172463
  } catch (error) {
171867
172464
  this.addNotice(error instanceof Error ? error.message : String(error), "error");
@@ -171972,6 +172569,11 @@ var ZCodeTui = class {
171972
172569
  });
171973
172570
  return this.sessionModelRecovery;
171974
172571
  }
172572
+ /** Background quota refresh (ui.quotaStatusline) updates the statusline through this setter. */
172573
+ setQuotaStatusPercent(percent) {
172574
+ this.quotaStatusPercent = percent;
172575
+ this.updateMetadata();
172576
+ }
171975
172577
  updateMetadata() {
171976
172578
  this.editor.planEnabled = this.planEnabled;
171977
172579
  const fields = [{
@@ -172017,6 +172619,15 @@ var ZCodeTui = class {
172017
172619
  priority: 85
172018
172620
  });
172019
172621
  }
172622
+ if (this.quotaStatusPercent !== void 0) {
172623
+ const percent = Math.round(this.quotaStatusPercent);
172624
+ const style = percent <= 0 ? this.theme.error : percent <= 20 ? this.theme.warning : this.theme.muted;
172625
+ fields.push({
172626
+ text: style(`quota ${percent}%`),
172627
+ compactText: style(`quota ${percent}%`),
172628
+ priority: 70
172629
+ });
172630
+ }
172020
172631
  if (this.sessionMetrics.totalTokens !== void 0) {
172021
172632
  const tokens = formatTokens(this.sessionMetrics.totalTokens);
172022
172633
  fields.push({
@@ -172389,10 +173000,52 @@ var ZCodeTui = class {
172389
173000
  }
172390
173001
  }
172391
173002
  };
173003
+ async function startQuotaStatuslineLoop(tui) {
173004
+ if (!await readQuotaStatusline()) return () => {};
173005
+ let stopped = false;
173006
+ let refreshInFlight = false;
173007
+ let requestController;
173008
+ const refresh = async () => {
173009
+ if (stopped || refreshInFlight) return;
173010
+ refreshInFlight = true;
173011
+ const controller = new AbortController();
173012
+ requestController = controller;
173013
+ try {
173014
+ const result = await loadCurrentQuotaOverview({ signal: controller.signal });
173015
+ if (stopped) return;
173016
+ if (!result.ok) {
173017
+ tui.setQuotaStatusPercent(void 0);
173018
+ return;
173019
+ }
173020
+ const percents = result.overview.balances.map((balance) => balance.percentLeft).filter((percent) => percent !== void 0);
173021
+ tui.setQuotaStatusPercent(percents.length ? Math.min(...percents) : void 0);
173022
+ } catch {} finally {
173023
+ refreshInFlight = false;
173024
+ if (requestController === controller) requestController = void 0;
173025
+ }
173026
+ };
173027
+ refresh();
173028
+ const timer = setInterval(() => {
173029
+ refresh();
173030
+ }, 3e5);
173031
+ timer.unref?.();
173032
+ return () => {
173033
+ stopped = true;
173034
+ clearInterval(timer);
173035
+ requestController?.abort();
173036
+ };
173037
+ }
172392
173038
  async function runTui(options) {
172393
173039
  suppressTuiAiSdkWarnings();
172394
173040
  const readyOptions = await loadTuiStartupOptions(options);
172395
- if (readyOptions) await new ZCodeTui(readyOptions).run();
173041
+ if (!readyOptions) return;
173042
+ const tui = new ZCodeTui(readyOptions);
173043
+ const stopQuotaStatuslineLoop = await startQuotaStatuslineLoop(tui);
173044
+ try {
173045
+ await tui.run();
173046
+ } finally {
173047
+ stopQuotaStatuslineLoop();
173048
+ }
172396
173049
  }
172397
173050
  //#endregion
172398
173051
  export { loginFailureDiagnostic, runTui, shouldSuspendForLoginCommand, shouldUseNoBrowserForLogin, suppressTuiAiSdkWarnings, suspendedZaiLoginCommand };