@phren/cli 0.3.70 → 0.3.72

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 (108) hide show
  1. package/dist/bridge/browser-env.d.ts +5 -0
  2. package/dist/bridge/browser-env.js +86 -0
  3. package/dist/bridge/browser-protocol.d.ts +120 -0
  4. package/dist/bridge/browser-protocol.js +70 -0
  5. package/dist/bridge/browser-recordings.d.ts +63 -0
  6. package/dist/bridge/browser-recordings.js +148 -0
  7. package/dist/bridge/browser-registry.d.ts +64 -0
  8. package/dist/bridge/browser-registry.js +262 -0
  9. package/dist/bridge/browser-routes.d.ts +4 -0
  10. package/dist/bridge/browser-routes.js +39 -0
  11. package/dist/bridge/browser-shim/phren-playwright.cjs +184 -0
  12. package/dist/bridge/browser-socket.d.ts +2 -0
  13. package/dist/bridge/browser-socket.js +10 -0
  14. package/dist/bridge/browser-stream.d.ts +3 -0
  15. package/dist/bridge/browser-stream.js +129 -0
  16. package/dist/bridge/claude-question-dialog.js +32 -7
  17. package/dist/bridge/dispatch.d.ts +10 -0
  18. package/dist/bridge/dispatch.js +3 -1
  19. package/dist/bridge/dream-schedule.d.ts +133 -0
  20. package/dist/bridge/dream-schedule.js +322 -0
  21. package/dist/bridge/herdr.js +15 -6
  22. package/dist/bridge/install.js +4 -0
  23. package/dist/bridge/launch-brief.d.ts +11 -0
  24. package/dist/bridge/launch-brief.js +22 -0
  25. package/dist/bridge/pane-status.js +1 -1
  26. package/dist/bridge/server-routes.d.ts +3 -0
  27. package/dist/bridge/server-routes.js +15 -15
  28. package/dist/bridge/server-stream.d.ts +4 -0
  29. package/dist/bridge/server-stream.js +24 -5
  30. package/dist/bridge/server.js +23 -3
  31. package/dist/bridge/session-move.d.ts +10 -4
  32. package/dist/bridge/session-move.js +65 -34
  33. package/dist/bridge/simulator-stream.d.ts +2 -0
  34. package/dist/bridge/simulator-stream.js +2 -0
  35. package/dist/bridge/tab-activity.d.ts +2 -0
  36. package/dist/bridge/tab-activity.js +15 -2
  37. package/dist/bridge/task-routes.d.ts +20 -16
  38. package/dist/bridge/task-routes.js +1 -1
  39. package/dist/bridge/terminal-herdr.js +2 -1
  40. package/dist/bridge/terminal-tmux.js +2 -1
  41. package/dist/bridge/worker-reports.js +15 -3
  42. package/dist/bridge-hook.mjs +36819 -35219
  43. package/dist/capabilities/mcp.js +1 -1
  44. package/dist/cli/config-dreaming.d.ts +7 -0
  45. package/dist/cli/config-dreaming.js +72 -0
  46. package/dist/cli/config.js +6 -0
  47. package/dist/cli/dream.d.ts +59 -0
  48. package/dist/cli/dream.js +315 -0
  49. package/dist/cli/namespaces-tasks.js +14 -0
  50. package/dist/cli-registry.js +24 -1
  51. package/dist/config/dreaming.d.ts +82 -0
  52. package/dist/config/dreaming.js +195 -0
  53. package/dist/config/resolve.js +11 -0
  54. package/dist/config/schema.d.ts +4 -4
  55. package/dist/config/schema.js +157 -1
  56. package/dist/content/citation-freshness.js +6 -0
  57. package/dist/content/learning.d.ts +1 -0
  58. package/dist/content/learning.js +2 -0
  59. package/dist/data/access.d.ts +1 -1
  60. package/dist/data/access.js +3 -1
  61. package/dist/data/task-contract.d.ts +5 -4
  62. package/dist/data/tasks.d.ts +5 -0
  63. package/dist/data/tasks.js +28 -2
  64. package/dist/dream/apply.d.ts +69 -0
  65. package/dist/dream/apply.js +372 -0
  66. package/dist/dream/budget.d.ts +78 -0
  67. package/dist/dream/budget.js +180 -0
  68. package/dist/dream/collect.d.ts +86 -0
  69. package/dist/dream/collect.js +449 -0
  70. package/dist/dream/eval/dream-adapter.d.ts +16 -0
  71. package/dist/dream/eval/dream-adapter.js +21 -0
  72. package/dist/dream/eval/fixture.d.ts +53 -0
  73. package/dist/dream/eval/fixture.js +172 -0
  74. package/dist/dream/eval/index.d.ts +40 -0
  75. package/dist/dream/eval/index.js +78 -0
  76. package/dist/dream/eval/score.d.ts +34 -0
  77. package/dist/dream/eval/score.js +99 -0
  78. package/dist/dream/eval/scripted-model.d.ts +19 -0
  79. package/dist/dream/eval/scripted-model.js +70 -0
  80. package/dist/dream/pages.d.ts +68 -0
  81. package/dist/dream/pages.js +220 -0
  82. package/dist/dream/privacy.d.ts +3 -0
  83. package/dist/dream/privacy.js +18 -0
  84. package/dist/dream/prompt.d.ts +13 -0
  85. package/dist/dream/prompt.js +84 -0
  86. package/dist/dream/run.d.ts +98 -0
  87. package/dist/dream/run.js +317 -0
  88. package/dist/dream/types.d.ts +74 -0
  89. package/dist/dream/types.js +4 -0
  90. package/dist/finding/lifecycle.d.ts +2 -2
  91. package/dist/finding/lifecycle.js +5 -2
  92. package/dist/finding/versions.d.ts +4 -0
  93. package/dist/finding/versions.js +28 -0
  94. package/dist/index.js +1 -0
  95. package/dist/modules/registry.js +9 -7
  96. package/dist/project-config.d.ts +3 -0
  97. package/dist/task/merge-links.d.ts +38 -0
  98. package/dist/task/merge-links.js +45 -0
  99. package/dist/task/reconcile.d.ts +39 -0
  100. package/dist/task/reconcile.js +201 -0
  101. package/dist/task/report-links.d.ts +10 -0
  102. package/dist/task/report-links.js +47 -0
  103. package/dist/tools/config.js +46 -4
  104. package/dist/tools/dispatch.js +2 -1
  105. package/dist/tools/dream.d.ts +3 -0
  106. package/dist/tools/dream.js +123 -0
  107. package/dist/tools/tasks.js +4 -1
  108. package/package.json +1 -1
