@phren/cli 0.3.36 → 0.3.39

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 (103) hide show
  1. package/dist/bridge/account-choice.d.ts +82 -0
  2. package/dist/bridge/account-choice.js +173 -0
  3. package/dist/bridge/account-failover.d.ts +61 -0
  4. package/dist/bridge/account-failover.js +189 -0
  5. package/dist/bridge/account-usage.d.ts +7 -2
  6. package/dist/bridge/account-usage.js +53 -8
  7. package/dist/bridge/agent-hooks.js +2 -0
  8. package/dist/bridge/changes.d.ts +5 -0
  9. package/dist/bridge/changes.js +4 -0
  10. package/dist/bridge/claude-accounts.d.ts +15 -4
  11. package/dist/bridge/claude-accounts.js +31 -16
  12. package/dist/bridge/claude-credits.d.ts +43 -0
  13. package/dist/bridge/claude-credits.js +236 -0
  14. package/dist/bridge/claude-question-dialog.js +6 -2
  15. package/dist/bridge/command.js +64 -3
  16. package/dist/bridge/device-enroll.d.ts +34 -0
  17. package/dist/bridge/device-enroll.js +57 -0
  18. package/dist/bridge/dispatch-command.d.ts +2 -0
  19. package/dist/bridge/dispatch-command.js +25 -1
  20. package/dist/bridge/dispatch-returns.d.ts +19 -0
  21. package/dist/bridge/dispatch-returns.js +93 -12
  22. package/dist/bridge/dispatch.d.ts +83 -3
  23. package/dist/bridge/dispatch.js +82 -10
  24. package/dist/bridge/file-range.d.ts +3 -0
  25. package/dist/bridge/file-range.js +5 -4
  26. package/dist/bridge/file-search.d.ts +37 -0
  27. package/dist/bridge/file-search.js +87 -0
  28. package/dist/bridge/file-write.d.ts +6 -0
  29. package/dist/bridge/file-write.js +120 -0
  30. package/dist/bridge/git-host-auth.d.ts +31 -0
  31. package/dist/bridge/git-host-auth.js +110 -0
  32. package/dist/bridge/git-host-gitboy.d.ts +46 -0
  33. package/dist/bridge/git-host-gitboy.js +296 -0
  34. package/dist/bridge/git-host-gitlab.d.ts +25 -0
  35. package/dist/bridge/git-host-gitlab.js +229 -0
  36. package/dist/bridge/git-host-http.d.ts +33 -0
  37. package/dist/bridge/git-host-http.js +70 -0
  38. package/dist/bridge/git-hosts.d.ts +92 -0
  39. package/dist/bridge/git-hosts.js +244 -0
  40. package/dist/bridge/git-publish.d.ts +15 -5
  41. package/dist/bridge/git-publish.js +69 -21
  42. package/dist/bridge/git-review.d.ts +23 -0
  43. package/dist/bridge/git-review.js +170 -0
  44. package/dist/bridge/git-sync.d.ts +14 -0
  45. package/dist/bridge/git-sync.js +143 -0
  46. package/dist/bridge/git.d.ts +20 -7
  47. package/dist/bridge/git.js +87 -68
  48. package/dist/bridge/gitboy-contract.d.ts +32 -0
  49. package/dist/bridge/gitboy-contract.js +46 -0
  50. package/dist/bridge/hand-off.d.ts +75 -3
  51. package/dist/bridge/hand-off.js +113 -27
  52. package/dist/bridge/health.d.ts +1 -1
  53. package/dist/bridge/health.js +5 -3
  54. package/dist/bridge/install.d.ts +14 -0
  55. package/dist/bridge/install.js +40 -1
  56. package/dist/bridge/launch-brief.d.ts +3 -0
  57. package/dist/bridge/launch-brief.js +16 -0
  58. package/dist/bridge/memory-store.d.ts +8 -0
  59. package/dist/bridge/memory-store.js +80 -2
  60. package/dist/bridge/pair.d.ts +6 -1
  61. package/dist/bridge/pair.js +74 -2
  62. package/dist/bridge/peers.js +4 -2
  63. package/dist/bridge/project-memory.d.ts +94 -0
  64. package/dist/bridge/project-memory.js +235 -0
  65. package/dist/bridge/push.d.ts +15 -0
  66. package/dist/bridge/push.js +39 -0
  67. package/dist/bridge/schedule-launch.js +5 -1
  68. package/dist/bridge/schedule-watch.d.ts +3 -0
  69. package/dist/bridge/schedule-watch.js +27 -1
  70. package/dist/bridge/scoped-gateway.d.ts +29 -0
  71. package/dist/bridge/scoped-gateway.js +239 -0
  72. package/dist/bridge/server-launch.d.ts +12 -0
  73. package/dist/bridge/server-launch.js +23 -12
  74. package/dist/bridge/server-pane-routes.js +54 -3
  75. package/dist/bridge/server-routes.d.ts +12 -0
  76. package/dist/bridge/server-routes.js +64 -5
  77. package/dist/bridge/server.js +50 -5
  78. package/dist/bridge/session-move.d.ts +288 -0
  79. package/dist/bridge/session-move.js +600 -0
  80. package/dist/bridge/subscription.d.ts +15 -0
  81. package/dist/bridge/subscription.js +23 -0
  82. package/dist/bridge/transport.js +21 -1
  83. package/dist/bridge/usage.d.ts +23 -4
  84. package/dist/bridge/usage.js +63 -11
  85. package/dist/bridge-hook.mjs +23280 -13252
  86. package/dist/cli/config.js +28 -2
  87. package/dist/cli-registry.js +10 -4
  88. package/dist/computers/command.js +3 -1
  89. package/dist/computers/read.d.ts +3 -0
  90. package/dist/computers/read.js +6 -0
  91. package/dist/content/summarize.d.ts +21 -0
  92. package/dist/content/summarize.js +56 -18
  93. package/dist/init/preferences.d.ts +6 -0
  94. package/dist/modules/registry.js +13 -13
  95. package/dist/project-config.d.ts +12 -0
  96. package/dist/project-config.js +29 -0
  97. package/dist/shared/retrieval.d.ts +1 -0
  98. package/dist/shared/retrieval.js +1 -1
  99. package/dist/sync/conflict-resolve.js +5 -6
  100. package/dist/tools/dispatch.js +20 -3
  101. package/dist/tools/finding.d.ts +25 -0
  102. package/dist/tools/finding.js +2 -1
  103. package/package.json +57 -1
@@ -4,6 +4,7 @@ import { setTelemetryEnabled, getTelemetrySummary, resetTelemetry } from "../tel
4
4
  import { readInstallPreferences, updateInstallPreferences } from "../init/preferences.js";
