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.
package/README.md CHANGED
@@ -145,6 +145,8 @@ workflow panels; status-bar-only Shift+Tab mode cycling
145
145
  cycling (Tab also cycles effort on an empty prompt); structured session-goal status in the right side of the turn footer;
146
146
  animated active-turn timer with a static `ZCODE_TUI_REDUCED_MOTION=1`
147
147
  fallback; responsive context-remaining and session-token metrics.
148
+ optional plan-quota statusline segment (`ui.quotaStatusline`) and a
149
+ `/quota` balance card for signed-in Coding Plan / Start Plan accounts.
148
150
 
149
151
  **Session discovery.** Bare `/resume` opens a directory-scoped picker;
150
152
  `/sessions` browses desktop and CLI sessions across directories, including forks
@@ -450,6 +452,12 @@ for intentional non-interactive execution, `--json` for structured output and
450
452
  `--scope user|workspace` to choose installation scope. Marketplace Git access
451
453
  behind a proxy uses `ZCODE_HTTP_PROXY`.
452
454
 
455
+ Each launcher plugin request has a 60-second timeout. For slow marketplace or
456
+ plugin downloads, set `ZCODE_PLUGIN_REQUEST_TIMEOUT_MS` to a larger duration in
457
+ milliseconds. For marketplace addition/update and plugin installation,
458
+ cancellation asks the runtime to stop the operation and release its storage lock
459
+ before the launcher terminates an unresponsive app-server.
460
+
453
461
  Plugins with configuration can load options from a JSON file without exposing
454
462
  values in the process argument list:
455
463
 
@@ -580,7 +588,8 @@ overrides leave Desktop's credentials and provider configuration untouched.
580
588
  Client headers and a local usage row do not independently prove server-side
581
589
  bonus accounting.
582
590
 
583
- `/settings` saves the default model; `/model` changes only the current session.
591
+ `/settings` and `/model default` save the default model; `/model` changes only
592
+ the current session.
584
593
  See [`provider.example.json`](./provider.example.json) for complete field examples
585
594
  and the [provider configuration reference](./docs/PROVIDER_CONFIG.md) for multimodal
586
595
  capabilities, native search, token limits, reasoning maps and automatic upstream
package/bin/zcode.js CHANGED
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  import { execFile, spawn } from "node:child_process";
3
+ import { createHash, randomUUID } from "node:crypto";
3
4
  import { appendFileSync, chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeSync } from "node:fs";
4
5
  import { constants, homedir } from "node:os";
5
6
  import { basename, dirname, join, posix, resolve, win32 } from "node:path";
6
7
  import { fileURLToPath } from "node:url";
7
- import { createHash, randomUUID } from "node:crypto";
8
8
  import { access, link, mkdir, open, readFile, rename, rm, stat } from "node:fs/promises";
9
9
  import { parseArgs, promisify } from "node:util";
