@phren/cli 0.3.36 → 0.3.39

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 (103) hide show
  1. package/dist/bridge/account-choice.d.ts +82 -0
  2. package/dist/bridge/account-choice.js +173 -0
  3. package/dist/bridge/account-failover.d.ts +61 -0
  4. package/dist/bridge/account-failover.js +189 -0
  5. package/dist/bridge/account-usage.d.ts +7 -2
  6. package/dist/bridge/account-usage.js +53 -8
  7. package/dist/bridge/agent-hooks.js +2 -0
  8. package/dist/bridge/changes.d.ts +5 -0
  9. package/dist/bridge/changes.js +4 -0
  10. package/dist/bridge/claude-accounts.d.ts +15 -4
  11. package/dist/bridge/claude-accounts.js +31 -16
  12. package/dist/bridge/claude-credits.d.ts +43 -0
  13. package/dist/bridge/claude-credits.js +236 -0
  14. package/dist/bridge/claude-question-dialog.js +6 -2
  15. package/dist/bridge/command.js +64 -3
  16. package/dist/bridge/device-enroll.d.ts +34 -0
  17. package/dist/bridge/device-enroll.js +57 -0
  18. package/dist/bridge/dispatch-command.d.ts +2 -0
  19. package/dist/bridge/dispatch-command.js +25 -1
  20. package/dist/bridge/dispatch-returns.d.ts +19 -0
  21. package/dist/bridge/dispatch-returns.js +93 -12
  22. package/dist/bridge/dispatch.d.ts +83 -3
  23. package/dist/bridge/dispatch.js +82 -10
  24. package/dist/bridge/file-range.d.ts +3 -0
  25. package/dist/bridge/file-range.js +5 -4
  26. package/dist/bridge/file-search.d.ts +37 -0
  27. package/dist/bridge/file-search.js +87 -0
  28. package/dist/bridge/file-write.d.ts +6 -0
  29. package/dist/bridge/file-write.js +120 -0
  30. package/dist/bridge/git-host-auth.d.ts +31 -0
  31. package/dist/bridge/git-host-auth.js +110 -0
  32. package/dist/bridge/git-host-gitboy.d.ts +46 -0
  33. package/dist/bridge/git-host-gitboy.js +296 -0
  34. package/dist/bridge/git-host-gitlab.d.ts +25 -0
  35. package/dist/bridge/git-host-gitlab.js +229 -0
  36. package/dist/bridge/git-host-http.d.ts +33 -0
  37. package/dist/bridge/git-host-http.js +70 -0
  38. package/dist/bridge/git-hosts.d.ts +92 -0
  39. package/dist/bridge/git-hosts.js +244 -0
  40. package/dist/bridge/git-publish.d.ts +15 -5
  41. package/dist/bridge/git-publish.js +69 -21
  42. package/dist/bridge/git-review.d.ts +23 -0
  43. package/dist/bridge/git-review.js +170 -0
  44. package/dist/bridge/git-sync.d.ts +14 -0
  45. package/dist/bridge/git-sync.js +143 -0
  46. package/dist/bridge/git.d.ts +20 -7
  47. package/dist/bridge/git.js +87 -68
  48. package/dist/bridge/gitboy-contract.d.ts +32 -0
  49. package/dist/bridge/gitboy-contract.js +46 -0
  50. package/dist/bridge/hand-off.d.ts +75 -3
  51. package/dist/bridge/hand-off.js +113 -27
  52. package/dist/bridge/health.d.ts +1 -1
  53. package/dist/bridge/health.js +5 -3
  54. package/dist/bridge/install.d.ts +14 -0
  55. package/dist/bridge/install.js +40 -1
  56. package/dist/bridge/launch-brief.d.ts +3 -0
  57. package/dist/bridge/launch-brief.js +16 -0
  58. package/dist/bridge/memory-store.d.ts +8 -0
  59. package/dist/bridge/memory-store.js +80 -2
  60. package/dist/bridge/pair.d.ts +6 -1
  61. package/dist/bridge/pair.js +74 -2
  62. package/dist/bridge/peers.js +4 -2
  63. package/dist/bridge/project-memory.d.ts +94 -0
  64. package/dist/bridge/project-memory.js +235 -0
  65. package/dist/bridge/push.d.ts +15 -0
  66. package/dist/bridge/push.js +39 -0
  67. package/dist/bridge/schedule-launch.js +5 -1
  68. package/dist/bridge/schedule-watch.d.ts +3 -0
  69. package/dist/bridge/schedule-watch.js +27 -1
  70. package/dist/bridge/scoped-gateway.d.ts +29 -0
  71. package/dist/bridge/scoped-gateway.js +239 -0
  72. package/dist/bridge/server-launch.d.ts +12 -0
  73. package/dist/bridge/server-launch.js +23 -12
  74. package/dist/bridge/server-pane-routes.js +54 -3
  75. package/dist/bridge/server-routes.d.ts +12 -0
  76. package/dist/bridge/server-routes.js +64 -5
  77. package/dist/bridge/server.js +50 -5
  78. package/dist/bridge/session-move.d.ts +288 -0
  79. package/dist/bridge/session-move.js +600 -0
  80. package/dist/bridge/subscription.d.ts +15 -0
  81. package/dist/bridge/subscription.js +23 -0
  82. package/dist/bridge/transport.js +21 -1
  83. package/dist/bridge/usage.d.ts +23 -4
  84. package/dist/bridge/usage.js +63 -11
  85. package/dist/bridge-hook.mjs +23280 -13252
  86. package/dist/cli/config.js +28 -2
  87. package/dist/cli-registry.js +10 -4
  88. package/dist/computers/command.js +3 -1
  89. package/dist/computers/read.d.ts +3 -0
  90. package/dist/computers/read.js +6 -0
  91. package/dist/content/summarize.d.ts +21 -0
  92. package/dist/content/summarize.js +56 -18
  93. package/dist/init/preferences.d.ts +6 -0
  94. package/dist/modules/registry.js +13 -13
  95. package/dist/project-config.d.ts +12 -0
  96. package/dist/project-config.js +29 -0
  97. package/dist/shared/retrieval.d.ts +1 -0
  98. package/dist/shared/retrieval.js +1 -1
  99. package/dist/sync/conflict-resolve.js +5 -6
  100. package/dist/tools/dispatch.js +20 -3
  101. package/dist/tools/finding.d.ts +25 -0
  102. package/dist/tools/finding.js +2 -1
  103. package/package.json +57 -1
