@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,94 @@
1
+ import { type FindingItem } from "../data/access.js";
2
+ export declare const PROJECT_MEMORY_ROUTE: RegExp;
3
+ export declare const MEMORY_LIMITS: {
4
+ readonly findings: 500;
5
+ readonly active: 200;
6
+ readonly queue: 200;
7
+ readonly done: 50;
8
+ };
9
+ export interface MemoryFinding {
10
+ id: string;
11
+ text: string;
12
+ type: string | null;
13
+ status: FindingItem["status"];
14
+ created: string | null;
15
+ citation: {
16
+ file: string | null;
17
+ line: number | null;
18
+ commit: string | null;
19
+ name: string | null;
20
+ } | null;
21
+ }
22
+ export interface MemoryTask {
23
+ id: string;
24
+ text: string;
25
+ created: string | null;
26
+ context: string | null;
27
+ }
28
+ export interface ProjectMemory {
29
+ project: string;
30
+ store_id: string | null;
31
+ remote: string | null;
32
+ truncated: boolean;
33
+ findings: MemoryFinding[];
34
+ truths: {
35
+ text: string;
36
+ }[];
37
+ tasks: {
38
+ active: MemoryTask[];
39
+ queue: MemoryTask[];
40
+ done: MemoryTask[];
41
+ };
42
+ }
43
+ export declare function projectMemory(base: string, rawProject: string): ProjectMemory;
44
+ export interface FileFinding extends MemoryFinding {
45
+ match: "file" | "symbol";
46
+ }
47
+ /** Findings about these repository files: cited by file, or citing a function,
48
+ * type or variable the code index places in one of them. */
49
+ export declare function memoryForFiles(base: string, rawProject: string, paths: string[]): Promise<{
50
+ project: string;
51
+ store_id: string | null;
52
+ symbols: "indexed" | "unavailable";
53
+ truncated: boolean;
54
+ findings: FileFinding[];
55
+ }>;
56
+ export interface SearchHit {
57
+ kind: "finding" | "truth";
58
+ score: number;
59
+ matched: number;
60
+ text: string;
61
+ finding: MemoryFinding | null;
62
+ }
63
+ /**
64
+ * Findings and truths ranked against `q` with phren's retrieval tokenizer and
65
+ * chunk matcher (the hook's relevance floor). Each query token is weighted by
66
+ * how rare it is across this project's findings and truths (the normalised IDF
67
+ * `tokenRarity` uses), so a stack trace's common words count for little.
68
+ * `score` is the matched share of that weight, 0 to 1; findings that are no
69
+ * longer active count half.
70
+ */
71
+ export declare function memorySearch(base: string, rawProject: string, q: string, limit: number): {
72
+ project: string;
73
+ query: string;
74
+ results: SearchHit[];
75
+ };
76
+ /** Open tasks that name this branch (or its last segment) or the issue number
77
+ * in it (`fix/123-login`, `issue-123`, `gh-123`). One read of tasks.md. */
78
+ export declare function tasksForBranch(base: string, rawProject: string, branch: string): {
79
+ project: string;
80
+ branch: string;
81
+ truncated: boolean;
82
+ tasks: (MemoryTask & {
83
+ section: "active" | "queue";
84
+ match: "branch" | "issue";
85
+ })[];
86
+ };
87
+ /** Save one finding through the same path as the add_finding MCP tool: the
88
+ * project's write permission, duplicate and conflict checks, the secret
89
+ * scan and citation validation against the code index. */
90
+ export declare function saveFinding(base: string, rawProject: string, input: unknown): Promise<{
91
+ project: string;
92
+ status: string;
93
+ finding: MemoryFinding | null;
94
+ }>;
@@ -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;
@@ -5,6 +5,7 @@ import path from "node:path";
5
5
  import { finished as streamFinished } from "node:stream/promises";
6
6
  import { askpassEnv } from "./sudo.js";
7
7
  import { claudeHome, claudeLaunchEnv } from "./claude-accounts.js";
8
+ import { pickClaudeAccount } from "./account-choice.js";
8
9
  import { fanoutRoot } from "./fanouts.js";
9
10
  import { pretrustFolder } from "./folder-trust.js";
10
11
  import { findPane, paneIdentity, servers, snapshot } from "./herdr.js";
@@ -104,7 +105,10 @@ export function headlessEnv(schedule, env = process.env) {
104
105
  return { ...env, ...claudeLaunchEnv(home) };
105
106
  }
