@phren/cli 0.3.59 → 0.3.61

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.
@@ -1,7 +1,7 @@
1
1
  import { type NotLinkedComputer } from "./hand-off.js";
2
2
  import { type HookPeer } from "./peers.js";
3
3
  import { type Json } from "./protocol.js";
4
- import { NEAR_LIMIT_LEFT, type AccountUsage, type Subscription, type UsageCredits, type UsageWindow } from "./usage.js";
4
+ import { NEAR_LIMIT_LEFT, type AccountUsage, type ApiCredit, type Subscription, type UsageCredits, type UsageWindow } from "./usage.js";
5
5
  export { NEAR_LIMIT_LEFT };
6
6
  /**
7
7
  * Every computer's agent usage merged by account, for a conductor choosing
@@ -44,6 +44,9 @@ export interface AccountWindow {
44
44
  exhausted?: true;
45
45
  usedUSD?: number;
46
46
  limitUSD?: number;
47
+ /** An API credit window: dollars left and its expiry. */
48
+ remainingUSD?: number;
49
+ expiresAt?: string;
47
50
  }
48
51
  export interface AccountUsageRow {
49
52
  /** `source` or `source|key`, as the phone keys its cards. */
@@ -53,9 +56,9 @@ export interface AccountUsageRow {
53
56
  /** The login's email, else the account's label, when the Hook names one. */
54
57
  account?: string;
55
58
  windows: AccountWindow[];
56
- /** Least room on any window with a percent; `limited` counts as 0. */
59
+ /** Least room on any window with a percent, the API credits counted as one balance; `limited` counts as 0. */
57
60
  leftPercent?: number;
58
- /** Under 20% left on some window. Information, not a reason to avoid the account. */
61
+ /** Under 20% left on some window or the credits together. Information, not a reason to avoid the account. */
59
62
  nearLimit: boolean;
60
63
  /** A window is at 100% or refusing requests: never dispatch to it until `availableIn`. */
61
64
  exhausted: boolean;
@@ -68,6 +71,8 @@ export interface AccountUsageRow {
68
71
  subscription?: Subscription;
69
72
  /** Codex's credit balance from the newest report that has one. */
70
73
  credits?: UsageCredits;
74
+ /** A Claude account's entered API credits added up over its unexpired credit windows (an estimate). */
75
+ apiCredit?: ApiCredit;
71
76
  updatedAt?: string;
72
77
  /** How old the standing report is, as "4m" or "2d 3h". */
73
78
  age?: string;
@@ -111,7 +116,7 @@ export declare function ageText(ms: number): string;
111
116
  export declare function accountIdentity(usage: AccountUsage, computer: string): string;
112
117
  /** Percent used and left, with a passed reset reported as reset rather than as its old percent. */
113
118
  export declare function settleWindow(window: UsageWindow, now: number): AccountWindow;
114
- /** Least room across an account's windows, undefined when none has a percent. */
119
+ /** Least room across an account's windows, its API credits counted as one; undefined when none has a percent. */
115
120
  export declare function roomLeft(windows: readonly AccountWindow[]): number | undefined;
116
121
  export interface NamedAccount {
117
122
  labels: readonly string[];
@@ -144,5 +149,7 @@ export declare function readAccountUsage(options?: ReadAccountUsageOptions): Pro
144
149
  export declare function usageSummary(view: AccountUsageView): string;
145
150
  /** "5-hour 82% left (resets in 2h 10m), weekly 64% left (resets in 3d 4h)": what launch and failover rank Claude accounts by. */
146
151
  export declare function claudeRoom(row: Pick<AccountUsageRow, "windows">): string;
152
+ /** "about $142.50 left of $200.00, the soonest expires 2026-12-31". */
153
+ export declare function apiCreditText(credit: ApiCredit): string;
147
154
  /** `phren dispatch usage` without --json. */
148
155
  export declare function formatAccountUsage(view: AccountUsageView): string;
@@ -3,6 +3,7 @@ import { creditsText, HARNESS_NAMES, resetsIn, USAGE_SOURCES } from "../computer
3
3
  import { hookRequest } from "./client.js";
4
4
  import { notLinkedFrom } from "./hand-off.js";
5
5
  import { optionalHookPeers, peerRequest } from "./peers.js";
6
+ import { creditSummary } from "./claude-credits.js";
6
7
  import { errorCode, object } from "./protocol.js";
7
8
  import { NEAR_LIMIT_LEFT, windowExhausted, windowLeft } from "./usage.js";
8
9
  export { NEAR_LIMIT_LEFT };
@@ -76,11 +77,38 @@ export function settleWindow(window, now) {
76
77
  out.usedUSD = window.usedUSD;
77
78
  if (window.limitUSD !== undefined)
78
79
  out.limitUSD = window.limitUSD;
80
+ // A credit's expiry is its `resetsAt`; an older Hook sends only that.
81
+ const credit = window.id.startsWith("credit:");
82
+ const remaining = window.remainingUSD ?? (credit && window.usedUSD !== undefined && window.limitUSD !== undefined
83
+ ? Math.round(Math.max(0, window.limitUSD - window.usedUSD) * 100) / 100 : undefined);
84
+ const expiresAt = window.expiresAt ?? (credit ? window.resetsAt : undefined);
85
+ if (remaining !== undefined)
86
+ out.remainingUSD = remaining;
87
+ if (expiresAt !== undefined)
88
+ out.expiresAt = expiresAt;
79
89
  return out;
80
90
  }
81
- /** Least room across an account's windows, undefined when none has a percent. */
91
+ const isCredit = (window) => window.id.startsWith("credit:");
92
+ const finite = (value) => typeof value === "number" && Number.isFinite(value);
93
+ /** The room in an account's API credits, one balance as capacityRoom counts them: the credits with a percent
94
+ * pool, their limits and spend summed. */
95
+ function creditRoom(windows) {
96
+ const credit = windows.filter(w => isCredit(w) && w.leftPercent !== undefined);
97
+ if (!credit.length)
98
+ return undefined;
99
+ if (credit.every(w => finite(w.usedUSD) && finite(w.limitUSD))) {
100
+ const limit = credit.reduce((sum, w) => sum + w.limitUSD, 0), used = credit.reduce((sum, w) => sum + w.usedUSD, 0);
101
+ return limit > 0 ? Math.max(0, Math.min(100, Math.round((limit - used) / limit * 100))) : 0;
102
+ }
103
+ const lefts = credit.map(w => w.leftPercent).filter((value) => value !== undefined);
104
+ return lefts.length ? Math.max(...lefts) : undefined;
105
+ }
106
+ /** Least room across an account's windows, its API credits counted as one; undefined when none has a percent. */
82
107
  export function roomLeft(windows) {
83
- const known = windows.map(w => w.leftPercent).filter((value) => value !== undefined);
108
+ const known = windows.filter(w => !isCredit(w)).map(w => w.leftPercent).filter((value) => value !== undefined);
109
+ const credit = creditRoom(windows);
110
+ if (credit !== undefined)
111
+ known.push(credit);
84
112
  return known.length ? Math.min(...known) : undefined;
85
113
  }
86
114
  function accountName(usage) {
@@ -167,13 +195,19 @@ export function mergeAccountUsage(reports, now = Date.now()) {
167
195
  const subscription = subscriptions.sort((a, b) => (date(b.usage.subscription?.checkedAt) || date(b.usage.updatedAt) || 0) - (date(a.usage.subscription?.checkedAt) || date(a.usage.updatedAt) || 0))[0]?.usage.subscription;
168
196
  const withWindows = reporting.filter(item => item.usage.windows.length);
169
197
  const standing = (withWindows.length ? withWindows : reporting).reduce(newer);
170
- const windows = mergedWindows(withWindows).map(window => settleWindow(window, now));
198
+ // A credit that expired since its report is gone, not reset.
199
+ const windows = mergedWindows(withWindows).filter(window => !(window.id.startsWith("credit:") && date(window.expiresAt ?? window.resetsAt) <= now))
200
+ .map(window => settleWindow(window, now));
201
+ const apiCredit = creditSummary(windows);
171
202
  const spend = mergedSpend(source, reporting);
172
203
  const withCredits = reporting.filter(item => item.usage.credits);
173
204
  const credits = withCredits.length ? withCredits.reduce(newer).usage.credits : undefined;
174
205
  const updated = date(standing.usage.updatedAt);
175
206
  const leftPercent = roomLeft(windows);
176
- const exhausted = windows.filter(w => w.exhausted);
207
+ // An account's API credits are one balance, as capacityRoom counts them: a spent credit exhausts the
208
+ // account only when every credit is spent.
209
+ const creditSpent = windows.filter(w => w.id.startsWith("credit:")).every(w => w.exhausted);
210
+ const exhausted = windows.filter(w => w.exhausted && (!w.id.startsWith("credit:") || creditSpent));
177
211
  // A credit's date is when it expires, not when it comes back.
178
212
  const availableAt = exhausted.filter(w => !w.id.startsWith("credit:")).map(w => w.resetsAt).filter((value) => Boolean(value)).sort().at(-1);
179
213
  const availableIn = availableAt ? resetsIn(availableAt, now) : undefined;
@@ -188,6 +222,7 @@ export function mergeAccountUsage(reports, now = Date.now()) {
188
222
  ...(spend ? { spend } : {}),
189
223
  ...(subscription ? { subscription } : {}),
190
224
  ...(credits ? { credits } : {}),
225
+ ...(apiCredit ? { apiCredit } : {}),
191
226
  ...(standing.usage.updatedAt ? { updatedAt: standing.usage.updatedAt } : {}),
192
227
  ...(Number.isFinite(updated) ? { age: ageText(now - updated) } : {}),
193
228
  stale: !Number.isFinite(updated) || now - updated > STALE_AFTER_MS || windows.some(w => w.reset),
@@ -287,13 +322,16 @@ export function usageSummary(view) {
287
322
  parts.push(`Out of quota, do not dispatch to: ${out.map(row => `${title(row)}${row.availableIn ? ` (back in ${row.availableIn})` : ""}`).join("; ")}.`);
288
323
  const near = view.accounts.filter(row => row.nearLimit && !row.exhausted);
289
324
  if (near.length)
290
- parts.push(`Low but usable: ${near.map(row => `${title(row)} (${row.leftPercent ?? 0}% left${tightest(row)?.resetsIn ? `, resets in ${tightest(row).resetsIn}` : ""})`).join("; ")}.`);
325
+ parts.push(`Low but usable: ${near.map(row => `${title(row)} (${row.leftPercent ?? 0}% left${tightestChange(row) ? `, ${tightestChange(row)}` : ""})`).join("; ")}.`);
291
326
  const limitedRows = view.accounts.filter(row => row.leftPercent !== undefined || row.exhausted);
292
327
  if (limitedRows.length && limitedRows.every(row => row.exhausted))
293
328
  parts.push("Every account with limits is out of quota: tell the owner before dispatching.");
294
329
  const claude = view.accounts.filter(row => row.harness === "claude" && claudeRoom(row));
295
330
  if (claude.length)
296
331
  parts.push(`Claude room: ${claude.map(row => `${title(row)} ${claudeRoom(row)}`).join("; ")}.`);
332
+ const credit = view.accounts.filter(row => row.apiCredit);
333
+ if (credit.length)
334
+ parts.push(`API credit: ${credit.map(row => `${title(row)} ${apiCreditText(row.apiCredit)}`).join("; ")}.`);
297
335
  const stale = view.accounts.filter(row => row.stale);
298
336
  if (stale.length)
299
337
  parts.push(`Stale: ${stale.map(row => `${title(row)} (${row.windows.some(w => w.reset) ? "a window reset since its report" : `reported ${row.age ? ago(row.age) : "at an unknown time"}`})`).join("; ")}.`);
@@ -315,8 +353,21 @@ export function claudeRoom(row) {
315
353
  };
316
354
  return [part("five_hour", "5-hour"), part("seven_day", "weekly")].filter(Boolean).join(", ");
317
355
  }
318
- function tightest(row) {
319
- return row.windows.filter(w => w.leftPercent !== undefined).sort((a, b) => a.leftPercent - b.leftPercent)[0];
356
+ /** "about $142.50 left of $200.00, the soonest expires 2026-12-31". */
357
+ export function apiCreditText(credit) {
358
+ return `about $${credit.remainingUSD.toFixed(2)} left of $${credit.limitUSD.toFixed(2)}${credit.expiresAt ? `, the soonest expires ${credit.expiresAt.slice(0, 10)}` : ""}`;
359
+ }
360
+ /** When the tightest room changes: a window's reset, or, when the API credits are tightest, the soonest expiry
361
+ * among credits with money left (a credit's expiry is not a reset, and a spent one's says nothing). */
362
+ function tightestChange(row) {
363
+ const window = row.windows.filter(w => !isCredit(w) && w.leftPercent !== undefined).sort((a, b) => a.leftPercent - b.leftPercent)[0];
364
+ const credit = creditRoom(row.windows);
365
+ if (credit !== undefined && (window === undefined || credit < window.leftPercent)) {
366
+ const soonest = row.windows.filter(w => isCredit(w) && w.resetsIn && (w.remainingUSD ?? 0) > 0)
367
+ .sort((a, b) => (a.expiresAt ?? a.resetsAt ?? "").localeCompare(b.expiresAt ?? b.resetsAt ?? ""))[0];
368
+ return soonest ? `credit expires in ${soonest.resetsIn}` : undefined;
369
+ }
370
+ return window?.resetsIn ? `resets in ${window.resetsIn}` : undefined;
320
371
  }
321
372
  /** `phren dispatch usage` without --json. */
322
373
  export function formatAccountUsage(view) {
@@ -338,6 +389,8 @@ export function formatAccountUsage(view) {
338
389
  const used = w.reset ? "reset, no new report" : w.usedPercent !== undefined ? `${w.usedPercent}% used${w.leftPercent !== undefined ? `, ${w.leftPercent}% left` : ""}` : w.usedUSD !== undefined ? `$${w.usedUSD.toFixed(2)}${w.limitUSD !== undefined ? ` of $${w.limitUSD.toFixed(2)}` : ""}` : "";
339
390
  lines.push(` ${w.name.padEnd(30)} ${used.padEnd(22)}${w.limited ? "limited now " : ""}${w.resetsIn ? `resets in ${w.resetsIn}${w.resetsAt ? ` (${w.resetsAt.slice(0, 16).replace("T", " ")} UTC)` : ""}` : ""}`.trimEnd());
340
391
  }
392
+ if (row.apiCredit && row.windows.filter(w => w.id.startsWith("credit:")).length > 1)
393
+ lines.push(` ${"API credit, all".padEnd(30)} ${apiCreditText(row.apiCredit)}`);
341
394
  if (row.credits?.hasCredits)
342
395
  lines.push(` credits${" ".repeat(24)}${creditsText(row.credits)}`);
343
396
  if (row.spend)
@@ -1,5 +1,5 @@
1
1
  import { type ClaudeHome } from "./claude-accounts.js";
2
- import type { UsageWindow } from "./usage.js";
2
+ import type { ApiCredit, UsageWindow } from "./usage.js";
3
3
  export interface ClaudeCredit {
4
4
  /** Short id derived from the entry, for `--remove`. */
5
5
  id: string;
@@ -45,3 +45,5 @@ export declare function homeSessionCosts(home: ClaudeHome): Record<string, Sessi
45
45
  * Expired credits are left out. The window's `resetsAt` is the expiry.
46
46
  */
47
47
  export declare function creditWindows(credits: readonly ClaudeCredit[], sessions: Record<string, SessionCost>, now?: Date): UsageWindow[];
48
+ /** The credit windows added up: dollars left and the soonest expiry among those with money left. None: undefined. */
49
+ export declare function creditSummary(windows: ReadonlyArray<Pick<UsageWindow, "id" | "usedUSD" | "limitUSD" | "remainingUSD" | "expiresAt">>): ApiCredit | undefined;
@@ -237,8 +237,21 @@ export function creditWindows(credits, sessions, now = new Date()) {
237
237
  const usedUSD = round(used.get(credit.id));
238
238
  return {
239
239
  id: `credit:${credit.id}`, name: `API credit${credit.label ? ` · ${credit.label}` : ""}, estimate`,
240
- usedUSD, limitUSD: credit.amountUSD, usedPercent: Math.min(100, Math.round(usedUSD / credit.amountUSD * 100)),
241
- ...(credit.expiresAt ? { resetsAt: credit.expiresAt } : {}), asOf: now.toISOString(),
240
+ usedUSD, limitUSD: credit.amountUSD, remainingUSD: round(Math.max(0, credit.amountUSD - usedUSD)),
241
+ usedPercent: Math.min(100, Math.round(usedUSD / credit.amountUSD * 100)),
242
+ ...(credit.expiresAt ? { resetsAt: credit.expiresAt, expiresAt: credit.expiresAt } : {}), asOf: now.toISOString(),
242
243
  };
243
244
  });
244
245
  }
246
+ /** The credit windows added up: dollars left and the soonest expiry among those with money left. None: undefined. */
247
+ export function creditSummary(windows) {
248
+ const credit = windows.filter(window => window.id.startsWith("credit:") && typeof window.limitUSD === "number" && typeof window.usedUSD === "number");
249
+ if (!credit.length)
250
+ return undefined;
251
+ const round = (value) => Math.round(value * 100) / 100;
252
+ const sum = (pick) => round(credit.reduce((total, window) => total + pick(window), 0));
253
+ const expiresAt = credit.filter(window => window.expiresAt && (window.remainingUSD ?? window.limitUSD - window.usedUSD) > 0)
254
+ .map(window => window.expiresAt).sort()[0];
255
+ return { remainingUSD: sum(window => Math.max(0, window.remainingUSD ?? window.limitUSD - window.usedUSD)), limitUSD: sum(window => window.limitUSD),
256
+ usedUSD: sum(window => window.usedUSD), ...(expiresAt ? { expiresAt } : {}), estimate: true };
257
+ }
@@ -145,7 +145,8 @@ async function materializeThread(session) {
145
145
  && state.turnSignature === turnSignature)
146
146
  return file;
147
147
  const pending = pendingMessage(history, session);
148
- const rows = objects(history.prepare("select rollout_ordinal, item_type, item_json, updated_at_ordinal from thread_items where thread_id = ? order by rollout_ordinal limit ?").all(session, MAX_ITEMS));
148
+ const rows = itemRows(history, session);
149
+ const stamps = turnStarts(history, session);
149
150
  const lines = [];
150
151
  if (fresh) {
151
152
  const meta = await threadMeta(session);
@@ -191,7 +192,8 @@ async function materializeThread(session) {
191
192
  continue;
192
193
  }
193
194
  else if (messageRow(item)) {
194
- const message = messageRow(item);
195
+ const at = rowTime(row, item, stamps);
196
+ const message = { ...messageRow(item), ...(at ? { timestamp: at } : {}) };
195
197
  const queued = item.type === "userMessage" && item.status === "queued";
196
198
  lines.push(JSON.stringify(queued ? { ...message, phrenQueued: true, phrenQueueKey: queueKey(session, id) } : message));
197
199
  // A question the agent asked (delivered async) rides along as the
@@ -243,6 +245,52 @@ async function materializeThread(session) {
243
245
  history.close();
244
246
  }
245
247
  }
248
+ /** The thread's items in order, with when each was created where the store records it (`created_at_ms`, absent
249
+ * from some stores) and its turn. */
250
+ function itemRows(history, session) {
251
+ try {
252
+ return objects(history.prepare("select rollout_ordinal, item_type, item_json, updated_at_ordinal, turn_id, created_at_ms from thread_items where thread_id = ? order by rollout_ordinal limit ?").all(session, MAX_ITEMS));
253
+ }
254
+ catch {
255
+ try {
256
+ return objects(history.prepare("select rollout_ordinal, item_type, item_json, updated_at_ordinal, turn_id from thread_items where thread_id = ? order by rollout_ordinal limit ?").all(session, MAX_ITEMS));
257
+ }
258
+ catch {
259
+ return objects(history.prepare("select rollout_ordinal, item_type, item_json, updated_at_ordinal from thread_items where thread_id = ? order by rollout_ordinal limit ?").all(session, MAX_ITEMS));
260
+ }
261
+ }
262
+ }
263
+ /** When each of the thread's turns started, in milliseconds; empty when the store cannot say. */
264
+ function turnStarts(history, session) {
265
+ const starts = new Map();
266
+ try {
267
+ for (const turn of objects(history.prepare("select turn_id, started_at from thread_turns where thread_id = ?").all(session))) {
268
+ const started = epochMs(turn.started_at);
269
+ if (started)
270
+ starts.set(String(turn.turn_id), started);
271
+ }
272
+ }
273
+ catch { /* no turns table */ }
274
+ return starts;
275
+ }
276
+ /** Seconds or milliseconds since the epoch, as milliseconds; undefined for anything else. */
277
+ function epochMs(value) {
278
+ const number = Number(value);
279
+ if (value === null || value === undefined || !Number.isFinite(number) || number <= 0)
280
+ return undefined;
281
+ return number > 1e12 ? number : number * 1000;
282
+ }
283
+ /**
284
+ * A materialized row's `timestamp`, as a rollout row carries one: when its item was created. The Hook settles a
285
+ * phone message only from rows stamped after it was typed, so an older identical message (an earlier "yes") is
286
+ * never taken for a new one. A user row the store keeps no creation time for has no stamp: its turn's start
287
+ * would be older than a steer typed during the turn, which the scan would then drop; unstamped, its position
288
+ * after the message's cursor decides, as before. An assistant row falls back to its turn's start.
289
+ */
290
+ function rowTime(row, item, turns) {
291
+ const at = epochMs(row.created_at_ms) ?? (item.type === "userMessage" || row.turn_id === undefined ? undefined : turns.get(String(row.turn_id)));
292
+ return at ? new Date(at).toISOString() : undefined;
293
+ }
246
294
  /** Codex 0.155 stores a child agent's lifecycle as `subAgentActivity` items
247
295
  * with camelCase fields; the rollout shape the child tree parses is the
248
296
  * `SubAgentActivity` event with snake_case fields. */
@@ -51,4 +51,36 @@ export declare function launchContinuation(input: unknown, launch: (data: z.infe
51
51
  }): Promise<Json>;
52
52
  export declare function saveContinuationIntent(input: Json): Promise<void>;
53
53
  export declare function continuationIntent(id: string): Promise<Json>;
54
+ /**
55
+ * The whole conversation a summary-by-target move copies to the receiving Hook, beside its intent: the source's
56
+ * prompts and replies, already redacted the way a peer hand-off is. The brief only has room for its newest turns;
57
+ * the receiving launch pulls this through the same intent route, in pages, and puts it in the new agent's brief
58
+ * folder. A Hook that predates it ignores the page parameter and answers with the intent, which has no
59
+ * `conversation`, so either side being older leaves the excerpt alone.
60
+ */
61
+ export declare const CONVERSATION_LIMIT = 2000000;
62
+ export declare const CONVERSATION_FILE = "conversation.md";
63
+ /** In a summary-by-target brief's opening line, so the receiving launch asks for a copy only for those moves. */
64
+ export declare const CONVERSATION_MARKER = "Phren copied its conversation instead";
65
+ /**
66
+ * Removes the saved conversations no move needs any more, as `done` decides from the move id and the copy's age
67
+ * (the move moved or failed, or it has no record at all), and any older than `maxAgeMs` whatever `done` says.
68
+ * A destination reads a copy only while its launch runs, which is over once the move is moved or failed. A write
69
+ * a crash left behind (`<copy>.<uuid>.tmp`) goes after an hour. Returns the move ids whose copy was removed.
70
+ */
71
+ export declare function pruneContinuationConversations(done: (id: string, ageMs: number) => boolean | Promise<boolean>, now?: number, maxAgeMs?: number): Promise<string[]>;
72
+ /** How long a copy with no move record (or a write a crash left) is kept: a move in another process records itself first. */
73
+ export declare const ORPHAN_GRACE_MS: number;
74
+ /** Saved once per move: a run of the move that starts again keeps the first copy, which a destination may be part way through reading. */
75
+ export declare function saveContinuationConversation(id: string, text: string): Promise<void>;
76
+ /** One page of the saved conversation from character `offset`, with its whole length and hash to check against. */
77
+ export declare function continuationConversationPage(id: string, offset: number): Promise<Json>;
78
+ /**
79
+ * The receiving side: every page of the source's conversation through `page(offset)`, checked against its length
80
+ * and hash and redacted again here, or undefined when the source has none (an older Hook, a move that never
81
+ * built one) or it does not arrive whole. Never fails the launch: the brief's excerpt stands on its own.
82
+ */
83
+ export declare function fetchContinuationConversation(page: (offset: number) => Promise<Json>, redact: (text: string) => string): Promise<string | undefined>;
84
+ /** Where the copied conversation is, to tell the new agent; appended only when the brief has room for it. */
85
+ export declare function withConversationPointer(text: string, file: string, limit?: number): string;
54
86
  export {};
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import { readFile } from "node:fs/promises";
2
+ import { lstat, readdir, readFile, rm, stat } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { z } from "zod";
5
5
  import { atomicInPrivateDir, BridgeError, bridgeRoot } from "./protocol.js";
@@ -104,3 +104,114 @@ export async function continuationIntent(id) {
104
104
  throw new BridgeError(404, "No owner-admitted continuation intent is recorded.");
105
105
  }
106
106
  }
107
+ /**
108
+ * The whole conversation a summary-by-target move copies to the receiving Hook, beside its intent: the source's
109
+ * prompts and replies, already redacted the way a peer hand-off is. The brief only has room for its newest turns;
110
+ * the receiving launch pulls this through the same intent route, in pages, and puts it in the new agent's brief
111
+ * folder. A Hook that predates it ignores the page parameter and answers with the intent, which has no
112
+ * `conversation`, so either side being older leaves the excerpt alone.
113
+ */
114
+ export const CONVERSATION_LIMIT = 2_000_000;
115
+ const CONVERSATION_PAGE = 262_144;
116
+ /** Under the 1 MiB a Hook reads of one peer answer (client.ts), escaped as JSON. */
117
+ const PAGE_BYTES = 900_000;
118
+ const conversationFile = (id) => path.join(bridgeRoot(), "move-intents", `${z.string().uuid().parse(id)}.conversation.md`);
119
+ export const CONVERSATION_FILE = "conversation.md";
120
+ /** In a summary-by-target brief's opening line, so the receiving launch asks for a copy only for those moves. */
121
+ export const CONVERSATION_MARKER = "Phren copied its conversation instead";
122
+ /**
123
+ * Removes the saved conversations no move needs any more, as `done` decides from the move id and the copy's age
124
+ * (the move moved or failed, or it has no record at all), and any older than `maxAgeMs` whatever `done` says.
125
+ * A destination reads a copy only while its launch runs, which is over once the move is moved or failed. A write
126
+ * a crash left behind (`<copy>.<uuid>.tmp`) goes after an hour. Returns the move ids whose copy was removed.
127
+ */
128
+ export async function pruneContinuationConversations(done, now = Date.now(), maxAgeMs = 7 * 24 * 60 * 60 * 1000) {
129
+ const root = path.join(bridgeRoot(), "move-intents");
130
+ const names = await readdir(root).catch(() => []);
131
+ const removed = [];
132
+ for (const name of names) {
133
+ const match = /^([0-9a-f-]{36})\.conversation\.md(\.[0-9a-f-]{36}\.tmp)?$/i.exec(name);
134
+ if (!match)
135
+ continue;
136
+ const file = path.join(root, name);
137
+ const info = await lstat(file).catch(() => undefined);
138
+ if (!info?.isFile())
139
+ continue;
140
+ const age = now - info.mtimeMs;
141
+ const remove = match[2] ? age > ORPHAN_GRACE_MS : age > maxAgeMs || await done(match[1], age);
142
+ if (remove)
143
+ await rm(file, { force: true }).then(() => { if (!match[2])
144
+ removed.push(match[1]); }, () => undefined);
145
+ }
146
+ return removed;
147
+ }
148
+ /** How long a copy with no move record (or a write a crash left) is kept: a move in another process records itself first. */
149
+ export const ORPHAN_GRACE_MS = 60 * 60 * 1000;
150
+ /** Saved once per move: a run of the move that starts again keeps the first copy, which a destination may be part way through reading. */
151
+ export async function saveContinuationConversation(id, text) {
152
+ if (text.length > CONVERSATION_LIMIT)
153
+ throw new BridgeError(413, "The conversation is too long to copy.");
154
+ if (await stat(conversationFile(id)).catch(() => undefined))
155
+ return;
156
+ await atomicInPrivateDir(conversationFile(id), text);
157
+ }
158
+ /** One page of the saved conversation from character `offset`, with its whole length and hash to check against. */
159
+ export async function continuationConversationPage(id, offset) {
160
+ let text;
161
+ try {
162
+ text = await readFile(conversationFile(id), "utf8");
163
+ }
164
+ catch {
165
+ throw new BridgeError(404, "No conversation is recorded for this move.");
166
+ }
167
+ if (!Number.isInteger(offset) || offset < 0 || offset > text.length)
168
+ throw new BridgeError(400, "Invalid conversation offset.");
169
+ let size = Math.min(CONVERSATION_PAGE, text.length - offset);
170
+ // Escaping can grow text several times; a page always fits one answer and always moves forward.
171
+ while (size > 1 && Buffer.byteLength(JSON.stringify(text.slice(offset, offset + size))) > PAGE_BYTES)
172
+ size = Math.floor(size / 2);
173
+ const end = offset + size;
174
+ return { conversation: { text: text.slice(offset, end), offset, next: end < text.length ? end : null, total: text.length,
175
+ sha256: createHash("sha256").update(text).digest("hex") } };
176
+ }
177
+ const pageSchema = z.object({ text: z.string(), offset: z.number().int().nonnegative(), next: z.number().int().positive().nullable(),
178
+ total: z.number().int().nonnegative().max(CONVERSATION_LIMIT), sha256: z.string().regex(/^[0-9a-f]{64}$/) });
179
+ /**
180
+ * The receiving side: every page of the source's conversation through `page(offset)`, checked against its length
181
+ * and hash and redacted again here, or undefined when the source has none (an older Hook, a move that never
182
+ * built one) or it does not arrive whole. Never fails the launch: the brief's excerpt stands on its own.
183
+ */
184
+ export async function fetchContinuationConversation(page, redact) {
185
+ const parts = [];
186
+ let offset = 0, total, hash;
187
+ for (let pages = 0; pages < 64; pages++) {
188
+ let answer;
189
+ try {
190
+ answer = await page(offset);
191
+ }
192
+ catch {
193
+ return undefined;
194
+ }
195
+ const parsed = pageSchema.safeParse(answer.conversation);
196
+ if (!parsed.success || parsed.data.offset !== offset)
197
+ return undefined;
198
+ if ((total ??= parsed.data.total) !== parsed.data.total || (hash ??= parsed.data.sha256) !== parsed.data.sha256)
199
+ return undefined;
200
+ parts.push(parsed.data.text);
201
+ offset += parsed.data.text.length;
202
+ if (parsed.data.next === null) {
203
+ const text = parts.join("");
204
+ if (text.length !== total || createHash("sha256").update(text).digest("hex") !== hash)
205
+ return undefined;
206
+ return redact(text);
207
+ }
208
+ if (parsed.data.next !== offset || offset > total)
209
+ return undefined;
210
+ }
211
+ return undefined;
212
+ }
213
+ /** Where the copied conversation is, to tell the new agent; appended only when the brief has room for it. */
214
+ export function withConversationPointer(text, file, limit = 32768) {
215
+ const pointer = `\n\nThe previous agent's conversation, more of it than the excerpt above, is in ${file}. Read what you need of it, from the end back, before you write your hand-off.`;
216
+ return text.length + pointer.length <= limit ? `${text}${pointer}` : text;
217
+ }
@@ -43,6 +43,8 @@ export interface RequestList {
43
43
  source: string;
44
44
  user?: string;
45
45
  };
46
+ /** The hosted repository the requests were listed from, when the host's tool chose it (see `repository`). */
47
+ repository?: string;
46
48
  }
47
49
  export interface GitHostProvider {
48
50
  readonly kind: HostKind;
@@ -57,6 +59,10 @@ export interface GitHostProvider {
57
59
  * when one is given. The host's own refusal (checks, approvals, conflicts)
58
60
  * comes back as `{ ok: false, reason: "blocked", message }`. */
59
61
  merge(root: string, request: MergeRequest, host: GitHost): Promise<Json>;
62
+ /** The hosted repository `list` and `merge` act on, as a URL or `domain/owner/repo`, when the host's own
63
+ * tool picks it rather than the remote (gh prefers an `upstream` or its `repo set-default`). Without it,
64
+ * the remote's `webUrl` is that repository. Null when it cannot be told. */
65
+ repository?(root: string, host: GitHost): Promise<string | null>;
60
66
  /** Who a token signs in as, for Connect; HTTP hosts only. */
61
67
  whoami?(root: string, host: GitHost, token: string, api?: string): Promise<{
62
68
  user: string;
@@ -68,6 +74,8 @@ export interface MergeRequest {
68
74
  method: MergeMethod;
69
75
  expectedHeadSha?: string;
70
76
  deleteBranch?: boolean;
77
+ /** `domain/owner/repo` checked against the reviewed card: the merge acts there and nowhere else. */
78
+ repository?: string;
71
79
  }
72
80
  /** `git@host:owner/repo.git`, `ssh://git@host:2222/owner/repo.git`,
73
81
  * `https://user@host/owner/repo` → the domain and the repository path. */
@@ -198,7 +198,9 @@ const github = {
198
198
  return { number: pull.number, title: pull.title, head: pull.headRefName, base: pull.baseRefName,
199
199
  author: String(author.login ?? author.name ?? ""), url: pull.url, draft: pull.isDraft === true, state: pull.state, updated: pull.updatedAt };
200
200
  });
201
- return { available: true, pulls, current: mine };
201
+ // gh picked the repository itself; its pull request URLs name it, without asking gh again.
202
+ const listed = [mine, ...pulls].map(pull => /^(https:\/\/[^\s?#]+?)\/pull\/\d+$/.exec(String(pull?.url ?? ""))?.[1]).find(Boolean);
203
+ return { available: true, pulls, current: mine, ...(listed ? { repository: listed } : {}) };
202
204
  }
203
205
  catch {
204
206
  return { available: false, reason: "auth", message: "The GitHub CLI (gh) is missing or not signed in on this computer. Install it, then run gh auth login there.", pulls: [], current: null };
@@ -226,8 +228,10 @@ const github = {
226
228
  async merge(root, request, host) {
227
229
  // No --delete-branch: gh would also delete and leave the local branch,
228
230
  // which may be an agent's checkout.
231
+ // A checked repository is named, so gh cannot resolve another one between the check and the merge.
229
232
  const args = ["pr", "merge", String(request.number), `--${request.method}`,
230
- ...(request.expectedHeadSha ? ["--match-head-commit", request.expectedHeadSha] : [])];
233
+ ...(request.expectedHeadSha ? ["--match-head-commit", request.expectedHeadSha] : []),
234
+ ...(request.repository ? ["--repo", request.repository] : [])];
231
235
  const result = await runCombined("gh", args, root, 60_000, ghEnv(host));
232
236
  if (result.missing)
233
237
  return { ok: false, reason: "missing", message: "The GitHub CLI (gh) is not installed on this computer." };
@@ -240,5 +244,15 @@ const github = {
240
244
  return { ok: false, reason: "auth", message: "The GitHub CLI is not signed in on this computer, or the account can't merge here. Run gh auth login there." };
241
245
  return { ok: false, reason: "failed", message: output.slice(0, 1000) || "gh pr merge failed." };
242
246
  },
247
+ async repository(root, host) {
248
+ // The repository gh's own pr commands resolve here, which for a fork is usually its upstream.
249
+ try {
250
+ const { stdout } = await exec("gh", ["repo", "view", "--json", "url", "--jq", ".url"], { cwd: root, timeout: 15_000, maxBuffer: 65_536, env: ghEnv(host) });
251
+ return stdout.trim() || null;
252
+ }
253
+ catch {
254
+ return null;
255
+ }
256
+ },
243
257
  };
244
258
  export const PROVIDERS = { github, gitlab, gitboy };
@@ -3,7 +3,7 @@ import { nonInteractiveGitEnv } from "../utils-helpers.js";
3
3
  import { BridgeError } from "./protocol.js";
4
4
  import { git, gitRoot } from "./projects.js";
5
5
  import { countGit } from "./metrics.js";
6
- import { defaultBranch, invalidatePulls, invalidateTree } from "./git.js";
6
+ import { defaultBranch, invalidatePulls, invalidateTree, normalizeRemote, remoteIdentity } from "./git.js";
7
7
  import { z } from "zod";
8
8
  import { detectHost, providerFor, unknownHost } from "./git-hosts.js";
9
9
  import { writeHostToken } from "./git-host-auth.js";
@@ -206,6 +206,8 @@ const MergeBody = z.object({
206
206
  method: z.enum(["merge", "squash", "rebase"]).default("merge"),
207
207
  expectedHeadSha: z.string().regex(/^[0-9a-f]{7,64}$/i).optional(),
208
208
  deleteBranch: z.boolean().optional(),
209
+ /** The pulls listing's `remote` the reviewed card came from; a different remote now is refused. */
210
+ expectedRemote: z.string().trim().min(1).max(512).optional(),
209
211
  });
210
212
  /** Merge one pull or merge request on the remote's host. The host decides:
211
213
  * its refusal (checks, approvals, conflicts, a head that moved past
@@ -215,13 +217,27 @@ export async function gitMergeRequest(cwd, data) {
215
217
  const root = await repository(cwd);
216
218
  const branch = (await git(root, "branch", "--show-current").catch(() => "")).trim();
217
219
  const host = await detectHost(root, branch);
220
+ const { expectedRemote, ...rest } = request;
221
+ const merge = rest;
222
+ if (expectedRemote !== undefined) {
223
+ const current = await remoteIdentity(root, host);
224
+ // Not merged unchecked: the host's tool could not say (gh signed out, offline), which is not a moved remote.
225
+ if (!current)
226
+ return { ok: false, reason: "failed", message: `Phren could not tell which repository ${host.name} merges in from this checkout, so nothing was merged. Check that its sign-in works, then try again.`, host };
227
+ if (current !== normalizeRemote(expectedRemote)) {
228
+ // The refresh the error asks for must read again: gh's choice of repository is not part of the cached listing's key.
229
+ invalidatePulls(root);
230
+ throw new BridgeError(409, "This checkout's remote is not the repository this pull request was reviewed in. Refresh pull requests before merging.", { code: "git-remote-changed" });
231
+ }
232
+ merge.repository = current;
233
+ }
218
234
  const provider = providerFor(host);
219
235
  if (!provider) {
220
236
  const { reason, message } = unknownHost(host);
221
237
  return { ok: false, reason, message, host };
222
238
  }
223
239
  try {
224
- return { ...await provider.merge(root, request, host), host };
240
+ return { ...await provider.merge(root, merge, host), host };
225
241
  }
226
242
  finally {
227
243
  invalidatePulls(root);
@@ -54,6 +54,14 @@ export declare function gitBranches(cwd: string): Promise<Json>;
54
54
  export declare function invalidatePulls(root: string): void;
55
55
  /** Tokens belong to a domain, so revoke every checkout and pending generation. */
56
56
  export declare function invalidatePullsForDomain(domain: string): void;
57
+ /** Which hosted repository the host's requests are listed and merged in, as `domain/owner/repo` in lower
58
+ * case: what a reviewed pull request card binds to, so a retargeted remote or a pane moved to another
59
+ * checkout cannot merge a same-number request in a different repository. It is the one the host's own tool
60
+ * resolves when it picks (gh: an `upstream`, or `gh repo set-default`), else the remote's. Null with no
61
+ * parsable remote, or when the tool cannot say. */
62
+ export declare function remoteIdentity(root: string, host: Awaited<ReturnType<typeof detectHost>>): Promise<string | null>;
63
+ /** `https://GitHub.com/Owner/Repo/`, `github.com/owner/repo` → `github.com/owner/repo`. */
64
+ export declare function normalizeRemote(value: string): string;
57
65
  /** Open pull or merge requests and the checked-out branch's own (any state)
58
66
  * with its checks, from whichever host the remote is on (git-hosts.ts). A
59
67
  * host that cannot answer (a missing CLI, a stubbed provider, an unknown
@@ -406,6 +406,22 @@ async function pullsTarget(cwd) {
406
406
  throw error;
407
407
  }
408
408
  }
409
+ /** Which hosted repository the host's requests are listed and merged in, as `domain/owner/repo` in lower
410
+ * case: what a reviewed pull request card binds to, so a retargeted remote or a pane moved to another
411
+ * checkout cannot merge a same-number request in a different repository. It is the one the host's own tool
412
+ * resolves when it picks (gh: an `upstream`, or `gh repo set-default`), else the remote's. Null with no
413
+ * parsable remote, or when the tool cannot say. */
414
+ export async function remoteIdentity(root, host) {
415
+ if (!host.domain)
416
+ return null;
417
+ const provider = providerFor(host);
418
+ const named = provider?.repository ? await provider.repository(root, host).catch(() => null) : host.webUrl;
419
+ return named ? normalizeRemote(named) : null;
420
+ }
421
+ /** `https://GitHub.com/Owner/Repo/`, `github.com/owner/repo` → `github.com/owner/repo`. */
422
+ export function normalizeRemote(value) {
423
+ return value.trim().toLowerCase().replace(/^[a-z][a-z0-9+.-]*:\/\//, "").replace(/\/+$/, "");
424
+ }
409
425
  /** Open pull or merge requests and the checked-out branch's own (any state)
410
426
  * with its checks, from whichever host the remote is on (git-hosts.ts). A
411
427
  * host that cannot answer (a missing CLI, a stubbed provider, an unknown
@@ -423,7 +439,14 @@ export async function gitPulls(cwd, retried = false) {
423
439
  pullsCache.invalidate(candidate => candidate === key);
424
440
  throw new CredentialsChanged();
425
441
  }
426
- return { ...list, branch: branch || null, host };
442
+ // `remote` is what `expectedRemote` is checked against on merge: the repository the requests came from
443
+ // when the host's tool picked it, else the remote's. With no requests listed there is no card to bind.
444
+ const { repository: listed, ...rest } = list;
445
+ const remote = host.domain ? listed ?? host.webUrl : null;
446
+ return { ...rest, branch: branch || null, host, remote: remote ? normalizeRemote(remote) : null };
447
+ })).then(list => ({
448
+ // Outside the cache, which worktrees of one repository share: this checkout, what `expectedRepository` is checked against.
449
+ ...list, repository: root,
427
450
  }));
428
451
  }
429
452
  catch (error) {