@phren/cli 0.3.50 → 0.3.52
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/computers.js +5 -4
- package/dist/bridge/conductor-role.d.ts +4 -0
- package/dist/bridge/conductor-role.js +20 -1
- package/dist/bridge/dispatch-origins.d.ts +32 -0
- package/dist/bridge/dispatch-origins.js +44 -0
- package/dist/bridge/dispatch-returns.d.ts +2 -1
- package/dist/bridge/dispatch-returns.js +9 -2
- package/dist/bridge/dispatch.d.ts +5 -0
- package/dist/bridge/dispatch.js +119 -23
- package/dist/bridge/gitboy-webhooks.d.ts +25 -0
- package/dist/bridge/gitboy-webhooks.js +200 -0
- package/dist/bridge/hand-off.d.ts +1 -0
- package/dist/bridge/hand-off.js +1 -1
- package/dist/bridge/install.d.ts +1 -0
- package/dist/bridge/install.js +7 -0
- package/dist/bridge/request-origin.d.ts +6 -0
- package/dist/bridge/request-origin.js +6 -0
- package/dist/bridge/scoped-gateway.d.ts +3 -0
- package/dist/bridge/scoped-gateway.js +22 -4
- package/dist/bridge/server-routes.d.ts +5 -0
- package/dist/bridge/server-routes.js +18 -3
- package/dist/bridge/server.js +7 -2
- package/dist/bridge/session-move.d.ts +10 -2
- package/dist/bridge/session-move.js +124 -12
- package/dist/bridge/store-pull.d.ts +22 -0
- package/dist/bridge/store-pull.js +62 -0
- package/dist/bridge-hook.mjs +3380 -2519
- package/dist/modules/registry.js +3 -3
- package/dist/sync/gitboy-webhook.d.ts +43 -0
- package/dist/sync/gitboy-webhook.js +119 -0
- package/dist/sync/pull-now.d.ts +11 -0
- package/dist/sync/pull-now.js +64 -0
- package/dist/sync/pull.d.ts +1 -1
- package/dist/sync/pull.js +4 -4
- package/dist/tools/dispatch.js +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { lstat, readFile } from "node:fs/promises";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { createServer } from "node:http";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { DeliveryLog, parseGitboyPush, storePushMatches, verifyGitboySignature } from "../sync/gitboy-webhook.js";
|
|
7
|
+
import { optionalHookPeers, peerRequest } from "./peers.js";
|
|
8
|
+
const storeSchema = z.object({
|
|
9
|
+
storeId: z.string().min(1).max(128), owner: z.string().min(1).max(256), name: z.string().min(1).max(256),
|
|
10
|
+
branch: z.string().min(1).max(1024), secret: z.string().min(1).max(4096).optional(), secretFile: z.string().min(1).optional(),
|
|
11
|
+
}).strict().refine(store => Boolean(store.secret) !== Boolean(store.secretFile));
|
|
12
|
+
const configSchema = z.object({ listenPort: z.number().int().min(1).max(65535), stores: z.array(storeSchema).min(1).max(64) }).strict();
|
|
13
|
+
async function privateText(file, cap) {
|
|
14
|
+
const info = await lstat(file);
|
|
15
|
+
// POSIX permission bits carry no meaning on Windows (ACLs); there only file type and size are checked.
|
|
16
|
+
if (!info.isFile() || info.isSymbolicLink() || info.size > cap || (process.platform !== "win32" && (info.mode & 0o077))
|
|
17
|
+
|| (process.getuid && info.uid !== process.getuid()))
|
|
18
|
+
throw new Error("Unsafe private webhook file.");
|
|
19
|
+
return readFile(file, "utf8");
|
|
20
|
+
}
|
|
21
|
+
const BODY_CAP = 1024 * 1024;
|
|
22
|
+
function readBody(request) {
|
|
23
|
+
return new Promise((resolve, reject) => {
|
|
24
|
+
const chunks = [];
|
|
25
|
+
let size = 0;
|
|
26
|
+
const cleanup = () => { clearTimeout(timer); request.off("data", data); request.off("end", end); request.off("error", error); request.off("aborted", aborted); };
|
|
27
|
+
const fail = (status) => { cleanup(); request.resume(); reject(status); };
|
|
28
|
+
const data = (chunk) => { size += chunk.length; if (size > BODY_CAP)
|
|
29
|
+
fail(413);
|
|
30
|
+
else
|
|
31
|
+
chunks.push(chunk); };
|
|
32
|
+
const end = () => { cleanup(); resolve(Buffer.concat(chunks)); };
|
|
33
|
+
const error = () => fail(400);
|
|
34
|
+
const aborted = () => fail(400);
|
|
35
|
+
const timer = setTimeout(() => fail(408), 5000);
|
|
36
|
+
request.on("data", data);
|
|
37
|
+
request.once("end", end);
|
|
38
|
+
request.once("error", error);
|
|
39
|
+
request.once("aborted", aborted);
|
|
40
|
+
if (Number(request.headers["content-length"]) > BODY_CAP)
|
|
41
|
+
fail(413);
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
/** All peers come from the private, verified directory; peerRequest pins SSH host keys. */
|
|
45
|
+
async function nudgePeers(identity) {
|
|
46
|
+
const { peers } = await optionalHookPeers();
|
|
47
|
+
await Promise.allSettled(peers.map(peer => peerRequest(peer, "/v1/store/pull-now", { ...identity }, 15_000)));
|
|
48
|
+
}
|
|
49
|
+
/** Optional private HTTP ingress. Invalid config disables only this listener, never the Hook. */
|
|
50
|
+
export class GitboyWebhooks {
|
|
51
|
+
root;
|
|
52
|
+
pull;
|
|
53
|
+
nudge;
|
|
54
|
+
status = { configured: false, listening: false };
|
|
55
|
+
server;
|
|
56
|
+
deliveries = new DeliveryLog();
|
|
57
|
+
bodies = new DeliveryLog();
|
|
58
|
+
nudges = new Map();
|
|
59
|
+
closed = false;
|
|
60
|
+
constructor(root, pull, nudge = nudgePeers) {
|
|
61
|
+
this.root = root;
|
|
62
|
+
this.pull = pull;
|
|
63
|
+
this.nudge = nudge;
|
|
64
|
+
}
|
|
65
|
+
notify(store) {
|
|
66
|
+
// Configuration may name a local attachment. Only the ID carried by that store is portable.
|
|
67
|
+
let storeId = store.storeId;
|
|
68
|
+
try {
|
|
69
|
+
storeId = this.pull(storeId) ?? storeId;
|
|
70
|
+
}
|
|
71
|
+
catch { /* Peers may still have the configured portable ID. */ }
|
|
72
|
+
const identity = { storeId, repository: `${store.owner}/${store.name}`.toLowerCase(), branch: store.branch };
|
|
73
|
+
let state = this.nudges.get(storeId);
|
|
74
|
+
if (!state) {
|
|
75
|
+
state = { running: false, pending: false, last: -Infinity, identity };
|
|
76
|
+
this.nudges.set(storeId, state);
|
|
77
|
+
}
|
|
78
|
+
state.identity = identity;
|
|
79
|
+
state.pending = true;
|
|
80
|
+
const schedule = () => {
|
|
81
|
+
if (state.running || state.timer || this.closed)
|
|
82
|
+
return;
|
|
83
|
+
state.timer = setTimeout(() => {
|
|
84
|
+
state.timer = undefined;
|
|
85
|
+
if (this.closed)
|
|
86
|
+
return;
|
|
87
|
+
state.pending = false;
|
|
88
|
+
state.running = true;
|
|
89
|
+
state.last = Date.now();
|
|
90
|
+
void this.nudge(state.identity).catch(() => { }).finally(() => {
|
|
91
|
+
state.running = false;
|
|
92
|
+
if (state.pending)
|
|
93
|
+
schedule();
|
|
94
|
+
});
|
|
95
|
+
}, Math.max(0, state.last + 10_000 - Date.now()));
|
|
96
|
+
state.timer.unref();
|
|
97
|
+
};
|
|
98
|
+
schedule();
|
|
99
|
+
}
|
|
100
|
+
async start() {
|
|
101
|
+
const file = path.join(this.root, "gitboy-webhooks.json");
|
|
102
|
+
try {
|
|
103
|
+
await lstat(file);
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
if (error.code === "ENOENT")
|
|
107
|
+
return;
|
|
108
|
+
this.status.problem = "Webhook config unavailable.";
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
this.status.configured = true;
|
|
112
|
+
try {
|
|
113
|
+
const config = configSchema.parse(JSON.parse(await privateText(file, 65_536)));
|
|
114
|
+
const stores = await Promise.all(config.stores.map(async (store) => ({ ...store,
|
|
115
|
+
secret: store.secret ?? (await privateText(path.resolve(this.root, store.secretFile), 4096)).trim(),
|
|
116
|
+
})));
|
|
117
|
+
if (stores.some(store => !store.secret))
|
|
118
|
+
throw new Error("Empty secret.");
|
|
119
|
+
const server = createServer({ maxHeaderSize: 16_384 }, (request, response) => {
|
|
120
|
+
const reply = (status, outcome) => {
|
|
121
|
+
this.status.lastDeliveryAt = new Date().toISOString();
|
|
122
|
+
this.status.lastOutcome = outcome;
|
|
123
|
+
response.writeHead(status, { "Connection": "close", "Cache-Control": "no-store" });
|
|
124
|
+
response.end();
|
|
125
|
+
};
|
|
126
|
+
void (async () => {
|
|
127
|
+
if (request.method !== "POST" || request.url !== "/gitboy/push") {
|
|
128
|
+
reply(404, "not-found");
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
if (![`127.0.0.1:${config.listenPort}`, `localhost:${config.listenPort}`].includes(request.headers.host ?? "")
|
|
132
|
+
|| request.headers.origin !== undefined || Object.keys(request.headers).some(name => name.startsWith("sec-fetch-"))) {
|
|
133
|
+
reply(403, "browser-refused");
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
if (!/^application\/json(?:\s*;.*)?$/i.test(request.headers["content-type"] ?? "")) {
|
|
137
|
+
reply(415, "content-type-refused");
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
const raw = await readBody(request);
|
|
141
|
+
const signature = request.headers["x-hub-signature-256"];
|
|
142
|
+
// Authenticate the raw bytes against EVERY secret before parsing or traversing the payload.
|
|
143
|
+
const verified = stores.filter(store => verifyGitboySignature(store.secret, raw, typeof signature === "string" ? signature : undefined));
|
|
144
|
+
if (!verified.length) {
|
|
145
|
+
reply(401, "unauthorized");
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
const push = parseGitboyPush(raw, request.headers);
|
|
149
|
+
if (!push?.repository) {
|
|
150
|
+
reply(400, "malformed");
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
const candidates = verified.filter(store => store.owner.toLowerCase() === push.repository.owner.toLowerCase()
|
|
154
|
+
&& store.name.toLowerCase() === push.repository.name.toLowerCase());
|
|
155
|
+
if (!candidates.length) {
|
|
156
|
+
reply(401, "unauthorized");
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
const repo = push.repository;
|
|
160
|
+
const duplicateId = this.deliveries.seen(JSON.stringify([repo.owner.toLowerCase(), repo.name.toLowerCase(), push.deliveryId]));
|
|
161
|
+
// Per verified store set: the same body signed with another stores secret is that stores delivery.
|
|
162
|
+
const storeKey = candidates.map(store => store.storeId).sort().join("\u0000");
|
|
163
|
+
const duplicateBody = this.bodies.seen(`${storeKey}\u0000${createHash("sha256").update(raw).digest("hex")}`);
|
|
164
|
+
if (duplicateId || duplicateBody) {
|
|
165
|
+
reply(200, "duplicate");
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
const matching = candidates.filter(store => storePushMatches(push, store));
|
|
169
|
+
if (!matching.length) {
|
|
170
|
+
reply(200, "non-matching");
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
reply(202, "accepted");
|
|
174
|
+
setImmediate(() => { if (!this.closed)
|
|
175
|
+
for (const store of matching)
|
|
176
|
+
this.notify(store); });
|
|
177
|
+
})().catch(error => reply(typeof error === "number" ? error : 400, typeof error === "number" && error === 413 ? "too-large" : "malformed"));
|
|
178
|
+
});
|
|
179
|
+
this.server = server;
|
|
180
|
+
server.requestTimeout = 6000;
|
|
181
|
+
server.headersTimeout = 5000;
|
|
182
|
+
server.maxHeadersCount = 32;
|
|
183
|
+
await new Promise((resolve, reject) => { server.once("error", reject); server.listen(config.listenPort, "127.0.0.1", resolve); });
|
|
184
|
+
server.on("error", () => { this.status.listening = false; this.status.problem = "Webhook listener failed."; });
|
|
185
|
+
this.status.listening = true;
|
|
186
|
+
this.status.listenPort = config.listenPort;
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
this.status.problem = "Webhook config invalid, unsafe, or port unavailable.";
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
stop() {
|
|
193
|
+
this.closed = true;
|
|
194
|
+
this.status.listening = false;
|
|
195
|
+
for (const state of this.nudges.values())
|
|
196
|
+
clearTimeout(state.timer);
|
|
197
|
+
this.server?.close();
|
|
198
|
+
this.server?.closeAllConnections();
|
|
199
|
+
}
|
|
200
|
+
}
|
package/dist/bridge/hand-off.js
CHANGED
|
@@ -161,7 +161,7 @@ export async function moveSession(input, options = {}) {
|
|
|
161
161
|
if (peer && target.server !== peer.server)
|
|
162
162
|
throw new BridgeError(400, "The target belongs to a different Herdr server on that computer.");
|
|
163
163
|
const to = { harness: data.harness, ...(data.account ? { account: data.account } : {}), ...(data.model ? { model: data.model } : {}), ...(data.effort ? { effort: data.effort } : {}) };
|
|
164
|
-
move = object((await request("/v1/sessions/move", { target, to: moveToSchema.parse(to), ...(data.id ? { id: data.id } : {}) })).move);
|
|
164
|
+
move = object((await request("/v1/sessions/move", { target, to: moveToSchema.parse(to), ...(options.agent ? { origin: "agent" } : {}), ...(data.id ? { id: data.id } : {}) })).move);
|
|
165
165
|
if (data.wait !== false && typeof move.id === "string") {
|
|
166
166
|
const until = Date.now() + (options.waitMs ?? MOVE_WAIT_MS);
|
|
167
167
|
while (!settled(move) && Date.now() < until) {
|
package/dist/bridge/install.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type ModuleSnapshot } from "../modules/runtime.js";
|
|
2
2
|
import type { GatewayScope } from "./scoped-gateway.js";
|
|
3
3
|
import { type CodexServerEntry } from "./codex-servers.js";
|
|
4
|
+
export declare const peerForcedCommand = "command=\"sh ~/.local/share/phren/bridge/dispatch-scoped peer\"";
|
|
4
5
|
export declare const forcedCommand = "command=\"sh ~/.local/share/phren/bridge/dispatch\"";
|
|
5
6
|
/** A scoped key's forced command. A separate script, so a key added before
|
|
6
7
|
* the Hook can serve its scope fails closed instead of reaching `dispatch`. */
|
package/dist/bridge/install.js
CHANGED
|
@@ -22,6 +22,7 @@ import { serversInService } from "./codex-servers.js";
|
|
|
22
22
|
const exec = promisify(execFile);
|
|
23
23
|
const label = "com.phren.hook";
|
|
24
24
|
const unit = "phren-hook.service";
|
|
25
|
+
export const peerForcedCommand = 'command="sh ~/.local/share/phren/bridge/dispatch-scoped peer"';
|
|
25
26
|
export const forcedCommand = 'command="sh ~/.local/share/phren/bridge/dispatch"';
|
|
26
27
|
/** A scoped key's forced command. A separate script, so a key added before
|
|
27
28
|
* the Hook can serve its scope fails closed instead of reaching `dispatch`. */
|
|
@@ -52,6 +53,12 @@ export function upgradeKeys(text) {
|
|
|
52
53
|
let changed = 0;
|
|
53
54
|
const result = text.split(/(?<=\n)/).map(line => {
|
|
54
55
|
const parsed = keyOptions(line);
|
|
56
|
+
if (parsed && parsed.options[0] === "restrict" && /^\s+ssh-ed25519 [A-Za-z0-9+/=]+ phren-computer:[A-Za-z0-9_.-]+\s*$/.test(parsed.rest)
|
|
57
|
+
&& parsed.options.includes(forcedCommand)) {
|
|
58
|
+
changed++;
|
|
59
|
+
return parsed.options.filter(option => option !== "pty" && option.toLowerCase() !== "port-forwarding" && !option.toLowerCase().startsWith("permitopen="))
|
|
60
|
+
.map(option => option === forcedCommand ? peerForcedCommand : option).join(",") + parsed.rest;
|
|
61
|
+
}
|
|
55
62
|
if (!parsed || parsed.options[0] !== "restrict" || !/^\s+ssh-ed25519 [A-Za-z0-9+/=]+ phren-(?:iphone|android)\s*$/.test(parsed.rest))
|
|
56
63
|
return line;
|
|
57
64
|
const old = /^command="(?:\/usr\/bin\/false|python3 ~\/\.local\/share\/phren\/chat-progress\.py|sh ~\/\.local\/share\/phren\/bridge\/dispatch)"$/;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { IncomingMessage } from "node:http";
|
|
2
|
+
import type { Json } from "./protocol.js";
|
|
3
|
+
/** Owner phone/desktop gateways and the owner's local CLI carry no agent or
|
|
4
|
+
* peer origin. Peer keys are forced through the peer scope, which rebuilds
|
|
5
|
+
* the request with its own origin header; MCP calls carry an agent origin. */
|
|
6
|
+
export declare function ownerRequest(request: Pick<IncomingMessage, "headers">, data: Json): boolean;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Owner phone/desktop gateways and the owner's local CLI carry no agent or
|
|
2
|
+
* peer origin. Peer keys are forced through the peer scope, which rebuilds
|
|
3
|
+
* the request with its own origin header; MCP calls carry an agent origin. */
|
|
4
|
+
export function ownerRequest(request, data) {
|
|
5
|
+
return request.headers?.["x-phren-origin"] === undefined && data.origin === undefined;
|
|
6
|
+
}
|
|
@@ -16,6 +16,9 @@ export type Admission = {
|
|
|
16
16
|
};
|
|
17
17
|
/** Decide one request: its head (through the blank line) and the bytes after it. */
|
|
18
18
|
export declare function admitScopedRequest(scope: GatewayScope, rawHead: string, rest?: Buffer): Admission;
|
|
19
|
+
/** A computer key's forced scope rebuilds the HTTP envelope. Client headers
|
|
20
|
+
* cannot impersonate the owner gateway, and peer keys cannot open terminals. */
|
|
21
|
+
export declare function admitPeerRequest(rawHead: string, rest?: Buffer): Admission;
|
|
19
22
|
export interface ScopedIO {
|
|
20
23
|
input: Readable;
|
|
21
24
|
output: Writable;
|
|
@@ -123,6 +123,8 @@ export function admitScopedRequest(scope, rawHead, rest = Buffer.alloc(0)) {
|
|
|
123
123
|
if ("ok" in head)
|
|
124
124
|
return head;
|
|
125
125
|
const rule = findRule(scope, head);
|
|
126
|
+
if (!rule && head.path === "/v1/sessions/move")
|
|
127
|
+
return refuse(403, "Only the owner can move the conductor.");
|
|
126
128
|
if (!rule)
|
|
127
129
|
return refuse(403, `This key only permits ${DESCRIBE[scope]}.`);
|
|
128
130
|
let target = head.path;
|
|
@@ -163,6 +165,22 @@ export function admitScopedRequest(scope, rawHead, rest = Buffer.alloc(0)) {
|
|
|
163
165
|
const body = JSON.stringify(checked.data);
|
|
164
166
|
return { ok: true, request: `${rule.method} ${target} HTTP/1.1\r\nHost: phren.local\r\nContent-Type: application/json\r\nContent-Length: ${Buffer.byteLength(body)}\r\nConnection: close\r\n\r\n${body}` };
|
|
165
167
|
}
|
|
168
|
+
/** A computer key's forced scope rebuilds the HTTP envelope. Client headers
|
|
169
|
+
* cannot impersonate the owner gateway, and peer keys cannot open terminals. */
|
|
170
|
+
export function admitPeerRequest(rawHead, rest = Buffer.alloc(0)) {
|
|
171
|
+
const head = parseHead(rawHead);
|
|
172
|
+
if ("ok" in head)
|
|
173
|
+
return head;
|
|
174
|
+
if (!["GET", "POST", "DELETE"].includes(head.method) || !head.path.startsWith("/v1/"))
|
|
175
|
+
return refuse(403, "This key only permits Hook API requests.");
|
|
176
|
+
if (head.contentLength > 8 * 1024 * 1024 || rest.length !== head.contentLength)
|
|
177
|
+
return refuse(400, "Send one bounded request matching Content-Length.");
|
|
178
|
+
if (rest.length && !head.json)
|
|
179
|
+
return refuse(415, "Send Content-Type: application/json.");
|
|
180
|
+
const body = rest.toString("utf8");
|
|
181
|
+
const target = head.path + (head.query === null ? "" : `?${head.query}`);
|
|
182
|
+
return { ok: true, request: `${head.method} ${target} HTTP/1.1\r\nHost: phren.local\r\nX-Phren-Origin: peer\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: ${Buffer.byteLength(body)}\r\n\r\n${body}` };
|
|
183
|
+
}
|
|
166
184
|
const REASONS = { 400: "Bad Request", 403: "Forbidden", 408: "Request Timeout", 413: "Content Too Large", 415: "Unsupported Media Type", 503: "Service Unavailable" };
|
|
167
185
|
function httpResponse(status, error) {
|
|
168
186
|
const body = JSON.stringify({ error, code: status === 503 ? "hook-unavailable" : "scope-refused" });
|
|
@@ -172,7 +190,7 @@ function httpResponse(status, error) {
|
|
|
172
190
|
* a body within its cap, exactly that many bytes. Stops at a limit, the
|
|
173
191
|
* timeout or EOF; bytes beyond the request make it refused. */
|
|
174
192
|
function readRequest(scope, input) {
|
|
175
|
-
const bodyCap = Math.max(0, ...RULES[scope].map(rule => rule.body?.max ?? 0));
|
|
193
|
+
const bodyCap = scope === "peer" ? 8 * 1024 * 1024 : Math.max(0, ...RULES[scope].map(rule => rule.body?.max ?? 0));
|
|
176
194
|
return new Promise(resolve => {
|
|
177
195
|
let buffer = Buffer.alloc(0), headEnd = -1, wanted = 0;
|
|
178
196
|
const finish = (value) => {
|
|
@@ -214,12 +232,12 @@ function readRequest(scope, input) {
|
|
|
214
232
|
* reads a normal response.
|
|
215
233
|
*/
|
|
216
234
|
export async function scopedDispatch(scope, command, io) {
|
|
217
|
-
if (!isGatewayScope(scope))
|
|
235
|
+
if (scope !== "peer" && !isGatewayScope(scope))
|
|
218
236
|
throw new BridgeError(403, "Unknown key scope.");
|
|
219
237
|
if (command !== SCOPED_COMMAND)
|
|
220
|
-
throw new BridgeError(403, `This SSH key only permits \`${SCOPED_COMMAND}\` with ${DESCRIBE[scope]}.`);
|
|
238
|
+
throw new BridgeError(403, `This SSH key only permits \`${SCOPED_COMMAND}\` with ${scope === "peer" ? "Hook API requests" : DESCRIBE[scope]}.`);
|
|
221
239
|
const read = await readRequest(scope, io.input);
|
|
222
|
-
const admission = "head" in read ? admitScopedRequest(scope, read.head, read.rest) : refuse(read.status, read.error);
|
|
240
|
+
const admission = "head" in read ? (scope === "peer" ? admitPeerRequest(read.head, read.rest) : admitScopedRequest(scope, read.head, read.rest)) : refuse(read.status, read.error);
|
|
223
241
|
if (!admission.ok) {
|
|
224
242
|
await new Promise(done => io.output.write(httpResponse(admission.status, admission.error), () => done()));
|
|
225
243
|
return;
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import type { StorePulls } from "./store-pull.js";
|
|
2
|
+
import type { GitboyWebhooks } from "./gitboy-webhooks.js";
|
|
1
3
|
import { type SessionMover } from "./session-move.js";
|
|
2
4
|
import type { OwnerInbox } from "./owner-inbox.js";
|
|
3
5
|
import type { HandOffQueue } from "./hand-off-queue.js";
|
|
@@ -52,6 +54,8 @@ export interface RouteContext {
|
|
|
52
54
|
computerID: string;
|
|
53
55
|
scheduleStore: string;
|
|
54
56
|
scheduler?: Scheduler;
|
|
57
|
+
storePulls?: StorePulls;
|
|
58
|
+
gitboyWebhooks?: GitboyWebhooks;
|
|
55
59
|
dispatches?: DispatchService;
|
|
56
60
|
returns?: DispatchReturns;
|
|
57
61
|
handOffs?: HandOffQueue;
|
|
@@ -135,6 +139,7 @@ export declare const capabilities: {
|
|
|
135
139
|
launchPermissionMode: boolean;
|
|
136
140
|
sessionMove: boolean;
|
|
137
141
|
moveNewChat: boolean;
|
|
142
|
+
moveConductor: boolean;
|
|
138
143
|
projectMemory: boolean;
|
|
139
144
|
fileWrite: boolean;
|
|
140
145
|
fileSearch: boolean;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ownerRequest } from "./request-origin.js";
|
|
1
2
|
import { listMoves, moveSessionFields, readMove } from "./session-move.js";
|
|
2
3
|
import { getTaskRoute, getTaskDirectoryRoute, updateTaskRoute, createTaskRoute, saveTaskRoute, launchTaskRoute } from "./task-routes.js";
|
|
3
4
|
import { ownerInboxView } from "./owner-inbox-view.js";
|
|
@@ -81,7 +82,7 @@ async function childActivity(source, session) {
|
|
|
81
82
|
export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
|
|
82
83
|
terminal: "ssh-pty", shell: "ssh-pty", paneTerminal: "ssh-pty", paneLayout: true, deskPresence: true, herdr: true, sessionRename: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
|
|
83
84
|
approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
|
|
84
|
-
files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, moveNewChat: true, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true, projectHostToken: true };
|
|
85
|
+
files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, moveNewChat: true, moveConductor: true, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true, projectHostToken: true };
|
|
85
86
|
export function capabilitiesForModules(snapshot) {
|
|
86
87
|
const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
|
|
87
88
|
const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
|
|
@@ -361,6 +362,13 @@ export function createRouteHandler(ctx) {
|
|
|
361
362
|
? await projectHostToken(modules.store, project, await journal.recent(), await body(request))
|
|
362
363
|
: await projectGit(modules.store, project, await journal.recent());
|
|
363
364
|
}
|
|
365
|
+
else if (url.pathname === "/v1/store/pull-now") {
|
|
366
|
+
if (request.method !== "POST")
|
|
367
|
+
throw new BridgeError(405, "Unsupported request method.");
|
|
368
|
+
if (!ctx.storePulls)
|
|
369
|
+
throw new BridgeError(503, "Store pulls unavailable.");
|
|
370
|
+
result = await ctx.storePulls.route(request, await body(request));
|
|
371
|
+
}
|
|
364
372
|
else if (url.pathname.startsWith("/v1/store/")) {
|
|
365
373
|
result = await storeRoute(modules.store, request.method ?? "", url, request.method === "POST" ? await body(request) : undefined);
|
|
366
374
|
}
|
|
@@ -381,7 +389,7 @@ export function createRouteHandler(ctx) {
|
|
|
381
389
|
case "/v1/health/details":
|
|
382
390
|
result = { ...await healthDetails({ hookVersion: version, computerId: computerID, store: scheduleStore,
|
|
383
391
|
scheduler: scheduler ? { running: true, lastTickAt: scheduler.lastTickAt } : undefined, push: agentHooks.push.status }),
|
|
384
|
-
gitWrites: gitWrites.snapshot() };
|
|
392
|
+
gitboyWebhooks: ctx.gitboyWebhooks?.status ?? { configured: false, listening: false }, gitWrites: gitWrites.snapshot() };
|
|
385
393
|
break;
|
|
386
394
|
case "/v1/health/peers": {
|
|
387
395
|
// A peer's health probe asks whether this computer lists it back.
|
|
@@ -774,7 +782,8 @@ export function createRouteHandler(ctx) {
|
|
|
774
782
|
// Answers once the move is checked and recorded; the hand-off and relaunch run on, and GET says where it is.
|
|
775
783
|
if (!ctx.mover)
|
|
776
784
|
throw new BridgeError(503, "This Hook cannot move sessions.");
|
|
777
|
-
|
|
785
|
+
const { origin: _origin, ...input } = data;
|
|
786
|
+
result = { ok: true, move: await ctx.mover.start(input, { owner: ownerRequest(request, data) }) };
|
|
778
787
|
}
|
|
779
788
|
else if (url.pathname === "/v1/sessions/rename") {
|
|
780
789
|
result = await renameSession(selectedServer(url), data);
|
|
@@ -860,10 +869,14 @@ export function createRouteHandler(ctx) {
|
|
|
860
869
|
: { ok: true, confirmation: await confirmAuthority(data, "phone") };
|
|
861
870
|
}
|
|
862
871
|
else if (url.pathname === "/v1/conductor/make") {
|
|
872
|
+
if (!ownerRequest(request, data))
|
|
873
|
+
throw new BridgeError(403, "Only the owner can change the conductor.");
|
|
863
874
|
// Serialized with launches, so a conductor launch and a make cannot both pass the set check.
|
|
864
875
|
result = await launches.run(async () => makeConductor(selectedServer(url), data));
|
|
865
876
|
}
|
|
866
877
|
else if (url.pathname === "/v1/conductor/stop") {
|
|
878
|
+
if (!ownerRequest(request, data))
|
|
879
|
+
throw new BridgeError(403, "Only the owner can change the conductor.");
|
|
867
880
|
result = await launches.run(async () => stopConductor(data));
|
|
868
881
|
}
|
|
869
882
|
else if (url.pathname === "/v1/sets/name") {
|
|
@@ -932,6 +945,8 @@ export function createRouteHandler(ctx) {
|
|
|
932
945
|
else {
|
|
933
946
|
if (url.pathname === "/v1/workspaces/launch") {
|
|
934
947
|
result = await launches.run(async () => {
|
|
948
|
+
if (data.role === "conductor" && !ownerRequest(request, data))
|
|
949
|
+
throw new BridgeError(403, "Only the owner can change the conductor.");
|
|
935
950
|
if (data.role === "conductor" && !modules.has("conductor"))
|
|
936
951
|
throw new BridgeError(404, disabledHint("conductor"));
|
|
937
952
|
if (data.agentFolder === true && (data.role === "conductor" || data.project !== undefined || (data.cwd !== undefined && data.cwd !== "") || data.worktree != null)) {
|
package/dist/bridge/server.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { StorePulls } from "./store-pull.js";
|
|
2
|
+
import { GitboyWebhooks } from "./gitboy-webhooks.js";
|
|
1
3
|
import { setChoiceReaders } from "./account-choice.js";
|
|
2
4
|
import { AccountFailover } from "./account-failover.js";
|
|
3
5
|
import { ownerInboxSources } from "./owner-inbox-sources.js";
|
|
@@ -218,6 +220,8 @@ export async function serve(version, options = {}) {
|
|
|
218
220
|
throw new Error("Phren Hook is already running.");
|
|
219
221
|
await unlink(socketPath());
|
|
220
222
|
}
|
|
223
|
+
const storePulls = new StorePulls(scheduleStore);
|
|
224
|
+
const gitboyWebhooks = new GitboyWebhooks(root, storeId => storePulls.request(storeId));
|
|
221
225
|
const stopRetention = modules.has("git") ? await startChangeRetention() : () => { };
|
|
222
226
|
if (modules.has("git"))
|
|
223
227
|
await rm(path.join(root, "changes-scratch"), { recursive: true, force: true });
|
|
@@ -234,7 +238,7 @@ export async function serve(version, options = {}) {
|
|
|
234
238
|
// 256 KiB: gitboy's /memory/files asks about up to 500 paths in one query string.
|
|
235
239
|
const http = createServer({ maxHeaderSize: 256 * 1024 }, createRouteHandler({ version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks,
|
|
236
240
|
journal, tabActivity, contextUsage, modelCatalog, modelSwitcher, settingsSwitcher, permissionModeSwitcher, sideQuestions, accountUsage, resources, codexQuestions, launches, locatedDirectories,
|
|
237
|
-
fanoutMessages, canary, streams, returns, handOffs, inbox, mover }));
|
|
241
|
+
fanoutMessages, canary, streams, returns, handOffs, inbox, mover, storePulls, gitboyWebhooks }));
|
|
238
242
|
http.requestTimeout = 20_000;
|
|
239
243
|
http.headersTimeout = 10_000;
|
|
240
244
|
http.maxHeadersCount = 32;
|
|
@@ -287,6 +291,7 @@ export async function serve(version, options = {}) {
|
|
|
287
291
|
});
|
|
288
292
|
await new Promise((resolve, reject) => { http.once("error", reject); http.listen(socketPath(), () => resolve()); });
|
|
289
293
|
await chmod(socketPath(), 0o600);
|
|
294
|
+
await gitboyWebhooks.start();
|
|
290
295
|
await agentHooks.start();
|
|
291
296
|
// Codex panes on the Hook's own app-servers: their requests become
|
|
292
297
|
// approval cards, and servers a previous Hook started are rejoined.
|
|
@@ -351,7 +356,7 @@ export async function serve(version, options = {}) {
|
|
|
351
356
|
})().finally(() => { recording = false; }).catch(() => { });
|
|
352
357
|
}, 5000);
|
|
353
358
|
await new Promise(resolve => {
|
|
354
|
-
const stop = () => { storeSync.stop(); fanoutMessages.close(); stopRetention(); clearInterval(scheduleTimer); clearInterval(canaryTimer); clearInterval(codexAuthTimer); clearInterval(activityTimer); scheduler?.close(); codeReindexer?.close(); codexServers.close(); agentHooks.close(); ws.clients.forEach(c => c.terminate()); ws.close(); http.close(() => resolve()); http.closeAllConnections(); };
|
|
359
|
+
const stop = () => { gitboyWebhooks.stop(); storePulls.stop(); storeSync.stop(); fanoutMessages.close(); stopRetention(); clearInterval(scheduleTimer); clearInterval(canaryTimer); clearInterval(codexAuthTimer); clearInterval(activityTimer); scheduler?.close(); codeReindexer?.close(); codexServers.close(); agentHooks.close(); ws.clients.forEach(c => c.terminate()); ws.close(); http.close(() => resolve()); http.closeAllConnections(); };
|
|
355
360
|
process.once("SIGTERM", stop);
|
|
356
361
|
process.once("SIGINT", stop);
|
|
357
362
|
});
|
|
@@ -97,6 +97,7 @@ declare const moveRecordSchema: z.ZodObject<{
|
|
|
97
97
|
"new-chat": "new-chat";
|
|
98
98
|
replace: "replace";
|
|
99
99
|
}>>;
|
|
100
|
+
modeForced: z.ZodOptional<z.ZodLiteral<"conductor">>;
|
|
100
101
|
handedOffTo: z.ZodOptional<z.ZodObject<{
|
|
101
102
|
target: z.ZodUnion<readonly [z.ZodObject<{
|
|
102
103
|
server: z.ZodString;
|
|
@@ -289,7 +290,7 @@ export declare function fallbackHandoff(input: {
|
|
|
289
290
|
label?: string;
|
|
290
291
|
}): string;
|
|
291
292
|
/** The hand-off file: who moved where and when, the body, then what Phren saw. */
|
|
292
|
-
export declare function handoffDocument(record: MoveRecord, body: string, observed: string, at: string): string;
|
|
293
|
+
export declare function handoffDocument(record: MoveRecord, body: string, observed: string, at: string, conductor?: boolean): string;
|
|
293
294
|
/** The new agent's first prompt: the whole hand-off when it fits the brief, else where to read it. */
|
|
294
295
|
export declare function continuePrompt(document: string, file: string): string;
|
|
295
296
|
export interface MoverDeps {
|
|
@@ -342,11 +343,18 @@ export declare class SessionMover {
|
|
|
342
343
|
private sleep;
|
|
343
344
|
private get poll();
|
|
344
345
|
/** Checks the move can happen, records it and starts it. Refuses before anything is typed. */
|
|
345
|
-
start(input: unknown
|
|
346
|
+
start(input: unknown, caller?: {
|
|
347
|
+
owner?: boolean;
|
|
348
|
+
}): Promise<MoveRecord>;
|
|
346
349
|
/** For tests: the move under way in a pane, until it settles. */
|
|
347
350
|
settled(server: string, pane: string): Promise<void> | undefined;
|
|
348
351
|
private update;
|
|
349
352
|
private run;
|
|
353
|
+
/** An ordinary move never acquires permission to stop a conductor merely
|
|
354
|
+
* because the owner promoted its source while the hand-off was running. */
|
|
355
|
+
private checkPromotion;
|
|
356
|
+
/** Uses the same durable prompt path as the hand-off and its first brief. */
|
|
357
|
+
private conductorNotice;
|
|
350
358
|
/** The agent's own hand-off, or why there is none. Fails only when the session itself went away. */
|
|
351
359
|
private askForHandoff;
|
|
352
360
|
private fallback;
|