@phren/cli 0.3.58 → 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.
Files changed (91) hide show
  1. package/README.md +1 -1
  2. package/dist/bridge/account-add.d.ts +30 -0
  3. package/dist/bridge/account-add.js +125 -19
  4. package/dist/bridge/account-failover.d.ts +9 -2
  5. package/dist/bridge/account-failover.js +1 -1
  6. package/dist/bridge/account-policy.d.ts +44 -0
  7. package/dist/bridge/account-policy.js +103 -0
  8. package/dist/bridge/account-pools.d.ts +35 -0
  9. package/dist/bridge/account-pools.js +171 -0
  10. package/dist/bridge/account-usage.d.ts +29 -4
  11. package/dist/bridge/account-usage.js +117 -8
  12. package/dist/bridge/agent-hook-callback.d.ts +6 -0
  13. package/dist/bridge/agent-hook-callback.js +10 -2
  14. package/dist/bridge/agent-hook-stores.d.ts +3 -0
  15. package/dist/bridge/agent-hook-stores.js +13 -0
  16. package/dist/bridge/agent-hooks.d.ts +12 -2
  17. package/dist/bridge/agent-hooks.js +41 -4
  18. package/dist/bridge/claude-account-setup.d.ts +16 -0
  19. package/dist/bridge/claude-account-setup.js +46 -2
  20. package/dist/bridge/claude-accounts.d.ts +9 -0
  21. package/dist/bridge/claude-accounts.js +53 -15
  22. package/dist/bridge/claude-credits.d.ts +8 -2
  23. package/dist/bridge/claude-credits.js +52 -31
  24. package/dist/bridge/codex-threads.js +50 -2
  25. package/dist/bridge/command.js +12 -3
  26. package/dist/bridge/continuation-launch.d.ts +32 -0
  27. package/dist/bridge/continuation-launch.js +112 -1
  28. package/dist/bridge/dispatch-command.js +22 -0
  29. package/dist/bridge/dispatch-returns.d.ts +23 -0
  30. package/dist/bridge/dispatch-returns.js +57 -0
  31. package/dist/bridge/dispatch.d.ts +26 -4
  32. package/dist/bridge/dispatch.js +100 -11
  33. package/dist/bridge/git-host-gitlab.js +2 -1
  34. package/dist/bridge/git-hosts.d.ts +8 -0
  35. package/dist/bridge/git-hosts.js +16 -2
  36. package/dist/bridge/git-publish.js +18 -2
  37. package/dist/bridge/git.d.ts +8 -0
  38. package/dist/bridge/git.js +24 -1
  39. package/dist/bridge/hand-off-queue.d.ts +71 -0
  40. package/dist/bridge/hand-off-queue.js +38 -0
  41. package/dist/bridge/harnesses.d.ts +12 -0
  42. package/dist/bridge/harnesses.js +20 -4
  43. package/dist/bridge/helper.d.ts +54 -0
  44. package/dist/bridge/helper.js +186 -0
  45. package/dist/bridge/herdr.js +6 -2
  46. package/dist/bridge/hook-fast.d.ts +3 -0
  47. package/dist/bridge/hook-fast.js +10 -2
  48. package/dist/bridge/move-computers.d.ts +15 -1
  49. package/dist/bridge/move-computers.js +123 -26
  50. package/dist/bridge/owner-inbox-sources.d.ts +12 -1
  51. package/dist/bridge/owner-inbox-sources.js +127 -49
  52. package/dist/bridge/peers.d.ts +2 -0
  53. package/dist/bridge/peers.js +35 -4
  54. package/dist/bridge/prompt-deliveries.d.ts +69 -2
  55. package/dist/bridge/prompt-deliveries.js +342 -28
  56. package/dist/bridge/schedule-watch.js +17 -3
  57. package/dist/bridge/server-routes.d.ts +6 -0
  58. package/dist/bridge/server-routes.js +98 -14
  59. package/dist/bridge/server-stream.js +6 -4
  60. package/dist/bridge/server.js +2 -1
  61. package/dist/bridge/session-move.d.ts +70 -1
  62. package/dist/bridge/session-move.js +311 -19
  63. package/dist/bridge/simulators.d.ts +19 -0
  64. package/dist/bridge/simulators.js +93 -13
  65. package/dist/bridge/speech-live.js +132 -22
  66. package/dist/bridge/task-routes.d.ts +16 -16
  67. package/dist/bridge/terminal-herdr.js +6 -1
  68. package/dist/bridge/terminal-tmux.js +9 -5
  69. package/dist/bridge/terminal.d.ts +9 -2
  70. package/dist/bridge/transcript-claude.d.ts +3 -0
  71. package/dist/bridge/transcript-claude.js +175 -29
  72. package/dist/bridge/transcript-preview.d.ts +11 -2
  73. package/dist/bridge/transcript-preview.js +90 -8
  74. package/dist/bridge/turn-records.d.ts +19 -0
  75. package/dist/bridge/turn-records.js +78 -3
  76. package/dist/bridge/usage.d.ts +17 -0
  77. package/dist/bridge/usage.js +3 -2
  78. package/dist/bridge-hook.mjs +11964 -10084
  79. package/dist/cli-registry.js +2 -2
  80. package/dist/content/citation.d.ts +4 -0
  81. package/dist/content/citation.js +21 -21
  82. package/dist/data/task-contract.d.ts +4 -4
  83. package/dist/governance/policy.js +5 -2
  84. package/dist/index.js +1 -1
  85. package/dist/modules/registry.js +5 -5
  86. package/dist/project-config.d.ts +14 -0
  87. package/dist/project-config.js +40 -1
  88. package/dist/tools/dispatch.js +1 -1
  89. package/dist/tools/helper.d.ts +3 -0
  90. package/dist/tools/helper.js +44 -0
  91. package/package.json +1 -1
