zcode-app-cli 3.7.7-12 → 3.7.7-14

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.
@@ -23,12 +23,13 @@ var config_example_default = {
23
23
  "models": {
24
24
  "glm-5.3": { "name": "GLM-5.3" },
25
25
  "glm-5.2": { "name": "GLM-5.2" },
26
- "glm-5.1": { "name": "GLM-5.1" }
26
+ "glm-5.1": { "name": "GLM-5.1" },
27
+ "glm-5-turbo": { "name": "GLM-5-Turbo" }
27
28
  }
28
29
  } },
29
30
  model: {
30
31
  "main": "zai/glm-5.2",
31
- "lite": "zai/glm-5.1"
32
+ "lite": "zai/glm-5-turbo"
32
33
  },
33
34
  modelCatalog: { "overrides": {} },
34
35
  modelStream: { "idleTimeoutMs": 6e4 },
@@ -129,6 +130,9 @@ function userConfigPath(env = process.env, platform = process.platform, fallback
129
130
  const configuredHome = (platform === "win32" ? env.USERPROFILE : env.HOME)?.trim();
130
131
  return path.join(configuredHome || fallbackHome, ".zcode", "cli", "config.json");
131
132
  }
133
+ function userConfigPathHint(platform = process.platform) {
134
+ return platform === "win32" ? "%USERPROFILE%\\.zcode\\cli\\config.json" : "~/.zcode/cli/config.json";
135
+ }
132
136
  async function ensureUserConfig(env = process.env) {
133
137
  const configPath = userConfigPath(env);
134
138
  const configDirectory = dirname(configPath);
@@ -157286,6 +157290,7 @@ var ChoiceDialog = class {
157286
157290
  this.contentExpanded = !this.contentExpanded;
157287
157291
  return;
157288
157292
  }
157293
+ if ((this.content?.handleInput)?.call(this.content, data) === true) return;
157289
157294
  if (this.contentExpanded) {
157290
157295
  if (matchesKey(data, "escape")) {
157291
157296
  this.contentExpanded = false;
@@ -158059,7 +158064,8 @@ function normalizeGoal(value) {
158059
158064
  function formatTokens(value) {
158060
158065
  if (value < 1e3) return Math.floor(value).toString();
158061
158066
  if (value < 1e6) return `${Number((value / 1e3).toFixed(1))}K`;
158062
- return `${Number((value / 1e6).toFixed(1))}M`;
158067
+ if (value < 1e9) return `${Number((value / 1e6).toFixed(1))}M`;
158068
+ return `${Number((value / 1e9).toFixed(1))}G`;
158063
158069
  }
158064
158070
  function formatGoalElapsed(totalSeconds) {
158065
158071
  const seconds = Math.max(0, Math.floor(totalSeconds));
@@ -158087,6 +158093,60 @@ function goalStatusText(goal) {
158087
158093
  return goal.timeUsedSeconds > 0 ? `${label} (${formatGoalElapsed(goal.timeUsedSeconds)})` : label;
158088
158094
  }
158089
158095
  //#endregion
158096
+ //#region packages/zcode-tui/src/session-status.ts
158097
+ function nonNegativeNumber(value) {
158098
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : void 0;
158099
+ }
158100
+ function projectionMetrics(value) {
158101
+ if (!isRecord(value)) return void 0;
158102
+ const metrics = {
158103
+ contextUsed: nonNegativeNumber(value.contextUsed),
158104
+ contextWindow: nonNegativeNumber(value.contextWindow),
158105
+ totalTokens: nonNegativeNumber(value.totalTokenCount),
158106
+ turnCount: nonNegativeNumber(value.turnCount)
158107
+ };
158108
+ return Object.values(metrics).some((metric) => metric !== void 0) ? metrics : void 0;
158109
+ }
158110
+ function usageMetrics(value) {
158111
+ if (!isRecord(value)) return void 0;
158112
+ const metrics = {
158113
+ totalTokens: nonNegativeNumber(value.totalTokens),
158114
+ inputTokens: nonNegativeNumber(value.inputTokens),
158115
+ outputTokens: nonNegativeNumber(value.outputTokens),
158116
+ reasoningTokens: nonNegativeNumber(value.reasoningTokens),
158117
+ cacheCreationTokens: nonNegativeNumber(value.cacheCreationTokens),
158118
+ cacheReadTokens: nonNegativeNumber(value.cacheReadTokens),
158119
+ modelRequestCount: nonNegativeNumber(value.modelRequestCount),
158120
+ modelErrorCount: nonNegativeNumber(value.modelErrorCount)
158121
+ };
158122
+ return Object.values(metrics).some((metric) => metric !== void 0) ? metrics : void 0;
158123
+ }
158124
+ function sessionIdFromUsage(value) {
158125
+ if (!isRecord(value)) return void 0;
158126
+ return (asString(value.sessionId) ?? asString(value.sessionID))?.trim() || void 0;
158127
+ }
158128
+ function mergeMetrics(current, update) {
158129
+ if (!update) return current;
158130
+ const defined = Object.fromEntries(Object.entries(update).filter((entry) => entry[1] !== void 0));
158131
+ return {
158132
+ ...current,
158133
+ ...defined
158134
+ };
158135
+ }
158136
+ function mergeProjectionMetrics(current, update, hasAuthoritativeSessionUsage) {
158137
+ if (!update || !hasAuthoritativeSessionUsage) return mergeMetrics(current, update);
158138
+ const { totalTokens: _projectionTotal, ...contextMetrics } = update;
158139
+ return mergeMetrics(current, contextMetrics);
158140
+ }
158141
+ function contextUsedPercent(metrics) {
158142
+ if (metrics.contextUsed === void 0 || !metrics.contextWindow) return void 0;
158143
+ return Math.max(0, Math.min(100, Math.round(metrics.contextUsed / metrics.contextWindow * 100)));
158144
+ }
158145
+ function contextRemainingPercent(metrics) {
158146
+ const used = contextUsedPercent(metrics);
158147
+ return used === void 0 ? void 0 : 100 - used;
158148
+ }
158149
+ //#endregion
158090
158150
  //#region packages/zcode-tui/src/context-status-view.ts
158091
158151
  const contextLabels = {
158092
158152
  system_prompt: "System prompt",
@@ -158095,65 +158155,206 @@ const contextLabels = {
158095
158155
  tool_prompt: "Tool prompts",
158096
158156
  system_tool_schemas: "System tool schemas",
158097
158157
  mcp_tool_schemas: "MCP tool schemas",
158098
- messages: "Messages"
158158
+ messages: "Messages",
158159
+ user_messages: "User messages",
158160
+ assistant_messages: "Assistant messages",
158161
+ tool_io: "Tool input/output"
158099
158162
  };
158100
158163
  function contextStyle(source, theme) {
158101
- if (source === "messages") return theme.accent;
158102
- if (source === "skills" || source === "mcp_tool_schemas") return theme.success;
158103
- if (source === "system_prompt" || source === "system_tool_schemas") return theme.warning;
158164
+ if (source === "messages" || source === "assistant_messages") return theme.accent;
158165
+ if (source === "user_messages" || source === "skills" || source === "mcp_tool_schemas") return theme.success;
158166
+ if (source === "tool_io" || source === "system_prompt" || source === "system_tool_schemas") return theme.warning;
158104
158167
  return theme.muted;
158105
158168
  }
158106
158169
  function percent(value, total) {
158107
158170
  return total > 0 ? `${(value / total * 100).toFixed(1)}%` : "0%";
158108
158171
  }
158172
+ function rate(value) {
158173
+ return value === void 0 ? "—" : `${Math.round(value * 100)}%`;
158174
+ }
158175
+ function summaryLine(label, summary, theme) {
158176
+ const tokens = `${formatTokens(summary.inputTokens)} input · ${formatTokens(summary.cacheReadTokens)} read · ${formatTokens(summary.cacheWriteTokens)} write`;
158177
+ return `${theme.bold(label)} ${rate(summary.hitRate)} hit · ${summary.requests} requests · ${theme.muted(tokens)}`;
158178
+ }
158179
+ function turnMarker(turn, theme) {
158180
+ if (turn.state === "unknown") return theme.muted("?");
158181
+ if (turn.state === "hit") return theme.success("█");
158182
+ return theme.warning("░");
158183
+ }
158184
+ function trendGraph(turns, width, theme) {
158185
+ const points = turns.slice(-Math.max(1, Math.min(80, width - 8)));
158186
+ if (points.length === 0) return [theme.muted("No request-level cache data yet.")];
158187
+ const height = 4;
158188
+ const columns = Array.from({ length: height }, () => "");
158189
+ for (let row = height; row >= 1; row -= 1) columns[height - row] = points.map((turn) => {
158190
+ if (turn.state === "unknown") return " ";
158191
+ return Math.max(0, Math.min(height, Math.round((turn.hitRate ?? 0) * height))) >= row ? turnMarker(turn, theme) : " ";
158192
+ }).join("");
158193
+ const labels = points.map((turn) => turn.state === "unknown" ? " " : "·").join("");
158194
+ return [
158195
+ `${theme.muted("100% ")} ${columns[0]}`,
158196
+ `${theme.muted(" 75% ")} ${columns[1]}`,
158197
+ `${theme.muted(" 50% ")} ${columns[2]}`,
158198
+ `${theme.muted(" 25% ")} ${columns[3]}`,
158199
+ `${theme.muted(" 0% ")} ${labels}`,
158200
+ theme.muted("█ cache hit · ░ uncached request · blank gap = unavailable")
158201
+ ];
158202
+ }
158203
+ function recentTurnLine(turn, theme) {
158204
+ const id = turn.messageId ? turn.messageId.slice(-8) : "unknown";
158205
+ const usage = turn.inputTokens === void 0 ? "cache data unavailable" : `${rate(turn.hitRate)} hit · ${formatTokens(turn.inputTokens)} input · ${formatTokens(turn.cacheReadTokens ?? 0)} read`;
158206
+ return `${turnMarker(turn, theme)} ${String(turn.index).padStart(3, " ")} ${theme.muted(id)} ${usage}`;
158207
+ }
158109
158208
  var ContextDetailView = class {
158110
158209
  theme;
158210
+ refresh;
158211
+ requestRender;
158111
158212
  usage;
158112
- constructor(theme, usage) {
158213
+ trend;
158214
+ page = "overview";
158215
+ refreshing = false;
158216
+ constructor(theme, usage, trend, refresh, requestRender) {
158113
158217
  this.theme = theme;
158218
+ this.refresh = refresh;
158219
+ this.requestRender = requestRender;
158114
158220
  this.usage = usage;
158221
+ this.trend = trend;
158115
158222
  }
158116
158223
  invalidate() {}
158224
+ setData(usage, trend) {
158225
+ this.usage = usage;
158226
+ this.trend = trend;
158227
+ }
158228
+ handleInput(data) {
158229
+ const key = data.length === 1 ? data.toLowerCase() : data;
158230
+ if (key === "1" || key === "2" || key === "3" || key === "v") {
158231
+ const pages = [
158232
+ "overview",
158233
+ "trend",
158234
+ "composition"
158235
+ ];
158236
+ this.page = key === "v" ? pages[(pages.indexOf(this.page) + 1) % pages.length] : pages[Number(key) - 1];
158237
+ this.requestRender?.();
158238
+ return true;
158239
+ }
158240
+ if (key !== "r" || !this.refresh || this.refreshing) return false;
158241
+ this.refreshing = true;
158242
+ this.requestRender?.();
158243
+ this.refresh().then((data) => {
158244
+ this.setData(data.usage, data.trend);
158245
+ }).catch(() => {}).finally(() => {
158246
+ this.refreshing = false;
158247
+ this.requestRender?.();
158248
+ });
158249
+ return true;
158250
+ }
158117
158251
  render(width) {
158252
+ if (this.page === "trend") return this.renderTrend(width);
158253
+ if (this.page === "composition") return this.renderComposition(width);
158254
+ return this.renderOverview(width);
158255
+ }
158256
+ renderOverview(width) {
158118
158257
  if (!this.usage) return [this.theme.muted("Context usage is unavailable in this runtime.")];
158258
+ const safeWidth = Math.max(1, width);
158119
158259
  const totalChars = this.usage.breakdown.reduce((total, item) => total + item.chars, 0);
158120
- const barWidth = Math.max(8, Math.min(40, width - 2));
158260
+ const barWidth = Math.max(8, Math.min(40, safeWidth - 2));
158121
158261
  const bar = this.usage.breakdown.map((item) => {
158122
158262
  const columns = totalChars > 0 ? Math.max(1, Math.round(item.chars / totalChars * barWidth)) : 0;
158123
158263
  return contextStyle(item.source, this.theme)("█".repeat(columns));
158124
158264
  }).join("");
158265
+ const usedPercent = contextUsedPercent({
158266
+ contextUsed: this.usage.used,
158267
+ contextWindow: this.usage.size
158268
+ }) ?? 0;
158269
+ const remaining = Math.max(0, this.usage.size - this.usage.used);
158270
+ const usageStyle = usedPercent >= 90 ? this.theme.error : usedPercent >= 70 ? this.theme.warning : (text) => text;
158271
+ const lines = [this.theme.bold("Context overview"), usageStyle(`${formatTokens(this.usage.used)} / ${formatTokens(this.usage.size)} tokens · ${usedPercent}% used · ${formatTokens(remaining)} remaining`)];
158272
+ if (this.refreshing) lines.push(this.theme.muted("Refreshing context data…"));
158273
+ if (this.trend) {
158274
+ lines.push("", this.theme.bold("Cache health · exact runtime tokens"), summaryLine("Active branch", this.trend.active, this.theme), summaryLine("Whole tree", this.trend.wholeTree, this.theme), this.theme.muted(`Latest ${rate(this.trend.wholeTree.latestHitRate)} · min ${rate(this.trend.wholeTree.minHitRate)} · max ${rate(this.trend.wholeTree.maxHitRate)} · ${this.trend.turns.length} turns`), ...trendGraph(this.trend.turns, safeWidth, this.theme), "", this.theme.bold("Recent cache requests"));
158275
+ lines.push(...this.trend.turns.slice(-8).map((turn) => recentTurnLine(turn, this.theme)));
158276
+ if (this.trend.turns.some((turn) => turn.state === "unknown")) lines.push(this.theme.muted("Request-level token data is unavailable; gaps are intentional."));
158277
+ }
158278
+ if (totalChars > 0) {
158279
+ lines.push("", this.theme.bold("Estimated prompt composition by characters"), truncateToWidth(bar, safeWidth));
158280
+ for (const item of this.usage.breakdown.slice().sort((left, right) => right.chars - left.chars)) {
158281
+ const label = contextLabels[item.source];
158282
+ const value = `${item.chars.toLocaleString()} chars · ${percent(item.chars, totalChars)}`;
158283
+ const available = Math.max(1, safeWidth - visibleWidth(value) - 3);
158284
+ lines.push(`${contextStyle(item.source, this.theme)("●")} ${truncateToWidth(label, available)} ${this.theme.muted(value)}`);
158285
+ }
158286
+ } else lines.push("", this.theme.muted("Prompt source composition is unavailable for this turn."));
158125
158287
  const cache = this.usage.cache;
158126
- const cacheHitRate = cache?.latestHitRate ?? cache?.hitRate;
158288
+ if (cache) {
158289
+ lines.push("", this.theme.bold("Session cache totals"));
158290
+ const latest = [
158291
+ cache.latestHitRate !== void 0 && cache.latestHitRate !== null ? `${Math.round(cache.latestHitRate * 100)}% hit` : void 0,
158292
+ cache.cacheReadTokens !== void 0 ? `${formatTokens(cache.cacheReadTokens)} read` : void 0,
158293
+ cache.cacheWriteTokens !== void 0 ? `${formatTokens(cache.cacheWriteTokens)} written` : void 0,
158294
+ cache.inputTokens !== void 0 ? `${formatTokens(cache.inputTokens)} input` : void 0
158295
+ ].filter(Boolean);
158296
+ if (latest.length > 0) {
158297
+ const latestLabel = cache.latestHitRate !== void 0 && cache.latestHitRate !== null ? `${Math.round(cache.latestHitRate * 100)}% hit rate` : latest.join(" · ");
158298
+ lines.push(this.theme.muted(`Latest request ${latestLabel}${latest.length > 1 ? ` · ${latest.slice(1).join(" · ")}` : ""}`));
158299
+ }
158300
+ const aggregateTokens = [
158301
+ cache.totalCacheReadTokens !== void 0 ? `${formatTokens(cache.totalCacheReadTokens)} read` : void 0,
158302
+ cache.totalCacheWriteTokens !== void 0 ? `${formatTokens(cache.totalCacheWriteTokens)} written` : void 0,
158303
+ cache.totalInputTokens !== void 0 ? `${formatTokens(cache.totalInputTokens)} input` : void 0
158304
+ ].filter(Boolean);
158305
+ if (aggregateTokens.length > 0) lines.push(this.theme.muted(`Session tokens ${aggregateTokens.join(" · ")}`));
158306
+ if (cache.hitRate !== void 0 && cache.hitRate !== null) lines.push(this.theme.muted(`Session total ${Math.round(cache.hitRate * 100)}% hit rate · ${cache.hitRateRequestCount ?? 0} requests`));
158307
+ }
158308
+ if (this.usage.cost) lines.push(this.theme.muted(`Cost: ${this.usage.cost.amount} ${this.usage.cost.currency}`));
158309
+ lines.push("", this.theme.muted("1 overview · 2 cache trend · 3 composition · v cycle · r refresh"));
158310
+ return lines.map((line) => truncateToWidth(line, safeWidth));
158311
+ }
158312
+ renderTrend(width) {
158313
+ const safeWidth = Math.max(1, width);
158314
+ if (!this.trend) return [
158315
+ this.theme.bold("Cache trend"),
158316
+ this.theme.muted("Per-turn cache data is unavailable in this runtime."),
158317
+ this.theme.muted("1 overview · 3 composition · r refresh")
158318
+ ];
158127
158319
  const lines = [
158128
- this.theme.bold("Context Usage"),
158129
- `${formatTokens(this.usage.used)} / ${formatTokens(this.usage.size)} tokens · ${Math.round(this.usage.used / this.usage.size * 100)}% used`,
158130
- truncateToWidth(bar, width),
158320
+ this.theme.bold("Context cache · per request"),
158321
+ summaryLine("Active branch", this.trend.active, this.theme),
158322
+ summaryLine("Whole tree", this.trend.wholeTree, this.theme),
158323
+ this.theme.muted(`Latest ${rate(this.trend.wholeTree.latestHitRate)} · min ${rate(this.trend.wholeTree.minHitRate)} · max ${rate(this.trend.wholeTree.maxHitRate)} · ${this.trend.turns.length} turns`),
158324
+ "",
158325
+ ...trendGraph(this.trend.turns, safeWidth, this.theme),
158326
+ this.theme.muted("Misses and gaps are kept; runtime restarts are not smoothed."),
158131
158327
  "",
158132
- this.theme.muted("Estimated prompt composition by characters")
158328
+ this.theme.bold("Recent 8 requests"),
158329
+ ...this.trend.turns.slice(-8).map((turn) => recentTurnLine(turn, this.theme)),
158330
+ this.theme.muted("1 overview · 2 cache trend · 3 composition · v cycle · r refresh")
158133
158331
  ];
158332
+ if (this.trend.turns.some((turn) => turn.state === "unknown")) lines.splice(lines.length - 1, 0, this.theme.muted("Unknown usage stays blank; no interpolation is applied."));
158333
+ return lines.map((line) => truncateToWidth(line, safeWidth));
158334
+ }
158335
+ renderComposition(width) {
158336
+ const safeWidth = Math.max(1, width);
158337
+ if (!this.usage) return [this.theme.muted("Prompt composition is unavailable in this runtime.")];
158338
+ const totalChars = this.usage.breakdown.reduce((total, item) => total + item.chars, 0);
158339
+ if (totalChars <= 0) return [
158340
+ this.theme.bold("Estimated prompt composition by characters"),
158341
+ this.theme.muted("Prompt source composition is unavailable for this turn."),
158342
+ this.theme.muted("1 overview · 2 cache trend · v cycle · r refresh")
158343
+ ];
158344
+ const barWidth = Math.max(8, Math.min(40, safeWidth - 2));
158345
+ const bar = this.usage.breakdown.map((item) => {
158346
+ const columns = Math.max(1, Math.round(item.chars / totalChars * barWidth));
158347
+ return contextStyle(item.source, this.theme)("█".repeat(columns));
158348
+ }).join("");
158349
+ const lines = [this.theme.bold("Estimated prompt composition by characters"), truncateToWidth(bar, safeWidth)];
158134
158350
  for (const item of this.usage.breakdown.slice().sort((left, right) => right.chars - left.chars)) {
158135
158351
  const label = contextLabels[item.source];
158136
158352
  const value = `${item.chars.toLocaleString()} chars · ${percent(item.chars, totalChars)}`;
158137
- const available = Math.max(1, width - visibleWidth(value) - 3);
158353
+ const available = Math.max(1, safeWidth - visibleWidth(value) - 3);
158138
158354
  lines.push(`${contextStyle(item.source, this.theme)("●")} ${truncateToWidth(label, available)} ${this.theme.muted(value)}`);
158139
158355
  }
158140
- if (cache) {
158141
- lines.push("", this.theme.bold("Prompt cache"));
158142
- lines.push(this.theme.muted([
158143
- cacheHitRate !== void 0 && cacheHitRate !== null ? `${Math.round(cacheHitRate * 100)}% hit rate` : void 0,
158144
- cache.cacheReadTokens !== void 0 ? `${formatTokens(cache.cacheReadTokens)} read` : void 0,
158145
- cache.cacheWriteTokens !== void 0 ? `${formatTokens(cache.cacheWriteTokens)} written` : void 0,
158146
- cache.inputTokens !== void 0 ? `${formatTokens(cache.inputTokens)} input` : void 0
158147
- ].filter(Boolean).join(" · ")));
158148
- if (cache.totalInputTokens !== void 0 || cache.hitRateRequestCount !== void 0) lines.push(this.theme.muted([
158149
- cache.hitRateRequestCount !== void 0 ? `${cache.hitRateRequestCount} requests` : void 0,
158150
- cache.totalInputTokens !== void 0 ? `${formatTokens(cache.totalInputTokens)} total input` : void 0,
158151
- cache.totalCacheReadTokens !== void 0 ? `${formatTokens(cache.totalCacheReadTokens)} total read` : void 0,
158152
- cache.totalCacheWriteTokens !== void 0 ? `${formatTokens(cache.totalCacheWriteTokens)} total written` : void 0
158153
- ].filter(Boolean).join(" · ")));
158154
- }
158155
- if (this.usage.cost) lines.push(this.theme.muted(`Cost: ${this.usage.cost.amount} ${this.usage.cost.currency}`));
158156
- return lines.map((line) => truncateToWidth(line, Math.max(1, width)));
158356
+ lines.push("", this.theme.muted("These values are character estimates, not provider token counts."), this.theme.muted("1 overview · 2 cache trend · 3 composition · v cycle · r refresh"));
158357
+ return lines.map((line) => truncateToWidth(line, safeWidth));
158157
158358
  }
158158
158359
  };
158159
158360
  var StatusDetailView = class {
@@ -158178,7 +158379,7 @@ var StatusDetailView = class {
158178
158379
  ["Runtime state", projection?.status],
158179
158380
  ["Last error", projection?.lastError ? [projection.lastError.code, projection.lastError.message].filter(Boolean).join(" · ") : void 0],
158180
158381
  ["Turns", String(metrics.turnCount ?? projection?.turnCount ?? 0)],
158181
- ["Tokens", metrics.totalTokens !== void 0 ? formatTokens(metrics.totalTokens) : void 0],
158382
+ ["Session tokens", metrics.totalTokens !== void 0 ? formatTokens(metrics.totalTokens) : void 0],
158182
158383
  ["Requests", metrics.modelRequestCount !== void 0 ? `${metrics.modelRequestCount}${metrics.modelErrorCount ? ` · ${metrics.modelErrorCount} errors` : ""}` : void 0],
158183
158384
  ["Active tools", projection ? String(projection.activeToolCalls.length) : void 0],
158184
158385
  ["Background", projection ? String(projection.backgroundJobs.filter((job) => job.status === "running").length) : void 0],
@@ -158193,6 +158394,209 @@ var StatusDetailView = class {
158193
158394
  }
158194
158395
  };
158195
158396
  //#endregion
158397
+ //#region packages/zcode-tui/src/context-breakdown.ts
158398
+ function valueLength(value) {
158399
+ const text = asString(value);
158400
+ if (text !== void 0) return text.length;
158401
+ if (value === void 0 || value === null) return 0;
158402
+ try {
158403
+ return JSON.stringify(value).length;
158404
+ } catch {
158405
+ return 0;
158406
+ }
158407
+ }
158408
+ function assistantPartLength(value) {
158409
+ if (!isRecord(value)) return {
158410
+ assistant: 0,
158411
+ tool: 0
158412
+ };
158413
+ const type = asString(value.type);
158414
+ if (type === "thought" || type === "reasoning") return {
158415
+ assistant: valueLength(value.text),
158416
+ tool: 0
158417
+ };
158418
+ if (type !== "tool") return {
158419
+ assistant: 0,
158420
+ tool: 0
158421
+ };
158422
+ return {
158423
+ assistant: 0,
158424
+ tool: valueLength(value.input) + valueLength(value.output) + valueLength(value.error)
158425
+ };
158426
+ }
158427
+ function estimateTranscriptContextBreakdown(value) {
158428
+ const messages = Array.isArray(value) ? value : isRecord(value) && Array.isArray(value.messages) ? value.messages : [];
158429
+ let userChars = 0;
158430
+ let assistantChars = 0;
158431
+ let toolChars = 0;
158432
+ for (const message of messages) {
158433
+ if (!isRecord(message)) continue;
158434
+ const role = asString(message.role);
158435
+ if (role === "user") {
158436
+ userChars += valueLength(message.content);
158437
+ continue;
158438
+ }
158439
+ if (role !== "agent" && role !== "assistant") continue;
158440
+ assistantChars += valueLength(message.content);
158441
+ const parts = Array.isArray(message.parts) ? message.parts : [];
158442
+ for (const part of parts) {
158443
+ const lengths = assistantPartLength(part);
158444
+ assistantChars += lengths.assistant;
158445
+ toolChars += lengths.tool;
158446
+ }
158447
+ }
158448
+ return [
158449
+ {
158450
+ source: "user_messages",
158451
+ chars: userChars
158452
+ },
158453
+ {
158454
+ source: "assistant_messages",
158455
+ chars: assistantChars
158456
+ },
158457
+ {
158458
+ source: "tool_io",
158459
+ chars: toolChars
158460
+ }
158461
+ ].filter((item) => item.chars > 0);
158462
+ }
158463
+ //#endregion
158464
+ //#region packages/zcode-tui/src/context-cache.ts
158465
+ function findActiveBranchMessageIds(value) {
158466
+ const messages = Array.isArray(value) ? value : isRecord(value) && Array.isArray(value.messages) ? value.messages : [];
158467
+ const byId = /* @__PURE__ */ new Map();
158468
+ const ids = [];
158469
+ for (const item of messages) {
158470
+ if (!isRecord(item)) continue;
158471
+ const info = isRecord(item.info) ? item.info : item;
158472
+ const id = recordString$1(info, "id", "messageId", "messageID") ?? recordString$1(item, "id", "messageId", "messageID");
158473
+ if (!id) continue;
158474
+ byId.set(id, info);
158475
+ ids.push(id);
158476
+ }
158477
+ const latest = ids.at(-1);
158478
+ if (!latest) return void 0;
158479
+ const active = /* @__PURE__ */ new Set();
158480
+ let current = latest;
158481
+ let followedParent = false;
158482
+ while (current && !active.has(current)) {
158483
+ active.add(current);
158484
+ const info = byId.get(current);
158485
+ const parent = info ? recordString$1(info, "parentID", "parentId", "parentMessageId") : void 0;
158486
+ followedParent ||= parent !== void 0;
158487
+ current = parent;
158488
+ }
158489
+ return followedParent || byId.size <= 1 ? active : new Set(ids);
158490
+ }
158491
+ function nonNegativeInteger$1(value) {
158492
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : void 0;
158493
+ }
158494
+ function recordString$1(value, ...keys) {
158495
+ for (const key of keys) {
158496
+ const candidate = asString(value[key])?.trim();
158497
+ if (candidate) return candidate;
158498
+ }
158499
+ }
158500
+ function tokenValue(value, ...keys) {
158501
+ if (!isRecord(value)) return 0;
158502
+ for (const key of keys) {
158503
+ const candidate = nonNegativeInteger$1(value[key]);
158504
+ if (candidate !== void 0) return candidate;
158505
+ }
158506
+ return 0;
158507
+ }
158508
+ function messageTokens(info, parts) {
158509
+ const raw = isRecord(info.tokens) ? info.tokens : void 0;
158510
+ let usage = {
158511
+ input: tokenValue(raw, "input"),
158512
+ read: isRecord(raw?.cache) ? tokenValue(raw.cache, "read") : 0,
158513
+ write: isRecord(raw?.cache) ? tokenValue(raw.cache, "write") : 0
158514
+ };
158515
+ if (usage.input > 0 || usage.read > 0 || usage.write > 0 || !Array.isArray(parts)) return usage;
158516
+ for (let index = parts.length - 1; index >= 0; index -= 1) {
158517
+ const part = parts[index];
158518
+ if (!isRecord(part) || asString(part.type) !== "step-finish" || !isRecord(part.tokens)) continue;
158519
+ const tokens = part.tokens;
158520
+ const candidate = {
158521
+ input: tokenValue(tokens, "input"),
158522
+ read: isRecord(tokens.cache) ? tokenValue(tokens.cache, "read") : 0,
158523
+ write: isRecord(tokens.cache) ? tokenValue(tokens.cache, "write") : 0
158524
+ };
158525
+ if (candidate.input > 0 || candidate.read > 0 || candidate.write > 0) {
158526
+ usage = candidate;
158527
+ break;
158528
+ }
158529
+ }
158530
+ return usage;
158531
+ }
158532
+ function summary(turns) {
158533
+ let requests = 0;
158534
+ let inputTokens = 0;
158535
+ let cacheReadTokens = 0;
158536
+ let cacheWriteTokens = 0;
158537
+ const rates = [];
158538
+ for (const turn of turns) {
158539
+ const input = turn.inputTokens ?? 0;
158540
+ const read = turn.cacheReadTokens ?? 0;
158541
+ const write = turn.cacheWriteTokens ?? 0;
158542
+ if (input <= 0 && read <= 0 && write <= 0) continue;
158543
+ requests += 1;
158544
+ inputTokens += input;
158545
+ cacheReadTokens += read;
158546
+ cacheWriteTokens += write;
158547
+ if (turn.hitRate !== void 0) rates.push(turn.hitRate);
158548
+ }
158549
+ const aggregateRate = inputTokens > 0 ? Math.max(0, Math.min(1, cacheReadTokens / inputTokens)) : void 0;
158550
+ return {
158551
+ requests,
158552
+ inputTokens,
158553
+ cacheReadTokens,
158554
+ cacheWriteTokens,
158555
+ hitRate: aggregateRate,
158556
+ latestHitRate: rates.at(-1),
158557
+ minHitRate: rates.length > 0 ? Math.min(...rates) : void 0,
158558
+ maxHitRate: rates.length > 0 ? Math.max(...rates) : void 0
158559
+ };
158560
+ }
158561
+ /**
158562
+ * Extracts request-level cache usage from raw session messages. Unknown token
158563
+ * records remain in the trend so a runtime restart is rendered as a gap rather
158564
+ * than an invented smooth line.
158565
+ */
158566
+ function extractContextCacheTrend(value, activeMessageIds) {
158567
+ const assistantMessages = (Array.isArray(value) ? value : isRecord(value) && Array.isArray(value.messages) ? value.messages : []).filter((item) => {
158568
+ if (!isRecord(item)) return false;
158569
+ const info = isRecord(item.info) ? item.info : item;
158570
+ return asString(info.role) === "assistant" && !info.summary;
158571
+ });
158572
+ const hasActiveFilter = Boolean(activeMessageIds && activeMessageIds.size > 0);
158573
+ const turns = assistantMessages.map((item, index) => {
158574
+ const info = isRecord(item.info) ? item.info : item;
158575
+ const usage = messageTokens(info, item.parts);
158576
+ const input = usage.input > 0 ? usage.input : void 0;
158577
+ const read = usage.read > 0 ? usage.read : usage.input > 0 ? 0 : void 0;
158578
+ const write = usage.write > 0 ? usage.write : usage.input > 0 ? 0 : void 0;
158579
+ const id = recordString$1(info, "id", "messageId", "messageID") ?? recordString$1(item, "id", "messageId", "messageID");
158580
+ const active = !hasActiveFilter || id !== void 0 && activeMessageIds.has(id);
158581
+ const hitRate = input !== void 0 ? Math.max(0, Math.min(1, usage.read / input)) : void 0;
158582
+ return {
158583
+ index: index + 1,
158584
+ messageId: id,
158585
+ inputTokens: input,
158586
+ cacheReadTokens: read,
158587
+ cacheWriteTokens: write,
158588
+ hitRate,
158589
+ state: input === void 0 ? "unknown" : usage.read > 0 ? "hit" : "miss",
158590
+ active
158591
+ };
158592
+ });
158593
+ return {
158594
+ turns,
158595
+ active: summary(turns.filter((turn) => turn.active)),
158596
+ wholeTree: summary(turns)
158597
+ };
158598
+ }
158599
+ //#endregion
158196
158600
  //#region node_modules/diff/libesm/diff/base.js
158197
158601
  var Diff = class {
158198
158602
  diff(oldStr, newStr, options = {}) {
@@ -161798,7 +162202,10 @@ const contextSources = /* @__PURE__ */ new Set([
161798
162202
  "tool_prompt",
161799
162203
  "system_tool_schemas",
161800
162204
  "mcp_tool_schemas",
161801
- "messages"
162205
+ "messages",
162206
+ "user_messages",
162207
+ "assistant_messages",
162208
+ "tool_io"
161802
162209
  ]);
161803
162210
  function finiteNumber(value) {
161804
162211
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
@@ -162301,49 +162708,6 @@ function skillDescription(candidate) {
162301
162708
  return description ? truncateGraphemes(description, skillDescriptionLimit) : void 0;
162302
162709
  }
162303
162710
  //#endregion
162304
- //#region packages/zcode-tui/src/session-status.ts
162305
- function nonNegativeNumber(value) {
162306
- return typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : void 0;
162307
- }
162308
- function projectionMetrics(value) {
162309
- if (!isRecord(value)) return void 0;
162310
- const metrics = {
162311
- contextUsed: nonNegativeNumber(value.contextUsed),
162312
- contextWindow: nonNegativeNumber(value.contextWindow),
162313
- totalTokens: nonNegativeNumber(value.totalTokenCount),
162314
- turnCount: nonNegativeNumber(value.turnCount)
162315
- };
162316
- return Object.values(metrics).some((metric) => metric !== void 0) ? metrics : void 0;
162317
- }
162318
- function usageMetrics(value) {
162319
- if (!isRecord(value)) return void 0;
162320
- const metrics = {
162321
- totalTokens: nonNegativeNumber(value.totalTokens),
162322
- inputTokens: nonNegativeNumber(value.inputTokens),
162323
- outputTokens: nonNegativeNumber(value.outputTokens),
162324
- reasoningTokens: nonNegativeNumber(value.reasoningTokens),
162325
- cacheCreationTokens: nonNegativeNumber(value.cacheCreationTokens),
162326
- cacheReadTokens: nonNegativeNumber(value.cacheReadTokens),
162327
- modelRequestCount: nonNegativeNumber(value.modelRequestCount),
162328
- modelErrorCount: nonNegativeNumber(value.modelErrorCount)
162329
- };
162330
- return Object.values(metrics).some((metric) => metric !== void 0) ? metrics : void 0;
162331
- }
162332
- function sessionIdFromUsage(value) {
162333
- if (!isRecord(value)) return void 0;
162334
- return (asString(value.sessionId) ?? asString(value.sessionID))?.trim() || void 0;
162335
- }
162336
- function mergeMetrics(current, update) {
162337
- return update ? {
162338
- ...current,
162339
- ...update
162340
- } : current;
162341
- }
162342
- function contextRemainingPercent(metrics) {
162343
- if (metrics.contextUsed === void 0 || !metrics.contextWindow) return void 0;
162344
- return Math.max(0, Math.min(100, Math.round((1 - metrics.contextUsed / metrics.contextWindow) * 100)));
162345
- }
162346
- //#endregion
162347
162711
  //#region packages/zcode-tui/src/shortcuts.ts
162348
162712
  const modes = [
162349
162713
  "build",
@@ -164787,8 +165151,9 @@ var ZCodeTui = class {
164787
165151
  this.editor.onSubmit = (text) => void this.submit(text);
164788
165152
  }
164789
165153
  updateLoginWarning() {
165154
+ const configPath = userConfigPathHint();
164790
165155
  this.loginWarning.setText(this.loginRequired ? this.theme.warning("Model access is not configured.") : "");
164791
- this.loginHelp.setText(this.loginRequired ? this.theme.warning("Run /login, or configure a custom provider in ~/.zcode/cli/config.json.") : "");
165156
+ this.loginHelp.setText(this.loginRequired ? this.theme.warning(`Run /login, or configure a custom provider in ${configPath}.`) : "");
164792
165157
  }
164793
165158
  setLoginRequired(required) {
164794
165159
  const changed = this.loginRequired !== required;
@@ -165458,7 +165823,7 @@ var ZCodeTui = class {
165458
165823
  if (appliesToSetting(settingTarget, "effort") && typeof result.thoughtLevel === "string") this.thoughtLevel = result.thoughtLevel;
165459
165824
  if (Array.isArray(result.modelOptions)) this.modelOptions = [...result.modelOptions];
165460
165825
  if (Array.isArray(result.effortOptions)) this.effortOptions = [...result.effortOptions];
165461
- this.sessionMetrics = mergeMetrics(this.sessionMetrics, projectionMetrics(result.projection));
165826
+ this.sessionMetrics = mergeProjectionMetrics(this.sessionMetrics, projectionMetrics(result.projection), Boolean(this.options.readSessionUsage));
165462
165827
  if (Array.isArray(result.todos)) this.todos = normalizeTodos(result.todos);
165463
165828
  if (Array.isArray(result.todoGroups)) this.todoGroups = normalizeTodoGroups(result);
165464
165829
  this.applyRuntimeProjection(normalizeRuntimeProjection(result));
@@ -166665,7 +167030,8 @@ var ZCodeTui = class {
166665
167030
  }))?.payload;
166666
167031
  if (!command?.command) return;
166667
167032
  if (command.command === customProviderHelpCommand) {
166668
- this.addNotice("Custom providers do not require login. Copy config.example.json to ~/.zcode/cli/config.json, set provider kind, baseURL, apiKey and model IDs, then run /new. See README: Custom provider without login.", "muted");
167033
+ const configPath = userConfigPathHint();
167034
+ this.addNotice(`Custom providers do not require login. Copy config.example.json to ${configPath}, set provider kind, baseURL, apiKey and model IDs, then run /new. See README: Custom provider without login.`, "muted");
166669
167035
  return;
166670
167036
  }
166671
167037
  if (!command.input) {
@@ -167246,17 +167612,54 @@ var ZCodeTui = class {
167246
167612
  }
167247
167613
  }
167248
167614
  async showContextDetails() {
167249
- await Promise.all([this.refreshRuntimeState(), this.refreshSessionUsage()]);
167615
+ const initial = await this.readContextDetailData();
167250
167616
  await this.showChoice({
167251
167617
  title: "Context",
167252
- prompt: "Current runtime context usage and source composition.",
167253
- content: new ContextDetailView(this.theme, this.runtimeProjection?.contextUsage),
167618
+ prompt: "Context pressure, cache health, and prompt composition. Exact cache tokens are kept separate from estimates.",
167619
+ content: new ContextDetailView(this.theme, initial.usage, initial.trend, () => this.readContextDetailData(), () => this.ui.requestRender()),
167254
167620
  items: [{
167255
167621
  value: "close",
167256
167622
  label: "Close"
167257
167623
  }]
167258
167624
  });
167259
167625
  }
167626
+ async readContextDetailData() {
167627
+ await Promise.all([this.refreshRuntimeState(), this.refreshSessionUsage()]);
167628
+ let usage = this.runtimeProjection?.contextUsage;
167629
+ let trend;
167630
+ let transcript;
167631
+ if (this.options.loadSessionTranscript) try {
167632
+ transcript = await this.options.loadSessionTranscript();
167633
+ } catch {}
167634
+ if (this.options.loadSessionContextMessages) try {
167635
+ const rawContextMessages = await this.options.loadSessionContextMessages();
167636
+ const activeIds = new Set(restoredMessages(transcript).flatMap((message) => message.messageId ? [message.messageId] : []));
167637
+ trend = extractContextCacheTrend(rawContextMessages, activeIds.size > 0 ? activeIds : findActiveBranchMessageIds(rawContextMessages));
167638
+ if (usage && trend) usage = {
167639
+ ...usage,
167640
+ cache: {
167641
+ ...usage.cache,
167642
+ latestHitRate: usage.cache?.latestHitRate ?? trend.wholeTree.latestHitRate,
167643
+ hitRate: trend.wholeTree.hitRate ?? usage.cache?.hitRate,
167644
+ hitRateRequestCount: trend.wholeTree.requests,
167645
+ totalInputTokens: trend.wholeTree.inputTokens,
167646
+ totalCacheReadTokens: trend.wholeTree.cacheReadTokens,
167647
+ totalCacheWriteTokens: trend.wholeTree.cacheWriteTokens
167648
+ }
167649
+ };
167650
+ } catch {}
167651
+ if (usage && usage.breakdown.length === 0 && transcript !== void 0) {
167652
+ const breakdown = estimateTranscriptContextBreakdown(transcript);
167653
+ if (breakdown.length > 0) usage = {
167654
+ ...usage,
167655
+ breakdown
167656
+ };
167657
+ }
167658
+ return {
167659
+ usage,
167660
+ trend
167661
+ };
167662
+ }
167260
167663
  async showStatusDetails() {
167261
167664
  await Promise.all([
167262
167665
  this.refreshRuntimeState(),
@@ -167674,11 +168077,28 @@ var ZCodeTui = class {
167674
168077
  priority: 90
167675
168078
  });
167676
168079
  }
168080
+ const runtimeCache = this.runtimeProjection?.contextUsage?.cache;
168081
+ const runtimeCacheRate = runtimeCache?.latestHitRate ?? runtimeCache?.hitRate;
168082
+ const sessionInputTokens = this.sessionMetrics.inputTokens;
168083
+ const sessionCacheReadTokens = this.sessionMetrics.cacheReadTokens;
168084
+ const sessionCacheRate = sessionInputTokens !== void 0 && sessionInputTokens > 0 && sessionCacheReadTokens !== void 0 ? sessionCacheReadTokens / sessionInputTokens : void 0;
168085
+ const useSessionFallback = !this.options.readRuntimeProjection;
168086
+ const cacheRateValue = runtimeCacheRate ?? (useSessionFallback ? sessionCacheRate : void 0);
168087
+ const hasCacheRequests = (runtimeCache?.hitRateRequestCount ?? 0) > 0 || runtimeCacheRate !== void 0 && runtimeCacheRate !== null || useSessionFallback && sessionCacheRate !== void 0;
168088
+ if (cacheRateValue !== void 0 && hasCacheRequests) {
168089
+ const cacheRate = Math.max(0, Math.min(100, Math.round(cacheRateValue * 100)));
168090
+ const style = cacheRate < 50 ? this.theme.warning : this.theme.muted;
168091
+ fields.push({
168092
+ text: style(`cache ${cacheRate}% hit`),
168093
+ compactText: style(`cache ${cacheRate}%`),
168094
+ priority: 85
168095
+ });
168096
+ }
167677
168097
  if (this.sessionMetrics.totalTokens !== void 0) {
167678
168098
  const tokens = formatTokens(this.sessionMetrics.totalTokens);
167679
168099
  fields.push({
167680
- text: this.theme.muted(`${tokens} tokens`),
167681
- compactText: this.theme.muted(`${tokens} tok`),
168100
+ text: this.theme.muted(`session ${tokens} tokens`),
168101
+ compactText: this.theme.muted(`session ${tokens}`),
167682
168102
  priority: 20
167683
168103
  });
167684
168104
  }
@@ -167759,12 +168179,12 @@ var ZCodeTui = class {
167759
168179
  this.runtimeProjection = projection;
167760
168180
  this.reconcileTurnTiming(projection);
167761
168181
  if (projection.sessionId) this.sessionId = projection.sessionId;
167762
- this.sessionMetrics = mergeMetrics(this.sessionMetrics, {
168182
+ this.sessionMetrics = mergeProjectionMetrics(this.sessionMetrics, {
167763
168183
  contextUsed: projection.contextUsage?.used,
167764
168184
  contextWindow: projection.contextUsage?.size,
167765
168185
  totalTokens: projection.totalTokenCount,
167766
168186
  turnCount: projection.turnCount
167767
- });
168187
+ }, Boolean(this.options.readSessionUsage));
167768
168188
  this.updateRuntimeActivity(false);
167769
168189
  }
167770
168190
  updateRuntimeActivity(requestRender = true) {