@phren/cli 0.3.37 → 0.3.40

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 (96) hide show
  1. package/dist/bridge/account-failover.d.ts +4 -0
  2. package/dist/bridge/account-failover.js +12 -4
  3. package/dist/bridge/account-usage.d.ts +5 -2
  4. package/dist/bridge/account-usage.js +36 -6
  5. package/dist/bridge/agent-hooks.js +2 -0
  6. package/dist/bridge/changes.d.ts +5 -0
  7. package/dist/bridge/changes.js +4 -0
  8. package/dist/bridge/claude-accounts.d.ts +15 -4
  9. package/dist/bridge/claude-accounts.js +31 -16
  10. package/dist/bridge/claude-credits.d.ts +43 -0
  11. package/dist/bridge/claude-credits.js +236 -0
  12. package/dist/bridge/claude-question-dialog.js +6 -2
  13. package/dist/bridge/command.js +64 -3
  14. package/dist/bridge/conductor-sets.d.ts +5 -0
  15. package/dist/bridge/conductor-sets.js +23 -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 +7 -0
  21. package/dist/bridge/dispatch-returns.js +56 -6
  22. package/dist/bridge/dispatch.d.ts +52 -0
  23. package/dist/bridge/dispatch.js +14 -0
  24. package/dist/bridge/enroll.js +22 -4
  25. package/dist/bridge/file-range.d.ts +3 -0
  26. package/dist/bridge/file-range.js +5 -4
  27. package/dist/bridge/file-search.d.ts +37 -0
  28. package/dist/bridge/file-search.js +87 -0
  29. package/dist/bridge/file-write.d.ts +6 -0
  30. package/dist/bridge/file-write.js +120 -0
  31. package/dist/bridge/git-host-auth.d.ts +31 -0
  32. package/dist/bridge/git-host-auth.js +110 -0
  33. package/dist/bridge/git-host-gitboy.d.ts +46 -0
  34. package/dist/bridge/git-host-gitboy.js +296 -0
  35. package/dist/bridge/git-host-gitlab.d.ts +25 -0
  36. package/dist/bridge/git-host-gitlab.js +229 -0
  37. package/dist/bridge/git-host-http.d.ts +33 -0
  38. package/dist/bridge/git-host-http.js +70 -0
  39. package/dist/bridge/git-hosts.d.ts +92 -0
  40. package/dist/bridge/git-hosts.js +244 -0
  41. package/dist/bridge/git-publish.d.ts +15 -5
  42. package/dist/bridge/git-publish.js +69 -21
  43. package/dist/bridge/git-review.d.ts +23 -0
  44. package/dist/bridge/git-review.js +170 -0
  45. package/dist/bridge/git-sync.d.ts +14 -0
  46. package/dist/bridge/git-sync.js +143 -0
  47. package/dist/bridge/git.d.ts +20 -7
  48. package/dist/bridge/git.js +87 -68
  49. package/dist/bridge/gitboy-contract.d.ts +32 -0
  50. package/dist/bridge/gitboy-contract.js +46 -0
  51. package/dist/bridge/hand-off.d.ts +52 -2
  52. package/dist/bridge/hand-off.js +77 -24
  53. package/dist/bridge/health.d.ts +1 -1
  54. package/dist/bridge/health.js +5 -3
  55. package/dist/bridge/install.d.ts +14 -0
  56. package/dist/bridge/install.js +40 -1
  57. package/dist/bridge/memory-store.d.ts +8 -0
  58. package/dist/bridge/memory-store.js +80 -2
  59. package/dist/bridge/pair.d.ts +6 -1
  60. package/dist/bridge/pair.js +74 -2
  61. package/dist/bridge/project-memory.d.ts +94 -0
  62. package/dist/bridge/project-memory.js +235 -0
  63. package/dist/bridge/push.d.ts +15 -0
  64. package/dist/bridge/push.js +39 -0
  65. package/dist/bridge/scoped-gateway.d.ts +29 -0
  66. package/dist/bridge/scoped-gateway.js +239 -0
  67. package/dist/bridge/server-launch.d.ts +12 -0
  68. package/dist/bridge/server-launch.js +17 -10
  69. package/dist/bridge/server-pane-routes.js +54 -3
  70. package/dist/bridge/server-routes.d.ts +13 -0
  71. package/dist/bridge/server-routes.js +63 -5
  72. package/dist/bridge/server.js +44 -5
  73. package/dist/bridge/session-move.d.ts +288 -0
  74. package/dist/bridge/session-move.js +600 -0
  75. package/dist/bridge/subscription.d.ts +15 -0
  76. package/dist/bridge/subscription.js +23 -0
  77. package/dist/bridge/transport.js +21 -1
  78. package/dist/bridge/usage.d.ts +20 -3
  79. package/dist/bridge/usage.js +61 -11
  80. package/dist/bridge-hook.mjs +12822 -3248
  81. package/dist/cli-registry.js +10 -4
  82. package/dist/computers/command.js +3 -1
  83. package/dist/computers/read.d.ts +3 -0
  84. package/dist/computers/read.js +6 -0
  85. package/dist/content/summarize.d.ts +21 -0
  86. package/dist/content/summarize.js +56 -18
  87. package/dist/modules/registry.js +14 -14
  88. package/dist/project-config.d.ts +12 -0
  89. package/dist/project-config.js +29 -0
  90. package/dist/shared/retrieval.d.ts +1 -0
  91. package/dist/shared/retrieval.js +1 -1
  92. package/dist/sync/conflict-resolve.js +5 -6
  93. package/dist/tools/dispatch.js +18 -1
  94. package/dist/tools/finding.d.ts +25 -0
  95. package/dist/tools/finding.js +2 -1
  96. package/package.json +57 -1
