@phren/cli 0.3.31 → 0.3.33
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.js +23 -7
- package/dist/bridge/approval-rules.d.ts +70 -0
- package/dist/bridge/approval-rules.js +231 -0
- package/dist/bridge/authority.d.ts +1 -2
- package/dist/bridge/authority.js +2 -7
- package/dist/bridge/changes.d.ts +4 -0
- package/dist/bridge/changes.js +47 -33
- package/dist/bridge/claude-suggestion.js +1 -1
- package/dist/bridge/computer-names.d.ts +4 -0
- package/dist/bridge/computer-names.js +19 -0
- package/dist/bridge/dispatch.js +1 -1
- package/dist/bridge/enroll.d.ts +6 -0
- package/dist/bridge/enroll.js +10 -4
- package/dist/bridge/git-worktrees.js +14 -17
- package/dist/bridge/git.d.ts +10 -2
- package/dist/bridge/git.js +148 -107
- package/dist/bridge/health.js +9 -5
- package/dist/bridge/herdr.js +6 -1
- package/dist/bridge/locate.js +14 -1
- package/dist/bridge/model-switch.d.ts +4 -0
- package/dist/bridge/model-switch.js +16 -4
- package/dist/bridge/projects.d.ts +8 -0
- package/dist/bridge/projects.js +142 -24
- package/dist/bridge/schedule-format.d.ts +12 -0
- package/dist/bridge/schedule-format.js +33 -2
- package/dist/bridge/schedules.d.ts +8 -1
- package/dist/bridge/schedules.js +109 -45
- package/dist/bridge/server-launch.js +39 -15
- package/dist/bridge/server-pane-routes.js +19 -11
- package/dist/bridge/server-routes.d.ts +2 -0
- package/dist/bridge/server-routes.js +36 -8
- package/dist/bridge/server.js +1 -0
- package/dist/bridge/settings-switch.js +2 -6
- package/dist/bridge/speech-key.d.ts +2 -9
- package/dist/bridge/speech-key.js +4 -37
- package/dist/bridge/terminal-tmux.js +22 -4
- package/dist/bridge/tmux-test-server.d.ts +13 -0
- package/dist/bridge/tmux-test-server.js +103 -0
- package/dist/bridge/transcript-claude.d.ts +3 -3
- package/dist/bridge/transcript-claude.js +7 -7
- package/dist/bridge/transcript-codex.js +6 -4
- package/dist/bridge/transcript-preview.js +1 -1
- package/dist/bridge/transcripts.js +14 -3
- package/dist/bridge-hook.mjs +2794 -2223
- package/dist/cli/schedules.js +8 -2
- package/dist/cli/session-stop.js +9 -1
- package/dist/cli-registry.js +1 -1
- package/dist/core/project-registry.d.ts +1 -0
- package/dist/core/project-registry.js +6 -2
- package/dist/core/project.d.ts +1 -0
- package/dist/core/project.js +5 -0
- package/dist/modules/registry.js +9 -7
- package/dist/phren-core.js +1 -1
- package/dist/phren-paths.d.ts +2 -2
- package/dist/phren-paths.js +2 -2
- package/dist/store-routing.d.ts +2 -2
- package/dist/store-routing.js +2 -2
- package/dist/sync/git-state.d.ts +13 -0
- package/dist/sync/git-state.js +22 -0
- package/dist/sync/store-merge.d.ts +2 -0
- package/dist/sync/store-merge.js +6 -1
- package/dist/test-global-setup.js +7 -0
- package/dist/tools/data.js +1 -1
- package/dist/tools/finding.js +1 -1
- package/dist/tools/search.js +1 -1
- package/dist/tools/tasks.js +1 -1
- package/package.json +1 -1
- package/starter/global/skills/conductor/SKILL.md +2 -2
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { approvalRuleContext, approvalRuleEffect } from "./approval-rules.js";
|
|
1
2
|
import { recordedConductor } from "./conductor-role.js";
|
|
2
|
-
import { conductorContext } from "./conductor-context.js";
|
|
3
|
+
import { conductorBrief, conductorContext } from "./conductor-context.js";
|
|
3
4
|
import { defaultPhrenPath } from "../shared.js";
|
|
4
5
|
import { disabledHint } from "../modules/registry.js";
|
|
5
6
|
import { activateModules as moduleSnapshot } from "../modules/runtime.js";
|
|
@@ -111,7 +112,7 @@ const DISPATCH_LEASE_MS = 45_000;
|
|
|
111
112
|
export function conductorCall(tool, input) {
|
|
112
113
|
// MCP tool names vary by harness: `dispatch`, `phren.dispatch`,
|
|
113
114
|
// `mcp__phren__dispatch`; phren_admin carries the action in its fields.
|
|
114
|
-
const tail = /(?:^|[.:/]|__)(dispatch|hand_off|phren_admin)$/.exec(tool)?.[1];
|
|
115
|
+
const tail = /(?:^|[.:/]|__)(dispatch|hand_off|phren_admin)$/.exec(tool.replace(/^mcp_phren_/, ""))?.[1];
|
|
115
116
|
const fields = object(input);
|
|
116
117
|
let action;
|
|
117
118
|
if (tail === "dispatch")
|
|
@@ -1537,7 +1538,7 @@ export class AgentHooks {
|
|
|
1537
1538
|
chunks.push(bytes);
|
|
1538
1539
|
}
|
|
1539
1540
|
const body = object(JSON.parse(Buffer.concat(chunks).toString()));
|
|
1540
|
-
// OpenCode
|
|
1541
|
+
// OpenCode and phren-agent ask when building the root session's system prompt. Resolve
|
|
1541
1542
|
// its process against the current conductor; no inherited pane env or
|
|
1542
1543
|
// plugin callback may create a session binding or a turn record here.
|
|
1543
1544
|
if (req.url === "/conductor-context") {
|
|
@@ -1554,7 +1555,7 @@ export class AgentHooks {
|
|
|
1554
1555
|
}
|
|
1555
1556
|
const s = await snapshot(role.server);
|
|
1556
1557
|
const pane = objects(s.panes).find(p => p.pane_id === role.pane);
|
|
1557
|
-
if (!pane || pane.agent
|
|
1558
|
+
if (!pane || !["opencode", "phren"].includes(String(pane.agent)) || (role.terminal && pane.terminal_id !== role.terminal)) {
|
|
1558
1559
|
res.end("{}");
|
|
1559
1560
|
return;
|
|
1560
1561
|
}
|
|
@@ -1564,9 +1565,9 @@ export class AgentHooks {
|
|
|
1564
1565
|
return;
|
|
1565
1566
|
}
|
|
1566
1567
|
const target = targetSchema.parse({ server: role.server, workspace: pane.workspace_id, tab: pane.tab_id,
|
|
1567
|
-
pane: role.pane, source:
|
|
1568
|
+
pane: role.pane, source: pane.agent, session: body.session });
|
|
1568
1569
|
const context = await conductorContext(target, s);
|
|
1569
|
-
res.end(JSON.stringify(context ? { context } : {}));
|
|
1570
|
+
res.end(JSON.stringify(context ? { context: pane.agent === "phren" ? `${context}\n\n${await conductorBrief()}` : context } : {}));
|
|
1570
1571
|
return;
|
|
1571
1572
|
}
|
|
1572
1573
|
let target = targetSchema.parse(body.target);
|
|
@@ -1675,9 +1676,24 @@ export class AgentHooks {
|
|
|
1675
1676
|
res.end("{}");
|
|
1676
1677
|
return;
|
|
1677
1678
|
}
|
|
1679
|
+
// Validate applicable shell restrictions before any directory/Git reads.
|
|
1680
|
+
const ruleEffect = body.event === "PermissionRequest" && target.source === "claude"
|
|
1681
|
+
? await approvalRuleEffect(String(body.tool), body.input, async () => {
|
|
1682
|
+
if (typeof body.cwd !== "string" || !path.isAbsolute(body.cwd))
|
|
1683
|
+
return undefined;
|
|
1684
|
+
const [paneContext, requestContext] = await Promise.all([
|
|
1685
|
+
trustedDirectory(pane).then(cwd => approvalRuleContext(cwd, target.source, target.session)).catch(() => undefined),
|
|
1686
|
+
approvalRuleContext(body.cwd, target.source, target.session),
|
|
1687
|
+
]);
|
|
1688
|
+
return paneContext && requestContext?.project === paneContext.project ? requestContext : undefined;
|
|
1689
|
+
}, undefined, { harness: target.source, session: target.session, computer: hostname() }) : undefined;
|
|
1690
|
+
if (ruleEffect === "deny") {
|
|
1691
|
+
res.end(JSON.stringify({ hookSpecificOutput: { hookEventName: "PermissionRequest", decision: { behavior: "deny", message: "Denied by an owner approval rule." } } }));
|
|
1692
|
+
return;
|
|
1693
|
+
}
|
|
1678
1694
|
if (body.event === "PermissionRequest")
|
|
1679
1695
|
this.terminalPrompts.delete(JSON.stringify(target));
|
|
1680
|
-
if (body.event === "PermissionRequest") {
|
|
1696
|
+
if (body.event === "PermissionRequest" && ruleEffect !== "always-ask") {
|
|
1681
1697
|
const conductor = conductorCall(String(body.tool || "action"), body.input);
|
|
1682
1698
|
if (conductor) {
|
|
1683
1699
|
// A standing grant answers the call before it becomes an approval card.
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
export declare const approvalRuleDraftSchema: z.ZodObject<{
|
|
3
|
+
tool: z.ZodLiteral<"Bash">;
|
|
4
|
+
command: z.ZodString;
|
|
5
|
+
match: z.ZodEnum<{
|
|
6
|
+
exact: "exact";
|
|
7
|
+
glob: "glob";
|
|
8
|
+
prefix: "prefix";
|
|
9
|
+
}>;
|
|
10
|
+
effect: z.ZodEnum<{
|
|
11
|
+
"always-ask": "always-ask";
|
|
12
|
+
deny: "deny";
|
|
13
|
+
}>;
|
|
14
|
+
scope: z.ZodObject<{
|
|
15
|
+
project: z.ZodString;
|
|
16
|
+
harness: z.ZodOptional<z.ZodEnum<{
|
|
17
|
+
claude: "claude";
|
|
18
|
+
codex: "codex";
|
|
19
|
+
copilot: "copilot";
|
|
20
|
+
opencode: "opencode";
|
|
21
|
+
phren: "phren";
|
|
22
|
+
}>>;
|
|
23
|
+
session: z.ZodOptional<z.ZodString>;
|
|
24
|
+
computer: z.ZodOptional<z.ZodString>;
|
|
25
|
+
}, z.core.$strict>;
|
|
26
|
+
projectName: z.ZodString;
|
|
27
|
+
until: z.ZodOptional<z.ZodString>;
|
|
28
|
+
}, z.core.$strict>;
|
|
29
|
+
export type ApprovalRuleDraft = z.infer<typeof approvalRuleDraftSchema>;
|
|
30
|
+
export interface ApprovalRule extends ApprovalRuleDraft {
|
|
31
|
+
id: string;
|
|
32
|
+
createdAt: string;
|
|
33
|
+
owner: string;
|
|
34
|
+
enabled: boolean;
|
|
35
|
+
}
|
|
36
|
+
export declare function listApprovalRules(root?: string, pairedKey?: string): Promise<{
|
|
37
|
+
tool: "Bash";
|
|
38
|
+
command: string;
|
|
39
|
+
match: "exact" | "glob" | "prefix";
|
|
40
|
+
effect: "always-ask" | "deny";
|
|
41
|
+
scope: {
|
|
42
|
+
project: string;
|
|
43
|
+
harness?: "claude" | "codex" | "copilot" | "opencode" | "phren" | undefined;
|
|
44
|
+
session?: string | undefined;
|
|
45
|
+
computer?: string | undefined;
|
|
46
|
+
};
|
|
47
|
+
projectName: string;
|
|
48
|
+
until?: string | undefined;
|
|
49
|
+
id: string;
|
|
50
|
+
createdAt: string;
|
|
51
|
+
owner: string;
|
|
52
|
+
enabled: boolean;
|
|
53
|
+
signerFingerprint: string;
|
|
54
|
+
matchesPairedKey: boolean;
|
|
55
|
+
}[]>;
|
|
56
|
+
/** The signed operations remain on disk and are verified again at every decision. */
|
|
57
|
+
export declare function changeApprovalRule(input: unknown, method: "POST" | "DELETE", root?: string): Promise<{
|
|
58
|
+
ok: boolean;
|
|
59
|
+
}>;
|
|
60
|
+
export interface ApprovalRuleContext {
|
|
61
|
+
project: string;
|
|
62
|
+
harness: NonNullable<ApprovalRuleDraft["scope"]["harness"]>;
|
|
63
|
+
session: string;
|
|
64
|
+
computer: string;
|
|
65
|
+
}
|
|
66
|
+
/** Bind project scope to the main repository, including linked worktrees. */
|
|
67
|
+
export declare function approvalRuleContext(cwd: string, harness: string, session: string): Promise<ApprovalRuleContext | undefined>;
|
|
68
|
+
/** Rules can only restrict a request the harness has already raised. Invalid policy
|
|
69
|
+
* falls back to that ordinary approval path; Settings reports the load error. */
|
|
70
|
+
export declare function approvalRuleEffect(tool: string, input: unknown, context: ApprovalRuleContext | undefined | (() => Promise<ApprovalRuleContext | undefined>), root?: string, knownScope?: Partial<ApprovalRuleContext>): Promise<"always-ask" | "deny" | undefined>;
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { promisify } from "node:util";
|
|
3
|
+
import { nonInteractiveGitEnv } from "../utils-helpers.js";
|
|
4
|
+
import { createHash, createPublicKey, verify } from "node:crypto";
|
|
5
|
+
import { lstat, mkdir, readFile, realpath } from "node:fs/promises";
|
|
6
|
+
import { hostname } from "node:os";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
import { homeDir } from "../home-paths.js";
|
|
10
|
+
import { tryFileLock } from "../governance/locks.js";
|
|
11
|
+
import { atomic, BridgeError, bridgeRoot, object } from "./protocol.js";
|
|
12
|
+
const exec = promisify(execFile);
|
|
13
|
+
// Each context needs at most two reads; slow Git falls back to ordinary approval.
|
|
14
|
+
async function git(cwd, ...args) {
|
|
15
|
+
return (await exec("git", ["-C", cwd, "--no-pager", ...args], {
|
|
16
|
+
timeout: 150, maxBuffer: 4_194_304,
|
|
17
|
+
env: nonInteractiveGitEnv({ ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_CONFIG_NOSYSTEM: "1" }),
|
|
18
|
+
})).stdout;
|
|
19
|
+
}
|
|
20
|
+
const text = z.string().min(1).max(4096).refine(value => !/[\x00-\x1f\x7f]/.test(value));
|
|
21
|
+
const scopeSchema = z.object({
|
|
22
|
+
project: text.refine(value => path.isAbsolute(value) && path.normalize(value) === value),
|
|
23
|
+
harness: z.enum(["claude", "codex", "copilot", "opencode", "phren"]).optional(),
|
|
24
|
+
session: text.optional(), computer: text.optional(),
|
|
25
|
+
}).strict();
|
|
26
|
+
export const approvalRuleDraftSchema = z.object({
|
|
27
|
+
tool: z.literal("Bash"), command: text, match: z.enum(["exact", "prefix", "glob"]),
|
|
28
|
+
effect: z.enum(["always-ask", "deny"]), scope: scopeSchema,
|
|
29
|
+
projectName: z.string().min(1).max(100), until: z.string().datetime({ offset: true }).optional(),
|
|
30
|
+
}).strict();
|
|
31
|
+
const operationSchema = z.discriminatedUnion("operation", [
|
|
32
|
+
z.object({ domain: z.literal("phren-approval-rules-v1"), operation: z.literal("add"), nonce: z.string().uuid(), at: z.string().datetime({ offset: true }), rule: approvalRuleDraftSchema }).strict(),
|
|
33
|
+
z.object({ domain: z.literal("phren-approval-rules-v1"), operation: z.literal("set-enabled"), nonce: z.string().uuid(), at: z.string().datetime({ offset: true }), id: z.string().uuid(), enabled: z.boolean() }).strict(),
|
|
34
|
+
z.object({ domain: z.literal("phren-approval-rules-v1"), operation: z.literal("revoke"), nonce: z.string().uuid(), at: z.string().datetime({ offset: true }), id: z.string().uuid() }).strict(),
|
|
35
|
+
]);
|
|
36
|
+
const envelopeSchema = z.object({ payload: z.string().min(1).max(16384), signature: z.string().min(1).max(128), publicKey: z.string().min(1).max(64) }).strict();
|
|
37
|
+
const policySchema = z.object({ operations: z.array(envelopeSchema).max(2048) }).strict();
|
|
38
|
+
const policyPath = (root) => path.join(root, "approval-rules.json");
|
|
39
|
+
const forbidden = () => new BridgeError(403, "Confirm this change with the paired iPhone's signing key.");
|
|
40
|
+
/** Restricted phone keys only; dispatch keys and arbitrary SSH keys cannot sign policy. */
|
|
41
|
+
async function ownerKeys() {
|
|
42
|
+
const keys = await readFile(path.join(homeDir(), ".ssh", "authorized_keys"), "utf8");
|
|
43
|
+
const result = new Set();
|
|
44
|
+
for (const line of keys.split("\n")) {
|
|
45
|
+
const match = /^restrict,pty,command="sh ~\/\.local\/share\/phren\/bridge\/dispatch" ssh-ed25519 ([A-Za-z0-9+/]+={0,2}) phren-iphone\s*$/.exec(line);
|
|
46
|
+
if (!match)
|
|
47
|
+
continue;
|
|
48
|
+
const wire = Buffer.from(match[1], "base64");
|
|
49
|
+
// SSH string("ssh-ed25519"), string(32-byte key).
|
|
50
|
+
if (wire.length === 51 && wire.readUInt32BE(0) === 11 && wire.subarray(4, 15).toString() === "ssh-ed25519" && wire.readUInt32BE(15) === 32)
|
|
51
|
+
result.add(wire.subarray(19).toString("base64"));
|
|
52
|
+
}
|
|
53
|
+
return result;
|
|
54
|
+
}
|
|
55
|
+
function verified(envelope, keys) {
|
|
56
|
+
const raw = Buffer.from(envelope.publicKey, "base64"), signature = Buffer.from(envelope.signature, "base64"), payload = Buffer.from(envelope.payload, "base64");
|
|
57
|
+
if (raw.length !== 32 || signature.length !== 64 || !keys.has(raw.toString("base64")))
|
|
58
|
+
throw forbidden();
|
|
59
|
+
const key = createPublicKey({ key: Buffer.concat([Buffer.from("302a300506032b6570032100", "hex"), raw]), format: "der", type: "spki" });
|
|
60
|
+
if (!verify(null, payload, key, signature))
|
|
61
|
+
throw forbidden();
|
|
62
|
+
const operation = operationSchema.parse(JSON.parse(payload.toString("utf8")));
|
|
63
|
+
return { operation, owner: createHash("sha256").update(raw).digest("hex") };
|
|
64
|
+
}
|
|
65
|
+
async function privateJSON(file, fallback, max = 2_097_152) {
|
|
66
|
+
const info = await lstat(file).catch(error => { if (error.code === "ENOENT")
|
|
67
|
+
return undefined; throw error; });
|
|
68
|
+
if (!info)
|
|
69
|
+
return fallback;
|
|
70
|
+
if (!info.isFile() || info.isSymbolicLink() || (info.mode & 0o077) || info.size > max)
|
|
71
|
+
throw new BridgeError(409, "Approval policy must be a private regular file.");
|
|
72
|
+
return JSON.parse(await readFile(file, "utf8"));
|
|
73
|
+
}
|
|
74
|
+
async function readPolicy(root) {
|
|
75
|
+
const policy = policySchema.parse(await privateJSON(policyPath(root), { operations: [] }));
|
|
76
|
+
const keys = policy.operations.length ? await ownerKeys() : new Set();
|
|
77
|
+
const rules = new Map(), nonces = new Set();
|
|
78
|
+
for (const envelope of policy.operations) {
|
|
79
|
+
const { operation, owner } = verified(envelope, keys);
|
|
80
|
+
if (nonces.has(operation.nonce))
|
|
81
|
+
throw new BridgeError(409, "Repeated policy operation.");
|
|
82
|
+
nonces.add(operation.nonce);
|
|
83
|
+
if (operation.operation === "add")
|
|
84
|
+
rules.set(operation.nonce, { ...operation.rule, id: operation.nonce, createdAt: operation.at, owner, enabled: true });
|
|
85
|
+
else if (operation.operation === "revoke")
|
|
86
|
+
rules.delete(operation.id);
|
|
87
|
+
else {
|
|
88
|
+
const rule = rules.get(operation.id);
|
|
89
|
+
if (rule)
|
|
90
|
+
rule.enabled = operation.enabled;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return { policy, rules, nonces };
|
|
94
|
+
}
|
|
95
|
+
const queues = new Map();
|
|
96
|
+
async function locked(root, work) {
|
|
97
|
+
const key = path.resolve(root), previous = queues.get(key) ?? Promise.resolve();
|
|
98
|
+
const next = previous.catch(() => { }).then(async () => {
|
|
99
|
+
await mkdir(key, { recursive: true, mode: 0o700 });
|
|
100
|
+
const release = tryFileLock(policyPath(key));
|
|
101
|
+
if (!release)
|
|
102
|
+
throw new BridgeError(409, "Approval rules are busy. Try again.");
|
|
103
|
+
try {
|
|
104
|
+
return await work();
|
|
105
|
+
}
|
|
106
|
+
finally {
|
|
107
|
+
release();
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
queues.set(key, next);
|
|
111
|
+
try {
|
|
112
|
+
return await next;
|
|
113
|
+
}
|
|
114
|
+
finally {
|
|
115
|
+
if (queues.get(key) === next)
|
|
116
|
+
queues.delete(key);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
export async function listApprovalRules(root = bridgeRoot(), pairedKey) {
|
|
120
|
+
try {
|
|
121
|
+
const pairedOwner = pairedKey ? createHash("sha256").update(Buffer.from(pairedKey, "base64")).digest("hex") : undefined;
|
|
122
|
+
return [...(await readPolicy(root)).rules.values()].map(rule => ({ ...rule,
|
|
123
|
+
signerFingerprint: "SHA256:" + Buffer.from(rule.owner, "hex").toString("base64").replace(/=+$/, ""),
|
|
124
|
+
matchesPairedKey: rule.owner === pairedOwner,
|
|
125
|
+
}));
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
throw new BridgeError(409, "Approval rules could not be loaded. Existing agent permissions and phone approvals continue unchanged.");
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/** The signed operations remain on disk and are verified again at every decision. */
|
|
132
|
+
export async function changeApprovalRule(input, method, root = bridgeRoot()) {
|
|
133
|
+
const envelope = envelopeSchema.parse(input), proof = verified(envelope, await ownerKeys());
|
|
134
|
+
if ((method === "DELETE" ? proof.operation.operation !== "revoke" : proof.operation.operation === "revoke") || !Number.isFinite(Date.parse(proof.operation.at)) || Math.abs(Date.now() - Date.parse(proof.operation.at)) > 300_000)
|
|
135
|
+
throw forbidden();
|
|
136
|
+
return locked(root, async () => {
|
|
137
|
+
const { policy, rules, nonces } = await readPolicy(root);
|
|
138
|
+
if (nonces.has(proof.operation.nonce))
|
|
139
|
+
throw new BridgeError(409, "This change has already been applied.");
|
|
140
|
+
if (proof.operation.operation === "add" && rules.size >= 128)
|
|
141
|
+
throw new BridgeError(409, "Revoke a rule before adding another.");
|
|
142
|
+
if (proof.operation.operation !== "add" && !rules.has(proof.operation.id))
|
|
143
|
+
throw new BridgeError(409, "This rule is no longer listed.");
|
|
144
|
+
if (policy.operations.length >= 2048)
|
|
145
|
+
throw new BridgeError(409, "Approval policy history is full; owner maintenance is required.");
|
|
146
|
+
policy.operations.push(envelope);
|
|
147
|
+
const bytes = JSON.stringify(policy);
|
|
148
|
+
if (Buffer.byteLength(bytes) > 2_097_152)
|
|
149
|
+
throw new BridgeError(409, "Approval policy history is full; owner maintenance is required.");
|
|
150
|
+
await atomic(policyPath(root), bytes);
|
|
151
|
+
return { ok: true };
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
/** Bind project scope to the main repository, including linked worktrees. */
|
|
155
|
+
export async function approvalRuleContext(cwd, harness, session) {
|
|
156
|
+
if (!path.isAbsolute(cwd))
|
|
157
|
+
return undefined;
|
|
158
|
+
try {
|
|
159
|
+
const directories = (await git(cwd, "rev-parse", "--path-format=absolute", "--git-common-dir", "--show-toplevel")).trim().split(/\r?\n/);
|
|
160
|
+
if (directories.length !== 2)
|
|
161
|
+
return undefined;
|
|
162
|
+
const [common, checkout, directory] = await Promise.all([...directories, cwd].map(value => realpath(value)));
|
|
163
|
+
const relative = path.relative(checkout, directory);
|
|
164
|
+
if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative))
|
|
165
|
+
return undefined;
|
|
166
|
+
if (path.basename(common) !== ".git")
|
|
167
|
+
return undefined;
|
|
168
|
+
// A writable .git pointer alone is not proof that a folder belongs to this repository.
|
|
169
|
+
const listed = (await git(common, "worktree", "list", "--porcelain", "-z")).split("\0")
|
|
170
|
+
.filter(field => field.startsWith("worktree ")).map(field => field.slice("worktree ".length));
|
|
171
|
+
const registered = await Promise.all(listed.map(directory => realpath(directory).catch(() => undefined)));
|
|
172
|
+
if (!registered.includes(checkout))
|
|
173
|
+
return undefined;
|
|
174
|
+
return { project: path.dirname(common), harness: scopeSchema.shape.harness.unwrap().parse(harness), session, computer: hostname() };
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
return undefined;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
function commandMatches(rule, command) {
|
|
181
|
+
if (rule.match === "exact")
|
|
182
|
+
return command === rule.command;
|
|
183
|
+
if (rule.match === "prefix")
|
|
184
|
+
return command === rule.command || command.startsWith(rule.command + " ");
|
|
185
|
+
// Bound pattern/command sizes avoid unbounded glob backtracking.
|
|
186
|
+
let i = 0, j = 0, star = -1, retry = 0;
|
|
187
|
+
while (j < command.length) {
|
|
188
|
+
if (i < rule.command.length && (rule.command[i] === "?" || rule.command[i] === command[j])) {
|
|
189
|
+
i++;
|
|
190
|
+
j++;
|
|
191
|
+
}
|
|
192
|
+
else if (rule.command[i] === "*") {
|
|
193
|
+
star = i++;
|
|
194
|
+
retry = j;
|
|
195
|
+
}
|
|
196
|
+
else if (star !== -1) {
|
|
197
|
+
i = star + 1;
|
|
198
|
+
j = ++retry;
|
|
199
|
+
}
|
|
200
|
+
else
|
|
201
|
+
return false;
|
|
202
|
+
}
|
|
203
|
+
while (rule.command[i] === "*")
|
|
204
|
+
i++;
|
|
205
|
+
return i === rule.command.length;
|
|
206
|
+
}
|
|
207
|
+
/** Rules can only restrict a request the harness has already raised. Invalid policy
|
|
208
|
+
* falls back to that ordinary approval path; Settings reports the load error. */
|
|
209
|
+
export async function approvalRuleEffect(tool, input, context, root = bridgeRoot(), knownScope = {}) {
|
|
210
|
+
const command = object(input).command;
|
|
211
|
+
if (tool !== "Bash" || typeof command !== "string")
|
|
212
|
+
return undefined;
|
|
213
|
+
try {
|
|
214
|
+
const { rules } = await readPolicy(root), now = Date.now();
|
|
215
|
+
const applicable = [...rules.values()].filter(rule => rule.enabled && rule.tool === tool && (!rule.until || Date.parse(rule.until) > now)
|
|
216
|
+
&& Object.entries(knownScope).every(([key, value]) => !rule.scope[key] || rule.scope[key] === value)
|
|
217
|
+
&& commandMatches(rule, command));
|
|
218
|
+
if (!applicable.length)
|
|
219
|
+
return undefined;
|
|
220
|
+
const resolved = typeof context === "function" ? await context() : context;
|
|
221
|
+
if (!resolved)
|
|
222
|
+
return undefined;
|
|
223
|
+
const matches = applicable.filter(rule => Object.entries(rule.scope).every(([key, value]) => resolved[key] === value));
|
|
224
|
+
if (matches.some(rule => rule.effect === "deny"))
|
|
225
|
+
return "deny";
|
|
226
|
+
return matches.some(rule => rule.effect === "always-ask") ? "always-ask" : undefined;
|
|
227
|
+
}
|
|
228
|
+
catch {
|
|
229
|
+
return undefined;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
@@ -99,8 +99,7 @@ declare const fileSchema: z.ZodObject<{
|
|
|
99
99
|
}>>;
|
|
100
100
|
}, z.core.$strict>;
|
|
101
101
|
export type AuthorityFile = z.infer<typeof fileSchema>;
|
|
102
|
-
/** Used until the owner first writes the policy:
|
|
103
|
-
* and Mina is go for App Store work (the owner's word, 2026-09-29). */
|
|
102
|
+
/** Used until the owner first writes the policy: no project is restricted. */
|
|
104
103
|
export declare const DEFAULT_AUTHORITY: AuthorityFile;
|
|
105
104
|
/** The permission ceiling of a project with any ask-first action that names none. */
|
|
106
105
|
export declare const ASK_FIRST_PERMISSION_MODE: PermissionMode;
|
package/dist/bridge/authority.js
CHANGED
|
@@ -31,13 +31,8 @@ const fileSchema = z.object({
|
|
|
31
31
|
updatedAt: z.string().datetime({ offset: true }).optional(),
|
|
32
32
|
updatedBy: writer.optional(),
|
|
33
33
|
}).strict();
|
|
34
|
-
/** Used until the owner first writes the policy:
|
|
35
|
-
|
|
36
|
-
export const DEFAULT_AUTHORITY = { projects: {
|
|
37
|
-
hub: { default: "ask" },
|
|
38
|
-
safety: { default: "ask" },
|
|
39
|
-
mina: { actions: { "app-store": "go" }, note: "Owner authorized App Store work on 2026-09-29." },
|
|
40
|
-
} };
|
|
34
|
+
/** Used until the owner first writes the policy: no project is restricted. */
|
|
35
|
+
export const DEFAULT_AUTHORITY = { projects: {} };
|
|
41
36
|
/** The permission ceiling of a project with any ask-first action that names none. */
|
|
42
37
|
export const ASK_FIRST_PERMISSION_MODE = "auto-edits";
|
|
43
38
|
const authorityFile = (root = bridgeRoot()) => path.join(root, "authority.yaml");
|
package/dist/bridge/changes.d.ts
CHANGED
|
@@ -11,6 +11,8 @@ export declare const changedFileSchema: z.ZodObject<{
|
|
|
11
11
|
added: z.ZodNumber;
|
|
12
12
|
removed: z.ZodNumber;
|
|
13
13
|
redacted: z.ZodOptional<z.ZodBoolean>;
|
|
14
|
+
binary: z.ZodOptional<z.ZodBoolean>;
|
|
15
|
+
truncated: z.ZodOptional<z.ZodBoolean>;
|
|
14
16
|
}, z.core.$strip>;
|
|
15
17
|
export type ChangedFile = z.infer<typeof changedFileSchema>;
|
|
16
18
|
export declare const secretName: (file: string) => boolean;
|
|
@@ -33,6 +35,8 @@ export declare class ToolChanges {
|
|
|
33
35
|
private results;
|
|
34
36
|
private controllers;
|
|
35
37
|
private claims;
|
|
38
|
+
private failures;
|
|
39
|
+
private failed;
|
|
36
40
|
/** A hook callback's wall-clock cap on Git work; past it the call records
|
|
37
41
|
* no change. Tests about what is captured raise it, since a loaded Windows
|
|
38
42
|
* runner's Git can take longer than a person's machine ever does. */
|
package/dist/bridge/changes.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { checkoutGitEnv } from "./projects.js";
|
|
2
2
|
import { execFile } from "node:child_process";
|
|
3
3
|
import { appendFile, copyFile, mkdir, mkdtemp, readdir, readFile, realpath, rm, stat, unlink, utimes } from "node:fs/promises";
|
|
4
4
|
import { homeDir } from "../home-paths.js";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
import { promisify } from "node:util";
|
|
7
|
-
import { bridgeRoot, object } from "./protocol.js";
|
|
7
|
+
import { BridgeError, bridgeRoot, object } from "./protocol.js";
|
|
8
8
|
import { z } from "zod";
|
|
9
9
|
import { ProcessPool } from "./limits.js";
|
|
10
10
|
import { phrenStoreRoot } from "./transcripts.js";
|
|
@@ -14,7 +14,7 @@ const exec = promisify(execFile);
|
|
|
14
14
|
* tree before the call and after it. `root` is the repository; `path` is
|
|
15
15
|
* relative to it. */
|
|
16
16
|
export const changedFileSchema = z.object({ root: z.string(), path: z.string(), status: z.string(), patch: z.string(),
|
|
17
|
-
added: z.number().int().nonnegative(), removed: z.number().int().nonnegative(), redacted: z.boolean().optional() });
|
|
17
|
+
added: z.number().int().nonnegative(), removed: z.number().int().nonnegative(), redacted: z.boolean().optional(), binary: z.boolean().optional(), truncated: z.boolean().optional() });
|
|
18
18
|
const changeRowSchema = z.object({ toolUseId: z.string(), files: z.array(changedFileSchema) });
|
|
19
19
|
export const secretName = (file) => /^(?:\.env(?:\..*)?|.*\.(?:pem|key|p12|pfx|keychain-db|tfstate)|id_rsa.*|id_ed25519.*|(?:.*\.)?credentials\.json|\.netrc|\.npmrc|\.pypirc)$/i.test(path.basename(file));
|
|
20
20
|
const gitPool = new ProcessPool(2);
|
|
@@ -52,7 +52,7 @@ export function namedPaths(command, input = {}) {
|
|
|
52
52
|
}
|
|
53
53
|
async function git(cwd, args, extra = {}, signal) {
|
|
54
54
|
return gitPool.run(signal, async () => (countGit("changes"), await exec("git", ["-C", cwd, "--no-pager", ...args], {
|
|
55
|
-
signal, timeout: 10_000, maxBuffer: 8_388_608, env:
|
|
55
|
+
signal, timeout: 10_000, maxBuffer: 8_388_608, env: { ...checkoutGitEnv(), ...extra },
|
|
56
56
|
})).stdout);
|
|
57
57
|
}
|
|
58
58
|
/** The repository holding `target` (a file, a folder, or something not yet
|
|
@@ -72,10 +72,12 @@ async function repositoryOf(target, cwd, home = homeDir(), signal) {
|
|
|
72
72
|
return undefined;
|
|
73
73
|
const dir = (await stat(real)).isDirectory() ? real : path.dirname(real);
|
|
74
74
|
try {
|
|
75
|
-
return await realpath((await git(dir, ["rev-parse", "--show-toplevel"], {}, signal)).
|
|
75
|
+
return await realpath((await git(dir, ["rev-parse", "--show-toplevel"], {}, signal)).replace(/\r?\n$/, ""));
|
|
76
76
|
}
|
|
77
|
-
catch {
|
|
78
|
-
|
|
77
|
+
catch (error) {
|
|
78
|
+
if (/not a git repository/.test(String(error.stderr)))
|
|
79
|
+
return undefined;
|
|
80
|
+
throw error;
|
|
79
81
|
}
|
|
80
82
|
}
|
|
81
83
|
async function scratchTree(root, signal) {
|
|
@@ -99,10 +101,11 @@ async function treeHash(root, env, signal) {
|
|
|
99
101
|
const index = path.resolve(root, (await git(root, ["rev-parse", "--git-path", "index"], {}, signal)).trim());
|
|
100
102
|
const temp = env.GIT_INDEX_FILE;
|
|
101
103
|
await unlink(temp).catch(() => undefined);
|
|
102
|
-
await copyFile(index, temp).catch(
|
|
104
|
+
await copyFile(index, temp).catch(error => { if (error.code !== "ENOENT")
|
|
105
|
+
throw error; });
|
|
103
106
|
// Force content checks for files rewritten to the same size in one instant.
|
|
104
107
|
await utimes(temp, 1, 1).catch(() => undefined);
|
|
105
|
-
await git(root, ["add", "-A", "--
|
|
108
|
+
await git(root, ["add", "-A", "--", "."], env, signal);
|
|
106
109
|
return (await git(root, ["write-tree"], env, signal)).trim();
|
|
107
110
|
}
|
|
108
111
|
const NO_DIFF = ["diff", "--no-ext-diff", "--no-textconv", "--no-color"];
|
|
@@ -111,21 +114,25 @@ async function treeDiff(root, before, after, env, signal) {
|
|
|
111
114
|
return [];
|
|
112
115
|
const records = (await git(root, [...NO_DIFF, "--name-status", "-z", before, after], env, signal)).split("\0");
|
|
113
116
|
const files = [];
|
|
114
|
-
for (let i = 0; i + 1 < records.length
|
|
117
|
+
for (let i = 0; i + 1 < records.length; i += 2) {
|
|
115
118
|
const status = records[i].slice(0, 1), original = records[i + 1];
|
|
116
119
|
let file = original;
|
|
117
120
|
if (/[RC]/.test(status))
|
|
118
121
|
file = records[++i + 1]; // the new name follows the old
|
|
119
122
|
if (!file)
|
|
120
123
|
continue;
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
const
|
|
124
|
-
|
|
125
|
-
|
|
124
|
+
if (files.length >= 40)
|
|
125
|
+
throw new BridgeError(413, "This tool changed more than 40 files; open repository Changes for the full status.", { code: "git-output-limit" });
|
|
126
|
+
const specs = [...new Set([original, file])].map(name => `:(literal)${name}`);
|
|
127
|
+
const counts = (await git(root, [...NO_DIFF, "--numstat", before, after, "--", ...specs], env, signal)).split("\t");
|
|
128
|
+
const binary = counts[0] === "-" || counts[1] === "-";
|
|
129
|
+
const redacted = secretName(original) || secretName(file) || binary;
|
|
130
|
+
let patch = redacted ? "" : await git(root, [...NO_DIFF, before, after, "--", ...specs], env, signal);
|
|
131
|
+
const truncated = patch.length > 200_000;
|
|
132
|
+
if (truncated)
|
|
126
133
|
patch = patch.slice(0, 200_000) + "\n… (truncated)\n";
|
|
127
134
|
const added = Number(counts[0]) || 0, removed = Number(counts[1]) || 0;
|
|
128
|
-
files.push({ root, path: file, status, patch, added, removed, ...(redacted ? { redacted: true } : {}) });
|
|
135
|
+
files.push({ root, path: file, status, patch, added, removed, binary, truncated, ...(redacted ? { redacted: true } : {}) });
|
|
129
136
|
}
|
|
130
137
|
return files;
|
|
131
138
|
}
|
|
@@ -192,6 +199,14 @@ export class ToolChanges {
|
|
|
192
199
|
results = new Map();
|
|
193
200
|
controllers = new Set();
|
|
194
201
|
claims = [];
|
|
202
|
+
failures = new Map();
|
|
203
|
+
failed(key, error) {
|
|
204
|
+
const failure = error instanceof BridgeError ? error : new BridgeError(503, "Git change capture failed or timed out. Refresh repository Changes for the current status.", { code: "git-capture-failed" });
|
|
205
|
+
if (this.failures.size >= 512)
|
|
206
|
+
this.failures.delete(this.failures.keys().next().value);
|
|
207
|
+
this.failures.set(key, failure);
|
|
208
|
+
return failure;
|
|
209
|
+
}
|
|
195
210
|
/** A hook callback's wall-clock cap on Git work; past it the call records
|
|
196
211
|
* no change. Tests about what is captured raise it, since a loaded Windows
|
|
197
212
|
* runner's Git can take longer than a person's machine ever does. */
|
|
@@ -236,6 +251,7 @@ export class ToolChanges {
|
|
|
236
251
|
this.snapshots.set(key, snapshot);
|
|
237
252
|
try {
|
|
238
253
|
await this.budget(async (signal) => {
|
|
254
|
+
await realpath(cwd); // A vanished checkout must not resolve to its parent repository.
|
|
239
255
|
const roots = new Set();
|
|
240
256
|
for (const target of [cwd, phrenStoreRoot(), ...namedPaths(command, input)]) {
|
|
241
257
|
signal.throwIfAborted();
|
|
@@ -246,12 +262,7 @@ export class ToolChanges {
|
|
|
246
262
|
roots.add(root);
|
|
247
263
|
}
|
|
248
264
|
for (const root of roots) {
|
|
249
|
-
|
|
250
|
-
snapshot.trees.set(root, await scratchTree(root, signal));
|
|
251
|
-
}
|
|
252
|
-
catch {
|
|
253
|
-
signal.throwIfAborted();
|
|
254
|
-
}
|
|
265
|
+
snapshot.trees.set(root, await scratchTree(root, signal));
|
|
255
266
|
}
|
|
256
267
|
signal.throwIfAborted();
|
|
257
268
|
});
|
|
@@ -273,7 +284,8 @@ export class ToolChanges {
|
|
|
273
284
|
}, 30 * 60_000);
|
|
274
285
|
snapshot.expiry.unref();
|
|
275
286
|
}
|
|
276
|
-
catch {
|
|
287
|
+
catch (error) {
|
|
288
|
+
this.failed(key, error);
|
|
277
289
|
if (this.snapshots.get(key) === snapshot)
|
|
278
290
|
this.snapshots.delete(key);
|
|
279
291
|
await this.discard(snapshot);
|
|
@@ -315,7 +327,14 @@ export class ToolChanges {
|
|
|
315
327
|
return;
|
|
316
328
|
}
|
|
317
329
|
snapshot.result ??= this.compute(snapshot);
|
|
318
|
-
|
|
330
|
+
let files;
|
|
331
|
+
try {
|
|
332
|
+
files = await snapshot.result;
|
|
333
|
+
}
|
|
334
|
+
catch (error) {
|
|
335
|
+
this.snapshots.delete(key);
|
|
336
|
+
throw this.failed(key, error);
|
|
337
|
+
}
|
|
319
338
|
if (this.snapshots.get(key) === snapshot) {
|
|
320
339
|
this.snapshots.delete(key);
|
|
321
340
|
await this.record(conversation, toolUseId, files);
|
|
@@ -326,12 +345,7 @@ export class ToolChanges {
|
|
|
326
345
|
return await this.budget(async (signal) => {
|
|
327
346
|
const files = [];
|
|
328
347
|
for (const [root, before] of snapshot.trees) {
|
|
329
|
-
|
|
330
|
-
files.push(...await treeDiff(root, before.hash, await treeHash(root, before.env, signal), before.env, signal));
|
|
331
|
-
}
|
|
332
|
-
catch {
|
|
333
|
-
signal.throwIfAborted();
|
|
334
|
-
}
|
|
348
|
+
files.push(...await treeDiff(root, before.hash, await treeHash(root, before.env, signal), before.env, signal));
|
|
335
349
|
}
|
|
336
350
|
// A file another agent's edit named during this call is its change,
|
|
337
351
|
// not this call's, even though it landed inside the same window.
|
|
@@ -349,9 +363,6 @@ export class ToolChanges {
|
|
|
349
363
|
return kept;
|
|
350
364
|
});
|
|
351
365
|
}
|
|
352
|
-
catch {
|
|
353
|
-
return [];
|
|
354
|
-
}
|
|
355
366
|
finally {
|
|
356
367
|
await this.discard(snapshot);
|
|
357
368
|
}
|
|
@@ -407,6 +418,9 @@ export class ToolChanges {
|
|
|
407
418
|
return !!snapshot && !snapshot.result && Date.now() - snapshot.at < PENDING_FOR;
|
|
408
419
|
},
|
|
409
420
|
changes: async (toolUseId) => {
|
|
421
|
+
const failure = this.failures.get(`${conversation}\0${toolUseId}`);
|
|
422
|
+
if (failure)
|
|
423
|
+
throw failure;
|
|
410
424
|
await this.after(conversation, toolUseId);
|
|
411
425
|
const known = (await this.load(conversation)).files.get(toolUseId);
|
|
412
426
|
return known?.length ? known : undefined;
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
import { stripTerminal } from "../terminal-text.js";
|
|
8
8
|
const MAX_SUGGESTION = 500;
|
|
9
9
|
// The input box sits between two rules; the upper one can carry the session
|
|
10
|
-
// title ("─────
|
|
10
|
+
// title ("───── Docs refresh ─").
|
|
11
11
|
const rule = (line) => /^[─━═]{3,}/.test(line.trim());
|
|
12
12
|
// Dim text Claude also draws in the empty input that is not a prediction: the
|
|
13
13
|
// first-turn example, the queued-message hints and a teammate's name.
|
|
@@ -2,3 +2,7 @@
|
|
|
2
2
|
* same Mac as its hostname, the hostname's first label and its Bonjour name.
|
|
3
3
|
* The Hook reports them in /v1/health so a peer can recognize this computer. */
|
|
4
4
|
export declare function localNames(): string[];
|
|
5
|
+
/** The name a schedule should carry for this computer: the Sharing name on a
|
|
6
|
+
* Mac (the hostname there follows the network, "Mac" or "Mac.example.net"),
|
|
7
|
+
* otherwise the hostname. */
|
|
8
|
+
export declare function stableComputerName(): string;
|
|
@@ -11,6 +11,25 @@ export function localNames() {
|
|
|
11
11
|
names.push(execFileSync("scutil", ["--get", "LocalHostName"], { encoding: "utf8", timeout: 1_000 }).trim());
|
|
12
12
|
}
|
|
13
13
|
catch { /* No Bonjour name set: the hostname forms above still match. */ }
|
|
14
|
+
// The name people see in Sharing ("Sam’s Mac mini"), which the phone and schedules use.
|
|
15
|
+
try {
|
|
16
|
+
names.push(execFileSync("scutil", ["--get", "ComputerName"], { encoding: "utf8", timeout: 1_000 }).trim());
|
|
17
|
+
}
|
|
18
|
+
catch { /* No Sharing name set. */ }
|
|
14
19
|
}
|
|
15
20
|
return [...new Set(names.filter(Boolean))];
|
|
16
21
|
}
|
|
22
|
+
/** The name a schedule should carry for this computer: the Sharing name on a
|
|
23
|
+
* Mac (the hostname there follows the network, "Mac" or "Mac.example.net"),
|
|
24
|
+
* otherwise the hostname. */
|
|
25
|
+
export function stableComputerName() {
|
|
26
|
+
if (process.platform === "darwin") {
|
|
27
|
+
try {
|
|
28
|
+
const name = execFileSync("scutil", ["--get", "ComputerName"], { encoding: "utf8", timeout: 1_000 }).trim();
|
|
29
|
+
if (name)
|
|
30
|
+
return name;
|
|
31
|
+
}
|
|
32
|
+
catch { /* No Sharing name set: fall back to the hostname. */ }
|
|
33
|
+
}
|
|
34
|
+
return hostname();
|
|
35
|
+
}
|