zcode-app-cli 3.7.6-12 → 3.7.7-13

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.
@@ -21,13 +21,15 @@ var config_example_default = {
21
21
  },
22
22
  "headers": {},
23
23
  "models": {
24
+ "glm-5.3": { "name": "GLM-5.3" },
24
25
  "glm-5.2": { "name": "GLM-5.2" },
25
- "glm-5.1": { "name": "GLM-5.1" }
26
+ "glm-5.1": { "name": "GLM-5.1" },
27
+ "glm-5-turbo": { "name": "GLM-5-Turbo" }
26
28
  }
27
29
  } },
28
30
  model: {
29
31
  "main": "zai/glm-5.2",
30
- "lite": "zai/glm-5.1"
32
+ "lite": "zai/glm-5-turbo"
31
33
  },
32
34
  modelCatalog: { "overrides": {} },
33
35
  modelStream: { "idleTimeoutMs": 6e4 },
@@ -157285,6 +157287,7 @@ var ChoiceDialog = class {
157285
157287
  this.contentExpanded = !this.contentExpanded;
157286
157288
  return;
157287
157289
  }
157290
+ if ((this.content?.handleInput)?.call(this.content, data) === true) return;
157288
157291
  if (this.contentExpanded) {
157289
157292
  if (matchesKey(data, "escape")) {
157290
157293
  this.contentExpanded = false;
@@ -158058,7 +158061,8 @@ function normalizeGoal(value) {
158058
158061
  function formatTokens(value) {
158059
158062
  if (value < 1e3) return Math.floor(value).toString();
158060
158063
  if (value < 1e6) return `${Number((value / 1e3).toFixed(1))}K`;
158061
- return `${Number((value / 1e6).toFixed(1))}M`;
158064
+ if (value < 1e9) return `${Number((value / 1e6).toFixed(1))}M`;
158065
+ return `${Number((value / 1e9).toFixed(1))}G`;
158062
158066
  }
158063
158067
  function formatGoalElapsed(totalSeconds) {
158064
158068
  const seconds = Math.max(0, Math.floor(totalSeconds));
@@ -158094,65 +158098,203 @@ const contextLabels = {
158094
158098
  tool_prompt: "Tool prompts",
158095
158099
  system_tool_schemas: "System tool schemas",
158096
158100
  mcp_tool_schemas: "MCP tool schemas",
158097
- messages: "Messages"
158101
+ messages: "Messages",
158102
+ user_messages: "User messages",
158103
+ assistant_messages: "Assistant messages",
158104
+ tool_io: "Tool input/output"
158098
158105
  };
158099
158106
  function contextStyle(source, theme) {
158100
- if (source === "messages") return theme.accent;
158101
- if (source === "skills" || source === "mcp_tool_schemas") return theme.success;
158102
- if (source === "system_prompt" || source === "system_tool_schemas") return theme.warning;
158107
+ if (source === "messages" || source === "assistant_messages") return theme.accent;
158108
+ if (source === "user_messages" || source === "skills" || source === "mcp_tool_schemas") return theme.success;
158109
+ if (source === "tool_io" || source === "system_prompt" || source === "system_tool_schemas") return theme.warning;
158103
158110
  return theme.muted;
158104
158111
  }
158105
158112
  function percent(value, total) {
158106
158113
  return total > 0 ? `${(value / total * 100).toFixed(1)}%` : "0%";
158107
158114
  }
158115
+ function rate(value) {
158116
+ return value === void 0 ? "—" : `${Math.round(value * 100)}%`;
158117
+ }
158118
+ function summaryLine(label, summary, theme) {
158119
+ const tokens = `${formatTokens(summary.inputTokens)} input · ${formatTokens(summary.cacheReadTokens)} read · ${formatTokens(summary.cacheWriteTokens)} write`;
158120
+ return `${theme.bold(label)} ${rate(summary.hitRate)} hit · ${summary.requests} requests · ${theme.muted(tokens)}`;
158121
+ }
158122
+ function turnMarker(turn, theme) {
158123
+ if (turn.state === "unknown") return theme.muted("?");
158124
+ if (turn.state === "hit") return theme.success("█");
158125
+ return theme.warning("░");
158126
+ }
158127
+ function trendGraph(turns, width, theme) {
158128
+ const points = turns.slice(-Math.max(1, Math.min(80, width - 8)));
158129
+ if (points.length === 0) return [theme.muted("No request-level cache data yet.")];
158130
+ const height = 4;
158131
+ const columns = Array.from({ length: height }, () => "");
158132
+ for (let row = height; row >= 1; row -= 1) columns[height - row] = points.map((turn) => {
158133
+ if (turn.state === "unknown") return " ";
158134
+ return Math.max(0, Math.min(height, Math.round((turn.hitRate ?? 0) * height))) >= row ? turnMarker(turn, theme) : " ";
158135
+ }).join("");
158136
+ const labels = points.map((turn) => turn.state === "unknown" ? " " : "·").join("");
158137
+ return [
158138
+ `${theme.muted("100% ")} ${columns[0]}`,
158139
+ `${theme.muted(" 75% ")} ${columns[1]}`,
158140
+ `${theme.muted(" 50% ")} ${columns[2]}`,
158141
+ `${theme.muted(" 25% ")} ${columns[3]}`,
158142
+ `${theme.muted(" 0% ")} ${labels}`,
158143
+ theme.muted("█ cache hit · ░ uncached request · blank gap = unavailable")
158144
+ ];
158145
+ }
158146
+ function recentTurnLine(turn, theme) {
158147
+ const id = turn.messageId ? turn.messageId.slice(-8) : "unknown";
158148
+ const usage = turn.inputTokens === void 0 ? "cache data unavailable" : `${rate(turn.hitRate)} hit · ${formatTokens(turn.inputTokens)} input · ${formatTokens(turn.cacheReadTokens ?? 0)} read`;
158149
+ return `${turnMarker(turn, theme)} ${String(turn.index).padStart(3, " ")} ${theme.muted(id)} ${usage}`;
158150
+ }
158108
158151
  var ContextDetailView = class {
158109
158152
  theme;
158153
+ refresh;
158154
+ requestRender;
158110
158155
  usage;
158111
- constructor(theme, usage) {
158156
+ trend;
158157
+ page = "overview";
158158
+ refreshing = false;
158159
+ constructor(theme, usage, trend, refresh, requestRender) {
158112
158160
  this.theme = theme;
158161
+ this.refresh = refresh;
158162
+ this.requestRender = requestRender;
158113
158163
  this.usage = usage;
158164
+ this.trend = trend;
158114
158165
  }
158115
158166
  invalidate() {}
158167
+ setData(usage, trend) {
158168
+ this.usage = usage;
158169
+ this.trend = trend;
158170
+ }
158171
+ handleInput(data) {
158172
+ const key = data.length === 1 ? data.toLowerCase() : data;
158173
+ if (key === "1" || key === "2" || key === "3" || key === "v") {
158174
+ const pages = [
158175
+ "overview",
158176
+ "trend",
158177
+ "composition"
158178
+ ];
158179
+ this.page = key === "v" ? pages[(pages.indexOf(this.page) + 1) % pages.length] : pages[Number(key) - 1];
158180
+ this.requestRender?.();
158181
+ return true;
158182
+ }
158183
+ if (key !== "r" || !this.refresh || this.refreshing) return false;
158184
+ this.refreshing = true;
158185
+ this.requestRender?.();
158186
+ this.refresh().then((data) => {
158187
+ this.setData(data.usage, data.trend);
158188
+ }).catch(() => {}).finally(() => {
158189
+ this.refreshing = false;
158190
+ this.requestRender?.();
158191
+ });
158192
+ return true;
158193
+ }
158116
158194
  render(width) {
158195
+ if (this.page === "trend") return this.renderTrend(width);
158196
+ if (this.page === "composition") return this.renderComposition(width);
158197
+ return this.renderOverview(width);
158198
+ }
158199
+ renderOverview(width) {
158117
158200
  if (!this.usage) return [this.theme.muted("Context usage is unavailable in this runtime.")];
158201
+ const safeWidth = Math.max(1, width);
158118
158202
  const totalChars = this.usage.breakdown.reduce((total, item) => total + item.chars, 0);
158119
- const barWidth = Math.max(8, Math.min(40, width - 2));
158203
+ const barWidth = Math.max(8, Math.min(40, safeWidth - 2));
158120
158204
  const bar = this.usage.breakdown.map((item) => {
158121
158205
  const columns = totalChars > 0 ? Math.max(1, Math.round(item.chars / totalChars * barWidth)) : 0;
158122
158206
  return contextStyle(item.source, this.theme)("█".repeat(columns));
158123
158207
  }).join("");
158208
+ const usedPercent = Math.max(0, Math.round(this.usage.used / this.usage.size * 100));
158209
+ const remaining = Math.max(0, this.usage.size - this.usage.used);
158210
+ const usageStyle = usedPercent >= 90 ? this.theme.error : usedPercent >= 70 ? this.theme.warning : (text) => text;
158211
+ const lines = [this.theme.bold("Context overview"), usageStyle(`${formatTokens(this.usage.used)} / ${formatTokens(this.usage.size)} tokens · ${usedPercent}% used · ${formatTokens(remaining)} remaining`)];
158212
+ if (this.refreshing) lines.push(this.theme.muted("Refreshing context data…"));
158213
+ if (this.trend) {
158214
+ 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"));
158215
+ lines.push(...this.trend.turns.slice(-8).map((turn) => recentTurnLine(turn, this.theme)));
158216
+ if (this.trend.turns.some((turn) => turn.state === "unknown")) lines.push(this.theme.muted("Request-level token data is unavailable; gaps are intentional."));
158217
+ }
158218
+ if (totalChars > 0) {
158219
+ lines.push("", this.theme.bold("Estimated prompt composition by characters"), truncateToWidth(bar, safeWidth));
158220
+ for (const item of this.usage.breakdown.slice().sort((left, right) => right.chars - left.chars)) {
158221
+ const label = contextLabels[item.source];
158222
+ const value = `${item.chars.toLocaleString()} chars · ${percent(item.chars, totalChars)}`;
158223
+ const available = Math.max(1, safeWidth - visibleWidth(value) - 3);
158224
+ lines.push(`${contextStyle(item.source, this.theme)("●")} ${truncateToWidth(label, available)} ${this.theme.muted(value)}`);
158225
+ }
158226
+ } else lines.push("", this.theme.muted("Prompt source composition is unavailable for this turn."));
158124
158227
  const cache = this.usage.cache;
158125
- const cacheHitRate = cache?.latestHitRate ?? cache?.hitRate;
158228
+ if (cache) {
158229
+ lines.push("", this.theme.bold("Session cache totals"));
158230
+ const latest = [
158231
+ cache.latestHitRate !== void 0 && cache.latestHitRate !== null ? `${Math.round(cache.latestHitRate * 100)}% hit` : void 0,
158232
+ cache.cacheReadTokens !== void 0 ? `${formatTokens(cache.cacheReadTokens)} read` : void 0,
158233
+ cache.cacheWriteTokens !== void 0 ? `${formatTokens(cache.cacheWriteTokens)} written` : void 0,
158234
+ cache.inputTokens !== void 0 ? `${formatTokens(cache.inputTokens)} input` : void 0
158235
+ ].filter(Boolean);
158236
+ if (latest.length > 0) {
158237
+ const latestLabel = cache.latestHitRate !== void 0 && cache.latestHitRate !== null ? `${Math.round(cache.latestHitRate * 100)}% hit rate` : latest.join(" · ");
158238
+ lines.push(this.theme.muted(`Latest request ${latestLabel}${latest.length > 1 ? ` · ${latest.slice(1).join(" · ")}` : ""}`));
158239
+ }
158240
+ const aggregateTokens = [
158241
+ cache.totalCacheReadTokens !== void 0 ? `${formatTokens(cache.totalCacheReadTokens)} read` : void 0,
158242
+ cache.totalCacheWriteTokens !== void 0 ? `${formatTokens(cache.totalCacheWriteTokens)} written` : void 0,
158243
+ cache.totalInputTokens !== void 0 ? `${formatTokens(cache.totalInputTokens)} input` : void 0
158244
+ ].filter(Boolean);
158245
+ if (aggregateTokens.length > 0) lines.push(this.theme.muted(`Session tokens ${aggregateTokens.join(" · ")}`));
158246
+ 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`));
158247
+ }
158248
+ if (this.usage.cost) lines.push(this.theme.muted(`Cost: ${this.usage.cost.amount} ${this.usage.cost.currency}`));
158249
+ lines.push("", this.theme.muted("1 overview · 2 cache trend · 3 composition · v cycle · r refresh"));
158250
+ return lines.map((line) => truncateToWidth(line, safeWidth));
158251
+ }
158252
+ renderTrend(width) {
158253
+ const safeWidth = Math.max(1, width);
158254
+ if (!this.trend) return [
158255
+ this.theme.bold("Cache trend"),
158256
+ this.theme.muted("Per-turn cache data is unavailable in this runtime."),
158257
+ this.theme.muted("1 overview · 3 composition · r refresh")
158258
+ ];
158126
158259
  const lines = [
158127
- this.theme.bold("Context Usage"),
158128
- `${formatTokens(this.usage.used)} / ${formatTokens(this.usage.size)} tokens · ${Math.round(this.usage.used / this.usage.size * 100)}% used`,
158129
- truncateToWidth(bar, width),
158260
+ this.theme.bold("Context cache · per request"),
158261
+ summaryLine("Active branch", this.trend.active, this.theme),
158262
+ summaryLine("Whole tree", this.trend.wholeTree, this.theme),
158263
+ 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`),
158130
158264
  "",
158131
- this.theme.muted("Estimated prompt composition by characters")
158265
+ ...trendGraph(this.trend.turns, safeWidth, this.theme),
158266
+ this.theme.muted("Misses and gaps are kept; runtime restarts are not smoothed."),
158267
+ "",
158268
+ this.theme.bold("Recent 8 requests"),
158269
+ ...this.trend.turns.slice(-8).map((turn) => recentTurnLine(turn, this.theme)),
158270
+ this.theme.muted("1 overview · 2 cache trend · 3 composition · v cycle · r refresh")
158132
158271
  ];
158272
+ 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."));
158273
+ return lines.map((line) => truncateToWidth(line, safeWidth));
158274
+ }
158275
+ renderComposition(width) {
158276
+ const safeWidth = Math.max(1, width);
158277
+ if (!this.usage) return [this.theme.muted("Prompt composition is unavailable in this runtime.")];
158278
+ const totalChars = this.usage.breakdown.reduce((total, item) => total + item.chars, 0);
158279
+ if (totalChars <= 0) return [
158280
+ this.theme.bold("Estimated prompt composition by characters"),
158281
+ this.theme.muted("Prompt source composition is unavailable for this turn."),
158282
+ this.theme.muted("1 overview · 2 cache trend · v cycle · r refresh")
158283
+ ];
158284
+ const barWidth = Math.max(8, Math.min(40, safeWidth - 2));
158285
+ const bar = this.usage.breakdown.map((item) => {
158286
+ const columns = Math.max(1, Math.round(item.chars / totalChars * barWidth));
158287
+ return contextStyle(item.source, this.theme)("█".repeat(columns));
158288
+ }).join("");
158289
+ const lines = [this.theme.bold("Estimated prompt composition by characters"), truncateToWidth(bar, safeWidth)];
158133
158290
  for (const item of this.usage.breakdown.slice().sort((left, right) => right.chars - left.chars)) {
158134
158291
  const label = contextLabels[item.source];
158135
158292
  const value = `${item.chars.toLocaleString()} chars · ${percent(item.chars, totalChars)}`;
158136
- const available = Math.max(1, width - visibleWidth(value) - 3);
158293
+ const available = Math.max(1, safeWidth - visibleWidth(value) - 3);
158137
158294
  lines.push(`${contextStyle(item.source, this.theme)("●")} ${truncateToWidth(label, available)} ${this.theme.muted(value)}`);
158138
158295
  }
158139
- if (cache) {
158140
- lines.push("", this.theme.bold("Prompt cache"));
158141
- lines.push(this.theme.muted([
158142
- cacheHitRate !== void 0 && cacheHitRate !== null ? `${Math.round(cacheHitRate * 100)}% hit rate` : void 0,
158143
- cache.cacheReadTokens !== void 0 ? `${formatTokens(cache.cacheReadTokens)} read` : void 0,
158144
- cache.cacheWriteTokens !== void 0 ? `${formatTokens(cache.cacheWriteTokens)} written` : void 0,
158145
- cache.inputTokens !== void 0 ? `${formatTokens(cache.inputTokens)} input` : void 0
158146
- ].filter(Boolean).join(" · ")));
158147
- if (cache.totalInputTokens !== void 0 || cache.hitRateRequestCount !== void 0) lines.push(this.theme.muted([
158148
- cache.hitRateRequestCount !== void 0 ? `${cache.hitRateRequestCount} requests` : void 0,
158149
- cache.totalInputTokens !== void 0 ? `${formatTokens(cache.totalInputTokens)} total input` : void 0,
158150
- cache.totalCacheReadTokens !== void 0 ? `${formatTokens(cache.totalCacheReadTokens)} total read` : void 0,
158151
- cache.totalCacheWriteTokens !== void 0 ? `${formatTokens(cache.totalCacheWriteTokens)} total written` : void 0
158152
- ].filter(Boolean).join(" · ")));
158153
- }
158154
- if (this.usage.cost) lines.push(this.theme.muted(`Cost: ${this.usage.cost.amount} ${this.usage.cost.currency}`));
158155
- return lines.map((line) => truncateToWidth(line, Math.max(1, width)));
158296
+ 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"));
158297
+ return lines.map((line) => truncateToWidth(line, safeWidth));
158156
158298
  }
158157
158299
  };
158158
158300
  var StatusDetailView = class {
@@ -158192,6 +158334,209 @@ var StatusDetailView = class {
158192
158334
  }
158193
158335
  };
158194
158336
  //#endregion
158337
+ //#region packages/zcode-tui/src/context-breakdown.ts
158338
+ function valueLength(value) {
158339
+ const text = asString(value);
158340
+ if (text !== void 0) return text.length;
158341
+ if (value === void 0 || value === null) return 0;
158342
+ try {
158343
+ return JSON.stringify(value).length;
158344
+ } catch {
158345
+ return 0;
158346
+ }
158347
+ }
158348
+ function assistantPartLength(value) {
158349
+ if (!isRecord(value)) return {
158350
+ assistant: 0,
158351
+ tool: 0
158352
+ };
158353
+ const type = asString(value.type);
158354
+ if (type === "thought" || type === "reasoning") return {
158355
+ assistant: valueLength(value.text),
158356
+ tool: 0
158357
+ };
158358
+ if (type !== "tool") return {
158359
+ assistant: 0,
158360
+ tool: 0
158361
+ };
158362
+ return {
158363
+ assistant: 0,
158364
+ tool: valueLength(value.input) + valueLength(value.output) + valueLength(value.error)
158365
+ };
158366
+ }
158367
+ function estimateTranscriptContextBreakdown(value) {
158368
+ const messages = Array.isArray(value) ? value : isRecord(value) && Array.isArray(value.messages) ? value.messages : [];
158369
+ let userChars = 0;
158370
+ let assistantChars = 0;
158371
+ let toolChars = 0;
158372
+ for (const message of messages) {
158373
+ if (!isRecord(message)) continue;
158374
+ const role = asString(message.role);
158375
+ if (role === "user") {
158376
+ userChars += valueLength(message.content);
158377
+ continue;
158378
+ }
158379
+ if (role !== "agent" && role !== "assistant") continue;
158380
+ assistantChars += valueLength(message.content);
158381
+ const parts = Array.isArray(message.parts) ? message.parts : [];
158382
+ for (const part of parts) {
158383
+ const lengths = assistantPartLength(part);
158384
+ assistantChars += lengths.assistant;
158385
+ toolChars += lengths.tool;
158386
+ }
158387
+ }
158388
+ return [
158389
+ {
158390
+ source: "user_messages",
158391
+ chars: userChars
158392
+ },
158393
+ {
158394
+ source: "assistant_messages",
158395
+ chars: assistantChars
158396
+ },
158397
+ {
158398
+ source: "tool_io",
158399
+ chars: toolChars
158400
+ }
158401
+ ].filter((item) => item.chars > 0);
158402
+ }
158403
+ //#endregion
158404
+ //#region packages/zcode-tui/src/context-cache.ts
158405
+ function findActiveBranchMessageIds(value) {
158406
+ const messages = Array.isArray(value) ? value : isRecord(value) && Array.isArray(value.messages) ? value.messages : [];
158407
+ const byId = /* @__PURE__ */ new Map();
158408
+ const ids = [];
158409
+ for (const item of messages) {
158410
+ if (!isRecord(item)) continue;
158411
+ const info = isRecord(item.info) ? item.info : item;
158412
+ const id = recordString$1(info, "id", "messageId", "messageID") ?? recordString$1(item, "id", "messageId", "messageID");
158413
+ if (!id) continue;
158414
+ byId.set(id, info);
158415
+ ids.push(id);
158416
+ }
158417
+ const latest = ids.at(-1);
158418
+ if (!latest) return void 0;
158419
+ const active = /* @__PURE__ */ new Set();
158420
+ let current = latest;
158421
+ let followedParent = false;
158422
+ while (current && !active.has(current)) {
158423
+ active.add(current);
158424
+ const info = byId.get(current);
158425
+ const parent = info ? recordString$1(info, "parentID", "parentId", "parentMessageId") : void 0;
158426
+ followedParent ||= parent !== void 0;
158427
+ current = parent;
158428
+ }
158429
+ return followedParent || byId.size <= 1 ? active : new Set(ids);
158430
+ }
158431
+ function nonNegativeInteger$1(value) {
158432
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : void 0;
158433
+ }
158434
+ function recordString$1(value, ...keys) {
158435
+ for (const key of keys) {
158436
+ const candidate = asString(value[key])?.trim();
158437
+ if (candidate) return candidate;
158438
+ }
158439
+ }
158440
+ function tokenValue(value, ...keys) {
158441
+ if (!isRecord(value)) return 0;
158442
+ for (const key of keys) {
158443
+ const candidate = nonNegativeInteger$1(value[key]);
158444
+ if (candidate !== void 0) return candidate;
158445
+ }
158446
+ return 0;
158447
+ }
158448
+ function messageTokens(info, parts) {
158449
+ const raw = isRecord(info.tokens) ? info.tokens : void 0;
158450
+ let usage = {
158451
+ input: tokenValue(raw, "input"),
158452
+ read: isRecord(raw?.cache) ? tokenValue(raw.cache, "read") : 0,
158453
+ write: isRecord(raw?.cache) ? tokenValue(raw.cache, "write") : 0
158454
+ };
158455
+ if (usage.input > 0 || usage.read > 0 || usage.write > 0 || !Array.isArray(parts)) return usage;
158456
+ for (let index = parts.length - 1; index >= 0; index -= 1) {
158457
+ const part = parts[index];
158458
+ if (!isRecord(part) || asString(part.type) !== "step-finish" || !isRecord(part.tokens)) continue;
158459
+ const tokens = part.tokens;
158460
+ const candidate = {
158461
+ input: tokenValue(tokens, "input"),
158462
+ read: isRecord(tokens.cache) ? tokenValue(tokens.cache, "read") : 0,
158463
+ write: isRecord(tokens.cache) ? tokenValue(tokens.cache, "write") : 0
158464
+ };
158465
+ if (candidate.input > 0 || candidate.read > 0 || candidate.write > 0) {
158466
+ usage = candidate;
158467
+ break;
158468
+ }
158469
+ }
158470
+ return usage;
158471
+ }
158472
+ function summary(turns) {
158473
+ let requests = 0;
158474
+ let inputTokens = 0;
158475
+ let cacheReadTokens = 0;
158476
+ let cacheWriteTokens = 0;
158477
+ const rates = [];
158478
+ for (const turn of turns) {
158479
+ const input = turn.inputTokens ?? 0;
158480
+ const read = turn.cacheReadTokens ?? 0;
158481
+ const write = turn.cacheWriteTokens ?? 0;
158482
+ if (input <= 0 && read <= 0 && write <= 0) continue;
158483
+ requests += 1;
158484
+ inputTokens += input;
158485
+ cacheReadTokens += read;
158486
+ cacheWriteTokens += write;
158487
+ if (turn.hitRate !== void 0) rates.push(turn.hitRate);
158488
+ }
158489
+ const aggregateRate = inputTokens > 0 ? Math.max(0, Math.min(1, cacheReadTokens / inputTokens)) : void 0;
158490
+ return {
158491
+ requests,
158492
+ inputTokens,
158493
+ cacheReadTokens,
158494
+ cacheWriteTokens,
158495
+ hitRate: aggregateRate,
158496
+ latestHitRate: rates.at(-1),
158497
+ minHitRate: rates.length > 0 ? Math.min(...rates) : void 0,
158498
+ maxHitRate: rates.length > 0 ? Math.max(...rates) : void 0
158499
+ };
158500
+ }
158501
+ /**
158502
+ * Extracts request-level cache usage from raw session messages. Unknown token
158503
+ * records remain in the trend so a runtime restart is rendered as a gap rather
158504
+ * than an invented smooth line.
158505
+ */
158506
+ function extractContextCacheTrend(value, activeMessageIds) {
158507
+ const assistantMessages = (Array.isArray(value) ? value : isRecord(value) && Array.isArray(value.messages) ? value.messages : []).filter((item) => {
158508
+ if (!isRecord(item)) return false;
158509
+ const info = isRecord(item.info) ? item.info : item;
158510
+ return asString(info.role) === "assistant" && !info.summary;
158511
+ });
158512
+ const hasActiveFilter = Boolean(activeMessageIds && activeMessageIds.size > 0);
158513
+ const turns = assistantMessages.map((item, index) => {
158514
+ const info = isRecord(item.info) ? item.info : item;
158515
+ const usage = messageTokens(info, item.parts);
158516
+ const input = usage.input > 0 ? usage.input : void 0;
158517
+ const read = usage.read > 0 ? usage.read : usage.input > 0 ? 0 : void 0;
158518
+ const write = usage.write > 0 ? usage.write : usage.input > 0 ? 0 : void 0;
158519
+ const id = recordString$1(info, "id", "messageId", "messageID") ?? recordString$1(item, "id", "messageId", "messageID");
158520
+ const active = !hasActiveFilter || id !== void 0 && activeMessageIds.has(id);
158521
+ const hitRate = input !== void 0 ? Math.max(0, Math.min(1, usage.read / input)) : void 0;
158522
+ return {
158523
+ index: index + 1,
158524
+ messageId: id,
158525
+ inputTokens: input,
158526
+ cacheReadTokens: read,
158527
+ cacheWriteTokens: write,
158528
+ hitRate,
158529
+ state: input === void 0 ? "unknown" : usage.read > 0 ? "hit" : "miss",
158530
+ active
158531
+ };
158532
+ });
158533
+ return {
158534
+ turns,
158535
+ active: summary(turns.filter((turn) => turn.active)),
158536
+ wholeTree: summary(turns)
158537
+ };
158538
+ }
158539
+ //#endregion
158195
158540
  //#region node_modules/diff/libesm/diff/base.js
158196
158541
  var Diff = class {
158197
158542
  diff(oldStr, newStr, options = {}) {
@@ -161797,7 +162142,10 @@ const contextSources = /* @__PURE__ */ new Set([
161797
162142
  "tool_prompt",
161798
162143
  "system_tool_schemas",
161799
162144
  "mcp_tool_schemas",
161800
- "messages"
162145
+ "messages",
162146
+ "user_messages",
162147
+ "assistant_messages",
162148
+ "tool_io"
161801
162149
  ]);
161802
162150
  function finiteNumber(value) {
161803
162151
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
@@ -164443,6 +164791,7 @@ const toolLifecycleEventKinds = /* @__PURE__ */ new Set([
164443
164791
  "error",
164444
164792
  "closed"
164445
164793
  ]);
164794
+ const runtimeCommandSummaries = /* @__PURE__ */ new Map([["login", "Sign in with Z.AI/BigModel OAuth or a Coding Plan API key (`/login` opens a method picker)"], ["new", "Start a fresh session (alias: /clear)"]]);
164446
164795
  const terminalThemeQueryTimeoutMs = 100;
164447
164796
  const exitUsageQueryTimeoutMs = 250;
164448
164797
  const updateAvailableBlockId = "update_available";
@@ -164884,14 +165233,14 @@ var ZCodeTui = class {
164884
165233
  if (!name) continue;
164885
165234
  commands.push({
164886
165235
  name,
164887
- description: command.description ?? command.summary,
165236
+ description: command.description ?? runtimeCommandSummaries.get(name) ?? command.summary,
164888
165237
  argumentHint: command.argumentHint ?? command.inputHint ?? command.usage
164889
165238
  });
164890
165239
  }
164891
165240
  for (const command of [
164892
165241
  {
164893
- name: "clear",
164894
- description: "Clear the visible transcript"
165242
+ name: "cls",
165243
+ description: "Clear the visible transcript (the runtime's /clear starts a new session)"
164895
165244
  },
164896
165245
  {
164897
165246
  name: "copy",
@@ -165087,7 +165436,7 @@ var ZCodeTui = class {
165087
165436
  this.stop();
165088
165437
  return;
165089
165438
  }
165090
- if (input === "/clear") {
165439
+ if (input === "/cls") {
165091
165440
  this.clearTranscriptProjection();
165092
165441
  this.workflowView = void 0;
165093
165442
  this.ui.requestRender(true);
@@ -167244,17 +167593,54 @@ var ZCodeTui = class {
167244
167593
  }
167245
167594
  }
167246
167595
  async showContextDetails() {
167247
- await Promise.all([this.refreshRuntimeState(), this.refreshSessionUsage()]);
167596
+ const initial = await this.readContextDetailData();
167248
167597
  await this.showChoice({
167249
167598
  title: "Context",
167250
- prompt: "Current runtime context usage and source composition.",
167251
- content: new ContextDetailView(this.theme, this.runtimeProjection?.contextUsage),
167599
+ prompt: "Context pressure, cache health, and prompt composition. Exact cache tokens are kept separate from estimates.",
167600
+ content: new ContextDetailView(this.theme, initial.usage, initial.trend, () => this.readContextDetailData(), () => this.ui.requestRender()),
167252
167601
  items: [{
167253
167602
  value: "close",
167254
167603
  label: "Close"
167255
167604
  }]
167256
167605
  });
167257
167606
  }
167607
+ async readContextDetailData() {
167608
+ await Promise.all([this.refreshRuntimeState(), this.refreshSessionUsage()]);
167609
+ let usage = this.runtimeProjection?.contextUsage;
167610
+ let trend;
167611
+ let transcript;
167612
+ if (this.options.loadSessionTranscript) try {
167613
+ transcript = await this.options.loadSessionTranscript();
167614
+ } catch {}
167615
+ if (this.options.loadSessionContextMessages) try {
167616
+ const rawContextMessages = await this.options.loadSessionContextMessages();
167617
+ const activeIds = new Set(restoredMessages(transcript).flatMap((message) => message.messageId ? [message.messageId] : []));
167618
+ trend = extractContextCacheTrend(rawContextMessages, activeIds.size > 0 ? activeIds : findActiveBranchMessageIds(rawContextMessages));
167619
+ if (usage && trend) usage = {
167620
+ ...usage,
167621
+ cache: {
167622
+ ...usage.cache,
167623
+ latestHitRate: usage.cache?.latestHitRate ?? trend.wholeTree.latestHitRate,
167624
+ hitRate: trend.wholeTree.hitRate ?? usage.cache?.hitRate,
167625
+ hitRateRequestCount: trend.wholeTree.requests,
167626
+ totalInputTokens: trend.wholeTree.inputTokens,
167627
+ totalCacheReadTokens: trend.wholeTree.cacheReadTokens,
167628
+ totalCacheWriteTokens: trend.wholeTree.cacheWriteTokens
167629
+ }
167630
+ };
167631
+ } catch {}
167632
+ if (usage && usage.breakdown.length === 0 && transcript !== void 0) {
167633
+ const breakdown = estimateTranscriptContextBreakdown(transcript);
167634
+ if (breakdown.length > 0) usage = {
167635
+ ...usage,
167636
+ breakdown
167637
+ };
167638
+ }
167639
+ return {
167640
+ usage,
167641
+ trend
167642
+ };
167643
+ }
167258
167644
  async showStatusDetails() {
167259
167645
  await Promise.all([
167260
167646
  this.refreshRuntimeState(),
@@ -167672,6 +168058,23 @@ var ZCodeTui = class {
167672
168058
  priority: 90
167673
168059
  });
167674
168060
  }
168061
+ const runtimeCache = this.runtimeProjection?.contextUsage?.cache;
168062
+ const runtimeCacheRate = runtimeCache?.latestHitRate ?? runtimeCache?.hitRate;
168063
+ const sessionInputTokens = this.sessionMetrics.inputTokens;
168064
+ const sessionCacheReadTokens = this.sessionMetrics.cacheReadTokens;
168065
+ const sessionCacheRate = sessionInputTokens !== void 0 && sessionInputTokens > 0 && sessionCacheReadTokens !== void 0 ? sessionCacheReadTokens / sessionInputTokens : void 0;
168066
+ const useSessionFallback = !this.options.readRuntimeProjection;
168067
+ const cacheRateValue = runtimeCacheRate ?? (useSessionFallback ? sessionCacheRate : void 0);
168068
+ const hasCacheRequests = (runtimeCache?.hitRateRequestCount ?? 0) > 0 || runtimeCacheRate !== void 0 && runtimeCacheRate !== null || useSessionFallback && sessionCacheRate !== void 0;
168069
+ if (cacheRateValue !== void 0 && hasCacheRequests) {
168070
+ const cacheRate = Math.max(0, Math.min(100, Math.round(cacheRateValue * 100)));
168071
+ const style = cacheRate < 50 ? this.theme.warning : this.theme.muted;
168072
+ fields.push({
168073
+ text: style(`cache ${cacheRate}% hit`),
168074
+ compactText: style(`cache ${cacheRate}%`),
168075
+ priority: 85
168076
+ });
168077
+ }
167675
168078
  if (this.sessionMetrics.totalTokens !== void 0) {
167676
168079
  const tokens = formatTokens(this.sessionMetrics.totalTokens);
167677
168080
  fields.push({