@phren/cli 0.3.3 → 0.3.5

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 (71) hide show
  1. package/dist/bridge/agent-hooks.d.ts +6 -0
  2. package/dist/bridge/agent-hooks.js +66 -25
  3. package/dist/bridge/canary.d.ts +4 -0
  4. package/dist/bridge/canary.js +17 -4
  5. package/dist/bridge/changes.d.ts +7 -0
  6. package/dist/bridge/changes.js +6 -1
  7. package/dist/bridge/client.js +2 -1
  8. package/dist/bridge/command.js +7 -5
  9. package/dist/bridge/conductor-group.d.ts +1 -0
  10. package/dist/bridge/conductor-group.js +4 -3
  11. package/dist/bridge/dispatch-command.js +2 -2
  12. package/dist/bridge/fanouts.js +6 -2
  13. package/dist/bridge/hand-off.d.ts +1 -0
  14. package/dist/bridge/hand-off.js +3 -2
  15. package/dist/bridge/harness-status.d.ts +12 -0
  16. package/dist/bridge/harness-status.js +153 -0
  17. package/dist/bridge/health.d.ts +18 -0
  18. package/dist/bridge/health.js +30 -4
  19. package/dist/bridge/herdr.d.ts +6 -0
  20. package/dist/bridge/herdr.js +62 -8
  21. package/dist/bridge/install.js +4 -0
  22. package/dist/bridge/model-switch.d.ts +4 -1
  23. package/dist/bridge/model-switch.js +12 -7
  24. package/dist/bridge/models.js +3 -2
  25. package/dist/bridge/pane-status.d.ts +37 -0
  26. package/dist/bridge/pane-status.js +139 -0
  27. package/dist/bridge/pane-text.d.ts +3 -11
  28. package/dist/bridge/pane-text.js +9 -16
  29. package/dist/bridge/peers.js +9 -6
  30. package/dist/bridge/prompt-once.d.ts +26 -0
  31. package/dist/bridge/prompt-once.js +69 -0
  32. package/dist/bridge/protocol.d.ts +10 -0
  33. package/dist/bridge/protocol.js +10 -0
  34. package/dist/bridge/schedule-format.d.ts +2 -0
  35. package/dist/bridge/schedule-launch.d.ts +10 -1
  36. package/dist/bridge/schedule-launch.js +29 -3
  37. package/dist/bridge/schedule-watch.js +1 -1
  38. package/dist/bridge/schedules.d.ts +10 -0
  39. package/dist/bridge/schedules.js +40 -0
  40. package/dist/bridge/server-launch.js +12 -10
  41. package/dist/bridge/server-pane-routes.js +23 -9
  42. package/dist/bridge/server-routes.d.ts +1 -0
  43. package/dist/bridge/server-routes.js +1 -1
  44. package/dist/bridge/session-servers.js +5 -6
  45. package/dist/bridge/side-questions.js +6 -5
  46. package/dist/bridge/terminal-choice.d.ts +12 -5
  47. package/dist/bridge/terminal-choice.js +66 -0
  48. package/dist/bridge/terminal-herdr.d.ts +5 -0
  49. package/dist/bridge/terminal-herdr.js +57 -0
  50. package/dist/bridge/terminal-tmux.d.ts +111 -0
  51. package/dist/bridge/terminal-tmux.js +549 -0
  52. package/dist/bridge/terminal.d.ts +119 -0
  53. package/dist/bridge/terminal.js +66 -0
  54. package/dist/bridge/transcript-claude.d.ts +6 -0
  55. package/dist/bridge/transcript-claude.js +20 -0
  56. package/dist/bridge/transcript-opencode.js +1 -1
  57. package/dist/bridge/transcript-preview.d.ts +5 -0
  58. package/dist/bridge/transcript-preview.js +52 -2
  59. package/dist/bridge/transport.js +10 -4
  60. package/dist/bridge-hook.mjs +4852 -3391
  61. package/dist/cli-registry.js +7 -0
  62. package/dist/entrypoint.js +2 -1
  63. package/dist/init/init.js +4 -0
  64. package/dist/link/doctor.js +33 -30
  65. package/dist/modules/agent-package.d.ts +35 -0
  66. package/dist/modules/agent-package.js +133 -0
  67. package/dist/modules/registry.js +2 -2
  68. package/dist/session/utils.js +1 -1
  69. package/dist/tools/dispatch.js +2 -2
  70. package/package.json +1 -1
  71. package/plugins/opencode/phren-transcript.js +97 -6