@@ -1,10 +1,12 @@
1
1
  import path from "node:path";
2
2
  import { setTimeout as sleep } from "node:timers/promises";
3
3
  import { z } from "zod";
4
- import { gitBranches, gitDiscard, gitLog, gitPulls, gitStage, gitStatus, gitTree, gitUnstage } from "./git.js";
4
+ import { gitBranches, gitDiscard, gitLog, gitPulls, gitShow, gitStage, gitStatus, gitTree, gitUnstage } from "./git.js";
5
5
  import { fanoutWorktrees } from "./fanouts.js";
6
6
  import { gitWorktrees, resolveWorktree } from "./git-worktrees.js";
7
- import { gitCommit, gitPullRequest, gitPush } from "./git-publish.js";
7
+ import { gitCommit, gitHostToken, gitMergeRequest, gitPullRequest, gitPush } from "./git-publish.js";
8
+ import { gitCheckout, gitFetch, gitPull } from "./git-sync.js";
9
+ import { gitApply, gitFile, sessionChanges } from "./git-review.js";
8
10
  import { findPane, paneAgentName, paneChatState, paneIdentity, snapshot, startingPane, trustedDirectory, validateStartingTarget, validateTarget } from "./herdr.js";
9
11
  import { agentNotReady, terminalProvider } from "./terminal.js";
10
12
  import { AppServerRpcError } from "./codex-app-server.js";
@@ -17,6 +19,8 @@ import { BridgeError, MAX_FRAME, object, objects, startingTargetSchema, targetSc
17
19
  import { childAgent, childAgentTree, conversationNamedPaths, targetTranscriptPath } from "./transcripts.js";
18
20
  import { sideQuestionText } from "./side-questions.js";
19
21
  import { saveUpload } from "./uploads.js";
22
+ import { writeRepoFile } from "./file-write.js";
23
+ import { fileSearchSchema, listRepositoryFiles, searchRepository } from "./file-search.js";
20
24
  import { deliveryIdSchema, PromptOnce, promptScope } from "./prompt-once.js";
21
25
  import { promptWithStartupRetry } from "./prompt-startup.js";
22
26
  import { sendServedPrompt, servedPane } from "./opencode-panes.js";
@@ -652,11 +656,35 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
652
656
  result = await repositoryDiff(cwd, paths, allowed);
653
657
  }
654
658
  }