@@ -15,7 +15,7 @@
15
15
  // the dispatch id (PHREN_DISPATCH_ID) its SessionStart or first prompt named,
16
16
  // so a dispatch placed on this computer is matched by id as well as by pane
17
17
  // and conversation.
18
- import { lstat, readFile } from "node:fs/promises";
18
+ import { lstat, readdir, readFile } from "node:fs/promises";
19
19
  import path from "node:path";
20
20
  import { z } from "zod";
21
21
  import { opencodeTurnStamps } from "./harness-status.js";
@@ -23,10 +23,14 @@ import { briefId } from "./launch-brief.js";
23
23
  import { atomicInPrivateDir, bridgeRoot, provider, serverName, sessionId } from "./protocol.js";
24
24
  /** Longest final reply kept from a Stop payload, in UTF-8 bytes (the receipt's limit). */
25
25
  export const TURN_REPLY_LIMIT = 4000;
26
- const MAX_RECORD_BYTES = 16_384;
26
+ /** Most background tasks a record keeps from one Stop, running ones first. */
27
+ export const STOP_TASKS_LIMIT = 256;
28
+ // Room for a typical full task list beside the reply and cwd; a record still larger sheds tasks (`fitRecord`).
29
+ const MAX_RECORD_BYTES = 65_536;
27
30
  // Not strict: a field a newer Hook adds (as `stop.cwd` was) is dropped on
28
31
  // read here, never a reason to throw the pane's record away.
29
32
  const stamp = z.object({ seq: z.number().int().min(0), at: z.string().datetime() });
33
+ const taskId = z.string().regex(/^[A-Za-z0-9._-]{1,128}$/);
30
34
  const turnRecordSchema = z.object({
31
35
  terminal: z.string().min(1).max(200), source: provider, session: sessionId,
32
36
  /** Climbs with every recorded event, so prompt and stop are ordered without trusting the clock. */
@@ -41,6 +45,11 @@ const turnRecordSchema = z.object({
41
45
  reply: z.string().max(TURN_REPLY_LIMIT).optional(), truncated: z.boolean().optional(),
42
46
  /** The agent's working directory when the turn stopped: where its uncommitted work would be. */
43
47
  cwd: z.string().max(4096).optional(),
48
+ /** Claude: the background tasks the Stop listed, by id (a sub-agent's is its agent id), still running
49
+ * or finished. The child tree trusts it over its quiet-transcript guess (transcript-claude.ts).
50
+ * `truncated`: the Stop listed more than STOP_TASKS_LIMIT; finished ones were dropped first. */
51
+ tasks: z.object({ running: z.array(taskId).max(STOP_TASKS_LIMIT), finished: z.array(taskId).max(STOP_TASKS_LIMIT),
52
+ truncated: z.boolean().optional() }).refine(tasks => tasks.running.length + tasks.finished.length <= STOP_TASKS_LIMIT).optional(),
44
53
  }).optional(),
45
54
  at: z.string().datetime(),
46
55
  });
@@ -55,6 +64,23 @@ export function truncateUtf8(value, limit = TURN_REPLY_LIMIT) {
55
64
  end--;
56
65
  return { text: bytes.subarray(0, end).toString("utf8"), truncated: true };
57
66
  }
