@narumitw/pi-starship 0.65.0 → 0.65.2

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.
Files changed (56) hide show
  1. package/CHANGELOG.md +322 -0
  2. package/README.md +3 -0
  3. package/dist/chunks/{chunk-S2KBLHE2.ts → chunk-3XLWHJ5Y.ts} +5 -5
  4. package/dist/chunks/chunk-3XLWHJ5Y.ts.map +7 -0
  5. package/dist/chunks/{chunk-I22B7QPQ.ts → chunk-5YA3XF7S.ts} +4 -3
  6. package/dist/chunks/chunk-5YA3XF7S.ts.map +7 -0
  7. package/dist/chunks/{chunk-D2YWQMYT.ts → chunk-PZWT7OTP.ts} +3 -3
  8. package/dist/chunks/{chunk-XTLQ4WUL.ts → chunk-QGB3NNTM.ts} +1 -1
  9. package/dist/chunks/chunk-QGB3NNTM.ts.map +7 -0
  10. package/dist/chunks/{chunk-YK4S4RRM.ts → chunk-RQY2AYI2.ts} +3 -2
  11. package/dist/chunks/chunk-RQY2AYI2.ts.map +7 -0
  12. package/dist/chunks/{cloud-J2ZOE3HE.ts → cloud-CNNWXSQ3.ts} +2 -2
  13. package/dist/chunks/{command-configuration-menu-BJYQXV2U.ts → command-configuration-menu-JHKQ5SDW.ts} +6 -3
  14. package/dist/chunks/command-configuration-menu-JHKQ5SDW.ts.map +7 -0
  15. package/dist/chunks/{command-settings-chat-42OTC7NJ.ts → command-settings-chat-RN2GDMF5.ts} +4 -4
  16. package/dist/chunks/{commands-ZL36J5TX.ts → commands-XIRYGV7S.ts} +6 -6
  17. package/dist/chunks/{deployment-NOJ2KCLI.ts → deployment-KNUSQSJ5.ts} +3 -3
  18. package/dist/chunks/{development-T3XXVVDP.ts → development-TJNVM4H2.ts} +2 -2
  19. package/dist/chunks/{execution-R2OHIP2L.ts → execution-OFQXHFAH.ts} +3 -3
  20. package/dist/chunks/{jujutsu-XLDYKSX2.ts → jujutsu-T2LTPHSY.ts} +2 -2
  21. package/dist/chunks/{languages-CBQNNYXM.ts → languages-VWXTVJ45.ts} +3 -3
  22. package/dist/chunks/{package-7KVAK3TC.ts → package-JA4CJ5DR.ts} +2 -2
  23. package/dist/chunks/{system-574MHB4R.ts → system-CDTPAQZX.ts} +2 -2
  24. package/dist/index.ts +58 -36
  25. package/dist/index.ts.map +2 -2
  26. package/package.json +6 -5
  27. package/skills/configure-pi-starship/references/module-catalog.md +2 -2
  28. package/skills/configure-pi-starship/references/modules.md +10 -2
  29. package/src/command-configuration-menu.ts +3 -0
  30. package/src/command-preview.ts +1 -0
  31. package/src/modules/catalog.ts +1 -1
  32. package/src/modules/cost.ts +2 -1
  33. package/src/modules/git/runtime.ts +33 -25
  34. package/src/modules/types.ts +1 -0
  35. package/src/pi-starship.ts +2 -0
  36. package/src/runtime/command.ts +8 -3
  37. package/src/runtime/github-pr.ts +5 -2
  38. package/src/runtime/helpers.ts +5 -4
  39. package/src/runtime/types.ts +1 -0
  40. package/src/usage.ts +17 -4
  41. package/dist/chunks/chunk-I22B7QPQ.ts.map +0 -7
  42. package/dist/chunks/chunk-S2KBLHE2.ts.map +0 -7
  43. package/dist/chunks/chunk-XTLQ4WUL.ts.map +0 -7
  44. package/dist/chunks/chunk-YK4S4RRM.ts.map +0 -7
  45. package/dist/chunks/command-configuration-menu-BJYQXV2U.ts.map +0 -7
  46. /package/dist/chunks/{chunk-D2YWQMYT.ts.map → chunk-PZWT7OTP.ts.map} +0 -0
  47. /package/dist/chunks/{cloud-J2ZOE3HE.ts.map → cloud-CNNWXSQ3.ts.map} +0 -0
  48. /package/dist/chunks/{command-settings-chat-42OTC7NJ.ts.map → command-settings-chat-RN2GDMF5.ts.map} +0 -0
  49. /package/dist/chunks/{commands-ZL36J5TX.ts.map → commands-XIRYGV7S.ts.map} +0 -0
  50. /package/dist/chunks/{deployment-NOJ2KCLI.ts.map → deployment-KNUSQSJ5.ts.map} +0 -0
  51. /package/dist/chunks/{development-T3XXVVDP.ts.map → development-TJNVM4H2.ts.map} +0 -0
  52. /package/dist/chunks/{execution-R2OHIP2L.ts.map → execution-OFQXHFAH.ts.map} +0 -0
  53. /package/dist/chunks/{jujutsu-XLDYKSX2.ts.map → jujutsu-T2LTPHSY.ts.map} +0 -0
  54. /package/dist/chunks/{languages-CBQNNYXM.ts.map → languages-VWXTVJ45.ts.map} +0 -0
  55. /package/dist/chunks/{package-7KVAK3TC.ts.map → package-JA4CJ5DR.ts.map} +0 -0
  56. /package/dist/chunks/{system-574MHB4R.ts.map → system-CDTPAQZX.ts.map} +0 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-starship",
