@phren/cli 0.3.30 → 0.3.32

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 (81) hide show
  1. package/dist/bridge/agent-hooks.d.ts +5 -55
  2. package/dist/bridge/agent-hooks.js +45 -162
  3. package/dist/bridge/approval-rules.d.ts +70 -0
  4. package/dist/bridge/approval-rules.js +231 -0
  5. package/dist/bridge/authority.d.ts +1 -2
  6. package/dist/bridge/authority.js +2 -7
  7. package/dist/bridge/changes.d.ts +4 -0
  8. package/dist/bridge/changes.js +47 -33
  9. package/dist/bridge/claude-suggestion.js +1 -1
  10. package/dist/bridge/codex-servers.d.ts +12 -0
  11. package/dist/bridge/codex-servers.js +35 -3
  12. package/dist/bridge/codex-thread-origin.d.ts +12 -0
  13. package/dist/bridge/codex-thread-origin.js +31 -0
  14. package/dist/bridge/dispatch.js +1 -1
  15. package/dist/bridge/enroll.d.ts +6 -0
  16. package/dist/bridge/enroll.js +10 -4
  17. package/dist/bridge/git-worktrees.js +14 -17
  18. package/dist/bridge/git.d.ts +10 -2
  19. package/dist/bridge/git.js +148 -107
  20. package/dist/bridge/hand-off-queue.d.ts +10 -0
  21. package/dist/bridge/hand-off-queue.js +33 -10
  22. package/dist/bridge/health.js +9 -5
  23. package/dist/bridge/herdr.js +6 -1
  24. package/dist/bridge/hook-main.js +12 -2
  25. package/dist/bridge/locate.js +14 -1
  26. package/dist/bridge/projects.d.ts +8 -0
  27. package/dist/bridge/projects.js +142 -24
  28. package/dist/bridge/prompt-deliveries.d.ts +99 -0
  29. package/dist/bridge/prompt-deliveries.js +327 -0
  30. package/dist/bridge/prompt-once.d.ts +2 -0
  31. package/dist/bridge/prompt-once.js +2 -0
  32. package/dist/bridge/schedule-format.d.ts +10 -0
  33. package/dist/bridge/schedule-format.js +24 -1
  34. package/dist/bridge/schedules.d.ts +3 -1
  35. package/dist/bridge/schedules.js +96 -40
  36. package/dist/bridge/server-launch.js +39 -15
  37. package/dist/bridge/server-pane-routes.js +91 -45
  38. package/dist/bridge/server-routes.d.ts +3 -0
  39. package/dist/bridge/server-routes.js +36 -8
  40. package/dist/bridge/server-stream.js +4 -2
  41. package/dist/bridge/server.js +12 -3
  42. package/dist/bridge/speech-key.d.ts +2 -9
  43. package/dist/bridge/speech-key.js +4 -37
  44. package/dist/bridge/sudo.d.ts +1 -1
  45. package/dist/bridge/sudo.js +51 -17
  46. package/dist/bridge/terminal-tmux.js +22 -4
  47. package/dist/bridge/tmux-test-server.d.ts +13 -0
  48. package/dist/bridge/tmux-test-server.js +103 -0
  49. package/dist/bridge/transcript-claude.d.ts +3 -3
  50. package/dist/bridge/transcript-claude.js +7 -7
  51. package/dist/bridge/transcript-codex.js +6 -4
  52. package/dist/bridge/transcript-preview.js +1 -1
  53. package/dist/bridge/transcripts.js +14 -3
  54. package/dist/bridge-hook.mjs +16011 -14121
  55. package/dist/cli/schedules.js +8 -2
  56. package/dist/cli/session-stop.js +9 -1
  57. package/dist/cli-registry.js +1 -1
  58. package/dist/core/project-registry.d.ts +1 -0
  59. package/dist/core/project-registry.js +6 -2
  60. package/dist/core/project.d.ts +1 -0
  61. package/dist/core/project.js +5 -0
  62. package/dist/generated/memory-ui-graph.browser.js +328 -333
  63. package/dist/init/setup.js +2 -2
  64. package/dist/memory-ui-graph.runtime.js +328 -333
  65. package/dist/modules/registry.js +9 -7
  66. package/dist/phren-core.js +1 -1
  67. package/dist/phren-paths.d.ts +2 -2
  68. package/dist/phren-paths.js +2 -2
  69. package/dist/store-routing.d.ts +2 -2
  70. package/dist/store-routing.js +2 -2
  71. package/dist/sync/git-state.d.ts +13 -0
  72. package/dist/sync/git-state.js +22 -0
  73. package/dist/sync/store-merge.d.ts +2 -0
  74. package/dist/sync/store-merge.js +6 -1
  75. package/dist/test-global-setup.js +7 -0
  76. package/dist/tools/data.js +1 -1
  77. package/dist/tools/finding.js +1 -1
  78. package/dist/tools/search.js +1 -1
  79. package/dist/tools/tasks.js +1 -1
  80. package/package.json +8 -8
  81. package/starter/global/skills/conductor/SKILL.md +2 -2
@@ -1,10 +1,11 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { stat } from "node:fs/promises";
2
3
  import { hostname } from "node:os";
3
4
  import path from "node:path";
4
5
  import { BridgeError } from "./protocol.js";
5
6
  import { getProjectSourcePath } from "../project-config.js";
6
7
  import { getProjectDirs } from "../shared.js";
7
- import { computerMatches, nextRun, readScheduleDocument, readScheduleRuns, runningStatuses, scheduleNotifications, scheduleSessionRoute, writeScheduleDocument, writeScheduleRuns, } from "./schedule-format.js";
8
+ import { computerMatches, latestScheduleBatch, nextRun, readScheduleDocument, readScheduleRuns, runningStatuses, scheduleNotifications, scheduleSessionRoute, writeScheduleDocument, writeScheduleRuns, } from "./schedule-format.js";
8
9
  export * from "./schedule-format.js";