@@ -15,12 +15,19 @@ export interface TerminalChoice {
15
15
  options: TerminalChoiceOption[];
16
16
  highlightedIndex?: number;
17
17
  }
18
- /** The question a pane's terminal lines are asking, in the same shape a held
19
- * permission request carries: every non-empty line above the first numbered
20
- * row (the "$ command" line included, the "Press enter" hint dropped), joined
21
- * with newlines, then one option per row. Keyless rows require exactly one
22
- * readable cursor so the Hook can navigate without confirming another row. */
18
+ export declare function unframed(text: string): string;
23
19
  export declare function visibleTerminalChoice(text: string): TerminalChoice | undefined;
20
+ /** OpenCode's permission prompt, read from the pane with its colors:
21
+ * "△ Permission required", what it asks, then one row "Allow once Allow
22
+ * always Reject" answered with ←/→ and Enter (Escape rejects). The row's
23
+ * selected option is the one drawn on a background the others don't share.
24
+ * The phone gets Allow once and Reject: Allow always opens OpenCode's own
25
+ * second confirmation. `selected` is the cursor's index in the three-option
26
+ * row; undefined when the colors do not say. */
27
+ export declare function opencodePermissionDialog(ansi: string): {
28
+ choice: TerminalChoice;
29
+ selected?: number;
30
+ } | undefined;
24
31
  /** The pane's last non-empty line is a password read: sudo's "[sudo] password
25
32
  * for user", or any "… Password:" prompt. */
26
33
  export declare function passwordLine(text: string): boolean;
@@ -1,5 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { BridgeError, object, objects } from "./protocol.js";
3
+ import { stripTerminal } from "../terminal-text.js";
3
4
  /** Reading the question a terminal dialog or held permission is asking:
4
5
  * numbered option rows, the highlighted row, password reads, and a released
5
6
  * AskUserQuestion's questions and answers. Pure functions over text and input. */
