@phren/cli 0.3.11 → 0.3.12

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 (168) hide show
  1. package/dist/bridge/agent-hook-stores.d.ts +3 -0
  2. package/dist/bridge/agent-hook-stores.js +5 -0
  3. package/dist/bridge/agent-hooks.d.ts +159 -5
  4. package/dist/bridge/agent-hooks.js +663 -49
  5. package/dist/bridge/approval-summary.d.ts +16 -0
  6. package/dist/bridge/approval-summary.js +133 -0
  7. package/dist/bridge/authority-command.d.ts +20 -0
  8. package/dist/bridge/authority-command.js +120 -0
  9. package/dist/bridge/authority.d.ts +223 -0
  10. package/dist/bridge/authority.js +231 -0
  11. package/dist/bridge/claude-account-setup.d.ts +14 -0
  12. package/dist/bridge/claude-account-setup.js +69 -0
  13. package/dist/bridge/claude-accounts.d.ts +49 -0
  14. package/dist/bridge/claude-accounts.js +195 -0
  15. package/dist/bridge/code-routes.js +2 -2
  16. package/dist/bridge/codex-app-server.d.ts +144 -0
  17. package/dist/bridge/codex-app-server.js +319 -0
  18. package/dist/bridge/codex-auth-refresh.d.ts +33 -0
  19. package/dist/bridge/codex-auth-refresh.js +71 -0
  20. package/dist/bridge/codex-question-reply.d.ts +16 -0
  21. package/dist/bridge/codex-question-reply.js +57 -0
  22. package/dist/bridge/codex-review-mode.d.ts +10 -0
  23. package/dist/bridge/codex-review-mode.js +74 -0
  24. package/dist/bridge/codex-servers.d.ts +217 -0
  25. package/dist/bridge/codex-servers.js +636 -0
  26. package/dist/bridge/command.js +94 -4
  27. package/dist/bridge/computer-identity.d.ts +75 -0
  28. package/dist/bridge/computer-identity.js +166 -0
  29. package/dist/bridge/conductor-group.d.ts +91 -8
  30. package/dist/bridge/conductor-group.js +105 -9
  31. package/dist/bridge/conductor-role.d.ts +94 -0
  32. package/dist/bridge/conductor-role.js +176 -0
  33. package/dist/bridge/conductor-sets.d.ts +20 -0
  34. package/dist/bridge/conductor-sets.js +59 -0
  35. package/dist/bridge/dispatch-command.d.ts +3 -0
  36. package/dist/bridge/dispatch-command.js +75 -11
  37. package/dist/bridge/dispatch-returns.d.ts +123 -19
  38. package/dist/bridge/dispatch-returns.js +357 -50
  39. package/dist/bridge/dispatch.d.ts +103 -2
  40. package/dist/bridge/dispatch.js +272 -40
  41. package/dist/bridge/fanouts.d.ts +7 -1
  42. package/dist/bridge/fanouts.js +39 -4
  43. package/dist/bridge/folder-trust.d.ts +56 -0
  44. package/dist/bridge/folder-trust.js +195 -0
  45. package/dist/bridge/grants.d.ts +22 -1
  46. package/dist/bridge/grants.js +57 -9
  47. package/dist/bridge/hand-off.d.ts +21 -9
  48. package/dist/bridge/hand-off.js +58 -45
  49. package/dist/bridge/harness-status.d.ts +11 -0
  50. package/dist/bridge/harness-status.js +32 -0
  51. package/dist/bridge/harnesses.d.ts +39 -0
  52. package/dist/bridge/harnesses.js +65 -0
  53. package/dist/bridge/health.d.ts +2 -0
  54. package/dist/bridge/health.js +1 -1
  55. package/dist/bridge/herdr.d.ts +11 -2
  56. package/dist/bridge/herdr.js +98 -23
  57. package/dist/bridge/hook-fast.d.ts +4 -0
  58. package/dist/bridge/hook-fast.js +68 -0
  59. package/dist/bridge/install.d.ts +16 -1
  60. package/dist/bridge/install.js +88 -21
  61. package/dist/bridge/launch-brief.d.ts +96 -0
  62. package/dist/bridge/launch-brief.js +164 -0
  63. package/dist/bridge/model-switch.d.ts +3 -0
  64. package/dist/bridge/model-switch.js +17 -1
  65. package/dist/bridge/models.d.ts +8 -4
  66. package/dist/bridge/models.js +24 -8
  67. package/dist/bridge/mux-wire.d.ts +9 -0
  68. package/dist/bridge/mux-wire.js +19 -0
  69. package/dist/bridge/opencode-pane-server.d.ts +113 -0
  70. package/dist/bridge/opencode-pane-server.js +332 -0
  71. package/dist/bridge/opencode-panes.d.ts +111 -0
  72. package/dist/bridge/opencode-panes.js +295 -0
  73. package/dist/bridge/pane-accounts.d.ts +8 -0
  74. package/dist/bridge/pane-accounts.js +46 -0
  75. package/dist/bridge/prompt-startup.d.ts +5 -0
  76. package/dist/bridge/prompt-startup.js +24 -0
  77. package/dist/bridge/protocol.d.ts +5 -0
  78. package/dist/bridge/protocol.js +4 -0
  79. package/dist/bridge/push.d.ts +5 -4
  80. package/dist/bridge/push.js +6 -4
  81. package/dist/bridge/questions.d.ts +37 -2
  82. package/dist/bridge/questions.js +158 -15
  83. package/dist/bridge/resources.d.ts +9 -3
  84. package/dist/bridge/resources.js +24 -8
  85. package/dist/bridge/schedule-format.d.ts +2 -0
  86. package/dist/bridge/schedule-format.js +3 -0
  87. package/dist/bridge/schedule-launch.d.ts +2 -1
  88. package/dist/bridge/schedule-launch.js +23 -53
  89. package/dist/bridge/schedule-watch.d.ts +10 -1
  90. package/dist/bridge/schedule-watch.js +54 -2
  91. package/dist/bridge/server-launch.d.ts +22 -5
  92. package/dist/bridge/server-launch.js +225 -29
  93. package/dist/bridge/server-overview.d.ts +3 -3
  94. package/dist/bridge/server-overview.js +22 -14
  95. package/dist/bridge/server-pane-routes.d.ts +2 -0
  96. package/dist/bridge/server-pane-routes.js +145 -15
  97. package/dist/bridge/server-routes.d.ts +7 -0
  98. package/dist/bridge/server-routes.js +163 -35
  99. package/dist/bridge/server-stream.d.ts +2 -0
  100. package/dist/bridge/server-stream.js +22 -8
  101. package/dist/bridge/server.d.ts +6 -1
  102. package/dist/bridge/server.js +44 -12
  103. package/dist/bridge/session-activity.d.ts +81 -0
  104. package/dist/bridge/session-activity.js +117 -0
  105. package/dist/bridge/session-rename.d.ts +48 -0
  106. package/dist/bridge/session-rename.js +190 -0
  107. package/dist/bridge/session-servers.js +2 -2
  108. package/dist/bridge/settings-switch.d.ts +60 -0
  109. package/dist/bridge/settings-switch.js +287 -0
  110. package/dist/bridge/speech-voice.d.ts +55 -0
  111. package/dist/bridge/speech-voice.js +132 -0
  112. package/dist/bridge/speech.d.ts +70 -11
  113. package/dist/bridge/speech.js +169 -41
  114. package/dist/bridge/terminal-herdr.js +9 -3
  115. package/dist/bridge/terminal-tmux.d.ts +3 -3
  116. package/dist/bridge/terminal-tmux.js +24 -9
  117. package/dist/bridge/terminal.d.ts +27 -4
  118. package/dist/bridge/terminal.js +8 -1
  119. package/dist/bridge/transcript-claude.js +57 -12
  120. package/dist/bridge/transcript-codex.d.ts +0 -2
  121. package/dist/bridge/transcript-codex.js +29 -4
  122. package/dist/bridge/transcript-preview.d.ts +1 -0
  123. package/dist/bridge/transcript-preview.js +24 -4
  124. package/dist/bridge/transcripts.d.ts +15 -2
  125. package/dist/bridge/transcripts.js +47 -16
  126. package/dist/bridge/turn-records.d.ts +85 -0
  127. package/dist/bridge/turn-records.js +143 -0
  128. package/dist/bridge/uploads.d.ts +3 -0
  129. package/dist/bridge/uploads.js +14 -0
  130. package/dist/bridge/usage.d.ts +39 -10
  131. package/dist/bridge/usage.js +155 -44
  132. package/dist/bridge-hook.mjs +19169 -13176
  133. package/dist/cli/claude-unmanaged.d.ts +12 -0
  134. package/dist/cli/claude-unmanaged.js +105 -0
  135. package/dist/cli/schedules.js +2 -1
  136. package/dist/cli/session-start.js +10 -1
  137. package/dist/cli/session-stop.js +9 -1
  138. package/dist/cli-registry.js +24 -5
  139. package/dist/data/task-receipts.d.ts +19 -0
  140. package/dist/data/task-receipts.js +68 -0
  141. package/dist/data/tasks.js +4 -1
  142. package/dist/generated/memory-ui-graph.browser.js +63 -63
  143. package/dist/graph-core/model.js +24 -3
  144. package/dist/graph-core/types.d.ts +4 -1
  145. package/dist/graph-core/types.js +1 -0
  146. package/dist/init/init-preset.js +7 -3
  147. package/dist/init/init-uninstall.js +2 -11
  148. package/dist/init/teardown.d.ts +3 -0
  149. package/dist/init/teardown.js +47 -0
  150. package/dist/link/context.js +21 -9
  151. package/dist/mcp/plugin-mode.js +1 -1
  152. package/dist/memory-ui-graph.runtime.js +63 -63
  153. package/dist/modules/code-package.d.ts +1 -0
  154. package/dist/modules/code-package.js +36 -7
  155. package/dist/modules/registry.js +14 -13
  156. package/dist/profile-store.d.ts +6 -0
  157. package/dist/profile-store.js +25 -1
  158. package/dist/shell/graph/glyphs.js +4 -0
  159. package/dist/shell/graph/graph-view.js +2 -0
  160. package/dist/status.js +7 -1
  161. package/dist/sync/task-claim.js +3 -2
  162. package/dist/task/lifecycle.js +25 -4
  163. package/dist/test-global-setup.js +5 -0
  164. package/dist/tools/dispatch.js +35 -2
  165. package/dist/tools/tasks.js +10 -1
  166. package/package.json +1 -1
  167. package/plugins/opencode/phren-transcript.js +87 -4
  168. package/starter/global/skills/conductor/SKILL.md +17 -2