106
107
  async function launchHeadless(context, store, started) {
107
- const env = headlessEnv(context.schedule);
108
+ // A Claude schedule that names no account runs under the one with the most room, as a Herdr launch does.
109
+ const choice = context.schedule.harness === "claude" && !context.schedule.account
110
+ ? await pickClaudeAccount(`Schedule "${context.schedule.name}"`).catch(() => undefined) : undefined;
111
+ const env = headlessEnv(choice ? { ...context.schedule, account: choice.account } : context.schedule);
108
112
  const root = fanoutRoot({ ...process.env, PHREN_PATH: store }), jobDir = path.join(root, context.runId);
109
113
  await mkdir(jobDir, { recursive: true, mode: 0o700 });
110
114
  const eventLog = "events.jsonl", now = new Date().toISOString();
@@ -54,6 +54,9 @@ export interface FinalTurn {
54
54
  }
55
55
  /** The public text of one assistant row, without reasoning or tool output. */
56
56
  export declare function publicAssistant(raw: Json, source: Provider): string | undefined;
57
+ /** How a Claude usage-limit error starts, so dispatch can tell it from any other failure (account-failover.ts). */
58
+ export declare const CLAUDE_USAGE_LIMIT = "Claude usage limit:";
59
+ export declare const isClaudeUsageLimit: (error: string | undefined) => boolean;
57
60
  /** Claude Code background work a transcript line starts or ends, by task id:
58
61
  * a backgrounded Bash call, an async subagent or a Monitor start one; a
59
62
  * task-notification with a final status, or a TaskStop, ends it. A
@@ -99,6 +99,22 @@ function turnError(raw, source) {
99
99
  const error = object(object(raw.payload).error), message = typeof error.message === "string" ? error.message.replace(/\s+/g, " ").trim() : "";
100
100
  return message ? message.slice(0, 500) : undefined;
101
101
  }
102
+ /** How a Claude usage-limit error starts, so dispatch can tell it from any other failure (account-failover.ts). */
103
+ export const CLAUDE_USAGE_LIMIT = "Claude usage limit:";
104
+ export const isClaudeUsageLimit = (error) => !!error?.startsWith(CLAUDE_USAGE_LIMIT);
105
+ /** Claude Code's own record of a subscription limit ending the turn: a synthetic assistant row
106
+ * (`isApiErrorMessage`, `error: "rate_limit"`) whose text says which limit and when it resets,
107
+ * as "You've hit your session limit · resets 3pm". A transient 429 Claude Code retries by itself never ends the turn. */
108
+ function claudeUsageLimit(raw) {
109
+ if (raw.type !== "assistant" || raw.isApiErrorMessage !== true || raw.error !== "rate_limit")
110
+ return undefined;
111
+ const content = object(raw.message).content;
112
+ const text = (typeof content === "string" ? content : objects(content).filter(block => block.type === "text").map(block => String(block.text ?? "")).join(" "))
113
+ .replace(/\s+/g, " ").trim();
114
+ if (!/\b(?:hit your|usage limit|limit reached|out of (?:extra )?usage)\b/i.test(text) && !raw.quotaLimits)
115
+ return undefined;
116
+ return `${CLAUDE_USAGE_LIMIT} ${text || "the subscription refused the request"}`.slice(0, 500);
117
+ }
102
118
  /** The owner stopping a turn: Claude's interruption marker, Codex's aborted turn, Copilot's abort. */
103
119
  function turnInterrupted(raw, source) {
104
120
  if (source === "codex")
@@ -216,18 +232,28 @@ export function finalTurnFromLines(lines, source) {
216
232
  copilotFinal = false;
217
233
  continue;
218
234
  }
235
+ // The limit ends the turn; its own text is the error, not the worker's last reply.
236
+ const limit = source === "claude" ? claudeUsageLimit(raw) : undefined;
237
+ if (limit) {
238
+ completed = true;
239
+ interrupted = false;
240
+ error = limit;
241
+ continue;
242
+ }
219
243
  const text = publicAssistant(raw, source);
220
244
  if (text) {
221
245
  lastAssistant = text;
222
246
  completed = false;
223
247
  interrupted = false;
248
+ error = undefined;
224
249
  }
225
250
  if (source === "copilot" && raw.type === "assistant.message" && !raw.agentId)
226
251
  copilotFinal = object(raw.data).phase === "final_answer";
252
+ // Claude's turn_duration after its limit row keeps that error.
227
253
  if (turnEnded(raw, source, copilotFinal)) {
228
254
  completed = true;
229
255
  interrupted = false;
230
- error = turnError(raw, source);
256
+ error = turnError(raw, source) ?? (source === "claude" ? error : undefined);
231
257
  copilotFinal = false;
232
258
  }
233
259
  }
@@ -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>;