@phren/cli 0.3.10 → 0.3.12
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.
- package/dist/bridge/agent-hook-stores.d.ts +3 -0
- package/dist/bridge/agent-hook-stores.js +5 -0
- package/dist/bridge/agent-hooks.d.ts +159 -5
- package/dist/bridge/agent-hooks.js +663 -49
- package/dist/bridge/approval-summary.d.ts +16 -0
- package/dist/bridge/approval-summary.js +133 -0
- package/dist/bridge/authority-command.d.ts +20 -0
- package/dist/bridge/authority-command.js +120 -0
- package/dist/bridge/authority.d.ts +223 -0
- package/dist/bridge/authority.js +231 -0
- package/dist/bridge/claude-account-setup.d.ts +14 -0
- package/dist/bridge/claude-account-setup.js +69 -0
- package/dist/bridge/claude-accounts.d.ts +49 -0
- package/dist/bridge/claude-accounts.js +195 -0
- package/dist/bridge/code-routes.js +2 -2
- package/dist/bridge/codex-app-server.d.ts +144 -0
- package/dist/bridge/codex-app-server.js +319 -0
- package/dist/bridge/codex-auth-refresh.d.ts +33 -0
- package/dist/bridge/codex-auth-refresh.js +71 -0
- package/dist/bridge/codex-question-reply.d.ts +16 -0
- package/dist/bridge/codex-question-reply.js +57 -0
- package/dist/bridge/codex-review-mode.d.ts +10 -0
- package/dist/bridge/codex-review-mode.js +74 -0
- package/dist/bridge/codex-servers.d.ts +217 -0
- package/dist/bridge/codex-servers.js +636 -0
- package/dist/bridge/command.js +94 -4
- package/dist/bridge/computer-identity.d.ts +75 -0
- package/dist/bridge/computer-identity.js +166 -0
- package/dist/bridge/conductor-group.d.ts +91 -8
- package/dist/bridge/conductor-group.js +105 -9
- package/dist/bridge/conductor-role.d.ts +94 -0
- package/dist/bridge/conductor-role.js +176 -0
- package/dist/bridge/conductor-sets.d.ts +20 -0
- package/dist/bridge/conductor-sets.js +59 -0
- package/dist/bridge/dispatch-command.d.ts +3 -0
- package/dist/bridge/dispatch-command.js +75 -11
- package/dist/bridge/dispatch-returns.d.ts +123 -19
- package/dist/bridge/dispatch-returns.js +357 -50
- package/dist/bridge/dispatch.d.ts +103 -2
- package/dist/bridge/dispatch.js +272 -40
- package/dist/bridge/fanout-messages.js +2 -2
- package/dist/bridge/fanouts.d.ts +7 -1
- package/dist/bridge/fanouts.js +40 -5
- package/dist/bridge/folder-trust.d.ts +56 -0
- package/dist/bridge/folder-trust.js +195 -0
- package/dist/bridge/grants.d.ts +22 -1
- package/dist/bridge/grants.js +57 -9
- package/dist/bridge/hand-off.d.ts +21 -9
- package/dist/bridge/hand-off.js +58 -45
- package/dist/bridge/harness-status.d.ts +11 -0
- package/dist/bridge/harness-status.js +32 -0
- package/dist/bridge/harnesses.d.ts +39 -0
- package/dist/bridge/harnesses.js +65 -0
- package/dist/bridge/health.d.ts +2 -0
- package/dist/bridge/health.js +1 -1
- package/dist/bridge/herdr.d.ts +11 -2
- package/dist/bridge/herdr.js +98 -23
- package/dist/bridge/hook-fast.d.ts +4 -0
- package/dist/bridge/hook-fast.js +68 -0
- package/dist/bridge/install.d.ts +16 -1
- package/dist/bridge/install.js +88 -21
- package/dist/bridge/launch-brief.d.ts +96 -0
- package/dist/bridge/launch-brief.js +164 -0
- package/dist/bridge/model-switch.d.ts +3 -0
- package/dist/bridge/model-switch.js +17 -1
- package/dist/bridge/models.d.ts +8 -4
- package/dist/bridge/models.js +24 -8
- package/dist/bridge/mux-wire.d.ts +9 -0
- package/dist/bridge/mux-wire.js +19 -0
- package/dist/bridge/opencode-pane-server.d.ts +113 -0
- package/dist/bridge/opencode-pane-server.js +332 -0
- package/dist/bridge/opencode-panes.d.ts +111 -0
- package/dist/bridge/opencode-panes.js +295 -0
- package/dist/bridge/pane-accounts.d.ts +8 -0
- package/dist/bridge/pane-accounts.js +46 -0
- package/dist/bridge/prompt-startup.d.ts +5 -0
- package/dist/bridge/prompt-startup.js +24 -0
- package/dist/bridge/protocol.d.ts +5 -0
- package/dist/bridge/protocol.js +4 -0
- package/dist/bridge/push.d.ts +5 -4
- package/dist/bridge/push.js +6 -4
- package/dist/bridge/questions.d.ts +37 -2
- package/dist/bridge/questions.js +158 -15
- package/dist/bridge/resources.d.ts +125 -0
- package/dist/bridge/resources.js +314 -0
- package/dist/bridge/schedule-format.d.ts +2 -0
- package/dist/bridge/schedule-format.js +3 -0
- package/dist/bridge/schedule-launch.d.ts +2 -1
- package/dist/bridge/schedule-launch.js +23 -53
- package/dist/bridge/schedule-watch.d.ts +10 -1
- package/dist/bridge/schedule-watch.js +54 -2
- package/dist/bridge/server-launch.d.ts +22 -5
- package/dist/bridge/server-launch.js +225 -29
- package/dist/bridge/server-overview.d.ts +8 -2
- package/dist/bridge/server-overview.js +26 -5
- package/dist/bridge/server-pane-routes.d.ts +2 -0
- package/dist/bridge/server-pane-routes.js +145 -15
- package/dist/bridge/server-routes.d.ts +11 -1
- package/dist/bridge/server-routes.js +195 -36
- package/dist/bridge/server-stream.d.ts +2 -0
- package/dist/bridge/server-stream.js +22 -8
- package/dist/bridge/server.d.ts +6 -1
- package/dist/bridge/server.js +47 -12
- package/dist/bridge/session-activity.d.ts +81 -0
- package/dist/bridge/session-activity.js +117 -0
- package/dist/bridge/session-rename.d.ts +48 -0
- package/dist/bridge/session-rename.js +190 -0
- package/dist/bridge/session-servers.js +2 -2
- package/dist/bridge/settings-switch.d.ts +60 -0
- package/dist/bridge/settings-switch.js +287 -0
- package/dist/bridge/speech-voice.d.ts +55 -0
- package/dist/bridge/speech-voice.js +132 -0
- package/dist/bridge/speech.d.ts +70 -11
- package/dist/bridge/speech.js +169 -41
- package/dist/bridge/terminal-herdr.js +9 -3
- package/dist/bridge/terminal-tmux.d.ts +3 -3
- package/dist/bridge/terminal-tmux.js +24 -9
- package/dist/bridge/terminal.d.ts +27 -4
- package/dist/bridge/terminal.js +8 -1
- package/dist/bridge/transcript-claude.js +62 -12
- package/dist/bridge/transcript-codex.d.ts +0 -2
- package/dist/bridge/transcript-codex.js +29 -4
- package/dist/bridge/transcript-preview.d.ts +1 -0
- package/dist/bridge/transcript-preview.js +24 -4
- package/dist/bridge/transcripts.d.ts +15 -2
- package/dist/bridge/transcripts.js +47 -16
- package/dist/bridge/turn-records.d.ts +85 -0
- package/dist/bridge/turn-records.js +143 -0
- package/dist/bridge/uploads.d.ts +3 -0
- package/dist/bridge/uploads.js +14 -0
- package/dist/bridge/usage.d.ts +73 -28
- package/dist/bridge/usage.js +313 -340
- package/dist/bridge-hook.mjs +24624 -18450
- package/dist/cli/claude-unmanaged.d.ts +12 -0
- package/dist/cli/claude-unmanaged.js +105 -0
- package/dist/cli/schedules.js +2 -1
- package/dist/cli/session-start.js +10 -1
- package/dist/cli/session-stop.js +9 -1
- package/dist/cli-registry.d.ts +2 -0
- package/dist/cli-registry.js +37 -5
- package/dist/computers/command.d.ts +6 -0
- package/dist/computers/command.js +152 -0
- package/dist/computers/mcp.d.ts +1 -0
- package/dist/computers/mcp.js +97 -0
- package/dist/computers/read.d.ts +85 -0
- package/dist/computers/read.js +177 -0
- package/dist/data/task-receipts.d.ts +19 -0
- package/dist/data/task-receipts.js +68 -0
- package/dist/data/tasks.js +4 -1
- package/dist/entrypoint.js +10 -0
- package/dist/fanout/adapters/claude.js +15 -2
- package/dist/fanout/adapters/types.d.ts +6 -0
- package/dist/fanout/launcher.d.ts +5 -1
- package/dist/fanout/launcher.js +34 -3
- package/dist/fanout/picker.js +3 -2
- package/dist/fanout/usage.js +1 -1
- package/dist/generated/memory-ui-graph.browser.js +63 -63
- package/dist/graph-core/model.js +24 -3
- package/dist/graph-core/types.d.ts +4 -1
- package/dist/graph-core/types.js +1 -0
- package/dist/init/init-preset.js +7 -3
- package/dist/init/init-uninstall.js +2 -11
- package/dist/init/teardown.d.ts +3 -0
- package/dist/init/teardown.js +47 -0
- package/dist/link/context.js +21 -9
- package/dist/mcp/plugin-mode.js +1 -1
- package/dist/memory-ui-graph.runtime.js +63 -63
- package/dist/modules/code-package.d.ts +1 -0
- package/dist/modules/code-package.js +36 -7
- package/dist/modules/registry.js +14 -13
- package/dist/profile-store.d.ts +6 -0
- package/dist/profile-store.js +25 -1
- package/dist/shell/graph/glyphs.js +4 -0
- package/dist/shell/graph/graph-view.js +2 -0
- package/dist/status.js +7 -1
- package/dist/sync/task-claim.js +3 -2
- package/dist/task/lifecycle.js +25 -4
- package/dist/test-global-setup.js +5 -0
- package/dist/tools/dispatch.js +35 -2
- package/dist/tools/tasks.js +10 -1
- package/package.json +1 -1
- package/plugins/opencode/phren-transcript.js +87 -4
- package/starter/global/skills/conductor/SKILL.md +17 -2
- package/starter/global/skills/fanout/SKILL.md +3 -0
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { readdir, readFile, statfs } from "node:fs/promises";
|
|
3
|
+
import { cpus, loadavg, totalmem, uptime } from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
import { homeDir } from "../home-paths.js";
|
|
7
|
+
import { recentServers, sharedSnapshot } from "./herdr.js";
|
|
8
|
+
import { intervalFromEnv } from "./limits.js";
|
|
9
|
+
import { objects } from "./protocol.js";
|
|
10
|
+
const exec = promisify(execFile);
|
|
11
|
+
/**
|
|
12
|
+
* This computer's live resources for `GET /v1/resources`, the overview
|
|
13
|
+
* stream's `resources` frames and the memory-free `phren computers` surface:
|
|
14
|
+
* load against cores, memory, free disk on the home volume, battery, uptime
|
|
15
|
+
* and the heavy jobs (simulators, emulators, xcodebuild, Gradle, agent
|
|
16
|
+
* workers) with the pane that started them where one did; any other program
|
|
17
|
+
* holding half a core or more across its processes shows as `busy`. macOS reads
|
|
18
|
+
* sysctl, pmset and ps; Linux reads /proc, /sys and ps. Nothing here needs a
|
|
19
|
+
* permission the Hook does not already have.
|
|
20
|
+
*/
|
|
21
|
+
export const RESOURCES_MAX_AGE_MS = intervalFromEnv("PHREN_RESOURCES_MAX_AGE_MS", 10_000, 1_000, 60_000);
|
|
22
|
+
/** Below this much free disk, or above twice the cores in load, a computer is stressed. */
|
|
23
|
+
export const LOW_DISK_BYTES = 10 * 1024 ** 3;
|
|
24
|
+
const GB = 1024 ** 3;
|
|
25
|
+
/** `ps -axo pid=,ppid=,pcpu=,rss=,comm=` paired with the `args=` listing by pid. */
|
|
26
|
+
export function parsePs(stats, args) {
|
|
27
|
+
const argv = new Map();
|
|
28
|
+
for (const line of args.split("\n")) {
|
|
29
|
+
const match = /^\s*(\d+)\s+(.*)$/.exec(line);
|
|
30
|
+
if (match)
|
|
31
|
+
argv.set(Number(match[1]), match[2]);
|
|
32
|
+
}
|
|
33
|
+
const rows = [];
|
|
34
|
+
for (const line of stats.split("\n")) {
|
|
35
|
+
const match = /^\s*(\d+)\s+(\d+)\s+([\d.]+)\s+(\d+)\s+(.*)$/.exec(line);
|
|
36
|
+
if (!match)
|
|
37
|
+
continue;
|
|
38
|
+
const pid = Number(match[1]);
|
|
39
|
+
rows.push({ pid, ppid: Number(match[2]), cpu: Number(match[3]), rssKB: Number(match[4]), command: match[5].trim(), args: argv.get(pid) ?? match[5].trim() });
|
|
40
|
+
}
|
|
41
|
+
return rows;
|
|
42
|
+
}
|
|
43
|
+
/** What kind of heavy job a process is, if any. */
|
|
44
|
+
export function heavyKind(row) {
|
|
45
|
+
const base = path.basename(row.command);
|
|
46
|
+
const args = row.args;
|
|
47
|
+
if (base === "launchd_sim") {
|
|
48
|
+
return { kind: "simulator", name: /XCTestDevices|Clone \d+ of /.test(args) ? "Simulator test clone" : "Simulator" };
|
|
49
|
+
}
|
|
50
|
+
if (/^qemu-system/.test(base) || base === "emulator" || /^emulator\d*-/.test(base))
|
|
51
|
+
return { kind: "emulator", name: "Android emulator" };
|
|
52
|
+
if (base === "xcodebuild")
|
|
53
|
+
return { kind: "xcodebuild", name: "xcodebuild" };
|
|
54
|
+
if (base === "java") {
|
|
55
|
+
if (/Gradle(?:Daemon|Worker|Main)|gradle-launcher|org\.gradle\./.test(args))
|
|
56
|
+
return { kind: "gradle", name: /Kotlin/.test(args) ? "Kotlin daemon" : "Gradle" };
|
|
57
|
+
if (/KotlinCompileDaemon/.test(args))
|
|
58
|
+
return { kind: "gradle", name: "Kotlin daemon" };
|
|
59
|
+
return { kind: "java", name: "Java" };
|
|
60
|
+
}
|
|
61
|
+
if (base === "codex" || base === "node" && /^\S*node\s+\S*\/codex(?:\.js)?(?:\s|$)/.test(args)) {
|
|
62
|
+
const service = /^\S+\s+(app-server|mcp-server)(?:\s|$)/.exec(args)?.[1];
|
|
63
|
+
return { kind: "codex", name: service === "app-server" ? "Codex app server" : service === "mcp-server" ? "Codex MCP server" : "Codex" };
|
|
64
|
+
}
|
|
65
|
+
if (base === "opencode" || base === ".opencode")
|
|
66
|
+
return { kind: "opencode", name: "OpenCode" };
|
|
67
|
+
if (base === "claude" || /(?:^|\/)claude\/versions\/\d+\.\d+\.\d+$/.test(row.command))
|
|
68
|
+
return { kind: "claude", name: "Claude Code" };
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* The heavy jobs in a process table. Every process counts toward its nearest
|
|
73
|
+
* heavy ancestor-or-self, so a Codex worker running xcodebuild shows both,
|
|
74
|
+
* each with only its own share. Any other program shows as `busy` when its
|
|
75
|
+
* processes together hold half a core. Known programs below both a core's
|
|
76
|
+
* tenth and 200 MiB are left out, including simulators and emulators.
|
|
77
|
+
* A memory-only row can be an idle session or helper; it is not evidence of
|
|
78
|
+
* agent activity. Counts include OS helpers, not just the named executable.
|
|
79
|
+
* On Linux, ps pcpu is a process lifetime average, so these cutoffs can miss
|
|
80
|
+
* daemons that spike briefly.
|
|
81
|
+
*/
|
|
82
|
+
export function heavyProcesses(rows, owners = new Map(), limit = 12) {
|
|
83
|
+
const byPid = new Map(rows.map(row => [row.pid, row]));
|
|
84
|
+
const kinds = new Map();
|
|
85
|
+
for (const row of rows) {
|
|
86
|
+
const kind = heavyKind(row);
|
|
87
|
+
if (kind)
|
|
88
|
+
kinds.set(row.pid, kind);
|
|
89
|
+
}
|
|
90
|
+
// npm's node launcher and its native Codex child are one process group.
|
|
91
|
+
// Keep independently launched/nested Codex workers as separate groups.
|
|
92
|
+
for (const row of rows) {
|
|
93
|
+
const parent = byPid.get(row.ppid);
|
|
94
|
+
if (kinds.get(row.pid)?.kind === "codex" && parent && path.basename(parent.command) === "node" && kinds.get(parent.pid)?.kind === "codex") {
|
|
95
|
+
kinds.set(parent.pid, kinds.get(row.pid));
|
|
96
|
+
kinds.delete(row.pid);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const totals = new Map();
|
|
100
|
+
const busy = new Map();
|
|
101
|
+
const claim = (row) => {
|
|
102
|
+
for (let at = row, hops = 0; at && hops < 64; at = byPid.get(at.ppid), hops++) {
|
|
103
|
+
if (kinds.has(at.pid))
|
|
104
|
+
return at.pid;
|
|
105
|
+
if (at.ppid === at.pid || at.ppid <= 1)
|
|
106
|
+
break;
|
|
107
|
+
}
|
|
108
|
+
return undefined;
|
|
109
|
+
};
|
|
110
|
+
const owner = (row) => {
|
|
111
|
+
for (let at = row, hops = 0; at && hops < 64; at = byPid.get(at.ppid), hops++) {
|
|
112
|
+
const pane = owners.get(at.pid);
|
|
113
|
+
if (pane)
|
|
114
|
+
return pane;
|
|
115
|
+
if (at.ppid === at.pid || at.ppid <= 1)
|
|
116
|
+
break;
|
|
117
|
+
}
|
|
118
|
+
return undefined;
|
|
119
|
+
};
|
|
120
|
+
for (const row of rows) {
|
|
121
|
+
const root = claim(row);
|
|
122
|
+
if (root === undefined) {
|
|
123
|
+
// Unclaimed work groups by program: twelve swift-frontends at 40% each are one busy job.
|
|
124
|
+
const name = path.basename(row.command).slice(0, 60);
|
|
125
|
+
const group = busy.get(name);
|
|
126
|
+
if (!group)
|
|
127
|
+
busy.set(name, { kind: "busy", name, pid: row.pid, processes: 1, cpuPercent: row.cpu, memoryBytes: row.rssKB * 1024, top: row.cpu, row });
|
|
128
|
+
else {
|
|
129
|
+
group.processes++;
|
|
130
|
+
group.cpuPercent += row.cpu;
|
|
131
|
+
group.memoryBytes += row.rssKB * 1024;
|
|
132
|
+
if (row.cpu > group.top) {
|
|
133
|
+
group.top = row.cpu;
|
|
134
|
+
group.pid = row.pid;
|
|
135
|
+
group.row = row;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
let total = totals.get(root);
|
|
141
|
+
if (!total) {
|
|
142
|
+
const { kind, name } = kinds.get(root);
|
|
143
|
+
const pane = owner(byPid.get(root));
|
|
144
|
+
total = { kind, name, pid: root, processes: 0, cpuPercent: 0, memoryBytes: 0, ...(pane ? { pane } : {}) };
|
|
145
|
+
totals.set(root, total);
|
|
146
|
+
}
|
|
147
|
+
total.processes++;
|
|
148
|
+
total.cpuPercent += row.cpu;
|
|
149
|
+
total.memoryBytes += row.rssKB * 1024;
|
|
150
|
+
}
|
|
151
|
+
for (const { top: _top, row, ...group } of busy.values()) {
|
|
152
|
+
if (group.cpuPercent < 50)
|
|
153
|
+
continue;
|
|
154
|
+
const pane = owner(row);
|
|
155
|
+
totals.set(group.pid, { ...group, ...(pane ? { pane } : {}) });
|
|
156
|
+
}
|
|
157
|
+
return [...totals.values()]
|
|
158
|
+
.filter(item => item.kind === "busy" || item.cpuPercent >= 10 || item.memoryBytes >= 200 * 1024 ** 2)
|
|
159
|
+
.map(item => ({ ...item, cpuPercent: Math.round(item.cpuPercent * 10) / 10,
|
|
160
|
+
resourceReason: (item.cpuPercent >= 10 ? "cpu" : item.memoryBytes >= 200 * 1024 ** 2 ? "memory" : "tracked") }))
|
|
161
|
+
.sort((a, b) => b.cpuPercent - a.cpuPercent || b.memoryBytes - a.memoryBytes)
|
|
162
|
+
.slice(0, limit);
|
|
163
|
+
}
|
|
164
|
+
/** `pmset -g batt`: "Now drawing from 'AC Power'" then " -InternalBattery-0 (id=…) 87%; charging; …". */
|
|
165
|
+
export function parsePmset(output) {
|
|
166
|
+
const match = /(\d{1,3})%;\s*([^;]+);/.exec(output);
|
|
167
|
+
if (!match)
|
|
168
|
+
return undefined;
|
|
169
|
+
const state = match[2].trim().toLowerCase();
|
|
170
|
+
return { percent: Math.min(100, Number(match[1])), charging: state === "charging" || state === "charged" || state === "finishing charge",
|
|
171
|
+
onAC: /'AC Power'/.test(output) };
|
|
172
|
+
}
|
|
173
|
+
/** `sysctl vm.swapusage`: "total = 2048.00M used = 798.50M free = …". */
|
|
174
|
+
export function parseSwap(output) {
|
|
175
|
+
const match = /used\s*=\s*([\d.]+)([KMG])/.exec(output);
|
|
176
|
+
if (!match)
|
|
177
|
+
return undefined;
|
|
178
|
+
return Math.round(Number(match[1]) * { K: 1024, M: 1024 ** 2, G: GB }[match[2]]);
|
|
179
|
+
}
|
|
180
|
+
/** /proc/meminfo: MemTotal, MemAvailable and swap, in kB. */
|
|
181
|
+
export function parseMeminfo(text) {
|
|
182
|
+
const field = (name) => { const match = new RegExp(`^${name}:\\s+(\\d+)`, "m").exec(text); return match ? Number(match[1]) * 1024 : undefined; };
|
|
183
|
+
const total = field("MemTotal") ?? totalmem(), available = field("MemAvailable");
|
|
184
|
+
const swapTotal = field("SwapTotal"), swapFree = field("SwapFree");
|
|
185
|
+
const availablePercent = available !== undefined && total ? Math.round(available / total * 100) : undefined;
|
|
186
|
+
return { totalBytes: total, ...(availablePercent !== undefined ? { availablePercent, pressure: availablePercent < 5 ? "critical" : availablePercent < 15 ? "warn" : "normal" } : {}),
|
|
187
|
+
...(swapTotal !== undefined && swapFree !== undefined ? { swapUsedBytes: swapTotal - swapFree } : {}) };
|
|
188
|
+
}
|
|
189
|
+
/** Gauge fill and warnings from the numbers. */
|
|
190
|
+
export function assess(value) {
|
|
191
|
+
const cpu = Math.min(1, value.cpu.loadPerCore / 2);
|
|
192
|
+
const memory = value.memory.pressure === "critical" ? 1
|
|
193
|
+
: Math.max(value.memory.pressure === "warn" ? 0.75 : 0, value.memory.availablePercent === undefined ? 0 : 1 - value.memory.availablePercent / 100);
|
|
194
|
+
const free = value.disk?.freeBytes, total = value.disk?.totalBytes;
|
|
195
|
+
// Plenty of room reads by fraction used; under 50 GB it climbs to full at 10 GB.
|
|
196
|
+
const disk = free === undefined || !total ? 0
|
|
197
|
+
: free >= 50 * GB ? 0.5 * (1 - free / total) : Math.min(1, 0.5 + (50 * GB - free) / (80 * GB));
|
|
198
|
+
const round = (n) => Math.round(Math.max(0, n) * 100) / 100;
|
|
199
|
+
const warnings = [];
|
|
200
|
+
if (value.cpu.loadPerCore > 2)
|
|
201
|
+
warnings.push("load-high");
|
|
202
|
+
if (value.memory.pressure === "critical" || (value.memory.availablePercent ?? 100) < 5)
|
|
203
|
+
warnings.push("memory-low");
|
|
204
|
+
if (free !== undefined && free < LOW_DISK_BYTES)
|
|
205
|
+
warnings.push("disk-low");
|
|
206
|
+
if (value.battery && !value.battery.onAC && value.battery.percent < 15)
|
|
207
|
+
warnings.push("battery-low");
|
|
208
|
+
const overall = Math.max(cpu, memory, disk);
|
|
209
|
+
return { pressure: { cpu: round(cpu), memory: round(memory), disk: round(disk), overall: round(overall) },
|
|
210
|
+
level: warnings.some(w => w !== "battery-low") || overall >= 0.9 ? "stressed" : overall >= 0.6 ? "busy" : "ok", warnings };
|
|
211
|
+
}
|
|
212
|
+
async function run(file, args) {
|
|
213
|
+
return (await exec(file, args, { timeout: 4_000, maxBuffer: 8 * 1024 * 1024, env: { ...process.env, LC_ALL: "C" } })).stdout;
|
|
214
|
+
}
|
|
215
|
+
async function darwinMemory() {
|
|
216
|
+
const [level, pressure, swap] = await Promise.all([
|
|
217
|
+
run("/usr/sbin/sysctl", ["-n", "kern.memorystatus_level"]).catch(() => ""),
|
|
218
|
+
run("/usr/sbin/sysctl", ["-n", "kern.memorystatus_vm_pressure_level"]).catch(() => ""),
|
|
219
|
+
run("/usr/sbin/sysctl", ["-n", "vm.swapusage"]).catch(() => ""),
|
|
220
|
+
]);
|
|
221
|
+
const available = Number(level.trim()), code = Number(pressure.trim()), swapUsedBytes = parseSwap(swap);
|
|
222
|
+
return { totalBytes: totalmem(),
|
|
223
|
+
...(level.trim() && Number.isFinite(available) ? { availablePercent: available } : {}),
|
|
224
|
+
...(pressure.trim() && Number.isFinite(code) ? { pressure: code >= 4 ? "critical" : code >= 2 ? "warn" : "normal" } : {}),
|
|
225
|
+
...(swapUsedBytes !== undefined ? { swapUsedBytes } : {}) };
|
|
226
|
+
}
|
|
227
|
+
async function linuxBattery() {
|
|
228
|
+
const root = "/sys/class/power_supply";
|
|
229
|
+
const names = await readdir(root).catch(() => []);
|
|
230
|
+
const battery = names.find(name => /^BAT/.test(name));
|
|
231
|
+
if (!battery)
|
|
232
|
+
return undefined;
|
|
233
|
+
const read = (name, field) => readFile(path.join(root, name, field), "utf8").then(text => text.trim()).catch(() => "");
|
|
234
|
+
const [capacity, status] = await Promise.all([read(battery, "capacity"), read(battery, "status")]);
|
|
235
|
+
const online = await Promise.all(names.filter(name => !/^BAT/.test(name)).map(name => read(name, "online")));
|
|
236
|
+
const percent = Number(capacity);
|
|
237
|
+
if (!capacity || !Number.isFinite(percent))
|
|
238
|
+
return undefined;
|
|
239
|
+
return { percent, charging: status === "Charging" || status === "Full", onAC: online.includes("1") };
|
|
240
|
+
}
|
|
241
|
+
async function processTable() {
|
|
242
|
+
const [stats, args] = await Promise.all([run("/bin/ps", ["-axo", "pid=,ppid=,pcpu=,rss=,comm="]), run("/bin/ps", ["-axo", "pid=,args="])]);
|
|
243
|
+
return parsePs(stats, args);
|
|
244
|
+
}
|
|
245
|
+
/** Every pid a Herdr or tmux pane holds (its shell and foreground), for naming a job's pane. */
|
|
246
|
+
export async function paneOwners() {
|
|
247
|
+
const owners = new Map();
|
|
248
|
+
const { terminalProvider } = await import("./terminal.js");
|
|
249
|
+
const provider = terminalProvider();
|
|
250
|
+
for (const server of (await recentServers()).slice(0, 8)) {
|
|
251
|
+
const name = String(server.session);
|
|
252
|
+
const s = await sharedSnapshot(name, RESOURCES_MAX_AGE_MS).catch(() => undefined);
|
|
253
|
+
if (!s)
|
|
254
|
+
continue;
|
|
255
|
+
const workspaces = new Map(objects(s.workspaces).map(w => [String(w.workspace_id), typeof w.label === "string" ? w.label : undefined]));
|
|
256
|
+
await Promise.all(objects(s.panes).slice(0, 64).map(async (pane) => {
|
|
257
|
+
const processes = await provider.processes(name, String(pane.pane_id)).catch(() => undefined);
|
|
258
|
+
if (!processes)
|
|
259
|
+
return;
|
|
260
|
+
const ref = { server: name, pane: String(pane.pane_id),
|
|
261
|
+
...(workspaces.get(String(pane.workspace_id)) ? { workspace: workspaces.get(String(pane.workspace_id)) } : {}),
|
|
262
|
+
...(typeof pane.agent === "string" ? { agent: pane.agent } : {}),
|
|
263
|
+
...(typeof pane.label === "string" && pane.label ? { label: pane.label } : {}) };
|
|
264
|
+
for (const pid of [processes.shellPid, ...processes.foregroundPids])
|
|
265
|
+
if (typeof pid === "number" && pid > 0)
|
|
266
|
+
owners.set(pid, ref);
|
|
267
|
+
}));
|
|
268
|
+
}
|
|
269
|
+
return owners;
|
|
270
|
+
}
|
|
271
|
+
export async function collectResources(deps) {
|
|
272
|
+
const [one, five, fifteen] = loadavg();
|
|
273
|
+
const cores = cpus().length || 1;
|
|
274
|
+
const platform = deps.platform;
|
|
275
|
+
const [memory, disk, battery, rows] = await Promise.all([
|
|
276
|
+
platform === "darwin" ? darwinMemory()
|
|
277
|
+
: platform === "linux" ? readFile("/proc/meminfo", "utf8").then(parseMeminfo).catch(() => ({ totalBytes: totalmem() }))
|
|
278
|
+
: Promise.resolve({ totalBytes: totalmem() }),
|
|
279
|
+
statfs(deps.home()).then(info => ({ path: "~", totalBytes: info.blocks * info.bsize, freeBytes: info.bavail * info.bsize })).catch(() => undefined),
|
|
280
|
+
platform === "darwin" ? run("/usr/bin/pmset", ["-g", "batt"]).then(parsePmset).catch(() => undefined)
|
|
281
|
+
: platform === "linux" ? linuxBattery() : Promise.resolve(undefined),
|
|
282
|
+
deps.processes().catch(() => []),
|
|
283
|
+
]);
|
|
284
|
+
// Pane pids cost one terminal call per pane: only when there is a job to name.
|
|
285
|
+
const preliminary = heavyProcesses(rows);
|
|
286
|
+
const owners = preliminary.length ? await deps.owners().catch(() => new Map()) : new Map();
|
|
287
|
+
const round = (n) => Math.round(n * 100) / 100;
|
|
288
|
+
const value = {
|
|
289
|
+
collectedAt: new Date(deps.now()).toISOString(), platform, uptimeSeconds: Math.round(uptime()),
|
|
290
|
+
cpu: { cores, load1: round(one), load5: round(five), load15: round(fifteen), loadPerCore: round(one / cores) },
|
|
291
|
+
memory, ...(disk ? { disk } : {}), ...(battery ? { battery } : {}),
|
|
292
|
+
heavy: owners.size ? heavyProcesses(rows, owners) : preliminary,
|
|
293
|
+
};
|
|
294
|
+
return { ...value, ...assess(value) };
|
|
295
|
+
}
|
|
296
|
+
/** One collection at a time, reused for `RESOURCES_MAX_AGE_MS`. */
|
|
297
|
+
export class ResourceMonitor {
|
|
298
|
+
maxAgeMs;
|
|
299
|
+
cached;
|
|
300
|
+
pending;
|
|
301
|
+
deps;
|
|
302
|
+
constructor(deps = {}, maxAgeMs = RESOURCES_MAX_AGE_MS) {
|
|
303
|
+
this.maxAgeMs = maxAgeMs;
|
|
304
|
+
this.deps = { platform: process.platform, now: Date.now, home: homeDir, processes: processTable, owners: paneOwners, ...deps };
|
|
305
|
+
}
|
|
306
|
+
async read() {
|
|
307
|
+
if (this.cached && this.deps.now() - this.cached.at < this.maxAgeMs)
|
|
308
|
+
return this.cached.value;
|
|
309
|
+
this.pending ??= collectResources(this.deps)
|
|
310
|
+
.then(value => { this.cached = { at: this.deps.now(), value }; return value; })
|
|
311
|
+
.finally(() => { this.pending = undefined; });
|
|
312
|
+
return this.pending;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
@@ -23,6 +23,8 @@ export interface Schedule {
|
|
|
23
23
|
computer: string;
|
|
24
24
|
harness: ScheduleHarness;
|
|
25
25
|
model?: string;
|
|
26
|
+
/** Claude account id (a slug) the run uses; absent means the default account. */
|
|
27
|
+
account?: string;
|
|
26
28
|
notify?: ScheduleNotify[];
|
|
27
29
|
every: ScheduleEvery;
|
|
28
30
|
at?: string;
|
|
@@ -4,6 +4,7 @@ import path from "node:path";
|
|
|
4
4
|
import * as yaml from "js-yaml";
|
|
5
5
|
import { z } from "zod";
|
|
6
6
|
import { atomicInPrivateDir, bridgeRoot, object } from "./protocol.js";
|
|
7
|
+
import { isAccountSlug } from "./claude-accounts.js";
|
|
7
8
|
/** The schedules.yaml store: the schedule and run record shapes, validation,
|
|
8
9
|
* the five timing forms evaluated in local time, and the run history file. */
|
|
9
10
|
export const SCHEDULE_EVERY = ["interval", "daily", "weekly", "once", "cron"];
|
|
@@ -62,6 +63,8 @@ export function parseSchedule(value) {
|
|
|
62
63
|
};
|
|
63
64
|
if (raw.model !== undefined)
|
|
64
65
|
schedule.model = singleLine(200).parse(raw.model);
|
|
66
|
+
if (raw.account !== undefined)
|
|
67
|
+
schedule.account = z.string().refine(isAccountSlug, "Account must be default or a lowercase slug.").parse(raw.account);
|
|
65
68
|
if (raw.notify !== undefined)
|
|
66
69
|
schedule.notify = z.array(z.enum(SCHEDULE_NOTIFY)).max(3).parse(raw.notify)
|
|
67
70
|
.filter((kind, index, kinds) => kinds.indexOf(kind) === index);
|
|
@@ -11,10 +11,11 @@ export declare function createScheduleLauncher(launchHerdr: HerdrLauncher, store
|
|
|
11
11
|
* since an open run blocks its schedule for good.
|
|
12
12
|
*/
|
|
13
13
|
export declare function resumeScheduleRun(run: ScheduleRun, schedule: Schedule, signal: AbortSignal, watch?: typeof watchHerdrRun): Promise<ScheduleRunOutcome>;
|
|
14
|
+
/** The environment a headless run gets: this Hook's, plus the chosen Claude account's config directory. */
|
|
15
|
+
export declare function headlessEnv(schedule: Schedule, env?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
|
|
14
16
|
export declare function headlessCommand(schedule: Schedule, cwd: string): {
|
|
15
17
|
file: string;
|
|
16
18
|
args: string[];
|
|
17
19
|
cwd: string;
|
|
18
20
|
};
|
|
19
|
-
export declare function ensureCodexDirTrusted(cwd: string): Promise<void>;
|
|
20
21
|
export {};
|
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import { createWriteStream } from "node:fs";
|
|
3
|
-
import { mkdir, readFile
|
|
4
|
-
import { codexHome } from "../home-paths.js";
|
|
3
|
+
import { mkdir, readFile } from "node:fs/promises";
|
|
5
4
|
import path from "node:path";
|
|
6
5
|
import { finished as streamFinished } from "node:stream/promises";
|
|
6
|
+
import { claudeHome, claudeLaunchEnv } from "./claude-accounts.js";
|
|
7
7
|
import { fanoutRoot } from "./fanouts.js";
|
|
8
|
+
import { pretrustFolder } from "./folder-trust.js";
|
|
8
9
|
import { findPane, paneIdentity, servers, snapshot } from "./herdr.js";
|
|
9
10
|
import { agentNotReady, terminalProvider } from "./terminal.js";
|
|
10
|
-
import {
|
|
11
|
-
import { logger } from "../logger.js";
|
|
11
|
+
import { atomicInPrivateDir, BridgeError } from "./protocol.js";
|
|
12
12
|
import { defaultPhrenPath } from "../shared.js";
|
|
13
13
|
import { watchHerdrRun } from "./schedule-watch.js";
|
|
14
14
|
/** Starting a scheduled run: in a Herdr pane when a server is live, otherwise
|
|
@@ -52,9 +52,13 @@ export async function resumeScheduleRun(run, schedule, signal, watch = watchHerd
|
|
|
52
52
|
return { status: "failed", reason: "Phren Hook restarted while this run was going, so its end was not observed." };
|
|
53
53
|
}
|
|
54
54
|
async function launchInHerdr(server, context, launchHerdr, signal) {
|
|
55
|
-
|
|
55
|
+
// The prompt goes with the launch where the harness takes one (Claude,
|
|
56
|
+
// Codex); otherwise it is typed once the agent is ready.
|
|
57
|
+
const brief = context.schedule.prompt.trim() ? { brief: { id: context.runId, text: context.schedule.prompt } } : {};
|
|
58
|
+
const launched = await launchHerdr(server, { cwd: context.cwd, label: context.schedule.name, kind: context.schedule.harness, model: context.schedule.model, ...(context.schedule.account ? { account: context.schedule.account } : {}), ...brief });
|
|
56
59
|
const workspaceId = String(launched.workspaceId), tabId = String(launched.tabId), paneId = String(launched.paneId);
|
|
57
|
-
|
|
60
|
+
if (launched.briefLaunched !== true)
|
|
61
|
+
await promptWhenReady(server, paneId, context.schedule.prompt, signal);
|
|
58
62
|
let sessionId = typeof launched.sessionId === "string" ? launched.sessionId : undefined;
|
|
59
63
|
for (let attempt = 0; attempt < 10 && !sessionId; attempt++) {
|
|
60
64
|
const pane = findPane(await snapshot(server), { workspace: workspaceId, tab: tabId, pane: paneId });
|
|
@@ -86,7 +90,17 @@ async function promptWhenReady(server, paneId, text, signal, waitMs = 60_000) {
|
|
|
86
90
|
}
|
|
87
91
|
}
|
|
88
92
|
}
|
|
93
|
+
/** The environment a headless run gets: this Hook's, plus the chosen Claude account's config directory. */
|
|
94
|
+
export function headlessEnv(schedule, env = process.env) {
|
|
95
|
+
if (!schedule.account || schedule.harness !== "claude")
|
|
96
|
+
return env;
|
|
97
|
+
const home = claudeHome(schedule.account, env);
|
|
98
|
+
if (!home)
|
|
99
|
+
throw new Error(`Schedule "${schedule.name}" uses Claude account "${schedule.account}", which is not set up on this computer. Run \`phren bridge accounts\`.`);
|
|
100
|
+
return { ...env, ...claudeLaunchEnv(home) };
|
|
101
|
+
}
|
|
89
102
|
async function launchHeadless(context, store, started) {
|
|
103
|
+
const env = headlessEnv(context.schedule);
|
|
90
104
|
const root = fanoutRoot({ ...process.env, PHREN_PATH: store }), jobDir = path.join(root, context.runId);
|
|
91
105
|
await mkdir(jobDir, { recursive: true, mode: 0o700 });
|
|
92
106
|
const eventLog = "events.jsonl", now = new Date().toISOString();
|
|
@@ -96,11 +110,12 @@ async function launchHeadless(context, store, started) {
|
|
|
96
110
|
await writeManifest(jobDir, manifest);
|
|
97
111
|
const command = headlessCommand(context.schedule, context.cwd);
|
|
98
112
|
// An untrusted directory only costs Codex a prompt; the run still starts, and the log says why.
|
|
113
|
+
// Headless Claude (`-p`) has no trust screen, so only Codex needs it here.
|
|
99
114
|
if (context.schedule.harness === "codex")
|
|
100
|
-
await
|
|
115
|
+
await pretrustFolder("codex", context.cwd, `scheduled run ${context.runId}`);
|
|
101
116
|
let child;
|
|
102
117
|
try {
|
|
103
|
-
child = spawn(command.file, command.args, { cwd: command.cwd, env
|
|
118
|
+
child = spawn(command.file, command.args, { cwd: command.cwd, env, stdio: ["pipe", "pipe", "pipe"] });
|
|
104
119
|
}
|
|
105
120
|
catch (error) {
|
|
106
121
|
await writeManifest(jobDir, { ...manifest, status: "failed", updatedAt: new Date().toISOString(), finishedAt: new Date().toISOString() });
|
|
@@ -145,51 +160,6 @@ export function headlessCommand(schedule, cwd) {
|
|
|
145
160
|
return { file: "opencode", cwd, args: ["run", "--format", "json", "--dir", cwd, ...model] };
|
|
146
161
|
return { file: "claude", cwd, args: ["-p", "--output-format", "stream-json", "--settings", CLAUDE_SCHEDULE_SETTINGS, ...model] };
|
|
147
162
|
}
|
|
148
|
-
function tomlQuote(value) {
|
|
149
|
-
return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
|
|
150
|
-
}
|
|
151
|
-
export async function ensureCodexDirTrusted(cwd) {
|
|
152
|
-
const directory = codexHome();
|
|
153
|
-
const file = path.join(directory, "config.toml");
|
|
154
|
-
let text = "";
|
|
155
|
-
try {
|
|
156
|
-
text = await readFile(file, "utf8");
|
|
157
|
-
}
|
|
158
|
-
// An unreadable config is left untouched; the caller logs why.
|
|
159
|
-
catch (error) {
|
|
160
|
-
if (error.code !== "ENOENT")
|
|
161
|
-
throw error;
|
|
162
|
-
}
|
|
163
|
-
const header = `[projects.${tomlQuote(cwd)}]`;
|
|
164
|
-
const trustLine = 'trust_level = "trusted"';
|
|
165
|
-
let next;
|
|
166
|
-
const at = text.indexOf(header);
|
|
167
|
-
if (at >= 0) {
|
|
168
|
-
const bodyStart = at + header.length;
|
|
169
|
-
const rest = text.slice(bodyStart);
|
|
170
|
-
const nextTable = rest.search(/^\s*\[/m);
|
|
171
|
-
const section = nextTable >= 0 ? rest.slice(0, nextTable) : rest;
|
|
172
|
-
if (new RegExp(`trust_level\\s*=\\s*"trusted"`).test(section))
|
|
173
|
-
return;
|
|
174
|
-
const existing = /^[ \t]*trust_level\s*=.*$/m.exec(section);
|
|
175
|
-
if (existing) {
|
|
176
|
-
const replaced = section.replace(existing[0], existing[0].match(/^[ \t]*/)[0] + trustLine);
|
|
177
|
-
next = text.slice(0, bodyStart) + replaced + rest.slice(section.length);
|
|
178
|
-
}
|
|
179
|
-
else {
|
|
180
|
-
const newline = section.startsWith("\n") || section.startsWith("\r\n") ? "" : "\n";
|
|
181
|
-
next = text.slice(0, bodyStart) + newline + trustLine + (section.startsWith("\n") || section.startsWith("\r\n") ? section : "\n" + section) + rest.slice(section.length);
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
else {
|
|
185
|
-
const separator = text && !text.endsWith("\n") ? "\n\n" : text ? "\n" : "";
|
|
186
|
-
next = text + `${separator}${header}\n${trustLine}\n`;
|
|
187
|
-
}
|
|
188
|
-
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
189
|
-
const metadata = await stat(file).catch(() => undefined);
|
|
190
|
-
const mode = metadata ? metadata.mode & 0o777 : 0o600;
|
|
191
|
-
await atomic(file, next, mode);
|
|
192
|
-
}
|
|
193
163
|
async function writeManifest(jobDir, manifest) {
|
|
194
164
|
await atomicInPrivateDir(path.join(jobDir, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n");
|
|
195
165
|
}
|
|
@@ -30,11 +30,20 @@ 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
|
+
/** `error`: the harness ended the turn on an error (Codex's usage limit) instead of a reply.
|
|
34
|
+
* `interrupted`: the owner stopped the last turn (Claude's "[Request interrupted by user]",
|
|
35
|
+
* Codex's turn_aborted); the harness sends no Stop for it.
|
|
36
|
+
* `background`: Claude Code background tasks (shells, subagents, monitors) started in
|
|
37
|
+
* the transcript's tail with no task-notification or TaskStop ending them yet.
|
|
38
|
+
* `finishedTasks`: when each Claude background task the tail shows finishing
|
|
39
|
+
* finished (its first final task-notification's timestamp), one per task. */
|
|
34
40
|
export interface FinalTurn {
|
|
35
41
|
completed: boolean;
|
|
36
42
|
lastAssistant?: string;
|
|
37
43
|
error?: string;
|
|
44
|
+
interrupted?: boolean;
|
|
45
|
+
background?: number;
|
|
46
|
+
finishedTasks?: string[];
|
|
38
47
|
}
|
|
39
48
|
/** The public text of one assistant row, without reasoning or tool output. */
|
|
40
49
|
export declare function publicAssistant(raw: Json, source: Provider): string | undefined;
|
|
@@ -83,10 +83,50 @@ function turnError(raw, source) {
|
|
|
83
83
|
const error = object(object(raw.payload).error), message = typeof error.message === "string" ? error.message.replace(/\s+/g, " ").trim() : "";
|
|
84
84
|
return message ? message.slice(0, 500) : undefined;
|
|
85
85
|
}
|
|
86
|
+
/** The owner stopping a turn: Claude's interruption marker, Codex's aborted turn. */
|
|
87
|
+
function turnInterrupted(raw, source) {
|
|
88
|
+
if (source === "codex")
|
|
89
|
+
return raw.type === "event_msg" && object(raw.payload).type === "turn_aborted";
|
|
90
|
+
if (source !== "claude" || raw.type !== "user")
|
|
91
|
+
return false;
|
|
92
|
+
const content = object(raw.message).content;
|
|
93
|
+
const text = typeof content === "string" ? content : objects(content).filter(block => block.type === "text").map(block => String(block.text ?? "")).join("");
|
|
94
|
+
return text.startsWith("[Request interrupted by user");
|
|
95
|
+
}
|
|
96
|
+
/** Claude Code background work a transcript line starts or ends, by task id:
|
|
97
|
+
* a backgrounded Bash call, an async subagent or a Monitor start one; a
|
|
98
|
+
* task-notification with a final status, or a TaskStop, ends it. A
|
|
99
|
+
* persistent monitor runs for the whole session and is never waited on.
|
|
100
|
+
* `finished` keeps when each task's first final notification was written.
|
|
101
|
+
* A notification reaching an idle session is written as a queue-operation
|
|
102
|
+
* row, and may stay there with no new turn to deliver it. */
|
|
103
|
+
function backgroundTasks(raw, running, finished) {
|
|
104
|
+
const result = object(raw.toolUseResult);
|
|
105
|
+
const started = typeof result.backgroundTaskId === "string" ? result.backgroundTaskId
|
|
106
|
+
: result.isAsync === true && typeof result.agentId === "string" ? result.agentId
|
|
107
|
+
: typeof result.taskId === "string" && result.persistent !== true && typeof result.timeoutMs === "number" ? result.taskId : undefined;
|
|
108
|
+
if (started)
|
|
109
|
+
running.add(started);
|
|
110
|
+
if (typeof result.task_id === "string" && typeof result.message === "string" && /\bstopped\b/i.test(result.message))
|
|
111
|
+
running.delete(result.task_id);
|
|
112
|
+
const content = object(raw.message).content, attachment = object(raw.attachment);
|
|
113
|
+
const notices = [typeof content === "string" ? content : "", typeof attachment.prompt === "string" ? attachment.prompt : "",
|
|
114
|
+
raw.type === "queue-operation" && typeof raw.content === "string" ? raw.content : ""];
|
|
115
|
+
// A monitor's events arrive as notifications too, without a final status.
|
|
116
|
+
for (const block of notices.flatMap(notice => notice.split("<task-notification>").slice(1))) {
|
|
117
|
+
const id = /<task-id>([^<\s]{1,100})<\/task-id>/.exec(block)?.[1];
|
|
118
|
+
if (!id || !/<status>(?:completed|failed|killed|stopped)<\/status>/.test(block))
|
|
119
|
+
continue;
|
|
120
|
+
running.delete(id);
|
|
121
|
+
if (!finished.has(id) && typeof raw.timestamp === "string" && !Number.isNaN(Date.parse(raw.timestamp)))
|
|
122
|
+
finished.set(id, raw.timestamp);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
86
125
|
/** The last assistant reply in a transcript and whether its turn finished.
|
|
87
126
|
* A person's message after the reply opens a new turn, so it clears both. */
|
|
88
127
|
export function finalTurnFromLines(lines, source) {
|
|
89
|
-
let completed = false, lastAssistant, error;
|
|
128
|
+
let completed = false, lastAssistant, error, interrupted = false;
|
|
129
|
+
const running = new Set(), finished = new Map();
|
|
90
130
|
for (const line of lines) {
|
|
91
131
|
if (!line.trim())
|
|
92
132
|
continue;
|
|
@@ -98,6 +138,13 @@ export function finalTurnFromLines(lines, source) {
|
|
|
98
138
|
continue;
|
|
99
139
|
}
|
|
100
140
|
const payload = object(raw.payload);
|
|
141
|
+
if (source === "claude")
|
|
142
|
+
backgroundTasks(raw, running, finished);
|
|
143
|
+
if (turnInterrupted(raw, source)) {
|
|
144
|
+
interrupted = true;
|
|
145
|
+
completed = false;
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
101
148
|
const userTurn = source === "claude" ? raw.type === "user" && !raw.isMeta && typeof object(raw.message).content === "string"
|
|
102
149
|
: source === "codex" ? raw.type === "response_item" && payload.type === "message" && payload.role === "user"
|
|
103
150
|
: raw.type === "user/message";
|
|
@@ -105,19 +152,24 @@ export function finalTurnFromLines(lines, source) {
|
|
|
105
152
|
completed = false;
|
|
106
153
|
lastAssistant = undefined;
|
|
107
154
|
error = undefined;
|
|
155
|
+
interrupted = false;
|
|
108
156
|
continue;
|
|
109
157
|
}
|
|
110
158
|
const text = publicAssistant(raw, source);
|
|
111
159
|
if (text) {
|
|
112
160
|
lastAssistant = text;
|
|
113
161
|
completed = false;
|
|
162
|
+
interrupted = false;
|
|
114
163
|
}
|
|
115
164
|
if (turnEnded(raw, source)) {
|
|
116
165
|
completed = true;
|
|
166
|
+
interrupted = false;
|
|
117
167
|
error = turnError(raw, source);
|
|
118
168
|
}
|
|
119
169
|
}
|
|
120
|
-
return { completed, ...(lastAssistant ? { lastAssistant } : {}), ...(completed && error ? { error } : {})
|
|
170
|
+
return { completed, ...(lastAssistant ? { lastAssistant } : {}), ...(completed && error ? { error } : {}),
|
|
171
|
+
...(interrupted ? { interrupted: true } : {}), ...(completed && running.size ? { background: running.size } : {}),
|
|
172
|
+
...(finished.size ? { finishedTasks: [...finished.values()] } : {}) };
|
|
121
173
|
}
|
|
122
174
|
/** The final turn of a conversation, read from the tail of its transcript. */
|
|
123
175
|
export async function readFinalTurn(source, sessionId) {
|
|
@@ -1,6 +1,9 @@
|
|
|
1
|
+
import { type HarnessInventory } from "./harnesses.js";
|
|
1
2
|
import { type Json } from "./protocol.js";
|
|
2
|
-
/** The live conductor on this computer,
|
|
3
|
-
*
|
|
3
|
+
/** The live conductor on this computer, as a target: the pane the Hook
|
|
4
|
+
* recorded (docs/conductor-sets.md), or before any record, a pane named as a
|
|
5
|
+
* conductor on any server, which is then recorded. `known` reuses a snapshot
|
|
6
|
+
* the caller already took. */
|
|
4
7
|
export declare function localConductor(known?: {
|
|
5
8
|
server: string;
|
|
6
9
|
snapshot: Json;
|
|
@@ -8,8 +11,23 @@ export declare function localConductor(known?: {
|
|
|
8
11
|
server: string;
|
|
9
12
|
target?: Json;
|
|
10
13
|
} | undefined>;
|
|
14
|
+
/** "Make conductor": the owner gives an agent already running in a pane on this computer the role. */
|
|
15
|
+
export declare function makeConductor(server: string, data: Json): Promise<Json>;
|
|
16
|
+
/** "Stop being conductor": the pane keeps its agent and loses the role. With
|
|
17
|
+
* `paneId`, only that pane's role ends. */
|
|
18
|
+
export declare function stopConductor(data: Json): Promise<Json>;
|
|
11
19
|
/** The Herdr agent-name slug for a human label: "Conductor smoke 4" becomes "conductor-smoke-4". */
|
|
12
20
|
export declare function herdrAgentName(label: string): string;
|
|
21
|
+
type InventoryReader = () => Promise<HarnessInventory>;
|
|
22
|
+
/** Only for tests: what this computer can launch. Without one, `PHREN_LAUNCH_CHECK=off` skips the early availability check. */
|
|
23
|
+
export declare function setLaunchInventory(reader: InventoryReader | undefined): void;
|
|
24
|
+
export interface LaunchOptions {
|
|
25
|
+
canary?: boolean;
|
|
26
|
+
/** `data.cwd` is a folder the Hook resolved itself (a dispatched or
|
|
27
|
+
* scheduled project's source folder), so it may be marked trusted for the
|
|
28
|
+
* harness before the launch. Never set for a folder the phone chose. */
|
|
29
|
+
trustFolder?: boolean;
|
|
30
|
+
}
|
|
13
31
|
/**
|
|
14
32
|
* "Open on a computer": a new Herdr workspace (or a tab in an existing one)
|
|
15
33
|
* in the project's directory, with the chosen agent started in its pane.
|
|
@@ -17,7 +35,6 @@ export declare function herdrAgentName(label: string): string;
|
|
|
17
35
|
* by diffing snapshots; `agent.start` returns once Herdr has detected the
|
|
18
36
|
* agent and it is ready for input, which can take most of `timeoutMs`.
|
|
19
37
|
*/
|
|
20
|
-
export declare function launchSession(server: string, data: Json, options?:
|
|
21
|
-
canary?: boolean;
|
|
22
|
-
}): Promise<Json>;
|
|
38
|
+
export declare function launchSession(server: string, data: Json, options?: LaunchOptions): Promise<Json>;
|
|
23
39
|
export declare function workspaceAction(server: string, operation: string, data: Json): Promise<Json>;
|
|
40
|
+
export {};
|