@phren/cli 0.2.16 → 0.3.0

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 (60) hide show
  1. package/dist/bridge/agent-hooks.d.ts +2 -0
  2. package/dist/bridge/agent-hooks.js +4 -0
  3. package/dist/bridge/code-note.d.ts +2 -1
  4. package/dist/bridge/code-note.js +13 -4
  5. package/dist/bridge/code-routes.d.ts +32 -14
  6. package/dist/bridge/code-routes.js +131 -8
  7. package/dist/bridge/dispatch-returns.d.ts +2 -0
  8. package/dist/bridge/dispatch-returns.js +12 -8
  9. package/dist/bridge/dispatch.d.ts +4 -1
  10. package/dist/bridge/dispatch.js +30 -5
  11. package/dist/bridge/install.d.ts +0 -4
  12. package/dist/bridge/install.js +3 -3
  13. package/dist/bridge/protocol.js +20 -1
  14. package/dist/bridge/schedule-watch.d.ts +2 -0
  15. package/dist/bridge/schedule-watch.js +16 -3
  16. package/dist/bridge/server-pane-routes.d.ts +7 -0
  17. package/dist/bridge/server-pane-routes.js +90 -11
  18. package/dist/bridge/server-routes.d.ts +2 -0
  19. package/dist/bridge/server-routes.js +44 -26
  20. package/dist/bridge/transcript-preview.d.ts +2 -0
  21. package/dist/bridge/transcript-preview.js +15 -0
  22. package/dist/bridge-hook.mjs +8842 -3209
  23. package/dist/cli/config-policy.js +25 -0
  24. package/dist/cli/extract.d.ts +0 -8
  25. package/dist/cli/extract.js +1 -1
  26. package/dist/cli-registry.js +7 -7
  27. package/dist/content/validate.d.ts +14 -3
  28. package/dist/content/validate.js +174 -114
  29. package/dist/data/access.d.ts +9 -0
  30. package/dist/data/access.js +18 -0
  31. package/dist/generated/memory-ui-graph.browser.js +520 -410
  32. package/dist/governance/policy.js +4 -3
  33. package/dist/hooks.d.ts +0 -15
  34. package/dist/hooks.js +1 -1
  35. package/dist/init/init-uninstall.js +13 -3
  36. package/dist/init/setup.js +19 -5
  37. package/dist/init/store-gitignore.d.ts +0 -5
  38. package/dist/init/store-gitignore.js +0 -8
  39. package/dist/link/context-imports.d.ts +15 -0
  40. package/dist/link/context-imports.js +101 -0
  41. package/dist/link/doctor.js +28 -4
  42. package/dist/mcp/profile.d.ts +0 -4
  43. package/dist/mcp/profile.js +0 -13
  44. package/dist/memory-ui-graph.runtime.js +520 -410
  45. package/dist/modules/code-package.js +10 -2
  46. package/dist/modules/registry.js +1 -1
  47. package/dist/profile-store.js +39 -3
  48. package/dist/project-topics.d.ts +1 -0
  49. package/dist/project-topics.js +9 -6
  50. package/dist/shared/retrieval.d.ts +0 -2
  51. package/dist/shared/retrieval.js +1 -1
  52. package/dist/tools/code.js +29 -21
  53. package/dist/tools/config.js +3 -0
  54. package/dist/tools/dispatch.js +1 -1
  55. package/dist/tools/finding.d.ts +11 -0
  56. package/dist/tools/finding.js +154 -99
  57. package/dist/ui/server.js +18 -1
  58. package/dist/update.js +21 -10
  59. package/package.json +7 -7
  60. package/starter/global/skills/conductor/SKILL.md +1 -1
@@ -113,6 +113,8 @@ export declare class AgentHooks {
113
113
  * its turn ends, so the record outlives the wait (up to ten minutes) and a
114
114
  * late submission to the wrong conversation is still refused. */
115
115
  expectDelivery(target: Target, text: string, waitMs?: number): Promise<DeliveryOutcome>;
116
+ /** A prompt Phren typed into `target` that its conversation has not submitted yet. */
117
+ deliveryPending(target: Target, text: string): boolean;
116
118
  /** Wait again for a delivery `expectDelivery` already reported pending,
117
119
  * after the Hook pressed Enter a second time. */
118
120
  awaitLateDelivery(target: Target, text: string, waitMs?: number): Promise<DeliveryOutcome>;
@@ -342,6 +342,10 @@ export class AgentHooks {
342
342
  this.deliveries.delete(this.deliveries.keys().next().value);
343
343
  });
344
344
  }
345
+ /** A prompt Phren typed into `target` that its conversation has not submitted yet. */
346
+ deliveryPending(target, text) {
347
+ return !!this.deliveries.get(promptKey(text))?.some(entry => entry.source === target.source && entry.session === target.session);
348
+ }
345
349
  /** Wait again for a delivery `expectDelivery` already reported pending,
346
350
  * after the Hook pressed Enter a second time. */