@@ -0,0 +1,96 @@
1
+ import { z } from "zod";
2
+ import { type Target } from "./protocol.js";
3
+ /**
4
+ * A worker's first prompt carried by its launch instead of typed into a
5
+ * starting pane. The brief is written to a private file on the computer that
6
+ * starts the agent, and the harness gets one short argument pointing at it:
7
+ * `claude "<prompt>"` and `codex "<prompt>"` both open the interactive TUI
8
+ * and submit that prompt themselves, so there is no Enter to lose and no
9
+ * starting pane to wait for. The same id is exported to the agent as
10
+ * `PHREN_DISPATCH_ID`, and its SessionStart and UserPromptSubmit hooks echo
11
+ * it back: the receipt is that echo, not a match on typed text.
12
+ *
13
+ * OpenCode takes its brief over the HTTP API its launched TUI serves
14
+ * (opencode-panes.ts); the file is still written so the arrival is recorded
15
+ * here. Copilot, with no such argument or API, keeps the typed path.
16
+ */
17
+ /** A dispatch receipt id or a scheduled run id: what `PHREN_DISPATCH_ID` carries. */
18
+ export declare const briefId: z.ZodString;
19
+ export declare const launchBriefSchema: z.ZodObject<{
20
+ id: z.ZodString;
21
+ text: z.ZodString;
22
+ }, z.core.$strict>;
23
+ export type LaunchBrief = z.infer<typeof launchBriefSchema>;
24
+ /** The variable a launched agent's hooks read its brief id from. */
25
+ export declare const DISPATCH_ID_ENV = "PHREN_DISPATCH_ID";
26
+ export declare function briefRoot(): string;
27
+ /** The harnesses whose TUI takes a first prompt as an argument, and the
28
+ * arguments that carry it. Claude reads outside its working directory only
29
+ * with permission, so the brief's own folder is added to its tool access;
30
+ * `--add-dir` takes several values, so it comes after the prompt. */
31
+ export declare function briefArgs(kind: string, file: string): string[] | undefined;
32
+ export declare function launchesWithBrief(kind: string): boolean;
33
+ /**
34
+ * The label the dispatcher gave a launched worker, kept beside its brief so
35
+ * this Hook can name the worker's session by it: the harness titles a session
36
+ * after its first prompt, which is only "Read and follow the brief in ...".
37
+ * Undefined for an id this computer wrote no label for (older dispatches).
38
+ */
39
+ export declare function briefLabel(id: string): Promise<string | undefined>;
40
+ /**
41
+ * Writes the brief (0600, in a 0700 folder of its own) and returns its path.
42
+ * A `label` is written beside it, inside the same folder, so it is published
43
+ * with the brief and never lags it.
44
+ * The folder is filled beside `briefs/` and renamed into place, so a brief
45
+ * folder never exists without its `brief.md`: anything that lists `briefs/`
46
+ * (the arrival route, a test, the owner) sees a whole brief or none. Writing
47
+ * it in place left a moment where the folder was there and the file was not.
48
+ */
49
+ export declare function writeLaunchBrief(brief: LaunchBrief, now?: number, label?: string): Promise<string>;
50
+ export declare const arrivalSchema: z.ZodObject<{
51
+ started: z.ZodOptional<z.ZodObject<{
52
+ at: z.ZodString;
53
+ target: z.ZodObject<{
54
+ server: z.ZodString;
55
+ workspace: z.ZodString;
56
+ tab: z.ZodString;
57
+ pane: z.ZodString;
58
+ source: z.ZodEnum<{
59
+ claude: "claude";
60
+ codex: "codex";
61
+ copilot: "copilot";
62
+ opencode: "opencode";
63
+ phren: "phren";
64
+ }>;
65
+ session: z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
66
+ }, z.core.$strip>;
67
+ }, z.core.$strict>>;
68
+ accepted: z.ZodOptional<z.ZodObject<{
69
+ at: z.ZodString;
70
+ target: z.ZodObject<{
71
+ server: z.ZodString;
72
+ workspace: z.ZodString;
73
+ tab: z.ZodString;
74
+ pane: z.ZodString;
75
+ source: z.ZodEnum<{
76
+ claude: "claude";
77
+ codex: "codex";
78
+ copilot: "copilot";
79
+ opencode: "opencode";
80
+ phren: "phren";
81
+ }>;
82
+ session: z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
83
+ }, z.core.$strip>;
84
+ }, z.core.$strict>>;
85
+ }, z.core.$strict>;
86
+ export type BriefArrival = z.infer<typeof arrivalSchema>;
87
+ /** What the worker's own hooks have said about its brief: `started` at its
88
+ * SessionStart, `accepted` when the brief prompt was submitted. Empty while
89
+ * neither has arrived; undefined when this computer wrote no such brief. */
90
+ export declare function briefArrival(id: string): Promise<BriefArrival | undefined>;
91
+ /** The brief id in a prompt that points at a brief file, for callbacks that
92
+ * cannot trust their own environment (Codex's shared hook daemon). */
93
+ export declare function briefIdInPrompt(prompt: string): string | undefined;
94
+ /** Records a worker hook's report about its brief. Only the first of each
95
+ * event counts, and only for a brief this computer wrote. */
96
+ export declare function recordBriefArrival(id: string, event: string, target: Target, now?: Date): Promise<void>;
@@ -0,0 +1,164 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { lstat, mkdir, readdir, readFile, rename, rm, stat } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { z } from "zod";
5
+ import { atomic, bridgeRoot, targetSchema } from "./protocol.js";
6
+ /**
7
+ * A worker's first prompt carried by its launch instead of typed into a
8
+ * starting pane. The brief is written to a private file on the computer that
9
+ * starts the agent, and the harness gets one short argument pointing at it:
10
+ * `claude "<prompt>"` and `codex "<prompt>"` both open the interactive TUI
11
+ * and submit that prompt themselves, so there is no Enter to lose and no
12
+ * starting pane to wait for. The same id is exported to the agent as
13
+ * `PHREN_DISPATCH_ID`, and its SessionStart and UserPromptSubmit hooks echo
14
+ * it back: the receipt is that echo, not a match on typed text.
15
+ *
16
+ * OpenCode takes its brief over the HTTP API its launched TUI serves
17
+ * (opencode-panes.ts); the file is still written so the arrival is recorded
18
+ * here. Copilot, with no such argument or API, keeps the typed path.
19
+ */
20
+ /** A dispatch receipt id or a scheduled run id: what `PHREN_DISPATCH_ID` carries. */
21
+ export const briefId = z.string().regex(/^[A-Za-z0-9_-]{8,64}$/);
22
+ export const launchBriefSchema = z.object({
23
+ id: briefId,
24
+ text: z.string().min(1).max(32768).refine(value => !!value.trim() && !/[\x00-\x08\x0b-\x1f\x7f]/.test(value)),
25
+ }).strict();
26
+ /** The variable a launched agent's hooks read its brief id from. */
27
+ export const DISPATCH_ID_ENV = "PHREN_DISPATCH_ID";
28
+ /** Briefs older than this are removed when the next one is written; a worker
29
+ * may re-read its brief after a compaction, so it is not removed on arrival. */
30
+ const KEEP_MS = 7 * 24 * 60 * 60 * 1000;
31
+ const MAX_BRIEFS = 256;
32
+ export function briefRoot() { return path.join(bridgeRoot(), "briefs"); }
33
+ function briefDirectory(id) { return path.join(briefRoot(), briefId.parse(id)); }
34
+ /** The harnesses whose TUI takes a first prompt as an argument, and the
35
+ * arguments that carry it. Claude reads outside its working directory only
36
+ * with permission, so the brief's own folder is added to its tool access;
37
+ * `--add-dir` takes several values, so it comes after the prompt. */
38
+ export function briefArgs(kind, file) {
39
+ if (!launchesWithBrief(kind))
40
+ return undefined;
41
+ const prompt = `Read and follow the brief in ${file}`;
42
+ if (kind === "claude")
43
+ return [prompt, "--add-dir", path.dirname(file)];
44
+ return [prompt];
45
+ }
46
+ export function launchesWithBrief(kind) { return kind === "claude" || kind === "codex"; }
47
+ async function prune(now) {
48
+ const root = briefRoot();
49
+ const names = (await readdir(root).catch(() => [])).filter(name => briefId.safeParse(name).success);
50
+ const entries = (await Promise.all(names.map(async (name) => {
51
+ const info = await lstat(path.join(root, name)).catch(() => undefined);
52
+ return info?.isDirectory() ? { name, at: info.mtimeMs } : undefined;
53
+ }))).filter((entry) => !!entry).sort((a, b) => b.at - a.at);
54
+ const stale = entries.filter((entry, index) => index >= MAX_BRIEFS - 1 || now - entry.at > KEEP_MS);
55
+ await Promise.all(stale.map(entry => rm(path.join(root, entry.name), { recursive: true, force: true }).catch(() => undefined)));
56
+ }
57
+ const LABEL_FILE = "label";
58
+ const MAX_LABEL = 200;
59
+ /** A dispatch label as stored and shown: control characters and runs of blanks collapsed, at most 200 characters. */
60
+ function cleanLabel(value) { return value.replace(/[\x00-\x1f\x7f]+/g, " ").replace(/\s+/g, " ").trim().slice(0, MAX_LABEL).trim(); }
61
+ /**
62
+ * The label the dispatcher gave a launched worker, kept beside its brief so
63
+ * this Hook can name the worker's session by it: the harness titles a session
64
+ * after its first prompt, which is only "Read and follow the brief in ...".
65
+ * Undefined for an id this computer wrote no label for (older dispatches).
66
+ */
67
+ export async function briefLabel(id) {
68
+ if (!briefId.safeParse(id).success)
69
+ return undefined;
70
+ const file = path.join(briefDirectory(id), LABEL_FILE);
71
+ try {
72
+ const info = await lstat(file);
73
+ if (!info.isFile() || info.size > 4 * MAX_LABEL)
74
+ return undefined;
75
+ return cleanLabel(await readFile(file, "utf8")) || undefined;
76
+ }
77
+ catch {
78
+ return undefined;
79
+ }
80
+ }
81
+ /**
82
+ * Writes the brief (0600, in a 0700 folder of its own) and returns its path.
83
+ * A `label` is written beside it, inside the same folder, so it is published
84
+ * with the brief and never lags it.
85
+ * The folder is filled beside `briefs/` and renamed into place, so a brief
86
+ * folder never exists without its `brief.md`: anything that lists `briefs/`
87
+ * (the arrival route, a test, the owner) sees a whole brief or none. Writing
88
+ * it in place left a moment where the folder was there and the file was not.
89
+ */
90
+ export async function writeLaunchBrief(brief, now = Date.now(), label) {
91
+ await mkdir(briefRoot(), { recursive: true, mode: 0o700 });
92
+ await prune(now);
93
+ const directory = briefDirectory(brief.id);
94
+ const file = path.join(directory, "brief.md");
95
+ const text = brief.text.endsWith("\n") ? brief.text : `${brief.text}\n`;
96
+ const named = label ? cleanLabel(label) : "";
97
+ const fill = async (folder) => {
98
+ await atomic(path.join(folder, "brief.md"), text);
99
+ if (named)
100
+ await atomic(path.join(folder, LABEL_FILE), named);
101
+ };
102
+ // The same id again (a retried launch) replaces the text and label in the existing folder.
103
+ if (await stat(directory).catch(() => undefined)) {
104
+ await fill(directory);
105
+ return file;
106
+ }
107
+ const staging = path.join(bridgeRoot(), "briefs-staging");
108
+ await mkdir(staging, { recursive: true, mode: 0o700 });
109
+ const draft = path.join(staging, `${brief.id}.${randomUUID()}`);
110
+ try {
111
+ await mkdir(draft, { mode: 0o700 });
112
+ await fill(draft);
113
+ await rename(draft, directory);
114
+ }
115
+ catch (error) {
116
+ await rm(draft, { recursive: true, force: true }).catch(() => undefined);
117
+ // Another writer published the same id first: write into its folder.
118
+ if (!(await stat(path.join(directory, "brief.md")).catch(() => undefined)))
119
+ throw error;
120
+ await fill(directory);
121
+ }
122
+ return file;
123
+ }
124
+ const arrivalEvent = z.object({ at: z.string().datetime(), target: targetSchema }).strict();
125
+ export const arrivalSchema = z.object({ started: arrivalEvent.optional(), accepted: arrivalEvent.optional() }).strict();
126
+ /** What the worker's own hooks have said about its brief: `started` at its
127
+ * SessionStart, `accepted` when the brief prompt was submitted. Empty while
128
+ * neither has arrived; undefined when this computer wrote no such brief. */
129
+ export async function briefArrival(id) {
130
+ const directory = briefDirectory(id);
131
+ if (!(await stat(directory).catch(() => undefined))?.isDirectory())
132
+ return undefined;
133
+ const text = await readFile(path.join(directory, "arrival.json"), "utf8").catch(() => undefined);
134
+ const parsed = text === undefined ? undefined : arrivalSchema.safeParse((() => { try {
135
+ return JSON.parse(text);
136
+ }
137
+ catch {
138
+ return undefined;
139
+ } })());
140
+ return parsed?.success ? parsed.data : {};
141
+ }
142
+ /** The brief id in a prompt that points at a brief file, for callbacks that
143
+ * cannot trust their own environment (Codex's shared hook daemon). */
144
+ export function briefIdInPrompt(prompt) {
145
+ const escaped = briefRoot().replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
146
+ const match = new RegExp(`${escaped}[\\\\/]([A-Za-z0-9_-]{8,64})[\\\\/]brief\\.md`).exec(prompt);
147
+ return match?.[1];
148
+ }
149
+ let arrivals = Promise.resolve();
150
+ /** Records a worker hook's report about its brief. Only the first of each
151
+ * event counts, and only for a brief this computer wrote. */
152
+ export function recordBriefArrival(id, event, target, now = new Date()) {
153
+ const kind = event === "UserPromptSubmit" ? "accepted" : event === "SessionStart" ? "started" : undefined;
154
+ if (!kind || !briefId.safeParse(id).success)
155
+ return Promise.resolve();
156
+ const run = arrivals.then(async () => {
157
+ const current = await briefArrival(id);
158
+ if (!current || current[kind])
159
+ return;
160
+ await atomic(path.join(briefDirectory(id), "arrival.json"), arrivalSchema.parse({ ...current, [kind]: { at: now.toISOString(), target } }));
161
+ });
162
+ arrivals = run.catch(() => undefined);
163
+ return run;
164
+ }
@@ -21,6 +21,9 @@ type EffortReply = {
21
21
  * the scrollback never confirms. A cap reports the level actually set; an
22
22
  * override or refusal is an error. */
23
23
  export declare function claudeEffortReply(text: string): EffortReply | undefined;
24
+ /** Empty prompts can draw a dim placeholder. Only ANSI evidence that every
25
+ * character after the prompt is dim distinguishes that from a person's draft. */
26
+ export declare function emptyComposer(line: string): boolean;
24
27
  /** Only a footer below Codex's empty composer proves the active model. Text
25
28
  * in history, a menu, or the startup banner must never confirm a switch. */
26
29
  export declare function codexModelStatus(text: string, model: AgentModel): boolean;
@@ -6,6 +6,7 @@ import { ModelCatalog } from "./models.js";
6
6
  import { BridgeError } from "./protocol.js";
7
7
  import { sideQuestionText } from "./side-questions.js";
8
8
  import { stripTerminal } from "../terminal-text.js";
9
+ import { codexServers } from "./codex-servers.js";
9
10
  export const MODEL_BUSY = "This agent is working. The model switch can happen when the turn ends. Choose Switch after this turn.";
10
11
  export const SLASH_BUSY = "This agent is working. Slash commands run between turns; send it again when this turn ends.";
11
12
  /** Busy slash commands must never enter the harness's text queue. Claude's
@@ -55,7 +56,7 @@ export function claudeEffortReply(text) {
55
56
  }
56
57
  /** Empty prompts can draw a dim placeholder. Only ANSI evidence that every
57
58
  * character after the prompt is dim distinguishes that from a person's draft. */
58
- function emptyComposer(line) {
59
+ export function emptyComposer(line) {
59
60
  if (!/^\s*[›❯>]\s*/.test(stripTerminal(line)))
60
61
  return false;
61
62
  let dim = false, prompt = false;
@@ -145,6 +146,21 @@ export class ModelSwitcher {
145
146
  throw new BridgeError(409, `Could not verify ${step}. Open terminal to check the model.`);
146
147
  };
147
148
  try {
149
+ // A Codex pane on the Hook's own app-server takes the model and effort
150
+ // with its next turn (turn/start overrides), as T3 does: no menu is
151
+ // walked in its TUI, and a working turn is left alone.
152
+ const served = target.source === "codex" ? codexServers.forTarget(target) : undefined;
153
+ if (served) {
154
+ const model = (await this.catalog.list("codex")).find(model => model.id === id);
155
+ if (!model)
156
+ throw new BridgeError(422, "That model is not in the computer's catalogue. Refresh the model list.");
157
+ const effort = chosenEffort ?? model.defaultReasoningEffort;
158
+ if (effort && model.supportedReasoningEfforts?.length && !model.supportedReasoningEfforts.includes(effort)) {
159
+ throw new BridgeError(422, "The catalogue does not confirm that reasoning effort. Refresh the model list.");
160
+ }
161
+ codexServers.setNextTurn(served, model.id, effort);
162
+ return { ok: true, model: model.id, name: model.name, ...(effort ? { effort } : {}), applies: "next-turn" };
163
+ }
148
164
  terminal = (await validate(true)).terminal_id;
149
165
  if (target.source === "opencode")
150
166
  throw new BridgeError(422, "OpenCode uses an interactive /models picker. Open terminal to switch models; remote selection cannot yet be verified.");
@@ -1,4 +1,4 @@
1
- import { type Json } from "./protocol.js";
1
+ import { BridgeError, type Json } from "./protocol.js";
2
2
  /** One entry of a `/model` menu as the phone draws it. */
3
3
  export interface AgentModel {
4
4
  id: string;
@@ -35,12 +35,16 @@ export declare function readClaudeModels(configDir?: string, installed?: string
35
35
  export declare function readOpenCodeModels(executable?: string, configDir?: string): Promise<AgentModel[]>;
36
36
  /** "claude-fable-5-1" reads as "Fable 5.1"; a date suffix is dropped. */
37
37
  export declare function claudeName(id: string): string;
38
- /** Catalogues change rarely and app-server takes seconds to start. */
38
+ /** The account a request names is not one on this computer (or has no catalogue for that source). */
39
+ export declare const accountUnavailable: (account: string) => BridgeError;
40
+ /** Catalogues change rarely and app-server takes seconds to start. Cached per
41
+ * `${source}:${account}`; only Claude has accounts, each reading its own home. */
39
42
  export declare class ModelCatalog {
40
43
  private readonly codex;
41
44
  private readonly claude;
42
45
  private readonly opencode;
46
+ private readonly cacheMs;
43
47
  private cache;
44
- constructor(codex?: () => Promise<AgentModel[]>, claude?: () => Promise<AgentModel[]>, opencode?: () => Promise<AgentModel[]>);
45
- list(source: string): Promise<AgentModel[]>;
48
+ constructor(codex?: () => Promise<AgentModel[]>, claude?: (configDir?: string) => Promise<AgentModel[]>, opencode?: () => Promise<AgentModel[]>, cacheMs?: number);
49
+ list(source: string, account?: string): Promise<AgentModel[]>;
46
50
  }
@@ -3,7 +3,8 @@ import { readdir, readFile, stat } from "node:fs/promises";
3
3
  import { homedir } from "node:os";
4
4
  import { claudeConfigDir } from "../home-paths.js";
5
5
  import path from "node:path";
6
- import { object, objects } from "./protocol.js";
6
+ import { BridgeError, object, objects } from "./protocol.js";
7
+ import { claudeHome, DEFAULT_ACCOUNT } from "./claude-accounts.js";
7
8
  import { codexExecutable } from "./codex-binary.js";
8
9
  /** Only initialize and list. Never a thread, a prompt, or a login. */
9
10
  export function readCodexModels(executable = codexExecutable()) {
@@ -237,23 +238,38 @@ export function claudeName(id) {
237
238
  const name = family.charAt(0).toUpperCase() + family.slice(1) + (version ? ` ${version}` : "");
238
239
  return id.endsWith("[1m]") ? `${name} (1M context)` : name;
239
240
  }
240
- /** Catalogues change rarely and app-server takes seconds to start. */
241
+ /** The account a request names is not one on this computer (or has no catalogue for that source). */
242
+ export const accountUnavailable = (account) => new BridgeError(404, `"${account}" is not an account on this computer.`, { code: "account_unavailable" });
243
+ /** Catalogues change rarely and app-server takes seconds to start. Cached per
244
+ * `${source}:${account}`; only Claude has accounts, each reading its own home. */
241
245
  export class ModelCatalog {
242
246
  codex;
243
247
  claude;
244
248
  opencode;
249
+ cacheMs;
245
250
  cache = new Map();
246
- constructor(codex = () => readCodexModels(), claude = () => readClaudeModels(), opencode = () => readOpenCodeModels()) {
251
+ constructor(codex = () => readCodexModels(), claude = dir => readClaudeModels(dir), opencode = () => readOpenCodeModels(), cacheMs = 600_000) {
247
252
  this.codex = codex;
248
253
  this.claude = claude;
249
254
  this.opencode = opencode;
255
+ this.cacheMs = cacheMs;
250
256
  }
251
- list(source) {
252
- const cached = this.cache.get(source);
253
- if (cached && Date.now() - cached.at < 600_000)
257
+ list(source, account) {
258
+ const id = account?.trim() || DEFAULT_ACCOUNT;
259
+ let dir;
260
+ if (source === "claude") {
261
+ const home = claudeHome(id);
262
+ if (!home)
263
+ return Promise.reject(accountUnavailable(id));
264
+ dir = home.isDefault ? undefined : home.dir;
265
+ }
266
+ else if (id !== DEFAULT_ACCOUNT)
267
+ return Promise.reject(accountUnavailable(id));
268
+ const key = `${source}:${id}`, cached = this.cache.get(key);
269
+ if (cached && Date.now() - cached.at < this.cacheMs)
254
270
  return cached.value;
255
- const value = (source === "codex" ? this.codex() : source === "claude" ? this.claude() : source === "opencode" ? this.opencode() : Promise.resolve([])).catch(() => []);
256
- this.cache.set(source, { at: Date.now(), value });
271
+ const value = (source === "codex" ? this.codex() : source === "claude" ? this.claude(dir) : source === "opencode" ? this.opencode() : Promise.resolve([])).catch(() => []);
272
+ this.cache.set(key, { at: Date.now(), value });
257
273
  return value;
258
274
  }
259
275
  }
@@ -0,0 +1,9 @@
1
+ import type { Json } from "./protocol.js";
2
+ /** Installed phones require the historical Herdr envelope even for tmux.
3
+ * A typed tmux selector opts into the source kind; the additive descriptor
4
+ * remains accurate in both formats. */
5
+ export declare function typedMuxRequest(url: URL): boolean;
6
+ export declare function muxReplyForClient(reply: Json, typed: boolean): Json;
7
+ /** New clients request /v1/muxes?typed=1. Older Hooks ignore that query,
8
+ * so callers must also accept the legacy Herdr aliases. */
9
+ export declare function muxListForClient(muxes: Json[], typed: boolean): Json[];
@@ -0,0 +1,19 @@
1
+ /** Installed phones require the historical Herdr envelope even for tmux.
2
+ * A typed tmux selector opts into the source kind; the additive descriptor
3
+ * remains accurate in both formats. */
4
+ export function typedMuxRequest(url) {
5
+ return url.searchParams.get("mux")?.startsWith("tmux:") === true;
6
+ }
7
+ export function muxReplyForClient(reply, typed) {
8
+ return !typed && reply.kind === "tmux" ? { ...reply, kind: "herdr" } : reply;
9
+ }
10
+ /** New clients request /v1/muxes?typed=1. Older Hooks ignore that query,
11
+ * so callers must also accept the legacy Herdr aliases. */
12
+ export function muxListForClient(muxes, typed) {
13
+ return muxes.map(mux => {
14
+ if (typed || mux.kind !== "tmux")
15
+ return mux;
16
+ return { ...mux, id: `herdr:${mux.session}`, kind: "herdr",
17
+ mux: { id: mux.id, kind: mux.kind, session: mux.session } };
18
+ });
19
+ }
@@ -0,0 +1,113 @@
1
+ export interface PaneServerEntry {
2
+ server: string;
3
+ pane: string;
4
+ port: number;
5
+ password: string;
6
+ pid: number;
7
+ directory: string;
8
+ createdAt: string;
9
+ /** What the TUI was started with (`--agent`, `--model`, `--variant`), for
10
+ * the first prompt of a session that has no earlier turn to follow. */
11
+ defaults?: {
12
+ agent?: string;
13
+ model?: string;
14
+ variant?: string;
15
+ };
16
+ }
17
+ export interface OpenCodeSession {
18
+ id: string;
19
+ directory?: string;
20
+ title?: string;
21
+ /** Set on a subagent's session; the TUI shows its root session. */
22
+ parentID?: string;
23
+ time?: {
24
+ created?: number;
25
+ updated?: number;
26
+ };
27
+ }
28
+ export interface OpenCodeMessage {
29
+ info?: {
30
+ id?: string;
31
+ role?: string;
32
+ agent?: string;
33
+ model?: {
34
+ providerID?: string;
35
+ modelID?: string;
36
+ variant?: string;
37
+ };
38
+ };
39
+ parts?: Array<{
40
+ type?: string;
41
+ text?: string;
42
+ }>;
43
+ }
44
+ export interface OpenCodePermission {
45
+ id: string;
46
+ sessionID?: string;
47
+ permission?: string;
48
+ patterns?: string[];
49
+ }
50
+ export interface OpenCodeQuestion {
51
+ id: string;
52
+ sessionID?: string;
53
+ questions?: unknown[];
54
+ }
55
+ /** The prompt never reached the server (refused, or nothing listening), so
56
+ * the caller may still send it another way without a duplicate. */
57
+ export declare class PromptNotSent extends Error {
58
+ }
59
+ export interface PaneEvent {
60
+ type: string;
61
+ properties?: Record<string, unknown>;
62
+ }
63
+ export type PermissionReply = "once" | "always" | "reject";
64
+ export interface PromptOptions {
65
+ /** `provider/model`; split on the first slash. */
66
+ model?: string;
67
+ agent?: string;
68
+ /** A model variant (reasoning effort), as `opencode --variant` takes it. */
69
+ variant?: string;
70
+ /** Without an explicit model or agent, continue with the ones the
71
+ * session's last user turn used, as the TUI would. */
72
+ inherit?: boolean;
73
+ timeoutMs?: number;
74
+ }
75
+ export type PromptResult = {
76
+ delivered: true;
77
+ messageId: string;
78
+ } | {
79
+ delivered: false;
80
+ reason: "timeout";
81
+ };
82
+ export declare function registerPaneServer(dir: string, entry: PaneServerEntry): string;
83
+ export declare function readPaneServer(dir: string, server: string, pane: string): PaneServerEntry | undefined;
84
+ /** Every registered pane whose OpenCode process is still running. An entry
85
+ * whose process is gone is removed as it is found. */
86
+ export declare function listPaneServers(dir: string): PaneServerEntry[];
87
+ export declare function removePaneServer(dir: string, server: string, pane: string): void;
88
+ export declare function freePort(): Promise<number>;
89
+ export declare function newPassword(): string;
90
+ export interface PaneClient {
91
+ /** True once the server answers an authenticated request within `timeoutMs`. */
92
+ ready(timeoutMs?: number): Promise<boolean>;
93
+ sessions(): Promise<OpenCodeSession[]>;
94
+ session(id: string): Promise<OpenCodeSession | undefined>;
95
+ currentSession(): Promise<OpenCodeSession | undefined>;
96
+ /** A new root session in the pane's directory. The TUI does not show it
97
+ * until `selectSession` moves it there. */
98
+ createSession(): Promise<OpenCodeSession>;
99
+ /** Asks the TUI to show `id`. A TUI still starting drops the request, so
100
+ * the caller checks the pane and asks again. */
101
+ selectSession(id: string): Promise<void>;
102
+ /** Renames the session (`PATCH /session/{id}`) and returns the title the server now holds. */
103
+ setTitle(sessionId: string, title: string): Promise<string | undefined>;
104
+ prompt(sessionId: string, text: string, opts?: PromptOptions): Promise<PromptResult>;
105
+ permissions(): Promise<OpenCodePermission[]>;
106
+ replyPermission(id: string, reply: PermissionReply, message?: string): Promise<void>;
107
+ questions(): Promise<OpenCodeQuestion[]>;
108
+ replyQuestion(id: string, answers: string[][]): Promise<void>;
109
+ rejectQuestion(id: string): Promise<void>;
110
+ abort(sessionId: string): Promise<boolean>;
111
+ events(signal?: AbortSignal): AsyncGenerator<PaneEvent>;
112
+ }
113
+ export declare function openPaneClient(entry: PaneServerEntry, fetchImpl?: typeof fetch): PaneClient;