@phren/cli 0.3.37 → 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 (93) hide show
  1. package/dist/bridge/account-failover.d.ts +4 -0
  2. package/dist/bridge/account-failover.js +12 -4
  3. package/dist/bridge/account-usage.d.ts +5 -2
  4. package/dist/bridge/account-usage.js +36 -6
  5. package/dist/bridge/agent-hooks.js +2 -0
  6. package/dist/bridge/changes.d.ts +5 -0
  7. package/dist/bridge/changes.js +4 -0
  8. package/dist/bridge/claude-accounts.d.ts +15 -4
  9. package/dist/bridge/claude-accounts.js +31 -16
  10. package/dist/bridge/claude-credits.d.ts +43 -0
  11. package/dist/bridge/claude-credits.js +236 -0
  12. package/dist/bridge/claude-question-dialog.js +6 -2
  13. package/dist/bridge/command.js +64 -3
  14. package/dist/bridge/device-enroll.d.ts +34 -0
  15. package/dist/bridge/device-enroll.js +57 -0
  16. package/dist/bridge/dispatch-command.d.ts +2 -0
  17. package/dist/bridge/dispatch-command.js +25 -1
  18. package/dist/bridge/dispatch-returns.d.ts +7 -0
  19. package/dist/bridge/dispatch-returns.js +56 -6
  20. package/dist/bridge/dispatch.d.ts +52 -0
  21. package/dist/bridge/dispatch.js +14 -0
  22. package/dist/bridge/file-range.d.ts +3 -0
  23. package/dist/bridge/file-range.js +5 -4
  24. package/dist/bridge/file-search.d.ts +37 -0
  25. package/dist/bridge/file-search.js +87 -0
  26. package/dist/bridge/file-write.d.ts +6 -0
  27. package/dist/bridge/file-write.js +120 -0
  28. package/dist/bridge/git-host-auth.d.ts +31 -0
  29. package/dist/bridge/git-host-auth.js +110 -0
  30. package/dist/bridge/git-host-gitboy.d.ts +46 -0
  31. package/dist/bridge/git-host-gitboy.js +296 -0
  32. package/dist/bridge/git-host-gitlab.d.ts +25 -0
  33. package/dist/bridge/git-host-gitlab.js +229 -0
  34. package/dist/bridge/git-host-http.d.ts +33 -0
  35. package/dist/bridge/git-host-http.js +70 -0
  36. package/dist/bridge/git-hosts.d.ts +92 -0
  37. package/dist/bridge/git-hosts.js +244 -0
  38. package/dist/bridge/git-publish.d.ts +15 -5
  39. package/dist/bridge/git-publish.js +69 -21
  40. package/dist/bridge/git-review.d.ts +23 -0
  41. package/dist/bridge/git-review.js +170 -0
  42. package/dist/bridge/git-sync.d.ts +14 -0
  43. package/dist/bridge/git-sync.js +143 -0
  44. package/dist/bridge/git.d.ts +20 -7
  45. package/dist/bridge/git.js +87 -68
  46. package/dist/bridge/gitboy-contract.d.ts +32 -0
  47. package/dist/bridge/gitboy-contract.js +46 -0
  48. package/dist/bridge/hand-off.d.ts +52 -2
  49. package/dist/bridge/hand-off.js +77 -24
  50. package/dist/bridge/health.d.ts +1 -1
  51. package/dist/bridge/health.js +5 -3
  52. package/dist/bridge/install.d.ts +14 -0
  53. package/dist/bridge/install.js +40 -1
  54. package/dist/bridge/memory-store.d.ts +8 -0
  55. package/dist/bridge/memory-store.js +80 -2
  56. package/dist/bridge/pair.d.ts +6 -1
  57. package/dist/bridge/pair.js +74 -2
  58. package/dist/bridge/project-memory.d.ts +94 -0
  59. package/dist/bridge/project-memory.js +235 -0
  60. package/dist/bridge/push.d.ts +15 -0
  61. package/dist/bridge/push.js +39 -0
  62. package/dist/bridge/scoped-gateway.d.ts +29 -0
  63. package/dist/bridge/scoped-gateway.js +239 -0
  64. package/dist/bridge/server-launch.d.ts +12 -0
  65. package/dist/bridge/server-launch.js +17 -10
  66. package/dist/bridge/server-pane-routes.js +54 -3
  67. package/dist/bridge/server-routes.d.ts +12 -0
  68. package/dist/bridge/server-routes.js +59 -4
  69. package/dist/bridge/server.js +44 -5
  70. package/dist/bridge/session-move.d.ts +288 -0
  71. package/dist/bridge/session-move.js +600 -0
  72. package/dist/bridge/subscription.d.ts +15 -0
  73. package/dist/bridge/subscription.js +23 -0
  74. package/dist/bridge/transport.js +21 -1
  75. package/dist/bridge/usage.d.ts +20 -3
  76. package/dist/bridge/usage.js +61 -11
  77. package/dist/bridge-hook.mjs +12751 -3207
  78. package/dist/cli-registry.js +10 -4
  79. package/dist/computers/command.js +3 -1
  80. package/dist/computers/read.d.ts +3 -0
  81. package/dist/computers/read.js +6 -0
  82. package/dist/content/summarize.d.ts +21 -0
  83. package/dist/content/summarize.js +56 -18
  84. package/dist/modules/registry.js +12 -12
  85. package/dist/project-config.d.ts +12 -0
  86. package/dist/project-config.js +29 -0
  87. package/dist/shared/retrieval.d.ts +1 -0
  88. package/dist/shared/retrieval.js +1 -1
  89. package/dist/sync/conflict-resolve.js +5 -6
  90. package/dist/tools/dispatch.js +18 -1
  91. package/dist/tools/finding.d.ts +25 -0
  92. package/dist/tools/finding.js +2 -1
  93. package/package.json +57 -1
