@phren/cli 0.3.71 → 0.3.73

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 (164) hide show
  1. package/dist/bridge/agent-hooks.js +11 -1
  2. package/dist/bridge/browser-env.d.ts +5 -0
  3. package/dist/bridge/browser-env.js +110 -0
  4. package/dist/bridge/browser-protocol.d.ts +120 -0
  5. package/dist/bridge/browser-protocol.js +70 -0
  6. package/dist/bridge/browser-recordings.d.ts +63 -0
  7. package/dist/bridge/browser-recordings.js +148 -0
  8. package/dist/bridge/browser-registry.d.ts +64 -0
  9. package/dist/bridge/browser-registry.js +262 -0
  10. package/dist/bridge/browser-routes.d.ts +4 -0
  11. package/dist/bridge/browser-routes.js +39 -0
  12. package/dist/bridge/browser-shim/phren-playwright.cjs +184 -0
  13. package/dist/bridge/browser-socket.d.ts +2 -0
  14. package/dist/bridge/browser-socket.js +10 -0
  15. package/dist/bridge/browser-stream.d.ts +3 -0
  16. package/dist/bridge/browser-stream.js +129 -0
  17. package/dist/bridge/browser-watch.d.ts +12 -0
  18. package/dist/bridge/browser-watch.js +83 -0
  19. package/dist/bridge/claude-account-setup.js +3 -1
  20. package/dist/bridge/claude-accounts.d.ts +5 -1
  21. package/dist/bridge/claude-accounts.js +36 -6
  22. package/dist/bridge/codex-servers.d.ts +2 -0
  23. package/dist/bridge/codex-servers.js +1 -1
  24. package/dist/bridge/command.js +24 -5
  25. package/dist/bridge/dispatch-clone.d.ts +33 -0
  26. package/dist/bridge/dispatch-clone.js +176 -0
  27. package/dist/bridge/dispatch-command.d.ts +14 -0
  28. package/dist/bridge/dispatch-command.js +98 -13
  29. package/dist/bridge/dispatch-idempotency.d.ts +85 -0
  30. package/dist/bridge/dispatch-idempotency.js +235 -0
  31. package/dist/bridge/dispatch-returns.d.ts +6 -0
  32. package/dist/bridge/dispatch-returns.js +131 -1
  33. package/dist/bridge/dispatch-wait.d.ts +32 -0
  34. package/dist/bridge/dispatch-wait.js +177 -0
  35. package/dist/bridge/dispatch.d.ts +78 -2
  36. package/dist/bridge/dispatch.js +841 -25
  37. package/dist/bridge/dream-schedule.d.ts +133 -0
  38. package/dist/bridge/dream-schedule.js +322 -0
  39. package/dist/bridge/fanouts.js +20 -3
  40. package/dist/bridge/files.d.ts +1 -1
  41. package/dist/bridge/git-credential.d.ts +44 -0
  42. package/dist/bridge/git-credential.js +113 -0
  43. package/dist/bridge/git-host-auth.d.ts +9 -1
  44. package/dist/bridge/git-host-auth.js +18 -5
  45. package/dist/bridge/git-host-gitboy.js +8 -1
  46. package/dist/bridge/git-hosts.d.ts +12 -1
  47. package/dist/bridge/git-publish.js +3 -2
  48. package/dist/bridge/herdr.d.ts +4 -0
  49. package/dist/bridge/herdr.js +44 -9
  50. package/dist/bridge/install.d.ts +1 -1
  51. package/dist/bridge/install.js +12 -4
  52. package/dist/bridge/launch-brief.d.ts +11 -0
  53. package/dist/bridge/launch-brief.js +22 -0
  54. package/dist/bridge/launch-worktree.d.ts +2 -0
  55. package/dist/bridge/launch-worktree.js +5 -1
  56. package/dist/bridge/pane-status.js +1 -1
  57. package/dist/bridge/protocol.d.ts +7 -0
  58. package/dist/bridge/schedule-watch.js +13 -2
  59. package/dist/bridge/server-launch.d.ts +2 -0
  60. package/dist/bridge/server-launch.js +251 -145
  61. package/dist/bridge/server-routes.d.ts +3 -0
  62. package/dist/bridge/server-routes.js +33 -17
  63. package/dist/bridge/server-stream.d.ts +4 -0
  64. package/dist/bridge/server-stream.js +24 -5
  65. package/dist/bridge/server.js +35 -4
  66. package/dist/bridge/session-move.d.ts +10 -4
  67. package/dist/bridge/session-move.js +65 -34
  68. package/dist/bridge/simulator-stream.d.ts +2 -0
  69. package/dist/bridge/simulator-stream.js +2 -0
  70. package/dist/bridge/status-line-fast.d.ts +9 -0
  71. package/dist/bridge/status-line-fast.js +56 -0
  72. package/dist/bridge/tab-activity.d.ts +2 -0
  73. package/dist/bridge/tab-activity.js +15 -2
  74. package/dist/bridge/task-routes.d.ts +20 -16
  75. package/dist/bridge/task-routes.js +1 -1
  76. package/dist/bridge/terminal-herdr.d.ts +5 -1
  77. package/dist/bridge/terminal-herdr.js +67 -2
  78. package/dist/bridge/terminal-tmux.d.ts +2 -0
  79. package/dist/bridge/terminal-tmux.js +29 -7
  80. package/dist/bridge/terminal.d.ts +5 -1
  81. package/dist/bridge/transcript-claude.js +192 -112
  82. package/dist/bridge/transcript-preview.d.ts +2 -1
  83. package/dist/bridge/transcript-preview.js +85 -3
  84. package/dist/bridge/transcripts.js +17 -11
  85. package/dist/bridge/turn-records.js +16 -4
  86. package/dist/bridge/usage.d.ts +7 -1
  87. package/dist/bridge/usage.js +47 -31
  88. package/dist/bridge/worker-close.d.ts +15 -0
  89. package/dist/bridge/worker-close.js +304 -3
  90. package/dist/bridge/worker-identity.d.ts +51 -0
  91. package/dist/bridge/worker-identity.js +289 -0
  92. package/dist/bridge/worker-reports.js +15 -3
  93. package/dist/bridge-hook.mjs +39990 -36152
  94. package/dist/capabilities/mcp.js +1 -1
  95. package/dist/cli/browser-hint.d.ts +2 -0
  96. package/dist/cli/browser-hint.js +21 -0
  97. package/dist/cli/config-dreaming.d.ts +7 -0
  98. package/dist/cli/config-dreaming.js +72 -0
  99. package/dist/cli/config.js +6 -0
  100. package/dist/cli/dream.d.ts +59 -0
  101. package/dist/cli/dream.js +315 -0
  102. package/dist/cli/hooks-context.d.ts +2 -2
  103. package/dist/cli/hooks-context.js +3 -3
  104. package/dist/cli/hooks.js +20 -11
  105. package/dist/cli/namespaces-tasks.js +14 -0
  106. package/dist/cli-registry.js +28 -3
  107. package/dist/config/dreaming.d.ts +82 -0
  108. package/dist/config/dreaming.js +195 -0
  109. package/dist/config/resolve.js +11 -0
  110. package/dist/config/schema.d.ts +4 -4
  111. package/dist/config/schema.js +157 -1
  112. package/dist/content/citation-freshness.js +6 -0
  113. package/dist/content/learning.d.ts +1 -0
  114. package/dist/content/learning.js +2 -0
  115. package/dist/data/access.d.ts +1 -1
  116. package/dist/data/access.js +3 -1
  117. package/dist/data/task-contract.d.ts +5 -4
  118. package/dist/data/tasks.d.ts +5 -0
  119. package/dist/data/tasks.js +28 -2
  120. package/dist/dream/apply.d.ts +69 -0
  121. package/dist/dream/apply.js +372 -0
  122. package/dist/dream/budget.d.ts +78 -0
  123. package/dist/dream/budget.js +180 -0
  124. package/dist/dream/collect.d.ts +86 -0
  125. package/dist/dream/collect.js +449 -0
  126. package/dist/dream/eval/dream-adapter.d.ts +16 -0
  127. package/dist/dream/eval/dream-adapter.js +21 -0
  128. package/dist/dream/eval/fixture.d.ts +53 -0
  129. package/dist/dream/eval/fixture.js +172 -0
  130. package/dist/dream/eval/index.d.ts +40 -0
  131. package/dist/dream/eval/index.js +78 -0
  132. package/dist/dream/eval/score.d.ts +34 -0
  133. package/dist/dream/eval/score.js +99 -0
  134. package/dist/dream/eval/scripted-model.d.ts +19 -0
  135. package/dist/dream/eval/scripted-model.js +70 -0
  136. package/dist/dream/pages.d.ts +68 -0
  137. package/dist/dream/pages.js +220 -0
  138. package/dist/dream/privacy.d.ts +3 -0
  139. package/dist/dream/privacy.js +18 -0
  140. package/dist/dream/prompt.d.ts +13 -0
  141. package/dist/dream/prompt.js +84 -0
  142. package/dist/dream/run.d.ts +98 -0
  143. package/dist/dream/run.js +317 -0
  144. package/dist/dream/types.d.ts +74 -0
  145. package/dist/dream/types.js +4 -0
  146. package/dist/finding/lifecycle.d.ts +2 -2
  147. package/dist/finding/lifecycle.js +5 -2
  148. package/dist/finding/versions.d.ts +4 -0
  149. package/dist/finding/versions.js +28 -0
  150. package/dist/index.js +1 -0
  151. package/dist/modules/registry.js +10 -8
  152. package/dist/project-config.d.ts +3 -0
  153. package/dist/task/merge-links.d.ts +38 -0
  154. package/dist/task/merge-links.js +45 -0
  155. package/dist/task/reconcile.d.ts +39 -0
  156. package/dist/task/reconcile.js +201 -0
  157. package/dist/task/report-links.d.ts +10 -0
  158. package/dist/task/report-links.js +47 -0
  159. package/dist/tools/config.js +46 -4
  160. package/dist/tools/dispatch.js +2 -1
  161. package/dist/tools/dream.d.ts +3 -0
  162. package/dist/tools/dream.js +123 -0
  163. package/dist/tools/tasks.js +4 -1
  164. package/package.json +1 -1
