@phren/cli 0.3.9 → 0.3.11

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.
@@ -29,6 +29,7 @@ import { ModelCatalog } from "./models.js";
29
29
  import { ModelSwitcher } from "./model-switch.js";
30
30
  import { SideQuestions } from "./side-questions.js";
31
31
  import { AccountUsageReader } from "./usage.js";
32
+ import { ResourceMonitor } from "./resources.js";
32
33
  import { createScheduleLauncher, Scheduler, scheduleRunsFile } from "./schedules.js";
33
34
  import { dailyCanaryDue, runCanary } from "./canary.js";
34
35
  import { defaultPhrenPath } from "../shared.js";
@@ -81,6 +82,7 @@ export async function serve(version) {
81
82
  const sideQuestions = new SideQuestions();
82
83
  const contextUsage = new WorkspaceContextUsage();
83
84
  const accountUsage = new AccountUsageReader();
85
+ const resources = new ResourceMonitor();
84
86
  const tabActivity = new TabActivityStore();
85
87
  const codexQuestions = new CodexQuestions();
86
88
  const scheduleStore = defaultPhrenPath();
@@ -139,9 +141,10 @@ export async function serve(version) {
139
141
  read: workspacesReader({ modules, info, agentHooks, journal, tabActivity, contextUsage }),
140
142
  info: () => ({ ...info, capabilities: info.capabilities }),
141
143
  renew: server => agentHooks.overview.renew(server),
144
+ resources: () => resources.read(),
142
145
  });
143
146
  const http = createServer(createRouteHandler({ version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks,
144
- journal, tabActivity, contextUsage, modelCatalog, modelSwitcher, sideQuestions, accountUsage, codexQuestions, launches, locatedDirectories,
147
+ journal, tabActivity, contextUsage, modelCatalog, modelSwitcher, sideQuestions, accountUsage, resources, codexQuestions, launches, locatedDirectories,
145
148
  fanoutMessages, canary, streams, returns }));
146
149
  http.requestTimeout = 20_000;
147
150
  http.headersTimeout = 10_000;
@@ -165,7 +168,7 @@ export async function serve(version) {
165
168
  ws.clients.delete(oldest);
166
169
  }
167
170
  if (overviewServer !== undefined) {
168
- overview(client, overviewServer, url.searchParams.get("watchApprovals") === "1");
171
+ overview(client, overviewServer, url.searchParams.get("watchApprovals") === "1", url.searchParams.get("resources") === "1");
169
172
  return;
170
173
  }