@@ -92,7 +93,35 @@ function numberedOptions(text) {
92
93
  * row (the "$ command" line included, the "Press enter" hint dropped), joined
93
94
  * with newlines, then one option per row. Keyless rows require exactly one
94
95
  * readable cursor so the Hook can navigate without confirming another row. */
96
+ /** Copilot CLI draws each select inside a box, so its rows read
97
+ * "│ ❯ 1. Yes │". Strip the frame (nested boxes too) so rows and the
98
+ * question read as bare lines. Inside a box the blank and border lines go,
99
+ * so the box's whole body (title, command, question) is one block above its
100
+ * options; the box's own edges become the blank lines around it. Text with
101
+ * no framed line passes through unchanged. */
102
+ const BAR = "│┃║";
103
+ const framed = new RegExp(`^\\s*[${BAR}] ?(.*?)\\s*[${BAR}]\\s*$`);
104
+ const border = /^[\s╭╮╰╯┌┐└┘├┤─━═│┃║]*$/;
105
+ export function unframed(text) {
106
+ let lines = text.split(/\r?\n/);
107
+ // Copilot's scrollbar: a "┃" closing most lines once the chat overflows.
108
+ const filled = lines.filter(line => line.trim());
109
+ if (filled.length && filled.filter(line => /┃\s*$/.test(line)).length * 2 > filled.length) {
110
+ lines = lines.map(line => line.replace(/\s*┃\s*$/, ""));
111
+ }
112
+ if (!lines.some(line => framed.test(line)))
113
+ return lines.join("\n");
114
+ return lines.flatMap(line => {
115
+ if (!framed.test(line))
116
+ return [border.test(line) ? "" : line];
117
+ let inner = line, match;
118
+ while ((match = framed.exec(inner)))
119
+ inner = match[1];
120
+ return border.test(inner) ? [] : [inner];
121
+ }).join("\n");
122
+ }
95
123
  export function visibleTerminalChoice(text) {
124
+ text = unframed(text);
96
125
  const parsed = numberedOptions(text);
97
126
  const highlights = parsed.flatMap((option, index) => option.highlighted ? [index] : []);
98
127
  const highlightedIndex = highlights.length === 1 ? highlights[0] : undefined;
@@ -121,6 +150,42 @@ export function visibleTerminalChoice(text) {
121
150
  return { title: title.slice(0, 4_000), options: options.slice(0, 12),
122
151
  ...(highlightedIndex !== undefined ? { highlightedIndex } : {}) };
123
152
  }
153
+ const OPENCODE_OPTIONS = ["Allow once", "Allow always", "Reject"];
154
+ /** OpenCode's permission prompt, read from the pane with its colors:
155
+ * "△ Permission required", what it asks, then one row "Allow once Allow
156
+ * always Reject" answered with ←/→ and Enter (Escape rejects). The row's
157
+ * selected option is the one drawn on a background the others don't share.
158
+ * The phone gets Allow once and Reject: Allow always opens OpenCode's own
159
+ * second confirmation. `selected` is the cursor's index in the three-option
160
+ * row; undefined when the colors do not say. */
161
+ export function opencodePermissionDialog(ansi) {
162
+ const raw = ansi.split(/\r?\n/);
163
+ const plain = raw.map(line => stripTerminal(line).replace(/\r/g, ""));
164
+ const content = (line) => line.replace(/^\s*[┃│]?/, "");
165
+ let header = -1;
166
+ plain.forEach((line, index) => { if (/^\s*△\s*Permission required\s*$/.test(content(line)))
167
+ header = index; });
168
+ if (header < 0)
169
+ return undefined;
170
+ const row = plain.findIndex((line, index) => index > header && OPENCODE_OPTIONS.every(label => line.includes(label)));
171
+ if (row < 0 || row - header > 24)
172
+ return undefined;
173
+ // Lines pushed far right are OpenCode's status column, not the question.
174
+ const body = plain.slice(header + 1, row).map(content)
175
+ .filter(line => line.trim() && !/^\s{24,}/.test(line)).map(line => line.trim());
176
+ const title = ["Permission required", ...body].join("\n").slice(0, 4_000);
177
+ const backgrounds = OPENCODE_OPTIONS.map(label => {
178
+ const at = raw[row].indexOf(label);
179
+ if (at < 0)
180
+ return undefined;
181
+ const before = [...raw[row].slice(0, at).matchAll(/\x1b\[[0-9;]*48;2;(\d+;\d+;\d+)[0-9;]*m/g)];
182
+ return before.at(-1)?.[1];
183
+ });
184
+ const unique = backgrounds.flatMap((background, index) => background !== undefined && backgrounds.filter(other => other === background).length === 1 ? [index] : []);
185
+ const selected = unique.length === 1 && backgrounds.every(background => background !== undefined) ? unique[0] : undefined;
186
+ return { choice: { title, options: [{ label: "Allow once", key: "1", hasKey: false }, { label: "Reject", key: "Escape", hasKey: true }],
187
+ ...(selected === 0 ? { highlightedIndex: 0 } : {}) }, ...(selected !== undefined ? { selected } : {}) };
188
+ }
124
189
  /** The pane's last non-empty line is a password read: sudo's "[sudo] password
125
190
  * for user", or any "… Password:" prompt. */
126
191
  export function passwordLine(text) {
@@ -136,6 +201,7 @@ export function passwordLine(text) {
136
201
  * " · ", and a footer offering "Esc to cancel" gains the Escape option.
137
202
  * Undefined without two numbered rows and a question. */
138
203
  export function numberedDialog(text) {
204
+ text = unframed(text);
139
205
  const row = /^\s*[>❯›▸▶»•*]?\s*(\d+)\.\s+(.+?)\s*$/;
140
206
  const lines = text.split(/\r?\n/);
141
207
  const first = lines.findIndex(line => row.test(line));
@@ -0,0 +1,5 @@
1
+ import { type Json } from "./protocol.js";
2
+ import type { TerminalPane, TerminalProvider } from "./terminal.js";
3
+ /** A Herdr snapshot's panes in the provider's shape; Herdr's agent report becomes hints. */
4
+ export declare function herdrPanes(server: string, s: Json): TerminalPane[];
5
+ export declare const herdrTerminal: TerminalProvider;
@@ -0,0 +1,57 @@
1
+ // Herdr as the Hook's terminal provider: each method is one call on Herdr's
2
+ // socket API. It calls herdr.ts's exported `rpc`, the seam the bridge tests
3
+ // fake, so a test that records Herdr requests sees exactly what it did before
4
+ // the provider existed.
5
+ import { rpc, snapshot } from "./herdr.js";
6
+ import { object, objects } from "./protocol.js";
7
+ const text = (value) => typeof value === "string" && value ? value : undefined;
8
+ /** A Herdr snapshot's panes in the provider's shape; Herdr's agent report becomes hints. */
9
+ export function herdrPanes(server, s) {
10
+ return objects(s.panes).filter(p => typeof p.pane_id === "string" && typeof p.tab_id === "string" && typeof p.workspace_id === "string").map(p => {
11
+ const reported = object(p.agent_session);
12
+ const session = reported.kind === "id" && reported.agent === p.agent ? text(reported.value) : undefined;
13
+ const hints = { agent: text(p.agent), status: text(p.agent_status), session };
14
+ return { server, workspace: String(p.workspace_id), tab: String(p.tab_id), pane: String(p.pane_id),
15
+ cwd: text(p.foreground_cwd) ?? text(p.cwd), title: text(p.title) ?? text(p.terminal_title_stripped), label: text(p.label),
16
+ ...(hints.agent || hints.status || hints.session ? { hints } : {}) };
17
+ });
18
+ }
19
+ export const herdrTerminal = {
20
+ kind: "herdr",
21
+ async ping(server) { await rpc(server, "ping"); },
22
+ async snapshot(server) { return object((await rpc(server, "session.snapshot")).snapshot); },
23
+ async listPanes(server) { return herdrPanes(server, await snapshot(server)); },
24
+ async processes(server, pane) {
25
+ const info = object((await rpc(server, "pane.process_info", { pane_id: pane })).process_info);
26
+ return { ...(Number.isSafeInteger(info.shell_pid) ? { shellPid: Number(info.shell_pid) } : {}),
27
+ foregroundPids: objects(info.foreground_processes).map(p => p.pid).filter((p) => Number.isSafeInteger(p)) };
28
+ },
29
+ async readScreen(server, pane, read) {
30
+ const params = { ...(read.scope === "agent" ? { target: pane } : { pane_id: pane }),
31
+ source: read.source, lines: read.lines, strip_ansi: read.stripAnsi ?? true,
32
+ // Herdr 0.9 answers plain text whatever `strip_ansi` says; "ansi" keeps the styles.
33
+ ...(read.format ? { format: read.format } : {}) };
34
+ // `pane.read` and `agent.read` both answer with a `read` object carrying the text.
35
+ const result = await rpc(server, read.scope === "agent" ? "agent.read" : "pane.read", params, undefined, read.timeoutMs);
36
+ const answer = object(result.read ?? result);
37
+ return typeof answer.text === "string" ? answer.text : "";
38
+ },
39
+ async sendKeys(server, pane, keys) { await rpc(server, "agent.send_keys", { target: pane, keys }); },
40
+ 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 });
45
+ },
46
+ async create(server, { workspace, label, cwd }) {
47
+ await rpc(server, workspace ? "tab.create" : "workspace.create", { workspace_id: workspace, label, cwd, focus: false, env: {} });
48
+ },
49
+ async startAgent(server, pane, { name, kind, args, timeoutMs }) {
50
+ // Herdr waits up to `timeout_ms` for the agent to become ready; the socket waits a little longer.
51
+ await rpc(server, "agent.start", { name, kind, pane_id: pane, timeout_ms: timeoutMs, ...(args.length ? { args } : {}) }, undefined, timeoutMs + 5_000);
52
+ },
53
+ async focusPane(server, pane) { await rpc(server, "pane.focus", { pane_id: pane }); },
54
+ async groupAction(server, operation, { workspace, tab }, label) {
55
+ await rpc(server, `${tab ? "tab" : "workspace"}.${operation}`, { ...(tab ? { tab_id: tab } : { workspace_id: workspace }), ...(label ? { label } : {}) });
56
+ },
57
+ };
@@ -0,0 +1,111 @@
1
+ import { type Json } from "./protocol.js";
2
+ import type { TerminalProvider } from "./terminal.js";
3
+ /** The owner's own tmux server (the default socket). */
4
+ export declare const TMUX_DEFAULT = "tmux";
5
+ /** The hidden server phone-started agents run in: `tmux -L phren`. */
6
+ export declare const TMUX_HIDDEN = "tmux-phren";
7
+ /** The tmux socket name (`-L`) a Hook server name stands for: "tmux" is the
8
+ * default socket and "tmux-<name>" the socket `<name>`. */
9
+ export declare function tmuxSocketName(server: string): string | undefined;
10
+ /** The Hook server name for a tmux socket name. */
11
+ export declare function tmuxServerName(socket: string): string | undefined;
12
+ /** Runs tmux with `args` (after the socket flags) and answers its stdout. */
13
+ export type TmuxRunner = (args: string[], options?: {
14
+ input?: string;
15
+ timeoutMs?: number;
16
+ signal?: AbortSignal;
17
+ }) => Promise<string>;
18
+ interface TmuxDeps {
19
+ /** The tmux executable, or undefined when this computer has none. */
20
+ binary: () => string | undefined;
21
+ run: (socket: string, args: string[], options?: {
22
+ input?: string;
23
+ timeoutMs?: number;
24
+ signal?: AbortSignal;
25
+ }) => Promise<string>;
26
+ /** `ps` rows: pid, process group, terminal's foreground group, terminal, command line. */
27
+ processes: () => Promise<string>;
28
+ /** `tmux -V`. */
29
+ version: () => Promise<string>;
30
+ /** The names of the tmux sockets this user has, whether or not they answer. */
31
+ sockets: () => Promise<string[]>;
32
+ sleep: (ms: number, signal?: AbortSignal) => Promise<void>;
33
+ }
34
+ /** The tmux on PATH or in the usual install folders; the Hook's service
35
+ * PATH can be shorter than a login shell's. Rechecked every minute. */
36
+ export declare function tmuxBinary(): string | undefined;
37
+ /** The folders this user's tmux sockets live in: `$TMUX_TMPDIR/tmux-<uid>`,
38
+ * where `-L` looks, then `/tmp/tmux-<uid>` when TMUX_TMPDIR points elsewhere
39
+ * (a server started from a shell with another TMUX_TMPDIR than the Hook's). */
40
+ export declare function tmuxSocketFolders(env?: NodeJS.ProcessEnv): string[];
41
+ /** The tmux sockets in `folder` this user owns, by name (at most 32). A socket
42
+ * outside the first folder of `tmuxSocketFolders` is remembered by path. */
43
+ export declare function tmuxSocketsIn(folder: string): Promise<string[]>;
44
+ /** For tests: replace how tmux and ps run; the returned function restores them. */
45
+ export declare function setTmuxDeps(replacement: Partial<TmuxDeps>): () => void;
46
+ declare const SIGILS: {
47
+ readonly s: "$";
48
+ readonly w: "@";
49
+ readonly p: "%";
50
+ };
51
+ export declare function fromTmuxId(value: string): string | undefined;
52
+ export declare function toTmuxId(value: string, kind: keyof typeof SIGILS): string;
53
+ /** The agent a command line runs, by the harness's executable or package. */
54
+ export declare function agentFromCommand(command: string): string | undefined;
55
+ interface Proc {
56
+ pid: number;
57
+ pgid: number;
58
+ tpgid: number;
59
+ tty: string;
60
+ args: string;
61
+ }
62
+ export declare function parseProcesses(text: string): Proc[];
63
+ declare const FIELDS: readonly ["session_id", "session_name", "session_attached", "session_activity", "window_id", "window_name", "window_active", "pane_id", "pane_pid", "pane_tty", "pane_active", "pane_current_path", "pane_current_command", "@phren_agent", "pane_title"];
64
+ type Row = Record<(typeof FIELDS)[number], string>;
65
+ export declare function parsePanes(text: string): Row[];
66
+ /** One tmux server in the shape of the Hook's pane snapshot (the shape
67
+ * Herdr's `session.snapshot` answers): workspaces are tmux sessions, tabs
68
+ * windows, panes panes. */
69
+ export declare function tmuxSnapshot(server: string): Promise<Json>;
70
+ /** The Hook's key names as tmux key names; undefined for a literal character. */
71
+ export declare function tmuxKey(key: string): string | undefined;
72
+ /** send-keys calls for `keys`, in order: named keys together, literal characters with -l. */
73
+ export declare function sendKeysCalls(pane: string, keys: string[]): string[][];
74
+ export declare const tmuxTerminal: TerminalProvider;
75
+ /** The tmux servers the Hook drives, as `/v1/muxes` lists servers: the owner's
76
+ * servers that answer, and the hidden server whenever tmux is installed (a
77
+ * launch starts it). `kind` stays "herdr", the phone's name for the Hook's
78
+ * session protocol; `terminal` names the multiplexer. */
79
+ export declare function tmuxServers(): Promise<Json[]>;
80
+ /** What `phren bridge doctor` and the health details say about tmux. */
81
+ export interface TmuxHealth {
82
+ /** "off" when PHREN_TMUX=off, "missing" without a tmux executable. */
83
+ state: "ok" | "off" | "missing";
84
+ version?: string;
85
+ /** Whether this tmux can start agents (3.0 and later). */
86
+ launches?: boolean;
87
+ /** The owner's servers that answer, by Hook server name. */
88
+ servers?: string[];
89
+ /** The hidden server phone launches use: running with its session count, or not started yet. */
90
+ hidden?: {
91
+ running: boolean;
92
+ sessions?: number;
93
+ };
94
+ }
95
+ export declare function tmuxHealth(): Promise<TmuxHealth>;
96
+ /** The tmux pane this process runs in, from the variables tmux sets in every
97
+ * pane, with its session and window asked of that server. */
98
+ export declare function tmuxPaneFromEnv(env?: NodeJS.ProcessEnv): Promise<{
99
+ server: string;
100
+ workspace: string;
101
+ tab: string;
102
+ pane: string;
103
+ } | undefined>;
104
+ /** The command that attaches the phone's SSH terminal to a tmux server. */
105
+ export declare function tmuxAttach(server: string): {
106
+ file: string;
107
+ args: string[];
108
+ };
109
+ /** For tests: forget the tmux executable lookup and the sockets found by path. */
110
+ export declare function resetTmuxBinary(): void;
111
+ export {};