@phren/cli 0.3.12 → 0.3.13

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 (52) hide show
  1. package/dist/bridge/account-usage.d.ts +124 -0
  2. package/dist/bridge/account-usage.js +258 -0
  3. package/dist/bridge/agent-hooks.d.ts +3 -0
  4. package/dist/bridge/agent-hooks.js +20 -1
  5. package/dist/bridge/codex-hook-trust.d.ts +27 -0
  6. package/dist/bridge/codex-hook-trust.js +237 -0
  7. package/dist/bridge/command.js +3 -0
  8. package/dist/bridge/dispatch-command.js +9 -3
  9. package/dist/bridge/dispatch-returns.d.ts +5 -0
  10. package/dist/bridge/dispatch-returns.js +16 -6
  11. package/dist/bridge/dispatch.d.ts +25 -1
  12. package/dist/bridge/dispatch.js +35 -6
  13. package/dist/bridge/hand-off-queue.d.ts +74 -0
  14. package/dist/bridge/hand-off-queue.js +235 -0
  15. package/dist/bridge/hand-off.d.ts +12 -4
  16. package/dist/bridge/hand-off.js +27 -7
  17. package/dist/bridge/install.js +16 -2
  18. package/dist/bridge/pane-status.d.ts +12 -0
  19. package/dist/bridge/pane-status.js +50 -1
  20. package/dist/bridge/push.d.ts +6 -0
  21. package/dist/bridge/push.js +21 -0
  22. package/dist/bridge/schedule-launch.d.ts +1 -1
  23. package/dist/bridge/schedule-launch.js +5 -1
  24. package/dist/bridge/schedule-watch.d.ts +15 -1
  25. package/dist/bridge/schedule-watch.js +45 -10
  26. package/dist/bridge/server-launch.js +14 -4
  27. package/dist/bridge/server-overview.d.ts +8 -1
  28. package/dist/bridge/server-overview.js +12 -3
  29. package/dist/bridge/server-pane-routes.d.ts +1 -0
  30. package/dist/bridge/server-pane-routes.js +9 -7
  31. package/dist/bridge/server-routes.d.ts +4 -0
  32. package/dist/bridge/server-routes.js +57 -7
  33. package/dist/bridge/server.js +15 -2
  34. package/dist/bridge/session-activity.d.ts +24 -12
  35. package/dist/bridge/session-activity.js +36 -14
  36. package/dist/bridge/stalls.d.ts +22 -0
  37. package/dist/bridge/stalls.js +57 -0
  38. package/dist/bridge/sudo.d.ts +209 -0
  39. package/dist/bridge/sudo.js +501 -0
  40. package/dist/bridge/terminal-tmux.d.ts +12 -0
  41. package/dist/bridge/terminal-tmux.js +79 -4
  42. package/dist/bridge/transcript-claude.d.ts +4 -0
  43. package/dist/bridge/transcript-claude.js +131 -6
  44. package/dist/bridge/usage.d.ts +17 -0
  45. package/dist/bridge/usage.js +37 -3
  46. package/dist/bridge-hook.mjs +19448 -18102
  47. package/dist/cli-registry.js +7 -1
  48. package/dist/modules/registry.js +8 -8
  49. package/dist/tools/dispatch.js +17 -2
  50. package/package.json +1 -1
  51. package/starter/global/AGENTS.md +4 -0
  52. package/starter/global/skills/conductor/SKILL.md +34 -2
@@ -6,11 +6,15 @@ import { backgroundLeft, readTurn, turnPhase } from "./turn-records.js";
6
6
  * title, from the pane's turn record (turn-records.ts) and the dispatch label
7
7
  * (launch-brief.ts):
8
8
  *