5
5
  import { resolveMcpProfile } from "../mcp/profile.js";
6
6
  import { resolveClanker } from "../clanker.js";
7
+ import { resolveAccountFailover } from "../bridge/account-choice.js";
7
8
  import { parsePullInterval, resolvePullInterval, periodicPullEnabled } from "../sync/pull.js";
8
9
  import * as path from "path";
9
10
  import { buildConfigView } from "../config/resolve.js";
@@ -123,11 +124,15 @@ export async function handleConfig(args) {
123
124
  return handleConfigMcpProfile(rest);
124
125
  case "clanker":
125
126
  return handleConfigClanker(rest);
127
+ case "account-failover":
128
+ return handleConfigAccountFailover(rest);
126
129
  case "set":
127
- // `phren config set clanker on` reads naturally; clanker is the only key it takes.
130
+ // `phren config set clanker on` reads naturally.
128
131
  if (rest[0] === "clanker")
129
132
  return handleConfigClanker(rest.slice(1));
130
- console.error("phren config set takes: clanker on|off. Other settings have their own subcommand (phren config).");
133
+ if (rest[0] === "account-failover")
134
+ return handleConfigAccountFailover(rest.slice(1));
135
+ console.error("phren config set takes: clanker on|off, account-failover on|off. Other settings have their own subcommand (phren config).");
131
136
  process.exitCode = 1;
132
137
  return;
133
138
  case "pull-interval":
@@ -182,6 +187,9 @@ Subcommands:
182
187
  phren config profiles All profiles and their projects
183
188
  phren config clanker [on|off] Compact keyword-first retrieval: hook, search and
184
189
  lists return id/title/keyword rows; full text by id
190
+ phren config account-failover [on|off]
191
+ Continue on another signed-in account when a dispatched
192
+ Claude worker stops at its usage limit (default: off)
185
193
  phren config pull-interval [seconds|off]
186
194
  Periodic MCP remote checks (default: off)
187
195
  phren config telemetry [on|off|reset] Local usage stats (opt-in, no external reporting)`);
@@ -289,6 +297,24 @@ function handleConfigClanker(args) {
289
297
  ? "The prompt hook, search_knowledge, get_tasks and get_findings return id, title, keyword and score rows; get_memory_detail fetches an entry by id."
290
298
  : "The prompt hook and tools return text snippets. `phren config clanker on` for compact rows.");
291
299
  }
300
+ function handleConfigAccountFailover(args) {
301
+ const phrenPath = getPhrenPath();
302
+ const want = args[0]?.trim().toLowerCase();
303
+ if (want === "on" || want === "off") {
304
+ updateInstallPreferences(phrenPath, () => ({ accountFailover: want === "on" }));
305
+ console.log(`Account failover ${want}. The Hook reads it on its next returns poll.`);
306
+ }
307
+ else if (want) {
308
+ console.error(`Unknown value "${want}". Use on or off.`);
309
+ process.exitCode = 1;
310
+ return;
311
+ }
312
+ const { on, source } = resolveAccountFailover(process.env, phrenPath);
313
+ console.log(`Account failover: ${on ? "on" : "off"} (${source})`);
314
+ console.log(on
315
+ ? "A dispatched Claude worker that stops at its usage limit continues on another of your signed-in accounts with room, on its computer or another; never on the same login before its window resets."
316
+ : "A dispatched Claude worker that stops at its usage limit returns failed and stays stopped. `phren config account-failover on` continues it on another signed-in account.");
317
+ }
292
318
  function handleConfigTelemetry(args) {
293
319
  const action = args[0];
294
320
  switch (action) {
@@ -134,8 +134,8 @@ const TEAM_SUBCOMMANDS = [
134
134
  // ── Registry ─────────────────────────────────────────────────────────────────
135
135
  export const REGISTRY = [
136
136
  {
137
- name: "pair", topic: "setup", usage: "phren pair [--minutes <1-30>] [--port <n>] [--no-install]",
138
- summary: "Connect your phone: show a pairing QR code and authorize the phone that scans it",
137
+ name: "pair", topic: "setup", usage: "phren pair [--minutes <1-30>] [--port <n>] [--no-install] | phren pair --scope gitboy-read|gitboy-write --key <public-key-file|->",
138
+ summary: "Connect your phone with a pairing QR code, or authorize a scoped key for gitboy (gitboy-read: project memory; gitboy-write: save findings)",
139
139
  run: async (args) => {
140
140
  const { runPair } = await import("./bridge/pair.js");
141
141
  const { VERSION } = await import("./package-metadata.js");
@@ -143,14 +143,15 @@ export const REGISTRY = [
143
143
  },
144
144
  },
145
145
  {
146
- name: "bridge", topic: "setup", usage: "phren bridge <install|status|doctor|update|rollback|uninstall|enroll-computer|accounts|discover|link|fanouts archive|speech-key set|speech-voice|speech-model|speech-region>",
146
+ name: "bridge", topic: "setup", usage: "phren bridge <install|status|doctor|update|rollback|uninstall|enroll-computer|accounts|discover|link|fanouts archive|git-host|speech-key set|speech-voice|speech-model|speech-region>",
147
147
  summary: "Install Phren Hook and enroll phone or computer connections",
148
148
  subcommands: [
149
149
  { name: "enroll-computer", usage: "phren bridge enroll-computer <name> [--accept <public-key-file>]", summary: "Print or accept a restricted computer dispatch key" },
150
- { name: "accounts", usage: "phren bridge accounts [add <slug> [--label <name>] | label <id> <label>]", summary: "List this computer's harnesses and Claude accounts, add a Claude account home, or label one" },
150
+ { name: "accounts", usage: "phren bridge accounts [add <slug> [--label <name>] | label <id> <label> | credit <id> [--amount <usd> [--expires <date>] [--label <name>] | --remove <credit>]]", summary: "List this computer's harnesses and Claude accounts, add a Claude account home, label one, or enter an API credit for a Console login" },
151
151
  { name: "discover", usage: "phren bridge discover", summary: "List computers you already reach over ssh that run Phren Hook and are not linked" },
152
152
  { name: "link", usage: "phren bridge link <ssh-host> [--name <name>] [--as <name>] [--back-address <address>] [--yes]", summary: "Link this computer and an ssh host both ways in one step, after confirming" },
153
153
  { name: "fanouts archive", usage: "phren bridge fanouts archive [--dry-run] [--parent <session-id>] [--older-than <minutes>]", summary: "Archive finished fan-out jobs older than 24 hours, or one parent chat's, or older than N minutes" },
154
+ { name: "git-host", usage: "phren bridge git-host [list | set <domain> gitlab|gitboy | remove <domain>]", summary: "Store, list or forget the GitLab or gitboy token the Hook uses for merge requests and pipelines (token from stdin, mode 600)" },
154
155
  { name: "speech-key set", usage: "phren bridge speech-key set", summary: "Store this computer's ElevenLabs key for spoken replies and dictation (read from stdin, mode 600)" },
155
156
  { name: "speech-voice", usage: "phren bridge speech-voice [show | set <voice-id> | clear]", summary: "Show or set the ElevenLabs voice talk mode speaks with; kept across install and update" },
156
157
  { name: "speech-model", usage: "phren bridge speech-model [show | set <model-id> | clear]", summary: "Show or set the ElevenLabs model talk mode speaks with (default eleven_v4_turbo); kept across install and update" },
@@ -200,6 +201,11 @@ export const REGISTRY = [
200
201
  summary: "Send work to an existing agent session through Phren Hook",
201
202
  run: async (args) => (await import("./bridge/dispatch-command.js")).runHandOff(args),
202
203
  },
204
+ {
205
+ name: "move", topic: "core", usage: "phren move <session-or-pane> --to <claude|codex|opencode|copilot> [--model <model>] [--effort <effort>] [--account <id>] [--computer <name>] [--no-wait]",
206
+ summary: "Move a live agent session to another harness: it writes a hand-off and exits, and the new agent continues in its pane",
207
+ run: async (args) => (await import("./bridge/dispatch-command.js")).runMove(args),
208
+ },
203
209
  {
204
210
  name: "canary", topic: "core", usage: "phren canary [--daily on|off]",
205
211
  summary: "Exercise launch, schedules, transcripts and peers through Phren Hook; saves canary.json",
@@ -1,4 +1,4 @@
1
- import { combineUsage, describe, findComputer, pickComputer, readComputers, readUsage } from "./read.js";
1
+ import { combineUsage, creditsText, describe, findComputer, pickComputer, readComputers, readUsage } from "./read.js";
2
2
  /**
3
3
  * `phren computers` and `phren usage`: read-only, answered by the Phren Hook
4
4
  * alone. They run without a Phren store (the registry marks them
@@ -52,6 +52,8 @@ export function formatHarness(h) {
52
52
  const used = w.usedPercent !== undefined ? `${w.usedPercent}% used` : w.usedUSD !== undefined ? `$${w.usedUSD.toFixed(2)}${w.limitUSD !== undefined ? ` of $${w.limitUSD.toFixed(2)}` : ""}` : "";
53
53
  lines.push(` ${w.name.padEnd(30)} ${used.padEnd(18)}${w.resetsIn ? `resets in ${w.resetsIn}` : ""}`);
54
54
  }
55
+ if (h.credits?.hasCredits)
56
+ lines.push(` credits${" ".repeat(24)}${creditsText(h.credits)}`);
55
57
  if (h.spend)
56
58
  lines.push(` spend ${h.spend.period.replace(/_/g, " ").padEnd(24)} $${h.spend.amountUSD.toFixed(2)}`);
57
59
  if (h.message)
@@ -26,6 +26,7 @@ export interface HarnessUsage {
26
26
  resetsIn?: string;
27
27
  }>;
28
28
  spend?: AccountUsage["spend"];
29
+ credits?: AccountUsage["credits"];
29
30
  updatedAt?: string;
30
31
  /** What the harness said, or why it gave nothing. Never a guess. */
31
32
  message?: string;
@@ -68,6 +69,8 @@ export declare function pickComputer(computers: ComputerReport[], platform?: Pla
68
69
  };
69
70
  export declare function describe(r: ComputerResources): string;
70
71
  export declare function resetsIn(resetsAt: string | undefined, now?: number): string | undefined;
72
+ /** "1,250 credits, in use" or "unlimited credits". */
73
+ export declare function creditsText(credits: NonNullable<AccountUsage["credits"]>): string;
71
74
  /**
72
75
  * Account limits are the same account seen from each computer, so the
73
76
  * freshest report with windows stands. OpenCode's cost ledger is per
@@ -118,9 +118,15 @@ function harness(account, now) {
118
118
  return window;
119
119
  }),
120
120
  ...(account.spend ? { spend: account.spend } : {}),
121
+ ...(account.credits ? { credits: account.credits } : {}),
121
122
  ...(account.updatedAt ? { updatedAt: account.updatedAt } : {}),
122
123
  ...(account.message ? { message: account.message } : !account.windows.length && !account.spend ? { message: "No usage data reported." } : {}) };
123
124
  }
125
+ /** "1,250 credits, in use" or "unlimited credits". */
126
+ export function creditsText(credits) {
127
+ const amount = credits.unlimited ? "unlimited credits" : credits.balance !== undefined ? `${credits.balance.toLocaleString("en-US", { maximumFractionDigits: 2 })} credits` : "credits";
128
+ return credits.inUse ? `${amount}, in use` : amount;
129
+ }
124
130
  const NOT_REPORTED = "This computer's Hook did not report this harness; it may predate it (phren bridge update).";
125
131
  function harnesses(accounts, now) {
126
132
  const list = Array.isArray(accounts) ? accounts : [];
@@ -40,6 +40,27 @@ export declare function inventedIdentifiers(prose: string, bullets: ArchivedBull
40
40
  export declare function proseNow(d: TopicDigest, bullets: ArchivedBullet[], signal?: AbortSignal): Promise<string>;
41
41
  /** Fingerprint of everything in a topic file except its own Now block. */
42
42
  export declare function contentFingerprint(content: string, start: string, end: string): string;
43
+ /**
44
+ * Where a marked block sits: from its first start marker to its last end
45
+ * marker, and where its body begins (after the last start marker line). The
46
+ * store syncs with git's union merge for markdown, so two computers that both
47
+ * rewrote a block leave both start lines (and possibly both bodies); reading
48
+ * past every marker and replacing the whole span heals the file on the next write.
49
+ */
50
+ export declare function blockSpan(content: string, start: string, end: string): {
51
+ start: number;
52
+ end: number;
53
+ pick: number;
54
+ body: number;
55
+ bodyEnd: number;
56
+ } | null;
57
+ /** The block rebuilt as one copy: the newest start marker, its body and the end marker. */
58
+ export declare function cleanBlock(content: string, start: string, end: string): {
59
+ rest: string;
60
+ block: string;
61
+ } | null;
62
+ /** A block's text without its markers and heading line ("## Now"). */
63
+ export declare function blockBody(content: string, start: string, end: string): string | null;
43
64
  /** Insert or replace a marked block. Topic files: before the first section; summary: at the end. */
44
65
  export declare function upsertBlock(content: string, start: string, end: string, rendered: string, where: "top" | "bottom"): string;
45
66
  /** The stamp and fingerprint inside an existing block, so unchanged files are not rewritten. */
@@ -194,18 +194,60 @@ function block(start, end, heading, body, stamp, hash = "") {
194
194
  }
195
195
  /** Fingerprint of everything in a topic file except its own Now block. */
196
196
  export function contentFingerprint(content, start, end) {
197
- const s = content.indexOf(start.replace("-->", ""));
198
- const e = content.indexOf(end);
199
- const rest = s !== -1 && e !== -1 && e > s ? content.slice(0, s) + content.slice(e + end.length) : content;
197
+ const span = blockSpan(content, start, end);
198
+ const rest = span ? content.slice(0, span.start) + content.slice(span.end) : content;
200
199
  return createHash("sha1").update(rest.replace(/\s+/g, " ").trim()).digest("hex").slice(0, 12);
201
200
  }
201
+ /**
202
+ * Where a marked block sits: from its first start marker to its last end
203
+ * marker, and where its body begins (after the last start marker line). The
204
+ * store syncs with git's union merge for markdown, so two computers that both
205
+ * rewrote a block leave both start lines (and possibly both bodies); reading
206
+ * past every marker and replacing the whole span heals the file on the next write.
207
+ */
208
+ export function blockSpan(content, start, end) {
209
+ const prefix = start.replace("-->", "");
210
+ const s = content.indexOf(prefix);
211
+ const e = content.lastIndexOf(end);
212
+ if (s === -1 || e === -1 || e <= s)
213
+ return null;
214
+ // Every start marker inside the span; the body to read is the newest one's
215
+ // (highest at= stamp), up to the next start marker or the end marker.
216
+ const starts = [];
217
+ for (let i = s; i !== -1 && i < e; i = content.indexOf(prefix, i + prefix.length))
218
+ starts.push(i);
219
+ const stampOf = (at) => /at=([^ ]+)/.exec(content.slice(at, content.indexOf("-->", at)))?.[1] ?? "";
220
+ let pick = starts[0];
221
+ for (const at of starts)
222
+ if (stampOf(at) > stampOf(pick))
223
+ pick = at;
224
+ const next = starts.find((at) => at > pick) ?? e;
225
+ const newline = content.indexOf("\n", pick);
226
+ const body = newline === -1 || newline >= next ? next : newline + 1;
227
+ return { start: s, end: e + end.length, pick, body, bodyEnd: next };
228
+ }
229
+ /** The block rebuilt as one copy: the newest start marker, its body and the end marker. */
230
+ export function cleanBlock(content, start, end) {
231
+ const span = blockSpan(content, start, end);
232
+ if (!span)
233
+ return null;
234
+ const marker = content.slice(span.pick, span.body).replace(/\n$/, "");
235
+ const body = content.slice(span.body, span.bodyEnd).replace(/\n+$/, "");
236
+ const after = content.slice(span.end).replace(/^\n+/, "");
237
+ return { rest: content.slice(0, span.start) + after, block: `${marker}\n${body}\n${end}` };
238
+ }
239
+ /** A block's text without its markers and heading line ("## Now"). */
240
+ export function blockBody(content, start, end) {
241
+ const span = blockSpan(content, start, end);
242
+ if (!span)
243
+ return null;
244
+ return content.slice(span.body, span.bodyEnd).replace(/^## [^\n]*\n/, "").trim();
245
+ }
202
246
  /** Insert or replace a marked block. Topic files: before the first section; summary: at the end. */
203
247
  export function upsertBlock(content, start, end, rendered, where) {
204
- const startRe = new RegExp(`${start.replace("-->", "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[^\\n]*-->`);
205
- const s = content.search(startRe);
206
- const e = content.indexOf(end);
207
- if (s !== -1 && e !== -1 && e > s) {
208
- return `${content.slice(0, s)}${rendered}${content.slice(e + end.length)}`;
248
+ const span = blockSpan(content, start, end);
249
+ if (span) {
250
+ return `${content.slice(0, span.start)}${rendered}${content.slice(span.end)}`;
209
251
  }
210
252
  if (where === "top") {
211
253
  const firstSection = content.search(/^## /m);
@@ -275,8 +317,7 @@ export async function summarizeTopicFile(filePath, slug, opts = {}) {
275
317
  // The block carries a fingerprint of the rest of the file; unchanged bullets
276
318
  // mean an unchanged summary, whatever the clock says.
277
319
  if (!opts.force && prev?.hash === fingerprint && !split) {
278
- const existing = content.slice(content.indexOf(NOW_START.replace("-->", "")), content.indexOf(NOW_END));
279
- return { slug, file: filePath, bullets: bullets.length, updated: false, now: existing.split("\n").slice(2).join("\n").trim() };
320
+ return { slug, file: filePath, bullets: bullets.length, updated: false, now: blockBody(content, NOW_START, NOW_END) ?? "" };
280
321
  }
281
322
  let now = "";
282
323
  if (opts.llm)
@@ -432,11 +473,9 @@ export function listTopicFiles(phrenPath, project) {
432
473
  }
433
474
  /** The current Now text of a topic file and whether it is structural or prose. */
434
475
  export function readNowBlock(content) {
435
- const s = content.indexOf(NOW_START.replace("-->", ""));
436
- const e = content.indexOf(NOW_END);
437
- if (s === -1 || e === -1 || e <= s)
476
+ const text = blockBody(content, NOW_START, NOW_END);
477
+ if (text === null)
438
478
  return null;
439
- const text = content.slice(s, e).split("\n").slice(2).join("\n").trim();
440
479
  return { text, structural: /^\d+ findings?\b|^Nothing archived/.test(text) };
441
480
  }
442
481
  /**
@@ -467,10 +506,9 @@ export function readKnowsBlock(phrenPath, project) {
467
506
  if (!summaryPath || !fs.existsSync(summaryPath))
468
507
  return null;
469
508
  const content = fs.readFileSync(summaryPath, "utf8");
470
- const s = content.indexOf(KNOWS_START.replace("-->", ""));
471
- const e = content.indexOf(KNOWS_END);
472
- if (s === -1 || e === -1)
509
+ const span = blockSpan(content, KNOWS_START, KNOWS_END);
510
+ if (!span)
473
511
  return null;
474
- const inner = content.slice(s, e).split("\n").slice(1).join("\n").trim();
512
+ const inner = content.slice(span.body, span.bodyEnd).trim();
475
513
  return inner ? { path: summaryPath, text: inner } : null;
476
514
  }
@@ -13,6 +13,12 @@ export interface InstallPreferences {
13
13
  * overrides it. See clanker.ts.
14
14
  */
15
15
  clanker?: boolean;
16
+ /**
17
+ * Whether a dispatched Claude worker that hits its usage limit continues on
18
+ * another signed-in account. Off when unset; PHREN_ACCOUNT_FAILOVER
19
+ * overrides it. See bridge/account-choice.ts.
20
+ */
21
+ accountFailover?: boolean;
16
22
  hooksEnabled?: boolean;
17
23
  skillsScope?: "global" | "project";
18
24
  projectOwnershipDefault?: "phren-managed" | "detached" | "repo-managed";
@@ -40,8 +40,8 @@ export const BUILTIN_MODULES = [
40
40
  { agents: ["claude", "codex", "copilot", "cursor"], events: ["Stop"], handler: "phren hook-stop" },
41
41
  { agents: ["claude"], events: ["PostToolUse"], handler: "phren hook-tool" },
42
42
  ],
43
- hookRoutes: [...routes("GET", ["/v1/store/head", "/v1/store/tree", "/v1/store/blob"]), ...routes("POST", ["/v1/store/file", "/v1/store/delete"])],
44
- capabilities: ["memory", "memoryStore"],
43
+ hookRoutes: [...routes("GET", ["/v1/store/head", "/v1/store/tree", "/v1/store/blob"]), ...routes("POST", ["/v1/store/blobs", "/v1/store/file", "/v1/store/delete"])],
44
+ capabilities: ["memory", "memoryStore", "memoryStoreBatch", "projectMemory"],
45
45
  storeFiles: [
46
46
  "phren.root.yaml", "machines.yaml", "profiles/*.yaml", ".config/modules.yaml", ".config/*.json",
47
47
  "<project>/AGENTS.md", "<project>/summary.md", "<project>/FINDINGS.md", "<project>/truths.md",
@@ -83,25 +83,25 @@ export const BUILTIN_MODULES = [
83
83
  "/v1/health", "/v1/health/details", "/v1/health/peers", "/v1/muxes", "/v1/activity", "/v1/metrics", "/v1/web-servers", "/v1/simulators",
84
84
  "/v1/simulators/screenshot", "/v1/simulators/apps", "/v1/files", "/v1/models", "/v1/harnesses", "/v1/projects/files",
85
85
  "/v1/uploads/image", "/v1/files/range", "/v1/files/resolve", "/v1/usage", "/v1/resources", "/v1/speech/voices", "/v1/push/status", "/v1/projects/locate", "/v1/projects/repos",
86
- "/v1/workspaces", "/v1/workspaces/panes", "/v1/transcripts/blob", "/v1/transcripts/history", "/v1/sudo",
87
- "/v1/subagents", "/v1/subagents/transcript", "/v1/subagents/messages",
86
+ "/v1/workspaces", "/v1/workspaces/panes", "/v1/workspaces/layout", "/v1/transcripts/blob", "/v1/transcripts/history", "/v1/sudo",
87
+ "/v1/subagents", "/v1/subagents/transcript", "/v1/subagents/messages", "/v1/sessions/move", "/v1/sessions/moves",
88
88
  ]),
89
89
  ...routes("POST", [
90
- "/v1/push/register", "/v1/push/answer", "/v1/push/target", "/v1/files", "/v1/files/delete", "/v1/projects/add", "/v1/simulators/action",
90
+ "/v1/push/register", "/v1/push/answer", "/v1/push/target", "/v1/push/presence", "/v1/files", "/v1/files/delete", "/v1/projects/add", "/v1/simulators/action",
91
91
  "/v1/workspaces/launch", "/v1/workspaces/create", "/v1/workspaces/focus", "/v1/workspaces/rename",
92
- "/v1/workspaces/close", "/v1/sessions/rename", "/v1/prompt", "/v1/prompt/status", "/v1/model", "/v1/settings", "/v1/agents/permission-mode", "/v1/side-question/dismiss", "/v1/keys", "/v1/secret", "/v1/upload",
92
+ "/v1/workspaces/close", "/v1/sessions/rename", "/v1/sessions/move", "/v1/prompt", "/v1/prompt/status", "/v1/model", "/v1/settings", "/v1/agents/permission-mode", "/v1/side-question/dismiss", "/v1/keys", "/v1/secret", "/v1/upload",
93
93
  "/v1/approvals/answer", "/v1/questions/answer", "/v1/subagents/resume", "/v1/subagents/archive-finished", "/v1/canary",
94
94
  "/v1/speech", "/v1/sudo/answer", "/v1/jobs/cleanup",
95
95
  ]),
96
96
  ...routes("WS", ["/v1/transcripts", "/v1/status", "/v1/overview", "/v1/speech/transcribe", "/v1/speech/live"]),
97
97
  ],
98
98
  capabilities: [
99
- "hook", "transcript", "progress", "images", "prompt", "stop", "terminal", "shell", "herdr",
99
+ "hook", "transcript", "progress", "images", "prompt", "stop", "terminal", "shell", "paneTerminal", "paneLayout", "deskPresence", "herdr",
100
100
  "webServers", "webPreview", "activity", "approvals", "questions", "accountUsage", "providers",
101
- "files", "repositoryFiles", "fileResolution", "subagents", "sideQuestions", "approvalPush", "simulators", "overviewStream", "speech", "speechTimestamps", "speechTimestampStream", "speechLive", "speechVoices", "speechFormats", "transcribe", "promptOnce", "promptStatus", "deliveryFrames", "resources", "sessionRename", "sudo", "sudoOutcome", "previewDeltas", "quickChat", "agentFolder", "launchPermissionMode",
101
+ "files", "repositoryFiles", "fileResolution", "subagents", "sideQuestions", "approvalPush", "simulators", "overviewStream", "speech", "speechTimestamps", "speechTimestampStream", "speechLive", "speechVoices", "speechFormats", "transcribe", "promptOnce", "promptStatus", "deliveryFrames", "resources", "sessionRename", "sudo", "sudoOutcome", "previewDeltas", "quickChat", "agentFolder", "launchPermissionMode", "sessionMove",
102
102
  ],
103
103
  storeFiles: [".runtime/sessions/opencode-*.events.jsonl", ".runtime/approvals/opencode-*.json"],
104
- localFiles: ["<bridge>/installed.json", "<bridge>/versions/**", "<bridge>/current", "<bridge>/dispatch", "<bridge>/askpass", "<bridge>/computer-id", "<bridge>/canary.json", "<bridge>/canary-daily"],
104
+ localFiles: ["<bridge>/installed.json", "<bridge>/versions/**", "<bridge>/current", "<bridge>/dispatch", "<bridge>/askpass", "<bridge>/computer-id", "<bridge>/canary.json", "<bridge>/canary-daily", "<bridge>/moves/*.json"],
105
105
  phoneScreens: [{ screen: "LiveSessionsView", capability: "hook" }, { screen: "AgentChatView", capability: "transcript" }],
106
106
  skills: [],
107
107
  },
@@ -115,9 +115,9 @@ export const BUILTIN_MODULES = [
115
115
  hookRoutes: [...routes("GET", ["/v1/git/status"]), ...routes("POST", [
116
116
  "/v1/diff", "/v1/web-servers/session", "/v1/git/status", "/v1/git/log", "/v1/git/branches", "/v1/git/pulls",
117
117
  "/v1/git/tree", "/v1/git/worktrees", "/v1/git/stage", "/v1/git/unstage", "/v1/git/discard",
118
- "/v1/git/commit", "/v1/git/push", "/v1/git/pr",
118
+ "/v1/git/commit", "/v1/git/push", "/v1/git/pr", "/v1/git/pr/merge", "/v1/git/host-token", "/v1/git/show", "/v1/git/checkout", "/v1/git/fetch", "/v1/git/pull", "/v1/git/file", "/v1/git/apply", "/v1/git/session-changes", "/v1/files/write", "/v1/files/search", "/v1/files/list",
119
119
  ])],
120
- capabilities: ["git", "diff"], storeFiles: [], localFiles: ["<bridge>/changes/**", "<bridge>/changes-scratch/**"],
120
+ capabilities: ["git", "diff", "fileWrite", "fileSearch", "gitReview", "gitHosts"], storeFiles: [], localFiles: ["<bridge>/changes/**", "<bridge>/changes-scratch/**"],
121
121
  phoneScreens: [{ screen: "AgentChangesView", capability: "git" }], skills: [],
122
122
  },
123
123
  {
@@ -130,8 +130,8 @@ export const BUILTIN_MODULES = [
130
130
  },
131
131
  {
132
132
  schemaVersion: 1, name: "conductor", version: VERSION, defaultEnabled: false, requires: ["memory", "hook"],
133
- tools: full(["dispatch", "dispatch_returns", "dispatch_approve", "hand_off", "live_sessions", "account_usage", "authority", "dispatch_report", "owner_inbox"]), cliCommands: ["dispatch", "dispatch status", "dispatch returns", "dispatch sessions", "dispatch usage", "dispatch report", "hand-off", "conductor", "conductor grants", "conductor status", "conductor make", "conductor stop", "conductor sets", "conductor integrator", "owner-inbox", "authority", "bridge enroll-computer"], agentHooks: [],
134
- hookRoutes: [...routes("GET", ["/v1/dispatch", "/v1/dispatch/capacity", "/v1/dispatch/arrival", "/v1/conductor", "/v1/conductor/grants", "/v1/computers", "/v1/sets", "/v1/authority", "/v1/owner-inbox", "/v1/conductor/integrator"]),
133
+ tools: full(["dispatch", "dispatch_returns", "dispatch_approve", "hand_off", "live_sessions", "account_usage", "authority", "dispatch_report", "owner_inbox", "move_session"]), cliCommands: ["dispatch", "dispatch status", "dispatch returns", "dispatch sessions", "dispatch usage", "dispatch report", "hand-off", "move", "conductor", "conductor grants", "conductor status", "conductor make", "conductor stop", "conductor sets", "conductor integrator", "owner-inbox", "authority", "bridge enroll-computer"], agentHooks: [],
134
+ hookRoutes: [...routes("GET", ["/v1/dispatch", "/v1/dispatch/capacity", "/v1/dispatch/arrival", "/v1/dispatch/brief", "/v1/conductor", "/v1/conductor/grants", "/v1/computers", "/v1/sets", "/v1/authority", "/v1/owner-inbox", "/v1/conductor/integrator"]),
135
135
  ...routes("POST", ["/v1/dispatch", "/v1/dispatch/workers", "/v1/dispatch/returns", "/v1/dispatch/approve", "/v1/dispatch/report", "/v1/dispatch/close", "/v1/owner-inbox", "/v1/conductor/integrator", "/v1/hand-off", "/v1/hand-off/status", "/v1/conductor/grants", "/v1/conductor/make", "/v1/conductor/stop", "/v1/sets/name", "/v1/authority", "/v1/authority/confirm"]), ...routes("DELETE", ["/v1/conductor/grants", "/v1/authority"])],
136
136
  capabilities: ["dispatch", "conductorSets", "ownerInbox", "workerReports", "queuedHandOff"], storeFiles: ["global/skills/conductor/**"],
137
137
  localFiles: ["<bridge>/hooks.yaml", "<bridge>/conductor.yaml", "<bridge>/conductor-role.json", "<bridge>/conductor/brief.md", "<bridge>/authority.yaml", "<bridge>/authority-confirmations.json", "<bridge>/dispatches/*.json", "<bridge>/hand-offs/*.json", "<bridge>/worker-reports/*.json", "<bridge>/closed-workers/*.json", "<bridge>/owner-inbox.json", "<bridge>/integrator.json"], phoneScreens: [], skills: ["conductor"],
@@ -33,6 +33,12 @@ export interface ProjectConfig {
33
33
  sourcePath?: string;
34
34
  /** Per-machine source folders, keyed by `getMachineName()`. Wins over `sourcePath`. */
35
35
  sourcePaths?: Record<string, string>;
36
+ /**
37
+ * The repository's clone URL on any host (`https://…`, `ssh://…`,
38
+ * `git@host:owner/repo.git`). Lets a Git server such as gitboy match one of
39
+ * its repositories to this project. Optional; never used to fetch.
40
+ */
41
+ remote?: string;
36
42
  skills?: boolean;
37
43
  hooks?: {
38
44
  enabled?: boolean;
@@ -61,6 +67,12 @@ export declare function updateProjectConfigOverrides(phrenPath: string, project:
61
67
  * when nothing more specific was recorded.
62
68
  */
63
69
  export declare function getProjectSourcePath(phrenPath: string, project: string, config?: ProjectConfig, machine?: string): string | undefined;
70
+ /**
71
+ * The project's `remote:` clone URL, safe to hand to another program: a
72
+ * string of a known clone form, with any password (and, for http(s), the user
73
+ * name) removed. Anything else, including local paths, reads as null.
74
+ */
75
+ export declare function getProjectRemote(phrenPath: string, project: string, config?: ProjectConfig): string | null;
64
76
  /**
65
77
  * Record `sourceRoot` as this machine's folder for the project, alongside the
66
78
  * legacy shared `sourcePath` older CLIs read.
@@ -122,6 +122,35 @@ export function getProjectSourcePath(phrenPath, project, config, machine = getMa
122
122
  const raw = typeof perMachine === "string" && perMachine.trim() ? perMachine : resolved.sourcePath;
123
123
  return typeof raw === "string" && raw.trim() ? path.resolve(raw) : undefined;
124
124
  }
125
+ /**
126
+ * The project's `remote:` clone URL, safe to hand to another program: a
127
+ * string of a known clone form, with any password (and, for http(s), the user
128
+ * name) removed. Anything else, including local paths, reads as null.
129
+ */
130
+ export function getProjectRemote(phrenPath, project, config) {
131
+ const raw = (config ?? readProjectConfig(phrenPath, project)).remote;
132
+ if (typeof raw !== "string")
133
+ return null;
134
+ const value = raw.trim();
135
+ if (!value || value.length > 2048 || /[\s\x00-\x1f\x7f]/.test(value))
136
+ return null;
137
+ // scp form: [user@]host:path, where host is not a single drive letter.
138
+ if (!/^file:/i.test(value) && /^(?:[A-Za-z0-9._-]+@)?[A-Za-z0-9.-]{2,}:(?!\/\/)[^:]+$/.test(value))
139
+ return value;
140
+ let url;
141
+ try {
142
+ url = new URL(value);
143
+ }
144
+ catch {
145
+ return null;
146
+ }
147
+ if (!["https:", "http:", "ssh:", "git:"].includes(url.protocol) || !url.hostname || url.search || url.hash)
148
+ return null;
149
+ url.password = "";
150
+ if (url.protocol === "https:" || url.protocol === "http:")
151
+ url.username = "";
152
+ return url.toString();
153
+ }
125
154
  /**
126
155
  * Record `sourceRoot` as this machine's folder for the project, alongside the
127
156
  * legacy shared `sourcePath` older CLIs read.
@@ -28,6 +28,7 @@ export declare function wantsTasks(prompt: string, intent: ReturnType<typeof det
28
28
  export declare function detectTaskIntent(prompt: string): "debug" | "review" | "build" | "docs" | "skill" | "general";
29
29
  export declare function fileRelevanceBoost(filePath: string, changedFiles: Set<string>): number;
30
30
  export declare function branchMatchBoost(content: string, branch: string | undefined): number;
31
+ export declare function tokenizeForOverlap(text: string, maxTokens?: number): string[];
31
32
  /** A doc's bullets (with their continuation lines) or, with none, its
32
33
  * paragraphs: the unit relevance is judged on. Topic archives are one doc
33
34
  * with hundreds of bullets, so a whole-file score matches almost anything. */
@@ -189,7 +189,7 @@ function normalizeToken(token) {
189
189
  normalized = normalized.slice(0, -1);
190
190
  return normalized;
191
191
  }
192
- function tokenizeForOverlap(text, maxTokens = 24) {
192
+ export function tokenizeForOverlap(text, maxTokens = 24) {
193
193
  const tokens = text
194
194
  .toLowerCase()
195
195
  .replace(/[^a-z0-9_\-\s]/g, " ")
@@ -20,7 +20,7 @@ import { debugLog, EXEC_TIMEOUT_MS } from "../shared.js";
20
20
  import { errorMessage } from "../utils.js";
21
21
  import { nonInteractiveGitEnv } from "../utils-helpers.js";
22
22
  import { mergeFindings, mergeTask } from "../content/validate.js";
23
- import { KNOWS_END, KNOWS_START, NOW_END, NOW_START, upsertBlock } from "../content/summarize.js";
23
+ import { cleanBlock, KNOWS_END, KNOWS_START, NOW_END, NOW_START, upsertBlock } from "../content/summarize.js";
24
24
  import { mergeTasksByBid } from "./task-merge.js";
25
25
  export function conflictStrategy(relFile) {
26
26
  const file = relFile.replace(/\\/g, "/");
@@ -55,12 +55,11 @@ function stage(cwd, n, relFile) {
55
55
  return null;
56
56
  }
57
57
  }
58
- const BLOCK_RE = (start, end) => new RegExp(`${start.replace("-->", "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[^\\n]*-->[\\s\\S]*?${end.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\n*`);
59
58
  function splitBlock(content, start, end) {
60
- const match = BLOCK_RE(start, end).exec(content);
61
- if (!match)
62
- return { rest: content, block: null };
63
- return { rest: content.slice(0, match.index) + content.slice(match.index + match[0].length), block: match[0].replace(/\n+$/, "") };
59
+ // The whole span, first start to last end, rebuilt as one copy: an earlier
60
+ // union merge may have left two start lines (and two bodies) behind.
61
+ const clean = cleanBlock(content, start, end);
62
+ return clean ?? { rest: content, block: null };
64
63
  }
65
64
  /** A line-level three-way merge through `git merge-file`; null when lines still conflict. */
66
65
  function mergeText(base, ours, theirs) {
@@ -3,12 +3,13 @@ import { ownerInboxSchema } from "../bridge/owner-inbox.js";
3
3
  import { z } from "zod";
4
4
  import { hookRequest } from "../bridge/client.js";
5
5
  import { dispatchSchema } from "../bridge/dispatch.js";
6
- import { handOff, handOffSchema, listLiveSessions } from "../bridge/hand-off.js";
6
+ import { handOff, handOffSchema, listLiveSessions, moveSession, moveSessionSchema } from "../bridge/hand-off.js";
7
7
  import { readAccountUsage, usageSummary } from "../bridge/account-usage.js";
8
8
  import { terminalPaneFromEnv } from "../bridge/terminal.js";
9
9
  import { dispatchIdFromEnv } from "../bridge/launch-brief.js";
10
10
  import { approvalDecisions } from "../bridge/protocol.js";
11
11
  import { mcpResponse } from "./types.js";
12
+ const object = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
12
13
  export function register(server) {
13
14
  server.registerTool("dispatch", {
14
15
  title: "◆ phren · dispatch",
@@ -59,7 +60,7 @@ export function register(server) {
59
60
  });
60
61
  server.registerTool("dispatch_returns", {
61
62
  title: "◆ phren · dispatch returns",
62
- description: "List unread returns from dispatched workers and mark them read: the worker finished (done, with its final reply), finished by asking the owner something (needs-you, with the question), failed (the harness ended the turn on an error such as a usage limit, with the error), is blocked on terminal input, or its pane is gone. A blocked row with an `approval` field (actionId, tool, request) is a permission request the worker is waiting on, forwarded from its computer: answer it with dispatch_approve. A worker that ended its turn with background tasks pending is waited on for up to two hours; a row has `waited` (the most tasks it waited on) or, if some were still running after that, `background`. A stalled row flags an unchanged working screen and transcript. A done row can include structured prs and integratorDelivery. Reading a done return closes its finished pane unless closeOnFinish:false was specified, after rechecking new and queued work. Each row has the dispatch id, computer, project, label and the worker's target for hand_off.",
63
+ description: "List unread returns from dispatched workers and mark them read: the worker finished (done, with its final reply), finished by asking the owner something (needs-you, with the question), failed (the harness ended the turn on an error such as a usage limit, with the error), is blocked on terminal input, or its pane is gone. A blocked row with an `approval` field (actionId, tool, request) is a permission request the worker is waiting on, forwarded from its computer: answer it with dispatch_approve. A worker that ended its turn with background tasks pending is waited on for up to two hours; a row has `waited` (the most tasks it waited on) or, if some were still running after that, `background`. A stalled row flags an unchanged working screen and transcript. A done row can include structured prs and integratorDelivery. Reading a done return closes its finished pane unless closeOnFinish:false was specified, after rechecking new and queued work. Each row has the dispatch id, computer, project, label and the worker's target for hand_off. When the owner has turned on `phren config account-failover on` (off by default), a Claude worker that stopped at its usage limit is continued on another signed-in account with room (same computer first, never the same login before its window resets): its row comes back with continued (the new dispatch id, computer and account, or why none could) and the error says \"Continued on account X\".",
63
64
  inputSchema: {},
64
65
  }, async () => {
65
66
  try {
@@ -91,7 +92,7 @@ export function register(server) {
91
92
  });
92
93
  server.registerTool("live_sessions", {
93
94
  title: "◆ phren · live sessions",
94
- description: "List the live agent sessions on this computer and every enrolled computer: computer, project, harness, status (working, with backgroundTasks, while background work runs after the main turn ended), idleFor (seconds since the tab last changed), role and the target hand_off takes. Computers that could not be reached are listed separately, and computers registered in the store but not linked in hooks.yaml come back in notLinked: their sessions are unknown, not absent.",
95
+ description: "List the live agent sessions on this computer and every enrolled computer: computer, project, harness, status (working, with backgroundTasks, while background work runs after the main turn ended), idleFor (seconds since the tab last changed), role, the target hand_off takes, and for Claude sessions quota (the account's 5-hour and weekly percent left and reset time). claudeAccounts lists every signed-in Claude account per computer with the same room. Computers that could not be reached are listed separately, and computers registered in the store but not linked in hooks.yaml come back in notLinked: their sessions are unknown, not absent.",
95
96
  inputSchema: {},
96
97
  }, async () => {
97
98
  try {
@@ -134,6 +135,22 @@ export function register(server) {
134
135
  return mcpResponse({ ok: false, error: error instanceof Error ? error.message : "Could not read the release authority policy." });
135
136
  }
136
137
  });
138
+ server.registerTool("move_session", {
139
+ title: "◆ phren · move session",
140
+ description: "Move a live session to another agent on its own computer: the agent writes a structured hand-off (goal, done, current state, decisions, next steps, open questions, key files), exits with its own exit command, and the target harness (claude with an optional account, codex, opencode or copilot, with an optional model and effort) starts in the same pane and folder with that hand-off as its first prompt. If the agent writes no hand-off in time, Phren builds one from the end of its transcript, the git state and the original brief. Nothing is committed; the hand-off lists the uncommitted changes. Only harnesses signed in and usable on that computer are accepted. A dispatched worker keeps its dispatch: its receipt follows the new agent and records the move under moves. Waits up to five minutes; pass id with status:true to check a move later.",
141
+ inputSchema: moveSessionSchema,
142
+ }, async (input) => {
143
+ try {
144
+ const result = await moveSession(input);
145
+ const move = result.move;
146
+ const message = move.state === "moved" ? `Moved to ${String(object(move.to).harness)} (${String(move.placement)}); hand-off at ${String(object(move.handoff).path)}.`
147
+ : move.state === "failed" ? `Move failed: ${String(move.error ?? "unknown error")}` : `Move ${String(move.id)} is ${String(move.state)}; check again with status:true.`;
148
+ return mcpResponse({ ok: result.ok, data: result, message });
149
+ }
150
+ catch (error) {
151
+ return mcpResponse({ ok: false, error: error instanceof Error ? error.message : "Could not move the session." });
152
+ }
153
+ });
137
154
  server.registerTool("hand_off", {
138
155
  title: "◆ phren · hand off",
139
156
  description: "Deliver a prompt to an existing local or enrolled-computer agent session through Phren Hook. Busy workers receive a durable queued message at their next idle. Keep deliveryId on retries. Use status:true with deliveryId and target or session to read queued, delivered, uncertain or failed without sending. Uncertain delivery is never retried automatically.",
@@ -1,6 +1,31 @@
1
1
  import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { type McpContext } from "./types.js";
3
+ import { FINDING_TYPES } from "../shared.js";
3
4
  export declare function findConflictCandidates(phrenPath: string, project: string, finding: string): string[];
5
+ export declare function handleAddFinding(ctx: McpContext, params: {
6
+ /** Provenance `tool:` for a caller other than an MCP client (the Hook's gitboy route). */
7
+ tool?: string;
8
+ project: string;
9
+ finding: string | string[];
10
+ citation?: {
11
+ file?: string;
12
+ line?: number;
13
+ repo?: string;
14
+ commit?: string;
15
+ name?: string;
16
+ symbol?: string;
17
+ supersedes?: string;
18
+ task_item?: string;
19
+ };
20
+ sessionId?: string;
21
+ findingType?: (typeof FINDING_TYPES)[number];
22
+ scope?: string;
23
+ }): Promise<{
24
+ content: {
25
+ type: "text";
26
+ text: string;
27
+ }[];
28
+ }>;
4
29
  export interface TeamStoreSyncResult {
5
30
  store: string;
6
31
  pushed: boolean;
@@ -117,7 +117,7 @@ function withLifecycleMutation(phrenPath, project, writeQueue, updateIndex, hand
117
117
  });
118
118
  }
119
119
  // ── Handlers ─────────────────────────────────────────────────────────────────
120
- async function handleAddFinding(ctx, params) {
120
+ export async function handleAddFinding(ctx, params) {
121
121
  const { finding, sessionId, findingType, scope } = params;
122
122
  // `name` is the citation's code link (a function, type or variable);
123
123
  // `symbol` is its deprecated spelling, accepted until 0.3.1. The stored
@@ -148,6 +148,7 @@ async function handleAddFinding(ctx, params) {
148
148
  machine: getMachineName(),
149
149
  actor: getCurrentActor(),
150
150
  session_id: sessionId,
151
+ ...(params.tool ? { tool: params.tool } : {}),
151
152
  };
152
153
  const normalizedScope = normalizeMemoryScope(scope ?? "shared");
153
154
  if (!normalizedScope)