@@ -1,3 +1,4 @@
1
+ import { browserRoute } from "./browser-routes.js";
1
2
  import { terminalProvider } from "./terminal.js";
2
3
  import { peerFingerprint } from "./dispatch-hosts.js";
3
4
  import { redactPeerHandoff } from "./peer-handoff.js";
@@ -11,7 +12,7 @@ import { ownerRequest, requestPeer } from "./request-origin.js";
11
12
  import { listMoves, moveSessionFields, readMove } from "./session-move.js";
12
13
  import { getTaskRoute, getTaskDirectoryRoute, updateTaskRoute, createTaskRoute, saveTaskRoute, launchTaskRoute } from "./task-routes.js";
13
14
  import { ownerInboxView } from "./owner-inbox-view.js";
14
- import { closeFinishedWorker, closeOwnPane } from "./worker-close.js";
15
+ import { cancelDispatch, closeFinishedWorker, closeOwnPane } from "./worker-close.js";
15
16
  import { reportWorker, readIntegrator, setIntegrator } from "./worker-reports.js";
16
17
  import { sessionStalls } from "./stalls.js";
17
18
  import { harnessInventoryWithin, launchCheckOff } from "./harnesses.js";
@@ -24,7 +25,7 @@ import { handOff } from "./hand-off.js";
24
25
  import { BUILTIN_MODULES, disabledHint } from "../modules/registry.js";
