zcode-app-cli 3.7.7-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.
package/bin/zcode.js CHANGED
@@ -21,12 +21,13 @@ var config_example_default = {
21
21
  "models": {
22
22
  "glm-5.3": { "name": "GLM-5.3" },
23
23
  "glm-5.2": { "name": "GLM-5.2" },
24
- "glm-5.1": { "name": "GLM-5.1" }
24
+ "glm-5.1": { "name": "GLM-5.1" },
25
+ "glm-5-turbo": { "name": "GLM-5-Turbo" }
25
26
  }
26
27
  } },
27
28
  model: {
28
29
  "main": "zai/glm-5.2",
29
- "lite": "zai/glm-5.1"
30
+ "lite": "zai/glm-5-turbo"
30
31
  },
31
32
  modelCatalog: { "overrides": {} },
32
33
  modelStream: { "idleTimeoutMs": 6e4 },
@@ -17,13 +17,16 @@
17
17
  },
18
18
  "glm-5.1": {
19
19
  "name": "GLM-5.1"
20
+ },
21
+ "glm-5-turbo": {
22
+ "name": "GLM-5-Turbo"
20
23
  }
21
24
  }
22
25
  }
23
26
  },
24
27
  "model": {
25
28
  "main": "zai/glm-5.2",
26
- "lite": "zai/glm-5.1"
29
+ "lite": "zai/glm-5-turbo"
27
30
  },
28
31
  "modelCatalog": {
29
32
  "overrides": {}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zcode-app-cli",
3
- "version": "3.7.7-12",
3
+ "version": "3.7.7-13",
4
4
  "description": "Unofficial terminal client for the ZCode agent runtime",
5
5
  "keywords": [
6
6
  "agent",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "appVersion": "3.7.7",
3
3
  "cliVersion": "0.16.3",
4
- "extractedAt": "2026-08-15T01:37:56.189Z",
4
+ "extractedAt": "2026-08-15T12:57:05.587Z",
5
5
  "sha512": "9vUj/HFAUk0AS7S/TwPr6qa+qJv8ccAIvHJxp29TYvVnMoOZKPQ3rDiTlXGo9htFL7V5HBRb0n+NbXm5Cm5BqA==",
6
6
  "source": "https://cdn-zcode.z.ai/zcode/electron/releases/3.7.7/linux-x64/ZCode-3.7.7-linux-x64.deb",
7
7
  "tui": {
@@ -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 },
@@ -157286,6 +157287,7 @@ var ChoiceDialog = class {
157286
157287
  this.contentExpanded = !this.contentExpanded;
157287
157288
  return;
157288
157289
  }
157290
+ if ((this.content?.handleInput)?.call(this.content, data) === true) return;
157289
157291
  if (this.contentExpanded) {
157290
157292
  if (matchesKey(data, "escape")) {
157291
157293
  this.contentExpanded = false;
@@ -158059,7 +158061,8 @@ function normalizeGoal(value) {
158059
158061
  function formatTokens(value) {
158060
158062
  if (value < 1e3) return Math.floor(value).toString();
158061
158063
  if (value < 1e6) return `${Number((value / 1e3).toFixed(1))}K`;
158062
- 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`;
158063
158066
  }
158064
158067
  function formatGoalElapsed(totalSeconds) {
158065
158068
  const seconds = Math.max(0, Math.floor(totalSeconds));
@@ -158095,65 +158098,203 @@ const contextLabels = {
158095
158098
  tool_prompt: "Tool prompts",
158096
158099
  system_tool_schemas: "System tool schemas",
158097
158100
  mcp_tool_schemas: "MCP tool schemas",
158098
- messages: "Messages"
158101
+ messages: "Messages",
158102
+ user_messages: "User messages",
158103
+ assistant_messages: "Assistant messages",
158104
+ tool_io: "Tool input/output"
158099
158105
  };
158100
158106
  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;
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;
158104
158110
  return theme.muted;
158105
158111
  }
158106
158112
  function percent(value, total) {
158107
158113
  return total > 0 ? `${(value / total * 100).toFixed(1)}%` : "0%";
158108
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
+ }
158109
158151
  var ContextDetailView = class {
158110
158152
  theme;
158153
+ refresh;
158154
+ requestRender;
158111
158155
  usage;
158112
- constructor(theme, usage) {
158156
+ trend;
158157
+ page = "overview";
158158
+ refreshing = false;
158159
+ constructor(theme, usage, trend, refresh, requestRender) {
158113
158160
  this.theme = theme;
158161
+ this.refresh = refresh;
158162
+ this.requestRender = requestRender;
158114
158163
  this.usage = usage;
158164
+ this.trend = trend;
158115
158165
  }
158116
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
+ }
158117
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) {
158118
158200
  if (!this.usage) return [this.theme.muted("Context usage is unavailable in this runtime.")];
158201
+ const safeWidth = Math.max(1, width);
158119
158202
  const totalChars = this.usage.breakdown.reduce((total, item) => total + item.chars, 0);
158120
- const barWidth = Math.max(8, Math.min(40, width - 2));
158203
+ const barWidth = Math.max(8, Math.min(40, safeWidth - 2));
158121
158204
  const bar = this.usage.breakdown.map((item) => {
158122
158205
  const columns = totalChars > 0 ? Math.max(1, Math.round(item.chars / totalChars * barWidth)) : 0;
158123
158206
  return contextStyle(item.source, this.theme)("█".repeat(columns));
158124
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."));
158125
158227
  const cache = this.usage.cache;
158126
- 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
+ ];
158127
158259
  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),
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`),
158131
158264
  "",
158132
- 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")
158133
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)];
158134
158290
  for (const item of this.usage.breakdown.slice().sort((left, right) => right.chars - left.chars)) {
158135
158291
  const label = contextLabels[item.source];
158136
158292
  const value = `${item.chars.toLocaleString()} chars · ${percent(item.chars, totalChars)}`;
158137
- const available = Math.max(1, width - visibleWidth(value) - 3);
158293
+ const available = Math.max(1, safeWidth - visibleWidth(value) - 3);
158138
158294
  lines.push(`${contextStyle(item.source, this.theme)("●")} ${truncateToWidth(label, available)} ${this.theme.muted(value)}`);
158139
158295
  }
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)));
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));
158157
158298
  }