9
- * - A Claude turn that ended while background shells or subagents still run
10
- * (its Stop's `background` count, less the tasks its transcript shows
11
- * finishing since, for at most BACKGROUND_STALE_MS), or a Codex session with
12
- * running subagents or fanout jobs, is still working. Herdr reports it idle, so the
13
- * phone listed it under IDLE with a moon badge. The tab keeps
9
+ * - A session whose turn ended while work it started still runs is still
10
+ * working: running sub-agents, teammates, workflow agents and fan-out jobs
11
+ * (its child tree, Claude and Codex alike), and for Claude the background
12
+ * shells and monitors started since the owner's last prompt that are not
13
+ * endless streams (`FinalTurn.awaited`, bounded by its Stop's count less the
14
+ * tasks finished since, for at most BACKGROUND_STALE_MS). A log tail, a
15
+ * watcher or a shell left over from an earlier exchange runs on without
16
+ * anyone waiting for it, so it does not count. Herdr reports such a session
17
+ * idle, so the phone listed it under IDLE with a moon badge. The tab keeps
14
18
  * `agentStatus: "working"` and gains `backgroundTasks`, the count.
15
19
  * - A dispatched worker is named by its dispatch label. Claude and Codex title
16
20
  * a session after its first prompt, which for a brief launch is
@@ -45,22 +49,27 @@ export function recordedBackground(record, finishedTasks, now = Date.now()) {
45
49
  return undefined;
46
50
  return backgroundLeft(phase.background, phase.at, finishedTasks) || undefined;
47
51
  }
48
- /** `recordedBackground` for a pane, reading the transcript (`readFinalTurn`,
49
- * passed in: schedule-watch imports herdr, which imports this) only when the
50
- * Stop left background work. Only Claude's Stop reports a count. */
52
+ /** The background shells and monitors a pane's ended Claude turn is waiting
53
+ * on (`FinalTurn.awaited`), at most `recordedBackground`. Reads the transcript
54
+ * (`readFinalTurn`, passed in: schedule-watch imports herdr, which imports
55
+ * this) only when the Stop left background work; only Claude's Stop reports
56
+ * a count. Sub-agents are not in it: the overview adds its running children.
57
+ * An unreadable transcript counts nothing, since the Stop's count alone
58
+ * cannot tell a build from a log tail. */
51
59
  export async function liveBackground(record, readFinal, now = Date.now()) {
52
60
  if (!record || record.source !== "claude" || !recordedBackground(record, [], now))
53
61
  return undefined;
54
62
  const final = await readFinal("claude", record.session).catch(() => undefined);
55
- return recordedBackground(record, final?.finishedTasks, now);
63
+ const left = recordedBackground(record, final?.finishedTasks, now);
64
+ return left && final?.awaited ? Math.min(left, final.awaited) : undefined;
56
65
  }
57
66
  /**
58
67
  * Marks a tab whose main turn ended but whose background work continues:
59
68
  * an idle or done tab becomes `working` with `backgroundTasks: count`. Called
60
- * again with a second source (the transcript's running children), it keeps the
61
- * larger count, never the sum: Claude's own Stop count already includes its
62
- * subagents. A tab that is working, blocked or waiting on its own is left
63
- * alone, so `backgroundTasks` never sits on a tab with a live turn.
69
+ * again with a fuller count (the awaited shells plus the running children,
70
+ * once the child tree is read), it keeps the larger. A tab that is working,
71
+ * blocked or waiting on its own is left alone, so `backgroundTasks` never
72
+ * sits on a tab with a live turn.
64
73
  */