9
10
  export * from "./schedule-launch.js";
10
11
  export * from "./schedule-watch.js";
@@ -19,6 +20,7 @@ export class Scheduler {
19
20
  log;
20
21
  serial = Promise.resolve();
21
22
  ticking = false;
23
+ dispatching = new Set();
22
24
  /** Runs this process launched; any other open run was left by an earlier Hook. */
23
25
  own = new Set();
24
26
  recovered = false;
@@ -70,11 +72,13 @@ export class Scheduler {
70
72
  }
71
73
  const project = path.basename(directory);
72
74
  for (const schedule of schedules) {
73
- const matching = runs.filter(run => run.project === project && run.scheduleId === schedule.id);
74
- const last = matching.at(-1), running = matching.some(run => runningStatuses.has(run.status));
75
+ const matching = runs.filter(run => (run.scheduleProject ?? run.project) === project && run.scheduleId === schedule.id);
76
+ const { lastRun: last, lastRuns } = latestScheduleBatch(matching);
77
+ const running = matching.some(run => runningStatuses.has(run.status));
75
78
  const due = computerMatches(schedule.computer, computer) ? nextRun(schedule, last) : null;
76
- result.push({ ...schedule, project, nextRun: due?.toISOString() ?? null,
79
+ result.push({ ...schedule, project, lastRuns, nextRun: due?.toISOString() ?? null,
77
80
  lastRun: last ? { startedAt: last.startedAt, ...(last.finishedAt ? { finishedAt: last.finishedAt } : {}), status: last.status,
81
+ ...(last.batchId ? { batchId: last.batchId, scheduleProject: last.scheduleProject } : {}),
78
82
  ...(last.reason ? { reason: last.reason } : {}),
79
83
  ...(last.blockedStartupPrompt ? { blockedStartupPrompt: last.blockedStartupPrompt } : {}),
80
84
  ...(last.blockNotified !== undefined ? { blockNotified: last.blockNotified } : {}), launch: last.launch } : null, running });
@@ -84,52 +88,99 @@ export class Scheduler {
84
88
  }
85
89
  async history(filters = {}) {
86
90
  const limit = Math.min(500, Math.max(1, filters.limit ?? 50));
87
- return (await readScheduleRuns(this.runsFile)).filter(run => (!filters.project || run.project.toLowerCase() === filters.project.toLowerCase())
91
+ return (await readScheduleRuns(this.runsFile)).filter(run => (!filters.project || (run.scheduleProject ?? run.project).toLowerCase() === filters.project.toLowerCase())
88
92
  && (!filters.id || run.scheduleId === filters.id)).slice(-limit).reverse();
89
93
  }
90
- async launchNow(projectName, id) {
94
+ async launchNow(projectName, id, onlyIfDue = false, expectedUpdatedAt) {
95
+ const key = `${projectName.toLowerCase()}/${id}`;
96
+ if (this.dispatching.has(key))
97
+ throw new BridgeError(409, "This schedule is already launching.");
98
+ this.dispatching.add(key);
99
+ try {
100
+ return await this.prepareAndLaunch(projectName, id, onlyIfDue, expectedUpdatedAt);
101
+ }
102
+ finally {
103
+ this.dispatching.delete(key);
104
+ }
105
+ }
106
+ async prepareAndLaunch(projectName, id, onlyIfDue, expectedUpdatedAt) {
91
107
  const prepared = await this.exclusive(async () => {
92
108
  const projectDir = this.projectDirectory(projectName), project = path.basename(projectDir);
93
109
  const file = await readScheduleDocument(projectDir), schedule = file.schedules.find(item => item.id === id);
94
110
  if (!schedule)
95
111
  throw new BridgeError(404, `Schedule "${id}" was not found in ${project}.`);
112
+ if (expectedUpdatedAt !== undefined && Date.parse(expectedUpdatedAt) !== Date.parse(schedule.updatedAt)) {
113
+ throw new BridgeError(409, "This computer has a different schedule revision. Wait for store sync to finish, refresh the schedule, and try Run now again.");
114
+ }
96
115
  if (!computerMatches(schedule.computer, this.computer()))
97
116
  throw new BridgeError(409, `${schedule.computer} owns this schedule; run it from that computer.`);
98
117
  const runs = await readScheduleRuns(this.runsFile);
99
- if (runs.some(run => run.project === project && run.scheduleId === id && runningStatuses.has(run.status))) {
118
+ const matching = runs.filter(run => (run.scheduleProject ?? run.project) === project && run.scheduleId === id);
119
+ if (matching.some(run => runningStatuses.has(run.status))) {
100
120
  throw new BridgeError(409, `Schedule "${schedule.name}" is already running.`);
101
121
  }
102
- const run = { id: randomUUID(), scheduleId: id, project, startedAt: this.now().toISOString(), status: "launched", launch: { mode: "headless" } };
103
- this.own.add(run.id);
104
- await writeScheduleRuns(this.runsFile, [...runs, run]);
122
+ // Recheck a tick's snapshot after a concurrent Run now or schedule edit.
123
+ const due = nextRun(schedule, matching.at(-1));
124
+ if (onlyIfDue && (!schedule.enabled || !due || due > this.now()))
125
+ return undefined;
126
+ const targets = [];
127
+ for (const name of schedule.projects ?? [project]) {
128
+ const targetDir = this.projectDirectory(name), target = path.basename(targetDir);
129
+ const source = getProjectSourcePath(this.store, target) ?? await this.locateProject(target);
130
+ if (!source && schedule.projects)
131
+ throw new BridgeError(409, `No source directory for project "${target}" on this computer.`);
132
+ const cwd = source ?? targetDir;
133
+ if (!await stat(cwd).then(info => info.isDirectory()).catch(() => false)) {
134
+ throw new BridgeError(409, `Source directory for project "${target}" is unavailable: ${cwd}`);
135
+ }
136
+ targets.push({ project: target, projectDir: targetDir, cwd });
137
+ }
138
+ const batchId = randomUUID(), startedAt = this.now().toISOString();
139
+ const children = targets.map(target => ({ ...target, run: {
140
+ id: randomUUID(), scheduleId: id, project: target.project, scheduleProject: project, batchId,
141
+ startedAt, status: "launched", launch: { mode: "headless" },
142
+ } }));
143
+ // One atomic replacement reserves every target before any external launch.
144
+ await writeScheduleRuns(this.runsFile, [...runs, ...children.map(child => child.run)]);
145
+ for (const child of children)
146
+ this.own.add(child.run.id);
105
147
  if (schedule.every === "once" && schedule.enabled) {
106
- const updatedAt = this.now().toISOString();
107
- const schedules = file.schedules.map(item => item.id === id ? { ...item, enabled: false, updatedAt } : item);
108
- await writeScheduleDocument(projectDir, schedules, file.document);
148
+ const schedules = file.schedules.map(item => item.id === id ? { ...item, enabled: false, updatedAt: startedAt } : item);
149
+ try {
150
+ await writeScheduleDocument(projectDir, schedules, file.document);
151
+ }
152
+ catch (error) {
153
+ // The durable batch already consumes the occurrence. A YAML write
154
+ // failure must not strand pending children in this running process.
155
+ this.log(`[schedule] Could not disable consumed once schedule ${project}/${id}: ${String(error)}`);
156
+ }
109
157
  }
110
- const source = getProjectSourcePath(this.store, project);
111
- return { projectDir, project, schedule, run, cwd: source ?? await this.locateProject(project) ?? projectDir };
158
+ return { schedule, children };
112
159
  });
113
- try {
114
- const launched = await this.launch({ schedule: prepared.schedule, project: prepared.project, projectDir: prepared.projectDir,
115
- cwd: prepared.cwd, runId: prepared.run.id,
116
- blockedStartup: promptText => this.recordBlockedStartup(prepared.run.id, prepared.schedule, promptText) });
117
- const running = await this.updateRun(prepared.run.id, { status: "running", launch: launched.launch });
118
- const notified = this.notifyRun(running, prepared.schedule, "scheduleStarted");
119
- if (launched.completion)
120
- void launched.completion.then(async (result) => {
121
- await this.finishRun(prepared.run.id, prepared.schedule, result.status, result.reason, notified);
122
- }).catch(async (error) => {
123
- await this.finishRun(prepared.run.id, prepared.schedule, "failed", error instanceof Error ? error.message : "The scheduled agent failed.", notified);
124
- }).catch(error => this.log(`[schedule] Could not finish run ${prepared.run.id}: ${String(error)}`));
125
- await notified;
126
- return running;
127
- }
128
- catch (error) {
129
- const reason = error instanceof Error ? error.message : "The scheduled agent could not start.";
130
- await this.finishRun(prepared.run.id, prepared.schedule, "failed", reason);
131
- throw error instanceof BridgeError ? error : new BridgeError(503, reason);
132
- }
160
+ if (!prepared)
161
+ return [];
162
+ // Independent attempts: one target's startup failure never cancels siblings.
163
+ return Promise.all(prepared.children.map(async (child) => {
164
+ try {
165
+ const launched = await this.launch({ schedule: prepared.schedule, project: child.project, projectDir: child.projectDir,
166
+ cwd: child.cwd, runId: child.run.id,
167
+ blockedStartup: promptText => this.recordBlockedStartup(child.run.id, prepared.schedule, promptText) });
168
+ const running = await this.updateRun(child.run.id, { status: "running", launch: launched.launch });
169
+ const notified = this.notifyRun(running, prepared.schedule, "scheduleStarted");
170
+ if (launched.completion)
171
+ void launched.completion.then(async (result) => {
172
+ await this.finishRun(child.run.id, prepared.schedule, result.status, result.reason, notified);
173
+ }).catch(async (error) => {
174
+ await this.finishRun(child.run.id, prepared.schedule, "failed", error instanceof Error ? error.message : "The scheduled agent failed.", notified);
175
+ }).catch(error => this.log(`[schedule] Could not finish run ${child.run.id}: ${String(error)}`));
176
+ await notified;
177
+ return running;
178
+ }
179
+ catch (error) {
180
+ const reason = error instanceof Error ? error.message : "The scheduled agent could not start.";
181
+ return this.finishRun(child.run.id, prepared.schedule, "failed", reason);
182
+ }
183
+ }));
133
184
  }
134
185
  async updateRun(id, patch) {
135
186
  return this.exclusive(async () => {
@@ -145,8 +196,9 @@ export class Scheduler {
145
196
  const run = await this.updateRun(id, { status, finishedAt: this.now().toISOString(), ...(reason ? { reason } : {}) });
146
197
  await previousNotification;
147
198
  if (run.blockedStartupPrompt && run.blockNotified)
148
- return;
199
+ return run;
149
200
  await this.notifyRun(run, schedule, status === "failed" ? "scheduleFailed" : "scheduleFinished");
201
+ return run;
150
202
  }
151
203
  async recordBlockedStartup(id, schedule, promptText) {
152
204
  try {
@@ -199,12 +251,16 @@ export class Scheduler {
199
251
  if (this.recovered || !resume)
200
252
  return;
201
253
  this.recovered = true;
202
- const open = (await readScheduleRuns(this.runsFile)).filter(run => runningStatuses.has(run.status) && !this.own.has(run.id));
254
+ const open = await this.exclusive(async () => {
255
+ const pending = (await readScheduleRuns(this.runsFile)).filter(run => runningStatuses.has(run.status) && !this.own.has(run.id));
256
+ for (const run of pending)
257
+ this.own.add(run.id);
258
+ return pending;
259
+ });
203
260
  for (const run of open) {
204
- this.own.add(run.id);
205
261
  let schedule;
206
262
  try {
207
- schedule = (await readScheduleDocument(this.projectDirectory(run.project))).schedules.find(item => item.id === run.scheduleId);
263
+ schedule = (await readScheduleDocument(this.projectDirectory(run.scheduleProject ?? run.project))).schedules.find(item => item.id === run.scheduleId);
208
264
  }
209
265
  catch {
210
266
  schedule = undefined;
@@ -234,7 +290,7 @@ export class Scheduler {
234
290
  for (const schedule of status.schedules) {
235
291
  if (!schedule.enabled || schedule.running || !schedule.nextRun || new Date(schedule.nextRun) > now)
236
292
  continue;
237
- await this.launchNow(schedule.project, schedule.id).catch(() => { });
293
+ await this.launchNow(schedule.project, schedule.id, true).catch(() => { });
238
294
  }
239
295
  }
240
296
  finally {
@@ -1,9 +1,10 @@
1
1
  import { markPaneClosed } from "./worker-close.js";
2
- import { mkdir, readFile } from "node:fs/promises";
2
+ import { mkdir, mkdtemp, readFile, realpath, rmdir } from "node:fs/promises";
3
3
  import { phrenStoreRoot } from "./transcripts.js";
4
4
  import path from "node:path";
5
5
  import { z } from "zod";
6
6
  import { homeDir } from "../home-paths.js";
7
+ import { defaultPhrenPath } from "../phren-paths.js";
7
8
  import { agentNames, findPane, isConductorName, paneChatState, paneIdentity, servers, snapshot } from "./herdr.js";
8
9
  import { agentNotReady, terminalKind, terminalName, terminalProvider } from "./terminal.js";
9
10
  import { tmuxScroll } from "./terminal-tmux.js";
@@ -43,7 +44,7 @@ function effortArgs(kind, effort) {
43
44
  return ["--reasoning-effort", effort];
44
45
  // phren-agent takes low to xhigh, and max as xhigh.
45
46
  if (kind === "phren")
46
- return ["--reasoning", effort === "minimal" ? "low" : effort];
47
+ return ["--reasoning", effort];
47
48
  return [];
48
49
  }
49
50
  /** phren's own agent runs as `phren agent`: the subcommand and its interactive TUI lead its arguments. */
@@ -105,7 +106,7 @@ export async function sessionUsedTools(session, store = phrenStoreRoot()) {
105
106
  * `--model` itself; the rest name their provider with `--provider`. Any other
106
107
  * model (an OpenRouter id typed by hand) passes through as it is. */
107
108
  export function phrenModelArgs(model) {
108
- const match = /^(anthropic|deepseek|ollama|openrouter)\/(.+)$/.exec(model);
109
+ const match = /^(anthropic|deepseek|ollama|openrouter|openai-compat)\/(.+)$/.exec(model);
109
110
  return match ? ["--provider", match[1], "--model", match[2]] : ["--model", model];
110
111
  }
111
112
  async function prepareConductor(kind, effort, model) {
@@ -126,6 +127,8 @@ async function prepareConductor(kind, effort, model) {
126
127
  await atomic(file, definition, 0o644);
127
128
  return [...(model ? ["--model", model] : []), "--agent", "conductor", "--variant", effort];
128
129
  }
130
+ if (kind === "phren")
131
+ return [...PHREN_AGENT_ARGS, ...(model ? phrenModelArgs(model) : []), "--append-system-prompt-file", briefFile, ...effortArgs(kind, effort)];
129
132
  throw new BridgeError(400, "The selected harness cannot run as a conductor.");
130
133
  }
131
134
  async function targetForPane(server, pane) {
@@ -178,7 +181,6 @@ async function requireNoConductor(server, before, except) {
178
181
  }
179
182
  /** The phone names the pane's workspace and tab too; the CLI may know only the pane. */
180
183
  const paneRequest = z.object({ workspaceId: id.optional(), tabId: id.optional(), paneId: id }).strict();
181
- const PHREN_NO_CONDUCTOR = "phren agent cannot run as a conductor: it takes no system brief at startup.";
182
184
  /** "Make conductor": the owner gives an agent already running in a pane on this computer the role. */
183
185
  export async function makeConductor(server, data) {
184
186
  const place = paneRequest.parse(data);
@@ -191,8 +193,6 @@ export async function makeConductor(server, data) {
191
193
  throw new BridgeError(409, "No agent is running in this pane.");
192
194
  if (pane.agent === "copilot")
193
195
  throw new BridgeError(400, "Copilot cannot run as a conductor.");
194
- if (pane.agent === "phren")
195
- throw new BridgeError(400, PHREN_NO_CONDUCTOR);
196
196
  const unchecked = await requireNoConductor(server, before, place.paneId);
197
197
  const target = await targetForPane(server, pane);
198
198
  await recordConductor(server, pane, "owner", typeof target?.session === "string" ? target.session : undefined);
@@ -218,7 +218,7 @@ const SHELL_READY_MS = intervalFromEnv("PHREN_SHELL_READY_MS", 15_000);
218
218
  /** Herdr starts an agent only at an interactive shell prompt and refuses
219
219
  * with `agent_pane_busy` ("is not an available shell") before that. A pane
220
220
  * created a moment ago is busy only while its login shell starts, which a
221
- * loaded computer can stretch to seconds (three Linuxbox dispatches failed
221
+ * loaded computer can stretch to seconds (three Devbox dispatches failed
222
222
  * this way on 2026-09-27; the same pane took the agent by hand a minute
223
223
  * later). Nothing is typed on a refusal, so retry until the shell is up. */
224
224
  async function startWhenShellReady(server, pane, agent) {
@@ -316,7 +316,12 @@ async function stillListed(server, result) {
316
316
  }
317
317
  async function startSession(server, data, options) {
318
318
  const role = z.enum(["agent", "conductor"]).default("agent").parse(data.role);
319
- const projectDirectory = z.string().min(1).max(4096).refine(t => path.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
319
+ const agentFolder = z.boolean().default(false).parse(data.agentFolder);
320
+ if (agentFolder && (role !== "agent" || data.project !== undefined || (data.cwd !== undefined && data.cwd !== "") || data.worktree != null)) {
321
+ throw new BridgeError(400, "An agent folder is for a projectless agent without cwd or worktree.");
322
+ }
323
+ const projectDirectory = agentFolder ? undefined
324
+ : z.string().min(1).max(4096).refine(t => path.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
320
325
  const worktreeRequest = data.worktree === undefined || data.worktree === null ? undefined : launchWorktreeSchema.parse(data.worktree);
321
326
  if (worktreeRequest && role === "conductor")
322
327
  throw new BridgeError(400, "A conductor works across projects, so it cannot start in a worktree.");
@@ -333,8 +338,8 @@ async function startSession(server, data, options) {
333
338
  throw new BridgeError(400, "phren agent takes its permissions from its own settings; permissionMode is for Claude, Codex and Copilot workers.");
334
339
  if (role === "conductor" && kind === "copilot")
335
340
  throw new BridgeError(400, "Copilot cannot run as a conductor.");
336
- if (role === "conductor" && kind === "phren")
337
- throw new BridgeError(400, PHREN_NO_CONDUCTOR);
341
+ if (role === "conductor" && data.mode === "chat")
342
+ throw new BridgeError(400, "A conductor needs agent mode with tools.");
338
343
  const phrenArgs = await phrenLaunchArgs(kind, data);
339
344
  // A dispatched worker's or scheduled run's first prompt. It rides on the
340
345
  // launch where the harness takes one; elsewhere the caller types it.
@@ -375,7 +380,7 @@ async function startSession(server, data, options) {
375
380
  const conductorHere = role === "agent" && workspace ? await conductorPane(server, before) : undefined;
376
381
  if (conductorHere && conductorHere.workspace_id === workspace)
377
382
  workspace = undefined;
378
- const args = role === "conductor" ? await prepareConductor(kind, effort, model)
383
+ const args = role === "conductor" ? [...await prepareConductor(kind, effort, model), ...(kind === "phren" ? phrenArgs : [])]
379
384
  : [...(kind === "phren" ? [...PHREN_AGENT_ARGS, ...phrenArgs] : []), ...(model && kind === "phren" ? phrenModelArgs(model) : model && modelFlag[kind] ? [modelFlag[kind], model] : []), ...(data.effort === undefined ? [] : effortArgs(kind, effort)),
380
385
  ...(permissionMode && kind === "claude" ? ["--permission-mode", CLAUDE_NAMES[permissionMode]] : []), ...(permissionMode && kind === "codex" ? codexModeFlags(permissionMode) : []), ...(permissionMode && kind === "copilot" ? copilotModeFlags(permissionMode) : [])];
381
386
  // A Codex worker runs on a Phren-owned app-server (codex-servers.ts): the
@@ -401,16 +406,35 @@ async function startSession(server, data, options) {
401
406
  // Created last, once nothing else can refuse the launch, so a refusal
402
407
  // never leaves a worktree or branch behind.
403
408
  const worktree = worktreeRequest ? await createLaunchWorktree(projectDirectory, worktreeRequest) : undefined;
404
- const cwd = worktree?.cwd ?? projectDirectory;
409
+ // The same root as the conductor, chosen by this computer's PHREN_PATH.
410
+ // mkdtemp keeps simultaneous chats with the same title isolated.
411
+ let scratch;
412
+ if (agentFolder) {
413
+ const store = await realpath(defaultPhrenPath());
414
+ // Runtime folders are excluded from project discovery and store sync.
415
+ const runtime = path.join(store, ".runtime");
416
+ await mkdir(runtime, { recursive: true, mode: 0o700 });
417
+ if (await realpath(runtime) !== runtime)
418
+ throw new BridgeError(403, "The runtime folder must be inside the Phren directory.");
419
+ const agents = path.join(runtime, "agents");
420
+ await mkdir(agents, { recursive: true, mode: 0o700 });
421
+ // A pre-existing symlink must not redirect the new folder outside the store.
422
+ if (await realpath(agents) !== agents)
423
+ throw new BridgeError(403, "The agents folder must be inside the Phren directory.");
424
+ scratch = await mkdtemp(path.join(agents, `${new Date().toISOString().slice(0, 10)}-${herdrAgentName(label)}-`));
425
+ }
426
+ const cwd = scratch ?? worktree?.cwd ?? projectDirectory;
405
427
  // Claude's folder-trust screen defaults to "No, exit" and Codex's holds the
406
428
  // agent too; a folder the Hook picked or just created is trusted up front.
407
- if (worktree || options.trustFolder)
408
- await pretrustFolder(kind, cwd, worktree ? `new worktree for ${worktree.branch}` : "project folder", home ? { ...process.env, ...claudeLaunchEnv(home) } : process.env);
429
+ if (scratch || worktree || options.trustFolder)
430
+ await pretrustFolder(kind, cwd, scratch ? "new agent folder" : worktree ? `new worktree for ${worktree.branch}` : "project folder", home ? { ...process.env, ...claudeLaunchEnv(home) } : process.env);
409
431
  try {
410
432
  await terminalProvider().create(server, { workspace, label, cwd, ...(env ? { env } : {}) });
411
433
  }
412
434
  catch (error) {
413
435
  await worktree?.discard();
436
+ if (scratch)
437
+ await rmdir(scratch).catch(() => undefined);
414
438
  throw error;
415
439
  }
416
440
  let created;
@@ -512,7 +536,7 @@ async function startSession(server, data, options) {
512
536
  await new JobRegistry().register({ pane: { server, pane: created.paneId, ...(created.workspaceId ? { workspace: created.workspaceId } : {}), agent: kind, label },
513
537
  ...(sessionId ? { session: sessionId } : {}), agent: kind, label, command: kind }).catch(() => undefined);
514
538
  }
515
- return { ok: true, ...created, agent: kind, agentStatus, role, sessionId, target, ...(account ? { account } : {}), ...(permissionMode ? { permissionMode } : {}), ...(unchecked.length ? { unchecked } : {}),
539
+ return { ok: true, ...created, cwd, agent: kind, agentStatus, role, sessionId, target, ...(account ? { account } : {}), ...(permissionMode ? { permissionMode } : {}), ...(unchecked.length ? { unchecked } : {}),
516
540
  // The caller types the brief itself unless it went with the launch.
517
541
  ...(brief ? { briefLaunched: appServer ? briefTurn !== undefined : !!briefLaunch || !!servedBrief,
518
542
  briefState: appServer ? briefTurn ?? "unconfirmed" : served ? (servedBrief?.delivered ? "sent" : "uncertain") : briefLaunch ? "sent" : "unconfirmed" } : {}),
@@ -12,7 +12,7 @@ import { CodexServerUnavailable, codexServers } from "./codex-servers.js";
12
12
  import { refuseWorkingSlash } from "./model-switch.js";
13
13
  import { PERMISSION_MODE_VALUES, refuseAgentOrigin } from "./permission-mode.js";
14
14
  import { sessionWebServers } from "./session-servers.js";
15
- import { repositoryDiff } from "./projects.js";
15
+ import { gitRoot, repositoryDiff, withGitReadDeadline } from "./projects.js";
16
16
  import { BridgeError, MAX_FRAME, object, objects, startingTargetSchema, targetSchema } from "./protocol.js";
17
17
  import { childAgent, childAgentTree, conversationNamedPaths, targetTranscriptPath } from "./transcripts.js";
18
18
  import { sideQuestionText } from "./side-questions.js";
@@ -42,7 +42,9 @@ export async function gitRepository(pane, target, child, worktree) {
42
42
  const relation = childAgent(await childAgentTree(target.source, target.session), id);
43
43
  if (!relation)
44
44
  throw new BridgeError(404, "That agent is not part of this conversation.");
45
- return relation.cwd ?? await trustedDirectory(pane);
45
+ if (!relation.cwd)
46
+ throw new BridgeError(409, "This agent has no recorded checkout. Its parent repository cannot be substituted.");
47
+ return trustedDirectory({ cwd: relation.cwd });
46
48
  }
47
49
  return trustedDirectory(pane);
48
50
  }
@@ -126,7 +128,7 @@ async function resubmitIfIdle(agentHooks, target, text) {
126
128
  } };
127
129
  if (await status() === "working")
128
130
  return "pending";
129
- const late = agentHooks.awaitLateDelivery(target, text);
131
+ const late = agentHooks.deliveries.awaitLate(target, text);
130
132
  await terminalProvider().sendKeys(target.server, target.pane, ["enter"]);
131
133
  const outcome = await late;
132
134
  if (outcome !== "pending")
@@ -143,7 +145,7 @@ export function followQueuedDelivery(agentHooks, target, terminal, text, interva
143
145
  const started = Date.now();
144
146
  let finishedLooks = 0;
145
147
  const look = async () => {
146
- if (!agentHooks.deliveryPending(target, text) || Date.now() - started > 600_000)
148
+ if (!agentHooks.deliveries.pending(target, text) || Date.now() - started > 600_000)
147
149
  return;
148
150
  let pane;
149
151
  try {
@@ -247,13 +249,38 @@ async function servedPrompt(target, session, text, typing) {
247
249
  return undefined;
248
250
  return sent.delivered ? { ok: true, delivered: true } : { ok: true, deliveryUncertain: true };
249
251
  }
252
+ /** A known message's reply by its id: `state` plus the legacy flags. */
253
+ function deliveryReply(agentHooks, id, target, text) {
254
+ const parsed = targetSchema.safeParse(target);
255
+ if (!parsed.success)
256
+ return undefined;
257
+ if (!agentHooks.deliveries.sameMessage(id, parsed.data, text))
258
+ throw new BridgeError(409, "This message id was already used for a different message.");
259
+ const status = agentHooks.deliveries.status(id, parsed.data);
260
+ if (status.state === "unknown")
261
+ return undefined;
262
+ return { ok: status.state !== "failed", state: status.state, ...(status.state === "delivered" ? { delivered: true } : {}),
263
+ ...(status.state === "queued" ? { queued: true } : {}), ...(status.reason ? { reason: status.reason } : {}) };
264
+ }
250
265
  export async function paneRoute(ctx, url, data, response) {
266
+ if (["/v1/diff", "/v1/git/status", "/v1/git/worktrees"].includes(url.pathname)) {
267
+ return withGitReadDeadline(() => paneRouteOnce(ctx, url, data, response, () => { }));
268
+ }
251
269
  if (url.pathname !== "/v1/prompt")
252
270
  return paneRouteOnce(ctx, url, data, response, () => { });
253
271
  // A retried send carries its first attempt's id; the Hook answers it with
254
272
  // that attempt's reply instead of typing the message a second time.
255
273
  const id = deliveryIdSchema.parse(data.deliveryId);
256
- return promptOnce.run(id, promptScope(object(data.target), String(data.text ?? "")), async (typing) => object(await paneRouteOnce(ctx, url, data, response, typing)));
274
+ const scope = promptScope(object(data.target), String(data.text ?? ""));
275
+ // The Hook keeps each message's state by its id (prompt-deliveries.ts), so
276
+ // a retry, even after a Hook restart, answers with where the message is
277
+ // now. Only a failed one is typed again, under the same id.
278
+ const known = id ? deliveryReply(ctx.agentHooks, id, object(data.target), String(data.text ?? "")) : undefined;
279
+ if (known && known.state !== "failed")
280
+ return { ...known, replayed: true };
281
+ if (known)
282
+ promptOnce.forget(id);
283
+ return promptOnce.run(id, scope, async (typing) => object(await paneRouteOnce(ctx, url, data, response, typing)));
257
284
  }
258
285
  export async function paneRouteOnce(ctx, url, data, response, typing) {
259
286
  const { agentHooks, modelSwitcher, settingsSwitcher, permissionModeSwitcher, codexQuestions, sideQuestions } = ctx;
@@ -358,6 +385,8 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
358
385
  }
359
386
  const text = typeof data.text === "string" && data.text && data.text.length <= 32768 && !/[\x00-\x08\x0b-\x1f\x7f]/.test(data.text) ? data.text : undefined;
360
387
  const served = text === undefined ? undefined : await servedPrompt(target, target.session, text, typing);
388
+ if (served?.delivered && text)
389
+ agentHooks.deliveries.delivered(deliveryIdSchema.parse(data.deliveryId), target, text);
361
390
  if (served)
362
391
  return served;
363
392
  }
@@ -381,30 +410,48 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
381
410
  }
382
411
  if (target.source === "codex" && /^\s*\/model\s+\S/i.test(text))
383
412
  throw new BridgeError(422, "Use the model picker to switch Codex models.");
384
- // A Codex pane on the Hook's own app-server takes the prompt as a turn on
385
- // its thread, acknowledged with the turn id; nothing is typed. A slash
413
+ // A Codex pane on the Hook's own app-server takes the prompt on its
414
+ // thread, as the TUI takes Enter: steered into a running turn, else a new
415
+ // turn; nothing is typed. The turn id only says Codex has it: the model
416
+ // reads it at its next step, possibly after a long tool call, and Codex's
417
+ // UserPromptSubmit says when. Until then it is queued, like typed text. A slash
386
418
  // command is the TUI's own and is still typed. An unreachable server
387
419
  // sent nothing, so the pane is typed into instead; a request that may
388
420
  // have reached it is reported uncertain and never retried.
389
421
  const owned = text.trim().startsWith("/") ? undefined : codexServers.forTarget(target);
390
422
  if (owned) {
391
423
  await typing();
424
+ const id = deliveryIdSchema.parse(data.deliveryId), refused = new AbortController();
425
+ // An idle thread starts the turn and confirms in about two seconds; a
426
+ // running one takes the text only after its current step.
427
+ const taken = agentHooks.deliveries.expect(target, text, owned.activeTurn ? 300 : 4_000, refused.signal, id, typeof pane.terminal_id === "string" ? pane.terminal_id : undefined);
392
428
  try {
393
- const { turnId } = await codexServers.prompt(owned, text);
394
- return { ok: true, delivered: true, turnId };
429
+ const { turnId } = await codexServers.send(owned, text);
430
+ if (await taken === "delivered")
431
+ return { ok: true, delivered: true, state: "delivered", turnId };
432
+ if (id)
433
+ agentHooks.deliveries.queue(id, target);
434
+ return { ok: true, queued: true, ...(id ? { state: "queued" } : {}), turnId };
395
435
  }
396
436
  catch (error) {
397
- if (error instanceof AppServerRpcError)
437
+ if (error instanceof AppServerRpcError) {
438
+ refused.abort();
398
439
  throw new BridgeError(409, `Codex refused the message: ${error.message}`);
399
- if (!(error instanceof CodexServerUnavailable))
400
- return { ok: true, deliveryUncertain: true };
440
+ }
441
+ if (error instanceof CodexServerUnavailable)
442
+ refused.abort();
443
+ else {
444
+ if (id)
445
+ agentHooks.deliveries.queue(id, target);
446
+ return { ok: true, deliveryUncertain: true, ...(id ? { state: "queued" } : {}) };
447
+ }
401
448
  }
402
449
  }
403
450
  const deliveryId = deliveryIdSchema.parse(data.deliveryId);
404
451
  let busy = String(pane.agent_status) === "working";
405
452
  let outcome = await promptWithStartupRetry(async () => {
406
453
  const refused = new AbortController();
407
- const expected = agentHooks.expectDelivery(target, text, busy && target.source !== "claude" ? 300 : 1_500, refused.signal, deliveryId);
454
+ const expected = agentHooks.deliveries.expect(target, text, busy && target.source !== "claude" ? 300 : 1_500, refused.signal, deliveryId, typeof pane.terminal_id === "string" ? pane.terminal_id : undefined);
408
455
  await typing();
409
456
  try {
410
457
  await terminalProvider().prompt(target.server, target.pane, text);
@@ -435,45 +482,40 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
435
482
  else
436
483
  followQueuedDelivery(agentHooks, target, pane.terminal_id, text);
437
484
  }
438
- const refusedHere = () => new BridgeError(409, "The conversation in this pane changed; the message was not delivered. Reopen the chat and send it again.");
439
- if (outcome === "blocked")
440
- throw refusedHere();
441
485
  // A bare slash command opens the agent's own menu; the phone may
442
486
  // walk it with keys for the next half minute. The command rides
443
487
  // along so a Codex /permissions walk can find its confirmation.
444
488
  if (/^\/[a-z][a-z0-9_-]*$/i.test(text.trim()))
445
489
  agentHooks.menuOpened(target, text.trim());
446
490
  if (outcome === "delivered")
447
- result = { ok: true, delivered: true };
491
+ result = { ok: true, delivered: true, state: "delivered" };
448
492
  else if (outcome === "unsubmitted") {
449
- result = { ok: true, deliveryUncertain: true, unsubmitted: true };
493
+ const reason = "The agent did not take the message; it may still be in its input line.";
494
+ if (deliveryId)
495
+ agentHooks.deliveries.fail(deliveryId, target, reason);
496
+ result = { ok: true, deliveryUncertain: true, unsubmitted: true, ...(deliveryId ? { state: "failed", reason } : {}) };
450
497
  }
451
498
  else {
452
- // The agent has not submitted it yet (a busy agent queues typed
453
- // input). Recheck fresh identity and never retry; a late
454
- // submission to another conversation is still refused above. A bare
455
- // ok acknowledges transport only, even if this is still the same
456
- // conversation. Callers needing a submitted turn require delivered.
499
+ // The agent has not submitted it yet: a busy agent holds typed input
500
+ // until its turn ends. The record is bound to the pane, so whichever
501
+ // conversation is there then takes it, and the Hook fails it loudly if
502
+ // the agent closes, restarts or ends its turn without it. A failed
503
+ // identity probe still says deliveryUncertain to phones without
504
+ // `paneDeliveries`. Never retried here.
457
505
  let confirmed = false;
458
506
  try {
459
507
  const current = findPane(await snapshot(target.server), target);
460
508
  confirmed = !!current && current.terminal_id === pane.terminal_id && await paneIdentity(target.server, current, true) === target.session;
461
509
  }
462
510
  catch { /* No reliable post-delivery identity. */ }
463
- // The hook can take it while the identity probe runs; its answer,
464
- // keyed by the delivery id, beats the probe.
465
- const late = deliveryId ? agentHooks.deliveryState(deliveryId, target) : "unknown";
466
- if (late === "blocked")
467
- throw refusedHere();
511
+ // The hook can take it while the identity probe runs.
512
+ const late = deliveryId ? agentHooks.deliveries.status(deliveryId, target).state : "unknown";
468
513
  if (late === "delivered")
469
- result = { ok: true, delivered: true };
514
+ result = { ok: true, delivered: true, state: "delivered" };
470
515
  else {
471
- // Still this conversation, in the same terminal: the agent holds the
472
- // message (a busy turn queues it) and its hook has not submitted it
473
- // yet. Queued, not delivered; `/v1/prompt/status` says when it lands.
474
- if (confirmed && deliveryId)
475
- agentHooks.queueDelivery(deliveryId, target);
476
- result = { ok: true, ...(!confirmed ? { deliveryUncertain: true } : { queued: true }) };
516
+ if (deliveryId)
517
+ agentHooks.deliveries.queue(deliveryId, target);
518
+ result = { ok: true, ...(!confirmed ? { deliveryUncertain: true } : { queued: true }), ...(deliveryId ? { state: "queued" } : {}) };
477
519
  }
478
520
  }
479
521
  }
@@ -482,7 +524,8 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
482
524
  const id = deliveryIdSchema.parse(data.deliveryId);
483
525
  if (!id)
484
526
  throw new BridgeError(400, "Name the message by its deliveryId.");
485
- result = { ok: true, state: agentHooks.deliveryState(id, target) };
527
+ // Bound to the pane: the conversation that took it may be a newer one.
528
+ result = { ok: true, ...agentHooks.deliveries.status(id, target) };
486
529
  }
487
530
  else if (url.pathname === "/v1/side-question/dismiss") {
488
531
  result = sideQuestions.dismiss(target, z.string().uuid().parse(data.id));
@@ -590,12 +633,7 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
590
633
  result = await repositoryDiff(await gitRepository(pane, target, data.child, data.worktree), [], []);
591
634
  }
592
635
  else if (child !== undefined) {
593
- // A spawned agent: its own worktree for a fan-out, otherwise the
594
- // parent's checkout. The whole repository, no phone-named paths.
595
- const relation = childAgent(await childAgentTree(target.source, target.session), child);
596
- if (!relation)
597
- throw new BridgeError(404, "That agent is not part of this conversation.");
598
- result = await repositoryDiff(relation.cwd ?? await trustedDirectory(pane), [], []);
636
+ result = await repositoryDiff(await gitRepository(pane, target, child), [], []);
599
637
  }
600
638
  else {
601
639
  const cwd = await trustedDirectory(pane), paths = z.array(z.string().max(4096)).max(24).optional().parse(data.paths) ?? [];
@@ -617,9 +655,17 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
617
655
  else if (url.pathname.startsWith("/v1/git/")) {
618
656
  // Git routes read the pane's repository, or a spawned child's own
619
657
  // worktree, exactly as /v1/diff resolves it.
620
- const cwd = await gitRepository(pane, target, data.child, data.worktree);
658
+ 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}`)
660
+ && data.expectedRepository !== undefined) {
661
+ 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
+ const root = await gitRoot(cwd);
663
+ if (root !== expected)
664
+ throw new BridgeError(409, "This pane's checkout changed. Refresh Changes before writing.", { code: "git-checkout-changed" });
665
+ cwd = root; // Execute in the validated root, never a path selected by the client.
666
+ }
621
667
  if (url.pathname === "/v1/git/status")
622
- result = await gitStatus(cwd);
668
+ result = await gitStatus(cwd, z.string().min(1).max(4096).optional().parse(data.untrackedPath));
623
669
  else if (url.pathname === "/v1/git/worktrees")
624
670
  result = await gitWorktrees(cwd, await worktreeWorkers(target));
625
671
  else if (url.pathname === "/v1/git/log")
@@ -631,7 +677,7 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
631
677
  else if (url.pathname === "/v1/git/tree")
632
678
  result = await gitTree(cwd, z.string().max(4096).optional().parse(data.path) ?? "", z.boolean().optional().parse(data.ignored) ?? false);
633
679
  else if (url.pathname === "/v1/git/stage")
634
- result = await gitStage(cwd, data.paths);
680
+ result = await gitStage(cwd, data.paths, z.boolean().optional().parse(data.confirmBulk) ?? false);
635
681
  else if (url.pathname === "/v1/git/unstage")
636
682
  result = await gitUnstage(cwd, data.paths);
637
683
  else if (url.pathname === "/v1/git/discard")