@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.
@@ -3,8 +3,55 @@
3
3
  // fake, so a test that records Herdr requests sees exactly what it did before
4
4
  // the provider existed.
5
5
  import { herdrSocketPath, rpc, snapshot } from "./herdr.js";
6
- import { object, objects } from "./protocol.js";
6
+ import { BridgeError, object, objects } from "./protocol.js";
7
+ import { agentFromCommand } from "./terminal-tmux.js";
7
8
  const text = (value) => typeof value === "string" && value ? value : undefined;
9
+ /** Who reports phren-agent's lifecycle to Herdr, which does not detect it itself. */
10
+ export const PHREN_REPORT_SOURCE = "phren-hook";
11
+ /** A word for a POSIX shell, quoted only when it needs it. */
12
+ export function shellWord(word) {
13
+ return /^[A-Za-z0-9_./:=@%+,-]+$/.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`;
14
+ }
15
+ /** What the Hook types into a Herdr pane's shell to start phren-agent:
16
+ * the agent, then Herdr's report of it released once it exits. */
17
+ export function phrenCommandLine(args) {
18
+ return [["phren", ...args].map(shellWord).join(" "),
19
+ `herdr pane release-agent "$HERDR_PANE_ID" --source ${PHREN_REPORT_SOURCE} --agent phren >/dev/null 2>&1`].join("; ");
20
+ }
21
+ /** Whether `pane` runs phren-agent as Herdr reports it, for the prompt and key fallbacks below. */
22
+ async function reportedPhren(server, pane) {
23
+ const info = object((await rpc(server, "pane.get", { pane_id: pane }).catch(() => ({}))).pane);
24
+ return info.agent === "phren";
25
+ }
26
+ /** Herdr's `agent.prompt` and `agent.send_keys` take only agents it started;
27
+ * a phren-agent pane it knows by report gets the pane calls instead. */
28
+ function unnamedAgent(error) {
29
+ return error instanceof BridgeError && error.details?.herdrCode === "agent_not_ready" && /not an active named agent/.test(error.message);
30
+ }
31
+ /** Herdr's `agent.start` knows a fixed list of harnesses and phren-agent is
32
+ * not on it. The Hook types `phren agent ...` at the pane's login shell
33
+ * instead, waits for it to be the foreground program, then reports it to
34
+ * Herdr as agent "phren" under the launch name, so the pane reads as an agent
35
+ * like the others. Its own lifecycle hooks keep the status (agent-hooks.ts). */
36
+ async function startPhren(server, pane, { name, args, timeoutMs }) {
37
+ const before = object((await rpc(server, "pane.process_info", { pane_id: pane })).process_info);
38
+ // Same refusal as Herdr's own start, so the caller waits for the shell.
39
+ if (!Number.isSafeInteger(before.shell_pid) || before.foreground_process_group_id !== before.shell_pid)
40
+ throw new BridgeError(409, `Herdr: agent target pane ${pane} is not an available shell`, { herdrCode: "agent_pane_busy" });
41
+ await rpc(server, "pane.send_text", { pane_id: pane, text: phrenCommandLine(args) });
42
+ await rpc(server, "pane.send_keys", { pane_id: pane, keys: ["Enter"] });
43
+ const deadline = Date.now() + Math.min(timeoutMs, 30_000);
44
+ for (;;) {
45
+ const info = object((await rpc(server, "pane.process_info", { pane_id: pane })).process_info);
46
+ if (objects(info.foreground_processes).some(p => typeof p.cmdline === "string" && agentFromCommand(p.cmdline) === "phren"))
47
+ break;
48
+ if (Date.now() >= deadline)
49
+ throw new BridgeError(504, "phren agent did not start in the Herdr pane. Check that phren and @phren/agent are installed on the login shell's PATH.");
50
+ await new Promise(resolve => setTimeout(resolve, 250));
51
+ }
52
+ await rpc(server, "pane.report_agent", { pane_id: pane, source: PHREN_REPORT_SOURCE, agent: "phren", state: "idle" });
53
+ await rpc(server, "agent.rename", { target: pane, name }).catch(() => undefined);
54
+ }
8
55
  /** A Herdr snapshot's panes in the provider's shape; Herdr's agent report becomes hints. */
9
56
  export function herdrPanes(server, s) {
10
57
  return objects(s.panes).filter(p => typeof p.pane_id === "string" && typeof p.tab_id === "string" && typeof p.workspace_id === "string").map(p => {
@@ -36,18 +83,42 @@ export const herdrTerminal = {
36
83
  const answer = object(result.read ?? result);
37
84
  return typeof answer.text === "string" ? answer.text : "";
38
85
  },
39
- async sendKeys(server, pane, keys) { await rpc(server, "agent.send_keys", { target: pane, keys }); },
86
+ async sendKeys(server, pane, keys) {
87
+ try {
88
+ await rpc(server, "agent.send_keys", { target: pane, keys });
89
+ }
90
+ catch (error) {
91
+ if (!unnamedAgent(error) || !await reportedPhren(server, pane))
92
+ throw error;
93
+ await rpc(server, "pane.send_keys", { pane_id: pane, keys });
94
+ }
95
+ },
40
96
  async prompt(server, pane, text, signal) {
41
- if (signal)
42
- await rpc(server, "agent.prompt", { target: pane, text }, signal);
43
- else
44
- await rpc(server, "agent.prompt", { target: pane, text });
97
+ try {
98
+ if (signal)
99
+ await rpc(server, "agent.prompt", { target: pane, text }, signal);
100
+ else
101
+ await rpc(server, "agent.prompt", { target: pane, text });
102
+ }
103
+ catch (error) {
104
+ if (!unnamedAgent(error) || !await reportedPhren(server, pane))
105
+ throw error;
106
+ // One bracketed paste keeps the newlines in phren-agent's composer; Enter submits it.
107
+ await rpc(server, "pane.send_text", { pane_id: pane, text: `\x1b[200~${text}\x1b[201~` }, signal);
108
+ await new Promise(resolve => setTimeout(resolve, 150));
109
+ await rpc(server, "pane.send_keys", { pane_id: pane, keys: ["Enter"] }, signal);
110
+ }
45
111
  },
46
112
  async create(server, { workspace, label, cwd, env }) {
47
113
  await rpc(server, workspace ? "tab.create" : "workspace.create", { workspace_id: workspace, label, cwd, focus: false, env: env ?? {} });
48
114
  },
49
115
  // `agent.start` takes no environment; the pane's shell got it at `create`.
50
- async startAgent(server, pane, { name, kind, args, timeoutMs }) {
116
+ async startAgent(server, pane, agent) {
117
+ const { name, kind, args, timeoutMs } = agent;
118
+ if (kind === "phren") {
119
+ await startPhren(server, pane, agent);
120
+ return;
121
+ }
51
122
  // Herdr waits up to `timeout_ms` for the agent to become ready; the socket waits a little longer.
52
123
  await rpc(server, "agent.start", { name, kind, pane_id: pane, timeout_ms: timeoutMs, ...(args.length ? { args } : {}) }, undefined, timeoutMs + 5_000);
53
124
  },
@@ -55,6 +126,9 @@ export const herdrTerminal = {
55
126
  paneEnv(server, { workspace, tab, pane }) {
56
127
  return { HERDR_ENV: "1", HERDR_SOCKET_PATH: herdrSocketPath(server), HERDR_WORKSPACE_ID: workspace, HERDR_TAB_ID: tab, HERDR_PANE_ID: pane };
57
128
  },
129
+ async reportAgent(server, pane, agent, state) {
130
+ await rpc(server, "pane.report_agent", { pane_id: pane, source: PHREN_REPORT_SOURCE, agent, state });
131
+ },
58
132
  async focusPane(server, pane) { await rpc(server, "pane.focus", { pane_id: pane }); },
59
133
  async closePane(server, pane) { await rpc(server, "pane.close", { pane_id: pane }); },
60
134
  async renamePane(server, pane, label) { await rpc(server, "pane.rename", { pane_id: pane, label }); },
@@ -208,7 +208,7 @@ export function agentFromCommand(command) {
208
208
  return "phren";
209
209
  // `phren agent` runs the same agent through the CLI.
210
210
  const next = words[words.indexOf(program) + 1];
211
- if ((name === "phren" || program.includes("@phren/cli/")) && next === "agent")
211
+ if ((name === "phren" || program.includes("@phren/cli/") || /\/packages\/cli\/dist\/index\.js$/.test(program)) && next === "agent")
212
212
  return "phren";
213
213
  return undefined;
214
214
  }
@@ -437,7 +437,7 @@ export const tmuxTerminal = {
437
437
  await tmux(server, ["new-session", "-d", "-s", sessionName(label, taken), "-x", "200", "-y", "50", ...directory, ...name]);
438
438
  },
439
439
  async startAgent(server, pane, { name, kind, args, timeoutMs, env }) {
440
- if (!["claude", "codex", "copilot", "opencode"].includes(kind))
440
+ if (!["claude", "codex", "copilot", "opencode", "phren"].includes(kind))
441
441
  throw new BridgeError(400, "This agent cannot be started in tmux.");
442
442
  await requireDirectExec();
443
443
  const target = toTmuxId(pane, "p"), row = await paneRow(server, target);
@@ -109,6 +109,9 @@ export interface TerminalProvider {
109
109
  tab: string;
110
110
  pane: string;
111
111
  }): Record<string, string> | undefined;
112
+ /** Tells a multiplexer that watches its agents what one it cannot detect
113
+ * (phren-agent in Herdr) is doing. Absent where the Hook keeps that itself (tmux). */
114
+ reportAgent?(server: string, pane: string, agent: string, state: "idle" | "working" | "blocked"): Promise<void>;
112
115
  focusPane(server: string, pane: string): Promise<void>;
113
116
  /** Sets the pane's own label (Herdr's pane label, a tmux pane option), shown by the Hook as the session's name. */
114
117
  closePane(server: string, pane: string): Promise<void>;
@@ -52,6 +52,7 @@ export const routedTerminal = {
52
52
  create: (server, placement) => route(server).create(server, placement),
53
53
  startAgent: (server, pane, agent) => route(server).startAgent(server, pane, agent),
54
54
  paneEnv: (server, place) => route(server).paneEnv?.(server, place),
55
+ reportAgent: async (server, pane, agent, state) => { await route(server).reportAgent?.(server, pane, agent, state); },
55
56
  focusPane: (server, pane) => route(server).focusPane(server, pane),
56
57
  closePane: (server, pane) => route(server).closePane(server, pane),
57
58
  renamePane: (server, pane, label) => route(server).renamePane(server, pane, label),
@@ -107,7 +107,7 @@ export async function dispatch(command) {
107
107
  }
108
108
  // Without Herdr: a login shell, or one agent, in a validated project folder
109
109
  // on the SSH PTY itself. Nothing persists after the phone disconnects.
110
- const shell = /^phren-hook v1 shell ([A-Za-z0-9_-]{1,8192})(?: (codex|claude|copilot|opencode))?$/.exec(command);
110
+ const shell = /^phren-hook v1 shell ([A-Za-z0-9_-]{1,8192})(?: (codex|claude|copilot|opencode|phren))?$/.exec(command);
111
111
  if (shell && shell[0] === command) {
112
112
  requireHook();
113
113
  const raw = decodeShellDirectory(shell[1]);
@@ -117,8 +117,9 @@ export async function dispatch(command) {
117
117
  if (!process.stdin.isTTY || !process.stdout.isTTY)
118
118
  throw new Error("Request an SSH terminal first.");
119
119
  const login = process.env.SHELL && path.isAbsolute(process.env.SHELL) ? process.env.SHELL : "/bin/sh";
120
- const [file, args] = shell[2] ? [shell[2], []] : [login, ["-l"]];
121
- await attach(file, args, { cwd, env: shellEnvironment() }, shell[2] ? `${shell[2]} exited.` : "The shell exited.");
120
+ // phren's own agent is the `phren agent` subcommand, in its interactive TUI.
121
+ const [file, args] = shell[2] === "phren" ? ["phren", ["agent", "-i"]] : shell[2] ? [shell[2], []] : [login, ["-l"]];
122
+ await attach(file, args, { cwd, env: shellEnvironment() }, shell[2] === "phren" ? "phren agent exited." : shell[2] ? `${shell[2]} exited.` : "The shell exited.");
122
123
  return;
123
124
  }
124
125
  const terminal = /^phren-hook v1 terminal ([A-Za-z0-9_.-]{1,100})$/.exec(command);