@phren/cli 0.3.31 → 0.3.33

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 (68) hide show
  1. package/dist/bridge/agent-hooks.js +23 -7
  2. package/dist/bridge/approval-rules.d.ts +70 -0
  3. package/dist/bridge/approval-rules.js +231 -0
  4. package/dist/bridge/authority.d.ts +1 -2
  5. package/dist/bridge/authority.js +2 -7
  6. package/dist/bridge/changes.d.ts +4 -0
  7. package/dist/bridge/changes.js +47 -33
  8. package/dist/bridge/claude-suggestion.js +1 -1
  9. package/dist/bridge/computer-names.d.ts +4 -0
  10. package/dist/bridge/computer-names.js +19 -0
  11. package/dist/bridge/dispatch.js +1 -1
  12. package/dist/bridge/enroll.d.ts +6 -0
  13. package/dist/bridge/enroll.js +10 -4
  14. package/dist/bridge/git-worktrees.js +14 -17
  15. package/dist/bridge/git.d.ts +10 -2
  16. package/dist/bridge/git.js +148 -107
  17. package/dist/bridge/health.js +9 -5
  18. package/dist/bridge/herdr.js +6 -1
  19. package/dist/bridge/locate.js +14 -1
  20. package/dist/bridge/model-switch.d.ts +4 -0
  21. package/dist/bridge/model-switch.js +16 -4
  22. package/dist/bridge/projects.d.ts +8 -0
  23. package/dist/bridge/projects.js +142 -24
  24. package/dist/bridge/schedule-format.d.ts +12 -0
  25. package/dist/bridge/schedule-format.js +33 -2
  26. package/dist/bridge/schedules.d.ts +8 -1
  27. package/dist/bridge/schedules.js +109 -45
  28. package/dist/bridge/server-launch.js +39 -15
  29. package/dist/bridge/server-pane-routes.js +19 -11
  30. package/dist/bridge/server-routes.d.ts +2 -0
  31. package/dist/bridge/server-routes.js +36 -8
  32. package/dist/bridge/server.js +1 -0
  33. package/dist/bridge/settings-switch.js +2 -6
  34. package/dist/bridge/speech-key.d.ts +2 -9
  35. package/dist/bridge/speech-key.js +4 -37
  36. package/dist/bridge/terminal-tmux.js +22 -4
  37. package/dist/bridge/tmux-test-server.d.ts +13 -0
  38. package/dist/bridge/tmux-test-server.js +103 -0
  39. package/dist/bridge/transcript-claude.d.ts +3 -3
  40. package/dist/bridge/transcript-claude.js +7 -7
  41. package/dist/bridge/transcript-codex.js +6 -4
  42. package/dist/bridge/transcript-preview.js +1 -1
  43. package/dist/bridge/transcripts.js +14 -3
  44. package/dist/bridge-hook.mjs +2794 -2223
  45. package/dist/cli/schedules.js +8 -2
  46. package/dist/cli/session-stop.js +9 -1
  47. package/dist/cli-registry.js +1 -1
  48. package/dist/core/project-registry.d.ts +1 -0
  49. package/dist/core/project-registry.js +6 -2
  50. package/dist/core/project.d.ts +1 -0
  51. package/dist/core/project.js +5 -0
  52. package/dist/modules/registry.js +9 -7
  53. package/dist/phren-core.js +1 -1
  54. package/dist/phren-paths.d.ts +2 -2
  55. package/dist/phren-paths.js +2 -2
  56. package/dist/store-routing.d.ts +2 -2
  57. package/dist/store-routing.js +2 -2
  58. package/dist/sync/git-state.d.ts +13 -0
  59. package/dist/sync/git-state.js +22 -0
  60. package/dist/sync/store-merge.d.ts +2 -0
  61. package/dist/sync/store-merge.js +6 -1
  62. package/dist/test-global-setup.js +7 -0
  63. package/dist/tools/data.js +1 -1
  64. package/dist/tools/finding.js +1 -1
  65. package/dist/tools/search.js +1 -1
  66. package/dist/tools/tasks.js +1 -1
  67. package/package.json +1 -1
  68. package/starter/global/skills/conductor/SKILL.md +2 -2