65
74
  export function markBackground(tab, count) {
66
75
  if (!count || count < 1)
@@ -79,6 +88,19 @@ export function meaningfulLabel(value) {
79
88
  const text = value.trim();
80
89
  return text && !/^\d+$/.test(text) && !/^\S*:\S*$/.test(text) && !/^[A-Za-z]{1,2}[_-]?\d+[A-Za-z]?$/.test(text) ? text : undefined;
81
90
  }
91
+ /** Spinner and status glyphs a harness puts around its terminal title while it
92
+ * works: Braille spinner frames (Codex), dingbat stars and checks (Claude's
93
+ * ✳), bullets, circles and hourglasses. */
94
+ const GLYPHS_AROUND = /^[\u2800-\u28ff\u2700-\u27bf\u25a0-\u25ff\u23f0-\u23ff\u2022\u00b7\u2219\u22c5\u2605\u2606\s]+|[\s\u2800-\u28ff\u2700-\u27bf\u25a0-\u25ff\u23f0-\u23ff\u2022\u00b7\u2219\u22c5\u2605\u2606]+$/gu;
95
+ /** A terminal title without the spinner or status glyphs around it, nor the
96
+ * separator they leave dangling (Codex's "⠸ | phren" before its thread has a
97
+ * title); undefined when nothing else is left. */
98
+ export function plainTitle(value) {
99
+ if (typeof value !== "string")
100
+ return undefined;
101
+ const text = value.replace(GLYPHS_AROUND, "").replace(/^\|\s+|\s+\|$/g, "").replace(GLYPHS_AROUND, "").trim();
102
+ return text || undefined;
103
+ }
82
104
  /** A harness title made from the brief launch's first prompt rather than the work: the prompt itself, the brief path, or "Brief <id>". */
83
105
  export function isBriefTitle(title) {
84
106
  return /^\s*read and follow the brief/i.test(title) || title.includes("/briefs/")
@@ -104,7 +126,7 @@ export function sessionTitle(input) {
104
126
  if (input.dispatchLabel)
105
127
  return input.dispatchLabel;
106
128
  const named = meaningfulLabel(input.tabLabel) ?? meaningfulLabel(input.workspaceLabel);
107
- const title = typeof input.harnessTitle === "string" && input.harnessTitle.trim() ? input.harnessTitle : undefined;
129
+ const title = plainTitle(input.harnessTitle);
108
130
  const chosen = input.dispatched ? named : !title ? undefined : isBriefTitle(title) ? named : title;
109
131
  const label = input.fallbackLabel;
110
132
  const blank = "fallbackLabel" in input && (typeof label !== "string" || !label.trim());
@@ -0,0 +1,22 @@
1
+ import type { Json, Target } from "./protocol.js";
2
+ export interface Stall {
3
+ stalled: true;
4
+ stalledSince: string;
5
+ stallFor: number;
6
+ }
7
+ export interface StallReaders {
8
+ screen: (target: Target) => Promise<string>;
9
+ transcript: (target: Target) => Promise<string>;
10
+ now: () => number;
11
+ threshold: () => number;
12
+ }
13
+ export declare function stallThreshold(): number;
14
+ /** Requires successful observations of both sources. Identity, terminal, work
15
+ * status and either source changing all reset the clock. Missing data is unknown. */
16
+ export declare class StallDetector {
17
+ private readers;
18
+ private entries;
19
+ constructor(readers?: StallReaders);
20
+ observe(target: Target, pane: Json): Promise<Stall | undefined>;
21
+ }
22
+ export declare const sessionStalls: StallDetector;
@@ -0,0 +1,57 @@
1
+ import { createHash } from "node:crypto";
2
+ import { open } from "node:fs/promises";
3
+ import { targetTranscriptPath } from "./transcripts.js";
4
+ import { terminalProvider } from "./terminal.js";
5
+ export function stallThreshold() {
6
+ const value = Number(process.env.PHREN_STALL_MS ?? 300_000);
7
+ return Number.isFinite(value) && value >= 0 ? value : 300_000;
8
+ }
9
+ async function transcriptStamp(target) {
10
+ const file = await open(await targetTranscriptPath(target), "r");
11
+ try {
12
+ const info = await file.stat(), start = Math.max(0, info.size - 8192), buffer = Buffer.alloc(info.size - start);
13
+ await file.read(buffer, 0, buffer.length, start);
14
+ return `${info.size}:${createHash("sha256").update(buffer).digest("hex")}`;
15
+ }
16
+ finally {
17
+ await file.close();
18
+ }
19
+ }
20
+ /** Requires successful observations of both sources. Identity, terminal, work
21
+ * status and either source changing all reset the clock. Missing data is unknown. */
22
+ export class StallDetector {
23
+ readers;
24
+ entries = new Map();
25
+ constructor(readers = {
26
+ screen: target => terminalProvider().readScreen(target.server, target.pane, { scope: "pane", source: "visible", lines: 120, stripAnsi: true, timeoutMs: 1000 }),
27
+ transcript: transcriptStamp, now: Date.now, threshold: stallThreshold,
28
+ }) {
29
+ this.readers = readers;
30
+ }
31
+ async observe(target, pane) {
32
+ const key = JSON.stringify([target.server, target.pane]);
33
+ if (pane.agent_status !== "working" || this.readers.threshold() === 0) {
34
+ this.entries.delete(key);
35
+ return undefined;
36
+ }
37
+ let screen, transcript;
38
+ try {
39
+ [screen, transcript] = await Promise.all([this.readers.screen(target), this.readers.transcript(target)]);
40
+ }
41
+ catch {
42
+ this.entries.delete(key);
43
+ return undefined;
44
+ }
45
+ const signature = createHash("sha256").update(JSON.stringify([target, pane.terminal_id, screen, transcript])).digest("hex");
46
+ const now = this.readers.now(), prior = this.entries.get(key);
47
+ if (!prior || prior.signature !== signature) {
48
+ this.entries.delete(key);
49
+ this.entries.set(key, { signature, since: now });
50
+ }
51
+ while (this.entries.size > 1024)
52
+ this.entries.delete(this.entries.keys().next().value);
53
+ const since = this.entries.get(key).since;
54
+ return now - since >= this.readers.threshold() ? { stalled: true, stalledSince: new Date(since).toISOString(), stallFor: Math.floor((now - since) / 1000) } : undefined;
55
+ }
56
+ }
57
+ export const sessionStalls = new StallDetector();
@@ -0,0 +1,209 @@
1
+ import { type IncomingMessage, type ServerResponse } from "node:http";
2
+ import { type Json } from "./protocol.js";
3
+ /**
4
+ * sudo with no terminal, answered from the phone.
5
+ *
6
+ * `sudo -A` runs `SUDO_ASKPASS` (`<bridge>/askpass`, a two-line script the
7
+ * Hook installs) with its prompt as the argument and reads the password from
8
+ * its stdout. The script runs the bundle's `askpass`, which asks the Hook over
9
+ * agent.sock and holds the connection. The password must reach sudo and no
10
+ * one else, so before asking the phone the Hook checks the whole chain
11
+ * (`verifyAsker`): the asker is this Hook's node running its bundle with no
12
+ * flags, its parent is the installed script, that script's parent is a sudo
13
+ * running as root (euid 0, which no process of the owner's can fake), and the
14
+ * asker's stdout is a pipe no other process of the owner's reads. The
15
+ * connection is bound to that process too: on macOS its other end must be
16
+ * held by the asker alone; on Linux the Hook writes the password straight into
17
+ * the asker's stdout (`/proc/<pid>/fd/1`), so a connection that names another
18
+ * process's pid gets nothing. It reads
19
+ * that sudo's command line itself and pushes the request to the phone; `GET /v1/sudo` and the overview socket's `sudo` frame
20
+ * list it. `POST /v1/sudo/answer` writes the password into the held
21
+ * connection and forgets the request: the password is never logged, stored,
22
+ * or kept past that write. Deny, a timeout, no reachable phone, or the asker
23
+ * going away ends the request, and askpass exits non-zero, so sudo fails.
24
+ */
25
+ export declare const SUDO_HOLD_MS: number;
26
+ /** Held askpass requests at once; more are refused. */
27
+ export declare const MAX_SUDO_PENDING = 8;
28
+ /** How long after a password is handed over the Hook waits to see whether
29
+ * sudo asks again, before calling it accepted. */
30
+ export declare const SUDO_OUTCOME_MS: number;
31
+ export type SudoOutcome = "accepted" | "rejected" | "unknown";
32
+ export declare const ASKPASS_FILE = "askpass";
33
+ export declare const askpassPath: () => string;
34
+ export declare const askpassInstalled: () => boolean;
35
+ /** SUDO_ASKPASS for a launch, when this computer's Hook installed its helper. */
36
+ export declare const askpassEnv: () => Record<string, string>;
37
+ /** sudo runs SUDO_ASKPASS with no arguments of its own, so the helper is a
38
+ * script: the node that installed the Hook, the current bundle, `askpass`.
39
+ * It stays node's parent (no exec) so the Hook can see it in the chain, and
40
+ * drops what would load other code into node. */
41
+ export declare function askpassScript(node: string, bundle: string): string;
42
+ export declare function installAskpass(node: string, bundle: string): Promise<void>;
43
+ export declare function removeAskpass(): Promise<void>;
44
+ export interface SudoSession {
45
+ source?: string;
46
+ label?: string;
47
+ server?: string;
48
+ workspace?: string;
49
+ tab?: string;
50
+ pane?: string;
51
+ }
52
+ /** What the phone sees. Never carries a password. */
53
+ export interface SudoRequestView {
54
+ /** `account` is whose password sudo asks for (the invoking user); `user` is who the command runs as. */
55
+ id: string;
56
+ computer: string;
57
+ command: string;
58
+ account?: string;
59
+ user?: string;
60
+ cwd?: string;
61
+ session?: SudoSession;
62
+ askedAt: string;
63
+ expiresAt: string;
64
+ }
65
+ /** What askpass gets: the password to print, word that the Hook wrote it into
66
+ * askpass's stdout itself (Linux), or why not. */
67
+ export type SudoReply = {
68
+ password: string;
69
+ } | {
70
+ delivered: true;
71
+ } | {
72
+ error: string;
73
+ status: number;
74
+ };
75
+ /** The command a sudo process will run, without sudo's own options, and the
76
+ * user it runs as. Falls back to the whole line when there is no command
77
+ * (`sudo -v`, `sudo -s`). */
78
+ export declare function sudoCommand(argv: string[]): {
79
+ command: string;
80
+ user?: string;
81
+ };
82
+ export interface ProcessRecord {
83
+ ppid: number;
84
+ /** Effective user id. */
85
+ euid: number;
86
+ /** Executable name (`comm`). */
87
+ name: string;
88
+ /** Arguments, split on NULs on Linux and on spaces on macOS. */
89
+ argv: string[];
90
+ /** The whole command line as ps prints it. */
91
+ line: string;
92
+ /** Environment names, where the platform shows them (Linux). */
93
+ env?: string[];
94
+ /** When it started (`ps -o lstart`), to tell it from a later process with its pid. */
95
+ started?: string;
96
+ }
97
+ /** One process's parent, effective uid, name and arguments. */
98
+ export declare function readProcess(pid: number): Promise<ProcessRecord | undefined>;
99
+ /** Whether `pid`'s stdout is a pipe that no process of the owner's other than
100
+ * `allowed` holds. sudo, running as root, is never visible here. */
101
+ export declare function stdoutReaders(pid: number, allowed: number[]): Promise<"sudo" | "other" | "unknown">;
102
+ /** macOS: whether the other end of the Hook's connection `hookFd` is held by
103
+ * `pid` and no other process of the owner's. */
104
+ export declare function connectionHolders(pid: number, hookFd: number | undefined): Promise<"asker" | "other" | "unknown">;
105
+ /** Linux: a process's start time, to tell it from a later one with its pid. */
106
+ export declare function processStart(pid: number): Promise<string | undefined>;
107
+ export interface AskerCheck {
108
+ processes: (pid: number) => Promise<ProcessRecord | undefined>;
109
+ stdout: (pid: number, allowed: number[]) => Promise<"sudo" | "other" | "unknown">;
110
+ /** Whether the connection that asked belongs to the asker alone. */
111
+ connection: (pid: number) => Promise<"asker" | "other" | "unknown">;
112
+ /** This Hook's node and the bundle paths askpass may run from. */
113
+ node: string;
114
+ bundles: string[];
115
+ script: string;
116
+ unprivilegedSudo?: boolean;
117
+ }
118
+ /** The chain from askpass up to sudo, or why it is refused. */
119
+ export declare function verifyAsker(pid: number, check: AskerCheck): Promise<{
120
+ sudo: ProcessRecord;
121
+ sudoPid: number;
122
+ } | {
123
+ refused: string;
124
+ }>;
125
+ export interface SudoBrokerOptions {
126
+ computer: () => string;
127
+ push?: {
128
+ readonly available: boolean;
129
+ notifySudo(value: SudoRequestView): Promise<boolean>;
130
+ };
131
+ /** Label and agent for the pane that asked, when the Hook can place it. */
132
+ describe?: (place: {
133
+ server: string;
134
+ workspace: string;
135
+ tab: string;
136
+ pane: string;
137
+ }) => Promise<Pick<SudoSession, "source" | "label"> | undefined>;
138
+ label?: (dispatchId: string) => Promise<string | undefined>;
139
+ /** Reads a process, to see whether sudo is still running; tests replace it. */
140
+ processes?: (pid: number) => Promise<ProcessRecord | undefined>;
141
+ /** The askpass chain check and how the password then reaches it; tests replace it. */
142
+ verify?: (pid: number, hookFd: number | undefined) => Promise<Verified | {
143
+ refused: string;
144
+ }>;
145
+ holdMs?: number;
146
+ outcomeMs?: number;
147
+ /** Whose password sudo asks for; this Hook's user. */
148
+ account?: string;
149
+ now?: () => number;
150
+ }
151
+ export interface Verified {
152
+ sudo: ProcessRecord;
153
+ sudoPid: number;
154
+ deliver: (password: string) => Promise<SudoReply>;
155
+ }
156
+ export declare class SudoBroker {
157
+ private options;
158
+ private pending;
159
+ private events;
160
+ private watchers;
161
+ private tries;
162
+ constructor(options: SudoBrokerOptions);
163
+ private get now();
164
+ list(): SudoRequestView[];
165
+ /** Overview sockets that asked for sudo frames. Each counts as a phone
166
+ * that can answer while it is open. */
167
+ subscribe(listener: (requests: SudoRequestView[]) => void): () => void;
168
+ private changed;
169
+ /** An askpass call: checks the caller, builds the request, holds it until
170
+ * an answer, a timeout, or `cancel` (the caller went away). */
171
+ ask(body: Json, respond: (reply: SudoReply) => void, hookFd?: number): Promise<{
172
+ cancel: () => void;
173
+ }>;
174
+ /** The phone's answer. Single use: the request is gone once answered.
175
+ * `outcome` resolves to whether sudo took the password: rejected when the
176
+ * same sudo asks again, accepted when it has not within `outcomeMs` (or
177
+ * is still running then), unknown when it gave up or the Hook cannot tell. */
178
+ answer(id: string, answer: {
179
+ password: string;
180
+ } | {
181
+ deny: true;
182
+ }): false | {
183
+ outcome: Promise<SudoOutcome | undefined>;
184
+ };
185
+ private watchOutcome;
186
+ close(): void;
187
+ /** The agent.sock `/sudo` route. */
188
+ handle(req: IncomingMessage, res: ServerResponse): Promise<void>;
189
+ }
190
+ /** A password as sudo reads it from askpass: one line, nothing it would cut. */
191
+ export declare function sudoAnswer(data: Json): {
192
+ id: string;
193
+ answer: {
194
+ password: string;
195
+ } | {
196
+ deny: true;
197
+ };
198
+ outcome: boolean;
199
+ };
200
+ export declare class SudoAnswerError extends Error {
201
+ constructor();
202
+ }
203
+ /** The bundle's `askpass` command, run by sudo through `<bridge>/askpass`.
204
+ * Prints the password and exits 0, or explains on stderr and exits 1. */
205
+ export declare function askpass(prompt: string | undefined, env?: NodeJS.ProcessEnv): Promise<number>;
206
+ /** `phren sudo <command...>`: `sudo -A` with this Hook's askpass, so the
207
+ * password comes from the phone even with no terminal (a `!` command, an
208
+ * agent's shell). Exits with sudo's status. */
209
+ export declare function runSudo(args: string[]): Promise<number>;