25
26
  import { homeDir } from "../home-paths.js";
26
27
  import { resolveCodeStore, CodeRoutes } from "./code-routes.js";
27
- import { dispatchProjectDirectory, dispatchStatus, originPaneSchema } from "./dispatch.js";
28
+ import { dispatchProjectDirectory, dispatchStatus, originPaneSchema, reconcileInterruptedDispatches } from "./dispatch.js";
28
29
  import { hookWorkers } from "./dispatch-returns.js";
29
30
  import { remoteChildren } from "./dispatch-tree.js";
30
31
  import { briefArrival, briefId, briefRoot, launchesWithBrief, readLaunchBrief } from "./launch-brief.js";
@@ -50,7 +51,7 @@ import { gitStatus } from "./git.js";
50
51
  import { gitRoot, launchDirectory, repositoryBranch, webServers, withGitReadDeadline } from "./projects.js";
51
52
  import { approvalDecisions, atomicInPrivateDir, BridgeError, bridgeRoot, MAX_FRAME, object, objects, PROTOCOL, provider, serverName, targetFromURL, targetSchema, sessionId } from "./protocol.js";
52
53
  import { bootedSimulators, simulatorAct, simulatorApps, simulatorDevices, simulatorScreenshot } from "./simulators.js";
53
- import { tabActivityKey } from "./tab-activity.js";
54
+ import { panesByTab, tabActivityKey } from "./tab-activity.js";
54
55
  import { childAgentTree, completionEntry, historicalImage, publicChildAgents, refreshTranscript, targetTranscriptPath, transcriptPath, TranscriptReader } from "./transcripts.js";
55
56
  import { conversationSearch } from "./conversation-search.js";
56
57
  import { listUploads, removeUpload, saveUpload, uploadImage } from "./uploads.js";
@@ -79,8 +80,8 @@ export const OVERVIEW_ENRICH_BUDGET_MS = 5_000;
79
80
  /** How long activity sampling may spend resolving background work before it
80
81
  * leaves an unresolved row at its last known status. */
81
82
  export const STATUS_ENRICH_BUDGET_MS = 2_000;