67
+ /** A Stop's background task list as ids still running and ids finished; undefined when it sent none.
68
+ * Past STOP_TASKS_LIMIT, finished ids go before running ones and the list says it was cut. */
69
+ function stopTasks(value) {
70
+ if (!Array.isArray(value))
71
+ return undefined;
72
+ const running = [], finished = [];
73
+ for (const task of value) {
74
+ const { id, running: live } = (task ?? {});
75
+ if (typeof id !== "string" || !taskId.safeParse(id).success || typeof live !== "boolean")
76
+ continue;
77
+ (live ? running : finished).push(id);
78
+ }
79
+ if (running.length + finished.length <= STOP_TASKS_LIMIT)
80
+ return { running, finished };
81
+ const kept = running.slice(0, STOP_TASKS_LIMIT);
82
+ return { running: kept, finished: finished.slice(0, STOP_TASKS_LIMIT - kept.length), truncated: true };
83
+ }
58
84
  /** The record after one lifecycle event; undefined for events that say nothing about turns.
59
85
  * Another conversation or terminal in the pane starts a fresh record. */
60
86
  export function nextTurn(previous, event) {
@@ -71,17 +97,33 @@ export function nextTurn(previous, event) {
71
97
  record.startedAt ??= at;
72
98
  // A resumed or cleared conversation in the same terminal no longer runs the background agents its
73
99
  // last Stop counted; a compaction keeps them.
74
- if ((event.start === "resume" || event.start === "clear") && record.stop?.background !== undefined)
100
+ if ((event.start === "resume" || event.start === "clear") && record.stop) {
75
101
  delete record.stop.background;
102
+ delete record.stop.tasks;
103
+ }
76
104
  }
77
105
  else if (event.event === "UserPromptSubmit")
78
106
  record.prompt = { seq: record.seq, at };
79
107
  else {
80
108
  const reply = event.reply?.trim() ? truncateUtf8(event.reply.trim()) : undefined;
109
+ const tasks = stopTasks(event.backgroundTasks);
81
110
  record.stop = { seq: record.seq, at, ...(event.background !== undefined ? { background: Math.min(999, Math.max(0, Math.floor(event.background))) } : {}),
111
+ ...(tasks ? { tasks } : {}),
82
112
  ...(reply ? { reply: reply.text, ...(reply.truncated ? { truncated: true } : {}) } : {}),
83
113
  ...(event.cwd && path.isAbsolute(event.cwd) && event.cwd.length <= 4096 ? { cwd: event.cwd } : {}) };
84
114
  }
115
+ return fitRecord(record);
116
+ }
117
+ /** `record` within MAX_RECORD_BYTES, which readRecord would otherwise throw away whole: its Stop's
118
+ * finished tasks go first, then running ones, and the list says it was cut. */
119
+ function fitRecord(record) {
120
+ const tasks = record.stop?.tasks;
121
+ while (tasks && Buffer.byteLength(JSON.stringify(record)) > MAX_RECORD_BYTES && (tasks.finished.length || tasks.running.length)) {
122
+ const over = Buffer.byteLength(JSON.stringify(record)) - MAX_RECORD_BYTES, drop = Math.max(1, Math.ceil(over / 64));
123
+ const list = tasks.finished.length ? tasks.finished : tasks.running;
124
+ list.splice(Math.max(0, list.length - drop));
125
+ tasks.truncated = true;
126
+ }
85
127
  return record;
86
128
  }
87
129
  /** Where the recorded conversation is: no prompt yet, a prompt with no Stop
@@ -137,6 +179,39 @@ export function noteTurn(server, pane, event) {
137
179
  export function readTurn(server, pane) {
138
180
  return readRecord(turnPath(server, pane));
139
181
  }
182
+ const STOP_TASKS_CACHE_MS = 2_000;
183
+ let stopTasksCache;
184
+ /** The background tasks the latest Stop of conversation `session` listed, from whichever pane's record
185
+ * holds it (the child tree knows the conversation, not its pane); undefined when no Stop listed any. */
186
+ export async function latestStopTasks(source, session) {
187
+ const root = path.join(bridgeRoot(), "turns"), now = Date.now();
188
+ if (!stopTasksCache || stopTasksCache.root !== root || now - stopTasksCache.at >= STOP_TASKS_CACHE_MS) {
189
+ stopTasksCache = { at: now, root, bySession: (async () => {
190
+ // The conversation's newest record decides, list or none: a resume in another pane (whose agents died
191
+ // with the old process) outdates the list a closed pane's record still holds.
192
+ // Panes are read in name order, and a record written in the same millisecond as another wins only when
193
+ // its last event came after its own Stop (the pane that went on), so a tie never depends on directory order.
194
+ const newest = new Map();
195
+ for (const server of (await readdir(root).catch(() => [])).sort()) {
196
+ for (const name of (await readdir(path.join(root, server)).catch(() => [])).filter(name => name.endsWith(".json")).sort()) {
197
+ const record = await readRecord(path.join(root, server, name));
198
+ if (!record)
199
+ continue;
200
+ const key = `${record.source}\0${record.session}`, previous = newest.get(key);
201
+ const at = Date.parse(record.at), before = previous ? Date.parse(previous.at) : -Infinity;
202
+ if (at > before || (at === before && record.stop?.seq !== record.seq && previous?.stop?.seq === previous?.seq))
203
+ newest.set(key, record);
204
+ }
205
+ }
206
+ const found = new Map();
207
+ for (const [key, record] of newest)
208
+ if (record.stop?.tasks)
209
+ found.set(key, { seq: record.stop.seq, at: record.stop.at, ...record.stop.tasks });
210
+ return found;
211
+ })() };
212
+ }
213
+ return (await stopTasksCache.bySession).get(`${source}\0${session}`);
214
+ }
140
215
  /** OpenCode's turns for a pane running `pids`, from the stamps phren's OpenCode
141
216
  * plugin writes on session.status busy / session.idle; undefined for an older
142
217
  * plugin that writes none. `terminal` is the pane's, since the PIDs are. */