10
10
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -62,6 +62,7 @@ var setting_example_default = {
62
62
  "theme": "auto",
63
63
  "tuiMode": "regular",
64
64
  "toolCallStyle": "regular",
65
+ "quotaStatusline": false,
65
66
  "copyOnSelect": true,
66
67
  "notifications": {
67
68
  "method": "auto",
@@ -355,6 +356,7 @@ async function markSetupPending(env = process.env) {
355
356
  async function clearSetupPending(env = process.env) {
356
357
  await rm(setupPendingPath(env), { force: true }).catch(() => {});
357
358
  }
359
+ new AsyncLocalStorage();
358
360
  promisify(execFile);
359
361
  promisify(execFile);
360
362
  new AsyncLocalStorage();
@@ -484,6 +486,7 @@ function classifyZaiOAuthInvocation(args) {
484
486
  //#region src/app-server-client.ts
485
487
  const maximumOutputBytes = 16 * 1024 * 1024;
486
488
  const forceTerminationDelayMilliseconds = 500;
489
+ const cooperativeCancellationDelayMilliseconds = 3e3;
487
490
  var AppServerRequestError = class extends Error {
488
491
  code;
489
492
  data;
@@ -510,6 +513,14 @@ var AppServerCancellationError = class extends Error {
510
513
  this.name = "AbortError";
511
514
  }
512
515
  };
516
+ var AppServerTimeoutError = class extends Error {
517
+ timeoutMs;
518
+ constructor(timeoutMs) {
519
+ super(`App-server request timed out after ${timeoutMs}ms.`);
520
+ this.timeoutMs = timeoutMs;
521
+ this.name = "TimeoutError";
522
+ }
523
+ };
513
524
  function signalExitCode$1(signal) {
514
525
  if (!signal) return 1;
515
526
  const number = constants.signals[signal];
@@ -560,6 +571,7 @@ function responseEnvelope(stdout) {
560
571
  }
561
572
  async function requestAppServer(request) {
562
573
  if (request.signal?.aborted) throw cancellationError(request.signal);
574
+ 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.");
563
575
  const child = spawn(request.transport.command, request.transport.args, {
564
576
  cwd: request.transport.cwd,
565
577
  env: request.transport.env,
@@ -573,6 +585,9 @@ async function requestAppServer(request) {
573
585
  let launchError;
574
586
  let overflow = false;
575
587
  let forceTerminationTimer;
588
+ let requestTimeoutTimer;
589
+ let timedOut = false;
590
+ let cancelling = false;
576
591
  const exited = new Promise((resolve) => {
577
592
  let settled = false;
578
593
  const finish = (code) => {
@@ -590,7 +605,7 @@ async function requestAppServer(request) {
590
605
  overflow = true;
591
606
  child.kill("SIGKILL");
592
607
  };
593
- const onAbort = () => {
608
+ const terminate = () => {
594
609
  if (child.exitCode !== null || child.signalCode !== null) return;
595
610
  child.kill(terminationSignal(request.signal));
596
611
  forceTerminationTimer = setTimeout(() => {
@@ -598,8 +613,19 @@ async function requestAppServer(request) {
598
613
  }, forceTerminationDelayMilliseconds);
599
614
  forceTerminationTimer.unref();
600
615
  };
601
- request.signal?.addEventListener("abort", onAbort, { once: true });
602
- if (request.signal?.aborted) onAbort();
616
+ const onAbort = () => {
617
+ if (cancelling || child.exitCode !== null || child.signalCode !== null) return;
618
+ cancelling = true;
619
+ if (requestTimeoutTimer) clearTimeout(requestTimeoutTimer);
620
+ if (request.cancellation && !child.stdin.writableEnded && !child.stdin.destroyed) {
621
+ child.stdin.end(`${JSON.stringify({
622
+ id: 2,
623
+ ...request.cancellation
624
+ })}\n`);
625
+ forceTerminationTimer = setTimeout(terminate, cooperativeCancellationDelayMilliseconds);
626
+ forceTerminationTimer.unref();
627
+ } else terminate();
628
+ };
603
629
  child.stdin.on("error", () => {});
604
630
  const decoder = new StringDecoder("utf8");
605
631
  let pending = "";
@@ -617,12 +643,22 @@ async function requestAppServer(request) {
617
643
  method: request.method,
618
644
  params: request.params
619
645
  })}\n`);
646
+ request.signal?.addEventListener("abort", onAbort, { once: true });
647
+ if (request.signal?.aborted) onAbort();
648
+ else if (request.timeoutMs !== void 0) {
649
+ requestTimeoutTimer = setTimeout(() => {
650
+ timedOut = true;
651
+ onAbort();
652
+ }, request.timeoutMs);
653
+ requestTimeoutTimer.unref();
654
+ }
620
655
  try {
621
656
  const [code, stdout, stderr] = await Promise.all([
622
657
  exited,
623
658
  stdoutPromise,
624
659
  readBounded(child.stderr, terminateForOverflow)
625
660
  ]);
661
+ if (timedOut) throw new AppServerTimeoutError(request.timeoutMs);
626
662
  if (request.signal?.aborted) throw cancellationError(request.signal);
627
663
  if (overflow) throw new Error(`App-server output exceeded ${maximumOutputBytes} bytes.`);
628
664
  if (launchError) throw launchError;
@@ -633,6 +669,7 @@ async function requestAppServer(request) {
633
669
  if (stderr) request.onStderr?.(stderr);
634
670
  return envelope.result;
635
671
  } finally {
672
+ if (requestTimeoutTimer) clearTimeout(requestTimeoutTimer);
636
673
  if (forceTerminationTimer) clearTimeout(forceTerminationTimer);
637
674
  request.signal?.removeEventListener("abort", onAbort);
638
675
  }
@@ -986,6 +1023,7 @@ async function runPluginCommand(args, options) {
986
1023
  success: "Marketplace validation succeeded."
987
1024
  }, false);
988
1025
  if (!command.yes && !await confirm(`Add marketplace from ${printable(value)}?`)) throw new Error("Marketplace addition cancelled. Use --yes for non-interactive use.");
1026
+ if (!command.json) stdout.write("Adding marketplace...\n");
989
1027
  const result = await call(pluginProtocolMethods.marketplaceAdd, { source: value });
990
1028
  print(result, () => renderMutation(stdout, result, {
991
1029
  failure: "Marketplace addition failed.",
@@ -1319,13 +1357,16 @@ async function readCatalog(path, missingIsEmpty = false) {
1319
1357
  }
1320
1358
  }
1321
1359
  /**
1322
- * Reject a CLI override before the interactive runtime starts when both local
1360
+ * Reject a CLI override before the runtime starts when both local
1323
1361
  * registries are readable and conclusively show that the selection is absent.
1324
- * If either registry is unavailable, defer to the runtime to avoid rejecting
1325
- * models supplied by a remote or not-yet-materialized catalog.
1362
+ * Account catalogs can add models and providers beyond the local registries,
1363
+ * so the runtime owns their validation. Also defer if either registry is unavailable.
1326
1364
  */
1327
1365
  async function invalidConfiguredPromptModel(model, env = process.env) {
1328
1366
  if (!model) return void 0;
1367
+ const separator = model.indexOf("/");
1368
+ const providerId = model.slice(0, separator);
1369
+ if (providerId.startsWith("account:")) return void 0;
1329
1370
  let personal;
1330
1371
  let builtin;
1331
1372
  try {
@@ -1336,8 +1377,6 @@ async function invalidConfiguredPromptModel(model, env = process.env) {
1336
1377
  return;
1337
1378
  }
1338
1379
  if (!personal || !builtin) return void 0;
1339
- const separator = model.indexOf("/");
1340
- const providerId = model.slice(0, separator);
1341
1380
  const modelId = model.slice(separator + 1);
1342
1381
  const personalModels = personal.get(providerId);
1343
1382
  const builtinModels = builtin.get(providerId);
@@ -1388,6 +1427,17 @@ const versionArguments = /* @__PURE__ */ new Set([
1388
1427
  "-v"
1389
1428
  ]);
1390
1429
  const runtimeVariadicOptions = /* @__PURE__ */ new Set(["--disallowedTools", "--disallowed-tools"]);
1430
+ const cancellablePluginMethods = /* @__PURE__ */ new Set([
1431
+ pluginProtocolMethods.marketplaceAdd,
1432
+ pluginProtocolMethods.marketplaceUpdate,
1433
+ pluginProtocolMethods.install
1434
+ ]);
1435
+ function pluginRequestTimeoutMs() {
1436
+ const value = process.env.ZCODE_PLUGIN_REQUEST_TIMEOUT_MS?.trim();
1437
+ const timeout = value ? Number(value) : 6e4;
1438
+ if (!Number.isInteger(timeout) || timeout <= 0 || timeout > 2147483647) throw new Error("ZCODE_PLUGIN_REQUEST_TIMEOUT_MS must be an integer between 1 and 2147483647.");
1439
+ return timeout;
1440
+ }
1391
1441
  function resolveModelRetryMaxRetries(env) {
1392
1442
  return env.ZCODE_MODEL_RETRY_MAX_RETRIES?.trim() || defaultModelRetryMaxRetries;
1393
1443
  }
@@ -1772,24 +1822,35 @@ async function main(args) {
1772
1822
  let pluginCommand;
1773
1823
  try {
1774
1824
  pluginCommand = await runPluginCommand(args, {
1775
- request: async ({ method, params, signal, workingDirectory }) => await requestAppServer({
1776
- method,
1777
- params,
1778
- onStderr: (stderr) => {
1779
- for (const line of stderr.split(/\r?\n/u)) {
1780
- if (!line.startsWith("ZCode Built-in: ignoring unavailable ZCODE_BUILTIN_PROVIDER_CONFIG_FILE ") || builtinProviderWarnings.has(line)) continue;
1781
- builtinProviderWarnings.add(line);
1782
- process.stderr.write(`${line}\n`);
1825
+ request: async ({ method, params, signal, workingDirectory }) => {
1826
+ const operationId = cancellablePluginMethods.has(method) ? randomUUID() : void 0;
1827
+ return await requestAppServer({
1828
+ method,
1829
+ params: operationId ? {
1830
+ ...params,
1831
+ operationId
1832
+ } : params,
1833
+ ...operationId ? { cancellation: {
1834
+ method: "plugins/cancelOperation",
1835
+ params: { operationId }
1836
+ } } : {},
1837
+ timeoutMs: pluginRequestTimeoutMs(),
1838
+ onStderr: (stderr) => {
1839
+ for (const line of stderr.split(/\r?\n/u)) {
1840
+ if (!line.startsWith("ZCode Built-in: ignoring unavailable ZCODE_BUILTIN_PROVIDER_CONFIG_FILE ") || builtinProviderWarnings.has(line)) continue;
1841
+ builtinProviderWarnings.add(line);
1842
+ process.stderr.write(`${line}\n`);
1843
+ }
1844
+ },
1845
+ signal: signal ?? pluginAbortController.signal,
1846
+ transport: {
1847
+ args: [runtimePath, "app-server"],
1848
+ command: node,
1849
+ cwd: workingDirectory,
1850
+ env: runtimeEnvironment()
1783
1851
  }
1784
- },
1785
- signal: signal ?? pluginAbortController.signal,
1786
- transport: {
1787
- args: [runtimePath, "app-server"],
1788
- command: node,
1789
- cwd: workingDirectory,
1790
- env: runtimeEnvironment()
1791
- }
1792
- }),
1852
+ });
1853
+ },
1793
1854
  signal: pluginAbortController.signal
1794
1855
  });
1795
1856
  } finally {
@@ -637,6 +637,16 @@ user config: `~/.zcode/cli/setting.json` on macOS/Linux or
637
637
  takes priority over terminal probing. `auto` queries the terminal background
638
638
  color and color scheme at startup and re-applies the matching palette.
639
639
 
640
+ ## Plan quota statusline
641
+
642
+ Set `ui.quotaStatusline` to `true` in the user config to add a `quota <percent>%`
643
+ segment to the compact statusline. It shows the lowest remaining balance across
644
+ the signed-in account's plan slots, warning-tinted below 20% and error-tinted
645
+ when exhausted, refreshed in the background every five minutes. It renders only
646
+ for OAuth sessions (Start Plan / Coding Plan); manual API-key providers have no
647
+ zcode-plan balance to read. `/quota` opens the full balance card on demand and
648
+ refreshes immediately.
649
+
640
650
  ## Turn completion notifications
641
651
 
642
652
  Notifications are enabled by default and emitted after a normal agent turn
@@ -705,10 +715,19 @@ export ZCODE_TUI_NOTIFICATION_CONDITION=always # unfocused|always
705
715
  zcode
706
716
  ```
707
717
 
718
+ ## Plugin request timeout
719
+
720
+ Launcher plugin requests time out after 60 seconds. Set
721
+ `ZCODE_PLUGIN_REQUEST_TIMEOUT_MS` to a positive integer in milliseconds (up to
722
+ 2147483647) to allow longer downloads. Marketplace addition/update and plugin
723
+ installation request runtime cleanup on timeout or cancellation before terminating
724
+ an unresponsive app-server.
725
+
708
726
  ## Official MCP Availability
709
727
 
710
- When the bundled runtime has no official MCP trusted-origin registry, official
711
- HTTP MCP services are reported as disabled with an `official_auth_unavailable`
712
- diagnostic. Other plugin components remain available. This does not disable
713
- certificate, origin, or permission checks, and does not suppress services when
714
- the runtime provides the required registry. No user configuration is rewritten.
728
+ Official HTTP MCP services that use ZCode's trusted-origin authentication
729
+ require the runtime host to provide its trusted-origin registry and auth-header
730
+ port. If those host capabilities are unavailable, the runtime fails that
731
+ service connection and reports that the official MCP trusted-origin registry is
732
+ unavailable. Other MCP services remain available. No user configuration is
733
+ rewritten, and certificate, origin, and permission checks remain enabled.
@@ -513,6 +513,18 @@ ZCODE_TUI_RUNTIME_LOG=/tmp/zcode-tui-runtime.log zcode
513
513
  }
514
514
  }
515
515
  ```
516
+ ```
517
+
518
+ ## 计划额度状态栏
519
+
520
+ 在用户配置中将 `ui.quotaStatusline` 设为 `true`,紧凑状态栏会追加
521
+ `quota <percent>%` 段:显示登录账号所有计划槽位中剩余最少的一项,
522
+ 低于 20% 时以警告色显示,耗尽时以错误色显示,后台每五分钟刷新一次。
523
+ 该功能仅适用于 OAuth 会话(Start Plan / Coding Plan);手动 API-key
524
+ 提供商没有可读取的 zcode-plan 余额。`/quota` 可随时打开完整余额卡片
525
+ 并立即刷新。
526
+
527
+
516
528
 
517
529
  正常退出或处理 `SIGINT`、`SIGTERM`、`SIGHUP` 时会恢复终端状态。
518
530
  任何终端程序都无法拦截强制的 `SIGKILL`。
@@ -595,6 +607,12 @@ export ZCODE_TUI_NOTIFICATION_CONDITION=always # unfocused|always
595
607
  zcode
596
608
  ```
597
609
 
610
+ ## 插件请求超时
611
+
612
+ 启动器的插件请求默认在 60 秒后超时。下载较慢时,可将
613
+ `ZCODE_PLUGIN_REQUEST_TIMEOUT_MS` 设置为更大的正整数毫秒值(最大 2147483647)。
614
+ 添加或更新市场、安装插件时,超时或取消会先请求 runtime 清理操作,再终止无响应的 app-server。
615
+
598
616
  ## 官方 MCP 可用性
599
617
 
600
618
  如果捆绑 runtime 没有官方 MCP 的可信来源 registry,官方 HTTP MCP 服务会显示为禁用,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zcode-app-cli",
3
- "version": "4.0.0-49",
3
+ "version": "4.0.0-51",
4
4
  "description": "Unofficial terminal client for the ZCode agent runtime",
5
5
  "keywords": [
6
6
  "agent",
@@ -56,6 +56,7 @@
56
56
  "theme": "auto",
57
57
  "tuiMode": "regular",
58
58
  "toolCallStyle": "regular",
59
+ "quotaStatusline": false,
59
60
  "copyOnSelect": true,
60
61
  "notifications": {
61
62
  "method": "auto",