82
- async function effectiveStatus(server, s, row, hooks) {
83
- const panes = objects(s.panes).filter(p => p.tab_id === row.tab && p.workspace_id === row.workspace && p.agent);
83
+ async function effectiveStatus(server, tabPanes, row, hooks) {
84
+ const panes = tabPanes.filter(p => p.agent);
84
85
  if (panes.length !== 1 || !provider.safeParse(panes[0].agent).success)
85
86
  return row;
86
87
  const pane = panes[0];
@@ -99,12 +100,13 @@ async function effectiveStatus(server, s, row, hooks) {
99
100
  * finish inside `budgetMs` is left out, which preserves its last known status. */
100
101
  export async function effectiveStatusRows(server, s, budgetMs = STATUS_ENRICH_BUDGET_MS, hooks) {
101
102
  const deadline = Date.now() + budgetMs;
103
+ const grouped = panesByTab(s);
102
104
  const rows = await Promise.all(objects(s.tabs).map(async (tab) => {
103
105
  const row = { workspace: tab.workspace_id, tab: tab.tab_id, status: tab.agent_status };
104
106
  let timer;
105
107
  const late = new Promise(resolve => { timer = setTimeout(() => resolve(undefined), Math.max(0, deadline - Date.now())); timer.unref(); });
106
108
  try {
107
- return await Promise.race([effectiveStatus(server, s, row, hooks).catch(() => row), late]);
109
+ return await Promise.race([effectiveStatus(server, grouped.get(tabActivityKey(row.workspace, row.tab)) ?? [], row, hooks).catch(() => row), late]);
108
110
  }
109
111
  finally {
110
112
  clearTimeout(timer);
@@ -112,7 +114,7 @@ export async function effectiveStatusRows(server, s, budgetMs = STATUS_ENRICH_BU
112
114
  }));
113
115
  return rows.filter((row) => row !== undefined);
114
116
  }
115
- export const capabilities = { turnCheckpoints: true, transcript: true, progress: true, images: true, prompt: true, stop: true,
117
+ export const capabilities = { browsers: true, turnCheckpoints: true, transcript: true, progress: true, images: true, prompt: true, stop: true,
116
118
  terminal: "ssh-pty", shell: "ssh-pty", paneTerminal: "ssh-pty", paneLayout: true, deskPresence: true, herdr: true, sessionRename: true, sessionSeen: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
117
119
  approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
118
120
  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", simulatorStream: process.platform === "darwin", simulatorDevices: process.platform === "darwin", simulatorDrag: 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, afterTurnQueue: true, queuedMessageActions: ["claude"], deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, moveNewChat: true, moveConductor: true, moveToComputer: true, moveConductorToComputer: true, moveResume: true, moveSummaryByTarget: true, moveConversationCopy: true, claudeAccountAdd: true, accountPools: true, workerRelocation: 1, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true, projectHostToken: true, gitRemoteIdentity: true, gitWatch: true, worktreeRemove: true, terminalResolve: true, conversationSearch: true };
@@ -202,15 +204,9 @@ export function workspacesReader(ctx) {
202
204
  const conductor = await conductorPane(server, s).catch(() => undefined);
203
205
  const workspaces = workspaceSnapshot(s, context, agentHooks.pendingPanes(server, s), lastChanged, conductor ? String(conductor.pane_id) : null);
204
206
  // The branch each tab's agent is on, for the session cards.
205
- const agentsByTab = new Map();
206
- for (const pane of objects(s.panes)) {
207
- if (!pane.agent)
208
- continue;
209
- const key = JSON.stringify([pane.workspace_id, pane.tab_id]);
210
- const agents = agentsByTab.get(key) ?? [];
211
- agents.push(pane);
212
- agentsByTab.set(key, agents);
213
- }
207
+ const agentsByTab = panesByTab(s);
208
+ for (const [key, panes] of agentsByTab)
209
+ agentsByTab.set(key, panes.filter(pane => pane.agent));
214
210
  // Move records are decoration: read alongside the rest, inside the budget.
215
211
  const movesRead = listMoves().catch(() => []);
216
212
  const tabs = objects(workspaces.groups).flatMap(group => objects(group.children).map(tab => ({ group, tab })));
@@ -222,6 +218,7 @@ export function workspacesReader(ctx) {
222
218
  if (agents.length !== 1)
223
219
  continue;
224
220
  const chat = chatStates.get(agents[0]);
221
+ tab.browserWatch = chat?.browserWatch ?? "unknown";
225
222
  if (chat?.starting === true)
226
223
  tab.starting = true;
227
224
  // After the identity probe above, which is what learns a pane's transcript.
@@ -446,6 +443,10 @@ export function createRouteHandler(ctx) {
446
443
  if (url.origin !== "http://phren.local")
447
444
  throw new BridgeError(400, "Invalid request origin.");
448
445
  requireRoute(modules, request.method ?? "", url.pathname);
446
+ if (url.pathname === "/v1/browsers" || url.pathname.startsWith("/v1/browsers/")) {
447
+ browserRoute(ctx.browsers, request.method ?? "", url, response);
448
+ return;
449
+ }
449
450
  let result;
450
451
  if (url.pathname.startsWith("/v1/conductor/move/")) {
451
452
  if (!ctx.succession)
@@ -532,6 +533,7 @@ export function createRouteHandler(ctx) {
532
533
  result = { integrator: await readIntegrator() ?? null };
533
534
  break;
534
535
  case "/v1/dispatch":
536
+ await reconcileInterruptedDispatches();
535
537
  result = { dispatches: await dispatchStatus() };
536
538
  break;
537
539
  // A session move (session-move.ts) by its id, or this computer's recent moves.
@@ -938,7 +940,7 @@ export function createRouteHandler(ctx) {
938
940
  const target = targetFromURL(url);
939
941
  await validateTarget(target);
940
942
  const { reader, source, session } = await childConversationReader(target, z.string().parse(url.searchParams.get("child")));
941
- const page = await reader.read();
943
+ const page = reader ? await reader.read() : emptyPage;
942
944
  result = { ...page, type: "backlog", source, session };
943
945
  break;
944
946
  }
@@ -1235,6 +1237,12 @@ export function createRouteHandler(ctx) {
1235
1237
  else if (url.pathname === "/v1/dispatch/close") {
1236
1238
  result = await closeFinishedWorker(data, ctx.handOffs);
1237
1239
  }
1240
+ else if (url.pathname === "/v1/dispatch/cancel") {
1241
+ // Cancel a running dispatch by id: stop its agent and close its pane.
1242
+ if (request.headers?.["x-phren-origin"] === "peer")
1243
+ throw new BridgeError(403, "A peer cannot cancel a dispatch on this computer.");
1244
+ result = await cancelDispatch(data);
1245
+ }
1238
1246
  else if (url.pathname === "/v1/dispatch/close-self") {
1239
1247
  result = await closeOwnPane(data);
1240
1248
  }
@@ -1255,6 +1263,14 @@ export function createRouteHandler(ctx) {
1255
1263
  else if (url.pathname === "/v1/dispatch/workers") {
1256
1264
  result = await hookWorkers(agentHooks)(data);
1257
1265
  }
1266
+ else if (url.pathname === "/v1/dispatch/returns/ack") {
1267
+ // `phren dispatch wait` acknowledges only the dispatch it followed,
1268
+ // never the other returns a conductor on this Hook still needs.
1269
+ if (request.headers?.["x-phren-origin"] === "peer")
1270
+ throw new BridgeError(403, "Peer conductor operations require the authenticated generation-scoped routes.");
1271
+ const body = z.object({ dispatch: z.string().uuid() }).strict().parse(data);
1272
+ result = await ctx.returns.acknowledgeOne(body.dispatch);
1273
+ }
1258
1274
  else if (url.pathname === "/v1/dispatch/returns" && url.searchParams.get("peek") === "1") {
1259
1275
  // The unread returns, left unread: a watcher (`phren dispatch returns --watch`) beside an agent
1260
1276
  // conductor, which still takes them. Read here, never forwarded to a successor, which would take them.
@@ -33,6 +33,10 @@ export declare function transcriptStreams(ctx: StreamContext): {
33
33
  session: string;
34
34
  }>;
35
35
  childConversationReader: (target: Target, child: string) => Promise<{
36
+ source: "claude" | "codex" | "copilot" | "opencode" | "phren";
37
+ session: string;
38
+ reader?: undefined;
39
+ } | {
36
40
  reader: TranscriptReader;
37
41
  source: "claude" | "codex" | "copilot" | "opencode" | "phren";
38
42
  session: string;
@@ -1,3 +1,4 @@
1
+ import { stat } from "node:fs/promises";
1
2
  import { WebSocket } from "ws";
2
3
  import { z } from "zod";
3
4
  import { logger } from "../logger.js";
@@ -70,6 +71,16 @@ export function transcriptStreams(ctx) {
70
71
  const relation = childAgent(await childAgentTree(target.source, target.session), child);
71
72
  if (!relation)
72
73
  throw new BridgeError(404, "This child agent does not belong to the selected conversation.");
74
+ // A verified child can be listed before its first transcript write.
75
+ // Keep its public identity while waiting, rather than reading the parent.
76
+ try {
77
+ await stat(relation.transcript);
78
+ }
79
+ catch (error) {
80
+ if (error.code === "ENOENT")
81
+ return { source: relation.provider, session: relation.id };
82
+ throw error;
83
+ }
73
84
  const reader = new TranscriptReader(relation.transcript, relation.provider, undefined, undefined, relation.provider === "claude", relation.cwd);
74
85
  return { reader, source: relation.provider, session: relation.id };
75
86
  }
@@ -80,7 +91,7 @@ export function transcriptStreams(ctx) {
80
91
  let busy = false, ready = false, first = true;
81
92
  let awaitingTranscript = false, lastTranscriptLookup = 0;
82
93
  let initialPane;
83
- let busyAt = 0;
94
+ let busyAt = 0, statusSentAt = 0, statusKey = "";
84
95
  const pending = [];
85
96
  const stop = () => { abort.abort(); clearInterval(timer); unwatch?.(); pending.length = 0; };
86
97
  client.once("close", stop);
@@ -116,7 +127,7 @@ export function transcriptStreams(ctx) {
116
127
  if (Date.now() - lastTranscriptLookup < 2_000)
117
128
  return;
118
129
  lastTranscriptLookup = Date.now();
119
- const opened = await conversationReader(target);
130
+ const opened = child === null ? await conversationReader(target) : await childConversationReader(target, child);
120
131
  if (opened.reader) {
121
132
  reader = opened.reader;
122
133
  conversation = { source: opened.source, session: opened.session };
@@ -231,7 +242,7 @@ export function transcriptStreams(ctx) {
231
242
  busyAt = Date.now();
232
243
  const nextPrompt = between && suggestion && suggestion.readAt > busyAt ? suggestion.text : undefined;
233
244
  const historyHealth = target.source === "codex" ? await threadHealth(target.session, pane.agent_status) : { stalled: false };
234
- send(client, { agentStatus: { source: target.source, session: target.session,
245
+ const frame = { agentStatus: { source: target.source, session: target.session,
235
246
  status: pendingApproval || servedQuestion ? "waiting" : resolvedStatus, pendingApproval, pendingQuestions, terminalPrompt,
236
247
  ...(waiting && agentHooks.passwordPrompt(target) ? { passwordPrompt: true } : {}),
237
248
  compacting: agentHooks.compacting(target),
@@ -248,7 +259,15 @@ export function transcriptStreams(ctx) {
248
259
  // through /v1/questions/answer, whether or not a hold caught it.
249
260
  ...(target.source === "claude" || servedQuestion ? { questions: true } : {}),
250
261
  // What the composer's permission, plan and fast chips can change here.
251
- ...(settings ? { settings } : {}) }, ...(settingsState ? { settingsState } : {}), branch } });
262
+ ...(settings ? { settings } : {}) }, ...(settingsState ? { settingsState } : {}), branch } };
263
+ // Keep polling for dialogs at 500 ms, but send idle sockets only
264
+ // a periodic full status refresh (also usable by older phones).
265
+ const key = JSON.stringify(frame), at = Date.now();
266
+ if (key !== statusKey || at - statusSentAt >= 20_000) {
267
+ send(client, frame);
268
+ statusKey = key;
269
+ statusSentAt = at;
270
+ }
252
271
  }
253
272
  if (sideAnswers && sideQuestions) {
254
273
  for (const { revision, ...side } of sideQuestions.list(target)) {
@@ -325,7 +344,7 @@ export function transcriptStreams(ctx) {
325
344
  const opened = child === null ? await conversationReader(target) : await childConversationReader(target, child);
326
345
  reader = opened.reader;
327
346
  conversation = { source: opened.source, session: opened.session };
328
- awaitingTranscript = child === null && !reader;
347
+ awaitingTranscript = !reader;
329
348
  lastTranscriptLookup = Date.now();
330
349
  }
331
350
  if (abort.signal.aborted) {
@@ -1,3 +1,5 @@
1
+ import { BrowserRegistry } from "./browser-registry.js";
2
+ import { streamBrowser } from "./browser-stream.js";
1
3
  import { continuationPlacement } from "./continuation-launch.js";
2
4
  import { ConductorSuccessionService, preflightConductorWorkers } from "./conductor-succession.js";
3
5
  import { StorePulls } from "./store-pull.js";
@@ -7,6 +9,7 @@ import { AccountFailover } from "./account-failover.js";
7
9
  import { ownerInboxSources } from "./owner-inbox-sources.js";
8
10
  import { OwnerInbox } from "./owner-inbox.js";
9
11
  import { closeFinishedWorker } from "./worker-close.js";
12
+ import { cleanupIdempotencyLocks, markHookServerProcess } from "./dispatch-idempotency.js";
10
13
  import { isLocalComputer } from "./dispatch-hosts.js";
11
14
  import { hookPeers, peerRequest } from "./peers.js";
12
15
  import { handOff } from "./hand-off.js";
@@ -35,7 +38,7 @@ import { approvalPushCapability } from "./push.js";
35
38
  import { startChangeRetention } from "./changes.js";
36
39
  import { CodeReindexer, CodeRoutes } from "./code-routes.js";
37
40
  import { WorkspaceContextUsage } from "./context.js";
38
- import { DispatchService } from "./dispatch.js";
41
+ import { DispatchService, reconcileInterruptedDispatches } from "./dispatch.js";
39
42
  import { DispatchReturns, hookWorkers } from "./dispatch-returns.js";
40
43
  import { findPane, paneChatState, paneIdentity, recentServers, sharedSnapshot, snapshot, validateTarget } from "./herdr.js";
41
44
  import { LaunchLimiter } from "./limits.js";
@@ -53,6 +56,8 @@ import { AccountUsageReader } from "./usage.js";
53
56
  import { ResourceMonitor } from "./resources.js";
54
57
  import { ALERT_CHECK_MS, HealthAlerts } from "./machine-health-alerts.js";
55
58
  import { createScheduleLauncher, Scheduler, scheduleRunsFile } from "./schedules.js";
59
+ import { DREAM_TICK_MS, DreamScheduler, dreamProjectOf, effectiveDreamSessions, dreamStoreProjects, dreamTickerEnabled, readLastRun, runDreamChild } from "./dream-schedule.js";
60
+ import { getDreamingConfig } from "../config/dreaming.js";
56
61
  import { dailyCanaryDue, runCanary } from "./canary.js";
57
62
  import { defaultPhrenPath } from "../shared.js";
58
63
  import { capabilitiesForModules, createRouteHandler, effectiveStatusRows, requireRoute, selectedServer, workspacesReader } from "./server-routes.js";
@@ -75,11 +80,14 @@ import { CodexAuthKeeper, codexAuthRefreshEnabled } from "./codex-auth-refresh.j
75
80
  import { localNames } from "./computer-names.js";
76
81
  import { startStoreSyncLoop } from "../sync/store-sync.js";
77
82
  import { SocketBudget, socketIdentity, socketKind } from "./socket-budget.js";
83
+ import { logger } from "../logger.js";
78
84
  export { capabilities, capabilitiesForModules, requireRoute } from "./server-routes.js";
79
85
  export { streamCloseReason } from "./server-stream.js";
80
86
  export { herdrAgentName, launchSession } from "./server-launch.js";
81
87
  export async function serve(version, options = {}) {
82
88
  process.umask(0o077);
89
+ markHookServerProcess();
90
+ await cleanupIdempotencyLocks().catch(error => logger.warn("dispatch", `Could not clean leftover idempotency locks: ${error instanceof Error ? error.message : String(error)}`));
83
91
  const modules = moduleSnapshot(defaultPhrenPath(), undefined, true);
84
92
  if (!modules.has("hook"))
85
93
  throw new BridgeError(404, disabledHint("hook"));
@@ -122,6 +130,9 @@ export async function serve(version, options = {}) {
122
130
  localWorkers: hookWorkers(agentHooks),
123
131
  close: async (receipt, verifiedPeer) => {
124
132
  const data = { target: receipt.target, dispatch: receipt.moves?.slice().reverse().find(move => move.to.computer)?.id ?? receipt.id, turn: receipt.closePending.turn };
133
+ // Keyed dispatches are local-only: close on this Hook, never over a peer.
134
+ if (receipt.idempotencyKey)
135
+ return closeFinishedWorker(data, handOffs);
125
136
  if (receipt.computerId === computerID)
126
137
  return closeFinishedWorker(data, handOffs);
127
138
  const peer = verifiedPeer ?? (await hookPeers().catch(() => [])).find(peer => peer.name === receipt.computer);
@@ -192,6 +203,7 @@ export async function serve(version, options = {}) {
192
203
  launch: (server, data, options) => launches.run(() => launchSession(server, data, { trustFolder: true, ...options })),
193
204
  inventory: () => launchCheckOff() ? Promise.resolve(undefined) : harnessInventoryWithin(2_500),
194
205
  transcript: async (target) => transcriptTail(await targetTranscriptPath(target)),
206
+ usage: () => accountUsage.limits(true),
195
207
  copyConversation: async (target, home, check) => copyClaudeConversation(await targetTranscriptPath(target), home, process.env, check),
196
208
  paneAccount: (server, pane) => paneAccount(paneAccountKey(server, pane.pane_id), typeof pane.terminal_id === "string" ? pane.terminal_id : undefined)?.id,
197
209
  paneDispatch: async (server, pane) => {
@@ -267,8 +279,14 @@ export async function serve(version, options = {}) {
267
279
  throw new Error("Phren Hook is already running.");
268
280
  await unlink(socketPath());
269
281
  }
282
+ // Only the Hook that owns the socket reconciles dispatch state: a second
283
+ // `bridge serve` stops above before touching any receipt or key record.
284
+ if (dispatches)
285
+ await reconcileInterruptedDispatches().catch(error => logger.warn("dispatch", `Could not reconcile interrupted dispatches: ${error instanceof Error ? error.message : String(error)}`));
270
286
  const storePulls = new StorePulls(scheduleStore);
271
287
  const gitboyWebhooks = new GitboyWebhooks(root, storeId => storePulls.request(storeId), undefined, scheduler ? event => scheduler.ingestEvent(event) : undefined);
288
+ const browsers = new BrowserRegistry(root);
289
+ await browsers.start();
272
290
  const stopRetention = modules.has("git") ? await startChangeRetention() : () => { };
273
291
  if (modules.has("git"))
274
292
  await rm(path.join(root, "changes-scratch"), { recursive: true, force: true });
@@ -286,7 +304,7 @@ export async function serve(version, options = {}) {
286
304
  // 256 KiB: gitboy's /memory/files asks about up to 500 paths in one query string.
287
305
  const http = createServer({ maxHeaderSize: 256 * 1024 }, createRouteHandler({ version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks,
288
306
  journal, tabActivity, contextUsage, modelCatalog, modelSwitcher, settingsSwitcher, permissionModeSwitcher, sideQuestions, accountUsage, resources, codexQuestions, launches, locatedDirectories,
289
- fanoutMessages, canary, streams, returns, handOffs, inbox, mover, succession, storePulls, gitboyWebhooks, turnQueue }));
307
+ fanoutMessages, canary, streams, returns, handOffs, inbox, mover, succession, storePulls, gitboyWebhooks, turnQueue, browsers }));
290
308
  http.requestTimeout = 20_000;
291
309
  http.headersTimeout = 10_000;
292
310
  http.maxHeadersCount = 32;
@@ -295,7 +313,7 @@ export async function serve(version, options = {}) {
295
313
  http.on("upgrade", (request, socket, head) => {
296
314
  try {
297
315
  const url = new URL(request.url || "/", "http://phren.local");
298
- if (!["/v1/transcripts", "/v1/status", "/v1/overview", "/v1/git/watch", "/v1/speech/transcribe", "/v1/speech/live", "/v1/simulators/stream"].includes(url.pathname) || url.origin !== "http://phren.local") {
316
+ if (!["/v1/transcripts", "/v1/status", "/v1/overview", "/v1/git/watch", "/v1/speech/transcribe", "/v1/speech/live", "/v1/simulators/stream", "/v1/browsers/stream"].includes(url.pathname) || url.origin !== "http://phren.local") {
299
317
  socket.destroy();
300
318
  return;
301
319
  }
@@ -324,6 +342,10 @@ export async function serve(version, options = {}) {
324
342
  void relayTranscription(client, url.searchParams).catch(() => failRelay(client));
325
343
  return;
326
344
  }
345
+ if (url.pathname === "/v1/browsers/stream") {
346
+ streamBrowser(client, url.searchParams, browsers);
347
+ return;
348
+ }
327
349
  if (url.pathname === "/v1/simulators/stream") {
328
350
  void streamSimulator(client, url.searchParams).catch(() => client.close(1011, "Simulator stream unavailable"));
329
351
  return;
@@ -351,6 +373,15 @@ export async function serve(version, options = {}) {
351
373
  await codexServers.adopt().catch(() => { });
352
374
  void scheduler?.tick().catch(() => { });
353
375
  const scheduleTimer = scheduler ? setInterval(() => { countTick("schedules"); void scheduler.tick().catch(() => { }); }, 30_000) : undefined;
376
+ // Dreaming (bridge/dream-schedule.ts): each project's `dreaming` config decides; off by default.
377
+ const dreamProject = dreamProjectOf(scheduleStore, modules.profile);
378
+ const dreams = dreamTickerEnabled() ? new DreamScheduler({ now: () => new Date(),
379
+ projects: () => dreamStoreProjects(scheduleStore, modules.profile),
380
+ config: project => getDreamingConfig(scheduleStore, project),
381
+ lastRun: project => readLastRun(scheduleStore, project),
382
+ liveSessions: async () => (await Promise.all((await recentServers()).map(async (server) => effectiveDreamSessions(String(server.session), await sharedSnapshot(String(server.session), 4000), dreamProject, agentHooks, codexQuestions)))).flat(),
383
+ run: project => runDreamChild(scheduleStore, project) }) : undefined;
384
+ const dreamTimer = dreams ? setInterval(() => { countTick("dreams"); void dreams.tick().catch(() => { }); }, DREAM_TICK_MS) : undefined;
354
385
  // Off unless PHREN_CANARY_DAILY=1 or `phren canary --daily on`.
355
386
  // Refresh the shared Codex sign-in before its workers each try to at once.
356
387
  const codexAuth = codexAppServerEnabled() && codexAuthRefreshEnabled() ? new CodexAuthKeeper(codexServers) : undefined;
@@ -413,7 +444,7 @@ export async function serve(version, options = {}) {
413
444
  })().finally(() => { recording = false; }).catch(() => { });
414
445
  }, 5000);
415
446
  await new Promise(resolve => {
416
- const stop = () => { gitboyWebhooks.stop(); storePulls.stop(); storeSync.stop(); fanoutMessages.close(); stopRetention(); clearInterval(scheduleTimer); clearInterval(canaryTimer); clearInterval(healthTimer); clearInterval(codexAuthTimer); clearInterval(activityTimer); scheduler?.close(); codeReindexer?.close(); codexServers.close(); gitWatch.close(); agentHooks.close(); ws.clients.forEach(c => c.terminate()); ws.close(); http.close(() => resolve()); http.closeAllConnections(); };
447
+ const stop = () => { browsers.close(); gitboyWebhooks.stop(); storePulls.stop(); storeSync.stop(); fanoutMessages.close(); stopRetention(); clearInterval(scheduleTimer); clearInterval(dreamTimer); clearInterval(canaryTimer); clearInterval(healthTimer); clearInterval(codexAuthTimer); clearInterval(activityTimer); scheduler?.close(); codeReindexer?.close(); codexServers.close(); gitWatch.close(); agentHooks.close(); ws.clients.forEach(c => c.terminate()); ws.close(); http.close(() => resolve()); http.closeAllConnections(); };
417
448
  process.once("SIGTERM", stop);
418
449
  process.once("SIGINT", stop);
419
450
  });
@@ -1,3 +1,4 @@
1
+ import { type AccountUsage } from "./usage.js";
1
2
  import type { ConductorSuccessionService } from "./conductor-succession.js";
2
3
  import { z } from "zod";
3
4
  import { type ClaudeHome } from "./claude-accounts.js";
@@ -47,8 +48,10 @@ export declare const moveRequestSchema: z.ZodObject<{
47
48
  replace: "replace";
48
49
  }>>;
49
50
  continuation: z.ZodDefault<z.ZodEnum<{
51
+ "agent-summary": "agent-summary";
50
52
  handoff: "handoff";
51
53
  resume: "resume";
54
+ "saved-history": "saved-history";
52
55
  "summary-by-target": "summary-by-target";
53
56
  }>>;
54
57
  id: z.ZodOptional<z.ZodString>;
@@ -113,7 +116,9 @@ declare const moveRecordSchema: z.ZodObject<{
113
116
  replace: "replace";
114
117
  }>>;
115
118
  continuation: z.ZodOptional<z.ZodEnum<{
119
+ "agent-summary": "agent-summary";
116
120
  resume: "resume";
121
+ "saved-history": "saved-history";
117
122
  "summary-by-target": "summary-by-target";
118
123
  }>>;
119
124
  modeForced: z.ZodOptional<z.ZodLiteral<"conductor">>;
@@ -328,8 +333,7 @@ export declare function fallbackHandoff(input: {
328
333
  dispatch?: string;
329
334
  label?: string;
330
335
  }): string;
331
- /** Whether a Claude conversation's last turn ended on its subscription's usage limit (Claude's own
332
- * rate-limit row): its agent cannot answer a hand-off request. */
336
+ /** Whether the harness ended its latest turn with a quota error: it cannot answer a hand-off request. */
333
337
  export declare function sourceOutOfUsage(lines: readonly string[], source: Provider): boolean;
334
338
  /**
335
339
  * The whole conversation a summary-by-target move copies to the other computer: every prompt and reply, oldest
@@ -380,7 +384,9 @@ export interface MoverDeps {
380
384
  inventory: () => Promise<HarnessInventory | undefined>;
381
385
  /** The conversation's transcript lines, its tail is enough. */
382
386
  transcript: (target: Target) => Promise<string[]>;
383
- /** The whole transcript for a summary-by-target move's copy, and whether all of it was read. */
387
+ /** Current account limits from the Hook's shared usage reader. */
388
+ usage?: () => Promise<AccountUsage[]>;
389
+ /** The whole transcript for a continuation copy, and whether all of it was read. */
384
390
  conversation?: (target: Target) => Promise<{
385
391
  lines: string[];
386
392
  complete: boolean;
@@ -461,7 +467,7 @@ export declare class SessionMover {
461
467
  private checkPromotion;
462
468
  /** Uses the same durable prompt path as the hand-off and its first brief. */
463
469
  private conductorNotice;
464
- /** The agent's own hand-off, or why there is none. Fails only when the session itself went away. */
470
+ /** The agent's optional hand-off, or why there is none; run also catches lifecycle failures. */
465
471
  private askForHandoff;
466
472
  private fallback;
467
473
  /** The same conversation under another Claude account: the old agent exits,