3
- "version": "0.65.0",
3
+ "version": "0.65.2",
4
4
  "description": "Native Starship-style TOML statusline and configuration skill for Pi.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -20,6 +20,7 @@
20
20
  "dist",
21
21
  "skills",
22
22
  "README.md",
23
+ "CHANGELOG.md",
23
24
  "LICENSE",
24
25
  "NOTICES.md"
25
26
  ],
@@ -39,7 +40,7 @@
39
40
  "typecheck": "tsc --noEmit"
40
41
  },
41
42
  "dependencies": {
42
- "@narumitw/pi-tui-kit": "^0.68.0",
43
+ "@narumitw/pi-tui-kit": "^0.69.0",
43
44
  "re2js": "^2.9.0",
44
45
  "semver": "^7.8.5",
45
46
  "smol-toml": "^1.9.1",
@@ -51,9 +52,9 @@
51
52
  "@earendil-works/pi-tui": "*"
52
53
  },
53
54
  "devDependencies": {
54
- "@earendil-works/pi-agent-core": "1.4.0",
55
- "@earendil-works/pi-coding-agent": "1.4.0",
56
- "@earendil-works/pi-tui": "1.4.0",
55
+ "@earendil-works/pi-agent-core": "1.5.0",
56
+ "@earendil-works/pi-coding-agent": "1.5.0",
57
+ "@earendil-works/pi-tui": "1.5.0",
57
58
  "@types/node": "26.6.5",
58
59
  "esbuild": "0.28.2",
59
60
  "typescript": "7.0.2"
@@ -1157,9 +1157,9 @@ Accepted style fields:
1157
1157
 
1158
1158
  ### `cost`
1159
1159
 
1160
- Reported estimated session cost or subscription state.
1160
+ Session cost, provider-total provenance, and subscription state.
1161
1161
 
1162
- - Format variables: `$symbol`, `$cost`, `$subscription`.
1162
+ - Format variables: `$symbol`, `$cost`, `$subscription`, `$source`.
1163
1163
  - Style variables in `format`: `$style`.
1164
1164
  - Default `format`: `"[ $symbol \\$$cost( $subscription) ]($style)"`.
1165
1165
  - Default `symbol`: `"💸"`.
@@ -28,7 +28,7 @@ Use this authoritative public reference whenever a question or change involves a
28
28
  | `context` | `$symbol`, `$percentage`, `$tokens`, `$window` | Context-window use |
29
29
  | `tokens` | `$symbol`, `$input`, `$output`, `$total` | Token totals |
30
30
  | `cache` | `$symbol`, `$rate`, `$read`, `$write` | Prompt-cache reads, writes, and latest hit rate; disabled by default |
31
- | `cost` | `$symbol`, `$cost`, `$subscription` | Session cost and optional `(sub)` marker |
31
+ | `cost` | `$symbol`, `$cost`, `$subscription`, `$source` | Session cost, provider-total provenance, and optional `(sub)` marker |
32
32
  | `time` | `$symbol`, `$time` | Formatted clock; local `HH:mm` by default |
33
33
  | `turn` | `$symbol`, `$count` | User turn count |
34
34
  | `package` | `$symbol`, `$version`, `$source` | Direct project manifest version |
@@ -208,7 +208,7 @@ These are inert labels, not evidence of cluster access or valid credentials.
208
208
  - Prompt waiting takes precedence without losing the underlying tool, streaming, completed, or idle state, which returns when the prompt closes.
209
209
  - Active and completed tool names in `$tool` and `$text` are single-line display text: line separators become spaces, and terminal and direction controls are removed. Raw tool identities remain unchanged.
210
210
  - `tokens`, `cache`, and `cost` total every usage-bearing session entry, matching Pi's native footer.
211
- This includes assistant messages, nested-LLM tool results, compactions, and branch summaries, including abandoned branches retained in the session.
211
+ This includes assistant messages, nested-LLM tool results, compactions, branch summaries, and standalone usage such as persisted cache warming, including abandoned branches retained in the session.
212
212
  - Cache `$read` and `$write` are cumulative.
213
213
  `$rate` uses only the latest assistant prompt with `cacheRead / (input + cacheRead + cacheWrite) * 100`.
214
214
  The module is empty when Pi has reported no cache reads or writes.
@@ -218,6 +218,14 @@ These are inert labels, not evidence of cluster access or valid credentials.
218
218
  Its default display hides values below 30%.
219
219
  Customize `[[context.display]]` when lower values should remain visible.
220
220
  The module name remains `context`, not `context_usage`.
221
+ - Cost `$source` is `provider` only for a nonempty, finite total when every included usage record has a finite nonnegative `cost.total` and `cost.totalFromProvider === true`.
222
+ It is `unconfirmed` for catalog estimates, mixed provenance, older sessions, empty sessions, or missing totals.
223
+ Records without usage do not contribute.
224
+ - `$cost` sums Pi's best available `cost.total` values, not estimated component costs.
225
+ Components remain catalog estimates and can differ from a provider total; these values do not establish exact prompt-cache savings.
226
+ Session-response costs are separate from account/key quotas and balances.
227
+ - The default cost format and thresholds are unchanged.
228
+ To show provenance, set `[cost].format` to `'$cost $source( $subscription)'`.
221
229
  - Subscription-backed OAuth models and `kimi-coding` set cost `$subscription` to `(sub)`.
222
230
  The dollar value is usage cost, not proof of an amount billed under a subscription.
223
231
 
@@ -57,6 +57,9 @@ export function showConfigurationMenu(
57
57
  tui.requestRender();
58
58
  };
59
59
  return {
60
+ get capturesViewportInput() {
61
+ return list.capturesViewportInput;
62
+ },
60
63
  render(width) {
61
64
  if (disposed) return [];
62
65
  lastWidth = width;
@@ -48,6 +48,7 @@ export async function showPreviewActionMenu<Value extends string>(
48
48
  };
49
49
 
50
50
  return {
51
+ capturesViewportInput: true,
51
52
  render(width: number): string[] {
52
53
  const safeWidth = Math.max(1, width);
53
54
  const terminalRows = Number.isFinite(tui.terminal.rows) ? Math.floor(tui.terminal.rows) : 24;
@@ -75,7 +75,7 @@ const MODULE_DESCRIPTIONS = {
75
75
  conda: "Active Conda environment.",
76
76
  container: "Current container or remote development environment.",
77
77
  context: "Current model context-window usage.",
78
- cost: "Reported estimated session cost or subscription state.",
78
+ cost: "Session cost, provider-total provenance, and subscription state.",
79
79
  deno: "Deno version detected in the current workspace.",
80
80
  directory: "Current working directory.",
81
81
  direnv: "Current direnv loading and permission state.",
@@ -3,7 +3,7 @@ import { defineModule } from "./types.js";
3
3
 
4
4
  export const costModule = defineModule({
5
5
  name: "cost",
6
- variables: ["symbol", "cost", "subscription"],
6
+ variables: ["symbol", "cost", "subscription", "source"],
7
7
  defaults: {
8
8
  format: "[ $symbol \\$$cost( $subscription) ]($style)",
9
9
  symbol: "💸",
@@ -22,6 +22,7 @@ export const costModule = defineModule({
22
22
  },
23
23
  values: ({ runtime }) => ({
24
24
  cost: formatCost(runtime.tokenTotals.cost),
25
+ source: runtime.tokenTotals.costTotalFromProvider === true ? "provider" : "unconfirmed",
25
26
  subscription: runtime.usingSubscription ? "(sub)" : "",
26
27
  }),
27
28
  });
@@ -2,8 +2,7 @@ import { existsSync, readFileSync } from "node:fs";
2
2
  import { basename, isAbsolute, join, resolve } from "node:path";
3
3
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
4
  import { execWorkspaceCommand } from "../../runtime/command.js";
5
- import { MAX_COMMAND_OUTPUT_BYTES } from "../../runtime/helpers.js";
6
- import type { WorkspaceExec } from "../../runtime/types.js";
5
+ import type { WorkspaceExec, WorkspaceExecResult } from "../../runtime/types.js";
7
6
  import type {
8
7
  GitBranchSnapshot,
9
8
  GitCommitSnapshot,
@@ -15,6 +14,8 @@ import type {
15
14
  } from "../types.js";
16
15
 
17
16
  const GIT_TIMEOUT_MS = 3_000;
17
+ // Bound complete porcelain records and repository metadata; omit larger footer replies in full.
18
+ const MAX_GIT_OUTPUT_BYTES = 64 * 1024;
18
19
 
19
20
  export interface ReadGitSnapshotOptions {
20
21
  includeMetrics: boolean;
@@ -69,17 +70,19 @@ export async function readGitSnapshot(
69
70
  metricsPromise,
70
71
  tagPromise,
71
72
  ]);
72
- if (options.signal?.aborted || statusResult.killed) return undefined;
73
+ if (statusResult.truncated || options.signal?.aborted || statusResult.killed) return undefined;
73
74
  if (statusResult.code !== 0) {
74
75
  return options.inspectBare ? readBareSnapshot(pi, cwd, options, tagResult) : undefined;
75
76
  }
76
77
 
77
78
  const parsed = parseGitStatusPorcelainV2(statusResult.stdout);
78
79
  const metadata =
79
- metadataResult.code === 0 && !metadataResult.killed ? parseGitRepositoryMetadata(metadataResult.stdout) : undefined;
80
+ !metadataResult.truncated && metadataResult.code === 0 && !metadataResult.killed
81
+ ? parseGitRepositoryMetadata(metadataResult.stdout)
82
+ : undefined;
80
83
  const commit = withTag(parsed.commit, tagResult);
81
84
  const metrics =
82
- metricsResult && metricsResult.code === 0 && !metricsResult.killed
85
+ metricsResult && !metricsResult.truncated && metricsResult.code === 0 && !metricsResult.killed
83
86
  ? parseGitDiffShortstat(metricsResult.stdout)
84
87
  : undefined;
85
88
 
@@ -93,7 +96,7 @@ export async function readGitSnapshot(
93
96
  };
94
97
  }
95
98
 
96
- type GitCommandResult = Awaited<ReturnType<ExtensionAPI["exec"]>>;
99
+ type GitCommandResult = WorkspaceExecResult;
97
100
 
98
101
  async function runGit(
99
102
  pi: ExtensionAPI,
@@ -101,22 +104,30 @@ async function runGit(
101
104
  args: string[],
102
105
  options: Pick<ReadGitSnapshotOptions, "signal" | "exec">,
103
106
  ): Promise<GitCommandResult> {
104
- const failed = { stdout: "", stderr: "", code: 1, killed: options.signal?.aborted ?? false };
107
+ const failed = { stdout: "", stderr: "", code: 1, killed: options.signal?.aborted ?? false, truncated: false };
105
108
  if (options.signal?.aborted) return failed;
106
109
  try {
107
110
  const result = options.exec
108
111
  ? await options.exec("git", args, {
109
112
  cwd,
110
113
  timeout: GIT_TIMEOUT_MS,
111
- maxOutputBytes: MAX_COMMAND_OUTPUT_BYTES,
114
+ maxOutputBytes: MAX_GIT_OUTPUT_BYTES,
112
115
  signal: options.signal,
113
116
  environment: process.env,
114
117
  })
115
- : await pi.exec("git", args, { cwd, signal: options.signal, timeout: GIT_TIMEOUT_MS });
116
- if (options.signal?.aborted) return { ...failed, killed: true };
117
- if (Buffer.byteLength(result.stdout) + Buffer.byteLength(result.stderr) > MAX_COMMAND_OUTPUT_BYTES) {
118
- return { ...failed, killed: true };
118
+ : await pi.exec("git", args, {
119
+ cwd,
120
+ signal: options.signal,
121
+ timeout: GIT_TIMEOUT_MS,
122
+ maxBuffer: MAX_GIT_OUTPUT_BYTES,
123
+ });
124
+ if (
125
+ result.truncated ||
126
+ Buffer.byteLength(result.stdout) + Buffer.byteLength(result.stderr) > MAX_GIT_OUTPUT_BYTES
127
+ ) {
128
+ return { ...failed, killed: result.killed, truncated: true };
119
129
  }
130
+ if (options.signal?.aborted) return { ...failed, killed: true };
120
131
  return result;
121
132
  } catch {
122
133
  return failed;
@@ -132,12 +143,13 @@ async function readBareSnapshot(
132
143
  const boundedOptions = { ...options, exec: options.exec ?? execWorkspaceCommand };
133
144
  const run = (args: string[]) => runGit(pi, cwd, args, boundedOptions);
134
145
  const bare = await run(["rev-parse", "--is-bare-repository"]);
135
- if (options.signal?.aborted || bare.killed || bare.code !== 0 || bare.stdout.trim() !== "true") return undefined;
146
+ if (bare.truncated || options.signal?.aborted || bare.killed || bare.code !== 0 || bare.stdout.trim() !== "true")
147
+ return undefined;
136
148
  const [head, hash] = await Promise.all([
137
149
  run(["symbolic-ref", "--short", "HEAD"]),
138
150
  run(["rev-parse", "--verify", "HEAD"]),
139
151
  ]);
140
- if (options.signal?.aborted || head.killed || hash.killed) return undefined;
152
+ if (head.truncated || hash.truncated || options.signal?.aborted || head.killed || hash.killed) return undefined;
141
153
  const name = head.code === 0 ? head.stdout.trim() : "";
142
154
  const commitHash = hash.code === 0 ? hash.stdout.trim() : "";
143
155
  const validHash = /^[a-fA-F0-9]{4,64}$/u.test(commitHash);
@@ -149,7 +161,9 @@ async function readBareSnapshot(
149
161
  : undefined;
150
162
  if (options.signal?.aborted) return undefined;
151
163
  const upstreamFields =
152
- upstreamResult?.code === 0 && !upstreamResult.killed ? upstreamResult.stdout.trimEnd().split("\0") : [];
164
+ upstreamResult && !upstreamResult.truncated && upstreamResult.code === 0 && !upstreamResult.killed
165
+ ? upstreamResult.stdout.trimEnd().split("\0")
166
+ : [];
153
167
  const remote = upstreamFields[0] === reference ? splitUpstream(upstreamFields[1]) : {};
154
168
  return {
155
169
  branch: { name: name || "HEAD", detached, bare: true, ...remote },
@@ -165,7 +179,7 @@ export async function readGitStatus(pi: ExtensionAPI, cwd: string): Promise<GitS
165
179
  ["--no-optional-locks", "status", "--porcelain=v2", "--branch", "--show-stash", "--untracked-files=normal"],
166
180
  {},
167
181
  );
168
- if (result.code !== 0 || result.killed) return undefined;
182
+ if (result.truncated || result.code !== 0 || result.killed) return undefined;
169
183
  return parseGitStatusPorcelainV2(result.stdout).status;
170
184
  }
171
185
 
@@ -176,7 +190,7 @@ export async function readGitWorktree(pi: ExtensionAPI, cwd: string): Promise<Gi
176
190
  ["rev-parse", "--path-format=absolute", "--show-toplevel", "--git-common-dir", "--git-dir"],
177
191
  {},
178
192
  );
179
- if (result.code !== 0 || result.killed) return undefined;
193
+ if (result.truncated || result.code !== 0 || result.killed) return undefined;
180
194
  return parseGitRepositoryMetadata(result.stdout)?.worktree;
181
195
  }
182
196
 
@@ -408,15 +422,9 @@ function splitUpstream(upstream: string | undefined): {
408
422
 
409
423
  function withTag(
410
424
  commit: GitCommitSnapshot | undefined,
411
- result:
412
- | {
413
- stdout: string;
414
- code: number;
415
- killed: boolean;
416
- }
417
- | undefined,
425
+ result: GitCommandResult | undefined,
418
426
  ): GitCommitSnapshot | undefined {
419
- if (!commit || !result || result.code !== 0 || result.killed) return commit;
427
+ if (!commit || !result || result.truncated || result.code !== 0 || result.killed) return commit;
420
428
  const tag = result.stdout.trim();
421
429
  return tag ? { ...commit, tag: tag.split(/\r?\n/u)[0] } : commit;
422
430
  }
@@ -109,6 +109,7 @@ export interface StarshipRuntimeSnapshot {
109
109
  cacheRead: number;
110
110
  cacheWrite: number;
111
111
  cost: number;
112
+ costTotalFromProvider?: boolean;
112
113
  latestCacheHitRate?: number;
113
114
  };
114
115
  usingSubscription: boolean;
@@ -192,6 +192,7 @@ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions
192
192
  eventDebounceTimer = undefined;
193
193
  requestRefresh(target);
194
194
  }, EVENT_DEBOUNCE_MS);
195
+ eventDebounceTimer.unref();
195
196
  };
196
197
 
197
198
  function restartLocalControllers(target: RefreshTarget) {
@@ -372,6 +373,7 @@ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions
372
373
  tui.requestRender();
373
374
  }, REFRESH_INTERVAL_MS)
374
375
  : undefined;
376
+ timer?.unref();
375
377
  let disposed = false;
376
378
 
377
379
  const dispose = () => {
@@ -6,7 +6,7 @@ const FORCE_KILL_DELAY_MS = 250;
6
6
  export const execWorkspaceCommand: WorkspaceExec = async (command, args, options) =>
7
7
  new Promise((resolve) => {
8
8
  if (options.signal?.aborted) {
9
- resolve({ stdout: "", stderr: "", code: 1, killed: true });
9
+ resolve({ stdout: "", stderr: "", code: 1, killed: true, truncated: false });
10
10
  return;
11
11
  }
12
12
 
@@ -21,13 +21,14 @@ export const execWorkspaceCommand: WorkspaceExec = async (command, args, options
21
21
  windowsHide: true,
22
22
  });
23
23
  } catch {
24
- resolve({ stdout: "", stderr: "", code: 1, killed: false });
24
+ resolve({ stdout: "", stderr: "", code: 1, killed: false, truncated: false });
25
25
  return;
26
26
  }
27
27
 
28
28
  const stdout: Buffer[] = [];
29
29
  const stderr: Buffer[] = [];
30
30
  let outputBytes = 0;
31
+ let truncated = false;
31
32
  let killed = false;
32
33
  let settled = false;
33
34
  let forceKillTimer: NodeJS.Timeout | undefined;
@@ -44,6 +45,7 @@ export const execWorkspaceCommand: WorkspaceExec = async (command, args, options
44
45
  stderr: Buffer.concat(stderr).toString("utf8"),
45
46
  code,
46
47
  killed,
48
+ truncated,
47
49
  });
48
50
  };
49
51
 
@@ -88,7 +90,10 @@ export const execWorkspaceCommand: WorkspaceExec = async (command, args, options
88
90
  const remaining = Math.max(0, options.maxOutputBytes - outputBytes);
89
91
  if (remaining > 0) target.push(chunk.subarray(0, remaining));
90
92
  outputBytes += chunk.byteLength;
91
- if (outputBytes > options.maxOutputBytes) terminate();
93
+ if (outputBytes > options.maxOutputBytes) {
94
+ truncated = true;
95
+ terminate();
96
+ }
92
97
  };
93
98
 
94
99
  child.stdout?.on("data", collect(stdout));
@@ -3,6 +3,7 @@ import type { GithubPrSnapshot, GithubPrState } from "../modules/types.js";
3
3
  import type { WorkspaceExec } from "./types.js";
4
4
 
5
5
  const GH_TIMEOUT_MS = 10_000;
6
+ // One PR's selected fields and check summaries; omit larger replies instead of parsing partial JSON.
6
7
  const MAX_GH_OUTPUT_BYTES = 128 * 1024;
7
8
  const MAX_URL_LENGTH = 4_096;
8
9
  const MAX_CHECKS = 1_000;
@@ -69,6 +70,7 @@ export async function queryGithubPr(
69
70
  now = Date.now(),
70
71
  options: GithubPrQueryOptions = {},
71
72
  ): Promise<GithubPrSnapshot | undefined> {
73
+ if (signal?.aborted) return undefined;
72
74
  const invocation = ghPrViewInvocation(options.platform);
73
75
  try {
74
76
  const result = await exec(invocation.command, invocation.args, {
@@ -78,8 +80,9 @@ export async function queryGithubPr(
78
80
  maxOutputBytes: MAX_GH_OUTPUT_BYTES,
79
81
  environment: githubPrEnvironment(options.environment),
80
82
  });
81
- if (result.killed || result.code !== 0) return undefined;
82
- if (Buffer.byteLength(result.stdout) > MAX_GH_OUTPUT_BYTES) return undefined;
83
+ if (result.truncated) return undefined;
84
+ if (signal?.aborted || result.killed || result.code !== 0) return undefined;
85
+ if (Buffer.byteLength(result.stdout) + Buffer.byteLength(result.stderr) > MAX_GH_OUTPUT_BYTES) return undefined;
83
86
  return buildGithubPrSnapshot(JSON.parse(result.stdout), now);
84
87
  } catch {
85
88
  return undefined;
@@ -7,6 +7,7 @@ export { formatVersion } from "../format/version.js";
7
7
 
8
8
  export const MAX_METADATA_FILE_BYTES = 64 * 1024;
9
9
  export const COMMAND_TIMEOUT_MS = 2_000;
10
+ // Footer probes need only version, health, or local metadata; omit larger replies in full.
10
11
  export const MAX_COMMAND_OUTPUT_BYTES = 64 * 1024;
11
12
  const MAX_DIRECTORY_ENTRIES = 2_048;
12
13
  const MAX_LABEL_LENGTH = 160;
@@ -206,11 +207,11 @@ export async function runBounded(
206
207
  signal: context.input.signal,
207
208
  environment: context.input.environment,
208
209
  });
210
+ if (result.truncated) return undefined;
209
211
  if (context.input.signal?.aborted || result.code !== 0 || result.killed) return undefined;
210
- const selectedOutput = result.stdout || result.stderr;
211
- const output = Buffer.from(selectedOutput).subarray(0, MAX_COMMAND_OUTPUT_BYTES + 1);
212
- if (output.byteLength > MAX_COMMAND_OUTPUT_BYTES) return undefined;
213
- return output.toString("utf8");
212
+ if (Buffer.byteLength(result.stdout) + Buffer.byteLength(result.stderr) > MAX_COMMAND_OUTPUT_BYTES)
213
+ return undefined;
214
+ return result.stdout || result.stderr;
214
215
  } catch {
215
216
  return undefined;
216
217
  }
@@ -7,6 +7,7 @@ export interface WorkspaceExecResult {
7
7
  stderr: string;
8
8
  code: number;
9
9
  killed: boolean;
10
+ truncated: boolean;
10
11
  }
11
12
 
12
13
  export type WorkspaceExec = (
package/src/usage.ts CHANGED
@@ -5,7 +5,7 @@ interface UsageLike {
5
5
  output?: number;
6
6
  cacheRead?: number;
7
7
  cacheWrite?: number;
8
- cost?: { total?: number };
8
+ cost?: { total?: number; totalFromProvider?: boolean };
9
9
  }
10
10
 
11
11
  export interface FooterUsageSummary {
@@ -14,6 +14,7 @@ export interface FooterUsageSummary {
14
14
  cacheRead: number;
15
15
  cacheWrite: number;
16
16
  cost: number;
17
+ costTotalFromProvider: boolean;
17
18
  latestCacheHitRate?: number;
18
19
  }
19
20
 
@@ -24,15 +25,18 @@ export function summarizeFooterUsage(entries: readonly SessionEntry[]): FooterUs
24
25
  cacheRead: 0,
25
26
  cacheWrite: 0,
26
27
  cost: 0,
28
+ costTotalFromProvider: false,
27
29
  };
30
+ let hasUsage = false;
31
+ let allTotalsFromProvider = true;
28
32
 
29
33
  for (const entry of entries) {
30
34
  let usage: UsageLike | undefined;
31
35
  if (entry.type === "message" && entry.message.role === "assistant") {
32
36
  usage = entry.message.usage;
33
- const input = usage.input ?? 0;
34
- const cacheRead = usage.cacheRead ?? 0;
35
- const cacheWrite = usage.cacheWrite ?? 0;
37
+ const input = usage?.input ?? 0;
38
+ const cacheRead = usage?.cacheRead ?? 0;
39
+ const cacheWrite = usage?.cacheWrite ?? 0;
36
40
  const promptTokens = input + cacheRead + cacheWrite;
37
41
  totals.latestCacheHitRate = promptTokens > 0 ? (cacheRead / promptTokens) * 100 : undefined;
38
42
  } else if (entry.type === "message" && entry.message.role === "toolResult") {
@@ -47,7 +51,16 @@ export function summarizeFooterUsage(entries: readonly SessionEntry[]): FooterUs
47
51
  totals.cacheRead += usage.cacheRead ?? 0;
48
52
  totals.cacheWrite += usage.cacheWrite ?? 0;
49
53
  totals.cost += usage.cost?.total ?? 0;
54
+ hasUsage = true;
55
+ const cost = usage.cost;
56
+ allTotalsFromProvider &&=
57
+ cost?.totalFromProvider === true &&
58
+ typeof cost.total === "number" &&
59
+ Number.isFinite(cost.total) &&
60
+ cost.total >= 0;
50
61
  }
51
62
 
63
+ // Empty or incomplete accounting cannot establish a provider-reported total.
64
+ totals.costTotalFromProvider = hasUsage && allTotalsFromProvider && Number.isFinite(totals.cost);
52
65
  return totals;
53
66
  }