passcontrol 1.7.1 → 1.8.0
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/bin/passcontrol.mjs +51 -0
- package/cli/codex-hooks.mjs +2 -2
- package/cli/memory-custody-sidecar.d.mts +19 -0
- package/cli/memory-custody-sidecar.mjs +470 -0
- package/cli/memory-custody.d.mts +24 -0
- package/cli/memory-custody.mjs +444 -0
- package/cli/memory-inventory.d.mts +15 -0
- package/cli/memory-inventory.mjs +390 -0
- package/cli/memory-review.d.mts +3 -0
- package/cli/memory-review.mjs +65 -0
- package/cli/menu.mjs +1 -0
- package/cli/mission-tools.d.mts +27 -0
- package/cli/mission-tools.mjs +373 -0
- package/cli/proxy-policy.mjs +1 -1
- package/cli/sidecar.mjs +176 -5
- package/cli/subscription-gate.mjs +32 -10
- package/cli/tool-gate.mjs +45 -3
- package/cli/tool-rules.d.mts +5 -1
- package/cli/tool-rules.mjs +29 -10
- package/cli/tripwire-scan.d.mts +20 -0
- package/cli/tripwire-scan.mjs +279 -0
- package/cli/tripwire-sidecar.d.mts +10 -0
- package/cli/tripwire-sidecar.mjs +84 -0
- package/cli/tripwires.d.mts +21 -0
- package/cli/tripwires.mjs +208 -0
- package/cli/visa-client.mjs +3 -0
- package/cli/watch-feed.mjs +1 -1
- package/package.json +1 -1
- package/sdk/passcontrol.js +8 -1
package/bin/passcontrol.mjs
CHANGED
|
@@ -71,6 +71,7 @@ import {
|
|
|
71
71
|
SERVICE_ENV,
|
|
72
72
|
supportsWrite,
|
|
73
73
|
} from "../cli/presets.mjs";
|
|
74
|
+
import { plantTripwires, removeTripwires, tripwirePlacementChoices } from "../cli/tripwires.mjs";
|
|
74
75
|
import { importCompletionMessage, noAgentCreateMessage } from "../cli/workspace-import-report.mjs";
|
|
75
76
|
import { announcesAfter, checkForUpdate, fetchLatest, REGISTRY_URL } from "../cli/update-check.mjs";
|
|
76
77
|
import {
|
|
@@ -133,6 +134,7 @@ import {
|
|
|
133
134
|
} from "../cli/instance-key.mjs";
|
|
134
135
|
import { FAILURE_REASONS, verifyAgentToken, verifyReceipt, verifySession, verifyStatement } from "../cli/verify.mjs";
|
|
135
136
|
import { compareProtocolSets } from "../cli/protocols.mjs";
|
|
137
|
+
import { memoryReviewCommand } from "../cli/memory-review.mjs";
|
|
136
138
|
import { defaultAllowedModelForProvider } from "../cli/integration-defaults.mjs";
|
|
137
139
|
import {
|
|
138
140
|
PASSPORT_KEY_STORAGE_OS,
|
|
@@ -274,6 +276,8 @@ ${heading("Manage")}
|
|
|
274
276
|
${cmd} statusline [--port 8788] one line for Claude Code's status line (configure claude-code --statusline)
|
|
275
277
|
${cmd} statusline --panel [--session <id>] the longer view the Claude Code plugin's /passcontrol shows
|
|
276
278
|
${cmd} watch [--port 8788] a live board of each call the sidecar relays (read-only)
|
|
279
|
+
${cmd} memory review [--port 8788] [--codex]
|
|
280
|
+
show the memory entries waiting at customs, with their text from this machine
|
|
277
281
|
${cmd} kill on|off toggle the tenant kill switch
|
|
278
282
|
${cmd} export [--out FILE] save a workspace configuration snapshot
|
|
279
283
|
${cmd} import <file> [--confirm IMPORT]
|
|
@@ -291,6 +295,8 @@ ${heading("Integrate")}
|
|
|
291
295
|
a ChatGPT plan in Codex: stops and tool rules
|
|
292
296
|
${cmd} configure claude-code --write --agent-note
|
|
293
297
|
tell the agent its own limits, only when they change
|
|
298
|
+
${cmd} configure tripwires --agent <id> [--places ${tripwirePlacementChoices()}] [--dry-run] [--remove]
|
|
299
|
+
plant decoy keys for one agent outside any repo (rerun rotates)
|
|
294
300
|
integrations: ${integrationChoices()}
|
|
295
301
|
|
|
296
302
|
${heading("Trust")}
|
|
@@ -3085,8 +3091,46 @@ function configureMcpClient(integration, opts = {}) {
|
|
|
3085
3091
|
ok(`wrote ${target}`);
|
|
3086
3092
|
}
|
|
3087
3093
|
|
|
3094
|
+
// ── Tripwire decoys (idea 12) ───────────────────────────────────────────────
|
|
3095
|
+
//
|
|
3096
|
+
// `configure tripwires` plants decoy Direct Agent Keys for ONE agent outside any repo,
|
|
3097
|
+
// registers only their digests with the gateway, and keeps a digest manifest the sidecar
|
|
3098
|
+
// reads. Re-running rotates; --remove retires them and deletes the files this wrote. The
|
|
3099
|
+
// placements and their order come from cli/tripwires.mjs, never typed here.
|
|
3100
|
+
async function tripwiresCommand(opts = {}) {
|
|
3101
|
+
const agentId = typeof opts.agent === "string" ? opts.agent : "";
|
|
3102
|
+
if (!/^[0-9a-f-]{36}$/i.test(agentId)) {
|
|
3103
|
+
throw new Error(`Usage: passcontrol configure tripwires --agent <agent-id> [--places ${tripwirePlacementChoices()}] [--dry-run] [--remove]`);
|
|
3104
|
+
}
|
|
3105
|
+
if (opts.remove) {
|
|
3106
|
+
const r = await removeTripwires({ agentId, retire: () => api("DELETE", `/agents/${agentId}/tripwires`) });
|
|
3107
|
+
ok(`retired this agent's decoys at the gateway (they stay armed 30 days in case a copy is still out there)`);
|
|
3108
|
+
for (const file of r.removed) step(`removed ${file}`);
|
|
3109
|
+
for (const file of r.kept) warn(`kept ${file}: it no longer holds the decoy this tool wrote`);
|
|
3110
|
+
return;
|
|
3111
|
+
}
|
|
3112
|
+
const origin = requireControlGateway(config);
|
|
3113
|
+
const placements = typeof opts.places === "string" ? opts.places.split(",").map((p) => p.trim()).filter(Boolean) : undefined;
|
|
3114
|
+
const r = await plantTripwires({
|
|
3115
|
+
agentId,
|
|
3116
|
+
origin,
|
|
3117
|
+
placements,
|
|
3118
|
+
dryRun: Boolean(opts.dryRun),
|
|
3119
|
+
register: (decoys, replace, retireDigests) =>
|
|
3120
|
+
api("POST", `/agents/${agentId}/tripwires`, replace ? { decoys, replace, retire_digests: retireDigests } : { decoys, replace }),
|
|
3121
|
+
});
|
|
3122
|
+
for (const p of r.planted) step(`${r.dryRun ? "would plant" : "planted"} ${p.placement}: ${p.path}`);
|
|
3123
|
+
if (r.dryRun) return;
|
|
3124
|
+
ok(r.rotated ? "rotated this agent's tripwire decoys" : "planted tripwire decoys for this agent");
|
|
3125
|
+
// Plain about what this is and is not (research/idea-12-tripwire/VERDICT.md).
|
|
3126
|
+
step("A decoy presented to PassControl suspends the agent it names at once. A decoy seen in an agent's");
|
|
3127
|
+
step("traffic is an alert. Silence proves nothing: an agent can avoid, encode or exfiltrate a decoy unobserved.");
|
|
3128
|
+
step("Your own scanners may flag these files; that is expected. Do not copy them into a repository.");
|
|
3129
|
+
}
|
|
3130
|
+
|
|
3088
3131
|
async function configureCommand(rest, opts = {}) {
|
|
3089
3132
|
const integration = String(rest[0] ?? "").toLowerCase();
|
|
3133
|
+
if (integration === "tripwires") return tripwiresCommand(opts);
|
|
3090
3134
|
if (!integration) {
|
|
3091
3135
|
throw new Error(
|
|
3092
3136
|
`Usage: passcontrol configure <${integrationChoices()}> [--write] [--force]`
|
|
@@ -4691,6 +4735,13 @@ async function main(argv = process.argv.slice(2), runtime = {}) {
|
|
|
4691
4735
|
case "seal":
|
|
4692
4736
|
await sealCommand(commandRest, opts);
|
|
4693
4737
|
break;
|
|
4738
|
+
case "memory": {
|
|
4739
|
+
// Idea 13. Shows only; the decision is the owner's, on the agent's page.
|
|
4740
|
+
if (commandRest[0] !== "review") throw new Error("Usage: passcontrol memory review [--port 8788] [--codex]");
|
|
4741
|
+
const port = Number(opts.port ?? process.env.SIDECAR_PORT ?? 8788);
|
|
4742
|
+
await memoryReviewCommand({ sidecarUrl: process.env.PASSCONTROL_SIDECAR_URL || `http://127.0.0.1:${port}`, client: opts.codex ? "codex" : "claude-code" });
|
|
4743
|
+
break;
|
|
4744
|
+
}
|
|
4694
4745
|
case "kill":
|
|
4695
4746
|
await killCommand(commandRest);
|
|
4696
4747
|
break;
|
package/cli/codex-hooks.mjs
CHANGED
|
@@ -244,7 +244,7 @@ export async function runCodexHook({ input, port, fetchImpl = fetch, promptTimeo
|
|
|
244
244
|
timer = setTimeout(() => { controller.abort(); resolve(""); }, postToolTimeoutMs);
|
|
245
245
|
});
|
|
246
246
|
const relay = async () => {
|
|
247
|
-
await fetchImpl(`http://127.0.0.1:${port}${HOOK_PATH}`, {
|
|
247
|
+
await fetchImpl(`http://127.0.0.1:${port}${HOOK_PATH}?client=codex`, {
|
|
248
248
|
method: "POST", headers: { "content-type": "application/json" }, body: input, signal: controller.signal,
|
|
249
249
|
});
|
|
250
250
|
return "";
|
|
@@ -261,7 +261,7 @@ export async function runCodexHook({ input, port, fetchImpl = fetch, promptTimeo
|
|
|
261
261
|
const timer = setTimeout(() => controller.abort(), tool ? toolTimeoutMs : promptTimeoutMs);
|
|
262
262
|
const warn = (why) => JSON.stringify({ systemMessage: `PassControl: ${why}, so this goes ahead unchecked.` });
|
|
263
263
|
try {
|
|
264
|
-
const url = `http://127.0.0.1:${port}${HOOK_PATH}${tool ?
|
|
264
|
+
const url = `http://127.0.0.1:${port}${HOOK_PATH}?client=codex${tool ? `&t=${CODEX_TOOL_HOOK_TIMEOUT_S}` : ""}`;
|
|
265
265
|
const response = await fetchImpl(url, {
|
|
266
266
|
method: "POST",
|
|
267
267
|
headers: { "content-type": "application/json" },
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export interface MemoryCustody {
|
|
2
|
+
hook(input: Record<string, unknown>, options?: { client?: "claude-code" | "codex"; api?: boolean }): Promise<void>;
|
|
3
|
+
/** In withhold mode: the request body with pending memory cut out, or null when unchanged. */
|
|
4
|
+
modelRequest(sessionId: string, body: unknown): Promise<any>;
|
|
5
|
+
fallback(sessionId: string | null | undefined, body: unknown): any;
|
|
6
|
+
mode(): string;
|
|
7
|
+
setView(view: unknown): void;
|
|
8
|
+
state(sessionId?: string): "off" | "clear" | "held";
|
|
9
|
+
review(cwd: string, client?: "claude-code" | "codex"): Promise<{ state: string; items: Record<string, unknown>[] }>;
|
|
10
|
+
_debug: { sessions: Map<string, unknown>; roots: Map<string, unknown> };
|
|
11
|
+
}
|
|
12
|
+
export function createMemoryCustody(options: {
|
|
13
|
+
send: (body: Record<string, unknown>) => Promise<{ status: number; body: any }>;
|
|
14
|
+
env?: Record<string, string | undefined>;
|
|
15
|
+
now?: () => number;
|
|
16
|
+
salt?: string | null;
|
|
17
|
+
onWarn?: (message: string) => void;
|
|
18
|
+
}): MemoryCustody;
|
|
19
|
+
export function workspaceRoot(cwd: string): string;
|
|
@@ -0,0 +1,470 @@
|
|
|
1
|
+
// Idea 13: the sidecar's half of memory custody. It sees the hooks Claude Code and Codex
|
|
2
|
+
// already send (and, in API mode, every model request), and turns them into the three
|
|
3
|
+
// ledger calls (observe, record, check) at POST /api/v1/memory-custody. Only hashes,
|
|
4
|
+
// file kinds and outside-content kinds leave; entry text never does.
|
|
5
|
+
//
|
|
6
|
+
// first prompt, or first tool check: every key present now. Arrivals arm the hold.
|
|
7
|
+
// before each tool rescan; a change no tool of this session made since the
|
|
8
|
+
// last scan (an `echo >>` from a background job, the owner's
|
|
9
|
+
// editor, another session) is checked at once, so it holds
|
|
10
|
+
// before the tool runs.
|
|
11
|
+
// after each tool outside-content marks for what the tool brought in
|
|
12
|
+
// (cli/memory-custody.mjs outsideMarks), then rescan: new keys
|
|
13
|
+
// are recorded as written by this session, with its marks.
|
|
14
|
+
// API mode: each model request the same "after" for the tool results it carries, and the
|
|
15
|
+
// memory sections Claude Code actually put in the context are
|
|
16
|
+
// hashed and checked too, so a file swapped back after the
|
|
17
|
+
// load is still caught.
|
|
18
|
+
//
|
|
19
|
+
// The hold, as the tool gate sees it (`state()`):
|
|
20
|
+
// off the owner has memory custody off (or this sidecar has not yet read /self)
|
|
21
|
+
// clear the last answer said nothing waits
|
|
22
|
+
// held arrivals or rejected entries wait, or the device's last check could not be
|
|
23
|
+
// completed: FAIL CLOSED, because an unknown custody state was not cleared
|
|
24
|
+
//
|
|
25
|
+
// Honest limit (RED-TEAM.md L1): this runs as the same user as the agent. An agent with a
|
|
26
|
+
// shell can stop it, rewrite it or its hook settings, or talk to the gateway with the
|
|
27
|
+
// agent's own credential. The ledger at the gateway limits what that can launder (sticky
|
|
28
|
+
// marks, the agent-wide exposure window, first custody wins, no decisions on the agent
|
|
29
|
+
// plane), but a sidecar the agent has replaced reports whatever the agent wants.
|
|
30
|
+
import { diffKeys, entryKeys, fileKey, memoryEntries, outsideMarks, requestMemorySections, withholdRequest } from "./memory-custody.mjs";
|
|
31
|
+
import fs from "node:fs";
|
|
32
|
+
import { custodySalt, scanMemory, workspaceRoot } from "./memory-inventory.mjs";
|
|
33
|
+
|
|
34
|
+
const DECLARED = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
35
|
+
const MAX_SESSIONS = 512;
|
|
36
|
+
const MAX_SEEN_TOOL_USES = 4096;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* @param {{
|
|
40
|
+
* send: (body: object) => Promise<{ status: number, body: any }>,
|
|
41
|
+
* env?: object,
|
|
42
|
+
* now?: () => number,
|
|
43
|
+
* salt?: string,
|
|
44
|
+
* onWarn?: (message: string) => void,
|
|
45
|
+
* claudeHome?: string,
|
|
46
|
+
* }} options
|
|
47
|
+
*/
|
|
48
|
+
export function createMemoryCustody({ send, env = process.env, now = Date.now, salt = null, onWarn = () => {} }) {
|
|
49
|
+
let mode = "unknown"; // from /self: "off" | "hold" | "withhold" | "unknown"
|
|
50
|
+
let integrity = "ok"; // the latest check's
|
|
51
|
+
const on = () => mode === "hold" || mode === "withhold";
|
|
52
|
+
let paths = [];
|
|
53
|
+
let gatewayHeld = false; // the latest answer that said
|
|
54
|
+
let failed = false; // the device's last check could not be completed
|
|
55
|
+
const sessions = new Map();
|
|
56
|
+
const roots = new Map(); // workspace root → { keys: string[], scan }
|
|
57
|
+
const touched = new Set(); // directories tools worked in (R1-8), bounded
|
|
58
|
+
// Explicit tool paths, including memory outside the workspace. Both sets are bounded and
|
|
59
|
+
// evict the oldest. That is not a coverage gap: a file only these sets reach lies either
|
|
60
|
+
// past a walker bound, which reports enumeration_incomplete itself, or in a directory the
|
|
61
|
+
// walk skips by design, and a path in use is touched again before the scan that follows
|
|
62
|
+
// it. A sticky overflow error here would hold a long-lived sidecar forever (A-10 review).
|
|
63
|
+
const touchedFiles = new Set();
|
|
64
|
+
const MAX_TOUCHED = 4096;
|
|
65
|
+
function touch(input) {
|
|
66
|
+
const ti = input?.tool_input && typeof input.tool_input === "object" ? input.tool_input : {};
|
|
67
|
+
const candidates = [ti.file_path, ti.path, ti.notebook_path];
|
|
68
|
+
// A shell read counts too (`cat node_modules/x/y` loads that directory's CLAUDE.md):
|
|
69
|
+
// path-like words of the command that exist on disk.
|
|
70
|
+
if (typeof ti.command === "string") {
|
|
71
|
+
for (const word of ti.command.split(/[\s;|&<>()]+/).slice(0, 64)) {
|
|
72
|
+
const w = word.replace(/^['"]+|['"]+$/g, "");
|
|
73
|
+
if (!w || w.startsWith("-") || !/[/.]/.test(w)) continue;
|
|
74
|
+
const abs = w.startsWith("/") ? w : typeof input.cwd === "string" ? `${input.cwd}/${w}` : null;
|
|
75
|
+
try {
|
|
76
|
+
if (abs && fs.existsSync(abs)) candidates.push(fs.statSync(abs).isDirectory() ? `${abs}/.` : abs);
|
|
77
|
+
} catch {}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
for (const p of candidates) {
|
|
81
|
+
if (typeof p !== "string" || !p) continue;
|
|
82
|
+
const abs = p.startsWith("/") ? p : typeof input.cwd === "string" ? `${input.cwd}/${p}` : null;
|
|
83
|
+
if (!abs) continue;
|
|
84
|
+
if (!touchedFiles.has(abs)) {
|
|
85
|
+
touchedFiles.add(abs);
|
|
86
|
+
if (touchedFiles.size > MAX_TOUCHED) touchedFiles.delete(touchedFiles.values().next().value);
|
|
87
|
+
}
|
|
88
|
+
const dir = abs.replace(/\/+[^/]*$/, "") || "/";
|
|
89
|
+
if (touched.has(dir)) continue;
|
|
90
|
+
touched.add(dir);
|
|
91
|
+
if (touched.size > MAX_TOUCHED) touched.delete(touched.values().next().value);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
let deviceSalt = salt;
|
|
95
|
+
|
|
96
|
+
const theSalt = () => (deviceSalt ??= custodySalt({ env }));
|
|
97
|
+
const sessionOf = (input) => {
|
|
98
|
+
const id = typeof input?.session_id === "string" && DECLARED.test(input.session_id) ? input.session_id : null;
|
|
99
|
+
if (!id) return null;
|
|
100
|
+
let s = sessions.get(id);
|
|
101
|
+
if (!s) {
|
|
102
|
+
s = { id, cwd: null, client: "claude-code", marks: new Map(), checked: false, inflight: 0, seen: new Set() };
|
|
103
|
+
sessions.set(id, s);
|
|
104
|
+
while (sessions.size > MAX_SESSIONS) sessions.delete(sessions.keys().next().value);
|
|
105
|
+
}
|
|
106
|
+
if (typeof input.cwd === "string" && input.cwd.startsWith("/")) s.cwd = input.cwd;
|
|
107
|
+
return s;
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
/** /self's `memory` view (undefined when the owner has it off). */
|
|
111
|
+
function setView(view) {
|
|
112
|
+
if (view === undefined || view === null) {
|
|
113
|
+
mode = "off";
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
if (view && (view.mode === "hold" || view.mode === "withhold")) {
|
|
117
|
+
mode = view.mode;
|
|
118
|
+
paths = Array.isArray(view.paths) ? view.paths.filter((p) => typeof p === "string").slice(0, 20) : [];
|
|
119
|
+
if (Array.isArray(view.integrity)) integrity = view.integrity.length ? String(view.integrity[0]) : "ok";
|
|
120
|
+
if (view.readable === false) gatewayHeld = true;
|
|
121
|
+
else if (typeof view.held === "boolean") gatewayHeld = view.held;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* The hold for one session. In `withhold` mode (direction 1) a session whose model
|
|
127
|
+
* requests pass through this sidecar has its pending memory cut out of every request, so
|
|
128
|
+
* it is not held for arrivals. It is held when withholding cannot be guaranteed: a check
|
|
129
|
+
* that did not complete, an integrity fault, pending text found where it could not be cut
|
|
130
|
+
* (residue), pending lines too short or shared with clean memory to cut safely,
|
|
131
|
+
* or a session no request of has passed here (subscription mode, Codex).
|
|
132
|
+
*/
|
|
133
|
+
function state(sessionId) {
|
|
134
|
+
if (!on()) return "off";
|
|
135
|
+
if (mode === "hold") return gatewayHeld || failed ? "held" : "clear";
|
|
136
|
+
const s = typeof sessionId === "string" ? sessions.get(sessionId) : null;
|
|
137
|
+
if (failed || integrity !== "ok" || s?.residue) return "held";
|
|
138
|
+
// Unheld only for a session whose OWN tool hooks are API-mode hooks: a subscription session
|
|
139
|
+
// whose real hooks say so stays held even if a request with its id is sent through here (R4-6).
|
|
140
|
+
if (!s?.api || !s.apiHook || s.nonApi) return gatewayHeld ? "held" : "clear";
|
|
141
|
+
if (pendingText().requiresHold) return "held";
|
|
142
|
+
return "clear";
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function scan(s) {
|
|
146
|
+
const cwd = s.cwd;
|
|
147
|
+
if (!cwd) return null;
|
|
148
|
+
return scanMemory({ salt: theSalt(), cwd, agent: s.client === "codex" ? "codex" : "claude-code", env, ownerPaths: paths, touchedDirs: [...touched], touchedFiles: [...touchedFiles] });
|
|
149
|
+
}
|
|
150
|
+
const filesOf = (scanned, extra = []) => [
|
|
151
|
+
...scanned.files.map((f) => ({ fileKey: f.fileKey, label: f.label, keys: f.keys })),
|
|
152
|
+
...extra,
|
|
153
|
+
];
|
|
154
|
+
const errorsOf = (scanned) => scanned.errors.map((e) => ({ fileKey: fileKey(theSalt(), e.id), label: e.label, reason: e.reason }));
|
|
155
|
+
|
|
156
|
+
async function call(body) {
|
|
157
|
+
try {
|
|
158
|
+
return await send(body);
|
|
159
|
+
} catch {
|
|
160
|
+
return { status: 0, body: null };
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async function runCheck(s, scanned, extra = []) {
|
|
165
|
+
const r = await call({
|
|
166
|
+
action: "check",
|
|
167
|
+
session: s.id,
|
|
168
|
+
workspace: scanned.workspace,
|
|
169
|
+
salt_fp: scanned.saltFp,
|
|
170
|
+
files: filesOf(scanned, extra),
|
|
171
|
+
errors: errorsOf(scanned),
|
|
172
|
+
});
|
|
173
|
+
if (r.status === 409 && r.body?.error === "memory_custody_off") {
|
|
174
|
+
mode = "off";
|
|
175
|
+
failed = false;
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
if (r.status !== 200 || typeof r.body?.hold !== "boolean") {
|
|
179
|
+
// Fail closed: the hold stays armed until a check completes.
|
|
180
|
+
failed = true;
|
|
181
|
+
onWarn("PassControl could not complete this agent's memory check, so its risky tools are held until it can.");
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
failed = false;
|
|
185
|
+
gatewayHeld = r.body.hold;
|
|
186
|
+
integrity = typeof r.body.integrity === "string" ? r.body.integrity : "ok";
|
|
187
|
+
s.checked = true;
|
|
188
|
+
roots.set(scanned.root, {
|
|
189
|
+
keys: [...scanned.files.flatMap((f) => f.keys), ...extra.flatMap((f) => f.keys)],
|
|
190
|
+
scanned,
|
|
191
|
+
// What the gateway says still waits (arrivals and rejected entries present): hashes only.
|
|
192
|
+
pending: new Set(Array.isArray(r.body.pending_keys) ? r.body.pending_keys.filter((k) => typeof k === "string") : []),
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async function addMarks(s, marks) {
|
|
197
|
+
const fresh = [];
|
|
198
|
+
for (const m of marks) {
|
|
199
|
+
const id = `${m.kind}|${m.host ?? ""}`;
|
|
200
|
+
if (!s.marks.has(id)) {
|
|
201
|
+
s.marks.set(id, m);
|
|
202
|
+
fresh.push(m);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
if (fresh.length) {
|
|
206
|
+
const r = await call({ action: "observe", session: s.id, marks: fresh });
|
|
207
|
+
if (r.status !== 200) failed = true;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async function ensureChecked(s) {
|
|
212
|
+
if (s.checked && !failed) return;
|
|
213
|
+
const scanned = scan(s);
|
|
214
|
+
if (scanned) await runCheck(s, scanned);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** After a tool (or a batch of them) ran in session `s`. */
|
|
218
|
+
async function afterTools(s, calls) {
|
|
219
|
+
const marks = [];
|
|
220
|
+
for (const c of calls) {
|
|
221
|
+
touch({ cwd: s.cwd, tool_input: c.tool_input });
|
|
222
|
+
marks.push(...outsideMarks(c, { cwd: s.cwd ?? undefined }));
|
|
223
|
+
}
|
|
224
|
+
await addMarks(s, marks);
|
|
225
|
+
const scanned = scan(s);
|
|
226
|
+
if (!scanned) return;
|
|
227
|
+
const before = roots.get(scanned.root);
|
|
228
|
+
if (!before || !s.checked) return void (await runCheck(s, scanned));
|
|
229
|
+
const now_ = scanned.files.flatMap((f) => f.keys);
|
|
230
|
+
const added = diffKeys(before.keys, now_);
|
|
231
|
+
const removed = before.keys.length !== now_.length || diffKeys(now_, before.keys).length > 0;
|
|
232
|
+
if (added.length) {
|
|
233
|
+
const byKey = new Map(scanned.files.flatMap((f) => f.keys.map((k) => [k, f])));
|
|
234
|
+
const r = await call({
|
|
235
|
+
action: "record",
|
|
236
|
+
session: s.id,
|
|
237
|
+
workspace: scanned.workspace,
|
|
238
|
+
salt_fp: scanned.saltFp,
|
|
239
|
+
entries: added.map((k) => ({ key: k, fileKey: byKey.get(k).fileKey, label: byKey.get(k).label })),
|
|
240
|
+
marks: [...s.marks.values()],
|
|
241
|
+
});
|
|
242
|
+
if (r.status === 409 && (r.body?.error === "not_enrolled" || r.body?.error === "salt_changed")) return void (await runCheck(s, scanned));
|
|
243
|
+
if (r.status !== 200) {
|
|
244
|
+
failed = true;
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
if (typeof r.body?.hold === "boolean") gatewayHeld = r.body.hold;
|
|
248
|
+
roots.set(scanned.root, { ...roots.get(scanned.root), keys: now_, scanned }); // keep the gateway's pending set (R4-0)
|
|
249
|
+
if (scanned.errors.length) await runCheck(s, scanned);
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
roots.set(scanned.root, { ...roots.get(scanned.root), keys: now_, scanned }); // keep the gateway's pending set (R4-0)
|
|
253
|
+
// Something left: if the agent is held, a removal may be what lifts it.
|
|
254
|
+
if (scanned.errors.length || (removed && state() === "held")) await runCheck(s, scanned);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Before a tool in session `s`: anything changed that no tool of this session wrote? */
|
|
258
|
+
async function beforeTool(s) {
|
|
259
|
+
await ensureChecked(s);
|
|
260
|
+
const scanned = scan(s);
|
|
261
|
+
if (!scanned) return;
|
|
262
|
+
const before = roots.get(scanned.root);
|
|
263
|
+
const now_ = scanned.files.flatMap((f) => f.keys);
|
|
264
|
+
if (!before) return void (await runCheck(s, scanned));
|
|
265
|
+
if (diffKeys(before.keys, now_).length === 0 && scanned.errors.length === (before.scanned?.errors.length ?? 0)) return;
|
|
266
|
+
if (s.inflight > 0) {
|
|
267
|
+
// A tool of this session is still running (parallel calls): its own write.
|
|
268
|
+
return void (await afterTools(s, []));
|
|
269
|
+
}
|
|
270
|
+
await runCheck(s, scanned); // unattributed: it arrives, and holds before this tool runs
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** One hook event. Never throws; the hook's own answer is the gates'. */
|
|
274
|
+
async function hook(input, { client = "claude-code", api = false } = {}) {
|
|
275
|
+
try {
|
|
276
|
+
if (!on()) return;
|
|
277
|
+
const s = sessionOf(input);
|
|
278
|
+
if (!s) return;
|
|
279
|
+
// Which channel this session's harness really uses. Sticky the cautious way: one
|
|
280
|
+
// non-API hook and the session can never be treated as withholdable.
|
|
281
|
+
if (api) s.apiHook = true;
|
|
282
|
+
else s.nonApi = true;
|
|
283
|
+
if (client === "codex") s.client = "codex";
|
|
284
|
+
const event = input.hook_event_name;
|
|
285
|
+
if (event === "UserPromptSubmit") return void (await ensureChecked(s));
|
|
286
|
+
if (event === "PreToolUse") {
|
|
287
|
+
if (s.loading) await s.loading;
|
|
288
|
+
touch(input);
|
|
289
|
+
await beforeTool(s);
|
|
290
|
+
s.inflight++;
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
if (event === "PostToolUse") {
|
|
294
|
+
s.inflight = Math.max(0, s.inflight - 1);
|
|
295
|
+
return void (await afterTools(s, [{ tool_name: input.tool_name, tool_input: input.tool_input }]));
|
|
296
|
+
}
|
|
297
|
+
if (event === "PostToolBatch") {
|
|
298
|
+
const calls = Array.isArray(input.tool_calls) ? input.tool_calls : [];
|
|
299
|
+
s.inflight = Math.max(0, s.inflight - Math.max(1, calls.length));
|
|
300
|
+
return void (await afterTools(s, calls.map((c) => ({ tool_name: c?.tool_name, tool_input: c?.tool_input }))));
|
|
301
|
+
}
|
|
302
|
+
} catch {
|
|
303
|
+
failed = true;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* API mode: a model request on its way through the sidecar. The tool results it carries
|
|
309
|
+
* are this session's "after"; its memory sections are what the model will actually read.
|
|
310
|
+
*/
|
|
311
|
+
async function modelRequest(sessionId, body) {
|
|
312
|
+
const s0 = DECLARED.test(String(sessionId ?? "")) ? sessionOf({ session_id: sessionId }) : null;
|
|
313
|
+
const run = modelRequestInner(sessionId, body);
|
|
314
|
+
// The next tool of this session waits for this check, however long it takes (R3-4).
|
|
315
|
+
if (s0) s0.loading = run;
|
|
316
|
+
try {
|
|
317
|
+
return await run;
|
|
318
|
+
} finally {
|
|
319
|
+
if (s0 && s0.loading === run) s0.loading = null;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
async function modelRequestInner(sessionId, body) {
|
|
323
|
+
try {
|
|
324
|
+
if (!on()) return null;
|
|
325
|
+
const s = DECLARED.test(String(sessionId ?? "")) ? sessionOf({ session_id: sessionId }) : null;
|
|
326
|
+
if (!s) return mode === "withhold" ? withholdAll(body) : null; // no session to check for: nothing unverified goes through
|
|
327
|
+
s.api = true;
|
|
328
|
+
s.cwd ??= cwdFromRequest(body);
|
|
329
|
+
if (!s.cwd) return mode === "withhold" ? withholdAll(body) : null;
|
|
330
|
+
if (!s.checked) await ensureChecked(s);
|
|
331
|
+
const uses = new Map();
|
|
332
|
+
const results = new Set();
|
|
333
|
+
for (const m of Array.isArray(body?.messages) ? body.messages : []) {
|
|
334
|
+
for (const b of Array.isArray(m?.content) ? m.content : []) {
|
|
335
|
+
if (m.role === "assistant" && b?.type === "tool_use" && typeof b.id === "string") uses.set(b.id, { tool_name: b.name, tool_input: b.input });
|
|
336
|
+
if (m.role === "user" && b?.type === "tool_result" && typeof b.tool_use_id === "string") results.add(b.tool_use_id);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
const done = [...results].filter((id) => uses.has(id) && !s.seen.has(id));
|
|
340
|
+
for (const id of done) {
|
|
341
|
+
s.seen.add(id);
|
|
342
|
+
if (s.seen.size > MAX_SEEN_TOOL_USES) s.seen.delete(s.seen.values().next().value);
|
|
343
|
+
}
|
|
344
|
+
if (done.length) {
|
|
345
|
+
s.inflight = Math.max(0, s.inflight - done.length);
|
|
346
|
+
await afterTools(s, done.map((id) => uses.get(id)));
|
|
347
|
+
}
|
|
348
|
+
// What Claude Code actually loaded. A section whose entries are not all on record is checked.
|
|
349
|
+
const sections = requestMemorySections(body);
|
|
350
|
+
const scanned = scan(s);
|
|
351
|
+
if (!sections.length || !scanned) return mode === "withhold" ? withholdFor(s, body) : null;
|
|
352
|
+
const known = new Set(roots.get(scanned.root)?.keys ?? []);
|
|
353
|
+
const extra = [];
|
|
354
|
+
for (const section of sections) {
|
|
355
|
+
const disk = scanned.files.find((f) => f.path === section.path);
|
|
356
|
+
const id = disk?.id ?? `import:abs:${section.path}`;
|
|
357
|
+
const entries = memoryEntries(section.text);
|
|
358
|
+
const keys = entryKeys(theSalt(), id, entries);
|
|
359
|
+
// A truncated load (MEMORY.md past 200 lines) ends in a prefix of a disk entry: not new text.
|
|
360
|
+
const novel = keys.filter((k, n) => !known.has(k) && !(disk?.entries ?? []).some((e) => e.text.startsWith(entries[n].text)));
|
|
361
|
+
if (novel.length) extra.push({ fileKey: fileKey(theSalt(), id), label: disk?.label ?? "imported_file", keys: novel });
|
|
362
|
+
}
|
|
363
|
+
if (extra.length) await runCheck(s, scanned, extra);
|
|
364
|
+
return mode === "withhold" ? withholdFor(s, body) : null;
|
|
365
|
+
} catch {
|
|
366
|
+
failed = true;
|
|
367
|
+
return mode === "withhold" ? withholdAll(body) : null;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// ── Direction 1: withhold ──────────────────────────────────────────────────
|
|
372
|
+
|
|
373
|
+
/** The workspace a request belongs to: Claude Code's own "working directory" line, or a project instruction file's folder. */
|
|
374
|
+
function cwdFromRequest(body) {
|
|
375
|
+
const texts = [];
|
|
376
|
+
if (typeof body?.system === "string") texts.push(body.system);
|
|
377
|
+
else if (Array.isArray(body?.system)) for (const b of body.system) if (typeof b?.text === "string") texts.push(b.text);
|
|
378
|
+
for (const t of texts) {
|
|
379
|
+
const m = t.match(/(?:Primary working directory|Working directory|cwd):\s*(\/[^\s]+)/i);
|
|
380
|
+
if (m) return m[1];
|
|
381
|
+
}
|
|
382
|
+
const home = env.HOME ?? "";
|
|
383
|
+
for (const section of requestMemorySections(body)) {
|
|
384
|
+
if (/\/(CLAUDE|AGENTS|CLAUDE\.local)\.md$/.test(section.path) && !(home && section.path.startsWith(`${home}/.claude/`))) return section.path.replace(/\/[^/]+$/, "");
|
|
385
|
+
}
|
|
386
|
+
return null;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** Pending entries' text from this machine's last checked scans: what to cut from tool results, and what counts as residue. */
|
|
390
|
+
function pendingText() {
|
|
391
|
+
const lines = new Set();
|
|
392
|
+
const clean = new Set();
|
|
393
|
+
for (const { scanned, pending } of roots.values()) {
|
|
394
|
+
for (const f of scanned.files) for (const e of f.entries) for (const l of e.text.split("\n")) (pending?.has(e.key) ? lines : clean).add(l.replace(/[ \t]+$/, ""));
|
|
395
|
+
}
|
|
396
|
+
const nonblank = [...lines].filter((l) => !/^[ \t]*$/.test(l));
|
|
397
|
+
// Short or shared lines are ambiguous in ordinary tool output: do not cut them.
|
|
398
|
+
// Hold instead, even before a read. Every cut candidate must also be long enough
|
|
399
|
+
// for the residue probe (16 characters), so an uncut format cannot silently pass.
|
|
400
|
+
const safe = (l) => !clean.has(l) && l.trim().length >= 16;
|
|
401
|
+
const only = nonblank.filter(safe);
|
|
402
|
+
return { stripLines: only, probes: only, requiresHold: nonblank.some((l) => !safe(l)) };
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** Nothing that this sidecar has not confirmed goes through: every memory section is cut. */
|
|
406
|
+
function withholdAll(body) {
|
|
407
|
+
const out = withholdRequest(body, { decide: () => "all", ...pendingText() });
|
|
408
|
+
return out.sectionsChanged || out.linesWithheld ? out.body : null;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function withholdFor(s, body) {
|
|
412
|
+
const root = roots.get(workspaceRoot(s.cwd));
|
|
413
|
+
if (!root || failed) {
|
|
414
|
+
s.residue ||= false;
|
|
415
|
+
return withholdAll(body);
|
|
416
|
+
}
|
|
417
|
+
const checked = new Set(root.keys);
|
|
418
|
+
const pending = root.pending ?? new Set();
|
|
419
|
+
const out = withholdRequest(body, {
|
|
420
|
+
...pendingText(),
|
|
421
|
+
decide: ({ path: p, entries }) => {
|
|
422
|
+
const disk = root.scanned.files.find((f) => f.path === p);
|
|
423
|
+
if (!disk) return "all"; // a file this machine has not checked
|
|
424
|
+
const keys = entryKeys(theSalt(), disk.id, entries);
|
|
425
|
+
const cut = new Set();
|
|
426
|
+
keys.forEach((k, n) => {
|
|
427
|
+
if (pending.has(k)) return void cut.add(n);
|
|
428
|
+
if (checked.has(k)) return;
|
|
429
|
+
// A truncated load ends in a prefix of a CLEAN disk entry: that is not new text. Only
|
|
430
|
+
// the LAST entry of a section can be cut short; anywhere else a prefix is new text (R4-2).
|
|
431
|
+
const prefixOfClean = n === entries.length - 1 && disk.entries.some((e) => !pending.has(e.key) && e.text.startsWith(entries[n].text));
|
|
432
|
+
if (!prefixOfClean) cut.add(n);
|
|
433
|
+
});
|
|
434
|
+
return cut;
|
|
435
|
+
},
|
|
436
|
+
});
|
|
437
|
+
if (out.residue > 0) {
|
|
438
|
+
s.residue = true;
|
|
439
|
+
onWarn("PassControl found memory waiting for review in a place it could not withhold it from, so this session's risky tools are held.");
|
|
440
|
+
}
|
|
441
|
+
return out.sectionsChanged || out.linesWithheld ? out.body : null;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/** A request this sidecar could not read in time or at all: cut every memory section, and hold its session. */
|
|
445
|
+
function fallback(sessionId, body) {
|
|
446
|
+
const s = DECLARED.test(String(sessionId ?? "")) ? sessionOf({ session_id: sessionId }) : null;
|
|
447
|
+
if (s) s.residue = true;
|
|
448
|
+
return body ? withholdAll(body) : null;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* For `passcontrol memory review`: what waits, with its text from THIS machine's files.
|
|
453
|
+
* The gateway answers with hashes; the text never left and is matched here.
|
|
454
|
+
*/
|
|
455
|
+
async function review(cwd, client = "claude-code") {
|
|
456
|
+
if (!on()) return { state: mode === "off" ? "off" : "unknown", items: [] };
|
|
457
|
+
const r = await call({ action: "pending" });
|
|
458
|
+
if (r.status !== 200 || !Array.isArray(r.body?.entries)) return { state: "unavailable", items: [] };
|
|
459
|
+
const scanned = scanMemory({ salt: theSalt(), cwd, agent: client, env, ownerPaths: paths, touchedDirs: [...touched], touchedFiles: [...touchedFiles] });
|
|
460
|
+
const byKey = new Map(scanned.files.flatMap((f) => f.entries.map((e) => [e.key, { file: f.path, label: f.label, text: e.text, scope: e.scope }])));
|
|
461
|
+
const items = r.body.entries
|
|
462
|
+
.filter((e) => e && typeof e.key === "string")
|
|
463
|
+
.map((e) => ({ ...e, local: byKey.get(e.key) ?? null }));
|
|
464
|
+
return { state: state(), items };
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
return { hook, modelRequest, fallback, mode: () => mode, setView, state, review, _debug: { sessions, roots } };
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
export { workspaceRoot };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export const PARSER_VERSION: number;
|
|
2
|
+
export interface MemoryEntry { text: string; scope: string[]; digest: string; occurrence: number; start: number; end: number }
|
|
3
|
+
export interface OutsideMark { kind: "web" | "mcp" | "shell_network" | "outside_read" | "workspace_read" | "memory_arrival"; host?: string }
|
|
4
|
+
export function sha256Hex(text: string): string;
|
|
5
|
+
export function hmacHex(saltHex: string, text: string): string;
|
|
6
|
+
export function memoryEntries(raw: string): MemoryEntry[];
|
|
7
|
+
export function fileKey(salt: string, fileId: string): string;
|
|
8
|
+
export function entryKeys(salt: string, fileId: string, entries: MemoryEntry[]): string[];
|
|
9
|
+
export function saltFingerprint(salt: string, version?: number): string;
|
|
10
|
+
export function diffKeys(prev: readonly string[], next: readonly string[]): string[];
|
|
11
|
+
export function isLoopbackHost(host: string): boolean;
|
|
12
|
+
export function bashNetworkSource(command: unknown): string | null;
|
|
13
|
+
export function normalizePath(p: string, cwd?: string): string;
|
|
14
|
+
export function outsideMarks(
|
|
15
|
+
event: { tool_name?: unknown; tool_input?: unknown },
|
|
16
|
+
ctx?: { cwd?: string; outsideReads?: boolean; localRoots?: string[]; workspaceTrust?: "own" | "third_party" }
|
|
17
|
+
): OutsideMark[];
|
|
18
|
+
export function requestMemorySections(body: unknown): { path: string; text: string }[];
|
|
19
|
+
export const WITHHELD_ENTRY: (n: number) => string;
|
|
20
|
+
export const WITHHELD_LINE: string;
|
|
21
|
+
export function withholdRequest(
|
|
22
|
+
body: unknown,
|
|
23
|
+
options: { decide: (section: { path: string; entries: MemoryEntry[] }) => Set<number> | "all" | null | undefined; stripLines?: string[]; probes?: string[] }
|
|
24
|
+
): { body: any; sectionsChanged: number; entriesWithheld: number; linesWithheld: number; residue: number };
|