zcode-app-cli 4.0.0-50 → 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) {
@@ -162659,11 +162716,11 @@ function findExecutable(name, env = process.env, platform = process.platform) {
162659
162716
  }
162660
162717
  return null;
162661
162718
  }
162662
- function record$3(value) {
162719
+ function record$4(value) {
162663
162720
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
162664
162721
  }
162665
162722
  function configuredNotifications(config) {
162666
- return record$3(record$3(record$3(config)?.ui)?.notifications);
162723
+ return record$4(record$4(record$4(config)?.ui)?.notifications);
162667
162724
  }
162668
162725
  function notificationSettings(env = process.env, config) {
162669
162726
  const configured = configuredNotifications(config);
@@ -162682,7 +162739,7 @@ async function readStoredNotificationSettings(env = process.env) {
162682
162739
  }
162683
162740
  async function writeNotificationSettings(settings, env = process.env) {
162684
162741
  return await updateCliSettings((config) => {
162685
- const ui = record$3(config.ui) ?? {};
162742
+ const ui = record$4(config.ui) ?? {};
162686
162743
  ui.notifications = { ...settings };
162687
162744
  config.ui = ui;
162688
162745
  }, env);
@@ -162919,11 +162976,11 @@ var TurnNotifier = class {
162919
162976
  };
162920
162977
  //#endregion
162921
162978
  //#region packages/zcode-tui/src/tui-mode.ts
162922
- function record$2(value) {
162979
+ function record$3(value) {
162923
162980
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
162924
162981
  }
162925
162982
  function configuredTuiMode(config) {
162926
- const value = record$2(record$2(config)?.ui)?.tuiMode;
162983
+ const value = record$3(record$3(config)?.ui)?.tuiMode;
162927
162984
  return typeof value === "string" ? value : void 0;
162928
162985
  }
162929
162986
  function tuiMode(value) {
@@ -162939,18 +162996,18 @@ async function readTuiMode(env = process.env) {
162939
162996
  }
162940
162997
  async function writeTuiMode(mode, env = process.env) {
162941
162998
  return await updateCliSettings((config) => {
162942
- const ui = record$2(config.ui) ?? {};
162999
+ const ui = record$3(config.ui) ?? {};
162943
163000
  ui.tuiMode = mode;
162944
163001
  config.ui = ui;
162945
163002
  }, env);
162946
163003
  }
162947
163004
  //#endregion
162948
163005
  //#region packages/zcode-tui/src/copy-on-select.ts
162949
- function record$1(value) {
163006
+ function record$2(value) {
162950
163007
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
162951
163008
  }
162952
163009
  function configuredCopyOnSelect(config) {
162953
- const value = record$1(record$1(config)?.ui)?.copyOnSelect;
163010
+ const value = record$2(record$2(config)?.ui)?.copyOnSelect;
162954
163011
  return typeof value === "boolean" ? value : void 0;
162955
163012
  }
162956
163013
  async function readCopyOnSelect(env = process.env) {
@@ -162958,25 +163015,25 @@ async function readCopyOnSelect(env = process.env) {
162958
163015
  }
162959
163016
  async function writeCopyOnSelect(enabled, env = process.env) {
162960
163017
  return await updateCliSettings((config) => {
162961
- const ui = record$1(config.ui) ?? {};
163018
+ const ui = record$2(config.ui) ?? {};
162962
163019
  ui.copyOnSelect = enabled;
162963
163020
  config.ui = ui;
162964
163021
  }, env);
162965
163022
  }
162966
163023
  //#endregion
162967
163024
  //#region packages/zcode-tui/src/tool-call-style.ts
162968
- function record(value) {
163025
+ function record$1(value) {
162969
163026
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
162970
163027
  }
162971
163028
  function resolveToolCallStyle(config) {
162972
- return record(record(config)?.ui)?.toolCallStyle === "compact" ? "compact" : "regular";
163029
+ return record$1(record$1(config)?.ui)?.toolCallStyle === "compact" ? "compact" : "regular";
162973
163030
  }
162974
163031
  async function readToolCallStyle(env = process.env) {
162975
163032
  return resolveToolCallStyle(await readCliSettings(env));
162976
163033
  }
162977
163034
  async function writeToolCallStyle(style, env = process.env) {
162978
163035
  return await updateCliSettings((config) => {
162979
- const ui = record(config.ui) ?? {};
163036
+ const ui = record$1(config.ui) ?? {};
162980
163037
  ui.toolCallStyle = style;
162981
163038
  config.ui = ui;
162982
163039
  }, env);
@@ -163100,6 +163157,9 @@ function explicitModelRequest(input) {
163100
163157
  if (separator <= 0 || separator === argument.length - 1) return void 0;
163101
163158
  return argument;
163102
163159
  }
163160
+ function isModelDefaultRequest(input) {
163161
+ return /^\/model\s+default$/iu.test(input.trim());
163162
+ }
163103
163163
  function isEffortPickerRequest(input) {
163104
163164
  return pickerRequest(input, /* @__PURE__ */ new Set(["effort", "variant"]));
163105
163165
  }
@@ -163641,7 +163701,9 @@ const backgroundStatuses = /* @__PURE__ */ new Set([
163641
163701
  "killed",
163642
163702
  "stopped",
163643
163703
  "spawn_error",
163644
- "lost"
163704
+ "lost",
163705
+ "owner_unknown",
163706
+ "running_elsewhere"
163645
163707
  ]);
163646
163708
  const todoStatuses$1 = /* @__PURE__ */ new Set([
163647
163709
  "pending",
@@ -163752,6 +163814,7 @@ function backgroundJobFrom(value) {
163752
163814
  const rawError = isRecord(value.error) ? value.error : void 0;
163753
163815
  return {
163754
163816
  taskId,
163817
+ executionId: stringField(value, "executionId"),
163755
163818
  taskKind,
163756
163819
  toolCallId: stringField(value, "toolCallId", "toolCallID"),
163757
163820
  toolName,
@@ -164730,6 +164793,439 @@ var StatusLine = class {
164730
164793
  }
164731
164794
  };
164732
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
164733
165229
  //#region packages/zcode-tui/src/system-event-view.ts
164734
165230
  var SystemEventView = class {
164735
165231
  theme;
@@ -166541,7 +167037,7 @@ var SessionWelcome = class {
166541
167037
  const innerWidth = Math.max(1, frameWidth - 4);
166542
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)];
166543
167039
  if (this.loginRequired) content.push(frameContent(this.theme.warning("Model access is not configured · Run /login."), frameWidth, this.theme));
166544
- 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));
166545
167041
  const lines = content.map((line) => truncateToWidth(line, safeWidth, "…"));
166546
167042
  return this.transitioning ? lines.map((line) => this.theme.muted(sanitizeTerminalText(line, { preserveSgr: false }))) : lines;
166547
167043
  }
@@ -167295,6 +167791,7 @@ var ZCodeTui = class {
167295
167791
  terminalFocus = "unknown";
167296
167792
  copyOnSelect = true;
167297
167793
  toolCallStyle = "regular";
167794
+ quotaStatusPercent = void 0;
167298
167795
  thoughtLevel;
167299
167796
  showReasoning;
167300
167797
  modelOptions;
@@ -168053,6 +168550,10 @@ var ZCodeTui = class {
168053
168550
  name: "status",
168054
168551
  description: "Inspect detailed runtime and session status"
168055
168552
  },
168553
+ {
168554
+ name: "quota",
168555
+ description: "Inspect plan quota and balances for the signed-in account"
168556
+ },
168056
168557
  {
168057
168558
  name: "rename",
168058
168559
  description: "Rename the current session",
@@ -168387,6 +168888,14 @@ var ZCodeTui = class {
168387
168888
  await this.showStatusDetails();
168388
168889
  return;
168389
168890
  }
168891
+ if (input === "/help") {
168892
+ await this.showHelpSummary();
168893
+ return;
168894
+ }
168895
+ if (input === "/quota") {
168896
+ await this.showQuotaDetails();
168897
+ return;
168898
+ }
168390
168899
  const renameRequest = sessionRenameRequest(input);
168391
168900
  if (renameRequest !== void 0) {
168392
168901
  await this.handleSessionRename(renameRequest);
@@ -168415,6 +168924,11 @@ var ZCodeTui = class {
168415
168924
  else await this.switchPlan(argument === "on" ? true : argument === "off" ? false : void 0);
168416
168925
  return;
168417
168926
  }
168927
+ if (isModelDefaultRequest(input)) {
168928
+ this.addUserMessage(submission.displayInput);
168929
+ await this.showModelProviderSettings();
168930
+ return;
168931
+ }
168418
168932
  const explicitModel = explicitModelRequest(input);
168419
168933
  if (explicitModel) {
168420
168934
  this.addUserMessage(submission.displayInput);
@@ -168699,7 +169213,7 @@ var ZCodeTui = class {
168699
169213
  const stopped = [];
168700
169214
  const failed = [];
168701
169215
  for (const job of active) try {
168702
- const failure = backgroundCancellationFailure(await cancelBackgroundTask(job.taskId));
169216
+ const failure = backgroundCancellationFailure(await cancelBackgroundTask(job.taskId, job.executionId));
168703
169217
  if (failure) {
168704
169218
  failed.push({
168705
169219
  detail: failure,
@@ -170537,7 +171051,7 @@ var ZCodeTui = class {
170537
171051
  const result = await this.options.setTransientModel(modelId);
170538
171052
  await this.handleResult(result, false);
170539
171053
  const status = !recovering && this.model === previousModel ? "already active" : "now";
170540
- 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");
170541
171055
  } catch (error) {
170542
171056
  this.addNotice(`Could not switch model: ${error instanceof Error ? error.message : String(error)}`, "error");
170543
171057
  } finally {
@@ -171471,6 +171985,49 @@ var ZCodeTui = class {
171471
171985
  });
171472
171986
  }
171473
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
+ /**
171474
172031
  * `/rename <title>`: persists a user-owned session title through the
171475
172032
  * runtime's setCustomSessionTitle capability, so the runtime's own title
171476
172033
  * generator will not replace it later. Older runtimes without the bridge
@@ -171628,7 +172185,7 @@ var ZCodeTui = class {
171628
172185
  return "back";
171629
172186
  }
171630
172187
  const active = isActiveBackgroundJob(job);
171631
- 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);
171632
172189
  const canStop = active && job.cancellable !== false && Boolean(this.options.cancelBackgroundTask);
171633
172190
  const items = [
171634
172191
  ...canMessage ? active ? [{
@@ -171691,7 +172248,7 @@ var ZCodeTui = class {
171691
172248
  if (action.value === "close") return "close";
171692
172249
  if (action.value === "refresh") continue;
171693
172250
  if (action.value === "stop") {
171694
- await this.stopBackgroundTask(job.taskId);
172251
+ await this.stopBackgroundTask(job.taskId, job);
171695
172252
  continue;
171696
172253
  }
171697
172254
  if (action.value === "resume" && !active) {
@@ -171821,6 +172378,10 @@ var ZCodeTui = class {
171821
172378
  this.addNotice(`${backgroundTaskKindLabel(job)} tasks cannot receive messages.`, "warning");
171822
172379
  return;
171823
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
+ }
171824
172385
  if (!this.options.sendBackgroundTaskMessage) {
171825
172386
  this.addNotice("Background agent messaging is unavailable in this runtime.", "warning");
171826
172387
  return;
@@ -171832,7 +172393,8 @@ var ZCodeTui = class {
171832
172393
  taskId: job.taskId,
171833
172394
  message,
171834
172395
  summary: message.replace(/\s+/gu, " ").trim().slice(0, 200),
171835
- restart
172396
+ restart,
172397
+ executionId: job.executionId
171836
172398
  });
171837
172399
  const record = isRecord(result) ? result : void 0;
171838
172400
  const status = asString(record?.status);
@@ -171867,7 +172429,7 @@ var ZCodeTui = class {
171867
172429
  this.backgroundTaskEvents.recordSystemMessage(job.taskId, detail, true);
171868
172430
  this.addNotice(detail, "warning");
171869
172431
  }
171870
- async stopBackgroundTask(taskId) {
172432
+ async stopBackgroundTask(taskId, selected) {
171871
172433
  if (!taskId) {
171872
172434
  this.addNotice("Usage: /tasks stop <task-id>", "muted");
171873
172435
  return;
@@ -171876,7 +172438,7 @@ var ZCodeTui = class {
171876
172438
  this.addNotice("Background task cancellation is unavailable in this runtime.", "warning");
171877
172439
  return;
171878
172440
  }
171879
- const job = this.runtimeProjection?.backgroundJobs.find((candidate) => candidate.taskId === taskId);
172441
+ const job = selected ?? this.runtimeProjection?.backgroundJobs.find((candidate) => candidate.taskId === taskId);
171880
172442
  if (job && !isActiveBackgroundJob(job)) {
171881
172443
  this.addNotice(`Background task ${taskId} is already ${job.status}.`, "muted");
171882
172444
  return;
@@ -171896,7 +172458,7 @@ var ZCodeTui = class {
171896
172458
  this.updateRuntimeActivity();
171897
172459
  }
171898
172460
  try {
171899
- await this.options.cancelBackgroundTask(taskId);
172461
+ await this.options.cancelBackgroundTask(taskId, job?.executionId);
171900
172462
  await this.refreshRuntimeState();
171901
172463
  } catch (error) {
171902
172464
  this.addNotice(error instanceof Error ? error.message : String(error), "error");
@@ -172007,6 +172569,11 @@ var ZCodeTui = class {
172007
172569
  });
172008
172570
  return this.sessionModelRecovery;
172009
172571
  }
172572
+ /** Background quota refresh (ui.quotaStatusline) updates the statusline through this setter. */
172573
+ setQuotaStatusPercent(percent) {
172574
+ this.quotaStatusPercent = percent;
172575
+ this.updateMetadata();
172576
+ }
172010
172577
  updateMetadata() {
172011
172578
  this.editor.planEnabled = this.planEnabled;
172012
172579
  const fields = [{
@@ -172052,6 +172619,15 @@ var ZCodeTui = class {
172052
172619
  priority: 85
172053
172620
  });
172054
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
+ }
172055
172631
  if (this.sessionMetrics.totalTokens !== void 0) {
172056
172632
  const tokens = formatTokens(this.sessionMetrics.totalTokens);
172057
172633
  fields.push({
@@ -172424,10 +173000,52 @@ var ZCodeTui = class {
172424
173000
  }
172425
173001
  }
172426
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
+ }
172427
173038
  async function runTui(options) {
172428
173039
  suppressTuiAiSdkWarnings();
172429
173040
  const readyOptions = await loadTuiStartupOptions(options);
172430
- 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
+ }
172431
173049
  }
172432
173050
  //#endregion
172433
173051
  export { loginFailureDiagnostic, runTui, shouldSuspendForLoginCommand, shouldUseNoBrowserForLogin, suppressTuiAiSdkWarnings, suspendedZaiLoginCommand };