@@ -1,3 +1,4 @@
1
+ import { mergeTaskIdentitySchema } from "../task/merge-links.js";
1
2
  import { randomUUID } from "node:crypto";
2
3
  import { lstat, mkdir, readdir, readFile, rename, rm, stat } from "node:fs/promises";
3
4
  import path from "node:path";
@@ -23,6 +24,7 @@ import { atomic, BridgeError, bridgeRoot, targetSchema } from "./protocol.js";
23
24
  export const briefId = z.string().regex(/^[A-Za-z0-9_-]{8,64}$/);
24
25
  export const launchBriefSchema = z.object({
25
26
  id: briefId,
27
+ task: mergeTaskIdentitySchema.optional(),
26
28
  text: z.string().min(1).max(32768).refine(value => !!value.trim() && !/[\x00-\x08\x0b-\x1f\x7f]/.test(value)),
27
29
  }).strict();
28
30
  /** The variable a launched agent's hooks read its brief id from. */
@@ -110,6 +112,8 @@ export async function writeLaunchBrief(brief, now = Date.now(), label) {
110
112
  const named = label ? cleanLabel(label) : "";
111
113
  const fill = async (folder) => {
112
114
  await atomic(path.join(folder, "brief.md"), text);
115
+ if (brief.task)
116
+ await atomic(path.join(folder, "task.json"), JSON.stringify(brief.task));
113
117
  if (named)
114
118
  await atomic(path.join(folder, LABEL_FILE), named);
115
119
  };
@@ -117,6 +121,9 @@ export async function writeLaunchBrief(brief, now = Date.now(), label) {
117
121
  const existing = async () => {
118
122
  if (await readFile(file, "utf8").catch(() => undefined) !== text)
119
123
  throw new BridgeError(409, "This brief id already belongs to another launch.");
124
+ const task = await readFile(path.join(directory, "task.json"), "utf8").catch(() => undefined);
125
+ if (task !== (brief.task ? JSON.stringify(brief.task) : undefined))
126
+ throw new BridgeError(409, "This brief id belongs to another task.");
120
127
  return file;
121
128
  };
122
129
  if (await stat(directory).catch(() => undefined))
@@ -196,3 +203,18 @@ export function recordBriefArrival(id, event, target, now = new Date()) {
196
203
  arrivals = run.catch(() => undefined);
197
204
  return run;
198
205
  }
206
+ /** Private association carried with the launch, never included in GitHub data. */
207
+ export async function briefTask(id) {
208
+ if (!briefId.safeParse(id).success)
209
+ return undefined;
210
+ try {
211
+ const file = path.join(briefDirectory(id), "task.json");
212
+ const info = await lstat(file);
213
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 1024)
214
+ return undefined;
215
+ return mergeTaskIdentitySchema.parse(JSON.parse(await readFile(file, "utf8")));
216
+ }
217
+ catch {
218
+ return undefined;
219
+ }
220
+ }
@@ -111,7 +111,7 @@ export function screenDialog(agent, screen) {
111
111
  return !!opencodePermissionDialog(screen);
112
112
  if (agent === "codex" || agent === "copilot")
113
113
  return !!visibleTerminalChoice(text);
114
- if (agent === "claude" && (claudeQuestionDialog(text) || claudeTeachAutoModeDialog(text)))
114
+ if (agent === "claude" && claudeQuestionDialog(text))
115
115
  return true;
116
116
  return !!claudePermissionDialog(text);
117
117
  }
@@ -1,3 +1,4 @@
1
+ import type { BrowserRegistry } from "./browser-registry.js";
1
2
  import type { TurnQueue } from "./turn-queue.js";
2
3
  import type { ConductorSuccessionService } from "./conductor-succession.js";
3
4
  import type { StorePulls } from "./store-pull.js";
@@ -50,6 +51,7 @@ export interface HookInfo {
50
51
  readonly gatewayMs: number | undefined;
51
52
  }
52
53
  export interface RouteContext {
54
+ browsers?: BrowserRegistry;
53
55
  turnQueue?: TurnQueue;
54
56
  version: string;
55
57
  modules: ModuleSnapshot;
@@ -100,6 +102,7 @@ export declare const STATUS_ENRICH_BUDGET_MS = 2000;
100
102
  * finish inside `budgetMs` is left out, which preserves its last known status. */
101
103
  export declare function effectiveStatusRows(server: string, s: Json, budgetMs?: number, hooks?: AgentHooks): Promise<StatusRow[]>;
102
104
  export declare const capabilities: {
105
+ browsers: boolean;
103
106
  turnCheckpoints: boolean;
104
107
  transcript: boolean;
105
108
  progress: boolean;
@@ -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";
@@ -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 })));
@@ -446,6 +442,10 @@ export function createRouteHandler(ctx) {
446
442
  if (url.origin !== "http://phren.local")
447
443
  throw new BridgeError(400, "Invalid request origin.");
448
444
  requireRoute(modules, request.method ?? "", url.pathname);
445
+ if (url.pathname === "/v1/browsers" || url.pathname.startsWith("/v1/browsers/")) {
446
+ browserRoute(ctx.browsers, request.method ?? "", url, response);
447
+ return;
448
+ }
449
449
  let result;
450
450
  if (url.pathname.startsWith("/v1/conductor/move/")) {
451
451
  if (!ctx.succession)
@@ -938,7 +938,7 @@ export function createRouteHandler(ctx) {
938
938
  const target = targetFromURL(url);
939
939
  await validateTarget(target);
940
940
  const { reader, source, session } = await childConversationReader(target, z.string().parse(url.searchParams.get("child")));
941
- const page = await reader.read();
941
+ const page = reader ? await reader.read() : emptyPage;
942
942
  result = { ...page, type: "backlog", source, session };
943
943
  break;
944
944
  }
@@ -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";
@@ -53,6 +55,8 @@ import { AccountUsageReader } from "./usage.js";
53
55
  import { ResourceMonitor } from "./resources.js";
54
56
  import { ALERT_CHECK_MS, HealthAlerts } from "./machine-health-alerts.js";
55
57
  import { createScheduleLauncher, Scheduler, scheduleRunsFile } from "./schedules.js";
58
+ import { DREAM_TICK_MS, DreamScheduler, dreamProjectOf, effectiveDreamSessions, dreamStoreProjects, dreamTickerEnabled, readLastRun, runDreamChild } from "./dream-schedule.js";
59
+ import { getDreamingConfig } from "../config/dreaming.js";
56
60
  import { dailyCanaryDue, runCanary } from "./canary.js";
57
61
  import { defaultPhrenPath } from "../shared.js";
58
62
  import { capabilitiesForModules, createRouteHandler, effectiveStatusRows, requireRoute, selectedServer, workspacesReader } from "./server-routes.js";
@@ -192,6 +196,7 @@ export async function serve(version, options = {}) {
192
196
  launch: (server, data, options) => launches.run(() => launchSession(server, data, { trustFolder: true, ...options })),
193
197
  inventory: () => launchCheckOff() ? Promise.resolve(undefined) : harnessInventoryWithin(2_500),
194
198
  transcript: async (target) => transcriptTail(await targetTranscriptPath(target)),
199
+ usage: () => accountUsage.limits(true),
195
200
  copyConversation: async (target, home, check) => copyClaudeConversation(await targetTranscriptPath(target), home, process.env, check),
196
201
  paneAccount: (server, pane) => paneAccount(paneAccountKey(server, pane.pane_id), typeof pane.terminal_id === "string" ? pane.terminal_id : undefined)?.id,
197
202
  paneDispatch: async (server, pane) => {
@@ -269,6 +274,8 @@ export async function serve(version, options = {}) {
269
274
  }
270
275
  const storePulls = new StorePulls(scheduleStore);
271
276
  const gitboyWebhooks = new GitboyWebhooks(root, storeId => storePulls.request(storeId), undefined, scheduler ? event => scheduler.ingestEvent(event) : undefined);
277
+ const browsers = new BrowserRegistry(root);
278
+ await browsers.start();
272
279
  const stopRetention = modules.has("git") ? await startChangeRetention() : () => { };
273
280
  if (modules.has("git"))
274
281
  await rm(path.join(root, "changes-scratch"), { recursive: true, force: true });
@@ -286,7 +293,7 @@ export async function serve(version, options = {}) {
286
293
  // 256 KiB: gitboy's /memory/files asks about up to 500 paths in one query string.
287
294
  const http = createServer({ maxHeaderSize: 256 * 1024 }, createRouteHandler({ version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks,
288
295
  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 }));
296
+ fanoutMessages, canary, streams, returns, handOffs, inbox, mover, succession, storePulls, gitboyWebhooks, turnQueue, browsers }));
290
297
  http.requestTimeout = 20_000;
291
298
  http.headersTimeout = 10_000;
292
299
  http.maxHeadersCount = 32;
@@ -295,7 +302,7 @@ export async function serve(version, options = {}) {
295
302
  http.on("upgrade", (request, socket, head) => {
296
303
  try {
297
304
  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") {
305
+ 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
306
  socket.destroy();
300
307
  return;
301
308
  }
@@ -324,6 +331,10 @@ export async function serve(version, options = {}) {
324
331
  void relayTranscription(client, url.searchParams).catch(() => failRelay(client));
325
332
  return;
326
333
  }
334
+ if (url.pathname === "/v1/browsers/stream") {
335
+ streamBrowser(client, url.searchParams, browsers);
336
+ return;
337
+ }
327
338
  if (url.pathname === "/v1/simulators/stream") {
328
339
  void streamSimulator(client, url.searchParams).catch(() => client.close(1011, "Simulator stream unavailable"));
329
340
  return;
@@ -351,6 +362,15 @@ export async function serve(version, options = {}) {
351
362
  await codexServers.adopt().catch(() => { });
352
363
  void scheduler?.tick().catch(() => { });
353
364
  const scheduleTimer = scheduler ? setInterval(() => { countTick("schedules"); void scheduler.tick().catch(() => { }); }, 30_000) : undefined;
365
+ // Dreaming (bridge/dream-schedule.ts): each project's `dreaming` config decides; off by default.
366
+ const dreamProject = dreamProjectOf(scheduleStore, modules.profile);
367
+ const dreams = dreamTickerEnabled() ? new DreamScheduler({ now: () => new Date(),
368
+ projects: () => dreamStoreProjects(scheduleStore, modules.profile),
369
+ config: project => getDreamingConfig(scheduleStore, project),
370
+ lastRun: project => readLastRun(scheduleStore, project),
371
+ liveSessions: async () => (await Promise.all((await recentServers()).map(async (server) => effectiveDreamSessions(String(server.session), await sharedSnapshot(String(server.session), 4000), dreamProject, agentHooks, codexQuestions)))).flat(),
372
+ run: project => runDreamChild(scheduleStore, project) }) : undefined;
373
+ const dreamTimer = dreams ? setInterval(() => { countTick("dreams"); void dreams.tick().catch(() => { }); }, DREAM_TICK_MS) : undefined;
354
374
  // Off unless PHREN_CANARY_DAILY=1 or `phren canary --daily on`.
355
375
  // Refresh the shared Codex sign-in before its workers each try to at once.
356
376
  const codexAuth = codexAppServerEnabled() && codexAuthRefreshEnabled() ? new CodexAuthKeeper(codexServers) : undefined;
@@ -413,7 +433,7 @@ export async function serve(version, options = {}) {
413
433
  })().finally(() => { recording = false; }).catch(() => { });
414
434
  }, 5000);
415
435
  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(); };
436
+ 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
437
  process.once("SIGTERM", stop);
418
438
  process.once("SIGINT", stop);
419
439
  });
@@ -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,
@@ -1,15 +1,16 @@
1
+ import { capacityRoom } from "./usage.js";
1
2
  import { targetTranscriptPath } from "./transcripts.js";
2
3
  import { CONVERSATION_LIMIT, CONVERSATION_MARKER, ORPHAN_GRACE_MS, pruneContinuationConversations, saveContinuationConversation, saveContinuationIntent } from "./continuation-launch.js";
3
4
  import { redactPeerHandoff } from "./peer-handoff.js";
4
- // Moving a live session to another agent: the agent in the pane writes a
5
- // hand-off, exits the way it normally does, and the target harness starts in
5
+ // Moving a live session to another agent: the Hook saves its history and an
6
+ // optional agent summary, exits the source, and the target harness starts in
6
7
  // the same pane by default, or a new chat that keeps the old agent running.
7
8
  //
8
9
  // The hand-off is asked for through the same durable prompt path `hand_off`
9
10
  // uses, as a reply between two marker lines; the Hook reads it from the
10
11
  // transcript and saves it. A reply never waits on a permission prompt, which
11
12
  // a write outside the checkout would in a supervised session. When the agent
12
- // does not answer in time, the hand-off is built from the transcript's tail,
13
+ // cannot answer, the hand-off is built from its saved conversation,
13
14
  // the git state and the original brief instead, as a worker continued on
14
15
  // another account is (account-failover.ts).
15
16
  //
@@ -48,8 +49,9 @@ export const moveRequestSchema = z.object({
48
49
  * account's home and the same conversation resumes there (`claude --resume`),
49
50
  * so an account at its usage limit can still switch. `summary-by-target` (a move to another computer):
50
51
  * the source is not asked for a hand-off; the new agent there builds one from the copied conversation.
51
- * A source whose last turn ended on its usage limit is moved this way without asking. */
52
- continuation: z.enum(["handoff", "resume", "summary-by-target"]).default("handoff"),
52
+ * `saved-history` continues immediately on this computer or a peer; `agent-summary` asks a healthy
53
+ * source for an optional summary. Omitted/`handoff` automatically skips an exhausted source. */
54
+ continuation: z.enum(["handoff", "resume", "summary-by-target", "agent-summary", "saved-history"]).default("handoff"),
53
55
  /** Kept on a retry: the same id returns the move already under way. */
54
56
  id: z.string().uuid().optional(),
55
57
  /** How long the agent gets to write its hand-off before Phren builds one. */
@@ -70,7 +72,7 @@ const moveRecordSchema = z.object({
70
72
  mode: z.enum(["replace", "new-chat"]).optional(),
71
73
  /** `resume`: the same conversation under another account here. `summary-by-target`: the source was out of
72
74
  * usage, so the agent on the other computer builds the hand-off from the copied conversation. */
73
- continuation: z.enum(["resume", "summary-by-target"]).optional(),
75
+ continuation: z.enum(["resume", "summary-by-target", "agent-summary", "saved-history"]).optional(),
74
76
  modeForced: z.literal("conductor").optional(),
75
77
  handedOffTo: z.object({ computer: z.string().optional(), target: z.union([targetSchema, startingTargetSchema]) }).strict().optional(),
76
78
  handedOffFrom: z.object({ target: targetSchema, title: z.string().max(200) }).strict().optional(),
@@ -394,10 +396,12 @@ export function fallbackHandoff(input) {
394
396
  // Written to a file, so the brief is never cut here.
395
397
  return input.original ? withOriginalBrief(head, input.original, Number.MAX_SAFE_INTEGER, "the original brief file") : head;
396
398
  }
397
- /** Whether a Claude conversation's last turn ended on its subscription's usage limit (Claude's own
398
- * rate-limit row): its agent cannot answer a hand-off request. */
399
+ /** Whether the harness ended its latest turn with a quota error: it cannot answer a hand-off request. */
399
400
  export function sourceOutOfUsage(lines, source) {
400
- return source === "claude" && isClaudeUsageLimit(finalTurnFromLines(lines, "claude").error);
401
+ if (source === "phren")
402
+ return false;
403
+ const error = finalTurnFromLines(lines, source).error;
404
+ return isClaudeUsageLimit(error) || /usage.?limit|rate.?limit|quota|insufficient.?credits|429/i.test(error ?? "");
401
405
  }
402
406
  /** Room left in a cross-computer brief for the copied conversation, once the rest of the hand-off is in. */
403
407
  const TRANSCRIPT_MARGIN = 2_000;
@@ -499,7 +503,7 @@ export function handoffDocument(record, body, observed, at, conductor = false) {
499
503
  }
500
504
  /** The new agent's first prompt: the whole hand-off when it fits the brief, else where to read it. */
501
505
  export function continuePrompt(document, file) {
502
- const lead = "Phren moved this session to you. The hand-off from the previous agent follows. Continue from here: check the current state first, keep its uncommitted changes, and do not start over.";
506
+ const lead = `Phren moved this session to you. The hand-off from the previous agent follows (saved at ${file}; resolve its history file beside it). Continue from here: check the current state first, keep its uncommitted changes, and do not start over.`;
503
507
  const whole = `${lead}\n\n${document}`;
504
508
  if (whole.length <= PROMPT_LIMIT)
505
509
  return whole;
@@ -680,7 +684,7 @@ export class SessionMover {
680
684
  const at = new Date(this.now).toISOString();
681
685
  const resume = data.continuation === "resume";
682
686
  const record = { id: data.id ?? randomUUID(), state: resume ? "exiting" : "handing-off", createdAt: at, updatedAt: at,
683
- ...(project ? { project } : {}), mode: conductor || peer ? "new-chat" : data.mode, ...(resume ? { continuation: "resume" } : data.continuation === "summary-by-target" ? { continuation: "summary-by-target" } : {}), ...(conductor ? { modeForced: "conductor" } : {}), from: { target, ...(account ? { account } : {}), ...(label ? { label: label.slice(0, 200) } : {}) }, to, cwd, ...(computerId ? { computerId } : {}), ...(peer?.fingerprint ? { computerFingerprint: peer.fingerprint } : {}), ...(accountChoice ? { accountChoice } : {}),
687
+ ...(project ? { project } : {}), mode: conductor || peer ? "new-chat" : data.mode, ...(data.continuation !== "handoff" ? { continuation: data.continuation } : {}), ...(conductor ? { modeForced: "conductor" } : {}), from: { target, ...(account ? { account } : {}), ...(label ? { label: label.slice(0, 200) } : {}) }, to, cwd, ...(computerId ? { computerId } : {}), ...(peer?.fingerprint ? { computerFingerprint: peer.fingerprint } : {}), ...(accountChoice ? { accountChoice } : {}),
684
688
  ...(dispatch && briefId.safeParse(dispatch).success ? { dispatch } : {}), ...(workerDispatch ? { workerDispatch } : {}) };
685
689
  await assertUnusedLaunchId(record.id);
686
690
  if (conductor && peer) {
@@ -709,18 +713,22 @@ export class SessionMover {
709
713
  const pids = pane ? (await this.deps.terminal.processes(from.server, from.pane).catch(() => undefined))?.foregroundPids ?? [] : [];
710
714
  const [git, processes] = await Promise.all([(this.deps.git ?? readGitState)(record.cwd).catch(() => undefined),
711
715
  (this.deps.processesBelow ?? processesBelow)(pids).catch(() => [])]);
712
- // A source out of usage cannot answer a hand-off request: on another computer, the new agent builds it.
713
- const requested = record.continuation === "summary-by-target";
714
- const lines = peer ? await this.deps.transcript(from).catch(() => undefined) : [];
715
- // Asked for by name, the move never launches an agent with no conversation to build from.
716
- if (requested && !lines?.length)
716
+ // Saved history is available even when the outgoing harness cannot answer or disappears.
717
+ const portable = !!peer || from.source !== record.to.harness || record.continuation === "saved-history";
718
+ const lines = await this.deps.transcript(from).catch(() => []);
719
+ const whole = portable ? await (this.deps.conversation ?? wholeTranscript)(from).catch(() => undefined) : undefined;
720
+ const entries = conversationEntries(whole?.lines ?? lines, from.source);
721
+ const limits = await this.deps.usage?.().catch(() => []);
722
+ const exhausted = sourceOutOfUsage(lines, from.source) || capacityRoom(limits ?? [], this.now)
723
+ .some(row => row.source === from.source && (from.source !== "claude" || (row.account ?? DEFAULT_ACCOUNT) === (record.from.account ?? DEFAULT_ACCOUNT)) && row.exhausted);
724
+ const requested = record.continuation === "summary-by-target" || record.continuation === "saved-history";
725
+ if (record.continuation === "summary-by-target" && !entries.length)
717
726
  throw new BridgeError(409, "The conversation could not be read, so the agent on the other computer would have nothing to build a hand-off from; the old chat remains open.");
718
- const exhausted = !!peer && sourceOutOfUsage(lines ?? [], from.source);
719
- const byTarget = !!peer && (requested || exhausted);
727
+ const byTarget = portable && (requested || exhausted);
720
728
  if (byTarget && !requested)
721
- await this.update(record, { continuation: "summary-by-target" });
722
- const written = byTarget ? { reason: `${exhausted ? "its account is out of usage" : "the owner asked"}, so the agent on ${peer.name} builds the hand-off from the copied conversation.` }
723
- : await this.askForHandoff(record, handoffMs);
729
+ await this.update(record, { continuation: peer ? "summary-by-target" : "saved-history" });
730
+ const written = byTarget ? { reason: `${exhausted ? "its account is out of usage" : "the owner asked for immediate continuation"}; continue from saved history.` }
731
+ : await this.askForHandoff(record, handoffMs).catch(error => ({ reason: `the hand-off request failed (${error instanceof Error ? error.message : String(error)}).` }));
724
732
  // The wait is over. Its request, if still untyped, is taken back first: typed later it would ask the old
725
733
  // agent (left running by a new-chat move) for a hand-off nobody reads. Then an interrupt already checking
726
734
  // finishes, and none starts after (the move goes on to exit or launch, where an Escape would hit the exit
@@ -730,32 +738,30 @@ export class SessionMover {
730
738
  await this.lifecycle(record.id, async () => { this.asking.delete(record.id); });
731
739
  const observed = observedState(git, processes, !peer), at = new Date(this.now).toISOString();
732
740
  let body;
733
- if (byTarget) {
741
+ if (byTarget || (portable && !("text" in written))) {
734
742
  const original = record.dispatch ? await this.deps.brief?.(record.dispatch).catch(() => undefined) : undefined;
735
- const entries = conversationEntries(lines ?? [], from.source);
736
743
  const fit = (room) => targetSummaryBody({ from: harnessName({ harness: from.source, account: record.from.account }), exhausted,
737
- entries, room, prepare: text => redactPeerHandoff(text.replaceAll(record.cwd, "<source checkout>")), ...(original ? { original } : {}),
744
+ entries, room, prepare: text => peer ? redactPeerHandoff(text.replaceAll(record.cwd, "<source checkout>")) : briefText(text),
745
+ original: original ?? entries.find(entry => entry.role === "owner")?.text,
738
746
  ...(record.dispatch ? { dispatch: record.dispatch } : {}), ...(record.from.label ? { label: record.from.label } : {}) });
739
747
  // What fits beside the rest of the hand-off in the one brief the other computer gets, measured as sent:
740
748
  // the checkout path replaced and credentials redacted, either of which can lengthen the text. Messages
741
749
  // are prepared that way before they are counted; the refit only catches what the rest of the brief adds.
742
750
  // The receiving Hook appends where it put the whole conversation, so that line's room is kept free.
743
751
  const limit = PROMPT_LIMIT - POINTER_ROOM;
744
- let room = limit - peerPrompt(record, handoffDocument(record, "", observed, at, !!conductor)).length - TRANSCRIPT_MARGIN;
752
+ const promptFor = (body) => {
753
+ const document = handoffDocument(record, body, observed, at, !!conductor);
754
+ return peer ? peerPrompt(record, document) : `Phren moved this session to you. Inspect the checkout before continuing.\n\n${document}`;
755
+ };
756
+ let room = limit - promptFor("").length - TRANSCRIPT_MARGIN;
745
757
  body = fit(room);
746
758
  for (let tries = 0; tries < 4; tries++) {
747
- const over = peerPrompt(record, handoffDocument(record, body, observed, at, !!conductor)).length - limit;
759
+ const over = promptFor(body).length - limit;
748
760
  if (over <= 0)
749
761
  break;
750
762
  room -= over + 500;
751
763
  body = fit(room);
752
764
  }
753
- // The whole conversation, for the receiving Hook to pull beside the brief (continuation-launch.ts). A copy
754
- // that cannot be saved leaves the excerpt, which the brief carries anyway.
755
- // Read whole here: the lines above are the transcript's last 512 KiB, which tool output can fill.
756
- const whole = await (this.deps.conversation ?? wholeTranscript)(from).catch(() => undefined);
757
- await saveContinuationConversation(record.id, conversationCopy(whole ? conversationEntries(whole.lines, from.source) : entries, text => briefText(redactPeerHandoff(text.replaceAll(record.cwd, "<source checkout>"))), CONVERSATION_LIMIT, whole?.complete ?? false))
758
- .catch(() => undefined);
759
765
  }
760
766
  else {
761
767
  const fallback = "text" in written ? undefined : await this.fallback(record, written.reason);
@@ -763,12 +769,37 @@ export class SessionMover {
763
769
  ? `## Goal and current state\n\n${fallback}\n\n## Next steps\n\nContinue the owner's goal above after checking the checkout and the latest agent reply.\n\n## Key files\n\nOpen or changed files are named in the conversation above and the checked Git state below; open editor tabs are not available to the Hook.`
764
770
  : fallback;
765
771
  }
772
+ if (portable && !peer && record.mode === "new-chat" && !("text" in written)) {
773
+ body = `## Goal and current state\n\n${body}\n\n## Next steps\n\nContinue the owner's goal above after checking the checkout and the latest agent reply.\n\n## Key files\n\nOpen or changed files are named in the conversation above and the checked Git state below; open editor tabs are not available to the Hook.`;
774
+ }
775
+ let savedHistory;
776
+ if (portable) {
777
+ const prepare = (text) => briefText(peer ? redactPeerHandoff(text.replaceAll(record.cwd, "<source checkout>")) : text);
778
+ const first = entries.find(entry => entry.role === "owner")?.text;
779
+ const original = record.dispatch ? await this.deps.brief?.(record.dispatch).catch(() => undefined) : undefined;
780
+ const prefix = [original ? `Original dispatch request:\n${prepare(original).slice(0, ORIGINAL_RESERVE)}` : "",
781
+ first ? `Original owner request:\n${prepare(first).slice(0, ORIGINAL_RESERVE)}` : ""].filter(Boolean).join("\n\n");
782
+ const copy = `${prefix}\n\n${conversationCopy(entries, prepare, CONVERSATION_LIMIT - prefix.length - 2, whole?.complete ?? false)}`;
783
+ // Save before exiting the source. This durable local copy outlives intent-copy cleanup.
784
+ // writeLaunchBrief publishes its folder atomically and owns the launch id.
785
+ // Fill in the history only after that publication, still before source exit.
786
+ savedHistory = copy;
787
+ if (peer) {
788
+ await saveContinuationConversation(record.id, copy);
789
+ if (!body.includes(CONVERSATION_MARKER))
790
+ body += `\n\n${CONVERSATION_MARKER}. Read more history from the conversation file supplied beside this brief as needed; inspect the checkout before continuing.`;
791
+ }
792
+ else
793
+ body += "\n\nSaved history: conversation.md, beside this hand-off file. Read more history from this file as needed, including the original request and earlier decisions. Inspect the checkout before continuing; preserve the owner's uncommitted changes.";
794
+ }
766
795
  const document = handoffDocument(record, body, observed, at, !!conductor);
767
796
  await this.assertNotAborted(record);
768
797
  const file = handoffPath(record.id);
769
798
  const prompt = briefText(continuePrompt(document, file));
770
799
  // The folder is the new agent's brief folder; the hand-off is written into it, whole.
771
800
  await writeLaunchBrief({ id: record.id, text: prompt }, this.now, record.from.label);
801
+ if (savedHistory !== undefined)
802
+ await atomic(path.join(path.dirname(file), "conversation.md"), savedHistory);
772
803
  await atomic(file, document);
773
804
  await this.update(record, { state: record.mode === "new-chat" ? "launching" : "exiting", handoff: { path: file, source: "text" in written ? "agent" : "fallback",
774
805
  ...("reason" in written ? { reason: written.reason.slice(0, 300) } : {}), chars: document.length } });
@@ -1120,7 +1151,7 @@ export class SessionMover {
1120
1151
  return `The conductor hand-over ${outcome}, but the new chat's notice could not be delivered: ${error instanceof Error ? error.message : String(error)}`.slice(0, 500);
1121
1152
  }
1122
1153
  }
1123
- /** The agent's own hand-off, or why there is none. Fails only when the session itself went away. */
1154
+ /** The agent's optional hand-off, or why there is none; run also catches lifecycle failures. */
1124
1155
  async askForHandoff(record, handoffMs) {
1125
1156
  const from = record.from.target;
1126
1157
  const deadline = this.now + handoffMs;
@@ -1147,7 +1178,7 @@ export class SessionMover {
1147
1178
  aborted();
1148
1179
  const pane = findPane(await this.deps.snapshot(from.server), placeOf(from));
1149
1180
  if (!pane || pane.agent !== from.source)
1150
- throw new BridgeError(409, "The session ended before it wrote its hand-off; nothing was started.");
1181
+ throw new BridgeError(409, "The session ended before it wrote its hand-off.");
1151
1182
  const lines = await this.deps.transcript(from).catch(() => []);
1152
1183
  const text = extractHandoff(repliesAfterRequest(conversationEntries(lines, from.source), record.id), record.id);
1153
1184
  if (!text)
@@ -84,6 +84,8 @@ export declare class LatestFrame {
84
84
  offer(frame: Buffer): void;
85
85
  /** The phone has a frame; an acknowledgement it owes nothing for is ignored. */
86
86
  ack(): void;
87
+ /** Discard a previous page's queued frame without forgiving its outstanding acknowledgements. */
88
+ discardWaiting(): void;
87
89
  close(): void;
88
90
  private get bytesPerSecond();
89
91
  private pump;