158158
158299
  };
158159
158300
  var StatusDetailView = class {
@@ -158193,6 +158334,209 @@ var StatusDetailView = class {
158193
158334
  }
158194
158335
  };
158195
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
158196
158540
  //#region node_modules/diff/libesm/diff/base.js
158197
158541
  var Diff = class {
158198
158542
  diff(oldStr, newStr, options = {}) {
@@ -161798,7 +162142,10 @@ const contextSources = /* @__PURE__ */ new Set([
161798
162142
  "tool_prompt",
161799
162143
  "system_tool_schemas",
161800
162144
  "mcp_tool_schemas",
161801
- "messages"
162145
+ "messages",
162146
+ "user_messages",
162147
+ "assistant_messages",
162148
+ "tool_io"
161802
162149
  ]);
161803
162150
  function finiteNumber(value) {
161804
162151
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
@@ -167246,17 +167593,54 @@ var ZCodeTui = class {
167246
167593
  }
167247
167594
  }
167248
167595
  async showContextDetails() {
167249
- await Promise.all([this.refreshRuntimeState(), this.refreshSessionUsage()]);
167596
+ const initial = await this.readContextDetailData();
167250
167597
  await this.showChoice({
167251
167598
  title: "Context",
167252
- prompt: "Current runtime context usage and source composition.",
167253
- 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()),
167254
167601
  items: [{
167255
167602
  value: "close",
167256
167603
  label: "Close"
167257
167604
  }]
167258
167605
  });
167259
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
+ }
167260
167644
  async showStatusDetails() {
167261
167645
  await Promise.all([
167262
167646
  this.refreshRuntimeState(),
@@ -167674,6 +168058,23 @@ var ZCodeTui = class {
167674
168058
  priority: 90
167675
168059
  });
167676
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
+ }
167677
168078
  if (this.sessionMetrics.totalTokens !== void 0) {
167678
168079
  const tokens = formatTokens(this.sessionMetrics.totalTokens);
167679
168080
  fields.push({