@phren/cli 0.3.17 → 0.3.19

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.
@@ -1686,6 +1686,11 @@ export class AgentHooks {
1686
1686
  const status = autoReview ? undefined : eventStatus(body.event);
1687
1687
  if (status && typeof pane.terminal_id === "string")
1688
1688
  notePaneStatus(target.server, target.pane, pane.terminal_id, status);
1689
+ // Herdr does not watch phren-agent: a pane the Hook reported as running
1690
+ // it (a phone launch) takes its status from these events.
1691
+ if (status && target.source === "phren" && pane.agent === "phren" && pane.agent_status !== status) {
1692
+ await terminalProvider().reportAgent?.(target.server, target.pane, "phren", status).catch(() => undefined);
1693
+ }
1689
1694
  // What a shell call changed on disk: snapshot before, diff after.
1690
1695
  const input = typeof body.input === "string" ? { patch: body.input } : object(body.input), command = [input.command, input.cmd].find(v => typeof v === "string");
1691
1696
  // A shell call by name, or any tool whose input is a command line —
@@ -1,6 +1,6 @@
1
1
  import { type AccountRef, type AuthRunner } from "./claude-accounts.js";
2
2
  import { type ToolVersion } from "./health.js";
3
- export type HarnessSource = "claude" | "codex" | "opencode" | "copilot";
3
+ export type HarnessSource = "claude" | "codex" | "opencode" | "copilot" | "phren";
4
4
  export interface HarnessAccount extends AccountRef {
5
5
  signedIn: boolean;
6
6
  usable: boolean;
@@ -1,19 +1,26 @@
1
1
  // What this computer can launch: each harness's install state and, for Claude and Codex, its accounts.
2
+ // `phren` is phren's own agent, run as `phren agent`; it needs no account here.
2
3
  // Served as GET /v1/harnesses and as `harnesses` on /v1/dispatch/capacity. See docs/accounts.md.
3
4
  import { existsSync } from "node:fs";
4
5
  import path from "node:path";
5
6
  import { codexHome } from "../home-paths.js";
6
7
  import { claudeAccountRef, claudeAuthStatus, claudeHomes, CODEX_ACCOUNT } from "./claude-accounts.js";
7
8
  import { toolVersion } from "./health.js";
8
- const SOURCES = ["claude", "codex", "opencode", "copilot"];
9
+ const SOURCES = ["claude", "codex", "opencode", "copilot", "phren"];
10
+ /** The binary is `phren`; the agent answers `phren agent --version` from the separate @phren/agent package. */
11
+ const probeSource = (source) => source === "phren" ? toolVersion("phren agent", "phren", ["agent"]) : toolVersion(source);
9
12
  export async function harnessInventory(deps = {}) {
10
13
  const env = deps.env ?? process.env;
11
- const probe = deps.toolVersion ?? ((tool) => toolVersion(tool));
14
+ const probe = deps.toolVersion ?? probeSource;
12
15
  const harnesses = await Promise.all(SOURCES.map(async (source) => {
13
16
  const found = await probe(source);
14
17
  // Only a missing binary is definite; a slow or failing --version (a loaded computer) stays usable.
15
18
  if (found.status === "missing")
16
19
  return { source, installed: false, usable: false, reason: "Not installed" };
20
+ // `phren agent` without @phren/agent prints an install hint and no version.
21
+ if (source === "phren" && found.status === "error" && found.detail?.startsWith("--version exited")) {
22
+ return { source, installed: false, usable: false, reason: "Not installed: npm install -g @phren/agent" };
23
+ }
17
24
  const base = { source, installed: true, ...(found.version ? { version: found.version } : {}) };
18
25
  if (source === "claude") {
19
26
  const accounts = await Promise.all(claudeHomes(env).map(async (home) => {
@@ -114,8 +114,9 @@ export interface HealthOptions {
114
114
  devices: number;
115
115
  };
116
116
  }
117
- /** `<tool> --version`, bounded to 3 seconds and remembered for 5 minutes. */
118
- export declare function toolVersion(tool: string, executable?: string): Promise<ToolVersion>;
117
+ /** `<tool> --version`, bounded to 3 seconds and remembered for 5 minutes. `args` come
118
+ * before `--version` for a tool behind a subcommand (`phren agent --version`). */
119
+ export declare function toolVersion(tool: string, executable?: string, args?: string[]): Promise<ToolVersion>;
119
120
  /** Only for tests: forget cached versions. */
120
121
  export declare function clearVersionCache(): void;
121
122
  /** Branch and ahead/behind against the upstream as last fetched; nothing is fetched here. */
@@ -38,14 +38,15 @@ const VERSION_TIMEOUT_MS = 3_000;
38
38
  const VERSION_CACHE_MS = 5 * 60_000;
39
39
  const PEER_TIMEOUT_MS = 5_000;
40
40
  const versionCache = new Map();
41
- /** `<tool> --version`, bounded to 3 seconds and remembered for 5 minutes. */
42
- export function toolVersion(tool, executable = tool) {
41
+ /** `<tool> --version`, bounded to 3 seconds and remembered for 5 minutes. `args` come
42
+ * before `--version` for a tool behind a subcommand (`phren agent --version`). */
43
+ export function toolVersion(tool, executable = tool, args = []) {
43
44
  const cached = versionCache.get(tool);
44
45
  if (cached && Date.now() - cached.at < VERSION_CACHE_MS)
45
46
  return cached.value;
46
47
  const value = new Promise(resolve => {
47
48
  let out = "", done = false;
48
- const child = spawn(executable, ["--version"], { cwd: homedir(), stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, NO_COLOR: "1" } });
49
+ const child = spawn(executable, [...args, "--version"], { cwd: homedir(), stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, NO_COLOR: "1" } });
49
50
  const finish = (result) => { if (!done) {
50
51
  done = true;
51
52
  clearTimeout(timer);
@@ -0,0 +1,48 @@
1
+ import type { AgentHooks } from "./agent-hooks.js";
2
+ import { type Json, type Target } from "./protocol.js";
3
+ /** An agent's permission mode as its own footer names it, and the route that
4
+ * changes it by pressing Shift+Tab through the harness's cycle. The phone's
5
+ * mode picker reads `agentStatus.permissionMode` / `permissionModes` off the
6
+ * chat status stream and posts one back here. Only Claude Code draws the mode
7
+ * in its footer; Codex and OpenCode keep theirs in config, so they offer none. */
8
+ /** Claude Code's `permissionMode` values in Shift+Tab cycle order. "default" is
9
+ * the footer's "manual mode on"; "auto" is "auto mode on". */
10
+ export declare const PERMISSION_CYCLE: readonly ["default", "acceptEdits", "plan", "auto"];
11
+ /** `bypassPermissions` is in the cycle only for a session launched allowing
12
+ * bypass, so it is a valid mode but not part of the standard list. */
13
+ export declare const PERMISSION_MODE_VALUES: readonly ["default", "acceptEdits", "plan", "auto", "bypassPermissions"];
14
+ export type PermissionModeName = (typeof PERMISSION_MODE_VALUES)[number];
15
+ /** The modes a Claude pane offers, in Shift+Tab cycle order. `bypass` adds the
16
+ * one only a session launched with --allow-dangerously-skip-permissions has. */
17
+ export declare function permissionModes(bypass: boolean): PermissionModeName[];
18
+ /** Claude's permission mode from the footer line its TUI draws under the
19
+ * composer. The transcript lags it: a `permission-mode` row is written only
20
+ * when a prompt is submitted, and a fresh session has no file yet. The line may
21
+ * trail hints ("(shift+tab to cycle) · 1 agent"), so only its start counts. A
22
+ * mode the footer does not mark is `undefined`: "manual mode on" is default. */
23
+ export declare function claudeFooterMode(screen: string): PermissionModeName | undefined;
24
+ /** Only the owner changes a session's permission mode, from the phone. An
25
+ * agent's call names its own pane (`origin`), and none is accepted: an agent
26
+ * could otherwise lift itself or another pane past the per-grant
27
+ * `maxPermissionMode` ceiling, up to bypassPermissions. Same rule as
28
+ * `/v1/sudo/answer`. */
29
+ export declare function refuseAgentOrigin(actor: unknown): void;
30
+ /** One Shift+Tab transaction per pane owns its terminal input until it ends,
31
+ * like the settings switcher, so a mode change and a settings change never
32
+ * press into the same composer at once. */
33
+ export declare class PermissionModeSwitcher {
34
+ private readonly hooks;
35
+ private readonly wait;
36
+ private active;
37
+ constructor(hooks: AgentHooks, wait?: number);
38
+ private key;
39
+ assertAvailable(target: Target): void;
40
+ /** Steps the pane to `mode`, or refuses. Only Claude offers the cycle; the
41
+ * machine's authority policy never caps an owner's own choice. */
42
+ set(target: Target, mode: PermissionModeName, actor?: unknown): Promise<Json>;
43
+ private cycle;
44
+ /** The mode after a press: polled from the screen until it differs from
45
+ * `from`, because the TUI redraws the footer asynchronously. */
46
+ private changed;
47
+ private assertLive;
48
+ }
@@ -0,0 +1,144 @@
1
+ import { stripTerminal } from "../terminal-text.js";
2
+ import { validateTarget } from "./herdr.js";
3
+ import { BridgeError } from "./protocol.js";
4
+ import { terminalProvider } from "./terminal.js";
5
+ import { visibleTerminalChoice } from "./terminal-choice.js";
6
+ /** An agent's permission mode as its own footer names it, and the route that
7
+ * changes it by pressing Shift+Tab through the harness's cycle. The phone's
8
+ * mode picker reads `agentStatus.permissionMode` / `permissionModes` off the
9
+ * chat status stream and posts one back here. Only Claude Code draws the mode
10
+ * in its footer; Codex and OpenCode keep theirs in config, so they offer none. */
11
+ /** Claude Code's `permissionMode` values in Shift+Tab cycle order. "default" is
12
+ * the footer's "manual mode on"; "auto" is "auto mode on". */
13
+ export const PERMISSION_CYCLE = ["default", "acceptEdits", "plan", "auto"];
14
+ /** `bypassPermissions` is in the cycle only for a session launched allowing
15
+ * bypass, so it is a valid mode but not part of the standard list. */
16
+ export const PERMISSION_MODE_VALUES = [...PERMISSION_CYCLE, "bypassPermissions"];
17
+ /** The modes a Claude pane offers, in Shift+Tab cycle order. `bypass` adds the
18
+ * one only a session launched with --allow-dangerously-skip-permissions has. */
19
+ export function permissionModes(bypass) {
20
+ return [...PERMISSION_CYCLE, ...(bypass ? ["bypassPermissions"] : [])];
21
+ }
22
+ /** Claude's permission mode from the footer line its TUI draws under the
23
+ * composer. The transcript lags it: a `permission-mode` row is written only
24
+ * when a prompt is submitted, and a fresh session has no file yet. The line may
25
+ * trail hints ("(shift+tab to cycle) · 1 agent"), so only its start counts. A
26
+ * mode the footer does not mark is `undefined`: "manual mode on" is default. */
27
+ export function claudeFooterMode(screen) {
28
+ for (const line of stripTerminal(screen).split(/\r?\n/).map(line => line.trim()).filter(Boolean).slice(-8).reverse()) {
29
+ const text = line.replace(/^[⏵⏸]+\s*/, "");
30
+ if (text === line)
31
+ continue;
32
+ if (/bypass permissions on/i.test(text))
33
+ return "bypassPermissions";
34
+ if (/^manual mode on\b/i.test(text))
35
+ return "default";
36
+ if (/^accept edits on\b/i.test(text))
37
+ return "acceptEdits";
38
+ if (/^plan mode on\b/i.test(text))
39
+ return "plan";
40
+ if (/^auto mode on\b/i.test(text))
41
+ return "auto";
42
+ }
43
+ return undefined;
44
+ }
45
+ /** Only the owner changes a session's permission mode, from the phone. An
46
+ * agent's call names its own pane (`origin`), and none is accepted: an agent
47
+ * could otherwise lift itself or another pane past the per-grant
48
+ * `maxPermissionMode` ceiling, up to bypassPermissions. Same rule as
49
+ * `/v1/sudo/answer`. */
50
+ export function refuseAgentOrigin(actor) {
51
+ if (actor !== undefined)
52
+ throw new BridgeError(403, "Only the owner changes a session's permission mode, from the phone.");
53
+ }
54
+ /** Who chose the mode, for the reply: always the owner (see `refuseAgentOrigin`). */
55
+ function attribution() {
56
+ return { setBy: "owner" };
57
+ }
58
+ const STEP_WAIT_MS = 2_000, POLL_MS = 100;
59
+ /** One Shift+Tab transaction per pane owns its terminal input until it ends,
60
+ * like the settings switcher, so a mode change and a settings change never
61
+ * press into the same composer at once. */
62
+ export class PermissionModeSwitcher {
63
+ hooks;
64
+ wait;
65
+ active = new Set();
66
+ constructor(hooks, wait = STEP_WAIT_MS) {
67
+ this.hooks = hooks;
68
+ this.wait = wait;
69
+ }
70
+ key(target) { return `${target.server}:${target.pane}`; }
71
+ assertAvailable(target) {
72
+ if (this.active.has(this.key(target)))
73
+ throw new BridgeError(409, "A permission-mode change is already in progress. Wait for it to finish.");
74
+ }
75
+ /** Steps the pane to `mode`, or refuses. Only Claude offers the cycle; the
76
+ * machine's authority policy never caps an owner's own choice. */
77
+ async set(target, mode, actor) {
78
+ refuseAgentOrigin(actor);
79
+ this.assertAvailable(target);
80
+ if (target.source !== "claude")
81
+ throw new BridgeError(422, "Changing the permission mode is not supported for this harness. Open terminal to change it.");
82
+ this.active.add(this.key(target));
83
+ try {
84
+ return await this.cycle(target, mode, actor);
85
+ }
86
+ finally {
87
+ this.active.delete(this.key(target));
88
+ }
89
+ }
90
+ async cycle(target, mode, actor) {
91
+ const first = await validateTarget(target, false, true);
92
+ const terminal = first.terminal_id, status = String(first.agent_status);
93
+ // Shift+Tab is the composer's key: a turn or a dialog would take it first.
94
+ if (status === "working")
95
+ throw new BridgeError(409, "This agent is mid-turn. Permission changes happen between turns; choose the mode again when the turn ends.");
96
+ const screen = await this.hooks.paneAnsi(target).catch(() => undefined);
97
+ if (screen === undefined)
98
+ throw new BridgeError(409, "Could not read Claude's permission mode from its screen. Open terminal to check.");
99
+ if (status === "blocked" || status === "waiting" || this.hooks.approval(target) || this.hooks.terminalPrompt(target)
100
+ || visibleTerminalChoice(stripTerminal(screen))) {
101
+ throw new BridgeError(409, "A permission prompt or dialog is open. Answer it before changing the permission mode.");
102
+ }
103
+ let current = claudeFooterMode(screen);
104
+ if (!current)
105
+ throw new BridgeError(409, "Could not read Claude's permission mode from its screen. Open terminal to check.");
106
+ if (current === mode)
107
+ return { ok: true, permissionMode: current, ...attribution() };
108
+ // Shift+Tab steps through the modes this session offers. A full lap back to
109
+ // the start (one more press than the cycle holds) means it does not offer
110
+ // the one asked for. The bound grows if the cycle turns out to include one
111
+ // more mode than the standard list (bypass).
112
+ const modes = new Set(PERMISSION_CYCLE);
113
+ for (let presses = 0;; presses++) {
114
+ if (presses >= modes.size + 1)
115
+ throw new BridgeError(422, `Claude doesn't offer ${mode} in this session.`, { permissionMode: current });
116
+ await this.assertLive(target, terminal);
117
+ await terminalProvider().sendKeys(target.server, target.pane, ["shift+tab"]);
118
+ current = await this.changed(target, terminal, current);
119
+ modes.add(current);
120
+ if (current === mode)
121
+ return { ok: true, permissionMode: current, ...attribution() };
122
+ }
123
+ }
124
+ /** The mode after a press: polled from the screen until it differs from
125
+ * `from`, because the TUI redraws the footer asynchronously. */
126
+ async changed(target, terminal, from) {
127
+ const deadline = Date.now() + this.wait;
128
+ do {
129
+ await new Promise(resolve => setTimeout(resolve, POLL_MS));
130
+ await this.assertLive(target, terminal);
131
+ const mode = claudeFooterMode(await this.hooks.paneAnsi(target).catch(() => ""));
132
+ if (mode && mode !== from)
133
+ return mode;
134
+ } while (Date.now() < deadline);
135
+ throw new BridgeError(409, "Could not verify Claude's permission mode. Open terminal to check it.");
136
+ }
137
+ async assertLive(target, terminal) {
138
+ const pane = await validateTarget(target, false, true);
139
+ if (pane.terminal_id !== terminal)
140
+ throw new BridgeError(409, "The terminal changed during the permission-mode change.");
141
+ if (pane.agent_status === "working")
142
+ throw new BridgeError(409, "The agent started working during the permission-mode change. The result is unconfirmed; check the terminal.");
143
+ }
144
+ }
@@ -28,7 +28,7 @@ import { atomic, BridgeError, bridgeRoot, id, launchEfforts, objects, PERMISSION
28
28
  import { CLAUDE_NAMES, CODEX_MODES, codexModeFlags } from "./settings-switch.js";
29
29
  /** Starting agents in Herdr from the phone: the launch route's harness
30
30
  * arguments, the conductor brief, and workspace, tab and pane actions. */
31
- const launchKinds = ["codex", "claude", "copilot", "opencode"];
31
+ const launchKinds = ["codex", "claude", "copilot", "opencode", "phren"];
32
32
  const plainText = (max) => z.string().min(1).max(max).refine(t => !/[\x00-\x1f\x7f]/.test(t));
33
33
  async function conductorBrief() {
34
34
  let source;
@@ -61,8 +61,13 @@ function effortArgs(kind, effort) {
61
61
  return ["-c", `model_reasoning_effort=${effort}`];
62
62
  if (kind === "opencode")
63
63
  return ["--variant", effort];
64
+ // phren-agent takes low to xhigh, and max as xhigh.
65
+ if (kind === "phren")
66
+ return ["--reasoning", effort === "minimal" ? "low" : effort];
64
67
  return [];
65
68
  }
69
+ /** phren's own agent runs as `phren agent`: the subcommand and its interactive TUI lead its arguments. */
70
+ const PHREN_AGENT_ARGS = ["agent", "-i"];
66
71
  async function prepareConductor(kind, effort, model) {
67
72
  const brief = await conductorBrief();
68
73
  const briefDirectory = path.join(bridgeRoot(), "conductor");
@@ -138,6 +143,7 @@ async function requireNoConductor(server, before, except) {
138
143
  }
139
144
  /** The phone names the pane's workspace and tab too; the CLI may know only the pane. */
140
145
  const paneRequest = z.object({ workspaceId: id.optional(), tabId: id.optional(), paneId: id }).strict();
146
+ const PHREN_NO_CONDUCTOR = "phren agent cannot run as a conductor: it takes no system brief at startup.";
141
147
  /** "Make conductor": the owner gives an agent already running in a pane on this computer the role. */
142
148
  export async function makeConductor(server, data) {
143
149
  const place = paneRequest.parse(data);
@@ -150,6 +156,8 @@ export async function makeConductor(server, data) {
150
156
  throw new BridgeError(409, "No agent is running in this pane.");
151
157
  if (pane.agent === "copilot")
152
158
  throw new BridgeError(400, "Copilot cannot run as a conductor.");
159
+ if (pane.agent === "phren")
160
+ throw new BridgeError(400, PHREN_NO_CONDUCTOR);
153
161
  const unchecked = await requireNoConductor(server, before, place.paneId);
154
162
  const target = await targetForPane(server, pane);
155
163
  await recordConductor(server, pane, "owner", typeof target?.session === "string" ? target.session : undefined);
@@ -239,8 +247,12 @@ export async function launchSession(server, data, options = {}) {
239
247
  throw new BridgeError(400, "OpenCode takes its permissions from its own config; permissionMode is for Claude and Codex workers.");
240
248
  if (permissionMode && kind === "copilot")
241
249
  throw new BridgeError(400, "Copilot takes its permissions from its own settings; permissionMode is for Claude and Codex workers.");
250
+ if (permissionMode && kind === "phren")
251
+ throw new BridgeError(400, "phren agent takes its permissions from its own settings; permissionMode is for Claude and Codex workers.");
242
252
  if (role === "conductor" && kind === "copilot")
243
253
  throw new BridgeError(400, "Copilot cannot run as a conductor.");
254
+ if (role === "conductor" && kind === "phren")
255
+ throw new BridgeError(400, PHREN_NO_CONDUCTOR);
244
256
  // A dispatched worker's or scheduled run's first prompt. It rides on the
245
257
  // launch where the harness takes one; elsewhere the caller types it.
246
258
  const brief = data.brief === undefined || data.brief === null ? undefined : launchBriefSchema.parse(data.brief);
@@ -257,7 +269,7 @@ export async function launchSession(server, data, options = {}) {
257
269
  const wanted = options.canary ? "phren-canary" : role === "conductor" ? (isConductorName(baseName) ? baseName : herdrAgentName(`conductor-${baseName}`))
258
270
  : isConductorName(baseName) ? herdrAgentName(`worker-${baseName}`) : baseName;
259
271
  const model = typeof data.model === "string" && data.model.trim() ? plainText(200).parse(data.model.trim()) : undefined;
260
- const modelFlag = { codex: "--model", claude: "--model", opencode: "--model" };
272
+ const modelFlag = { codex: "--model", claude: "--model", opencode: "--model", phren: "--model" };
261
273
  let workspace = data.workspaceId === undefined ? undefined : id.parse(data.workspaceId);
262
274
  // Herdr 0.9.1 refuses a start timeout of 3000 ms or less (invalid_agent_timeout).
263
275
  const timeout = Math.min(120_000, Math.max(3_001, data.timeoutMs === undefined ? 45_000 : z.number().int().parse(data.timeoutMs)));
@@ -281,7 +293,7 @@ export async function launchSession(server, data, options = {}) {
281
293
  if (conductorHere && conductorHere.workspace_id === workspace)
282
294
  workspace = undefined;
283
295
  const args = role === "conductor" ? await prepareConductor(kind, effort, model)
284
- : [...(model && modelFlag[kind] ? [modelFlag[kind], model] : []), ...(data.effort === undefined ? [] : effortArgs(kind, effort)),
296
+ : [...(kind === "phren" ? PHREN_AGENT_ARGS : []), ...(model && modelFlag[kind] ? [modelFlag[kind], model] : []), ...(data.effort === undefined ? [] : effortArgs(kind, effort)),
285
297
  ...(permissionMode && kind === "claude" ? ["--permission-mode", CLAUDE_NAMES[permissionMode]] : []), ...(permissionMode && kind === "codex" ? codexModeFlags(permissionMode) : [])];
286
298
  // A Codex worker runs on a Phren-owned app-server (codex-servers.ts): the
287
299
  // pane joins the thread the Hook started, and the brief is that thread's
@@ -2,6 +2,7 @@ import type { ServerResponse } from "node:http";
2
2
  import type { AgentHooks } from "./agent-hooks.js";
3
3
  import { type WorktreeWorker } from "./git-worktrees.js";
4
4
  import { type ModelSwitcher } from "./model-switch.js";
5
+ import { type PermissionModeSwitcher } from "./permission-mode.js";
5
6
  import type { SettingsSwitcher } from "./settings-switch.js";
6
7
  import { type Json, type Target } from "./protocol.js";
7
8
  import type { CodexQuestions } from "./questions.js";
@@ -13,6 +14,7 @@ export interface PaneRouteContext {
13
14
  agentHooks: AgentHooks;
14
15
  modelSwitcher: ModelSwitcher;
15
16
  settingsSwitcher: SettingsSwitcher;
17
+ permissionModeSwitcher: PermissionModeSwitcher;
16
18
  codexQuestions: CodexQuestions;
17
19
  sideQuestions: SideQuestions;
18
20
  }
@@ -10,6 +10,7 @@ import { agentNotReady, terminalProvider } from "./terminal.js";
10
10
  import { AppServerRpcError } from "./codex-app-server.js";
11
11
  import { CodexServerUnavailable, codexServers } from "./codex-servers.js";
12
12
  import { refuseWorkingSlash } from "./model-switch.js";
13
+ import { PERMISSION_MODE_VALUES, refuseAgentOrigin } from "./permission-mode.js";
13
14
  import { sessionWebServers } from "./session-servers.js";
14
15
  import { repositoryDiff } from "./projects.js";
15
16
  import { BridgeError, MAX_FRAME, object, objects, startingTargetSchema, targetSchema } from "./protocol.js";
@@ -255,7 +256,7 @@ export async function paneRoute(ctx, url, data, response) {
255
256
  return promptOnce.run(id, promptScope(object(data.target), String(data.text ?? "")), async (typing) => object(await paneRouteOnce(ctx, url, data, response, typing)));
256
257
  }
257
258
  export async function paneRouteOnce(ctx, url, data, response, typing) {
258
- const { agentHooks, modelSwitcher, settingsSwitcher, codexQuestions, sideQuestions } = ctx;
259
+ const { agentHooks, modelSwitcher, settingsSwitcher, permissionModeSwitcher, codexQuestions, sideQuestions } = ctx;
259
260
  let result;
260
261
  if (url.pathname === "/v1/keys" && object(data.target).starting === true) {
261
262
  // A folder-trust or login prompt comes before the agent has a
@@ -328,10 +329,11 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
328
329
  const target = targetSchema.parse(data.target);
329
330
  // Uploads store bytes without answering or interrupting the agent.
330
331
  // They still require fresh identity, just like prompt mutations.
331
- const sendsInput = ["/v1/prompt", "/v1/keys", "/v1/secret", "/v1/model", "/v1/settings"].includes(url.pathname);
332
+ const sendsInput = ["/v1/prompt", "/v1/keys", "/v1/secret", "/v1/model", "/v1/settings", "/v1/agents/permission-mode"].includes(url.pathname);
332
333
  if (sendsInput) {
333
334
  modelSwitcher.assertAvailable(target);
334
335
  settingsSwitcher.assertAvailable(target);
336
+ permissionModeSwitcher.assertAvailable(target);
335
337
  sideQuestions.assertAvailable(target);
336
338
  }
337
339
  // A key press is how a prompt the agent draws in its terminal gets
@@ -341,6 +343,7 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
341
343
  if (sendsInput) {
342
344
  modelSwitcher.assertAvailable(target);
343
345
  settingsSwitcher.assertAvailable(target);
346
+ permissionModeSwitcher.assertAvailable(target);
344
347
  sideQuestions.assertAvailable(target);
345
348
  }
346
349
  if (url.pathname === "/v1/prompt") {
@@ -483,6 +486,13 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
483
486
  else if (url.pathname === "/v1/settings") {
484
487
  result = await settingsSwitcher.switch(target, data);
485
488
  }
489
+ else if (url.pathname === "/v1/agents/permission-mode") {
490
+ // The owner's own choice from the phone: no authority ceiling applies.
491
+ // An agent's call carries its pane as `origin` and is refused, so no
492
+ // agent can raise its own or another pane's mode past its ceiling.
493
+ refuseAgentOrigin(data && typeof data === "object" && "origin" in data ? data.origin ?? null : undefined);
494
+ result = await permissionModeSwitcher.set(target, z.enum(PERMISSION_MODE_VALUES).parse(data.mode));
495
+ }
486
496
  else if (url.pathname === "/v1/keys" && await agentHooks.servedKeys(target, z.array(z.enum(ANSWER_KEYS)).min(1).max(4).parse(data.keys), String(pane.agent_status))) {
487
497
  // A served OpenCode pane: Esc aborts its turn or declines its question,
488
498
  // a digit answers its question, over its own API.
@@ -14,6 +14,7 @@ import type { CodexQuestions } from "./questions.js";
14
14
  import type { TabActivityStore } from "./tab-activity.js";
15
15
  import type { ModelCatalog } from "./models.js";
16
16
  import type { ModelSwitcher } from "./model-switch.js";
17
+ import type { PermissionModeSwitcher } from "./permission-mode.js";
17
18
  import type { SettingsSwitcher } from "./settings-switch.js";
18
19
  import type { SideQuestions } from "./side-questions.js";
19
20
  import { type AccountUsageReader } from "./usage.js";
@@ -61,6 +62,7 @@ export interface RouteContext {
61
62
  modelCatalog: ModelCatalog;
62
63
  modelSwitcher: ModelSwitcher;
63
64
  settingsSwitcher: SettingsSwitcher;
65
+ permissionModeSwitcher: PermissionModeSwitcher;
64
66
  sideQuestions: SideQuestions;
65
67
  accountUsage: AccountUsageReader;
66
68
  resources: ResourceMonitor;
@@ -177,8 +177,8 @@ export function transcriptStreams(ctx) {
177
177
  : undefined);
178
178
  // Claude's own state comes from its footer, which leads the transcript.
179
179
  const codexServed = target.source === "codex" && !!codexServers.forTarget(target);
180
- const { settings, settingsState, suggestion } = settingsSwitcher ? await settingsSwitcher.streamSettings(target, pane.terminal_id, codexServed)
181
- : { settings: settingsCapabilities(target.source, codexServed), settingsState: undefined, suggestion: undefined };
180
+ const { settings, settingsState, suggestion, permissionMode, permissionModes } = settingsSwitcher ? await settingsSwitcher.streamSettings(target, pane.terminal_id, codexServed)
181
+ : { settings: settingsCapabilities(target.source, codexServed), settingsState: undefined, suggestion: undefined, permissionMode: undefined, permissionModes: undefined };
182
182
  // Claude's suggested next prompt, only between turns. The footer
183
183
  // read can be a throttle old, so one from before a turn this
184
184
  // stream saw start is stale: the turn cleared it.
@@ -192,6 +192,9 @@ export function transcriptStreams(ctx) {
192
192
  ...(waiting && agentHooks.passwordPrompt(target) ? { passwordPrompt: true } : {}),
193
193
  compacting: agentHooks.compacting(target),
194
194
  ...(nextPrompt ? { suggestion: nextPrompt } : {}),
195
+ // The mode Claude's footer shows and the cycle its picker offers,
196
+ // only from a confident read (a Claude pane's readable footer).
197
+ ...(permissionMode ? { permissionMode, permissionModes } : {}),
195
198
  ...(historyHealth.stalled ? { historyStalled: true, historyStalledSince: historyHealth.since } : {}),
196
199
  modules: info.modules, store: info.store, profile: info.profile, generation: info.generation,
197
200
  capabilities: { ...activeCapabilities, asyncQuestions: codexQuestions.availableFor(target),
@@ -36,6 +36,7 @@ import { childAgentTree } from "./transcripts.js";
36
36
  import { ModelCatalog } from "./models.js";
37
37
  import { ModelSwitcher } from "./model-switch.js";
38
38
  import { SettingsSwitcher } from "./settings-switch.js";
39
+ import { PermissionModeSwitcher } from "./permission-mode.js";
39
40
  import { SideQuestions } from "./side-questions.js";
40
41
  import { AccountUsageReader } from "./usage.js";
41
42
  import { ResourceMonitor } from "./resources.js";
@@ -134,11 +135,12 @@ export async function serve(version, options = {}) {
134
135
  const modelCatalog = options.modelCatalog ?? new ModelCatalog();
135
136
  const modelSwitcher = new ModelSwitcher(agentHooks, modelCatalog);
136
137
  const settingsSwitcher = new SettingsSwitcher(agentHooks);
138
+ const permissionModeSwitcher = new PermissionModeSwitcher(agentHooks);
137
139
  const sideQuestions = new SideQuestions();
138
140
  const handOffs = dispatches ? new HandOffQueue({
139
141
  validate: target => validateTarget(target, false, true),
140
142
  notify: (target, text, deliveryId, computer) => handOff({ computer, target, text, deliveryId }, { notifySender: false }),
141
- send: async (target, text, deliveryId, typing) => await paneRouteOnce({ agentHooks, modelSwitcher, settingsSwitcher, codexQuestions, sideQuestions }, new URL("http://phren.local/v1/prompt"), { target, text, deliveryId, hookQueued: true }, {}, typing),
143
+ send: async (target, text, deliveryId, typing) => await paneRouteOnce({ agentHooks, modelSwitcher, settingsSwitcher, permissionModeSwitcher, codexQuestions, sideQuestions }, new URL("http://phren.local/v1/prompt"), { target, text, deliveryId, hookQueued: true }, {}, typing),
142
144
  }) : undefined;
143
145
  const contextUsage = new WorkspaceContextUsage();
144
146
  const accountUsage = options.accountUsage ?? new AccountUsageReader();
@@ -206,7 +208,7 @@ export async function serve(version, options = {}) {
206
208
  sudo: agentHooks.sudo,
207
209
  });
208
210
  const http = createServer(createRouteHandler({ version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks,
209
- journal, tabActivity, contextUsage, modelCatalog, modelSwitcher, settingsSwitcher, sideQuestions, accountUsage, resources, codexQuestions, launches, locatedDirectories,
211
+ journal, tabActivity, contextUsage, modelCatalog, modelSwitcher, settingsSwitcher, permissionModeSwitcher, sideQuestions, accountUsage, resources, codexQuestions, launches, locatedDirectories,
210
212
  fanoutMessages, canary, streams, returns, handOffs, inbox }));
211
213
  http.requestTimeout = 20_000;
212
214
  http.headersTimeout = 10_000;
@@ -1,6 +1,8 @@
1
1
  import { AgentHooks } from "./agent-hooks.js";
2
2
  import { type CodexNextTurn } from "./codex-servers.js";
3
+ import { type PermissionModeName } from "./permission-mode.js";
3
4
  import { type Json, type PermissionMode, type Target } from "./protocol.js";
5
+ export { claudeFooterMode } from "./permission-mode.js";
4
6
  /** T3's CodexSessionRuntime mapping. The reviewer is always sent: leaving it
5
7
  * out would keep `auto_review` from an earlier turn. */
6
8
  export declare const CODEX_MODES: Record<PermissionMode, Pick<CodexNextTurn, "approvalPolicy" | "approvalsReviewer" | "sandboxPolicy">>;
@@ -17,11 +19,6 @@ export interface SettingsCapabilities {
17
19
  * from its transcript, but switching is not offered. Claude's cycle holds
18
20
  * `full-access` only when it was launched allowing bypass. */
19
21
  export declare function settingsCapabilities(source: string, codexServed: boolean, claudeBypass?: boolean): SettingsCapabilities | undefined;
20
- /** Claude's permission mode from the footer line its TUI draws under the
21
- * composer. The transcript lags it: a `permission-mode` row is written only
22
- * when a prompt is submitted, and a fresh session has no file yet. The line may
23
- * trail hints ("(shift+tab to cycle) · 1 agent"), so only its start counts. */
24
- export declare function claudeFooterMode(screen: string): string | undefined;
25
22
  export interface SettingsState {
26
23
  permissionMode?: string;
27
24
  plan?: boolean;
@@ -43,6 +40,8 @@ export declare class ClaudeSettingsReader {
43
40
  text: string;
44
41
  readAt: number;
45
42
  };
43
+ permissionMode?: PermissionModeName;
44
+ permissionModes?: PermissionModeName[];
46
45
  }>;
47
46
  }
48
47
  /** One settings transaction per pane owns its terminal input until it ends. */
@@ -53,7 +52,8 @@ export declare class SettingsSwitcher {
53
52
  private readonly reader;
54
53
  constructor(hooks: AgentHooks, wait?: number);
55
54
  /** A Claude pane's footer-read settings and capabilities for the stream,
56
- * with the suggested next prompt its input box shows. */
55
+ * with the suggested next prompt its input box shows and the raw permission
56
+ * mode (`agentStatus.permissionMode`) its picker offers. */
57
57
  streamSettings(target: Target, terminal: unknown, codexServed: boolean): Promise<{
58
58
  settings?: SettingsCapabilities;
59
59
  settingsState?: SettingsState;
@@ -61,6 +61,8 @@ export declare class SettingsSwitcher {
61
61
  text: string;
62
62
  readAt: number;
63
63
  };
64
+ permissionMode?: PermissionModeName;
65
+ permissionModes?: PermissionModeName[];
64
66
  }>;
65
67
  private key;
66
68
  assertAvailable(target: Target): void;
@@ -1,15 +1,17 @@
1
1
  import { open, stat } from "node:fs/promises";
2
2
  import { z } from "zod";
3
+ import { stripTerminal } from "../terminal-text.js";
3
4
  import { visibleTerminalChoice } from "./agent-hooks.js";
4
5
  import { claudeSuggestion } from "./claude-suggestion.js";
5
6
  import { codexServers } from "./codex-servers.js";
6
7
  import { validateTarget } from "./herdr.js";
7
8
  import { intervalFromEnv } from "./limits.js";
8
9
  import { emptyComposer } from "./model-switch.js";
10
+ import { claudeFooterMode, permissionModes } from "./permission-mode.js";
9
11
  import { BridgeError, object, PERMISSION_MODES } from "./protocol.js";
10
12
  import { terminalProvider } from "./terminal.js";
11
13
  import { transcriptPath } from "./transcripts.js";
12
- import { stripTerminal } from "../terminal-text.js";
14
+ export { claudeFooterMode } from "./permission-mode.js";
13
15
  /** T3's CodexSessionRuntime mapping. The reviewer is always sent: leaving it
14
16
  * out would keep `auto_review` from an earlier turn. */
15
17
  export const CODEX_MODES = {
@@ -41,28 +43,6 @@ export function settingsCapabilities(source, codexServed, claudeBypass = false)
41
43
  }
42
44
  const request = z.object({ permissionMode: z.enum(PERMISSION_MODES).optional(), plan: z.boolean().optional(), fast: z.boolean().optional() })
43
45
  .strict().refine(value => value.permissionMode !== undefined || value.plan !== undefined || value.fast !== undefined, "Choose a setting to change.");
44
- /** Claude's permission mode from the footer line its TUI draws under the
45
- * composer. The transcript lags it: a `permission-mode` row is written only
46
- * when a prompt is submitted, and a fresh session has no file yet. The line may
47
- * trail hints ("(shift+tab to cycle) · 1 agent"), so only its start counts. */
48
- export function claudeFooterMode(screen) {
49
- for (const line of stripTerminal(screen).split(/\r?\n/).map(line => line.trim()).filter(Boolean).slice(-8).reverse()) {
50
- const text = line.replace(/^[⏵⏸]+\s*/, "");
51
- if (text === line)
52
- continue;
53
- if (/bypass permissions on/i.test(text))
54
- return "bypassPermissions";
55
- if (/^manual mode on\b/i.test(text))
56
- return "default";
57
- if (/^accept edits on\b/i.test(text))
58
- return "acceptEdits";
59
- if (/^plan mode on\b/i.test(text))
60
- return "plan";
61
- if (/^auto mode on\b/i.test(text))
62
- return "auto";
63
- }
64
- return undefined;
65
- }
66
46
  /** A Claude pane's settings as its footer shows them, read at most once per
67
47
  * `PHREN_DIALOG_THROTTLE_MS` like the dialog check, and whether bypass was
68
48
  * ever seen in it (which is when full access is offered). The same read, with
@@ -96,7 +76,10 @@ export class ClaudeSettingsReader {
96
76
  }
97
77
  const phone = entry.mode ? CLAUDE_MODES[entry.mode] : undefined;
98
78
  return { bypass: entry.bypass, ...(phone ? { state: phone === "plan" ? { plan: true } : { permissionMode: phone, plan: false } } : {}),
99
- ...(entry.suggestion ? { suggestion: { text: entry.suggestion, readAt: entry.at } } : {}) };
79
+ ...(entry.suggestion ? { suggestion: { text: entry.suggestion, readAt: entry.at } } : {}),
80
+ // The raw Claude mode the phone's mode picker shows, only when the footer
81
+ // was read: an unreadable one is not a confident "default".
82
+ ...(entry.mode ? { permissionMode: entry.mode, permissionModes: permissionModes(entry.bypass) } : {}) };
100
83
  }
101
84
  }
102
85
  /** Claude's answer to a slash command: the first `<local-command-stdout>` user
@@ -137,14 +120,16 @@ export class SettingsSwitcher {
137
120
  this.reader = new ClaudeSettingsReader(hooks);
138
121
  }
139
122
  /** A Claude pane's footer-read settings and capabilities for the stream,
140
- * with the suggested next prompt its input box shows. */
123
+ * with the suggested next prompt its input box shows and the raw permission
124
+ * mode (`agentStatus.permissionMode`) its picker offers. */
141
125
  async streamSettings(target, terminal, codexServed) {
142
126
  if (target.source !== "claude") {
143
127
  const settings = settingsCapabilities(target.source, codexServed);
144
128
  return settings ? { settings } : {};
145
129
  }
146
- const { state, bypass, suggestion } = await this.reader.read(target, terminal);
147
- return { settings: settingsCapabilities("claude", false, bypass), ...(state ? { settingsState: state } : {}), ...(suggestion ? { suggestion } : {}) };
130
+ const { state, bypass, suggestion, permissionMode, permissionModes } = await this.reader.read(target, terminal);
131
+ return { settings: settingsCapabilities("claude", false, bypass), ...(state ? { settingsState: state } : {}), ...(suggestion ? { suggestion } : {}),
132
+ ...(permissionMode ? { permissionMode, permissionModes } : {}) };
148
133
  }
149
134
  key(target) { return `${target.server}:${target.pane}`; }
150
135
  assertAvailable(target) {
@@ -1,5 +1,12 @@
1
1
  import { type Json } from "./protocol.js";
2
2
  import type { TerminalPane, TerminalProvider } from "./terminal.js";
3
+ /** Who reports phren-agent's lifecycle to Herdr, which does not detect it itself. */
4
+ export declare const PHREN_REPORT_SOURCE = "phren-hook";
5
+ /** A word for a POSIX shell, quoted only when it needs it. */
6
+ export declare function shellWord(word: string): string;
7
+ /** What the Hook types into a Herdr pane's shell to start phren-agent:
8
+ * the agent, then Herdr's report of it released once it exits. */
9
+ export declare function phrenCommandLine(args: string[]): string;
3
10
  /** A Herdr snapshot's panes in the provider's shape; Herdr's agent report becomes hints. */
4
11
  export declare function herdrPanes(server: string, s: Json): TerminalPane[];
5
12
  export declare const herdrTerminal: TerminalProvider;