@phren/cli 0.3.16 → 0.3.17
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-hooks.d.ts +10 -0
- package/dist/bridge/agent-hooks.js +49 -10
- package/dist/bridge/claude-suggestion.d.ts +8 -0
- package/dist/bridge/claude-suggestion.js +71 -0
- package/dist/bridge/dispatch-returns.d.ts +6 -3
- package/dist/bridge/dispatch-returns.js +29 -17
- package/dist/bridge/job-registry.d.ts +144 -0
- package/dist/bridge/job-registry.js +247 -0
- package/dist/bridge/opencode-permissions.d.ts +17 -0
- package/dist/bridge/opencode-permissions.js +96 -0
- package/dist/bridge/protocol.d.ts +4 -0
- package/dist/bridge/protocol.js +3 -0
- package/dist/bridge/resources.d.ts +38 -5
- package/dist/bridge/resources.js +110 -19
- package/dist/bridge/server-launch.js +8 -0
- package/dist/bridge/server-routes.d.ts +1 -1
- package/dist/bridge/server-routes.js +8 -6
- package/dist/bridge/server-stream.js +11 -2
- package/dist/bridge/session-activity.d.ts +13 -0
- package/dist/bridge/session-activity.js +27 -2
- package/dist/bridge/settings-switch.d.ts +12 -2
- package/dist/bridge/settings-switch.js +13 -6
- package/dist/bridge/speech.d.ts +6 -4
- package/dist/bridge/speech.js +6 -4
- package/dist/bridge/terminal-tmux.d.ts +4 -2
- package/dist/bridge/terminal-tmux.js +13 -7
- package/dist/bridge/transcript-claude.d.ts +9 -1
- package/dist/bridge/transcript-claude.js +50 -1
- package/dist/bridge/transcript-codex.js +23 -3
- package/dist/bridge/transcripts.d.ts +5 -1
- package/dist/bridge/transcripts.js +13 -3
- package/dist/bridge-hook.mjs +1044 -528
- package/dist/computers/command.js +2 -1
- package/dist/fanout/opencode-serve.js +3 -2
- package/dist/hooks.d.ts +3 -0
- package/dist/hooks.js +41 -6
- package/dist/init/setup.js +6 -3
- package/dist/modules/registry.js +1 -1
- package/dist/tools/dispatch.js +3 -2
- package/package.json +1 -1
- package/plugins/opencode/phren-transcript.js +4 -4
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { atomicInPrivateDir, bridgeRoot } from "./protocol.js";
|
|
5
|
+
const paneSchema = z.object({
|
|
6
|
+
server: z.string().min(1).max(200),
|
|
7
|
+
workspace: z.string().max(200).optional(),
|
|
8
|
+
pane: z.string().min(1).max(200),
|
|
9
|
+
agent: z.string().max(60).optional(),
|
|
10
|
+
label: z.string().max(200).optional(),
|
|
11
|
+
}).strict();
|
|
12
|
+
const jobSchema = z.object({
|
|
13
|
+
/** The worker's process group, once the process table has shown it. */
|
|
14
|
+
pgid: z.number().int().positive().optional(),
|
|
15
|
+
/** When the group's leader started (epoch ms), recorded with the pgid, so a
|
|
16
|
+
* group id the system later reuses for another program is never signalled. */
|
|
17
|
+
leaderStartedAt: z.number().int().nonnegative().optional(),
|
|
18
|
+
pane: paneSchema.optional(),
|
|
19
|
+
session: z.string().min(1).max(200).optional(),
|
|
20
|
+
agent: z.string().max(60).optional(),
|
|
21
|
+
label: z.string().max(200).optional(),
|
|
22
|
+
/** The Harness/executable the Hook started, for display and a reuse check. */
|
|
23
|
+
command: z.string().min(1).max(500),
|
|
24
|
+
/** Epoch ms. */
|
|
25
|
+
startedAt: z.number().int().nonnegative(),
|
|
26
|
+
}).strict();
|
|
27
|
+
const stateSchema = z.object({ version: z.literal(1), jobs: z.array(jobSchema).max(1024) }).strict();
|
|
28
|
+
/** The identity of a job: its pane while one exists, else its session, else its group. */
|
|
29
|
+
export const paneKey = (pane) => `${pane.server}\0${pane.pane}`;
|
|
30
|
+
export function jobKey(job) {
|
|
31
|
+
if (job.pane)
|
|
32
|
+
return `pane:${paneKey(job.pane)}`;
|
|
33
|
+
if (job.session)
|
|
34
|
+
return `session:${job.session}`;
|
|
35
|
+
if (job.pgid !== undefined)
|
|
36
|
+
return `pgid:${job.pgid}`;
|
|
37
|
+
return `command:${job.command}`;
|
|
38
|
+
}
|
|
39
|
+
/** The registered jobs by their process group, for attribution. */
|
|
40
|
+
export function jobPgids(jobs) {
|
|
41
|
+
const byPgid = new Map();
|
|
42
|
+
for (const job of jobs)
|
|
43
|
+
if (job.pgid !== undefined && !byPgid.has(job.pgid))
|
|
44
|
+
byPgid.set(job.pgid, job);
|
|
45
|
+
return byPgid;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Fill each job's process group from the pane it owns: a job registered before
|
|
49
|
+
* its terminal started has no pgid until the process table shows the pane's
|
|
50
|
+
* shell (or an already-detached process) in a group. Never invents a group.
|
|
51
|
+
*/
|
|
52
|
+
export function resolveJobGroups(jobs, rows, owners) {
|
|
53
|
+
const byPane = new Map();
|
|
54
|
+
for (const row of rows) {
|
|
55
|
+
const pane = owners.get(row.pid);
|
|
56
|
+
if (pane && row.pgid > 1 && !byPane.has(paneKey(pane)))
|
|
57
|
+
byPane.set(paneKey(pane), row.pgid);
|
|
58
|
+
}
|
|
59
|
+
const leaders = new Map(rows.filter(row => row.pid === row.pgid && row.startedAt !== undefined).map(row => [row.pid, Math.round(row.startedAt)]));
|
|
60
|
+
return jobs.map(job => {
|
|
61
|
+
if (job.pgid !== undefined || !job.pane)
|
|
62
|
+
return job;
|
|
63
|
+
const pgid = byPane.get(paneKey(job.pane));
|
|
64
|
+
if (pgid === undefined)
|
|
65
|
+
return job;
|
|
66
|
+
const leaderStartedAt = leaders.get(pgid);
|
|
67
|
+
return { ...job, pgid, ...(leaderStartedAt !== undefined ? { leaderStartedAt } : {}) };
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
/** How long a job's process group is left alone after its pane was requested,
|
|
71
|
+
* so a launch that is still coming up is never signalled. */
|
|
72
|
+
export const CLEANUP_LEASE_MS = 5 * 60_000;
|
|
73
|
+
/** `ps` reports elapsed time in whole seconds, read at slightly different moments. */
|
|
74
|
+
export const LEADER_START_TOLERANCE_MS = 3_000;
|
|
75
|
+
/** How long a finished or reused record is kept before it is dropped. */
|
|
76
|
+
export const CLEANUP_RETAIN_MS = 24 * 60 * 60_000;
|
|
77
|
+
/** Whether a process in a job's group still looks like the command the Hook started. */
|
|
78
|
+
function commandMatches(job, row) {
|
|
79
|
+
return path.basename(row.command) === path.basename(job.command) || row.args.includes(job.command);
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Decide which registered process groups may be ended. A job is ended only when
|
|
83
|
+
* every one of these holds: it has a resolved group above 1, its owning pane is
|
|
84
|
+
* not in `live`, its group still has processes, none of them is the Hook itself,
|
|
85
|
+
* the lease has passed, and a process still matches the command the Hook
|
|
86
|
+
* started. Anything else is kept (with a reason) or, when the group is gone or
|
|
87
|
+
* the record is old, forgotten. A caller that could not read the live panes
|
|
88
|
+
* passes `panesKnown: false`, so a failed snapshot never triggers a kill.
|
|
89
|
+
*/
|
|
90
|
+
export function planCleanup(jobs, rows, live, options = {}) {
|
|
91
|
+
const now = options.now ?? Date.now(), leaseMs = options.leaseMs ?? CLEANUP_LEASE_MS, retainMs = options.retainMs ?? CLEANUP_RETAIN_MS;
|
|
92
|
+
const self = options.selfPid ?? process.pid;
|
|
93
|
+
const panesKnown = options.panesKnown ?? true;
|
|
94
|
+
const byPgid = new Map();
|
|
95
|
+
for (const row of rows) {
|
|
96
|
+
const list = byPgid.get(row.pgid);
|
|
97
|
+
if (list)
|
|
98
|
+
list.push(row);
|
|
99
|
+
else
|
|
100
|
+
byPgid.set(row.pgid, [row]);
|
|
101
|
+
}
|
|
102
|
+
// The Hook's own process group, whatever its pid: never a target.
|
|
103
|
+
const ownGroup = rows.find(row => row.pid === self)?.pgid;
|
|
104
|
+
const kill = [], keep = [], forget = [];
|
|
105
|
+
for (const job of jobs) {
|
|
106
|
+
const kept = (reason) => keep.push({ job, reason });
|
|
107
|
+
if (!panesKnown) {
|
|
108
|
+
kept("unknown");
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
if (job.pgid === undefined) {
|
|
112
|
+
// No group recorded: nothing may be signalled. A record whose pane has
|
|
113
|
+
// been gone past the lease cannot resolve any more, so it is dropped;
|
|
114
|
+
// a fresh one is kept while its launch comes up.
|
|
115
|
+
if (job.pane && !live.has(paneKey(job.pane)) && now - job.startedAt > leaseMs)
|
|
116
|
+
forget.push(job);
|
|
117
|
+
else
|
|
118
|
+
kept("unresolved");
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (job.pgid <= 1 || job.pgid === ownGroup) {
|
|
122
|
+
kept("reserved");
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
// Only a job pinned to a pane is ever ended: a session-only record has no
|
|
126
|
+
// pane to prove gone, so it is never signalled.
|
|
127
|
+
if (!job.pane) {
|
|
128
|
+
kept("no-pane");
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
if (!options.servers?.has(job.pane.server)) {
|
|
132
|
+
kept("server-unknown");
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
if (live.has(paneKey(job.pane))) {
|
|
136
|
+
kept("pane-alive");
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
const group = byPgid.get(job.pgid);
|
|
140
|
+
if (!group || group.length === 0) {
|
|
141
|
+
forget.push(job);
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
if (group.some(row => row.pid === self)) {
|
|
145
|
+
kept("self");
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
if (now - job.startedAt < leaseMs) {
|
|
149
|
+
kept("lease");
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
if (!group.some(row => commandMatches(job, row))) {
|
|
153
|
+
// The group id was reused by an unrelated program: the worker's group is
|
|
154
|
+
// gone and this record no longer describes anything safe to end.
|
|
155
|
+
if (now - job.startedAt > retainMs)
|
|
156
|
+
forget.push(job);
|
|
157
|
+
else
|
|
158
|
+
kept("reused");
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
// A group id is only reused once its group is empty. While the leader
|
|
162
|
+
// lives it must be the leader recorded with the pgid; a leader with no
|
|
163
|
+
// recorded start can't be told apart from a newcomer, so it is left alone.
|
|
164
|
+
// With the leader gone the group still holds its id, so it is the original.
|
|
165
|
+
const leader = group.find(row => row.pid === job.pgid);
|
|
166
|
+
if (leader && (job.leaderStartedAt === undefined || leader.startedAt === undefined
|
|
167
|
+
|| Math.abs(leader.startedAt - job.leaderStartedAt) > LEADER_START_TOLERANCE_MS)) {
|
|
168
|
+
if (now - job.startedAt > retainMs)
|
|
169
|
+
forget.push(job);
|
|
170
|
+
else
|
|
171
|
+
kept("leader-unverified");
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
kill.push(job);
|
|
175
|
+
}
|
|
176
|
+
return { kill, keep, forget };
|
|
177
|
+
}
|
|
178
|
+
/** The registry file: one JSON object, written atomically like the Hook's other state. */
|
|
179
|
+
const defaultFile = () => path.join(bridgeRoot(), "jobs.json");
|
|
180
|
+
/**
|
|
181
|
+
* The on-disk job registry. The Hook is the only writer, so the file is read
|
|
182
|
+
* whole; a damaged file reads as no jobs rather than failing a report.
|
|
183
|
+
*/
|
|
184
|
+
export class JobRegistry {
|
|
185
|
+
file;
|
|
186
|
+
now;
|
|
187
|
+
constructor(file = defaultFile(), now = Date.now) {
|
|
188
|
+
this.file = file;
|
|
189
|
+
this.now = now;
|
|
190
|
+
}
|
|
191
|
+
async list() {
|
|
192
|
+
try {
|
|
193
|
+
const parsed = stateSchema.safeParse(JSON.parse(readFileSync(this.file, "utf8")));
|
|
194
|
+
return parsed.success ? parsed.data.jobs : [];
|
|
195
|
+
}
|
|
196
|
+
catch {
|
|
197
|
+
return [];
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
async replace(jobs) {
|
|
201
|
+
await atomicInPrivateDir(this.file, JSON.stringify({ version: 1, jobs }, null, 2) + "\n");
|
|
202
|
+
}
|
|
203
|
+
/** Record (or refresh) one worker's job, keyed by its pane. */
|
|
204
|
+
async register(job) {
|
|
205
|
+
const entry = { ...job, startedAt: job.startedAt ?? this.now() };
|
|
206
|
+
const key = jobKey(entry);
|
|
207
|
+
const jobs = await this.list();
|
|
208
|
+
await this.replace([...jobs.filter(existing => jobKey(existing) !== key), entry].slice(-1024));
|
|
209
|
+
return entry;
|
|
210
|
+
}
|
|
211
|
+
/** Resolve process groups against the current table and persist any change. */
|
|
212
|
+
async reconcile(rows, owners) {
|
|
213
|
+
const jobs = await this.list();
|
|
214
|
+
const resolved = resolveJobGroups(jobs, rows, owners);
|
|
215
|
+
if (JSON.stringify(resolved) !== JSON.stringify(jobs))
|
|
216
|
+
await this.replace(resolved);
|
|
217
|
+
return resolved;
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* End every registered process group that is safe to end (`planCleanup`) and
|
|
221
|
+
* drop the records that are gone. `live` is the set of pane keys the caller
|
|
222
|
+
* still sees; a caller whose snapshot failed passes `panesKnown: false`, and
|
|
223
|
+
* nothing is ended.
|
|
224
|
+
*/
|
|
225
|
+
async cleanup(rows, live, options = {}) {
|
|
226
|
+
const jobs = options.owners ? await this.reconcile(rows, options.owners) : await this.list();
|
|
227
|
+
const plan = planCleanup(jobs, rows, live, { ...options, ...(options.now === undefined ? { now: this.now() } : {}) });
|
|
228
|
+
const signal = options.kill ?? ((pgid, value) => { process.kill(-pgid, value); });
|
|
229
|
+
const killed = [];
|
|
230
|
+
for (const job of plan.kill) {
|
|
231
|
+
try {
|
|
232
|
+
signal(job.pgid, "SIGTERM");
|
|
233
|
+
killed.push(job.pgid);
|
|
234
|
+
}
|
|
235
|
+
catch { /* Already gone between the plan and the signal. */ }
|
|
236
|
+
}
|
|
237
|
+
const done = new Set([...plan.forget, ...plan.kill].map(jobKey));
|
|
238
|
+
const remaining = jobs.filter(job => !done.has(jobKey(job)));
|
|
239
|
+
if (remaining.length !== jobs.length)
|
|
240
|
+
await this.replace(remaining);
|
|
241
|
+
return {
|
|
242
|
+
killed,
|
|
243
|
+
kept: plan.keep.map(({ job, reason }) => ({ ...(job.pgid !== undefined ? { pgid: job.pgid } : {}), reason })),
|
|
244
|
+
forgotten: plan.forget.flatMap(job => (job.pgid !== undefined ? [job.pgid] : [])),
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** Writing "Allow everywhere" for an OpenCode permission ask: the permission
|
|
2
|
+
* is answered with OpenCode's own `always` reply, which lasts only the running
|
|
3
|
+
* session, so the tool is also added to the user's OpenCode config as an
|
|
4
|
+
* allow rule. The config is read under a lock and rewritten through an atomic
|
|
5
|
+
* rename, so a concurrent OpenCode write is never clobbered and every other
|
|
6
|
+
* key is preserved. */
|
|
7
|
+
/** The OpenCode config `phren` edits: ~/.config/opencode/opencode.json. */
|
|
8
|
+
export declare function opencodeConfigPath(env?: NodeJS.ProcessEnv, home?: string): string;
|
|
9
|
+
/** A tool name OpenCode's `permission` block keys by. */
|
|
10
|
+
export declare function opencodeToolName(value: unknown): string | undefined;
|
|
11
|
+
/** The config with `permission[tool] = "allow"` added, every other key kept.
|
|
12
|
+
* A granular rule for the tool keeps its patterns: the allow becomes the
|
|
13
|
+
* catch-all `*` (specific rules after it still win, OpenCode's last-match rule). */
|
|
14
|
+
export declare function withAllowedTool(config: Record<string, unknown>, tool: string): Record<string, unknown>;
|
|
15
|
+
/** Add an allow rule for `tool` to the user's OpenCode config, under a lock
|
|
16
|
+
* with an atomic rename. */
|
|
17
|
+
export declare function allowOpencodeToolEverywhere(tool: unknown, file?: string): Promise<string>;
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { lstat, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { tryFileLock } from "../governance/locks.js";
|
|
5
|
+
import { homeDir } from "../home-paths.js";
|
|
6
|
+
import { BridgeError } from "./protocol.js";
|
|
7
|
+
/** Writing "Allow everywhere" for an OpenCode permission ask: the permission
|
|
8
|
+
* is answered with OpenCode's own `always` reply, which lasts only the running
|
|
9
|
+
* session, so the tool is also added to the user's OpenCode config as an
|
|
10
|
+
* allow rule. The config is read under a lock and rewritten through an atomic
|
|
11
|
+
* rename, so a concurrent OpenCode write is never clobbered and every other
|
|
12
|
+
* key is preserved. */
|
|
13
|
+
/** The OpenCode config `phren` edits: ~/.config/opencode/opencode.json. */
|
|
14
|
+
export function opencodeConfigPath(env = process.env, home = homeDir(env)) {
|
|
15
|
+
return path.join(env.XDG_CONFIG_HOME || path.join(home, ".config"), "opencode", "opencode.json");
|
|
16
|
+
}
|
|
17
|
+
/** A tool name OpenCode's `permission` block keys by. */
|
|
18
|
+
export function opencodeToolName(value) {
|
|
19
|
+
if (typeof value !== "string")
|
|
20
|
+
return undefined;
|
|
21
|
+
const name = value.trim().slice(0, 100);
|
|
22
|
+
return /^[A-Za-z0-9_*-]+$/.test(name) ? name : undefined;
|
|
23
|
+
}
|
|
24
|
+
async function readConfig(file) {
|
|
25
|
+
let text;
|
|
26
|
+
try {
|
|
27
|
+
text = await readFile(file, "utf8");
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
if (error.code === "ENOENT")
|
|
31
|
+
return {};
|
|
32
|
+
throw new BridgeError(409, "Could not read ~/.config/opencode/opencode.json.");
|
|
33
|
+
}
|
|
34
|
+
let parsed;
|
|
35
|
+
try {
|
|
36
|
+
parsed = JSON.parse(text);
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
throw new BridgeError(409, "~/.config/opencode/opencode.json is not valid JSON.");
|
|
40
|
+
}
|
|
41
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
42
|
+
throw new BridgeError(409, "~/.config/opencode/opencode.json is not a JSON object.");
|
|
43
|
+
return parsed;
|
|
44
|
+
}
|
|
45
|
+
/** The config with `permission[tool] = "allow"` added, every other key kept.
|
|
46
|
+
* A granular rule for the tool keeps its patterns: the allow becomes the
|
|
47
|
+
* catch-all `*` (specific rules after it still win, OpenCode's last-match rule). */
|
|
48
|
+
export function withAllowedTool(config, tool) {
|
|
49
|
+
const permission = config.permission;
|
|
50
|
+
if (permission === undefined)
|
|
51
|
+
return { ...config, permission: { [tool]: "allow" } };
|
|
52
|
+
// The whole-block string form ("allow") applies to every tool: keep it as
|
|
53
|
+
// the `*` entry so adding one tool never drops that choice.
|
|
54
|
+
if (typeof permission === "string")
|
|
55
|
+
return { ...config, permission: { "*": permission, [tool]: "allow" } };
|
|
56
|
+
if (!permission || typeof permission !== "object" || Array.isArray(permission)) {
|
|
57
|
+
throw new BridgeError(409, "The opencode permission block is not a JSON object.");
|
|
58
|
+
}
|
|
59
|
+
const block = { ...permission };
|
|
60
|
+
const existing = block[tool];
|
|
61
|
+
if (existing && typeof existing === "object" && !Array.isArray(existing)) {
|
|
62
|
+
const merged = { "*": "allow", ...existing };
|
|
63
|
+
merged["*"] = "allow";
|
|
64
|
+
block[tool] = merged;
|
|
65
|
+
}
|
|
66
|
+
else
|
|
67
|
+
block[tool] = "allow";
|
|
68
|
+
return { ...config, permission: block };
|
|
69
|
+
}
|
|
70
|
+
/** Add an allow rule for `tool` to the user's OpenCode config, under a lock
|
|
71
|
+
* with an atomic rename. */
|
|
72
|
+
export async function allowOpencodeToolEverywhere(tool, file = opencodeConfigPath()) {
|
|
73
|
+
const name = opencodeToolName(tool);
|
|
74
|
+
if (!name)
|
|
75
|
+
throw new BridgeError(400, "OpenCode did not name a tool this can allow.");
|
|
76
|
+
const release = tryFileLock(file);
|
|
77
|
+
if (!release)
|
|
78
|
+
throw new BridgeError(409, "~/.config/opencode/opencode.json is being updated. Try again.");
|
|
79
|
+
try {
|
|
80
|
+
const config = withAllowedTool(await readConfig(file), name);
|
|
81
|
+
const mode = (await lstat(file).catch(() => undefined))?.mode;
|
|
82
|
+
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
83
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
84
|
+
await writeFile(temporary, `${JSON.stringify(config, null, 2)}\n`, { mode: mode === undefined ? 0o600 : mode & 0o777, flag: "wx" });
|
|
85
|
+
try {
|
|
86
|
+
await rename(temporary, file);
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
await unlink(temporary).catch(() => { });
|
|
90
|
+
}
|
|
91
|
+
return name;
|
|
92
|
+
}
|
|
93
|
+
finally {
|
|
94
|
+
release();
|
|
95
|
+
}
|
|
96
|
+
}
|
|
@@ -45,6 +45,10 @@ export declare const startingTargetSchema: z.ZodObject<{
|
|
|
45
45
|
}, z.core.$strip>;
|
|
46
46
|
export type StartingTarget = z.infer<typeof startingTargetSchema>;
|
|
47
47
|
export type Json = Record<string, unknown>;
|
|
48
|
+
/** The decisions an approval answer may carry. An OpenCode permission ask
|
|
49
|
+
* accepts both grant scopes; every other provider approves or denies only. */
|
|
50
|
+
export declare const approvalDecisions: readonly ["approve", "deny", "allow-project", "allow-everywhere"];
|
|
51
|
+
export type ApprovalDecision = typeof approvalDecisions[number];
|
|
48
52
|
/** `value` when it is a plain object, else an empty one. */
|
|
49
53
|
export declare function object(value: unknown): Json;
|
|
50
54
|
export declare function objects(value: unknown): Json[];
|
package/dist/bridge/protocol.js
CHANGED
|
@@ -27,6 +27,9 @@ export const targetSchema = z.object({
|
|
|
27
27
|
export const startingTargetSchema = targetSchema.omit({ session: true }).extend({
|
|
28
28
|
starting: z.literal(true), startingToken: z.string().regex(/^[a-f0-9]{64}$/),
|
|
29
29
|
});
|
|
30
|
+
/** The decisions an approval answer may carry. An OpenCode permission ask
|
|
31
|
+
* accepts both grant scopes; every other provider approves or denies only. */
|
|
32
|
+
export const approvalDecisions = ["approve", "deny", "allow-project", "allow-everywhere"];
|
|
30
33
|
/** `value` when it is a plain object, else an empty one. */
|
|
31
34
|
export function object(value) { return isRecord(value) ? value : {}; }
|
|
32
35
|
export function objects(value) { return Array.isArray(value) ? value.map(object) : []; }
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type CleanupReport, type JobSource, type ProcessLike, type TrackedJob } from "./job-registry.js";
|
|
1
2
|
/**
|
|
2
3
|
* This computer's live resources for `GET /v1/resources`, the overview
|
|
3
4
|
* stream's `resources` frames and the memory-free `phren computers` surface:
|
|
@@ -29,6 +30,10 @@ export interface HeavyProcess {
|
|
|
29
30
|
memoryBytes: number;
|
|
30
31
|
/** Why this process group is listed; resource use does not establish session activity. */
|
|
31
32
|
resourceReason?: "cpu" | "memory" | "tracked";
|
|
33
|
+
/** The harness that owns the job, when a pane or a registered group says so. */
|
|
34
|
+
agent?: string;
|
|
35
|
+
/** True when the group is one the Hook registered for a dispatched worker. */
|
|
36
|
+
tracked?: boolean;
|
|
32
37
|
pane?: PaneRef;
|
|
33
38
|
}
|
|
34
39
|
export interface ComputerResources {
|
|
@@ -69,15 +74,15 @@ export interface ComputerResources {
|
|
|
69
74
|
level: "ok" | "busy" | "stressed";
|
|
70
75
|
warnings: Array<"load-high" | "memory-low" | "disk-low" | "battery-low">;
|
|
71
76
|
}
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
ppid: number;
|
|
77
|
+
/** A `ps` row; `pgid` is the process group the job registry attributes work by. */
|
|
78
|
+
export interface ProcessRow extends ProcessLike {
|
|
75
79
|
cpu: number;
|
|
76
80
|
rssKB: number;
|
|
77
81
|
command: string;
|
|
78
82
|
args: string;
|
|
79
83
|
}
|
|
80
|
-
/** `ps -axo pid=,ppid=,pcpu=,rss=,comm=` paired with the `args=` listing by
|
|
84
|
+
/** `ps -axo pid=,ppid=,pgid=,pcpu=,rss=,comm=` paired with the `args=` listing by
|
|
85
|
+
* pid. The older five-column stats (no pgid) still parse, with pgid 0. */
|
|
81
86
|
export declare function parsePs(stats: string, args: string): ProcessRow[];
|
|
82
87
|
/** What kind of heavy job a process is, if any. */
|
|
83
88
|
export declare function heavyKind(row: ProcessRow): {
|
|
@@ -95,7 +100,7 @@ export declare function heavyKind(row: ProcessRow): {
|
|
|
95
100
|
* On Linux, ps pcpu is a process lifetime average, so these cutoffs can miss
|
|
96
101
|
* daemons that spike briefly.
|
|
97
102
|
*/
|
|
98
|
-
export declare function heavyProcesses(rows: ProcessRow[], owners?: Map<number, PaneRef>, limit?: number): HeavyProcess[];
|
|
103
|
+
export declare function heavyProcesses(rows: ProcessRow[], owners?: Map<number, PaneRef>, jobs?: readonly TrackedJob[], limit?: number): HeavyProcess[];
|
|
99
104
|
/** `pmset -g batt`: "Now drawing from 'AC Power'" then " -InternalBattery-0 (id=…) 87%; charging; …". */
|
|
100
105
|
export declare function parsePmset(output: string): ComputerResources["battery"];
|
|
101
106
|
/** `sysctl vm.swapusage`: "total = 2048.00M used = 798.50M free = …". */
|
|
@@ -104,6 +109,20 @@ export declare function parseSwap(output: string): number | undefined;
|
|
|
104
109
|
export declare function parseMeminfo(text: string): ComputerResources["memory"];
|
|
105
110
|
/** Gauge fill and warnings from the numbers. */
|
|
106
111
|
export declare function assess(value: Omit<ComputerResources, "pressure" | "level" | "warnings">): Pick<ComputerResources, "pressure" | "level" | "warnings">;
|
|
112
|
+
/** Seconds from `ps`'s `etime` (`[[dd-]hh:]mm:ss`), or undefined. */
|
|
113
|
+
export declare function parseEtime(value: string): number | undefined;
|
|
114
|
+
/** Each row's start time (epoch ms, to about a second) from a `pid=,etime=`
|
|
115
|
+
* listing. The job registry checks a process group's leader by it, so a group
|
|
116
|
+
* id the system reused for another program is never signalled. */
|
|
117
|
+
export declare function withStartTimes(rows: ProcessRow[], elapsed: string, now: number): ProcessRow[];
|
|
118
|
+
/** Every pane of every terminal server this computer knows, or undefined when
|
|
119
|
+
* any server's snapshot could not be read. Cleanup ends a job only when its
|
|
120
|
+
* pane is missing from a complete listing: a pane that merely failed to
|
|
121
|
+
* answer, or sat past a display cap, must never look gone. */
|
|
122
|
+
export declare function livePanes(): Promise<{
|
|
123
|
+
panes: Set<string>;
|
|
124
|
+
servers: Set<string>;
|
|
125
|
+
} | undefined>;
|
|
107
126
|
/** Every pid a Herdr or tmux pane holds (its shell and foreground), for naming a job's pane. */
|
|
108
127
|
export declare function paneOwners(): Promise<Map<number, PaneRef>>;
|
|
109
128
|
export interface ResourceDeps {
|
|
@@ -112,6 +131,12 @@ export interface ResourceDeps {
|
|
|
112
131
|
home: () => string;
|
|
113
132
|
processes: () => Promise<ProcessRow[]>;
|
|
114
133
|
owners: () => Promise<Map<number, PaneRef>>;
|
|
134
|
+
/** Every live pane and the servers listed, or undefined when the listing is incomplete (see `livePanes`). */
|
|
135
|
+
panes: () => Promise<{
|
|
136
|
+
panes: Set<string>;
|
|
137
|
+
servers: Set<string>;
|
|
138
|
+
} | undefined>;
|
|
139
|
+
jobs?: JobSource;
|
|
115
140
|
}
|
|
116
141
|
export declare function collectResources(deps: ResourceDeps): Promise<ComputerResources>;
|
|
117
142
|
/** One collection at a time, reused for `RESOURCES_MAX_AGE_MS`. */
|
|
@@ -120,6 +145,14 @@ export declare class ResourceMonitor {
|
|
|
120
145
|
private cached?;
|
|
121
146
|
private pending?;
|
|
122
147
|
private readonly deps;
|
|
148
|
+
private readonly registry;
|
|
123
149
|
constructor(deps?: Partial<ResourceDeps>, maxAgeMs?: number);
|
|
124
150
|
read(): Promise<ComputerResources>;
|
|
151
|
+
/**
|
|
152
|
+
* End only the registered process groups whose owning pane is gone. The
|
|
153
|
+
* registry (job-registry.ts) does the safety checks; a failed pane read ends
|
|
154
|
+
* nothing. Never the Hook's own service, never an owner's session, never an
|
|
155
|
+
* unregistered process.
|
|
156
|
+
*/
|
|
157
|
+
cleanupJobs(): Promise<CleanupReport>;
|
|
125
158
|
}
|