171
174
  if (url.pathname === "/v1/speech/transcribe") {
@@ -297,6 +297,11 @@ export function phrenHookContext(raw, includeSidechain = false) {
297
297
  * private reasoning redacted, queued phone messages, background task
298
298
  * notifications and compaction markers. */
299
299
  export function visibleClaudeEvent(raw, includeSidechain = false) {
300
+ // A follow-up the phone sent a Claude fan-out worker, written into its
301
+ // event log by the Hook before the resumed run.
302
+ if (raw.type === "phren/fanout-message" && typeof raw.text === "string") {
303
+ return { type: "user", timestamp: raw.timestamp, message: { role: "user", content: raw.text.slice(0, 65_536) } };
304
+ }
300
305
  // A queued phone message carries the same wrapper; unwrap before the
301
306
  // digest so enqueue and remove keep matching keys.
302
307
  if (raw.type === "queue-operation" && typeof raw.content === "string")
@@ -8,6 +8,26 @@ export declare function childTranscriptBelongsTo(file: string, parent: string):
8
8
  /** Codex rows the phone may see: public messages, tool calls and their
9
9
  * outputs, the answering model, and turn/usage events. */
10
10
  export declare function visibleCodexEvent(raw: Json): Json | undefined;
11
+ export interface CodeModeWrapper {
12
+ callId: string;
13
+ images: string[];
14
+ }
15
+ /** A numbered rollout's code-mode `exec` call whose every tool call is
16
+ * recorded as an item. A script that calls anything else stays as it is. */
17
+ export declare function codeModeWrapper(raw: Json): CodeModeWrapper | undefined;
18
+ /** The wrapper a numbered rollout's code-mode result answers, by call id. */
19
+ export declare function codeModeOutputCall(raw: Json): string | undefined;
20
+ /** A covered wrapper's result: an image viewer keeps only its pictures, a
21
+ * "Script completed"/"Script running" status is hidden (the items carry the
22
+ * actions), and a failure or abort is listed with the script it ended, whose
23
+ * own row was hidden, so the phone draws the pair. */
24
+ export declare function projectCodeModeOutput(raw: Json, call: Json | undefined): Json | undefined;
25
+ /** The wrapper call a result answers, found within the rows just before it
26
+ * (a script's own items sit between the two; 32 rows apart at most seen). */
27
+ export declare function findCodeModeCall(rows: (before: number, after: number) => AsyncIterable<{
28
+ line: number;
29
+ bytes?: Buffer;
30
+ }>, line: number, callId: string): Promise<Json | undefined>;
11
31
  /** Codex 0.155 code mode: the model calls one generic tool whose input is
12
32
  * JavaScript, and that source invokes `tools.apply_patch`/`tools.shell`/
13
33
  * `tools.read`. The Hook resolves each invocation into the ordinary call the
@@ -90,8 +90,13 @@ export function visibleCodexEvent(raw) {
90
90
  payload: { type: "error", ...(typeof p.message === "string" ? { message: p.message } : {}) } };
91
91
  if (raw.type === "event_msg" && ["token_count", "task_started", "task_complete", "task_completed", "turn_aborted", "task_aborted", "error"].includes(String(p.type)))
92
92
  return raw;
93
+ if (raw.type === "event_msg" && p.type === "item_completed")
94
+ return itemCall(raw, object(p.item));
93
95
  if (raw.type !== "response_item")
94
96
  return undefined;
97
+ const wrapper = codeModeWrapper(raw);
98
+ if (wrapper)
99
+ return wrapper.images.length ? imageCall(raw, wrapper) : undefined;
95
100
  if (p.type === "message" && ["user", "assistant"].includes(String(p.role)) && p.channel !== "analysis") {
96
101
  const text = typeof p.content === "string" ? p.content : objects(p.content).map(b => typeof b.text === "string" ? b.text : "").join("\n");
97
102
  return p.role === "user" && harnessPreamble(text) ? undefined : raw;
@@ -100,6 +105,162 @@ export function visibleCodexEvent(raw) {
100
105
  return raw;
101
106
  return undefined;
102
107
  }
108
+ /** Codex 0.155.1 and later number their rollout rows (`ordinal`) and record
109
+ * each action a code-mode script runs as its own `item_completed` row: the
110
+ * command and its output, the patch, the MCP call. The `exec` call wrapping
111
+ * those actions in JavaScript and its "Script completed" result only repeat
112
+ * them, so the phone reads the items as the ordinary calls it already draws. */
113
+ const OUTPUT_TAIL = 4_000, MCP_OUTPUT = 65_536, PATCH_FILE = 200_000, COMMAND = 16_384;
114
+ const WRAPPED_TOOL = /\btools\s*\.\s*([A-Za-z_$][\w$]*)\s*\(/g;
115
+ const VIEW_IMAGE = /\btools\s*\.\s*view_image\s*\(/g;
116
+ /** Tools whose every call Codex records as an item (`write_stdin` finishes
117
+ * the command it feeds; `view_image` has only a path item, so its picture is
118
+ * taken from the wrapper's own result). */
119
+ const ITEM_TOOLS = new Set(["exec_command", "write_stdin", "apply_patch", "view_image"]);
120
+ /** A numbered rollout's code-mode `exec` call whose every tool call is
121
+ * recorded as an item. A script that calls anything else stays as it is. */
122
+ export function codeModeWrapper(raw) {
123
+ const p = object(raw.payload), source = p.input, callId = p.call_id;
124
+ if (typeof raw.ordinal !== "number" || raw.type !== "response_item" || p.type !== "custom_tool_call" || p.name !== "exec")
125
+ return undefined;
126
+ if (typeof source !== "string" || typeof callId !== "string" || !callId || source.trimStart().startsWith("*** Begin Patch"))
127
+ return undefined;
128
+ const tools = [...source.matchAll(WRAPPED_TOOL)].map(match => match[1]);
129
+ if (!tools.length || !tools.every(tool => ITEM_TOOLS.has(tool) || /^mcp__\w+$/.test(tool)))
130
+ return undefined;
131
+ const images = [...source.matchAll(VIEW_IMAGE)].map(match => {
132
+ const args = callArguments(source, (match.index ?? 0) + match[0].length - 1);
133
+ return (args === undefined ? undefined : argumentString(args, source, ["path"])) ?? "";
134
+ });
135
+ return { callId, images };
136
+ }
137
+ /** A wrapper that viewed an image becomes the `view_image` call its result
138
+ * (the picture) pairs with; the ImageView item names only the path. */
139
+ function imageCall(raw, wrapper) {
140
+ const file = wrapper.images.find(Boolean);
141
+ return { type: "response_item", ...(raw.timestamp !== undefined ? { timestamp: raw.timestamp } : {}),
142
+ payload: { type: "function_call", name: "view_image", call_id: wrapper.callId, arguments: JSON.stringify(file ? { path: file.slice(0, 4_096) } : {}) } };
143
+ }
144
+ /** The wrapper a numbered rollout's code-mode result answers, by call id. */
145
+ export function codeModeOutputCall(raw) {
146
+ const p = object(raw.payload);
147
+ return typeof raw.ordinal === "number" && raw.type === "response_item" && p.type === "custom_tool_call_output"
148
+ && typeof p.call_id === "string" && p.call_id ? p.call_id : undefined;
149
+ }
150
+ /** A covered wrapper's result: an image viewer keeps only its pictures, a
151
+ * "Script completed"/"Script running" status is hidden (the items carry the
152
+ * actions), and a failure or abort is listed with the script it ended, whose
153
+ * own row was hidden, so the phone draws the pair. */
154
+ export function projectCodeModeOutput(raw, call) {
155
+ const wrapper = call && codeModeWrapper(call);
156
+ if (!call || !wrapper)
157
+ return raw;
158
+ const p = object(raw.payload), blocks = Array.isArray(p.output) ? objects(p.output) : [];
159
+ const images = blocks.filter(block => ["input_image", "image"].includes(String(block.type)));
160
+ // The view_image call is already listed on the script's own row.
161
+ if (wrapper.images.length)
162
+ return images.length ? { ...raw, payload: { ...p, output: images } } : raw;
163
+ const text = typeof p.output === "string" ? p.output : blocks.map(block => typeof block.text === "string" ? block.text : "").join("\n");
164
+ if (/^Script (completed|running)\b/.test(text))
165
+ return undefined;
166
+ return { type: "response_item", ...(call.timestamp !== undefined ? { timestamp: call.timestamp } : {}),
167
+ payload: { type: "custom_tool_call", name: "exec", call_id: wrapper.callId, input: object(call.payload).input }, phren_item_output: raw };
168
+ }
169
+ /** The wrapper call a result answers, found within the rows just before it
170
+ * (a script's own items sit between the two; 32 rows apart at most seen). */
171
+ export async function findCodeModeCall(rows, line, callId) {
172
+ const needle = Buffer.from(JSON.stringify(callId));
173
+ for await (const row of rows(line, Math.max(0, line - 256))) {
174
+ if (!row.bytes?.includes(needle))
175
+ continue;
176
+ try {
177
+ const raw = object(JSON.parse(row.bytes.toString())), p = object(raw.payload);
178
+ if (raw.type === "response_item" && p.type === "custom_tool_call" && p.call_id === callId)
179
+ return raw;
180
+ }
181
+ catch { /* Not the call. */ }
182
+ }
183
+ return undefined;
184
+ }
185
+ /** A shell command as the terminal shows it: the script a `sh -lc` runs. */
186
+ function commandText(value) {
187
+ if (typeof value === "string")
188
+ return value;
189
+ const parts = Array.isArray(value) ? value.filter((part) => typeof part === "string") : [];
190
+ if (parts.length === 3 && ["-lc", "-c"].includes(parts[1]) && /(^|\/)(ba|z|da|fi|k)?sh$/.test(parts[0]))
191
+ return parts[2];
192
+ return parts.join(" ");
193
+ }
194
+ function localPath(value) {
195
+ if (typeof value !== "string" || !value)
196
+ return undefined;
197
+ // The URL names a path on the computer Codex ran on, which may not follow
198
+ // this platform's rules (fileURLToPath refuses `file:///work` on Windows).
199
+ if (value.startsWith("file://")) {
200
+ try {
201
+ const url = new URL(value);
202
+ if (url.host)
203
+ return undefined;
204
+ const pathname = decodeURIComponent(url.pathname);
205
+ return /^\/[A-Za-z]:\//.test(pathname) ? pathname.slice(1) : pathname;
206
+ }
207
+ catch {
208
+ return undefined;
209
+ }
210
+ }
211
+ return value.startsWith("/") ? value : undefined;
212
+ }
213
+ /** A FileChange's files as the apply_patch text the patch card draws. */
214
+ function changePatch(changes) {
215
+ const sections = Object.entries(object(changes)).slice(0, 50).map(([file, value]) => {
216
+ const change = object(value), kind = String(change.type ?? "update");
217
+ if (kind === "add") {
218
+ const content = typeof change.content === "string" ? change.content.slice(0, PATCH_FILE).replace(/\n$/, "") : "";
219
+ return `*** Add File: ${file}\n` + content.split("\n").map(line => "+" + line).join("\n");
220
+ }
221
+ if (kind === "delete")
222
+ return `*** Delete File: ${file}`;
223
+ const moved = typeof change.move_path === "string" && change.move_path ? `\n*** Move to: ${change.move_path}` : "";
224
+ const diff = typeof change.unified_diff === "string" ? change.unified_diff.slice(0, PATCH_FILE).replace(/\n$/, "") : "";
225
+ return `*** Update File: ${file}${moved}${diff ? "\n" + diff : ""}`;
226
+ });
227
+ return ["*** Begin Patch", ...sections, "*** End Patch"].join("\n");
228
+ }
229
+ /** An action item as the call the phone draws, carrying its result under
230
+ * `phren_item_output` for the reader to list right after it. Reasoning,
231
+ * messages (already rows of their own) and bookkeeping items stay hidden. */
232
+ function itemCall(raw, item) {
233
+ const id = typeof item.id === "string" && item.id ? item.id.slice(0, 200) : "";
234
+ if (!id)
235
+ return undefined;
236
+ const stamp = raw.timestamp !== undefined ? { timestamp: raw.timestamp } : {};
237
+ const row = (call, output) => ({ type: "response_item", ...stamp, payload: { ...call, call_id: id },
238
+ phren_item_output: { type: "response_item", ...stamp, payload: { ...output, call_id: id } } });
239
+ const status = typeof item.status === "string" ? item.status : "completed";
240
+ switch (item.type) {
241
+ case "CommandExecution": {
242
+ const workdir = localPath(item.cwd);
243
+ const text = [item.aggregated_output, item.formatted_output].find(v => typeof v === "string")
244
+ ?? [item.stdout, item.stderr].filter(v => typeof v === "string").join("");
245
+ const tail = text.slice(-OUTPUT_TAIL);
246
+ const output = typeof item.exit_code === "number" ? JSON.stringify({ output: tail, exit_code: item.exit_code })
247
+ : `${tail}${tail && !tail.endsWith("\n") ? "\n" : ""}[${status}]`;
248
+ return row({ type: "function_call", name: "exec_command", arguments: JSON.stringify({ cmd: commandText(item.command).slice(0, COMMAND), ...(workdir ? { workdir } : {}) }) }, { type: "function_call_output", output });
249
+ }
250
+ case "FileChange": {
251
+ const said = [status === "completed" ? item.stdout : item.stderr, item.stdout, item.stderr].find(v => typeof v === "string" && v.trim());
252
+ return row({ type: "custom_tool_call", name: "apply_patch", input: changePatch(item.changes) }, { type: "custom_tool_call_output", output: (said ?? status).slice(-OUTPUT_TAIL) });
253
+ }
254
+ case "McpToolCall": {
255
+ const result = object(item.result), ok = object(result.Ok ?? result), error = result.Err ?? item.error;
256
+ const text = objects(ok.content).filter(block => block.type === "text" && typeof block.text === "string").map(block => String(block.text)).join("\n");
257
+ const output = text || (error !== undefined && error !== null ? (typeof error === "string" ? error : JSON.stringify(error)) : status);
258
+ const args = typeof item.arguments === "string" ? item.arguments : JSON.stringify(item.arguments ?? {});
259
+ return row({ type: "function_call", name: `mcp__${String(item.server ?? "mcp")}__${String(item.tool ?? "tool")}`, arguments: args.slice(0, 262_144) }, { type: "function_call_output", output: output.slice(0, MCP_OUTPUT) });
260
+ }
261
+ default: return undefined;
262
+ }
263
+ }
103
264
  const CODE_TOOL_CALL = /\btools\s*\.\s*(apply_patch|shell|read)\s*\(/g;
104
265
  const JS_ESCAPES = { n: "\n", r: "\r", t: "\t", b: "\b", f: "\f", v: "\v", "0": "\0", "'": "'", '"': '"', "\\": "\\", "/": "/" };
105
266
  function unescapeJs(value) {
@@ -167,7 +328,9 @@ function callArguments(source, open) {
167
328
  }
168
329
  return undefined;
169
330
  }
170
- function shellCommand(expression, source) {
331
+ /** A string argument: a literal, a string identifier, or one of `keys` in an
332
+ * object literal. */
333
+ function argumentString(expression, source, keys) {
171
334
  const inline = resolveString(expression, source);
172
335
  if (inline !== undefined)
173
336
  return inline;
@@ -177,9 +340,12 @@ function shellCommand(expression, source) {
177
340
  const body = inner.trim();
178
341
  if (/^[A-Za-z_$][\w$]*$/.test(body))
179
342
  return resolveString(body, source);
180
- const property = /(?:^|[,{])\s*(?:command|cmd)\s*:\s*("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`|[A-Za-z_$][\w$]*)/.exec(body);
343
+ const property = new RegExp(`(?:^|[,{])\\s*(?:${keys.join("|")})\\s*:\\s*("(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|\`(?:\\\\.|[^\`\\\\])*\`|[A-Za-z_$][\\w$]*)`).exec(body);
181
344
  return property ? resolveString(property[1], source) : undefined;
182
345
  }
346
+ function shellCommand(expression, source) {
347
+ return argumentString(expression, source, ["command", "cmd"]);
348
+ }
183
349
  /** Every recognized invocation in a code-mode source, in the order written. */
184
350
  export function codeToolCalls(source) {
185
351
  const calls = [], original = source.slice(0, 262_144);
@@ -253,6 +419,15 @@ function renameProjectedChanges(raw, base) {
253
419
  export function projectCodexRow(raw) {
254
420
  if (raw.type !== "response_item")
255
421
  return { rows: [raw] };
422
+ if (raw.phren_item_output !== undefined) {
423
+ // An item's call and result, or a failed script listed with its result.
424
+ // Only the script is source to project; an item's patch text is not.
425
+ const { phren_item_output: output, ...call } = raw, result = object(output);
426
+ const expanded = object(call.payload).name === "exec" ? projectCodexRow(call) : { rows: [call] };
427
+ if (!expanded.base)
428
+ return { rows: [...expanded.rows, result] };
429
+ return { rows: [...expanded.rows, { ...result, payload: { ...object(result.payload), call_id: `${expanded.base}:1` } }] };
430
+ }
256
431
  const payload = object(raw.payload), type = String(payload.type), callId = typeof payload.call_id === "string" ? payload.call_id : "";
257
432
  if (type === "custom_tool_call" || type === "function_call") {
258
433
  const source = codeToolSource(payload.input ?? payload.arguments);
@@ -9,7 +9,7 @@ import { materializeCodexThread, materializedRoot } from "./codex-threads.js";
9
9
  import { namedPaths, SHELL_TOOLS, outputCallIds } from "./changes.js";
10
10
  import { fanoutChildren } from "./fanouts.js";
11
11
  import { claudeChildAgents, visibleClaudeEvent } from "./transcript-claude.js";
12
- import { childTranscriptBelongsTo, directChildAgents, projectCodexRow, rewriteProjectedOutput, visibleCodexEvent } from "./transcript-codex.js";
12
+ import { childTranscriptBelongsTo, codeModeOutputCall, directChildAgents, findCodeModeCall, projectCodeModeOutput, projectCodexRow, rewriteProjectedOutput, visibleCodexEvent } from "./transcript-codex.js";
13
13
  import { visibleCopilotEvent } from "./transcript-copilot.js";
14
14
  import { visibleOpencodeEvent } from "./transcript-opencode.js";
15
15
  export { isNarration, unwrapPastedContent } from "./transcript-claude.js";
@@ -285,6 +285,11 @@ export class TranscriptReader {
285
285
  const { isSidechain: _sidechain, ...own } = raw;
286
286
  raw = own;
287
287
  }
288
+ // A code-mode script's result follows from the script it answers,
289
+ // a few rows earlier: hidden when its items carry the actions.
290
+ const codeModeCall = raw && this.source === "codex" ? codeModeOutputCall(raw) : undefined;
291
+ if (raw && codeModeCall)
292
+ raw = projectCodeModeOutput(raw, await findCodeModeCall((upper, lower) => index.rows(handle, upper, lower, signal), row.line, codeModeCall));
288
293
  if (raw) {
289
294
  if (this.changes && this.imageLine === undefined) {
290
295
  // A shell call's output carries what it changed on disk. While
@@ -9,6 +9,8 @@ export interface UsageWindow {
9
9
  limitUSD?: number;
10
10
  usedTokens?: number;
11
11
  resetsAt?: string;
12
+ /** The service says this window is refusing requests now (OpenCode Go's `rate-limited`). */
13
+ limited?: boolean;
12
14
  asOf?: string;
13
15
  }
14
16
  export interface UsageSpend {
@@ -16,7 +18,7 @@ export interface UsageSpend {
16
18
  period: "rolling_7_days" | "rolling_30_days" | "calendar_week";
17
19
  }
18
20
  export interface AccountUsage {
19
- source: "codex" | "claude" | "opencode" | "opencode-go" | "openrouter";
21
+ source: "codex" | "claude" | "opencode" | "opencode-go" | "openrouter" | "copilot";
20
22
  windows: UsageWindow[];
21
23
  updatedAt?: string;
22
24
  message?: string;
@@ -39,26 +41,32 @@ export declare function openCodeFailure(error: unknown): string;
39
41
  export declare function readOpenRouterKey(): Promise<string | undefined>;
40
42
  /** OpenCode Go's key stays local and is sent only to the Go gateway. */
41
43
  export declare function readOpenCodeGoKey(): Promise<string | undefined>;
42
- type GoPeriod = "5h" | "7d" | "30d";
43
- type GoLimit = {
44
- limitUSD: number;
45
- resetsAt?: string;
46
- };
47
- type GoLimits = Map<string, Partial<Record<GoPeriod, GoLimit>>>;
48
- type GoTotals = Map<string, Record<GoPeriod, {
49
- usedUSD: number;
50
- usedTokens: number;
51
- }>>;
52
- /** Best-effort gateway discovery. All four requests are independent because
53
- * undocumented routes vary by OpenCode release and account. */
54
- export declare function fetchOpenCodeGoLimits(key: string, fetchImpl?: typeof fetch): Promise<GoLimits>;
55
- /** Sum only completed OpenCode Go fan-outs. Their ledger stays on the
56
- * computer and malformed jobs are ignored rather than becoming usage. */
57
- export declare function readOpenCodeGoLedger(root?: string, now?: Date): Promise<GoTotals>;
44
+ /**
45
+ * Go's own report of the plan, `GET /zen/go/v1/usage`:
46
+ * `{usage: {rolling|weekly|monthly: {status, percent, resetsAt}}}`. It is
47
+ * account-wide, so it already counts every computer's use, and it is what
48
+ * Go enforces: `status: "rate-limited"` is the window that refuses requests.
49
+ * It carries no dollar amounts, so none are shown.
50
+ */
51
+ export declare function openCodeGoPlan(value: unknown): UsageWindow[];
52
+ export declare function fetchOpenCodeGoPlan(key: string, fetchImpl?: typeof fetch): Promise<UsageWindow[]>;
53
+ export interface GoRefusals {
54
+ count: number;
55
+ first: string;
56
+ last: string;
57
+ models: string[];
58
+ }
59
+ /** "Go usage limit exceeded" refusals in OpenCode's own log over the last
60
+ * `withinMs`. The first read of a log covers at most its last 64 MB. */
61
+ export declare function readGoRefusals(now?: Date, withinMs?: number, root?: string): Promise<GoRefusals | undefined>;
62
+ export declare function openCodeGoUsage(windows: UsageWindow[], refusals: GoRefusals | undefined, now: Date, hasKey: boolean, planError?: boolean): AccountUsage;
63
+ /** The accounts one caller can read: the sources it names, and Go's plan
64
+ * windows only for a caller that asked for them (`goPlan=1`). */
65
+ export declare function usageForCaller(accounts: AccountUsage[], sources: Set<string>, goPlan: boolean): AccountUsage[];
58
66
  export declare function readOpenCodeGoUsage(now?: Date, options?: {
59
- root?: string;
60
67
  readKey?: () => Promise<string | undefined>;
61
68
  fetchImpl?: typeof fetch;
69
+ readRefusals?: (now: Date) => Promise<GoRefusals | undefined>;
62
70
  }): Promise<AccountUsage>;
63
71
  /** OpenRouter reports the current UTC calendar week's charged usage per key. */
64
72
  export declare function fetchOpenRouterUsage(key: string, fetchImpl?: typeof fetch, now?: Date): Promise<AccountUsage>;
@@ -95,6 +103,14 @@ export declare function readClaudeToken(execSecurity?: typeof execFile.__promisi
95
103
  export declare function fetchClaudeUsage(token: string, fetchImpl?: typeof fetch, now?: Date): Promise<AccountUsage>;
96
104
  /** Only initialize and read limits. Never create a thread, prompt, or login. */
97
105
  export declare function readCodexLimits(executable?: string): Promise<AccountUsage>;
106
+ /**
107
+ * GitHub Copilot's own quota report (`gh api /copilot_internal/user`): one
108
+ * window per limited quota (premium requests, usually) with the monthly
109
+ * reset. Unlimited quotas are named in the message, not drawn as 0%.
110
+ */
111
+ export declare function copilotUsage(value: unknown, now?: Date): AccountUsage;
112
+ /** Reads through the GitHub CLI's own sign-in; the token never reaches Phren. */
113
+ export declare function readCopilotUsage(now?: Date, run?: (file: string, args: string[]) => Promise<string>): Promise<AccountUsage>;
98
114
  export declare class AccountUsageReader {
99
115
  private readCodex;
100
116
  private now;
@@ -102,13 +118,14 @@ export declare class AccountUsageReader {
102
118
  private readOpenCode;
103
119
  private readOpenRouter;
104
120
  private readOpenCodeGo;
121
+ private readCopilot;
105
122
  private cached?;
106
123
  private pending?;
107
124
  private claudeCached?;
108
125
  private claudePending?;
109
126
  private spendingCached?;
110
127
  private spendingPending?;
111
- constructor(readCodex?: typeof readCodexLimits, now?: () => number, readClaudeLive?: (now: Date) => Promise<AccountUsage | undefined>, readOpenCode?: (now: Date) => Promise<AccountUsage>, readOpenRouter?: (now: Date) => Promise<AccountUsage | undefined>, readOpenCodeGo?: (now: Date) => Promise<AccountUsage>);
128
+ constructor(readCodex?: typeof readCodexLimits, now?: () => number, readClaudeLive?: (now: Date) => Promise<AccountUsage | undefined>, readOpenCode?: (now: Date) => Promise<AccountUsage>, readOpenRouter?: (now: Date) => Promise<AccountUsage | undefined>, readOpenCodeGo?: (now: Date) => Promise<AccountUsage>, readCopilot?: (now: Date) => Promise<AccountUsage>);
112
129
  read(): Promise<{
113
130
  accounts: AccountUsage[];
114
131
  }>;
@@ -121,4 +138,3 @@ export declare class AccountUsageReader {
121
138
  /** Wrap an existing status line, preserving its input, output and options. */
122
139
  export declare function usageStatusLine(current: unknown, program: string, remove: boolean): unknown;
123
140
  export declare function captureClaudeUsage(original: string): Promise<void>;
124
- export {};