347
351
  awaitLateDelivery(target, text, waitMs = 2_500) {
@@ -3,7 +3,8 @@ import { type Json } from "./protocol.js";
3
3
  export declare const codeNoteSchema: z.ZodObject<{
4
4
  store: z.ZodOptional<z.ZodString>;
5
5
  project: z.ZodString;
6
- symbol: z.ZodString;
6
+ name: z.ZodOptional<z.ZodString>;
7
+ symbol: z.ZodOptional<z.ZodString>;
7
8
  file: z.ZodString;
8
9
  line: z.ZodNumber;
9
10
  text: z.ZodString;
@@ -6,23 +6,32 @@ import { BridgeError, sessionId } from "./protocol.js";
6
6
  import { projectName } from "./dispatch.js";
7
7
  export const codeNoteSchema = z.object({
8
8
  store: z.string().min(1).max(200).optional(),
9
- project: projectName, symbol: z.string().min(1).max(4600),
9
+ project: projectName,
10
+ // The function, type or variable the note is about; `symbol` is the older
11
+ // phone's spelling, accepted until 0.3.1.
12
+ name: z.string().min(1).max(4600).optional(), symbol: z.string().min(1).max(4600).optional(),
10
13
  file: z.string().min(1).max(4096).refine(file => !path.isAbsolute(file) && !file.includes("\0") && !file.split(/[\\/]/).includes("..")),
11
14
  line: z.number().int().positive(), text: z.string().trim().min(1).max(4500).refine(text => !/[\x00-\x08\x0b-\x1f\x7f]/.test(text)),
12
15
  target: z.union([z.object({ session: sessionId }).strict(), z.object({ harness: z.enum(["codex", "claude", "opencode"]) }).strict()]).optional(),
13
16
  }).strict();
17
+ const noteName = (note) => {
18
+ const name = note.name ?? note.symbol;
19
+ if (!name)
20
+ throw new BridgeError(400, "Say which function, type or variable the note is about.");
21
+ return name;
22
+ };
14
23
  export async function saveCodeNote(store, input, deliver) {
15
24
  const note = codeNoteSchema.parse(input);
16
25
  if (note.target && !deliver)
17
26
  throw new BridgeError(409, "Enable conductor to send code notes to an agent.");
18
27
  const code = await requireCodePackage(store);
19
- const result = await code.definition(store, note.project, note.symbol);
28
+ const result = await code.definition(store, note.project, noteName(note));
20
29
  if (!result.available || !result.value)
21
- throw new BridgeError(404, "The symbol is not in this project's code index.");
30
+ throw new BridgeError(404, "That function, type or variable is not in this project's code index.");
22
31
  const definition = result.value;
23
32
  const lastSnippetLine = definition.symbol.line + definition.snippet.split("\n").length - 1;
24
33
  if (definition.symbol.file !== note.file || note.line < definition.symbol.line || note.line > Math.min(definition.symbol.endLine, lastSnippetLine)) {
25
- throw new BridgeError(409, "The selected line no longer belongs to this symbol. Refresh its dossier.");
34
+ throw new BridgeError(409, `The selected line is no longer part of ${noteName(note)}. Open it again.`);
26
35
  }
27
36
  const citation = { file: note.file, line: note.line, symbol: code.citationSymbolName(definition.symbol) };
28
37
  const saved = addFindingToFile(store, note.project, note.text, citation);
@@ -35,22 +35,40 @@ export declare class CodeRoutes {
35
35
  maxUses: number;
36
36
  project: string;
37
37
  }>;
38
- recent(projectValue: string | null, directoryValue?: string | null): Promise<{
38
+ /** The checkout this computer indexes for `project`, or a 404 naming the project. */
39
+ private checkout;
40
+ private changedIn;
41
+ /**
42
+ * What changed: the functions, types and variables that today's agent
43
+ * sessions edited in this project's checkout, and its last 10 commits,
44
+ * grouped by file, most recent work first. Session edits carry the line
45
+ * numbers they had when made, so a later edit to the same file can shift one.
46
+ */
47
+ whatChanged(projectValue: string | null, now?: Date): Promise<{
48
+ project: string;
49
+ files: {
50
+ path: string;
51
+ items: import("@phren/code").ChangedDeclaration[];
52
+ }[];
53
+ }>;
54
+ /**
55
+ * Per-file counts for the Changes tree's chips: functions and types the
56
+ * working tree changes or adds (variables stay out to keep a chip short).
57
+ * An untracked file is new throughout.
58
+ */
59
+ changeCounts(projectValue: string | null, pathsValue: string | null): Promise<{
39
60
  project: string;
40
61
  entries: {
41
- id: number;
42
- name: string;
43
- kind: string;
44
- file: string;
45
- line: number;
46
- endLine: number;
47
- signature: string;
48
- doc: string;
49
- parent: string | null;
50
- exported: boolean;
51
- uses: number;
52
- rank?: number;
53
- indexedAt: number;
62
+ path: string;
63
+ functions: {
64
+ changed: number;
65
+ added: number;
66
+ };
67
+ types: {
68
+ changed: number;
69
+ added: number;
70
+ };
71
+ first?: string | undefined;
54
72
  }[];
55
73
  }>;
56
74
  /** Turns code intelligence off for a project: its index is deleted, and
@@ -10,7 +10,7 @@ const indexProject = async (store, ...args) => (await requireCodePackage(store))
10
10
  import { isValidProjectName } from "../utils-paths.js";
11
11
  import { errorMessage } from "../utils.js";
12
12
  import { logger } from "../logger.js";
13
- import { BridgeError } from "./protocol.js";
13
+ import { BridgeError, bridgeRoot } from "./protocol.js";
14
14
  export async function requireCodePackage(store) {
15
15
  const code = await loadCodePackage(store);
16
16
  if (!code)
@@ -107,12 +107,135 @@ export class CodeRoutes {
107
107
  throw noIndex(project);
108
108
  return { project, ...result.value };
109
109
  }
110
- async recent(projectValue, directoryValue) {
111
- const project = projectSchema.parse(projectValue ?? "");
112
- const result = await (await requireCodePackage(this.store)).recentSymbols(this.store, project, optionalPath(directoryValue));
110
+ /** The checkout this computer indexes for `project`, or a 404 naming the project. */
111
+ async checkout(project) {
112
+ try {
113
+ return fs.realpathSync((await requireCodePackage(this.store)).resolveRepoRoot(this.store, project));
114
+ }
115
+ catch {
116
+ throw new BridgeError(404, `${project} has no checkout on this computer.`);
117
+ }
118
+ }
119
+ async changedIn(project, added) {
120
+ const code = await requireCodePackage(this.store);
121
+ if (typeof code.changedDeclarations !== "function")
122
+ throw new BridgeError(503, "Update @phren/code to see what changed.");
123
+ const result = await code.changedDeclarations(this.store, project, new Map([...added].map(([file, lines]) => [file, [...lines].sort((a, b) => a - b)])));
113
124
  if (!result.available)
114
125
  throw noIndex(project);
115
- return { project, entries: result.value };
126
+ return result.value;
127
+ }
128
+ /**
129
+ * What changed: the functions, types and variables that today's agent
130
+ * sessions edited in this project's checkout, and its last 10 commits,
131
+ * grouped by file, most recent work first. Session edits carry the line
132
+ * numbers they had when made, so a later edit to the same file can shift one.
133
+ */
134
+ async whatChanged(projectValue, now = new Date()) {
135
+ const project = projectSchema.parse(projectValue ?? "");
136
+ const root = await this.checkout(project);
137
+ const code = await requireCodePackage(this.store);
138
+ const added = new Map();
139
+ const take = (patch) => {
140
+ for (const [file, lines] of code.addedLinesByFile(patch)) {
141
+ const set = added.get(file) ?? new Set();
142
+ for (const line of lines)
143
+ set.add(line);
144
+ added.set(file, set);
145
+ }
146
+ };
147
+ const midnight = new Date(now);
148
+ midnight.setHours(0, 0, 0, 0);
149
+ const dir = path.join(bridgeRoot(), "changes");
150
+ const logs = fs.existsSync(dir) ? fs.readdirSync(dir).filter(name => name.endsWith(".jsonl")) : [];
151
+ const today = logs.map(name => ({ file: path.join(dir, name), at: fs.statSync(path.join(dir, name)).mtimeMs }))
152
+ .filter(entry => entry.at >= midnight.getTime()).sort((a, b) => b.at - a.at);
153
+ for (const log of today) {
154
+ for (const line of fs.readFileSync(log.file, "utf8").split("\n")) {
155
+ if (!line.trim())
156
+ continue;
157
+ let record;
158
+ try {
159
+ record = JSON.parse(line);
160
+ }
161
+ catch {
162
+ continue;
163
+ }
164
+ for (const file of record.files ?? []) {
165
+ if (typeof file.root !== "string" || typeof file.patch !== "string")
166
+ continue;
167
+ let same = false;
168
+ try {
169
+ same = fs.realpathSync(file.root) === root;
170
+ }
171
+ catch {
172
+ same = false;
173
+ }
174
+ if (same)
175
+ take(file.patch);
176
+ }
177
+ }
178
+ }
179
+ // A repository's first commit adds every file; it is the import, not work.
180
+ try {
181
+ take(await git(root, "-c", "log.showRoot=false", "log", "-10", "--format=", "-p", "-U0", "--no-color", "--no-ext-diff"));
182
+ }
183
+ catch { /* A checkout without commits yet has only its session edits. */ }
184
+ const items = await this.changedIn(project, added);
185
+ const files = [];
186
+ for (const item of items) {
187
+ let group = files.find(entry => entry.path === item.file);
188
+ if (!group) {
189
+ group = { path: item.file, items: [] };
190
+ files.push(group);
191
+ }
192
+ group.items.push(item);
193
+ }
194
+ return { project, files };
195
+ }
196
+ /**
197
+ * Per-file counts for the Changes tree's chips: functions and types the
198
+ * working tree changes or adds (variables stay out to keep a chip short).
199
+ * An untracked file is new throughout.
200
+ */
201
+ async changeCounts(projectValue, pathsValue) {
202
+ const project = projectSchema.parse(projectValue ?? "");
203
+ let raw;
204
+ try {
205
+ raw = JSON.parse(pathsValue ?? "[]");
206
+ }
207
+ catch {
208
+ throw new BridgeError(400, "Choose valid paths.");
209
+ }
210
+ const paths = [...new Set(z.array(relativePathSchema).min(1).max(200).parse(raw))];
211
+ const root = await this.checkout(project);
212
+ const code = await requireCodePackage(this.store);
213
+ const added = new Map();
214
+ for (const [file, lines] of code.addedLinesByFile(await git(root, "diff", "HEAD", "-U0", "--no-color", "--no-ext-diff", "--", ...paths).catch(() => "")))
215
+ added.set(file, new Set(lines));
216
+ const untracked = (await git(root, "ls-files", "--others", "--exclude-standard", "--", ...paths).catch(() => "")).split("\n").filter(Boolean);
217
+ for (const file of untracked) {
218
+ let count = 0;
219
+ try {
220
+ count = fs.readFileSync(path.join(root, file), "utf8").split("\n").length;
221
+ }
222
+ catch {
223
+ continue;
224
+ }
225
+ added.set(file, new Set(Array.from({ length: count }, (_, index) => index + 1)));
226
+ }
227
+ const items = await this.changedIn(project, added);
228
+ const entries = paths.map(file => {
229
+ const mine = items.filter(item => item.file === file || item.file.startsWith(file + "/"));
230
+ const tally = (family) => ({
231
+ changed: mine.filter(item => item.family === family && !item.isNew).length,
232
+ added: mine.filter(item => item.family === family && item.isNew).length,
233
+ });
234
+ const first = mine.find(item => item.family !== "variable");
235
+ return { path: file, functions: tally("function"), types: tally("type"),
236
+ ...(first ? { first: `${first.file}::${first.parent ? first.parent + "." : ""}${first.name}` } : {}) };
237
+ });
238
+ return { project, entries };
116
239
  }
117
240
  /** Turns code intelligence off for a project: its index is deleted, and
118
241
  * the reindexer follows only projects that have one, so nothing rebuilds it
@@ -173,7 +296,7 @@ export class CodeRoutes {
173
296
  if (!result.available)
174
297
  throw noIndex(project);
175
298
  if (!result.value)
176
- throw new BridgeError(404, `No symbol "${symbol}" in ${project}.`);
299
+ throw new BridgeError(404, `Nothing named "${symbol}" in ${project}.`);
177
300
  return { project, definition: { ...result.value, findings: (await requireCodePackage(this.store)).findingsCitingSymbol(this.store, project, (await requireCodePackage(this.store)).citationSymbolName(result.value.symbol)) } };
178
301
  }
179
302
  async references(projectValue, symbolValue, limitValue) {
@@ -184,7 +307,7 @@ export class CodeRoutes {
184
307
  if (!result.available)
185
308
  throw noIndex(project);
186
309
  if (!result.value)
187
- throw new BridgeError(404, `No symbol "${symbol}" in ${project}.`);
310
+ throw new BridgeError(404, `Nothing named "${symbol}" in ${project}.`);
188
311
  return { project, references: result.value };
189
312
  }
190
313
  async usage(projectValue, topValue) {
@@ -286,7 +409,7 @@ export class CodeReindexer {
286
409
  this.running.add(project);
287
410
  try {
288
411
  const result = await this.index(this.store, project, { full });
289
- this.log(`re-indexed ${project}${full ? " (full)" : ""}: ${result.parsed} parsed, ${result.symbols} symbols, ${result.durationMs} ms`);
412
+ this.log(`re-indexed ${project}${full ? " (full)" : ""}: ${result.parsed} parsed, ${result.symbols} declarations, ${result.durationMs} ms`);
290
413
  }
291
414
  catch (error) {
292
415
  this.log(`re-index of ${project} failed: ${errorMessage(error)}`);
@@ -59,6 +59,8 @@ export interface WorkerObservation {
59
59
  completed?: boolean;
60
60
  reply?: string;
61
61
  truncated?: boolean;
62
+ /** The error the harness ended the turn on (Codex's usage limit). */
63
+ error?: string;
62
64
  }
63
65
  export interface WorkerReaders {
64
66
  snapshot: (server: string) => Promise<Json>;
@@ -74,7 +74,7 @@ export async function workerStates(input, readers = defaultReaders) {
74
74
  return { state, ...(session ? { session } : {}) };
75
75
  const turn = await readers.finalTurn(target.source, session).catch(() => undefined);
76
76
  const reply = turn?.lastAssistant ? truncateUtf8(turn.lastAssistant) : undefined;
77
- return { state, session, completed: turn?.completed === true,
77
+ return { state, session, completed: turn?.completed === true, ...(turn?.error ? { error: turn.error } : {}),
78
78
  ...(reply ? { reply: reply.text, ...(reply.truncated ? { truncated: true } : {}) } : {}) };
79
79
  }));
80
80
  return { workers };
@@ -82,7 +82,7 @@ export async function workerStates(input, readers = defaultReaders) {
82
82
  const observationSchema = z.object({
83
83
  state: z.enum(["working", "idle", "done", "blocked", "unknown", "gone", "unavailable"]),
84
84
  session: z.string().max(200).optional(), completed: z.boolean().optional(),
85
- reply: z.string().max(REPLY_LIMIT).optional(), truncated: z.boolean().optional(),
85
+ reply: z.string().max(REPLY_LIMIT).optional(), truncated: z.boolean().optional(), error: z.string().max(500).optional(),
86
86
  }).passthrough();
87
87
  function turnKey(reply) {
88
88
  return reply ? createHash("sha256").update(reply).digest("hex").slice(0, 16) : undefined;
@@ -104,7 +104,9 @@ export function observe(receipt, value, now) {
104
104
  }
105
105
  }
106
106
  const sawWorking = receipt.worker?.sawWorking === true || seen.state === "working" || seen.state === "blocked";
107
- const question = seen.completed && seen.reply ? ownerQuestion(seen.reply) : undefined;
107
+ // A turn the harness ended on an error (a usage limit) failed, reply or not.
108
+ const failed = seen.completed && seen.error ? seen.error : undefined;
109
+ const question = seen.completed && seen.reply && !failed ? ownerQuestion(seen.reply) : undefined;
108
110
  let next;
109
111
  if (seen.state === "gone")
110
112
  next = "gone";
@@ -112,11 +114,13 @@ export function observe(receipt, value, now) {
112
114
  next = "working";
113
115
  else if (seen.state === "blocked")
114
116
  next = "blocked";
117
+ else if (failed)
118
+ next = "failed";
115
119
  else if (seen.completed)
116
120
  next = question ? "needs-you" : "done";
117
121
  else
118
122
  next = sawWorking || now - Date.parse(receipt.createdAt) > IDLE_GRACE_MS ? "done" : "working";
119
- const turn = next === "done" || next === "needs-you" ? turnKey(seen.reply) : undefined;
123
+ const turn = next === "done" || next === "needs-you" ? turnKey(seen.reply) : next === "failed" ? turnKey(failed) : undefined;
120
124
  const previous = receipt.worker?.state;
121
125
  // The same finished state with a different final reply is a new turn: the
122
126
  // worker took more work (a hand_off) and finished again between two polls.
@@ -132,17 +136,17 @@ export function observe(receipt, value, now) {
132
136
  if (next !== "working") {
133
137
  receipt.returned = { state: next, at, read: false,
134
138
  ...(seen.reply && (next === "done" || next === "needs-you") ? { reply: seen.reply, ...(seen.truncated ? { truncated: true } : {}) } : {}),
135
- ...(question ? { question } : {}), ...(turn ? { turn } : {}) };
139
+ ...(failed ? { error: failed } : {}), ...(question ? { question } : {}), ...(turn ? { turn } : {}) };
136
140
  }
137
141
  return true;
138
142
  }
139
143
  /** One line for the dispatching agent: who returned, how, and where to read it. */
140
144
  export function noticeLine(receipts) {
141
145
  const clean = (value, max) => value.replace(/[\x00-\x1f\x7f]+/g, " ").replace(/\s+/g, " ").trim().slice(0, max);
142
- const word = { "done": "done", "needs-you": "needs you", "blocked": "blocked", "gone": "gone" };
146
+ const word = { "done": "done", "needs-you": "needs you", "failed": "failed", "blocked": "blocked", "gone": "gone" };
143
147
  const describe = (receipt, room) => {
144
148
  const returned = receipt.returned;
145
- const detail = returned.state === "needs-you" ? returned.question
149
+ const detail = returned.state === "needs-you" ? returned.question : returned.state === "failed" ? returned.error
146
150
  : returned.state === "done" ? returned.reply?.split("\n").find(line => line.trim()) : undefined;
147
151
  const excerpt = detail ? clean(detail.replace(/[*_`#>]+/g, ""), room) : "";
148
152
  return `${clean(receipt.computer, 60)} ${clean(receipt.label, 80)} ${word[returned.state]}${excerpt ? `, ${excerpt}` : ""}`;
@@ -157,7 +161,7 @@ export function returnRow(receipt) {
157
161
  const returned = receipt.returned;
158
162
  return { id: receipt.id, computer: receipt.computer, project: receipt.project, label: receipt.label, harness: receipt.harness,
159
163
  state: returned.state, at: returned.at, ...(returned.reply !== undefined ? { reply: returned.reply } : {}),
160
- ...(returned.truncated ? { truncated: true } : {}), ...(returned.question ? { question: returned.question } : {}),
164
+ ...(returned.truncated ? { truncated: true } : {}), ...(returned.error ? { error: returned.error } : {}), ...(returned.question ? { question: returned.question } : {}),
161
165
  ...(receipt.target ? { target: receipt.target } : {}) };
162
166
  }
163
167
  const originKey = (origin) => JSON.stringify([origin.server, origin.workspace, origin.tab, origin.pane, origin.terminal]);
@@ -48,7 +48,7 @@ export declare const originPaneSchema: z.ZodObject<{
48
48
  pane: z.ZodString;
49
49
  }, z.core.$strict>;
50
50
  export type OriginPane = z.infer<typeof originPaneSchema>;
51
- export declare const workerStates: readonly ["working", "done", "needs-you", "blocked", "gone"];
51
+ export declare const workerStates: readonly ["working", "done", "needs-you", "failed", "blocked", "gone"];
52
52
  export type WorkerState = typeof workerStates[number];
53
53
  declare const receiptSchema: z.ZodObject<{
54
54
  computer: z.ZodUnion<readonly [z.ZodLiteral<"anywhere">, z.ZodString]>;
@@ -148,6 +148,7 @@ declare const receiptSchema: z.ZodObject<{
148
148
  state: z.ZodEnum<{
149
149
  blocked: "blocked";
150
150
  done: "done";
151
+ failed: "failed";
151
152
  gone: "gone";
152
153
  "needs-you": "needs-you";
153
154
  working: "working";
@@ -160,11 +161,13 @@ declare const receiptSchema: z.ZodObject<{
160
161
  state: z.ZodEnum<{
161
162
  blocked: "blocked";
162
163
  done: "done";
164
+ failed: "failed";
163
165
  gone: "gone";
164
166
  "needs-you": "needs-you";
165
167
  }>;
166
168
  at: z.ZodString;
167
169
  reply: z.ZodOptional<z.ZodString>;
170
+ error: z.ZodOptional<z.ZodString>;
168
171
  truncated: z.ZodOptional<z.ZodBoolean>;
169
172
  question: z.ZodOptional<z.ZodString>;
170
173
  turn: z.ZodOptional<z.ZodString>;
@@ -26,7 +26,7 @@ export const dispatchSchema = z.object({
26
26
  const remoteTarget = z.union([targetSchema, startingTargetSchema]);
27
27
  /** The local pane that asked for the dispatch, where return notices go. */
28
28
  export const originPaneSchema = z.object({ server: serverName, workspace: id, tab: id, pane: id }).strict();
29
- export const workerStates = ["working", "done", "needs-you", "blocked", "gone"];
29
+ export const workerStates = ["working", "done", "needs-you", "failed", "blocked", "gone"];
30
30
  const timestamp = z.string().datetime();
31
31
  const receiptSchema = dispatchSchema.omit({ prompt: true }).extend({
32
32
  id: z.string().uuid(), createdAt: z.string().datetime(), updatedAt: z.string().datetime(),
@@ -41,10 +41,10 @@ const receiptSchema = dispatchSchema.omit({ prompt: true }).extend({
41
41
  worker: z.object({ state: z.enum(workerStates), since: timestamp, checkedAt: timestamp, sawWorking: z.boolean() }).strict().optional()
42
42
  .describe("The worker pane's last observed state."),
43
43
  returned: z.object({
44
- state: z.enum(["done", "needs-you", "blocked", "gone"]), at: timestamp,
45
- reply: z.string().max(4000).optional(), truncated: z.boolean().optional(), question: z.string().max(200).optional(),
44
+ state: z.enum(["done", "needs-you", "failed", "blocked", "gone"]), at: timestamp,
45
+ reply: z.string().max(4000).optional(), error: z.string().max(500).optional(), truncated: z.boolean().optional(), question: z.string().max(200).optional(),
46
46
  turn: z.string().regex(/^[a-f0-9]{16}$/).optional(), read: z.boolean(), notifiedAt: timestamp.optional(),
47
- }).strict().optional().describe("The latest return: the worker finished, needs the owner, is blocked or is gone."),
47
+ }).strict().optional().describe("The latest return: the worker finished, needs the owner, failed, is blocked or is gone."),
48
48
  });
49
49
  export async function dispatchProjectDirectory(project) {
50
50
  const name = projectName.parse(project);
@@ -159,6 +159,31 @@ async function settledTarget(peer, launched, harness) {
159
159
  }
160
160
  return undefined;
161
161
  }
162
+ /**
163
+ * Sends the brief. A fresh agent can read `unknown` to Herdr for a while (long
164
+ * on a loaded machine), and the Hook refuses a prompt to such a pane before
165
+ * typing anything. So that refusal is retried while the pane is still
166
+ * unclassified; a pane that is blocked or waiting really needs its terminal,
167
+ * and that refusal stands.
168
+ */
169
+ async function sendBrief(peer, target, text) {
170
+ for (let attempt = 0;; attempt++) {
171
+ try {
172
+ return await peer.request("/v1/prompt", { target, text });
173
+ }
174
+ catch (error) {
175
+ const unsettled = error instanceof BridgeError && error.status === 409 && /needs input in the terminal first/.test(error.message);
176
+ if (!unsettled || attempt >= 20)
177
+ throw error;
178
+ const panes = await peer.request(`/v1/workspaces/panes?server=${encodeURIComponent(peer.server)}&groupId=${encodeURIComponent(String(target.workspace))}&childId=${encodeURIComponent(String(target.tab))}`).catch(() => undefined);
179
+ const pane = (Array.isArray(panes?.panes) ? panes.panes : []).find((p) => p && typeof p === "object" && p.id === target.pane);
180
+ const status = pane?.agentStatus;
181
+ if (typeof status === "string" && ["blocked", "waiting"].includes(status))
182
+ throw error;
183
+ await new Promise(resolve => setTimeout(resolve, 1_000));
184
+ }
185
+ }
186
+ }
162
187
  export class DispatchService {
163
188
  identity;
164
189
  local;
@@ -236,7 +261,7 @@ export class DispatchService {
236
261
  receipt.state = "sending";
237
262
  receipt.updatedAt = new Date().toISOString();
238
263
  await save(receipt);
239
- const result = await peer.request("/v1/prompt", { target: receipt.target, text: prompt });
264
+ const result = await sendBrief(peer, receipt.target, prompt);
240
265
  receipt.state = result.ok === true && result.deliveryUncertain !== true ? "accepted" : "uncertain";
241
266
  }
242
267
  catch (error) {
@@ -23,10 +23,6 @@ export declare function detectGateway(env?: NodeJS.ProcessEnv): Promise<GatewayK
23
23
  * socket through a tiny forwarder, so a loaded machine never pays for a fresh
24
24
  * node process; every other SSH command falls through to the node gateway. */
25
25
  export declare function gatewayScript(gateway: GatewayKind, environment: GatewayEnvironment): string;
26
- /** The launchd domain for the LaunchAgent: the GUI session when someone is
27
- * logged in at the screen, else the per-user background domain an SSH login
28
- * has (gui/<uid> does not exist there, so a bootstrap into it fails). */
29
- export declare function launchDomain(uid: number, guiSession: boolean): string;
30
26
  /** The commands that restart the Hook in `domain`, printed when launchd refuses. */
31
27
  export declare function launchCommands(domain: string, plist: string): string[];
32
28
  export declare function install(version: string, noService?: boolean): Promise<void>;
@@ -42,7 +42,7 @@ export function upgradeKeys(text) {
42
42
  let changed = 0;
43
43
  const result = text.split(/(?<=\n)/).map(line => {
44
44
  const parsed = keyOptions(line);
45
- if (!parsed || parsed.options[0] !== "restrict" || !/^\s+ssh-ed25519 [A-Za-z0-9+/=]+ phren-iphone\s*$/.test(parsed.rest))
45
+ if (!parsed || parsed.options[0] !== "restrict" || !/^\s+ssh-ed25519 [A-Za-z0-9+/=]+ phren-(?:iphone|android)\s*$/.test(parsed.rest))
46
46
  return line;
47
47
  const old = /^command="(?:\/usr\/bin\/false|python3 ~\/\.local\/share\/phren\/chat-progress\.py|sh ~\/\.local\/share\/phren\/bridge\/dispatch)"$/;
48
48
  if (!parsed.options.some(option => old.test(option)))
@@ -114,7 +114,7 @@ async function activate(version) {
114
114
  /** The launchd domain for the LaunchAgent: the GUI session when someone is
115
115
  * logged in at the screen, else the per-user background domain an SSH login
116
116
  * has (gui/<uid> does not exist there, so a bootstrap into it fails). */
117
- export function launchDomain(uid, guiSession) {
117
+ function launchDomain(uid, guiSession) {
118
118
  return guiSession ? `gui/${uid}` : `user/${uid}`;
119
119
  }
120
120
  /** The commands that restart the Hook in `domain`, printed when launchd refuses. */
@@ -284,7 +284,7 @@ export async function uninstall() {
284
284
  await applyAgentHooks(await planAgentHooks(path.join(bridgeRoot(), "current/bridge-hook.mjs"), true));
285
285
  await applyOpencodePlugin(true);
286
286
  // Preserve journal, settings, uploaded images, rollback version and SSH backups.
287
- console.log("Phren Hook stopped and its background service removed. Remove phren-iphone and phren-computer keys from authorized_keys to revoke device access. Local data remains in " + bridgeRoot());
287
+ console.log("Phren Hook stopped and its background service removed. Remove phren-iphone, phren-android and phren-computer keys from authorized_keys to revoke device access. Local data remains in " + bridgeRoot());
288
288
  }
289
289
  async function missingFile(operation) {
290
290
  try {
@@ -53,12 +53,31 @@ export async function atomic(file, value, mode = 0o600) {
53
53
  const text = typeof value === "string" ? value : JSON.stringify(value);
54
54
  await writeFile(temporary, text, { mode, flag: "wx" });
55
55
  try {
56
- await rename(temporary, file);
56
+ await renameOver(temporary, file);
57
57
  }
58
58
  finally {
59
59
  await unlink(temporary).catch(() => { });
60
60
  }
61
61
  }
62
+ /**
63
+ * Windows refuses to replace a file another handle holds open (a concurrent
64
+ * reader, or another writer's rename landing at the same moment) with EPERM,
65
+ * EACCES or EBUSY, where POSIX replaces it atomically. Those holds last
66
+ * milliseconds, so retry briefly before giving up.
67
+ */
68
+ async function renameOver(from, to) {
69
+ for (let attempt = 0;; attempt++) {
70
+ try {
71
+ return await rename(from, to);
72
+ }
73
+ catch (error) {
74
+ const code = error.code ?? "";
75
+ if (process.platform !== "win32" || attempt >= 20 || !["EPERM", "EACCES", "EBUSY"].includes(code))
76
+ throw error;
77
+ await new Promise(resolve => setTimeout(resolve, 5 * (attempt + 1)));
78
+ }
79
+ }
80
+ }
62
81
  /** {@link atomic}, first creating the file's directory (0700 where it is new). */
63
82
  export async function atomicInPrivateDir(file, value, mode) {
64
83
  await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
@@ -30,9 +30,11 @@ export interface StartupWatchEnv {
30
30
  panes?: (server: string) => Promise<Json[]>;
31
31
  finalTurn?: (source: ScheduleHarness, sessionId: string | undefined) => Promise<FinalTurn | undefined>;
32
32
  }
33
+ /** `error`: the harness ended the turn on an error (Codex's usage limit) instead of a reply. */
33
34
  export interface FinalTurn {
34
35
  completed: boolean;
35
36
  lastAssistant?: string;
37
+ error?: string;
36
38
  }
37
39
  /** The public text of one assistant row, without reasoning or tool output. */
38
40
  export declare function publicAssistant(raw: Json, source: Provider): string | undefined;
@@ -75,10 +75,18 @@ function turnEnded(raw, source) {
75
75
  return raw.type === "event_msg" && ["task_complete", "task_completed"].includes(String(payload.type));
76
76
  return data.stop_reason === "end_turn";
77
77
  }
78
+ /** The error a turn ended on, when the harness records one: Codex's
79
+ * task_complete carries `error.message` (a usage limit, a failed compaction). */
80
+ function turnError(raw, source) {
81
+ if (source !== "codex")
82
+ return;
83
+ const error = object(object(raw.payload).error), message = typeof error.message === "string" ? error.message.replace(/\s+/g, " ").trim() : "";
84
+ return message ? message.slice(0, 500) : undefined;
85
+ }
78
86
  /** The last assistant reply in a transcript and whether its turn finished.
79
87
  * A person's message after the reply opens a new turn, so it clears both. */
80
88
  export function finalTurnFromLines(lines, source) {
81
- let completed = false, lastAssistant;
89
+ let completed = false, lastAssistant, error;
82
90
  for (const line of lines) {
83
91
  if (!line.trim())
84
92
  continue;
@@ -96,6 +104,7 @@ export function finalTurnFromLines(lines, source) {
96
104
  if (userTurn) {
97
105
  completed = false;
98
106
  lastAssistant = undefined;
107
+ error = undefined;
99
108
  continue;
100
109
  }
101
110
  const text = publicAssistant(raw, source);
@@ -103,10 +112,12 @@ export function finalTurnFromLines(lines, source) {
103
112
  lastAssistant = text;
104
113
  completed = false;
105
114
  }
106
- if (turnEnded(raw, source))
115
+ if (turnEnded(raw, source)) {
107
116
  completed = true;
117
+ error = turnError(raw, source);
118
+ }
108
119
  }
109
- return { completed, ...(lastAssistant ? { lastAssistant } : {}) };
120
+ return { completed, ...(lastAssistant ? { lastAssistant } : {}), ...(completed && error ? { error } : {}) };
110
121
  }
111
122
  /** The final turn of a conversation, read from the tail of its transcript. */
112
123
  export async function readFinalTurn(source, sessionId) {
@@ -198,6 +209,8 @@ export async function watchHerdrRun(server, target, signal, startup, env = {}) {
198
209
  if (!sessionId)
199
210
  sessionId = await resolveSession(server, pane);
200
211
  const turn = await finalTurn(startup.source, sessionId).catch(() => undefined);
212
+ if (turn?.completed && turn.error)
213
+ return { status: "failed", reason: turn.error };
201
214
  const question = turn?.completed && turn.lastAssistant ? ownerQuestion(turn.lastAssistant) : undefined;
202
215
  return question ? { status: "needs-you", reason: question } : { status: "finished" };
203
216
  }
@@ -26,4 +26,11 @@ export declare function gitRepository(pane: Json, target: Target, child: unknown
26
26
  * an agent launched into a new worktree from the phone is named here. Listed
27
27
  * last, so a sub-agent or fan-out manifest for the same folder wins a tie. */
28
28
  export declare function herdrWorktreeWorkers(s: Json): WorktreeWorker[];
29
+ /** A busy Claude Code queues typed text on Enter, but after a long paste
30
+ * ("paste again to expand") it can swallow that Enter and leave the text in
31
+ * its input line, where it stays after the turn ends. Follow the pane: once
32
+ * it has stayed finished for two looks while the prompt is still unsubmitted,
33
+ * press Enter once. A closed or replaced pane, a delivery the conversation
34
+ * took, or ten minutes end the watch; a pane asking for input is never answered. */
35
+ export declare function followQueuedDelivery(agentHooks: AgentHooks, target: Target, terminal: unknown, text: string, intervalMs?: number): void;
29
36
  export declare function paneRoute(ctx: PaneRouteContext, url: URL, data: Json, response: ServerResponse): Promise<unknown>;