@@ -0,0 +1,235 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { readFindings } from "../data/access.js";
4
+ import { readTasks } from "../data/tasks.js";
5
+ import { taskStores } from "../data/task-store-directory.js";
6
+ import { FINDING_TAGS } from "../phren-core.js";
7
+ import { getProjectRemote, readProjectConfig } from "../project-config.js";
8
+ import { redactSecretsForLog } from "../content/secrets.js";
9
+ import { resolveProject } from "../store-routing.js";
10
+ import { isValidProjectName } from "../utils.js";
11
+ import { BridgeError } from "./protocol.js";
12
+ import { moduleEnabled } from "../modules/runtime.js";
13
+ import { loadCodePackage } from "../modules/code-package.js";
14
+ import { bestChunkMatch, tokenizeForOverlap } from "../shared/retrieval.js";
15
+ import { findingWriteSchema, isBranchName, isRepoPath, isSearchText, MAX_FILE_PATHS, MAX_FINDING_BODY, MAX_SEARCH_LIMIT } from "./gitboy-contract.js";
16
+ // `GET /v1/projects/:project/memory`: one project's findings, truths and
17
+ // tasks as a fixed read-only contract, for a client that renders them beside
18
+ // the repository (gitboy). Phren stays the source of truth; nothing here
19
+ // writes. The scoped `gitboy-read` SSH key reaches only this route
20
+ // (scoped-gateway.ts). Contract: docs/phren-hook.md#gitboy-read-only-memory.
21
+ export const PROJECT_MEMORY_ROUTE = /^\/v1\/projects\/([^/]+)\/(memory|memory\/files|memory\/search|tasks|findings)$/;
22
+ export const MEMORY_LIMITS = { findings: 500, active: 200, queue: 200, done: 50 };
23
+ const TAG = new RegExp(`^\\[(${FINDING_TAGS.join("|")})\\]\\s*`, "i");
24
+ const DATE = /^\d{4}-\d{2}-\d{2}/;
25
+ /** Text that trips phren's credential detector is withheld whole, never cut. */
26
+ const safe = (text) => redactSecretsForLog(text);
27
+ function finding(item) {
28
+ const tag = TAG.exec(item.text);
29
+ const cite = item.citationData;
30
+ const citation = cite && (cite.file || cite.line || cite.commit || cite.symbol)
31
+ ? { file: cite.file ?? null, line: Number.isInteger(cite.line) ? cite.line : null, commit: cite.commit ?? null, name: cite.symbol ?? null }
32
+ : null;
33
+ const created = DATE.test(item.date) ? item.date.slice(0, 10) : cite?.created_at && DATE.test(cite.created_at) ? cite.created_at.slice(0, 10) : null;
34
+ return {
35
+ id: item.stableId ? `fid:${item.stableId}` : item.id,
36
+ text: safe(tag ? item.text.slice(tag[0].length) : item.text),
37
+ type: tag ? tag[1].toLowerCase() : null,
38
+ status: item.status, created, citation,
39
+ };
40
+ }
41
+ function task(item) {
42
+ return {
43
+ id: item.stableId ? `bid:${item.stableId}` : item.id,
44
+ text: safe(item.line), created: item.createdAt ?? null,
45
+ context: item.context ? safe(item.context) : null,
46
+ };
47
+ }
48
+ function locate(base, rawProject) {
49
+ let project;
50
+ try {
51
+ project = decodeURIComponent(rawProject);
52
+ }
53
+ catch {
54
+ throw new BridgeError(400, "Invalid project name.");
55
+ }
56
+ if (!isValidProjectName(project))
57
+ throw new BridgeError(400, "Invalid project name.");
58
+ let root;
59
+ try {
60
+ root = resolveProject(base, project).store.path;
61
+ }
62
+ catch {
63
+ throw new BridgeError(404, "Project not found.");
64
+ }
65
+ const storeId = taskStores(base).find(entry => path.resolve(entry.path) === path.resolve(root))?.taskStoreId ?? null;
66
+ return { project, root, storeId };
67
+ }
68
+ /** Newest first, so a cap drops the oldest. Undated findings sort last. */
69
+ function sortedFindings(root, project) {
70
+ const result = readFindings(root, project);
71
+ if (!result.ok)
72
+ throw new BridgeError(404, "Project not found.");
73
+ return result.data.map((item, index) => ({ item, index, date: DATE.test(item.date) ? item.date : "" }))
74
+ .sort((a, b) => b.date.localeCompare(a.date) || a.index - b.index).map(entry => entry.item);
75
+ }
76
+ function readTruths(root, project) {
77
+ const file = path.join(root, project, "truths.md");
78
+ return fs.existsSync(file) ? fs.readFileSync(file, "utf8").split("\n").filter(line => line.startsWith("- ")).map(line => line.slice(2).trim()) : [];
79
+ }
80
+ export function projectMemory(base, rawProject) {
81
+ const { project, root, storeId } = locate(base, rawProject);
82
+ const allFindings = sortedFindings(root, project);
83
+ const truths = readTruths(root, project).map(text => ({ text: safe(text) }));
84
+ // Tasks are their own module; with it off the sections are empty.
85
+ const taskDoc = readTasks(root, project);
86
+ const items = taskDoc.ok ? taskDoc.data.items : { Active: [], Queue: [], Done: [] };
87
+ const truncated = allFindings.length > MEMORY_LIMITS.findings || items.Active.length > MEMORY_LIMITS.active
88
+ || items.Queue.length > MEMORY_LIMITS.queue || items.Done.length > MEMORY_LIMITS.done;
89
+ return {
90
+ project, store_id: storeId, remote: getProjectRemote(root, project, readProjectConfig(root, project)), truncated,
91
+ findings: allFindings.slice(0, MEMORY_LIMITS.findings).map(finding),
92
+ truths,
93
+ tasks: {
94
+ active: items.Active.slice(0, MEMORY_LIMITS.active).map(task),
95
+ queue: items.Queue.slice(0, MEMORY_LIMITS.queue).map(task),
96
+ // Done is newest first in tasks.md; keep the most recent.
97
+ done: items.Done.slice(0, MEMORY_LIMITS.done).map(task),
98
+ },
99
+ };
100
+ }
101
+ /** Findings about these repository files: cited by file, or citing a function,
102
+ * type or variable the code index places in one of them. */
103
+ export async function memoryForFiles(base, rawProject, paths) {
104
+ const { project, root, storeId } = locate(base, rawProject);
105
+ if (paths.length < 1 || paths.length > MAX_FILE_PATHS || !paths.every(isRepoPath)) {
106
+ throw new BridgeError(400, `Send 1 to ${MAX_FILE_PATHS} repository-relative paths.`);
107
+ }
108
+ const wanted = new Set(paths);
109
+ const all = sortedFindings(root, project);
110
+ const citedFile = (item) => item.citationData?.file?.replace(/^\.\//, "");
111
+ const named = all.filter(item => item.citationData?.symbol && !wanted.has(citedFile(item) ?? ""));
112
+ let symbols = "unavailable";
113
+ let files = {};
114
+ if (named.length && moduleEnabled(root, "code")) {
115
+ const code = await loadCodePackage(root).catch(() => undefined);
116
+ if (code && typeof code.resolveSymbolFiles === "function") {
117
+ const resolved = await code.resolveSymbolFiles(root, project, named.map(item => item.citationData.symbol)).catch(() => undefined);
118
+ if (resolved?.available) {
119
+ symbols = "indexed";
120
+ files = resolved.value;
121
+ }
122
+ }
123
+ }
124
+ const matches = [];
125
+ for (const item of all) {
126
+ const file = citedFile(item), name = item.citationData?.symbol;
127
+ if (file && wanted.has(file))
128
+ matches.push({ ...finding(item), match: "file" });
129
+ else if (name && files[name] && wanted.has(files[name]))
130
+ matches.push({ ...finding(item), match: "symbol" });
131
+ }
132
+ return { project, store_id: storeId, symbols, truncated: matches.length > MEMORY_LIMITS.findings,
133
+ findings: matches.slice(0, MEMORY_LIMITS.findings) };
134
+ }
135
+ /**
136
+ * Findings and truths ranked against `q` with phren's retrieval tokenizer and
137
+ * chunk matcher (the hook's relevance floor). Each query token is weighted by
138
+ * how rare it is across this project's findings and truths (the normalised IDF
139
+ * `tokenRarity` uses), so a stack trace's common words count for little.
140
+ * `score` is the matched share of that weight, 0 to 1; findings that are no
141
+ * longer active count half.
142
+ */
143
+ export function memorySearch(base, rawProject, q, limit) {
144
+ const { project, root } = locate(base, rawProject);
145
+ if (!isSearchText(q))
146
+ throw new BridgeError(400, "q must be 1 to 1000 characters of text.");
147
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_SEARCH_LIMIT)
148
+ throw new BridgeError(400, `limit must be 1 to ${MAX_SEARCH_LIMIT}.`);
149
+ const entries = [
150
+ ...sortedFindings(root, project).map(item => ({ kind: "finding", text: item.text, item })),
151
+ ...readTruths(root, project).map(text => ({ kind: "truth", text, item: undefined })),
152
+ ];
153
+ const tokens = tokenizeForOverlap(q, 64);
154
+ const corpus = entries.map(entry => new Set(tokenizeForOverlap(entry.text, Number.POSITIVE_INFINITY)));
155
+ const total = entries.length, scale = Math.log(total + 1);
156
+ const rarity = new Map();
157
+ for (const token of tokens) {
158
+ const df = corpus.filter(set => set.has(token)).length;
159
+ if (df > 0)
160
+ rarity.set(token, total > 1 ? Math.max(0.05, Math.min(1, Math.log((total + 1) / (df + 1)) / scale)) : 1);
161
+ }
162
+ const present = [...rarity.keys()];
163
+ const weight = present.reduce((sum, token) => sum + rarity.get(token), 0);
164
+ const minimum = Math.min(2, present.length);
165
+ const hits = [];
166
+ if (weight > 0)
167
+ for (const entry of entries) {
168
+ const best = bestChunkMatch(present, { content: entry.text }, rarity);
169
+ if (!best || best.distinct < minimum)
170
+ continue;
171
+ const inactive = entry.item && entry.item.status !== "active";
172
+ const score = Math.round((best.rarity / weight) * (inactive ? 0.5 : 1) * 1000) / 1000;
173
+ const shaped = entry.item ? finding(entry.item) : null;
174
+ hits.push({ kind: entry.kind, score, matched: best.distinct, text: shaped ? shaped.text : safe(entry.text), finding: shaped });
175
+ }
176
+ hits.sort((a, b) => b.score - a.score || b.matched - a.matched);
177
+ return { project, query: q, results: hits.slice(0, limit) };
178
+ }
179
+ // ── /tasks?branch= ───────────────────────────────────────────────────────────
180
+ /** Open tasks that name this branch (or its last segment) or the issue number
181
+ * in it (`fix/123-login`, `issue-123`, `gh-123`). One read of tasks.md. */
182
+ export function tasksForBranch(base, rawProject, branch) {
183
+ const { project, root } = locate(base, rawProject);
184
+ if (!isBranchName(branch))
185
+ throw new BridgeError(400, "Invalid branch name.");
186
+ const taskDoc = readTasks(root, project);
187
+ const items = taskDoc.ok ? taskDoc.data.items : { Active: [], Queue: [], Done: [] };
188
+ const lower = branch.toLowerCase();
189
+ const tail = lower.includes("/") ? lower.slice(lower.lastIndexOf("/") + 1) : "";
190
+ const names = [lower, ...(tail.length >= 4 ? [tail] : [])];
191
+ const issues = [...lower.matchAll(/(?:^|[\/_-])(?:issue-?|gh-?|#)?(\d{1,7})(?=$|[\/_-])/g)].map(match => Number(match[1]));
192
+ const mentionsIssue = (text, issue) => new RegExp(`(?:#|/issues/|/pull/|/pulls/)${issue}(?!\\d)`).test(text);
193
+ const matches = [];
194
+ for (const [section, list] of [["active", items.Active], ["queue", items.Queue]]) {
195
+ for (const item of list) {
196
+ const text = `${item.line}\n${item.context ?? ""}`.toLowerCase();
197
+ const match = names.some(name => text.includes(name)) ? "branch"
198
+ : issues.some(issue => item.githubIssue === issue || (item.githubUrl && mentionsIssue(item.githubUrl, issue)) || mentionsIssue(text, issue)) ? "issue"
199
+ : undefined;
200
+ if (match)
201
+ matches.push({ ...task(item), section, match });
202
+ }
203
+ }
204
+ return { project, branch, truncated: matches.length > 50, tasks: matches.slice(0, 50) };
205
+ }
206
+ // ── POST /findings ───────────────────────────────────────────────────────────
207
+ let writes = Promise.resolve();
208
+ /** Save one finding through the same path as the add_finding MCP tool: the
209
+ * project's write permission, duplicate and conflict checks, the secret
210
+ * scan and citation validation against the code index. */
211
+ export async function saveFinding(base, rawProject, input) {
212
+ const { project } = locate(base, rawProject);
213
+ if (Buffer.byteLength(JSON.stringify(input ?? null)) > MAX_FINDING_BODY)
214
+ throw new BridgeError(413, `The body must be at most ${MAX_FINDING_BODY} bytes.`);
215
+ const body = findingWriteSchema.parse(input);
216
+ const { handleAddFinding } = await import("../tools/finding.js");
217
+ const ctx = {
218
+ phrenPath: base, profile: process.env.PHREN_PROFILE ?? "",
219
+ db: () => { throw new Error("No index in the Hook."); }, rebuildIndex: async () => { }, updateFileInIndex: () => { },
220
+ withWriteQueue: (fn) => { const next = writes.then(fn, fn); writes = next.catch(() => undefined); return next; },
221
+ };
222
+ const response = await handleAddFinding(ctx, {
223
+ project, finding: body.text, findingType: body.type, tool: "gitboy",
224
+ ...(body.citation && Object.keys(body.citation).length ? { citation: body.citation } : {}),
225
+ });
226
+ const result = JSON.parse(response.content[0].text);
227
+ if (!result.ok) {
228
+ const error = result.error ?? "The finding was not saved.";
229
+ throw new BridgeError(/permission|denied|not allowed/i.test(error) ? 403 : 400, safe(error));
230
+ }
231
+ const status = result.data?.status === "skipped" ? "duplicate" : "saved";
232
+ const saved = status === "saved" ? sortedFindings(locate(base, rawProject).root, project)
233
+ .find(item => item.text === (result.data?.finding ?? "").replace(/^-\s+/, "").trim()) : undefined;
234
+ return { project, status, finding: saved ? finding(saved) : null };
235
+ }
@@ -118,7 +118,22 @@ export declare class ApprovalPushService {
118
118
  register(value: unknown): Promise<void>;
119
119
  /** One phone: the relay when it registered through one, otherwise direct. */
120
120
  private send;
121
+ /** Until when the owner is at Phren desktop (ms epoch): approval pushes wait for the desk to go quiet. */
122
+ private deskUntil;
123
+ private held;
124
+ /** Whether an approval is still unanswered; AgentHooks sets it. Unset means "assume pending". */
125
+ stillPending?: (binding: string) => boolean;
126
+ /** Phren desktop saw the owner's keyboard or mouse: hold phone alerts for `activeForMs` (at most 2 min). */
127
+ markDesk(activeForMs: number): void;
128
+ get deskActive(): boolean;
129
+ /**
130
+ * Desk first: while the owner is at the desktop, the desktop shows the
131
+ * approval and the phone stays quiet. Once the desk has been idle past its
132
+ * window and the approval is still pending, the phone gets the alert.
133
+ */
121
134
  notify(value: ApprovalPush): Promise<boolean>;
135
+ private holdForDesk;
136
+ protected notifyNow(value: ApprovalPush): Promise<boolean>;
122
137
  notifySudo(value: SudoRequestView): Promise<boolean>;
123
138
  /** A headless worker whose permission the plugin refused. Approval-registered
124
139
  * phones already accept agent alerts; the payload carries the reason so the
@@ -243,7 +243,46 @@ export class ApprovalPushService {
243
243
  }
244
244
  return this.sender && device.token ? this.sender.send(device, payload, headers) : false;
245
245
  }
246
+ /** Until when the owner is at Phren desktop (ms epoch): approval pushes wait for the desk to go quiet. */
247
+ deskUntil = 0;
248
+ held = new Map();
249
+ /** Whether an approval is still unanswered; AgentHooks sets it. Unset means "assume pending". */
250
+ stillPending;
251
+ /** Phren desktop saw the owner's keyboard or mouse: hold phone alerts for `activeForMs` (at most 2 min). */
252
+ markDesk(activeForMs) {
253
+ const span = Math.min(Math.max(Number.isFinite(activeForMs) ? activeForMs : 0, 0), 120_000);
254
+ this.deskUntil = Math.max(this.deskUntil, Date.now() + span);
255
+ }
256
+ get deskActive() { return Date.now() < this.deskUntil; }
257
+ /**
258
+ * Desk first: while the owner is at the desktop, the desktop shows the
259
+ * approval and the phone stays quiet. Once the desk has been idle past its
260
+ * window and the approval is still pending, the phone gets the alert.
261
+ */
246
262
  async notify(value) {
263
+ if (!this.deskActive)
264
+ return this.notifyNow(value);
265
+ if (!this.held.has(value.binding))
266
+ this.holdForDesk(value);
267
+ return true;
268
+ }
269
+ holdForDesk(value) {
270
+ const timer = setTimeout(() => {
271
+ this.held.delete(value.binding);
272
+ if (this.stillPending && !this.stillPending(value.binding))
273
+ return;
274
+ if (Date.parse(value.expiresAt) <= Date.now())
275
+ return;
276
+ if (this.deskActive) {
277
+ this.holdForDesk(value);
278
+ return;
279
+ }
280
+ void this.notifyNow(value).catch(() => { });
281
+ }, Math.max(this.deskUntil - Date.now(), 0) + 250);
282
+ timer.unref?.();
283
+ this.held.set(value.binding, timer);
284
+ }
285
+ async notifyNow(value) {
247
286
  const devices = this.reachable.filter(device => device.kinds.includes("approval"));
248
287
  if (!devices.length)
249
288
  return false;
@@ -0,0 +1,29 @@
1
+ import type { Readable, Writable } from "node:stream";
2
+ export declare const GATEWAY_SCOPES: readonly ["gitboy-read", "gitboy-write"];
3
+ export type GatewayScope = typeof GATEWAY_SCOPES[number];
4
+ /** The authorized_keys comment each scope's key carries. */
5
+ export declare const SCOPE_KEY_COMMENT: Record<GatewayScope, string>;
6
+ /** The only SSH command a scoped key may send, the same one the phone's pipe uses. */
7
+ export declare const SCOPED_COMMAND = "phren-hook v1 pipe";
8
+ export declare function isGatewayScope(value: string): value is GatewayScope;
9
+ export type Admission = {
10
+ ok: true;
11
+ request: string;
12
+ } | {
13
+ ok: false;
14
+ status: number;
15
+ error: string;
16
+ };
17
+ /** Decide one request: its head (through the blank line) and the bytes after it. */
18
+ export declare function admitScopedRequest(scope: GatewayScope, rawHead: string, rest?: Buffer): Admission;
19
+ export interface ScopedIO {
20
+ input: Readable;
21
+ output: Writable;
22
+ socket: string;
23
+ }
24
+ /**
25
+ * Serve one scoped SSH session. Commands other than the pipe are refused
26
+ * outright; a refused request gets an HTTP error on the channel so the client
27
+ * reads a normal response.
28
+ */
29
+ export declare function scopedDispatch(scope: string, command: string, io: ScopedIO): Promise<void>;
@@ -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)
@@ -321,6 +321,8 @@ async function startSession(server, data, options) {
321
321
  if (agentFolder && (role !== "agent" || data.project !== undefined || (data.cwd !== undefined && data.cwd !== "") || data.worktree != null)) {
322
322
  throw new BridgeError(400, "An agent folder is for a projectless agent without cwd or worktree.");
323
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.");
324
326
  const projectDirectory = agentFolder ? undefined
325
327
  : z.string().min(1).max(4096).refine(t => path.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
326
328
  const worktreeRequest = data.worktree === undefined || data.worktree === null ? undefined : launchWorktreeSchema.parse(data.worktree);
@@ -401,7 +403,8 @@ async function startSession(server, data, options) {
401
403
  const briefFile = brief && (launchesWithBrief(kind) || structured || served) ? await writeLaunchBrief(brief, Date.now(), label) : undefined;
402
404
  const briefLaunch = brief && briefFile && launchesWithBrief(kind) ? briefArgs(kind, briefFile) : undefined;
403
405
  // sudo -A in the new agent asks the phone for the password (sudo.ts).
404
- 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) : {}) };
405
408
  const env = Object.keys(variables).length ? variables : undefined;
406
409
  if (workspace && !objects(before.workspaces).some(w => w.workspace_id === workspace))
407
410
  throw new BridgeError(409, "The workspace changed.");
@@ -432,16 +435,18 @@ async function startSession(server, data, options) {
432
435
  // agent too; a folder the Hook picked or just created is trusted up front.
433
436
  if (scratch || worktree || options.trustFolder)
434
437
  await pretrustFolder(kind, cwd, scratch ? "new agent folder" : worktree ? `new worktree for ${worktree.branch}` : "project folder", home ? { ...process.env, ...claudeLaunchEnv(home) } : process.env);
435
- try {
436
- await terminalProvider().create(server, { workspace, label, cwd, ...(env ? { env } : {}) });
437
- }
438
- catch (error) {
439
- await worktree?.discard();
440
- if (scratch)
441
- await rmdir(scratch).catch(() => undefined);
442
- 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
+ }
443
448
  }
444
- let created;
449
+ let created = options.into;
445
450
  for (let attempt = 0; attempt < 25 && !created; attempt++) {
446
451
  const s = await snapshot(server);
447
452
  const fresh = objects(s.tabs).filter(t => !knownTabs.has(t.tab_id)
@@ -500,6 +505,8 @@ async function startSession(server, data, options) {
500
505
  const host = terminalName(server);
501
506
  const reason = error instanceof BridgeError && error.status === 504 ? "it did not become ready in time"
502
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.`);
503
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"}.`);
504
511
  }
505
512
  }