659
+ else if (url.pathname === "/v1/files/write") {
660
+ // The desktop editor's save, inside the pane's repository (or a child's worktree).
661
+ const cwd = await gitRepository(pane, target, data.child, data.worktree);
662
+ const repository = await gitRoot(cwd);
663
+ if (!repository)
664
+ throw new BridgeError(409, "This pane is not in a project repository.");
665
+ result = await writeRepoFile(repository, z.string().max(4096).parse(data.path), z.string().parse(data.content), data.version === undefined ? undefined : z.string().max(200).parse(data.version));
666
+ }
667
+ else if (url.pathname === "/v1/files/list") {
668
+ // Every file path in the repository, for the desktop editor's quick open.
669
+ const repository = await gitRoot(await gitRepository(pane, target, data.child, data.worktree));
670
+ if (!repository)
671
+ throw new BridgeError(409, "This pane is not in a project repository.");
672
+ result = await listRepositoryFiles(repository);
673
+ }
674
+ else if (url.pathname === "/v1/files/search") {
675
+ // The desktop editor's find in files, over the same repository.
676
+ const repository = await gitRoot(await gitRepository(pane, target, data.child, data.worktree));
677
+ if (!repository)
678
+ throw new BridgeError(409, "This pane is not in a project repository.");
679
+ result = await searchRepository(repository, fileSearchSchema.parse({
680
+ query: data.query, regex: data.regex, caseSensitive: data.caseSensitive, wholeWord: data.wholeWord, include: data.include, limit: data.limit,
681
+ }));
682
+ }
655
683
  else if (url.pathname.startsWith("/v1/git/")) {
656
684
  // Git routes read the pane's repository, or a spawned child's own
657
685
  // worktree, exactly as /v1/diff resolves it.
658
686
  let cwd = await gitRepository(pane, target, data.child, data.worktree);
659
- if (["stage", "unstage", "discard", "commit", "push", "pr"].some(action => url.pathname === `/v1/git/${action}`)
687
+ if (["stage", "unstage", "discard", "commit", "push", "pr", "pr/merge", "host-token", "checkout", "fetch", "pull", "apply"].some(action => url.pathname === `/v1/git/${action}`)
660
688
  && data.expectedRepository !== undefined) {
661
689
  const expected = z.string().min(1).max(4096).refine(value => path.isAbsolute(value) && !value.includes("\0"), "Expected an absolute repository path.").parse(data.expectedRepository);
662
690
  const root = await gitRoot(cwd);
@@ -688,6 +716,29 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
688
716
  result = await gitPush(cwd, data.confirmDefault);
689
717
  else if (url.pathname === "/v1/git/pr")
690
718
  result = await gitPullRequest(cwd, data.draft);
719
+ else if (url.pathname === "/v1/git/pr/merge")
720
+ result = await gitMergeRequest(cwd, data);
721
+ else if (url.pathname === "/v1/git/host-token")
722
+ result = await gitHostToken(cwd, data);
723
+ else if (url.pathname === "/v1/git/show")
724
+ result = await gitShow(cwd, data.sha);
725
+ else if (url.pathname === "/v1/git/checkout")
726
+ result = await gitCheckout(cwd, data);
727
+ else if (url.pathname === "/v1/git/fetch")
728
+ result = await gitFetch(cwd);
729
+ else if (url.pathname === "/v1/git/pull")
730
+ result = await gitPull(cwd);
731
+ else if (url.pathname === "/v1/git/file")
732
+ result = await gitFile(cwd, data.ref, data.path);
733
+ else if (url.pathname === "/v1/git/apply")
734
+ result = await gitApply(cwd, data.patch, data.reverse);
735
+ else if (url.pathname === "/v1/git/session-changes") {
736
+ // This conversation's own recorded edits, in the repository the route resolved.
737
+ const root = await gitRoot(cwd);
738
+ if (!root)
739
+ throw new BridgeError(409, "This pane is not in a Git repository.", { code: "git-not-repository" });
740
+ result = sessionChanges(root, await agentHooks.changes.history(`${target.source}:${target.session}`));
741
+ }
691
742
  else
692
743
  throw new BridgeError(404, "Unknown Phren Hook route.");
693
744
  }
@@ -1,3 +1,4 @@
1
+ import { type SessionMover } from "./session-move.js";
1
2
  import type { OwnerInbox } from "./owner-inbox.js";
2
3
  import type { HandOffQueue } from "./hand-off-queue.js";
3
4
  import type { IncomingMessage, ServerResponse } from "node:http";
@@ -55,6 +56,7 @@ export interface RouteContext {
55
56
  returns?: DispatchReturns;
56
57
  handOffs?: HandOffQueue;
57
58
  inbox?: OwnerInbox;
59
+ mover?: SessionMover;
58
60
  agentHooks: AgentHooks;
59
61
  journal: ActivityJournal;
60
62
  tabActivity: TabActivityStore;
@@ -83,6 +85,9 @@ export declare const capabilities: {
83
85
  stop: boolean;
84
86
  terminal: string;
85
87
  shell: string;
88
+ paneTerminal: string;
89
+ paneLayout: boolean;
90
+ deskPresence: boolean;
86
91
  herdr: boolean;
87
92
  sessionRename: boolean;
88
93
  diff: boolean;
@@ -100,6 +105,7 @@ export declare const capabilities: {
100
105
  sideQuestions: boolean;
101
106
  dispatch: boolean;
102
107
  conductorSets: boolean;
108
+ setLink: boolean;
103
109
  ownerInbox: boolean;
104
110
  workerReports: boolean;
105
111
  queuedHandOff: boolean;
@@ -127,6 +133,13 @@ export declare const capabilities: {
127
133
  quickChat: boolean;
128
134
  agentFolder: boolean;
129
135
  launchPermissionMode: boolean;
136
+ sessionMove: boolean;
137
+ projectMemory: boolean;
138
+ fileWrite: boolean;
139
+ fileSearch: boolean;
140
+ gitReview: boolean;
141
+ memoryStoreBatch: boolean;
142
+ gitHosts: boolean;
130
143
  };
131
144
  export declare function capabilitiesForModules(snapshot: ModuleSnapshot): Record<string, unknown>;
132
145
  export declare function requireRoute(snapshot: ModuleSnapshot, method: string, route: string): void;
@@ -1,3 +1,4 @@
1
+ import { listMoves, readMove } from "./session-move.js";
1
2
  import { getTaskRoute, getTaskDirectoryRoute, updateTaskRoute, createTaskRoute, saveTaskRoute, launchTaskRoute } from "./task-routes.js";
2
3
  import { ownerInboxView } from "./owner-inbox-view.js";
3
4
  import { closeFinishedWorker } from "./worker-close.js";
@@ -26,8 +27,9 @@ import { browseFiles } from "./files.js";
26
27
  import { MAX_FILE_RANGE, rangeInteger, readFileRange } from "./file-range.js";
27
28
  import { resolveFilePath } from "./file-resolve.js";
28
29
  import { storeRoute } from "./memory-store.js";
30
+ import { memoryForFiles, memorySearch, PROJECT_MEMORY_ROUTE, projectMemory, saveFinding, tasksForBranch } from "./project-memory.js";
29
31
  import { liveBackground, markBackground, paneRecord, recordTitle } from "./session-activity.js";
30
- import { paneAccountField, paneChatState, panes, servers, snapshot, validateTarget, workspaceSnapshot } from "./herdr.js";
32
+ import { paneAccountField, paneChatState, panes, rpc, servers, snapshot, validateTarget, workspaceSnapshot } from "./herdr.js";
31
33
  import { locateProject } from "./locate.js";
32
34
  import { gitStatus } from "./git.js";
33
35
  import { gitRoot, launchDirectory, repositoryBranch, webServers, withGitReadDeadline } from "./projects.js";
@@ -44,7 +46,7 @@ import { loadCodePackage, loadedFrom } from "../modules/code-package.js";
44
46
  import { gitRepository, paneRoute, uploadBody } from "./server-pane-routes.js";
45
47
  import { renameSession } from "./session-rename.js";
46
48
  import { launchSession, makeConductor, stopConductor, workspaceAction } from "./server-launch.js";
47
- import { conductorAnswer, nameSet, readSets } from "./conductor-sets.js";
49
+ import { conductorAnswer, linkSetMember, nameSet, readSets } from "./conductor-sets.js";
48
50
  import { conductorPane } from "./conductor-role.js";
49
51
  import { hookMetrics } from "./metrics.js";
50
52
  import { SPEECH_FORMATS, streamSpeech } from "./speech.js";
@@ -74,9 +76,9 @@ async function childActivity(source, session) {
74
76
  return result;
75
77
  }
76
78
  export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
77
- terminal: "ssh-pty", shell: "ssh-pty", herdr: true, sessionRename: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
79
+ terminal: "ssh-pty", shell: "ssh-pty", paneTerminal: "ssh-pty", paneLayout: true, deskPresence: true, herdr: true, sessionRename: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
78
80
  approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
79
- files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true };
81
+ files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true };
80
82
  export function capabilitiesForModules(snapshot) {
81
83
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
82
84
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
@@ -306,7 +308,27 @@ export function createRouteHandler(ctx) {
306
308
  throw new BridgeError(400, "Invalid request origin.");
307
309
  requireRoute(modules, request.method ?? "", url.pathname);
308
310
  let result;
309
- if (url.pathname.startsWith("/v1/store/")) {
311
+ const memoryRoute = PROJECT_MEMORY_ROUTE.exec(url.pathname);
312
+ if (memoryRoute) {
313
+ const [, project, route] = memoryRoute;
314
+ if (request.method !== (route === "findings" ? "POST" : "GET"))
315
+ throw new BridgeError(405, "Unsupported request method.");
316
+ if (!modules.has("memory"))
317
+ throw new BridgeError(404, disabledHint("memory"));
318
+ if (route === "tasks" && !modules.has("tasks"))
319
+ throw new BridgeError(404, disabledHint("tasks"));
320
+ if (route === "memory")
321
+ result = projectMemory(modules.store, project);
322
+ else if (route === "memory/files")
323
+ result = await memoryForFiles(modules.store, project, url.searchParams.getAll("path"));
324
+ else if (route === "memory/search")
325
+ result = memorySearch(modules.store, project, url.searchParams.get("q") ?? "", Number(url.searchParams.get("limit") ?? "5"));
326
+ else if (route === "tasks")
327
+ result = tasksForBranch(modules.store, project, url.searchParams.get("branch") ?? "");
328
+ else
329
+ result = await saveFinding(modules.store, project, await body(request));
330
+ }
331
+ else if (url.pathname.startsWith("/v1/store/")) {
310
332
  result = await storeRoute(modules.store, request.method ?? "", url, request.method === "POST" ? await body(request) : undefined);
311
333
  }
312
334
  else if (request.method === "GET") {
@@ -343,6 +365,17 @@ export function createRouteHandler(ctx) {
343
365
  case "/v1/dispatch":
344
366
  result = { dispatches: await dispatchStatus() };
345
367
  break;
368
+ // A session move (session-move.ts) by its id, or this computer's recent moves.
369
+ case "/v1/sessions/move": {
370
+ const move = await readMove(z.string().uuid().parse(url.searchParams.get("id")));
371
+ if (!move)
372
+ throw new BridgeError(404, "No move with that id on this computer.");
373
+ result = { move };
374
+ break;
375
+ }
376
+ case "/v1/sessions/moves":
377
+ result = { moves: (await listMoves()).slice(0, 50) };
378
+ break;
346
379
  // Receiving side of a launched brief: what the worker's hooks reported for it.
347
380
  case "/v1/dispatch/arrival":
348
381
  result = { arrival: await briefArrival(briefId.parse(url.searchParams.get("id"))) ?? null };
@@ -546,6 +579,17 @@ export function createRouteHandler(ctx) {
546
579
  result = muxReplyForClient(await readWorkspaces(server, await snapshot(server), url.searchParams.get("watchApprovals") === "1"), typedMuxRequest(url));
547
580
  break;
548
581
  }
582
+ case "/v1/workspaces/layout": {
583
+ // A Herdr tab's split layout (pane rects and splits) around one of its panes, for
584
+ // Phren desktop's mirror of a Herdr tab. Herdr only: tmux has no such query here.
585
+ const server = selectedServer(url);
586
+ if (terminalKind(server) !== "herdr")
587
+ throw new BridgeError(501, "Pane layouts need Herdr.");
588
+ const pane = z.string().regex(/^[A-Za-z0-9_:.-]{1,100}$/).parse(url.searchParams.get("pane"));
589
+ const answer = await rpc(server, "pane.layout", { pane_id: pane });
590
+ result = { layout: object(answer).layout ?? null };
591
+ break;
592
+ }
549
593
  case "/v1/workspaces/panes":
550
594
  result = muxReplyForClient(await panes(selectedServer(url), url.searchParams.get("groupId") || "", url.searchParams.get("childId") || ""), typedMuxRequest(url));
551
595
  break;
@@ -692,6 +736,12 @@ export function createRouteHandler(ctx) {
692
736
  harness: note.target && "harness" in note.target ? note.target.harness : "codex", prompt, label: `Code note: ${note.symbol}`.slice(0, 200) });
693
737
  } : undefined);
694
738
  }
739
+ else if (url.pathname === "/v1/sessions/move") {
740
+ // Answers once the move is checked and recorded; the hand-off and relaunch run on, and GET says where it is.
741
+ if (!ctx.mover)
742
+ throw new BridgeError(503, "This Hook cannot move sessions.");
743
+ result = { ok: true, move: await ctx.mover.start(data) };
744
+ }
695
745
  else if (url.pathname === "/v1/sessions/rename") {
696
746
  result = await renameSession(selectedServer(url), data);
697
747
  }
@@ -779,6 +829,9 @@ export function createRouteHandler(ctx) {
779
829
  else if (url.pathname === "/v1/sets/name") {
780
830
  result = await nameSet(data);
781
831
  }
832
+ else if (url.pathname === "/v1/sets/link") {
833
+ result = await linkSetMember(data);
834
+ }
782
835
  else if (url.pathname === "/v1/push/register") {
783
836
  // Registration is kept for when a key is added; the reply says whether push works now.
784
837
  await agentHooks.push.register(data);
@@ -806,6 +859,11 @@ export function createRouteHandler(ctx) {
806
859
  await agentHooks.answerPush(z.string().uuid().parse(data.binding), data.decision);
807
860
  result = { ok: true };
808
861
  }
862
+ else if (url.pathname === "/v1/push/presence") {
863
+ // Phren desktop: the owner is at the desk, so approval alerts wait before reaching the phone.
864
+ agentHooks.push.markDesk(z.number().int().min(0).max(120_000).parse(data.activeForMs));
865
+ result = { ok: true, deskActive: agentHooks.push.deskActive };
866
+ }
809
867
  else if (url.pathname === "/v1/push/target") {
810
868
  // A tapped notification opens its session; the binding stays unspent.
811
869
  const target = agentHooks.pushTarget(z.string().uuid().parse(data.binding));
@@ -52,6 +52,14 @@ import { typedMuxRequest } from "./mux-wire.js";
52
52
  import { overviewStream } from "./server-overview.js";
53
53
  import { transcriptStreams } from "./server-stream.js";
54
54
  import { launchSession } from "./server-launch.js";
55
+ import { SessionMover, transcriptTail } from "./session-move.js";
56
+ import { harnessInventoryWithin, launchCheckOff } from "./harnesses.js";
57
+ import { paneAccount, paneAccountKey } from "./pane-accounts.js";
58
+ import { readTurn } from "./turn-records.js";
59
+ import { readLaunchBrief } from "./launch-brief.js";
60
+ import { conductorPane } from "./conductor-role.js";
61
+ import { terminalKind, terminalProvider } from "./terminal.js";
62
+ import { targetTranscriptPath } from "./transcripts.js";
55
63
  import { codexAppServerEnabled, codexServers } from "./codex-servers.js";
56
64
  import { CodexAuthKeeper, codexAuthRefreshEnabled } from "./codex-auth-refresh.js";
57
65
  import { localNames } from "./computer-names.js";
@@ -122,6 +130,7 @@ export async function serve(version, options = {}) {
122
130
  const settingsSwitcher = new SettingsSwitcher(agentHooks);
123
131
  const permissionModeSwitcher = new PermissionModeSwitcher(agentHooks);
124
132
  const sideQuestions = new SideQuestions();
133
+ const sendPrompt = async (target, text, deliveryId, typing) => await paneRouteOnce({ agentHooks, modelSwitcher, settingsSwitcher, permissionModeSwitcher, codexQuestions, sideQuestions }, new URL("http://phren.local/v1/prompt"), { target, text, deliveryId, hookQueued: true }, {}, typing);
125
134
  const handOffs = dispatches ? new HandOffQueue({
126
135
  validate: target => validateTarget(target, false, true),
127
136
  current: async (target) => {
@@ -130,8 +139,27 @@ export async function serve(version, options = {}) {
130
139
  return pane && session ? { session, terminal: pane.terminal_id } : undefined;
131
140
  },
132
141
  notify: (target, text, deliveryId, computer) => handOff({ computer, target, text, deliveryId }, { notifySender: false }),
133
- send: async (target, text, deliveryId, typing) => await paneRouteOnce({ agentHooks, modelSwitcher, settingsSwitcher, permissionModeSwitcher, codexQuestions, sideQuestions }, new URL("http://phren.local/v1/prompt"), { target, text, deliveryId, hookQueued: true }, {}, typing),
142
+ send: sendPrompt,
134
143
  }) : undefined;
144
+ // Moving a session to another agent (session-move.ts): its hand-off request
145
+ // takes the hand_off path, and the new agent starts through the launch path.
146
+ const mover = new SessionMover({
147
+ snapshot: server => snapshot(server),
148
+ identity: (server, pane) => paneIdentity(server, pane, true),
149
+ terminal: terminalProvider(),
150
+ deliver: (target, text, deliveryId) => handOffs ? handOffs.enqueue({ target, text, deliveryId }) : sendPrompt(target, text, deliveryId, async () => { }),
151
+ // The new agent starts in the folder an agent already ran in, so it is trusted for the new harness too.
152
+ launch: (server, data, options) => launches.run(() => launchSession(server, data, { trustFolder: true, ...options })),
153
+ inventory: () => launchCheckOff() ? Promise.resolve(undefined) : harnessInventoryWithin(2_500),
154
+ transcript: async (target) => transcriptTail(await targetTranscriptPath(target)),
155
+ paneAccount: (server, pane) => paneAccount(paneAccountKey(server, pane.pane_id), typeof pane.terminal_id === "string" ? pane.terminal_id : undefined)?.id,
156
+ paneDispatch: async (server, pane) => (await readTurn(server, String(pane.pane_id)))?.dispatch,
157
+ brief: readLaunchBrief,
158
+ isConductor: async (server, pane) => (await conductorPane(server, await snapshot(server)))?.pane_id === pane.pane_id,
159
+ envAtStart: server => terminalKind(server) === "tmux",
160
+ afterExit: async (server, pane) => { const entry = codexServers.forPane(server, pane); if (entry)
161
+ await codexServers.stop(entry); },
162
+ });
135
163
  const contextUsage = new WorkspaceContextUsage();
136
164
  const accountUsage = options.accountUsage ?? new AccountUsageReader();
137
165
  // A Claude launch that names no account runs under the one with the most room (account-choice.ts).
@@ -200,13 +228,15 @@ export async function serve(version, options = {}) {
200
228
  resources: () => resources.read(),
201
229
  sudo: agentHooks.sudo,
202
230
  });
203
- const http = createServer(createRouteHandler({ version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks,
231
+ // 256 KiB: gitboy's /memory/files asks about up to 500 paths in one query string.
232
+ const http = createServer({ maxHeaderSize: 256 * 1024 }, createRouteHandler({ version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks,
204
233
  journal, tabActivity, contextUsage, modelCatalog, modelSwitcher, settingsSwitcher, permissionModeSwitcher, sideQuestions, accountUsage, resources, codexQuestions, launches, locatedDirectories,
205
- fanoutMessages, canary, streams, returns, handOffs, inbox }));
234
+ fanoutMessages, canary, streams, returns, handOffs, inbox, mover }));
206
235
  http.requestTimeout = 20_000;
207
236
  http.headersTimeout = 10_000;
208
237
  http.maxHeadersCount = 32;
209
238
  const ws = new WebSocketServer({ noServer: true, maxPayload: 65_536, perMessageDeflate: false });
239
+ const socketPools = new Map();
210
240
  http.on("upgrade", (request, socket, head) => {
211
241
  try {
212
242
  const url = new URL(request.url || "/", "http://phren.local");
@@ -217,11 +247,20 @@ export async function serve(version, options = {}) {
217
247
  requireRoute(modules, "WS", url.pathname);
218
248
  // Parsed before the upgrade: an invalid server name is refused as the other routes refuse it.
219
249
  const overviewServer = url.pathname === "/v1/overview" ? selectedServer(url) : undefined;
250
+ // Each client kind has its own pool of 16, so a desktop that holds many
251
+ // sockets never evicts the phone's (and the reverse). The header is a
252
+ // fairness hint between already-authorized clients, not an identity.
253
+ const pool = request.headers["x-phren-client"] === "desktop" ? "desktop" : "default";
220
254
  ws.handleUpgrade(request, socket, head, client => {
221
- while (ws.clients.size > 16) {
222
- const oldest = ws.clients.values().next().value;
255
+ const members = socketPools.get(pool) ?? new Set();
256
+ socketPools.set(pool, members);
257
+ members.add(client);
258
+ client.once("close", () => members.delete(client));
259
+ while (members.size > 16) {
260
+ const oldest = members.values().next().value;
223
261
  oldest.close(1008, "Too many connections; reconnect");
224
262
  oldest.terminate();
263
+ members.delete(oldest);
225
264
  ws.clients.delete(oldest);
226
265
  }
227
266
  if (overviewServer !== undefined) {
@@ -0,0 +1,288 @@
1
+ import { z } from "zod";
2
+ import { moveToSchema } from "./dispatch.js";
3
+ import { type HarnessInventory } from "./harnesses.js";
4
+ import { type Json, type Provider, type StartingTarget, type Target } from "./protocol.js";
5
+ import type { TerminalProvider } from "./terminal.js";
6
+ export { moveToSchema };
7
+ export type MoveTo = z.infer<typeof moveToSchema>;
8
+ export declare const moveRequestSchema: z.ZodObject<{
9
+ target: z.ZodObject<{
10
+ server: z.ZodString;
11
+ workspace: z.ZodString;
12
+ tab: z.ZodString;
13
+ pane: z.ZodString;
14
+ source: z.ZodEnum<{
15
+ claude: "claude";
16
+ codex: "codex";
17
+ copilot: "copilot";
18
+ opencode: "opencode";
19
+ phren: "phren";
20
+ }>;
21
+ session: z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
22
+ }, z.core.$strip>;
23
+ to: z.ZodObject<{
24
+ harness: z.ZodEnum<{
25
+ claude: "claude";
26
+ codex: "codex";
27
+ copilot: "copilot";
28
+ opencode: "opencode";
29
+ }>;
30
+ account: z.ZodOptional<z.ZodString>;
31
+ model: z.ZodOptional<z.ZodString>;
32
+ effort: z.ZodOptional<z.ZodEnum<{
33
+ high: "high";
34
+ low: "low";
35
+ max: "max";
36
+ medium: "medium";
37
+ minimal: "minimal";
38
+ xhigh: "xhigh";
39
+ }>>;
40
+ }, z.core.$strict>;
41
+ id: z.ZodOptional<z.ZodString>;
42
+ handoffTimeoutMs: z.ZodOptional<z.ZodNumber>;
43
+ }, z.core.$strict>;
44
+ declare const moveRecordSchema: z.ZodObject<{
45
+ id: z.ZodString;
46
+ state: z.ZodEnum<{
47
+ exiting: "exiting";
48
+ failed: "failed";
49
+ "handing-off": "handing-off";
50
+ launching: "launching";
51
+ moved: "moved";
52
+ }>;
53
+ createdAt: z.ZodString;
54
+ updatedAt: z.ZodString;
55
+ from: z.ZodObject<{
56
+ target: z.ZodObject<{
57
+ server: z.ZodString;
58
+ workspace: z.ZodString;
59
+ tab: z.ZodString;
60
+ pane: z.ZodString;
61
+ source: z.ZodEnum<{
62
+ claude: "claude";
63
+ codex: "codex";
64
+ copilot: "copilot";
65
+ opencode: "opencode";
66
+ phren: "phren";
67
+ }>;
68
+ session: z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
69
+ }, z.core.$strip>;
70
+ account: z.ZodOptional<z.ZodString>;
71
+ label: z.ZodOptional<z.ZodString>;
72
+ }, z.core.$strict>;
73
+ to: z.ZodObject<{
74
+ harness: z.ZodEnum<{
75
+ claude: "claude";
76
+ codex: "codex";
77
+ copilot: "copilot";
78
+ opencode: "opencode";
79
+ }>;
80
+ account: z.ZodOptional<z.ZodString>;
81
+ model: z.ZodOptional<z.ZodString>;
82
+ effort: z.ZodOptional<z.ZodEnum<{
83
+ high: "high";
84
+ low: "low";
85
+ max: "max";
86
+ medium: "medium";
87
+ minimal: "minimal";
88
+ xhigh: "xhigh";
89
+ }>>;
90
+ }, z.core.$strict>;
91
+ cwd: z.ZodString;
92
+ dispatch: z.ZodOptional<z.ZodString>;
93
+ handoff: z.ZodOptional<z.ZodObject<{
94
+ path: z.ZodString;
95
+ source: z.ZodEnum<{
96
+ agent: "agent";
97
+ fallback: "fallback";
98
+ }>;
99
+ reason: z.ZodOptional<z.ZodString>;
100
+ chars: z.ZodNumber;
101
+ }, z.core.$strict>>;
102
+ exit: z.ZodOptional<z.ZodEnum<{
103
+ clean: "clean";
104
+ interrupted: "interrupted";
105
+ killed: "killed";
106
+ }>>;
107
+ placement: z.ZodOptional<z.ZodEnum<{
108
+ "adjacent-pane": "adjacent-pane";
109
+ "same-pane": "same-pane";
110
+ }>>;
111
+ target: z.ZodOptional<z.ZodUnion<readonly [z.ZodObject<{
112
+ server: z.ZodString;
113
+ workspace: z.ZodString;
114
+ tab: z.ZodString;
115
+ pane: z.ZodString;
116
+ source: z.ZodEnum<{
117
+ claude: "claude";
118
+ codex: "codex";
119
+ copilot: "copilot";
120
+ opencode: "opencode";
121
+ phren: "phren";
122
+ }>;
123
+ session: z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
124
+ }, z.core.$strip>, z.ZodObject<{
125
+ server: z.ZodString;
126
+ workspace: z.ZodString;
127
+ tab: z.ZodString;
128
+ pane: z.ZodString;
129
+ source: z.ZodEnum<{
130
+ claude: "claude";
131
+ codex: "codex";
132
+ copilot: "copilot";
133
+ opencode: "opencode";
134
+ phren: "phren";
135
+ }>;
136
+ starting: z.ZodLiteral<true>;
137
+ startingToken: z.ZodString;
138
+ }, z.core.$strip>]>>;
139
+ movedAt: z.ZodOptional<z.ZodString>;
140
+ error: z.ZodOptional<z.ZodString>;
141
+ }, z.core.$strict>;
142
+ export type MoveRecord = z.infer<typeof moveRecordSchema>;
143
+ /** What a dispatching Hook records on its receipt when its worker moved. */
144
+ export interface MovedWorker {
145
+ id: string;
146
+ at: string;
147
+ handoff?: string;
148
+ from: {
149
+ harness: Provider;
150
+ account?: string;
151
+ };
152
+ to: MoveTo;
153
+ target: Target | StartingTarget;
154
+ }
155
+ export declare function movesRoot(): string;
156
+ /** The hand-off sits beside the new agent's brief, in a folder Claude is given read access to. */
157
+ export declare const handoffPath: (id: string) => string;
158
+ export declare function readMove(id: string): Promise<MoveRecord | undefined>;
159
+ /** Recent moves, newest first; old ones are removed on the way. */
160
+ export declare function listMoves(now?: number): Promise<MoveRecord[]>;
161
+ /** The move that took the agent out of `target`'s pane: a target with a
162
+ * conversation matches only that conversation; a starting one, the pane. */
163
+ export declare function moveFrom(records: readonly MoveRecord[], target: {
164
+ server: string;
165
+ pane: string;
166
+ source: string;
167
+ session?: string;
168
+ }): MoveRecord | undefined;
169
+ /** The receipt fields for a finished move. */
170
+ export declare function movedWorker(record: MoveRecord): MovedWorker | undefined;
171
+ /** A harness as people name it, with its account and model: "Claude (work, opus)". */
172
+ export declare function harnessName(to: {
173
+ harness: string;
174
+ account?: string;
175
+ model?: string;
176
+ effort?: string;
177
+ }): string;
178
+ /** What the moving agent is asked to write. */
179
+ export declare function handoffRequest(id: string, to: MoveTo): string;
180
+ /** The hand-off between the markers in the agent's replies after the request,
181
+ * or undefined while its end marker has not arrived. Code fences around the
182
+ * block are dropped. */
183
+ export declare function extractHandoff(replies: readonly string[], id: string): string | undefined;
184
+ /** One message from a conversation's tail. */
185
+ export interface TailEntry {
186
+ role: "owner" | "agent";
187
+ text: string;
188
+ }
189
+ /** The owner's prompts and the agent's replies in a transcript's lines, oldest first. */
190
+ export declare function conversationEntries(lines: readonly string[], source: Provider): TailEntry[];
191
+ /** The agent's replies after the move's request: the request names the move, so an older hand-off never counts. */
192
+ export declare function repliesAfterRequest(entries: readonly TailEntry[], id: string): string[];
193
+ /** What `git` shows in the checkout at the move. */
194
+ export interface GitState {
195
+ root: string;
196
+ branch?: string;
197
+ head?: string;
198
+ upstream?: string;
199
+ ahead?: number;
200
+ behind?: number;
201
+ /** `git status --porcelain` lines: every change, tracked or not. */
202
+ changes: string[];
203
+ }
204
+ export declare function readGitState(directory: string): Promise<GitState | undefined>;
205
+ /** The commands of every process below `pids` (the agent's own children), not the agent itself. */
206
+ export declare function processesBelow(pids: readonly number[]): Promise<string[]>;
207
+ /** What Phren itself saw at the move, appended to every hand-off. */
208
+ export declare function observedState(git: GitState | undefined, processes: readonly string[]): string;
209
+ /** A hand-off built without the agent: the conversation's tail, the original brief and the git state. */
210
+ export declare function fallbackHandoff(input: {
211
+ reason: string;
212
+ from: string;
213
+ entries: readonly TailEntry[];
214
+ original?: string;
215
+ dispatch?: string;
216
+ label?: string;
217
+ }): string;
218
+ /** The hand-off file: who moved where and when, the body, then what Phren saw. */
219
+ export declare function handoffDocument(record: MoveRecord, body: string, observed: string, at: string): string;
220
+ /** The new agent's first prompt: the whole hand-off when it fits the brief, else where to read it. */
221
+ export declare function continuePrompt(document: string, file: string): string;
222
+ export interface MoverDeps {
223
+ snapshot: (server: string) => Promise<Json>;
224
+ /** The conversation the pane runs now. */
225
+ identity: (server: string, pane: Json) => Promise<string | undefined>;
226
+ terminal: Pick<TerminalProvider, "prompt" | "sendKeys" | "processes" | "closePane">;
227
+ /** The `hand_off` delivery path: queued while the agent is busy. */
228
+ deliver: (target: Target, text: string, deliveryId: string) => Promise<Json>;
229
+ /** Starts the new agent (`startSession`), in `into` when given. */
230
+ launch: (server: string, data: Json, options: {
231
+ into?: {
232
+ workspaceId: string;
233
+ tabId: string;
234
+ paneId: string;
235
+ };
236
+ dispatchId?: string;
237
+ }) => Promise<Json>;
238
+ inventory: () => Promise<HarnessInventory | undefined>;
239
+ /** The conversation's transcript lines, its tail is enough. */
240
+ transcript: (target: Target) => Promise<string[]>;
241
+ git?: (directory: string) => Promise<GitState | undefined>;
242
+ processesBelow?: (pids: readonly number[]) => Promise<string[]>;
243
+ /** The Claude account the pane runs under, when known. */
244
+ paneAccount?: (server: string, pane: Json) => string | undefined;
245
+ /** The dispatch the pane's agent was launched for. */
246
+ paneDispatch?: (server: string, pane: Json) => Promise<string | undefined>;
247
+ /** The text of a brief this computer wrote. */
248
+ brief?: (id: string) => Promise<string | undefined>;
249
+ /** Whether the pane holds this computer's conductor. */
250
+ isConductor?: (server: string, pane: Json) => Promise<boolean>;
251
+ /** Herdr gives a pane its variables only when it is created; tmux sets them on every start. */
252
+ envAtStart?: (server: string) => boolean;
253
+ /** Cleanup after the old agent exited (a Codex pane's app-server). */
254
+ afterExit?: (server: string, pane: string) => Promise<void>;
255
+ kill?: (pid: number, signal: NodeJS.Signals) => void;
256
+ now?: () => number;
257
+ sleep?: (ms: number) => Promise<void>;
258
+ pollMs?: number;
259
+ /** How long a clean exit, then an interrupt, may take before the agent counts as hung. */
260
+ exitMs?: number;
261
+ }
262
+ /** Runs moves on the computer that runs the session. A move outlives the
263
+ * request that started it (the Hook answers in seconds); its record says where it is. */
264
+ export declare class SessionMover {
265
+ private readonly deps;
266
+ private readonly running;
267
+ constructor(deps: MoverDeps);
268
+ private get now();
269
+ private sleep;
270
+ private get poll();
271
+ /** Checks the move can happen, records it and starts it. Refuses before anything is typed. */
272
+ start(input: unknown): Promise<MoveRecord>;
273
+ /** For tests: the move under way in a pane, until it settles. */
274
+ settled(server: string, pane: string): Promise<void> | undefined;
275
+ private update;
276
+ private run;
277
+ /** The agent's own hand-off, or why there is none. Fails only when the session itself went away. */
278
+ private askForHandoff;
279
+ private fallback;
280
+ /** Ends the old agent with its own exit command; an interrupt, then a kill, only when it hangs. */
281
+ private exit;
282
+ /** Starts the target in the old pane when its shell has what the target needs, else in a new tab beside it. */
283
+ private relaunch;
284
+ /** The new agent's full target, waiting a little for its conversation id when the launch did not have it yet. */
285
+ private newTarget;
286
+ }
287
+ /** The last `bytes` of a transcript as lines, the first (cut) one dropped. */
288
+ export declare function transcriptTail(file: string, bytes?: number): Promise<string[]>;