@@ -16,6 +16,9 @@ export interface UsageWindow {
16
16
  usedCharacters?: number;
17
17
  limitCharacters?: number;
18
18
  resetsAt?: string;
19
+ /** An API credit window (`credit:<id>`): what is left of it, and when it expires (also its `resetsAt`). */
20
+ remainingUSD?: number;
21
+ expiresAt?: string;
19
22
  /** The service says this window is refusing requests now (OpenCode Go's `rate-limited`). */
20
23
  limited?: boolean;
21
24
  asOf?: string;
@@ -35,6 +38,18 @@ export interface UsageCredits {
35
38
  balance?: number;
36
39
  inUse?: true;
37
40
  }
41
+ /**
42
+ * A Claude home's API credits entered by the owner (claude-credits.ts), added up over the unexpired ones: dollars
43
+ * left, and the soonest expiry among credits with money left (spend it first). Always an estimate: Claude Code
44
+ * reports no Console balance.
45
+ */
46
+ export interface ApiCredit {
47
+ remainingUSD: number;
48
+ limitUSD: number;
49
+ usedUSD: number;
50
+ expiresAt?: string;
51
+ estimate: true;
52
+ }
38
53
  export interface UsageSpend {
39
54
  amountUSD: number;
40
55
  period: "rolling_7_days" | "rolling_30_days" | "calendar_week";
@@ -48,6 +63,8 @@ export interface AccountUsage {
48
63
  subscription?: Subscription;
49
64
  /** Codex's credit balance, when Codex reports one. */
50
65
  credits?: UsageCredits;
66
+ /** A Claude home's API credits, when the owner entered any. */
67
+ apiCredit?: ApiCredit;
51
68
  /** Opaque key identity used only to avoid counting one OpenRouter key twice. */
52
69
  accountId?: string;
53
70
  /** Which Claude report fed this account: the status-line rate_limits payload
@@ -13,7 +13,7 @@ import { readSpeechKey } from "./speech-key.js";
13
13
  import { resolveSpeechRegion, SPEECH_REGIONS } from "./speech-voice.js";
14
14
  import { accountWindows } from "./account-choice.js";
15
15
  import { CODEX_ACCOUNT, claudeAccountSubscription, claudeAccountEmail, claudeAccountRef, claudeAuthStatus, claudeHomeOfEnv, claudeHomes, claudePlanUnknown } from "./claude-accounts.js";
16
- import { claudeCredits, creditWindows, homeSessionCosts, recordSessionCost } from "./claude-credits.js";
16
+ import { claudeCredits, creditSummary, creditWindows, homeSessionCosts, recordSessionCost } from "./claude-credits.js";
17
17
  import { claudePlan, planName, subscriptionDate } from "./subscription.js";
18
18
  const exec = promisify(execFile);
19
19
  /** The status-line snapshot: `usage/claude.json` for the default home, `usage/claude-<id>.json` for others. */
@@ -837,7 +837,8 @@ export class AccountUsageReader {
837
837
  const subscription = claudeAccountSubscription(home, now, fallback);
838
838
  const usage = settleClaudeUsage(await this.claude(home), this.now());
839
839
  const credit = credits.length ? creditWindows(credits, homeSessionCosts(home), now) : [];
840
- const withCredit = credit.length ? { ...usage, windows: [...usage.windows, ...credit], message: undefined, updatedAt: usage.updatedAt ?? now.toISOString() } : usage;
840
+ const apiCredit = creditSummary(credit);
841
+ const withCredit = credit.length ? { ...usage, windows: [...usage.windows, ...credit], ...(apiCredit ? { apiCredit } : {}), message: undefined, updatedAt: usage.updatedAt ?? now.toISOString() } : usage;
841
842
  return { ...withCredit, ...(subscription ? { subscription } : {}), account: { ...claudeAccountRef(home), ...(email ? { email } : {}) } };
842
843
  };
843
844
  const [codexValue, claude, subscription] = await Promise.all([codex, Promise.all(homes.map(claudeRow)), readCodexSubscription(undefined, new Date(this.now()))]);