@phren/cli 0.3.16 → 0.3.18
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/permission-mode.d.ts +48 -0
- package/dist/bridge/permission-mode.js +144 -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-pane-routes.d.ts +2 -0
- package/dist/bridge/server-pane-routes.js +12 -2
- package/dist/bridge/server-routes.d.ts +3 -1
- package/dist/bridge/server-routes.js +8 -6
- package/dist/bridge/server-stream.js +14 -2
- package/dist/bridge/server.js +4 -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 +19 -7
- package/dist/bridge/settings-switch.js +21 -29
- 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 +1169 -546
- 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 +2 -2
- 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
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { AgentHooks } from "./agent-hooks.js";
|
|
2
|
+
import { type Json, type Target } from "./protocol.js";
|
|
3
|
+
/** An agent's permission mode as its own footer names it, and the route that
|
|
4
|
+
* changes it by pressing Shift+Tab through the harness's cycle. The phone's
|
|
5
|
+
* mode picker reads `agentStatus.permissionMode` / `permissionModes` off the
|
|
6
|
+
* chat status stream and posts one back here. Only Claude Code draws the mode
|
|
7
|
+
* in its footer; Codex and OpenCode keep theirs in config, so they offer none. */
|
|
8
|
+
/** Claude Code's `permissionMode` values in Shift+Tab cycle order. "default" is
|
|
9
|
+
* the footer's "manual mode on"; "auto" is "auto mode on". */
|
|
10
|
+
export declare const PERMISSION_CYCLE: readonly ["default", "acceptEdits", "plan", "auto"];
|
|
11
|
+
/** `bypassPermissions` is in the cycle only for a session launched allowing
|
|
12
|
+
* bypass, so it is a valid mode but not part of the standard list. */
|
|
13
|
+
export declare const PERMISSION_MODE_VALUES: readonly ["default", "acceptEdits", "plan", "auto", "bypassPermissions"];
|
|
14
|
+
export type PermissionModeName = (typeof PERMISSION_MODE_VALUES)[number];
|
|
15
|
+
/** The modes a Claude pane offers, in Shift+Tab cycle order. `bypass` adds the
|
|
16
|
+
* one only a session launched with --allow-dangerously-skip-permissions has. */
|
|
17
|
+
export declare function permissionModes(bypass: boolean): PermissionModeName[];
|
|
18
|
+
/** Claude's permission mode from the footer line its TUI draws under the
|
|
19
|
+
* composer. The transcript lags it: a `permission-mode` row is written only
|
|
20
|
+
* when a prompt is submitted, and a fresh session has no file yet. The line may
|
|
21
|
+
* trail hints ("(shift+tab to cycle) · 1 agent"), so only its start counts. A
|
|
22
|
+
* mode the footer does not mark is `undefined`: "manual mode on" is default. */
|
|
23
|
+
export declare function claudeFooterMode(screen: string): PermissionModeName | undefined;
|
|
24
|
+
/** Only the owner changes a session's permission mode, from the phone. An
|
|
25
|
+
* agent's call names its own pane (`origin`), and none is accepted: an agent
|
|
26
|
+
* could otherwise lift itself or another pane past the per-grant
|
|
27
|
+
* `maxPermissionMode` ceiling, up to bypassPermissions. Same rule as
|
|
28
|
+
* `/v1/sudo/answer`. */
|
|
29
|
+
export declare function refuseAgentOrigin(actor: unknown): void;
|
|
30
|
+
/** One Shift+Tab transaction per pane owns its terminal input until it ends,
|
|
31
|
+
* like the settings switcher, so a mode change and a settings change never
|
|
32
|
+
* press into the same composer at once. */
|
|
33
|
+
export declare class PermissionModeSwitcher {
|
|
34
|
+
private readonly hooks;
|
|
35
|
+
private readonly wait;
|
|
36
|
+
private active;
|
|
37
|
+
constructor(hooks: AgentHooks, wait?: number);
|
|
38
|
+
private key;
|
|
39
|
+
assertAvailable(target: Target): void;
|
|
40
|
+
/** Steps the pane to `mode`, or refuses. Only Claude offers the cycle; the
|
|
41
|
+
* machine's authority policy never caps an owner's own choice. */
|
|
42
|
+
set(target: Target, mode: PermissionModeName, actor?: unknown): Promise<Json>;
|
|
43
|
+
private cycle;
|
|
44
|
+
/** The mode after a press: polled from the screen until it differs from
|
|
45
|
+
* `from`, because the TUI redraws the footer asynchronously. */
|
|
46
|
+
private changed;
|
|
47
|
+
private assertLive;
|
|
48
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { stripTerminal } from "../terminal-text.js";
|
|
2
|
+
import { validateTarget } from "./herdr.js";
|
|
3
|
+
import { BridgeError } from "./protocol.js";
|
|
4
|
+
import { terminalProvider } from "./terminal.js";
|
|
5
|
+
import { visibleTerminalChoice } from "./terminal-choice.js";
|
|
6
|
+
/** An agent's permission mode as its own footer names it, and the route that
|
|
7
|
+
* changes it by pressing Shift+Tab through the harness's cycle. The phone's
|
|
8
|
+
* mode picker reads `agentStatus.permissionMode` / `permissionModes` off the
|
|
9
|
+
* chat status stream and posts one back here. Only Claude Code draws the mode
|
|
10
|
+
* in its footer; Codex and OpenCode keep theirs in config, so they offer none. */
|
|
11
|
+
/** Claude Code's `permissionMode` values in Shift+Tab cycle order. "default" is
|
|
12
|
+
* the footer's "manual mode on"; "auto" is "auto mode on". */
|
|
13
|
+
export const PERMISSION_CYCLE = ["default", "acceptEdits", "plan", "auto"];
|
|
14
|
+
/** `bypassPermissions` is in the cycle only for a session launched allowing
|
|
15
|
+
* bypass, so it is a valid mode but not part of the standard list. */
|
|
16
|
+
export const PERMISSION_MODE_VALUES = [...PERMISSION_CYCLE, "bypassPermissions"];
|
|
17
|
+
/** The modes a Claude pane offers, in Shift+Tab cycle order. `bypass` adds the
|
|
18
|
+
* one only a session launched with --allow-dangerously-skip-permissions has. */
|
|
19
|
+
export function permissionModes(bypass) {
|
|
20
|
+
return [...PERMISSION_CYCLE, ...(bypass ? ["bypassPermissions"] : [])];
|
|
21
|
+
}
|
|
22
|
+
/** Claude's permission mode from the footer line its TUI draws under the
|
|
23
|
+
* composer. The transcript lags it: a `permission-mode` row is written only
|
|
24
|
+
* when a prompt is submitted, and a fresh session has no file yet. The line may
|
|
25
|
+
* trail hints ("(shift+tab to cycle) · 1 agent"), so only its start counts. A
|
|
26
|
+
* mode the footer does not mark is `undefined`: "manual mode on" is default. */
|
|
27
|
+
export function claudeFooterMode(screen) {
|
|
28
|
+
for (const line of stripTerminal(screen).split(/\r?\n/).map(line => line.trim()).filter(Boolean).slice(-8).reverse()) {
|
|
29
|
+
const text = line.replace(/^[⏵⏸]+\s*/, "");
|
|
30
|
+
if (text === line)
|
|
31
|
+
continue;
|
|
32
|
+
if (/bypass permissions on/i.test(text))
|
|
33
|
+
return "bypassPermissions";
|
|
34
|
+
if (/^manual mode on\b/i.test(text))
|
|
35
|
+
return "default";
|
|
36
|
+
if (/^accept edits on\b/i.test(text))
|
|
37
|
+
return "acceptEdits";
|
|
38
|
+
if (/^plan mode on\b/i.test(text))
|
|
39
|
+
return "plan";
|
|
40
|
+
if (/^auto mode on\b/i.test(text))
|
|
41
|
+
return "auto";
|
|
42
|
+
}
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
/** Only the owner changes a session's permission mode, from the phone. An
|
|
46
|
+
* agent's call names its own pane (`origin`), and none is accepted: an agent
|
|
47
|
+
* could otherwise lift itself or another pane past the per-grant
|
|
48
|
+
* `maxPermissionMode` ceiling, up to bypassPermissions. Same rule as
|
|
49
|
+
* `/v1/sudo/answer`. */
|
|
50
|
+
export function refuseAgentOrigin(actor) {
|
|
51
|
+
if (actor !== undefined)
|
|
52
|
+
throw new BridgeError(403, "Only the owner changes a session's permission mode, from the phone.");
|
|
53
|
+
}
|
|
54
|
+
/** Who chose the mode, for the reply: always the owner (see `refuseAgentOrigin`). */
|
|
55
|
+
function attribution() {
|
|
56
|
+
return { setBy: "owner" };
|
|
57
|
+
}
|
|
58
|
+
const STEP_WAIT_MS = 2_000, POLL_MS = 100;
|
|
59
|
+
/** One Shift+Tab transaction per pane owns its terminal input until it ends,
|
|
60
|
+
* like the settings switcher, so a mode change and a settings change never
|
|
61
|
+
* press into the same composer at once. */
|
|
62
|
+
export class PermissionModeSwitcher {
|
|
63
|
+
hooks;
|
|
64
|
+
wait;
|
|
65
|
+
active = new Set();
|
|
66
|
+
constructor(hooks, wait = STEP_WAIT_MS) {
|
|
67
|
+
this.hooks = hooks;
|
|
68
|
+
this.wait = wait;
|
|
69
|
+
}
|
|
70
|
+
key(target) { return `${target.server}:${target.pane}`; }
|
|
71
|
+
assertAvailable(target) {
|
|
72
|
+
if (this.active.has(this.key(target)))
|
|
73
|
+
throw new BridgeError(409, "A permission-mode change is already in progress. Wait for it to finish.");
|
|
74
|
+
}
|
|
75
|
+
/** Steps the pane to `mode`, or refuses. Only Claude offers the cycle; the
|
|
76
|
+
* machine's authority policy never caps an owner's own choice. */
|
|
77
|
+
async set(target, mode, actor) {
|
|
78
|
+
refuseAgentOrigin(actor);
|
|
79
|
+
this.assertAvailable(target);
|
|
80
|
+
if (target.source !== "claude")
|
|
81
|
+
throw new BridgeError(422, "Changing the permission mode is not supported for this harness. Open terminal to change it.");
|
|
82
|
+
this.active.add(this.key(target));
|
|
83
|
+
try {
|
|
84
|
+
return await this.cycle(target, mode, actor);
|
|
85
|
+
}
|
|
86
|
+
finally {
|
|
87
|
+
this.active.delete(this.key(target));
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
async cycle(target, mode, actor) {
|
|
91
|
+
const first = await validateTarget(target, false, true);
|
|
92
|
+
const terminal = first.terminal_id, status = String(first.agent_status);
|
|
93
|
+
// Shift+Tab is the composer's key: a turn or a dialog would take it first.
|
|
94
|
+
if (status === "working")
|
|
95
|
+
throw new BridgeError(409, "This agent is mid-turn. Permission changes happen between turns; choose the mode again when the turn ends.");
|
|
96
|
+
const screen = await this.hooks.paneAnsi(target).catch(() => undefined);
|
|
97
|
+
if (screen === undefined)
|
|
98
|
+
throw new BridgeError(409, "Could not read Claude's permission mode from its screen. Open terminal to check.");
|
|
99
|
+
if (status === "blocked" || status === "waiting" || this.hooks.approval(target) || this.hooks.terminalPrompt(target)
|
|
100
|
+
|| visibleTerminalChoice(stripTerminal(screen))) {
|
|
101
|
+
throw new BridgeError(409, "A permission prompt or dialog is open. Answer it before changing the permission mode.");
|
|
102
|
+
}
|
|
103
|
+
let current = claudeFooterMode(screen);
|
|
104
|
+
if (!current)
|
|
105
|
+
throw new BridgeError(409, "Could not read Claude's permission mode from its screen. Open terminal to check.");
|
|
106
|
+
if (current === mode)
|
|
107
|
+
return { ok: true, permissionMode: current, ...attribution() };
|
|
108
|
+
// Shift+Tab steps through the modes this session offers. A full lap back to
|
|
109
|
+
// the start (one more press than the cycle holds) means it does not offer
|
|
110
|
+
// the one asked for. The bound grows if the cycle turns out to include one
|
|
111
|
+
// more mode than the standard list (bypass).
|
|
112
|
+
const modes = new Set(PERMISSION_CYCLE);
|
|
113
|
+
for (let presses = 0;; presses++) {
|
|
114
|
+
if (presses >= modes.size + 1)
|
|
115
|
+
throw new BridgeError(422, `Claude doesn't offer ${mode} in this session.`, { permissionMode: current });
|
|
116
|
+
await this.assertLive(target, terminal);
|
|
117
|
+
await terminalProvider().sendKeys(target.server, target.pane, ["shift+tab"]);
|
|
118
|
+
current = await this.changed(target, terminal, current);
|
|
119
|
+
modes.add(current);
|
|
120
|
+
if (current === mode)
|
|
121
|
+
return { ok: true, permissionMode: current, ...attribution() };
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/** The mode after a press: polled from the screen until it differs from
|
|
125
|
+
* `from`, because the TUI redraws the footer asynchronously. */
|
|
126
|
+
async changed(target, terminal, from) {
|
|
127
|
+
const deadline = Date.now() + this.wait;
|
|
128
|
+
do {
|
|
129
|
+
await new Promise(resolve => setTimeout(resolve, POLL_MS));
|
|
130
|
+
await this.assertLive(target, terminal);
|
|
131
|
+
const mode = claudeFooterMode(await this.hooks.paneAnsi(target).catch(() => ""));
|
|
132
|
+
if (mode && mode !== from)
|
|
133
|
+
return mode;
|
|
134
|
+
} while (Date.now() < deadline);
|
|
135
|
+
throw new BridgeError(409, "Could not verify Claude's permission mode. Open terminal to check it.");
|
|
136
|
+
}
|
|
137
|
+
async assertLive(target, terminal) {
|
|
138
|
+
const pane = await validateTarget(target, false, true);
|
|
139
|
+
if (pane.terminal_id !== terminal)
|
|
140
|
+
throw new BridgeError(409, "The terminal changed during the permission-mode change.");
|
|
141
|
+
if (pane.agent_status === "working")
|
|
142
|
+
throw new BridgeError(409, "The agent started working during the permission-mode change. The result is unconfirmed; check the terminal.");
|
|
143
|
+
}
|
|
144
|
+
}
|
|
@@ -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) : []; }
|