@@ -0,0 +1,239 @@
1
+ import { connect } from "node:net";
2
+ import { BridgeError } from "./protocol.js";
3
+ import { findingWriteSchema, isBranchName, isRepoPath, isSearchText, MAX_FILE_PATHS, MAX_FINDING_BODY, PROJECT_NAME, } from "./gitboy-contract.js";
4
+ // A scoped SSH key reaches the Hook through this gateway instead of the full
5
+ // byte pipe. The key's forced command names the scope
6
+ // (`sh ~/.local/share/phren/bridge/dispatch-scoped gitboy-read`); the gateway
7
+ // reads one HTTP request from the SSH channel, admits it only if the scope
8
+ // allows that exact method, path, query and body, and then sends the Hook a
9
+ // request it builds itself from the validated values. The client's bytes never
10
+ // reach the socket, so extra headers, query keys, JSON fields, pipelined
11
+ // requests and upgrades cannot widen the scope.
12
+ export const GATEWAY_SCOPES = ["gitboy-read", "gitboy-write"];
13
+ /** The authorized_keys comment each scope's key carries. */
14
+ export const SCOPE_KEY_COMMENT = { "gitboy-read": "phren-gitboy", "gitboy-write": "phren-gitboy-write" };
15
+ /** The only SSH command a scoped key may send, the same one the phone's pipe uses. */
16
+ export const SCOPED_COMMAND = "phren-hook v1 pipe";
17
+ /** Room for 500 repository paths in one query string; the Hook allows the same. */
18
+ const MAX_HEAD = 256 * 1024;
19
+ const MAX_HEADER_LINE = 8192;
20
+ const MAX_HEADERS = 32;
21
+ const READ_TIMEOUT_MS = 10_000;
22
+ const PROJECT = PROJECT_NAME.source.slice(1, -1);
23
+ const one = (query, key) => query.get(key)?.length === 1 ? query.get(key)[0] : undefined;
24
+ const only = (query, keys) => [...query.keys()].every(key => keys.includes(key));
25
+ const RULES = {
26
+ "gitboy-read": [
27
+ { method: "GET", path: new RegExp(`^/v1/projects/${PROJECT}/memory$`) },
28
+ { method: "GET", path: new RegExp(`^/v1/projects/${PROJECT}/memory/files$`), query: query => {
29
+ const paths = query.get("path") ?? [];
30
+ if (!only(query, ["path"]) || paths.length < 1 || paths.length > MAX_FILE_PATHS)
31
+ return `Send 1 to ${MAX_FILE_PATHS} path parameters and nothing else.`;
32
+ if (!paths.every(isRepoPath))
33
+ return "Each path must be repository-relative.";
34
+ return paths.map(value => ["path", value]);
35
+ } },
36
+ { method: "GET", path: new RegExp(`^/v1/projects/${PROJECT}/memory/search$`), query: query => {
37
+ const q = one(query, "q"), limit = query.has("limit") ? one(query, "limit") : "5";
38
+ if (!only(query, ["q", "limit"]) || q === undefined || limit === undefined)
39
+ return "Send one q and at most one limit.";
40
+ if (!isSearchText(q))
41
+ return "q must be 1 to 1000 characters of text.";
42
+ if (!/^(?:[1-9]|1\d|20)$/.test(limit))
43
+ return "limit must be 1 to 20.";
44
+ return [["q", q], ["limit", limit]];
45
+ } },
46
+ { method: "GET", path: new RegExp(`^/v1/projects/${PROJECT}/tasks$`), query: query => {
47
+ const branch = one(query, "branch");
48
+ if (!only(query, ["branch"]) || branch === undefined || !isBranchName(branch))
49
+ return "Send one valid branch.";
50
+ return [["branch", branch]];
51
+ } },
52
+ ],
53
+ "gitboy-write": [
54
+ { method: "POST", path: new RegExp(`^/v1/projects/${PROJECT}/findings$`), body: { max: MAX_FINDING_BODY, schema: findingWriteSchema } },
55
+ ],
56
+ };
57
+ const DESCRIBE = {
58
+ "gitboy-read": "GET /v1/projects/<project>/memory, /memory/files, /memory/search and /tasks",
59
+ "gitboy-write": "POST /v1/projects/<project>/findings",
60
+ };
61
+ export function isGatewayScope(value) {
62
+ return GATEWAY_SCOPES.includes(value);
63
+ }
64
+ const refuse = (status, error) => ({ ok: false, status, error });
65
+ function parseHead(head) {
66
+ const lines = head.split("\r\n");
67
+ if (lines.length < 3 || lines.at(-1) !== "" || lines.at(-2) !== "")
68
+ return refuse(400, "Malformed request.");
69
+ const request = /^([A-Z]+) (\/[^\s?#]*)(?:\?([^\s#]*))? HTTP\/1\.[01]$/.exec(lines[0]);
70
+ if (!request)
71
+ return refuse(400, "Malformed request.");
72
+ const headers = lines.slice(1, -2);
73
+ if (headers.length > MAX_HEADERS)
74
+ return refuse(400, "Too many headers.");
75
+ let contentLength, json = false;
76
+ for (const header of headers) {
77
+ if (header.length > MAX_HEADER_LINE)
78
+ return refuse(400, "Header too large.");
79
+ const match = /^([!#$%&'*+.^_`|~0-9A-Za-z-]+):[ \t]*(.*?)[ \t]*$/.exec(header);
80
+ if (!match)
81
+ return refuse(400, "Malformed request.");
82
+ const name = match[1].toLowerCase();
83
+ if (name === "transfer-encoding" || name === "upgrade" || name === "expect")
84
+ return refuse(400, "Send a plain request with a Content-Length body, if any.");
85
+ if (name === "content-length") {
86
+ if (contentLength !== undefined || !/^\d{1,7}$/.test(match[2]))
87
+ return refuse(400, "Invalid Content-Length.");
88
+ contentLength = Number(match[2]);
89
+ }
90
+ if (name === "content-type")
91
+ json = /^application\/json(?:\s*;\s*charset=utf-8)?$/i.test(match[2]);
92
+ }
93
+ return { method: request[1], path: request[2], query: request[3] ?? null, contentLength: contentLength ?? 0, json };
94
+ }
95
+ function parseQuery(raw) {
96
+ const query = new Map();
97
+ for (const pair of raw.split("&")) {
98
+ const match = /^([a-z]{1,10})=([A-Za-z0-9._~%+!$'()*,;:@\/-]*)$/.exec(pair);
99
+ if (!match)
100
+ return undefined;
101
+ let value;
102
+ try {
103
+ value = decodeURIComponent(match[2].replace(/\+/g, " "));
104
+ }
105
+ catch {
106
+ return undefined;
107
+ }
108
+ query.set(match[1], [...(query.get(match[1]) ?? []), value]);
109
+ }
110
+ return query;
111
+ }
112
+ function findRule(scope, head) {
113
+ return RULES[scope].find(rule => rule.method === head.method && rule.path.test(head.path));
114
+ }
115
+ /** Decide one request: its head (through the blank line) and the bytes after it. */
116
+ export function admitScopedRequest(scope, rawHead, rest = Buffer.alloc(0)) {
117
+ const head = parseHead(rawHead);
118
+ if ("ok" in head)
119
+ return head;
120
+ const rule = findRule(scope, head);
121
+ if (!rule)
122
+ return refuse(403, `This key only permits ${DESCRIBE[scope]}.`);
123
+ let target = head.path;
124
+ if (rule.query) {
125
+ if (head.query === null)
126
+ return refuse(400, "This route needs its query parameters.");
127
+ const query = parseQuery(head.query);
128
+ if (!query)
129
+ return refuse(400, "Malformed query.");
130
+ const pairs = rule.query(query);
131
+ if (typeof pairs === "string")
132
+ return refuse(400, pairs);
133
+ target += `?${new URLSearchParams(pairs).toString()}`;
134
+ }
135
+ else if (head.query !== null)
136
+ return refuse(400, "This route takes no query.");
137
+ if (!rule.body) {
138
+ if (head.contentLength !== 0 || rest.length > 0)
139
+ return refuse(400, "Send one request with no body.");
140
+ return { ok: true, request: `${rule.method} ${target} HTTP/1.1\r\nHost: phren.local\r\nConnection: close\r\n\r\n` };
141
+ }
142
+ if (!head.json)
143
+ return refuse(415, "Send Content-Type: application/json.");
144
+ if (head.contentLength < 1 || head.contentLength > rule.body.max)
145
+ return refuse(413, `The body must be 1 to ${rule.body.max} bytes.`);
146
+ if (rest.length !== head.contentLength)
147
+ return refuse(400, "The body must match Content-Length, with nothing after it.");
148
+ let parsed;
149
+ try {
150
+ parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(rest));
151
+ }
152
+ catch {
153
+ return refuse(400, "The body is not JSON.");
154
+ }
155
+ const checked = rule.body.schema.safeParse(parsed);
156
+ if (!checked.success)
157
+ return refuse(400, `Invalid body: ${checked.error.issues.map(issue => `${issue.path.join(".") || "body"} ${issue.message}`).join("; ").slice(0, 300)}`);
158
+ const body = JSON.stringify(checked.data);
159
+ return { ok: true, request: `${rule.method} ${target} HTTP/1.1\r\nHost: phren.local\r\nContent-Type: application/json\r\nContent-Length: ${Buffer.byteLength(body)}\r\nConnection: close\r\n\r\n${body}` };
160
+ }
161
+ const REASONS = { 400: "Bad Request", 403: "Forbidden", 408: "Request Timeout", 413: "Content Too Large", 415: "Unsupported Media Type", 503: "Service Unavailable" };
162
+ function httpResponse(status, error) {
163
+ const body = JSON.stringify({ error, code: status === 503 ? "hook-unavailable" : "scope-refused" });
164
+ return `HTTP/1.1 ${status} ${REASONS[status] ?? "Bad Request"}\r\nContent-Type: application/json\r\nCache-Control: no-store\r\nConnection: close\r\nContent-Length: ${Buffer.byteLength(body)}\r\n\r\n${body}`;
165
+ }
166
+ /** Read the head, then, when the scope has a body route and the head declares
167
+ * a body within its cap, exactly that many bytes. Stops at a limit, the
168
+ * timeout or EOF; bytes beyond the request make it refused. */
169
+ function readRequest(scope, input) {
170
+ const bodyCap = Math.max(0, ...RULES[scope].map(rule => rule.body?.max ?? 0));
171
+ return new Promise(resolve => {
172
+ let buffer = Buffer.alloc(0), headEnd = -1, wanted = 0;
173
+ const finish = (value) => {
174
+ clearTimeout(timer);
175
+ input.off("data", data);
176
+ input.off("end", end);
177
+ input.off("error", end);
178
+ input.pause();
179
+ resolve(value);
180
+ };
181
+ const complete = () => finish({ head: buffer.subarray(0, headEnd).toString("latin1"), rest: buffer.subarray(headEnd) });
182
+ const data = (chunk) => {
183
+ buffer = Buffer.concat([buffer, chunk]);
184
+ if (headEnd === -1) {
185
+ const at = buffer.indexOf("\r\n\r\n");
186
+ if (at === -1 || at + 4 > MAX_HEAD) {
187
+ if (buffer.length > MAX_HEAD)
188
+ finish({ status: 400, error: "Request is too large." });
189
+ return;
190
+ }
191
+ headEnd = at + 4;
192
+ const declared = /\r\ncontent-length:[ \t]*(\d{1,7})[ \t]*\r\n/i.exec(buffer.subarray(0, headEnd).toString("latin1"));
193
+ // Over the cap, admission refuses it without waiting for the bytes.
194
+ wanted = declared && Number(declared[1]) <= bodyCap ? Number(declared[1]) : 0;
195
+ }
196
+ if (buffer.length - headEnd >= wanted)
197
+ complete();
198
+ };
199
+ const end = () => headEnd === -1 ? finish({ status: 400, error: "Malformed request." }) : complete();
200
+ const timer = setTimeout(() => finish({ status: 408, error: "The request did not arrive in time." }), READ_TIMEOUT_MS);
201
+ input.on("data", data);
202
+ input.once("end", end);
203
+ input.once("error", end);
204
+ });
205
+ }
206
+ /**
207
+ * Serve one scoped SSH session. Commands other than the pipe are refused
208
+ * outright; a refused request gets an HTTP error on the channel so the client
209
+ * reads a normal response.
210
+ */
211
+ export async function scopedDispatch(scope, command, io) {
212
+ if (!isGatewayScope(scope))
213
+ throw new BridgeError(403, "Unknown key scope.");
214
+ if (command !== SCOPED_COMMAND)
215
+ throw new BridgeError(403, `This SSH key only permits \`${SCOPED_COMMAND}\` with ${DESCRIBE[scope]}.`);
216
+ const read = await readRequest(scope, io.input);
217
+ const admission = "head" in read ? admitScopedRequest(scope, read.head, read.rest) : refuse(read.status, read.error);
218
+ if (!admission.ok) {
219
+ await new Promise(done => io.output.write(httpResponse(admission.status, admission.error), () => done()));
220
+ return;
221
+ }
222
+ await new Promise(resolve => {
223
+ const socket = connect(io.socket);
224
+ let answered = false;
225
+ socket.once("data", () => { answered = true; });
226
+ socket.on("connect", () => {
227
+ // Never half-close: the Hook answers and closes (Connection: close).
228
+ socket.write(admission.request);
229
+ socket.pipe(io.output, { end: false });
230
+ });
231
+ socket.on("error", () => {
232
+ if (answered)
233
+ return;
234
+ answered = true;
235
+ io.output.write(httpResponse(503, "Phren Hook is not running on this computer."));
236
+ });
237
+ socket.on("close", () => resolve());
238
+ });
239
+ }
@@ -47,6 +47,18 @@ export interface LaunchOptions {
47
47
  * scheduled project's source folder), so it may be marked trusted for the
48
48
  * harness before the launch. Never set for a folder the phone chose. */
49
49
  trustFolder?: boolean;
50
+ /** Start the agent in this existing pane, at its shell prompt, instead of a
51
+ * new one: a session moved to another harness (session-move.ts). Herdr
52
+ * gives a pane its variables only when it is created, so the caller uses
53
+ * this only where the pane's shell already has what the agent needs. */
54
+ into?: {
55
+ workspaceId: string;
56
+ tabId: string;
57
+ paneId: string;
58
+ };
59
+ /** The `PHREN_DISPATCH_ID` the agent gets when it is not the brief's own id:
60
+ * a moved worker keeps the dispatch it was launched for. */
61
+ dispatchId?: string;
50
62
  }
51
63
  /**
52
64
  * "Open on a computer": a new Herdr workspace (or a tab in an existing one)
@@ -19,6 +19,7 @@ import { clearConductor, conductorPane, noteConductorSession, readRoleState, rec
19
19
  import { localNames } from "./computer-names.js";
20
20
  import { pretrustFolder } from "./folder-trust.js";
21
21
  import { claudeHome, claudeLaunchEnv, isAccountSlug, DEFAULT_ACCOUNT } from "./claude-accounts.js";
22
+ import { pickClaudeAccount } from "./account-choice.js";
22
23
  import { harnessInventoryWithin, hasUsable, launchCheckOff } from "./harnesses.js";
23
24
  import { paneAccountKey, recordPaneAccount } from "./pane-accounts.js";
24
25
  import { optionalHookPeers } from "./peers.js";
@@ -320,6 +321,8 @@ async function startSession(server, data, options) {
320
321
  if (agentFolder && (role !== "agent" || data.project !== undefined || (data.cwd !== undefined && data.cwd !== "") || data.worktree != null)) {
321
322
  throw new BridgeError(400, "An agent folder is for a projectless agent without cwd or worktree.");
322
323
  }
324
+ if (options.into && (role !== "agent" || agentFolder || data.worktree != null))
325
+ throw new BridgeError(400, "Only a worker starts in an existing pane, in that pane's folder.");
323
326
  const projectDirectory = agentFolder ? undefined
324
327
  : z.string().min(1).max(4096).refine(t => path.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
325
328
  const worktreeRequest = data.worktree === undefined || data.worktree === null ? undefined : launchWorktreeSchema.parse(data.worktree);
@@ -328,7 +331,7 @@ async function startSession(server, data, options) {
328
331
  const label = plainText(200).parse(data.label);
329
332
  const kind = z.enum(launchKinds).parse(data.kind);
330
333
  const effort = z.enum(launchEfforts).default("medium").parse(data.effort);
331
- const account = data.account === undefined || data.account === null ? undefined : z.string().refine(isAccountSlug, "Account must be default or a lowercase slug.").parse(data.account);
334
+ const named = data.account === undefined || data.account === null ? undefined : z.string().refine(isAccountSlug, "Account must be default or a lowercase slug.").parse(data.account);
332
335
  const permissionMode = z.enum(PERMISSION_MODES).optional().parse(data.permissionMode ?? undefined);
333
336
  if (permissionMode && role === "conductor")
334
337
  throw new BridgeError(400, "A conductor starts with its own permissions; permissionMode is for workers.");
@@ -362,6 +365,9 @@ async function startSession(server, data, options) {
362
365
  // Herdr 0.9.1 refuses a start timeout of 3000 ms or less (invalid_agent_timeout).
363
366
  const timeout = Math.min(120_000, Math.max(3_001, data.timeoutMs === undefined ? 45_000 : z.number().int().parse(data.timeoutMs)));
364
367
  // Checked before anything is created, so a refusal leaves no pane, worktree or brief file behind.
368
+ // A Claude launch that names no account runs under the signed-in one with the most room left.
369
+ const choice = kind === "claude" && named === undefined ? await pickClaudeAccount(`Launch "${label}"`).catch(() => undefined) : undefined;
370
+ const account = named ?? choice?.account;
365
371
  await requireAvailable(kind, account);
366
372
  const home = kind === "claude" && account && account !== DEFAULT_ACCOUNT ? claudeHome(account) : undefined;
367
373
  if (kind === "claude" && account && account !== DEFAULT_ACCOUNT && !home)
@@ -397,7 +403,8 @@ async function startSession(server, data, options) {
397
403
  const briefFile = brief && (launchesWithBrief(kind) || structured || served) ? await writeLaunchBrief(brief, Date.now(), label) : undefined;
398
404
  const briefLaunch = brief && briefFile && launchesWithBrief(kind) ? briefArgs(kind, briefFile) : undefined;
399
405
  // sudo -A in the new agent asks the phone for the password (sudo.ts).
400
- const variables = { ...askpassEnv(), ...(brief ? { [DISPATCH_ID_ENV]: brief.id } : {}), ...served?.env, ...(home ? claudeLaunchEnv(home) : {}) };
406
+ const dispatchId = options.dispatchId ?? brief?.id;
407
+ const variables = { ...askpassEnv(), ...(dispatchId ? { [DISPATCH_ID_ENV]: dispatchId } : {}), ...served?.env, ...(home ? claudeLaunchEnv(home) : {}) };
401
408
  const env = Object.keys(variables).length ? variables : undefined;
402
409
  if (workspace && !objects(before.workspaces).some(w => w.workspace_id === workspace))
403
410
  throw new BridgeError(409, "The workspace changed.");
@@ -428,16 +435,18 @@ async function startSession(server, data, options) {
428
435
  // agent too; a folder the Hook picked or just created is trusted up front.
429
436
  if (scratch || worktree || options.trustFolder)
430
437
  await pretrustFolder(kind, cwd, scratch ? "new agent folder" : worktree ? `new worktree for ${worktree.branch}` : "project folder", home ? { ...process.env, ...claudeLaunchEnv(home) } : process.env);
431
- try {
432
- await terminalProvider().create(server, { workspace, label, cwd, ...(env ? { env } : {}) });
433
- }
434
- catch (error) {
435
- await worktree?.discard();
436
- if (scratch)
437
- await rmdir(scratch).catch(() => undefined);
438
- throw error;
438
+ if (!options.into) {
439
+ try {
440
+ await terminalProvider().create(server, { workspace, label, cwd, ...(env ? { env } : {}) });
441
+ }
442
+ catch (error) {
443
+ await worktree?.discard();
444
+ if (scratch)
445
+ await rmdir(scratch).catch(() => undefined);
446
+ throw error;
447
+ }
439
448
  }
440
- let created;
449
+ let created = options.into;
441
450
  for (let attempt = 0; attempt < 25 && !created; attempt++) {
442
451
  const s = await snapshot(server);
443
452
  const fresh = objects(s.tabs).filter(t => !knownTabs.has(t.tab_id)
@@ -496,6 +505,8 @@ async function startSession(server, data, options) {
496
505
  const host = terminalName(server);
497
506
  const reason = error instanceof BridgeError && error.status === 504 ? "it did not become ready in time"
498
507
  : error instanceof BridgeError && error.message.startsWith(`${host}: `) ? error.message.slice(host.length + 2) : `${host} reported an error`;
508
+ if (options.into)
509
+ throw new BridgeError(409, `${host} couldn't start ${kind} in the "${label}" pane (${reason}). The pane is still open at its shell prompt.`);
499
510
  throw new BridgeError(409, `${host} couldn't start ${kind} in the new "${label}" pane (${reason}). The workspace was created and is still open on the computer — open it from ${host === "Herdr" ? "Herdr workspaces" : "its tmux session"}.`);
500
511
  }
501
512
  }
@@ -536,7 +547,7 @@ async function startSession(server, data, options) {
536
547
  await new JobRegistry().register({ pane: { server, pane: created.paneId, ...(created.workspaceId ? { workspace: created.workspaceId } : {}), agent: kind, label },
537
548
  ...(sessionId ? { session: sessionId } : {}), agent: kind, label, command: kind }).catch(() => undefined);
538
549
  }
539
- return { ok: true, ...created, cwd, agent: kind, agentStatus, role, sessionId, target, ...(account ? { account } : {}), ...(permissionMode ? { permissionMode } : {}), ...(unchecked.length ? { unchecked } : {}),
550
+ return { ok: true, ...created, cwd, agent: kind, agentStatus, role, sessionId, target, ...(account ? { account } : {}), ...(choice ? { accountChoice: choice.reason } : {}), ...(permissionMode ? { permissionMode } : {}), ...(unchecked.length ? { unchecked } : {}),
540
551
  // The caller types the brief itself unless it went with the launch.
541
552
  ...(brief ? { briefLaunched: appServer ? briefTurn !== undefined : !!briefLaunch || !!servedBrief,
542
553
  briefState: appServer ? briefTurn ?? "unconfirmed" : served ? (servedBrief?.delivered ? "sent" : "uncertain") : briefLaunch ? "sent" : "unconfirmed" } : {}),
@@ -1,10 +1,12 @@
1
1
  import path from "node:path";
2
2
  import { setTimeout as sleep } from "node:timers/promises";
3
3
  import { z } from "zod";
4
- import { gitBranches, gitDiscard, gitLog, gitPulls, gitStage, gitStatus, gitTree, gitUnstage } from "./git.js";
4
+ import { gitBranches, gitDiscard, gitLog, gitPulls, gitShow, gitStage, gitStatus, gitTree, gitUnstage } from "./git.js";
5
5
  import { fanoutWorktrees } from "./fanouts.js";
6
6
  import { gitWorktrees, resolveWorktree } from "./git-worktrees.js";
7
- import { gitCommit, gitPullRequest, gitPush } from "./git-publish.js";
7
+ import { gitCommit, gitHostToken, gitMergeRequest, gitPullRequest, gitPush } from "./git-publish.js";
8
+ import { gitCheckout, gitFetch, gitPull } from "./git-sync.js";
9
+ import { gitApply, gitFile, sessionChanges } from "./git-review.js";
8
10
  import { findPane, paneAgentName, paneChatState, paneIdentity, snapshot, startingPane, trustedDirectory, validateStartingTarget, validateTarget } from "./herdr.js";
9
11
  import { agentNotReady, terminalProvider } from "./terminal.js";
10
12
  import { AppServerRpcError } from "./codex-app-server.js";
@@ -17,6 +19,8 @@ import { BridgeError, MAX_FRAME, object, objects, startingTargetSchema, targetSc
17
19
  import { childAgent, childAgentTree, conversationNamedPaths, targetTranscriptPath } from "./transcripts.js";
18
20
  import { sideQuestionText } from "./side-questions.js";
19
21
  import { saveUpload } from "./uploads.js";
22
+ import { writeRepoFile } from "./file-write.js";
23
+ import { fileSearchSchema, listRepositoryFiles, searchRepository } from "./file-search.js";
20
24
  import { deliveryIdSchema, PromptOnce, promptScope } from "./prompt-once.js";
21
25
  import { promptWithStartupRetry } from "./prompt-startup.js";
22
26
  import { sendServedPrompt, servedPane } from "./opencode-panes.js";
@@ -652,11 +656,35 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
652
656
  result = await repositoryDiff(cwd, paths, allowed);
653
657
  }
654
658
  }
659
+ else if (url.pathname === "/v1/files/write") {
660
+ // The desktop editor's save, inside the pane's repository (or a child's worktree).
661
+ const cwd = await gitRepository(pane, target, data.child, data.worktree);
662
+ const repository = await gitRoot(cwd);
663
+ if (!repository)
664
+ throw new BridgeError(409, "This pane is not in a project repository.");
665
+ result = await writeRepoFile(repository, z.string().max(4096).parse(data.path), z.string().parse(data.content), data.version === undefined ? undefined : z.string().max(200).parse(data.version));
666
+ }
667
+ else if (url.pathname === "/v1/files/list") {
668
+ // Every file path in the repository, for the desktop editor's quick open.
669
+ const repository = await gitRoot(await gitRepository(pane, target, data.child, data.worktree));
670
+ if (!repository)
671
+ throw new BridgeError(409, "This pane is not in a project repository.");
672
+ result = await listRepositoryFiles(repository);
673
+ }
674
+ else if (url.pathname === "/v1/files/search") {
675
+ // The desktop editor's find in files, over the same repository.
676
+ const repository = await gitRoot(await gitRepository(pane, target, data.child, data.worktree));
677
+ if (!repository)
678
+ throw new BridgeError(409, "This pane is not in a project repository.");
679
+ result = await searchRepository(repository, fileSearchSchema.parse({
680
+ query: data.query, regex: data.regex, caseSensitive: data.caseSensitive, wholeWord: data.wholeWord, include: data.include, limit: data.limit,
681
+ }));
682
+ }
655
683
  else if (url.pathname.startsWith("/v1/git/")) {
656
684
  // Git routes read the pane's repository, or a spawned child's own
657
685
  // worktree, exactly as /v1/diff resolves it.
658
686
  let cwd = await gitRepository(pane, target, data.child, data.worktree);
659
- if (["stage", "unstage", "discard", "commit", "push", "pr"].some(action => url.pathname === `/v1/git/${action}`)
687
+ if (["stage", "unstage", "discard", "commit", "push", "pr", "pr/merge", "host-token", "checkout", "fetch", "pull", "apply"].some(action => url.pathname === `/v1/git/${action}`)
660
688
  && data.expectedRepository !== undefined) {
661
689
  const expected = z.string().min(1).max(4096).refine(value => path.isAbsolute(value) && !value.includes("\0"), "Expected an absolute repository path.").parse(data.expectedRepository);
662
690
  const root = await gitRoot(cwd);
@@ -688,6 +716,29 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
688
716
  result = await gitPush(cwd, data.confirmDefault);
689
717
  else if (url.pathname === "/v1/git/pr")
690
718
  result = await gitPullRequest(cwd, data.draft);
719
+ else if (url.pathname === "/v1/git/pr/merge")
720
+ result = await gitMergeRequest(cwd, data);
721
+ else if (url.pathname === "/v1/git/host-token")
722
+ result = await gitHostToken(cwd, data);
723
+ else if (url.pathname === "/v1/git/show")
724
+ result = await gitShow(cwd, data.sha);
725
+ else if (url.pathname === "/v1/git/checkout")
726
+ result = await gitCheckout(cwd, data);
727
+ else if (url.pathname === "/v1/git/fetch")
728
+ result = await gitFetch(cwd);
729
+ else if (url.pathname === "/v1/git/pull")
730
+ result = await gitPull(cwd);
731
+ else if (url.pathname === "/v1/git/file")
732
+ result = await gitFile(cwd, data.ref, data.path);
733
+ else if (url.pathname === "/v1/git/apply")
734
+ result = await gitApply(cwd, data.patch, data.reverse);
735
+ else if (url.pathname === "/v1/git/session-changes") {
736
+ // This conversation's own recorded edits, in the repository the route resolved.
737
+ const root = await gitRoot(cwd);
738
+ if (!root)
739
+ throw new BridgeError(409, "This pane is not in a Git repository.", { code: "git-not-repository" });
740
+ result = sessionChanges(root, await agentHooks.changes.history(`${target.source}:${target.session}`));
741
+ }
691
742
  else
692
743
  throw new BridgeError(404, "Unknown Phren Hook route.");
693
744
  }
@@ -1,3 +1,4 @@
1
+ import { type SessionMover } from "./session-move.js";
1
2
  import type { OwnerInbox } from "./owner-inbox.js";
2
3
  import type { HandOffQueue } from "./hand-off-queue.js";
3
4
  import type { IncomingMessage, ServerResponse } from "node:http";
@@ -55,6 +56,7 @@ export interface RouteContext {
55
56
  returns?: DispatchReturns;
56
57
  handOffs?: HandOffQueue;
57
58
  inbox?: OwnerInbox;
59
+ mover?: SessionMover;
58
60
  agentHooks: AgentHooks;
59
61
  journal: ActivityJournal;
60
62
  tabActivity: TabActivityStore;
@@ -83,6 +85,9 @@ export declare const capabilities: {
83
85
  stop: boolean;
84
86
  terminal: string;
85
87
  shell: string;
88
+ paneTerminal: string;
89
+ paneLayout: boolean;
90
+ deskPresence: boolean;
86
91
  herdr: boolean;
87
92
  sessionRename: boolean;
88
93
  diff: boolean;
@@ -127,6 +132,13 @@ export declare const capabilities: {
127
132
  quickChat: boolean;
128
133
  agentFolder: boolean;
129
134
  launchPermissionMode: boolean;
135
+ sessionMove: boolean;
136
+ projectMemory: boolean;
137
+ fileWrite: boolean;
138
+ fileSearch: boolean;
139
+ gitReview: boolean;
140
+ memoryStoreBatch: boolean;
141
+ gitHosts: boolean;
130
142
  };
131
143
  export declare function capabilitiesForModules(snapshot: ModuleSnapshot): Record<string, unknown>;
132
144
  export declare function requireRoute(snapshot: ModuleSnapshot, method: string, route: string): void;
@@ -1,3 +1,4 @@
1
+ import { listMoves, readMove } from "./session-move.js";
1
2
  import { getTaskRoute, getTaskDirectoryRoute, updateTaskRoute, createTaskRoute, saveTaskRoute, launchTaskRoute } from "./task-routes.js";
2
3
  import { ownerInboxView } from "./owner-inbox-view.js";
3
4
  import { closeFinishedWorker } from "./worker-close.js";
@@ -15,7 +16,7 @@ import { resolveCodeStore, CodeRoutes } from "./code-routes.js";
15
16
  import { dispatchProjectDirectory, dispatchStatus, originPaneSchema } from "./dispatch.js";
16
17
  import { hookWorkers } from "./dispatch-returns.js";
17
18
  import { remoteChildren } from "./dispatch-tree.js";
18
- import { briefArrival, briefId } from "./launch-brief.js";
19
+ import { briefArrival, briefId, readLaunchBrief } from "./launch-brief.js";
19
20
  import { listApprovalRules, changeApprovalRule } from "./approval-rules.js";
20
21
  import { addGrant, listNamedGrants, removeGrant } from "./grants.js";
21
22
  import { clearProjectAuthority, confirmAuthority, listConfirmations, projectAuthority, readAuthority, setProjectAuthority } from "./authority.js";
@@ -26,8 +27,9 @@ import { browseFiles } from "./files.js";
26
27
  import { MAX_FILE_RANGE, rangeInteger, readFileRange } from "./file-range.js";
27
28
  import { resolveFilePath } from "./file-resolve.js";
28
29
  import { storeRoute } from "./memory-store.js";
30
+ import { memoryForFiles, memorySearch, PROJECT_MEMORY_ROUTE, projectMemory, saveFinding, tasksForBranch } from "./project-memory.js";
29
31
  import { liveBackground, markBackground, paneRecord, recordTitle } from "./session-activity.js";
30
- import { paneAccountField, paneChatState, panes, servers, snapshot, validateTarget, workspaceSnapshot } from "./herdr.js";
32
+ import { paneAccountField, paneChatState, panes, rpc, servers, snapshot, validateTarget, workspaceSnapshot } from "./herdr.js";
31
33
  import { locateProject } from "./locate.js";
32
34
  import { gitStatus } from "./git.js";
33
35
  import { gitRoot, launchDirectory, repositoryBranch, webServers, withGitReadDeadline } from "./projects.js";
@@ -74,9 +76,9 @@ async function childActivity(source, session) {
74
76
  return result;
75
77
  }
76
78
  export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
77
- terminal: "ssh-pty", shell: "ssh-pty", herdr: true, sessionRename: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
79
+ terminal: "ssh-pty", shell: "ssh-pty", paneTerminal: "ssh-pty", paneLayout: true, deskPresence: true, herdr: true, sessionRename: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
78
80
  approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
79
- files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true };
81
+ files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true };
80
82
  export function capabilitiesForModules(snapshot) {
81
83
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
82
84
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
@@ -306,7 +308,27 @@ export function createRouteHandler(ctx) {
306
308
  throw new BridgeError(400, "Invalid request origin.");
307
309
  requireRoute(modules, request.method ?? "", url.pathname);
308
310
  let result;
309
- if (url.pathname.startsWith("/v1/store/")) {
311
+ const memoryRoute = PROJECT_MEMORY_ROUTE.exec(url.pathname);
312
+ if (memoryRoute) {
313
+ const [, project, route] = memoryRoute;
314
+ if (request.method !== (route === "findings" ? "POST" : "GET"))
315
+ throw new BridgeError(405, "Unsupported request method.");
316
+ if (!modules.has("memory"))
317
+ throw new BridgeError(404, disabledHint("memory"));
318
+ if (route === "tasks" && !modules.has("tasks"))
319
+ throw new BridgeError(404, disabledHint("tasks"));
320
+ if (route === "memory")
321
+ result = projectMemory(modules.store, project);
322
+ else if (route === "memory/files")
323
+ result = await memoryForFiles(modules.store, project, url.searchParams.getAll("path"));
324
+ else if (route === "memory/search")
325
+ result = memorySearch(modules.store, project, url.searchParams.get("q") ?? "", Number(url.searchParams.get("limit") ?? "5"));
326
+ else if (route === "tasks")
327
+ result = tasksForBranch(modules.store, project, url.searchParams.get("branch") ?? "");
328
+ else
329
+ result = await saveFinding(modules.store, project, await body(request));
330
+ }
331
+ else if (url.pathname.startsWith("/v1/store/")) {
310
332
  result = await storeRoute(modules.store, request.method ?? "", url, request.method === "POST" ? await body(request) : undefined);
311
333
  }
312
334
  else if (request.method === "GET") {
@@ -343,10 +365,25 @@ export function createRouteHandler(ctx) {
343
365
  case "/v1/dispatch":
344
366
  result = { dispatches: await dispatchStatus() };
345
367
  break;
368
+ // A session move (session-move.ts) by its id, or this computer's recent moves.
369
+ case "/v1/sessions/move": {
370
+ const move = await readMove(z.string().uuid().parse(url.searchParams.get("id")));
371
+ if (!move)
372
+ throw new BridgeError(404, "No move with that id on this computer.");
373
+ result = { move };
374
+ break;
375
+ }
376
+ case "/v1/sessions/moves":
377
+ result = { moves: (await listMoves()).slice(0, 50) };
378
+ break;
346
379
  // Receiving side of a launched brief: what the worker's hooks reported for it.
347
380
  case "/v1/dispatch/arrival":
348
381
  result = { arrival: await briefArrival(briefId.parse(url.searchParams.get("id"))) ?? null };
349
382
  break;
383
+ // Asked by the dispatching Hook when this computer's worker hit its usage limit and continues on another account.
384
+ case "/v1/dispatch/brief":
385
+ result = { text: await readLaunchBrief(briefId.parse(url.searchParams.get("id"))) ?? null };
386
+ break;
350
387
  case "/v1/approval-rules":
351
388
  result = { rules: await listApprovalRules(undefined, z.string().regex(/^[A-Za-z0-9+/]{43}=$/).optional().parse(url.searchParams.get("pairedKey") ?? undefined)) };
352
389
  break;
@@ -542,6 +579,17 @@ export function createRouteHandler(ctx) {
542
579
  result = muxReplyForClient(await readWorkspaces(server, await snapshot(server), url.searchParams.get("watchApprovals") === "1"), typedMuxRequest(url));
543
580
  break;
544
581
  }
582
+ case "/v1/workspaces/layout": {
583
+ // A Herdr tab's split layout (pane rects and splits) around one of its panes, for
584
+ // Phren desktop's mirror of a Herdr tab. Herdr only: tmux has no such query here.
585
+ const server = selectedServer(url);
586
+ if (terminalKind(server) !== "herdr")
587
+ throw new BridgeError(501, "Pane layouts need Herdr.");
588
+ const pane = z.string().regex(/^[A-Za-z0-9_:.-]{1,100}$/).parse(url.searchParams.get("pane"));
589
+ const answer = await rpc(server, "pane.layout", { pane_id: pane });
590
+ result = { layout: object(answer).layout ?? null };
591
+ break;
592
+ }
545
593
  case "/v1/workspaces/panes":
546
594
  result = muxReplyForClient(await panes(selectedServer(url), url.searchParams.get("groupId") || "", url.searchParams.get("childId") || ""), typedMuxRequest(url));
547
595
  break;
@@ -688,6 +736,12 @@ export function createRouteHandler(ctx) {
688
736
  harness: note.target && "harness" in note.target ? note.target.harness : "codex", prompt, label: `Code note: ${note.symbol}`.slice(0, 200) });
689
737
  } : undefined);
690
738
  }
739
+ else if (url.pathname === "/v1/sessions/move") {
740
+ // Answers once the move is checked and recorded; the hand-off and relaunch run on, and GET says where it is.
741
+ if (!ctx.mover)
742
+ throw new BridgeError(503, "This Hook cannot move sessions.");
743
+ result = { ok: true, move: await ctx.mover.start(data) };
744
+ }
691
745
  else if (url.pathname === "/v1/sessions/rename") {
692
746
  result = await renameSession(selectedServer(url), data);
693
747
  }
@@ -802,6 +856,11 @@ export function createRouteHandler(ctx) {
802
856
  await agentHooks.answerPush(z.string().uuid().parse(data.binding), data.decision);
803
857
  result = { ok: true };
804
858
  }
859
+ else if (url.pathname === "/v1/push/presence") {
860
+ // Phren desktop: the owner is at the desk, so approval alerts wait before reaching the phone.
861
+ agentHooks.push.markDesk(z.number().int().min(0).max(120_000).parse(data.activeForMs));
862
+ result = { ok: true, deskActive: agentHooks.push.deskActive };
863
+ }
805
864
  else if (url.pathname === "/v1/push/target") {
806
865
  // A tapped notification opens its session; the binding stays unspent.
807
866
  const target = agentHooks.pushTarget(z.string().uuid().parse(data.binding));