@@ -1,10 +1,11 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { hostname } from "node:os";
2
+ import { stat } from "node:fs/promises";
3
+ import { localNames, stableComputerName } from "./computer-names.js";
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";
@@ -14,11 +15,14 @@ export class Scheduler {
14
15
  launch;
15
16
  runsFile;
16
17
  computer;
18
+ /** Every name this computer answers to; a schedule names one of them. */
19
+ names;
17
20
  locateProject;
18
21
  push;
19
22
  log;
20
23
  serial = Promise.resolve();
21
24
  ticking = false;
25
+ dispatching = new Set();
22
26
  /** Runs this process launched; any other open run was left by an earlier Hook. */
23
27
  own = new Set();
24
28
  recovered = false;
@@ -33,8 +37,10 @@ export class Scheduler {
33
37
  this.computer = options.computer;
34
38
  else {
35
39
  const computer = options.computer;
36
- this.computer = () => computer ?? hostname();
40
+ this.computer = () => computer ?? stableComputerName();
37
41
  }
42
+ const aliases = options.aliases ?? [];
43
+ this.names = options.computer === undefined ? () => [...localNames(), ...aliases] : () => [this.computer(), ...aliases];
38
44
  this.locateProject = options.locateProject ?? (async () => undefined);
39
45
  this.push = options.push;
40
46
  this.log = options.log ?? (message => console.error(message));
@@ -58,8 +64,11 @@ export class Scheduler {
58
64
  release();
59
65
  }
60
66
  }
67
+ owns(schedule, names = this.names()) {
68
+ return names.some(name => computerMatches(schedule.computer, name));
69
+ }
61
70
  async statuses() {
62
- const runs = await readScheduleRuns(this.runsFile), result = [], computer = this.computer();
71
+ const runs = await readScheduleRuns(this.runsFile), result = [], computer = this.computer(), names = this.names();
63
72
  for (const directory of this.projectDirectories()) {
64
73
  let schedules;
65
74
  try {
@@ -70,11 +79,14 @@ export class Scheduler {
70
79
  }
71
80
  const project = path.basename(directory);
72
81
  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 due = computerMatches(schedule.computer, computer) ? nextRun(schedule, last) : null;
76
- result.push({ ...schedule, project, nextRun: due?.toISOString() ?? null,
82
+ const matching = runs.filter(run => (run.scheduleProject ?? run.project) === project && run.scheduleId === schedule.id);
83
+ const { lastRun: last, lastRuns } = latestScheduleBatch(matching);
84
+ const running = matching.some(run => runningStatuses.has(run.status));
85
+ const due = this.owns(schedule, names) ? nextRun(schedule, last) : null;
86
+ const owned = this.owns(schedule, names);
87
+ result.push({ ...schedule, project, lastRuns, owned, nextRun: due?.toISOString() ?? null,
77
88
  lastRun: last ? { startedAt: last.startedAt, ...(last.finishedAt ? { finishedAt: last.finishedAt } : {}), status: last.status,
89
+ ...(last.batchId ? { batchId: last.batchId, scheduleProject: last.scheduleProject } : {}),
78
90
  ...(last.reason ? { reason: last.reason } : {}),
79
91
  ...(last.blockedStartupPrompt ? { blockedStartupPrompt: last.blockedStartupPrompt } : {}),
80
92
  ...(last.blockNotified !== undefined ? { blockNotified: last.blockNotified } : {}), launch: last.launch } : null, running });
@@ -84,52 +96,99 @@ export class Scheduler {
84
96
  }
85
97
  async history(filters = {}) {
86
98
  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())
99
+ return (await readScheduleRuns(this.runsFile)).filter(run => (!filters.project || (run.scheduleProject ?? run.project).toLowerCase() === filters.project.toLowerCase())
88
100
  && (!filters.id || run.scheduleId === filters.id)).slice(-limit).reverse();
89
101
  }
90
- async launchNow(projectName, id) {
102
+ async launchNow(projectName, id, onlyIfDue = false, expectedUpdatedAt) {
103
+ const key = `${projectName.toLowerCase()}/${id}`;
104
+ if (this.dispatching.has(key))
105
+ throw new BridgeError(409, "This schedule is already launching.");
106
+ this.dispatching.add(key);
107
+ try {
108
+ return await this.prepareAndLaunch(projectName, id, onlyIfDue, expectedUpdatedAt);
109
+ }
110
+ finally {
111
+ this.dispatching.delete(key);
112
+ }
113
+ }
114
+ async prepareAndLaunch(projectName, id, onlyIfDue, expectedUpdatedAt) {
91
115
  const prepared = await this.exclusive(async () => {
92
116
  const projectDir = this.projectDirectory(projectName), project = path.basename(projectDir);
93
117
  const file = await readScheduleDocument(projectDir), schedule = file.schedules.find(item => item.id === id);
94
118
  if (!schedule)
95
119
  throw new BridgeError(404, `Schedule "${id}" was not found in ${project}.`);
96
- if (!computerMatches(schedule.computer, this.computer()))
120
+ if (expectedUpdatedAt !== undefined && Date.parse(expectedUpdatedAt) !== Date.parse(schedule.updatedAt)) {
121
+ 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.");
122
+ }
123
+ if (!this.owns(schedule))
97
124
  throw new BridgeError(409, `${schedule.computer} owns this schedule; run it from that computer.`);
98
125
  const runs = await readScheduleRuns(this.runsFile);
99
- if (runs.some(run => run.project === project && run.scheduleId === id && runningStatuses.has(run.status))) {
126
+ const matching = runs.filter(run => (run.scheduleProject ?? run.project) === project && run.scheduleId === id);
127
+ if (matching.some(run => runningStatuses.has(run.status))) {
100
128
  throw new BridgeError(409, `Schedule "${schedule.name}" is already running.`);
101
129
  }
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]);
130
+ // Recheck a tick's snapshot after a concurrent Run now or schedule edit.
131
+ const due = nextRun(schedule, matching.at(-1));
132
+ if (onlyIfDue && (!schedule.enabled || !due || due > this.now()))
133
+ return undefined;
134
+ const targets = [];
135
+ for (const name of schedule.projects ?? [project]) {
136
+ const targetDir = this.projectDirectory(name), target = path.basename(targetDir);
137
+ const source = getProjectSourcePath(this.store, target) ?? await this.locateProject(target);
138
+ if (!source && schedule.projects)
139
+ throw new BridgeError(409, `No source directory for project "${target}" on this computer.`);
140
+ const cwd = source ?? targetDir;
141
+ if (!await stat(cwd).then(info => info.isDirectory()).catch(() => false)) {
142
+ throw new BridgeError(409, `Source directory for project "${target}" is unavailable: ${cwd}`);
143
+ }
144
+ targets.push({ project: target, projectDir: targetDir, cwd });
145
+ }
146
+ const batchId = randomUUID(), startedAt = this.now().toISOString();
147
+ const children = targets.map(target => ({ ...target, run: {
148
+ id: randomUUID(), scheduleId: id, project: target.project, scheduleProject: project, batchId,
149
+ startedAt, status: "launched", launch: { mode: "headless" },
150
+ } }));
151
+ // One atomic replacement reserves every target before any external launch.
152
+ await writeScheduleRuns(this.runsFile, [...runs, ...children.map(child => child.run)]);
153
+ for (const child of children)
154
+ this.own.add(child.run.id);
105
155
  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);
156
+ const schedules = file.schedules.map(item => item.id === id ? { ...item, enabled: false, updatedAt: startedAt } : item);
157
+ try {
158
+ await writeScheduleDocument(projectDir, schedules, file.document);
159
+ }
160
+ catch (error) {
161
+ // The durable batch already consumes the occurrence. A YAML write
162
+ // failure must not strand pending children in this running process.
163
+ this.log(`[schedule] Could not disable consumed once schedule ${project}/${id}: ${String(error)}`);
164
+ }
109
165
  }
110
- const source = getProjectSourcePath(this.store, project);
111
- return { projectDir, project, schedule, run, cwd: source ?? await this.locateProject(project) ?? projectDir };
166
+ return { schedule, children };
112
167
  });
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
- }
168
+ if (!prepared)
169
+ return [];
170
+ // Independent attempts: one target's startup failure never cancels siblings.
171
+ return Promise.all(prepared.children.map(async (child) => {
172
+ try {
173
+ const launched = await this.launch({ schedule: prepared.schedule, project: child.project, projectDir: child.projectDir,
174
+ cwd: child.cwd, runId: child.run.id,
175
+ blockedStartup: promptText => this.recordBlockedStartup(child.run.id, prepared.schedule, promptText) });
176
+ const running = await this.updateRun(child.run.id, { status: "running", launch: launched.launch });
177
+ const notified = this.notifyRun(running, prepared.schedule, "scheduleStarted");
178
+ if (launched.completion)
179
+ void launched.completion.then(async (result) => {
180
+ await this.finishRun(child.run.id, prepared.schedule, result.status, result.reason, notified);
181
+ }).catch(async (error) => {
182
+ await this.finishRun(child.run.id, prepared.schedule, "failed", error instanceof Error ? error.message : "The scheduled agent failed.", notified);
183
+ }).catch(error => this.log(`[schedule] Could not finish run ${child.run.id}: ${String(error)}`));
184
+ await notified;
185
+ return running;
186
+ }
187
+ catch (error) {
188
+ const reason = error instanceof Error ? error.message : "The scheduled agent could not start.";
189
+ return this.finishRun(child.run.id, prepared.schedule, "failed", reason);
190
+ }
191
+ }));
133
192
  }
134
193
  async updateRun(id, patch) {
135
194
  return this.exclusive(async () => {
@@ -145,8 +204,9 @@ export class Scheduler {
145
204
  const run = await this.updateRun(id, { status, finishedAt: this.now().toISOString(), ...(reason ? { reason } : {}) });
146
205
  await previousNotification;
147
206
  if (run.blockedStartupPrompt && run.blockNotified)
148
- return;
207
+ return run;
149
208
  await this.notifyRun(run, schedule, status === "failed" ? "scheduleFailed" : "scheduleFinished");
209
+ return run;
150
210
  }
151
211
  async recordBlockedStartup(id, schedule, promptText) {
152
212
  try {
@@ -199,12 +259,16 @@ export class Scheduler {
199
259
  if (this.recovered || !resume)
200
260
  return;
201
261
  this.recovered = true;
202
- const open = (await readScheduleRuns(this.runsFile)).filter(run => runningStatuses.has(run.status) && !this.own.has(run.id));
262
+ const open = await this.exclusive(async () => {
263
+ const pending = (await readScheduleRuns(this.runsFile)).filter(run => runningStatuses.has(run.status) && !this.own.has(run.id));
264
+ for (const run of pending)
265
+ this.own.add(run.id);
266
+ return pending;
267
+ });
203
268
  for (const run of open) {
204
- this.own.add(run.id);
205
269
  let schedule;
206
270
  try {
207
- schedule = (await readScheduleDocument(this.projectDirectory(run.project))).schedules.find(item => item.id === run.scheduleId);
271
+ schedule = (await readScheduleDocument(this.projectDirectory(run.scheduleProject ?? run.project))).schedules.find(item => item.id === run.scheduleId);
208
272
  }
209
273
  catch {
210
274
  schedule = undefined;
@@ -234,7 +298,7 @@ export class Scheduler {
234
298
  for (const schedule of status.schedules) {
235
299
  if (!schedule.enabled || schedule.running || !schedule.nextRun || new Date(schedule.nextRun) > now)
236
300
  continue;
237
- await this.launchNow(schedule.project, schedule.id).catch(() => { });
301
+ await this.launchNow(schedule.project, schedule.id, true).catch(() => { });
238
302
  }
239
303
  }
240
304
  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
  }
@@ -261,6 +263,9 @@ function deliveryReply(agentHooks, id, target, text) {
261
263
  ...(status.state === "queued" ? { queued: true } : {}), ...(status.reason ? { reason: status.reason } : {}) };
262
264
  }
263
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
+ }
264
269
  if (url.pathname !== "/v1/prompt")
265
270
  return paneRouteOnce(ctx, url, data, response, () => { });
266
271
  // A retried send carries its first attempt's id; the Hook answers it with
@@ -628,12 +633,7 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
628
633
  result = await repositoryDiff(await gitRepository(pane, target, data.child, data.worktree), [], []);
629
634
  }
630
635
  else if (child !== undefined) {
631
- // A spawned agent: its own worktree for a fan-out, otherwise the
632
- // parent's checkout. The whole repository, no phone-named paths.
633
- const relation = childAgent(await childAgentTree(target.source, target.session), child);
634
- if (!relation)
635
- throw new BridgeError(404, "That agent is not part of this conversation.");
636
- result = await repositoryDiff(relation.cwd ?? await trustedDirectory(pane), [], []);
636
+ result = await repositoryDiff(await gitRepository(pane, target, child), [], []);
637
637
  }
638
638
  else {
639
639
  const cwd = await trustedDirectory(pane), paths = z.array(z.string().max(4096)).max(24).optional().parse(data.paths) ?? [];
@@ -655,9 +655,17 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
655
655
  else if (url.pathname.startsWith("/v1/git/")) {
656
656
  // Git routes read the pane's repository, or a spawned child's own
657
657
  // worktree, exactly as /v1/diff resolves it.
658
- 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
+ }
659
667
  if (url.pathname === "/v1/git/status")
660
- result = await gitStatus(cwd);
668
+ result = await gitStatus(cwd, z.string().min(1).max(4096).optional().parse(data.untrackedPath));
661
669
  else if (url.pathname === "/v1/git/worktrees")
662
670
  result = await gitWorktrees(cwd, await worktreeWorkers(target));
663
671
  else if (url.pathname === "/v1/git/log")
@@ -669,7 +677,7 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
669
677
  else if (url.pathname === "/v1/git/tree")
670
678
  result = await gitTree(cwd, z.string().max(4096).optional().parse(data.path) ?? "", z.boolean().optional().parse(data.ignored) ?? false);
671
679
  else if (url.pathname === "/v1/git/stage")
672
- result = await gitStage(cwd, data.paths);
680
+ result = await gitStage(cwd, data.paths, z.boolean().optional().parse(data.confirmBulk) ?? false);
673
681
  else if (url.pathname === "/v1/git/unstage")
674
682
  result = await gitUnstage(cwd, data.paths);
675
683
  else if (url.pathname === "/v1/git/discard")
@@ -125,6 +125,8 @@ export declare const capabilities: {
125
125
  sudoOutcome: boolean;
126
126
  previewDeltas: boolean;
127
127
  quickChat: boolean;
128
+ agentFolder: boolean;
129
+ launchPermissionMode: boolean;
128
130
  };
129
131
  export declare function capabilitiesForModules(snapshot: ModuleSnapshot): Record<string, unknown>;
130
132
  export declare function requireRoute(snapshot: ModuleSnapshot, method: string, route: string): void;
@@ -16,6 +16,7 @@ import { dispatchProjectDirectory, dispatchStatus, originPaneSchema } from "./di
16
16
  import { hookWorkers } from "./dispatch-returns.js";
17
17
  import { remoteChildren } from "./dispatch-tree.js";
18
18
  import { briefArrival, briefId } from "./launch-brief.js";
19
+ import { listApprovalRules, changeApprovalRule } from "./approval-rules.js";
19
20
  import { addGrant, listNamedGrants, removeGrant } from "./grants.js";
20
21
  import { clearProjectAuthority, confirmAuthority, listConfirmations, projectAuthority, readAuthority, setProjectAuthority } from "./authority.js";
21
22
  import { readComputers } from "./computer-identity.js";
@@ -28,7 +29,8 @@ import { storeRoute } from "./memory-store.js";
28
29
  import { liveBackground, markBackground, paneRecord, recordTitle } from "./session-activity.js";
29
30
  import { paneAccountField, paneChatState, panes, servers, snapshot, validateTarget, workspaceSnapshot } from "./herdr.js";
30
31
  import { locateProject } from "./locate.js";
31
- import { gitRoot, launchDirectory, repositoryBranch, webServers } from "./projects.js";
32
+ import { gitStatus } from "./git.js";
33
+ import { gitRoot, launchDirectory, repositoryBranch, webServers, withGitReadDeadline } from "./projects.js";
32
34
  import { approvalDecisions, BridgeError, bridgeRoot, MAX_FRAME, object, objects, PROTOCOL, provider, serverName, targetFromURL, targetSchema } from "./protocol.js";
33
35
  import { bootedSimulators, simulatorAct, simulatorApps, simulatorScreenshot } from "./simulators.js";
34
36
  import { childAgentTree, historicalImage, publicChildAgents, refreshTranscript, runningChildAgents, targetTranscriptPath } from "./transcripts.js";
@@ -74,13 +76,17 @@ async function childActivity(source, session) {
74
76
  export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
75
77
  terminal: "ssh-pty", shell: "ssh-pty", herdr: true, sessionRename: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
76
78
  approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
77
- files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true };
79
+ files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true };
78
80
  export function capabilitiesForModules(snapshot) {
79
81
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
80
82
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
81
83
  for (const name of ["memory", "tasks", "hook", "git", "schedules"])
82
84
  if (snapshot.has(name))
83
85
  result[name] = true;
86
+ if (snapshot.has("hook"))
87
+ result.approvalRules = { version: 2, effects: ["always-ask", "deny"], harnesses: ["claude"], events: ["PermissionRequest"], tools: ["Bash"], inputField: "command", conductorTools: false, mcpTools: false, preExecution: false };
88
+ if (snapshot.has("schedules"))
89
+ result.scheduleProjects = true;
84
90
  if (snapshot.has("tasks")) {
85
91
  result.taskDependencies = true;
86
92
  result.taskWriterSafety = true;
@@ -341,6 +347,9 @@ export function createRouteHandler(ctx) {
341
347
  case "/v1/dispatch/arrival":
342
348
  result = { arrival: await briefArrival(briefId.parse(url.searchParams.get("id"))) ?? null };
343
349
  break;
350
+ case "/v1/approval-rules":
351
+ result = { rules: await listApprovalRules(undefined, z.string().regex(/^[A-Za-z0-9+/]{43}=$/).optional().parse(url.searchParams.get("pairedKey") ?? undefined)) };
352
+ break;
344
353
  case "/v1/conductor/grants":
345
354
  result = { grants: await listNamedGrants() };
346
355
  break;
@@ -418,6 +427,14 @@ export function createRouteHandler(ctx) {
418
427
  case "/v1/files":
419
428
  result = { files: await listUploads("files") };
420
429
  break;
430
+ case "/v1/git/status": {
431
+ result = await withGitReadDeadline(async () => {
432
+ const target = targetFromURL(url), pane = await validateTarget(target);
433
+ const cwd = await gitRepository(pane, target, url.searchParams.get("child") ?? undefined, url.searchParams.get("worktree") ?? undefined);
434
+ return gitStatus(cwd, z.string().min(1).max(4096).optional().parse(url.searchParams.get("untrackedPath") ?? undefined));
435
+ });
436
+ break;
437
+ }
421
438
  case "/v1/files/resolve": {
422
439
  const target = targetFromURL(url), pane = await validateTarget(target);
423
440
  const cwd = await gitRepository(pane, target, url.searchParams.get("child") ?? undefined, url.searchParams.get("worktree") ?? undefined);
@@ -682,8 +699,10 @@ export function createRouteHandler(ctx) {
682
699
  result = await scheduler.statuses();
683
700
  }
684
701
  else if (url.pathname === "/v1/schedules/run") {
685
- const input = z.object({ project: z.string().min(1).max(200), id: z.string().regex(/^[a-f0-9]{8}$/) }).parse(data);
686
- result = { ok: true, run: await scheduler.launchNow(input.project, input.id) };
702
+ const input = z.object({ project: z.string().min(1).max(200), id: z.string().regex(/^[a-f0-9]{8}$/),
703
+ expectedUpdatedAt: z.string().datetime({ offset: true }).optional() }).parse(data);
704
+ const runs = await scheduler.launchNow(input.project, input.id, false, input.expectedUpdatedAt);
705
+ result = { ok: runs.every(run => run.status !== "failed"), run: runs[0], runs };
687
706
  }
688
707
  else if (url.pathname === "/v1/schedules/history") {
689
708
  const input = z.object({ project: z.string().min(1).max(200).optional(), id: z.string().regex(/^[a-f0-9]{8}$/).optional(),
@@ -733,6 +752,9 @@ export function createRouteHandler(ctx) {
733
752
  await ctx.returns.answerApproval(body.id, body.decision, body.actionId, body.origin);
734
753
  result = { ok: true };
735
754
  }
755
+ else if (url.pathname === "/v1/approval-rules") {
756
+ result = await changeApprovalRule(data, "POST");
757
+ }
736
758
  else if (url.pathname === "/v1/conductor/grants") {
737
759
  result = { ok: true, grant: await addGrant(data) };
738
760
  }
@@ -800,7 +822,7 @@ export function createRouteHandler(ctx) {
800
822
  else if (url.pathname === "/v1/projects/add") {
801
823
  // Enrolling a repository with phren from the phone: an existing
802
824
  // checkout, or a clone. Serialized like launches — one at a time.
803
- result = await launches.run(async () => enrollProject(z.object({ directory: z.string().max(4096).optional(), cloneUrl: z.string().max(512).optional() }).parse(data)));
825
+ result = await launches.run(async () => enrollProject(z.object({ directory: z.string().max(4096).optional(), cloneUrl: z.string().max(512).optional(), project: z.string().max(100).optional(), store: z.string().max(200).optional() }).parse(data)));
804
826
  }
805
827
  else if (url.pathname === "/v1/simulators/action") {
806
828
  result = await simulatorAct(z.string().parse(data.udid), z.object({ action: z.string(), bundleId: z.string().optional(), url: z.string().optional(), x: z.number().optional(), y: z.number().optional(), text: z.string().optional(), submit: z.boolean().optional() }).parse(data));
@@ -810,12 +832,15 @@ export function createRouteHandler(ctx) {
810
832
  result = await launches.run(async () => {
811
833
  if (data.role === "conductor" && !modules.has("conductor"))
812
834
  throw new BridgeError(404, disabledHint("conductor"));
835
+ if (data.agentFolder === true && (data.role === "conductor" || data.project !== undefined || (data.cwd !== undefined && data.cwd !== "") || data.worktree != null)) {
836
+ throw new BridgeError(400, "An agent folder is for a projectless agent without cwd or worktree.");
837
+ }
813
838
  if (data.project !== undefined && data.cwd !== undefined)
814
839
  throw new BridgeError(400, "Choose project or cwd, not both.");
815
840
  // A conductor belongs to no one project: without a folder it starts in
816
841
  // this computer's phren store and dispatches into any project from there.
817
842
  const storeRooted = data.role === "conductor" && data.project === undefined && (data.cwd === undefined || data.cwd === "");
818
- const cwd = storeRooted ? await launchDirectory(defaultPhrenPath(), [], [defaultPhrenPath()])
843
+ const cwd = data.agentFolder === true ? undefined : storeRooted ? await launchDirectory(defaultPhrenPath(), [], [defaultPhrenPath()])
819
844
  : data.project !== undefined ? await dispatchProjectDirectory(data.project)
820
845
  : await launchDirectory(data.cwd, await journal.recent(), locatedDirectories);
821
846
  // A project the Hook resolved (a dispatch) is a folder it may trust; a folder the phone named is not.
@@ -833,10 +858,13 @@ export function createRouteHandler(ctx) {
833
858
  }
834
859
  }
835
860
  else if (request.method === "DELETE") {
836
- if (url.pathname !== "/v1/conductor/grants" && url.pathname !== "/v1/authority")
861
+ if (url.pathname !== "/v1/conductor/grants" && url.pathname !== "/v1/authority" && url.pathname !== "/v1/approval-rules")
837
862
  throw new BridgeError(404, "Unknown Phren Hook route.");
838
863
  const data = await body(request);
839
- if (url.pathname === "/v1/authority") {
864
+ if (url.pathname === "/v1/approval-rules") {
865
+ result = await changeApprovalRule(data, "DELETE");
866
+ }
867
+ else if (url.pathname === "/v1/authority") {
840
868
  if (data.origin !== undefined)
841
869
  throw new BridgeError(403, "Only the owner changes the release authority policy, from the phone or `phren authority` in their own terminal.");
842
870
  result = { ok: true, authority: await clearProjectAuthority(data, "phone") };
@@ -155,6 +155,7 @@ export async function serve(version, options = {}) {
155
155
  const codexQuestions = new CodexQuestions(undefined, codexServers);
156
156
  const scheduleStore = defaultPhrenPath();
157
157
  const scheduler = modules.has("schedules") ? new Scheduler({ now: () => new Date(), store: scheduleStore, runsFile: scheduleRunsFile(),
158
+ aliases: [computerID],
158
159
  // A schedule starts in its project's folder, which the Hook resolved itself.
159
160
  launch: createScheduleLauncher((server, data) => launchSession(server, data, { trustFolder: true }), scheduleStore),
160
161
  push: { notify: value => agentHooks.push.notifySchedule(value) },