@mokuyoaxis/agent-guard 0.2.3-rc1 → 0.2.3
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/README.md +124 -52
- package/README.zh-CN.md +102 -41
- package/adapters/dsh/README.md +92 -10
- package/adapters/dsh/harness/README.md +384 -0
- package/adapters/dsh/harness/baseline.patch.yml +8 -0
- package/adapters/dsh/harness/bootstrap.patch.yml +5 -0
- package/adapters/dsh/harness/bootstrap_init.mjs +48 -0
- package/adapters/dsh/harness/guard_lab.py +771 -0
- package/adapters/dsh/harness/native_session.py +503 -0
- package/adapters/dsh/harness/profiles.py +212 -0
- package/adapters/dsh/harness/read_fixture.py +60 -0
- package/adapters/dsh/harness/retry_stream.py +171 -0
- package/adapters/dsh/harness/session_decode.mjs +117 -0
- package/adapters/dsh/lib/index.js +46 -5
- package/adapters/dsh/lib/read_result_guard.js +207 -0
- package/adapters/dsh/lib/read_result_guard.py +139 -0
- package/adapters/harness_support.py +109 -0
- package/adapters/kimi-code/README.md +15 -7
- package/adapters/kimi-code/harness/README.md +126 -0
- package/adapters/kimi-code/harness/guard_lab.py +430 -0
- package/core/lab.py +2396 -0
- package/core/redaction.py +157 -55
- package/docs/architecture.md +75 -0
- package/docs/development-note-unguarded-deletion.md +6 -7
- package/docs/friction.md +140 -4
- package/docs/guard-lab-clean-task.md +4 -0
- package/docs/guard-lab-read-trial-task.md +7 -0
- package/docs/guard-lab-trial-task.md +5 -0
- package/docs/guard-lab.md +398 -0
- package/docs/harness-capabilities.md +8 -5
- package/docs/release-notes-0.2.0-rc1.md +2 -2
- package/docs/release-notes-0.2.0.md +2 -2
- package/docs/release-notes-0.2.2.md +7 -8
- package/docs/release-notes-0.2.3-rc1.md +4 -2
- package/docs/release-notes-0.2.3-rc2.md +189 -0
- package/docs/release-notes-0.2.3.md +84 -0
- package/docs/secret-guard-analysis.md +13 -12
- package/docs/secret-guard-architecture.md +5 -3
- package/docs/secret-guard-design.md +7 -3
- package/docs/test-report-codex-gpt-5.6-sol.md +10 -11
- package/docs/test-report-dsh-0.2-upgrade.md +142 -0
- package/docs/test-report-dsh-guard-lab.md +154 -0
- package/docs/test-report-dsh-native-session.md +118 -0
- package/docs/test-report-dsh-paired-lab.md +183 -0
- package/docs/test-report-dsh-read-redaction.md +114 -0
- package/docs/test-report-dsh-real-followup.md +170 -0
- package/docs/test-report-dsh-retry-evidence.md +134 -0
- package/docs/test-report-kimi-code-block.md +19 -20
- package/docs/test-report-kimi-guard-lab.md +117 -0
- package/docs/test-report-release-readiness-0.2.3.md +239 -0
- package/docs/test-report-workbuddy-windows-core.md +53 -0
- package/docs/test-report-zcode-glm-flash.md +9 -9
- package/docs/threat-model.md +42 -0
- package/guard_lab.py +14 -0
- package/package.json +8 -5
- package/skills/delete-guard/SKILL.md +2 -3
- package/skills/exfil-guard/SKILL.md +37 -7
- package/skills/exfil-guard/references/rules.md +84 -16
- package/skills/exfil-guard/scripts/_payload.py +99 -0
- package/skills/exfil-guard/scripts/check_span.py +14 -81
- package/skills/exfil-guard/scripts/sanitize.py +113 -34
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* agent-guard - DSH host adapter (Decision Protocol).
|
|
3
3
|
*
|
|
4
4
|
* A Cordis plugin for the DeepSeek Harness launcher composition. Three
|
|
5
|
-
* contributions:
|
|
5
|
+
* default contributions:
|
|
6
6
|
*
|
|
7
7
|
* 1. Interception: a `tools/pre-execute` waterfall runs every destructive-
|
|
8
8
|
* looking bash command through the shared Python core (check.py
|
|
@@ -13,6 +13,8 @@
|
|
|
13
13
|
* 2. Model tools: agent_guard_safe_delete / agent_guard_restore /
|
|
14
14
|
* agent_guard_status - the supported path is also the easiest path.
|
|
15
15
|
* 3. Prompt guidance: deletion discipline as a system-prompt section.
|
|
16
|
+
* An optional pinned text-read result guard delegates to the shared exfil
|
|
17
|
+
* Core and replaces native values so content and metadata regenerate.
|
|
16
18
|
*
|
|
17
19
|
* The decision rules are NOT implemented here. This adapter only translates;
|
|
18
20
|
* the single rule engine lives in skills/delete-guard/scripts/check.py,
|
|
@@ -43,6 +45,7 @@ const CONFIG_DIALECTS = new Set([
|
|
|
43
45
|
]);
|
|
44
46
|
const CONFIG_FIELDS = new Set([
|
|
45
47
|
"repoRoot", "defaultCwd", "promptSection", "sectionOrder", "dialect",
|
|
48
|
+
"readResultGuard", "readGuardDshRoot",
|
|
46
49
|
]);
|
|
47
50
|
|
|
48
51
|
// Keep the adapter installable without importing a host-private helper. DSH's
|
|
@@ -121,13 +124,15 @@ export const Config = {
|
|
|
121
124
|
promptSection: true,
|
|
122
125
|
sectionOrder: 105,
|
|
123
126
|
dialect: "",
|
|
127
|
+
readResultGuard: false,
|
|
128
|
+
readGuardDshRoot: "",
|
|
124
129
|
};
|
|
125
130
|
for (const key of Object.keys(input)) {
|
|
126
131
|
if (!CONFIG_FIELDS.has(key)) {
|
|
127
132
|
issues.push({ message: `unknown agent-guard config field: ${key}`, path: [key] });
|
|
128
133
|
}
|
|
129
134
|
}
|
|
130
|
-
for (const key of ["repoRoot", "defaultCwd"]) {
|
|
135
|
+
for (const key of ["repoRoot", "defaultCwd", "readGuardDshRoot"]) {
|
|
131
136
|
if (!Object.prototype.hasOwnProperty.call(input, key)) continue;
|
|
132
137
|
if (typeof input[key] !== "string") {
|
|
133
138
|
issues.push({ message: `${key} must be a string`, path: [key] });
|
|
@@ -149,6 +154,19 @@ export const Config = {
|
|
|
149
154
|
config.sectionOrder = input.sectionOrder;
|
|
150
155
|
}
|
|
151
156
|
}
|
|
157
|
+
if (Object.prototype.hasOwnProperty.call(input, "readResultGuard")) {
|
|
158
|
+
if (typeof input.readResultGuard !== "boolean") {
|
|
159
|
+
issues.push({ message: "readResultGuard must be a boolean", path: ["readResultGuard"] });
|
|
160
|
+
} else {
|
|
161
|
+
config.readResultGuard = input.readResultGuard;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
if (config.readResultGuard && !path.isAbsolute(config.readGuardDshRoot)) {
|
|
165
|
+
issues.push({ message: "readGuardDshRoot must be an absolute pinned DSH package root", path: ["readGuardDshRoot"] });
|
|
166
|
+
}
|
|
167
|
+
if (config.readResultGuard && !path.isAbsolute(config.defaultCwd)) {
|
|
168
|
+
issues.push({ message: "defaultCwd must be an absolute workspace for readResultGuard", path: ["defaultCwd"] });
|
|
169
|
+
}
|
|
152
170
|
if (Object.prototype.hasOwnProperty.call(input, "dialect")) {
|
|
153
171
|
const requested = input.dialect;
|
|
154
172
|
if (typeof requested !== "string" ||
|
|
@@ -224,7 +242,7 @@ function buildRuntime(ctx, config, shell, systemPrompt) {
|
|
|
224
242
|
return collected.text || "";
|
|
225
243
|
}
|
|
226
244
|
|
|
227
|
-
function runScript(scriptName, argString, workdir, timeoutMs, exec) {
|
|
245
|
+
async function runScript(scriptName, argString, workdir, timeoutMs, exec) {
|
|
228
246
|
const request = {
|
|
229
247
|
command:
|
|
230
248
|
"python3 " +
|
|
@@ -237,7 +255,13 @@ function buildRuntime(ctx, config, shell, systemPrompt) {
|
|
|
237
255
|
const dir = workdir || config.defaultCwd || undefined;
|
|
238
256
|
if (dir) request.workdir = dir;
|
|
239
257
|
if (exec && exec.signal) request.signal = exec.signal;
|
|
240
|
-
|
|
258
|
+
const spec = shell.resolve(request);
|
|
259
|
+
// DSH 0.2 returns a live execution handle; await its foreground result.
|
|
260
|
+
// Keep the previously tested 0.1 API for existing installations.
|
|
261
|
+
if (typeof shell.execute === "function") {
|
|
262
|
+
return (await shell.execute(spec)).result();
|
|
263
|
+
}
|
|
264
|
+
return shell.run(spec);
|
|
241
265
|
}
|
|
242
266
|
|
|
243
267
|
function parseJson(text) {
|
|
@@ -261,9 +285,12 @@ function buildRuntime(ctx, config, shell, systemPrompt) {
|
|
|
261
285
|
};
|
|
262
286
|
}
|
|
263
287
|
|
|
264
|
-
|
|
288
|
+
// Async functions cannot be mistaken for constructor plugins by Cordis.
|
|
289
|
+
// The host must await optional read-guard startup before admitting work.
|
|
290
|
+
export async function apply(ctx, config) {
|
|
265
291
|
const shell = ctx.get ? ctx.get("shell") : undefined;
|
|
266
292
|
if (shell === undefined) {
|
|
293
|
+
if (config.readResultGuard) throw new Error("[agent-guard] READ_GUARD_STARTUP_REFUSED");
|
|
267
294
|
console.error("[agent-guard] shell service unavailable; adapter disabled");
|
|
268
295
|
return;
|
|
269
296
|
}
|
|
@@ -271,10 +298,24 @@ export function apply(ctx, config) {
|
|
|
271
298
|
const rt = buildRuntime(ctx, config, shell, systemPrompt);
|
|
272
299
|
|
|
273
300
|
if (!rt.pythonReady) {
|
|
301
|
+
if (config.readResultGuard) throw new Error("[agent-guard] READ_GUARD_STARTUP_REFUSED");
|
|
274
302
|
console.error("[agent-guard] check.py not found under", rt.repoRoot);
|
|
275
303
|
return;
|
|
276
304
|
}
|
|
277
305
|
|
|
306
|
+
if (config.readResultGuard) {
|
|
307
|
+
return import("./read_result_guard.js").then(async ({ installReadResultGuard }) => {
|
|
308
|
+
await installReadResultGuard(ctx, config, rt.repoRoot);
|
|
309
|
+
contribute(ctx, config, rt);
|
|
310
|
+
}).catch(() => {
|
|
311
|
+
throw new Error("[agent-guard] READ_GUARD_STARTUP_REFUSED");
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
contribute(ctx, config, rt);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function contribute(ctx, config, rt) {
|
|
318
|
+
const { systemPrompt } = rt;
|
|
278
319
|
ctx.effect(() => {
|
|
279
320
|
const disposers = [];
|
|
280
321
|
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
// Experimental, default-off policy boundary for one pinned native text read.
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { spawn } from "node:child_process";
|
|
6
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
7
|
+
|
|
8
|
+
export const MAX_INPUT_BYTES = 1024 * 1024;
|
|
9
|
+
const MAX_OUTPUT_BYTES = 2 * MAX_INPUT_BYTES;
|
|
10
|
+
const WORKER = fileURLToPath(new URL("./read_result_guard.py", import.meta.url));
|
|
11
|
+
const LEGACY_PINNED = {
|
|
12
|
+
"dsh-tools": "aaba52bf5d0149355407642b3965c06977d1e9143f5c61bc19429abbe6a11c5d",
|
|
13
|
+
"dsh-tool-fs": "57cbfdf103d663e169cc4df3c089c4a8a260f5a05f2f99c9a97f177f7e059639",
|
|
14
|
+
"dsh-fs-local": "7ea33bc933daf5a60600dce74915510355a605473dc935041280be6a16fdd34b",
|
|
15
|
+
};
|
|
16
|
+
const RUNTIMES = {
|
|
17
|
+
"0.1.5-rc.1": { dependencyVersion: "0.1.5-rc.2", artifacts: LEGACY_PINNED },
|
|
18
|
+
"0.2.0-rc.2": { dependencyVersion: "0.2.0-rc.2", artifacts: {
|
|
19
|
+
"dsh-tools": "40f47709337c3c205d4e09e647f8588f4977e66f6d52f019b3cc7ef81159d84f",
|
|
20
|
+
"dsh-tool-fs": "66742231de99695b98400cdbc7bcf47b8ef2bf24600cf86f66bb35591981427f",
|
|
21
|
+
"dsh-fs-local": "63fbb41d2c33e07111884b798be507e68c2752acab8249c821c20ade436e894f",
|
|
22
|
+
"dsh-fs-sandbox": "cac65e21a0f0895b073cb9a447196ac265f2a171cc7f67c7434a6b3b7782caf5",
|
|
23
|
+
} },
|
|
24
|
+
};
|
|
25
|
+
const CODES = new Set([
|
|
26
|
+
"READ_RESULT_SCHEMA", "READ_RESULT_INCOMPLETE", "READ_RESULT_POLICY",
|
|
27
|
+
"READ_RESULT_SCAN_FAILED", "READ_RESULT_SIZE", "READ_RESULT_TIMEOUT",
|
|
28
|
+
"READ_RESULT_CANCELLED", "READ_RESULT_BINDING", "READ_RESULT_CONTEXT",
|
|
29
|
+
]);
|
|
30
|
+
|
|
31
|
+
export function blockRead(code) {
|
|
32
|
+
const safe = CODES.has(code) ? code : "READ_RESULT_SCAN_FAILED";
|
|
33
|
+
return { kind: "block", feedback: [{ type: "text", text: `[agent-guard] ${safe}: text read withheld.` }] };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Fixed executable and script, no shell or file payload. The worker does not
|
|
37
|
+
// read the target file; the native filesystem provider remains its owner.
|
|
38
|
+
export function scanReadValue(value, workspace, signal, options = {}) {
|
|
39
|
+
let payload;
|
|
40
|
+
try {
|
|
41
|
+
payload = Buffer.from(JSON.stringify({ workspace, value }), "utf8");
|
|
42
|
+
if (payload.length > MAX_INPUT_BYTES) return Promise.resolve(blockRead("READ_RESULT_SIZE"));
|
|
43
|
+
} catch { return Promise.resolve(blockRead("READ_RESULT_SCHEMA")); }
|
|
44
|
+
if (signal?.aborted) return Promise.resolve(blockRead("READ_RESULT_CANCELLED"));
|
|
45
|
+
return new Promise((resolve) => {
|
|
46
|
+
let child, timer, done = false, size = 0;
|
|
47
|
+
const chunks = [];
|
|
48
|
+
const finish = (decision) => {
|
|
49
|
+
if (done) return;
|
|
50
|
+
done = true;
|
|
51
|
+
clearTimeout(timer);
|
|
52
|
+
signal?.removeEventListener("abort", abort);
|
|
53
|
+
resolve(decision);
|
|
54
|
+
};
|
|
55
|
+
const stop = (code) => {
|
|
56
|
+
child?.kill("SIGKILL");
|
|
57
|
+
finish(blockRead(code));
|
|
58
|
+
};
|
|
59
|
+
const abort = () => stop("READ_RESULT_CANCELLED");
|
|
60
|
+
try {
|
|
61
|
+
child = (options.spawnProcess ?? spawn)("python3", ["-I", WORKER], {
|
|
62
|
+
stdio: ["pipe", "pipe", "pipe"], windowsHide: true,
|
|
63
|
+
});
|
|
64
|
+
timer = setTimeout(() => stop("READ_RESULT_TIMEOUT"), options.timeoutMs ?? 10000);
|
|
65
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
66
|
+
if (signal?.aborted) abort();
|
|
67
|
+
child.on("error", () => stop("READ_RESULT_SCAN_FAILED"));
|
|
68
|
+
child.stdin.on("error", () => stop("READ_RESULT_SCAN_FAILED"));
|
|
69
|
+
// Suppress worker diagnostics, including interpreter/import failures.
|
|
70
|
+
child.stderr.on("data", () => {});
|
|
71
|
+
child.stdout.on("data", (chunk) => {
|
|
72
|
+
if (done) return;
|
|
73
|
+
size += chunk.length;
|
|
74
|
+
if (size > MAX_OUTPUT_BYTES) return stop("READ_RESULT_SIZE");
|
|
75
|
+
chunks.push(chunk);
|
|
76
|
+
});
|
|
77
|
+
child.on("close", (code) => {
|
|
78
|
+
if (done) return;
|
|
79
|
+
if (code !== 0) return finish(blockRead("READ_RESULT_SCAN_FAILED"));
|
|
80
|
+
try {
|
|
81
|
+
const reply = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
82
|
+
if (reply.kind === "block") return finish(blockRead(reply.code));
|
|
83
|
+
if (reply.kind !== "accept" || !["ALLOW", "SANITIZE"].includes(reply.decision) ||
|
|
84
|
+
!Number.isSafeInteger(reply.redactions) || reply.redactions < 0 || !reply.value) {
|
|
85
|
+
return finish(blockRead("READ_RESULT_SCAN_FAILED"));
|
|
86
|
+
}
|
|
87
|
+
finish({ kind: "accept", value: reply.value });
|
|
88
|
+
} catch { finish(blockRead("READ_RESULT_SCAN_FAILED")); }
|
|
89
|
+
});
|
|
90
|
+
child.stdin.end(payload);
|
|
91
|
+
} catch { stop("READ_RESULT_SCAN_FAILED"); }
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function canonical(value) {
|
|
96
|
+
if (Array.isArray(value)) return value.map(canonical);
|
|
97
|
+
if (value && typeof value === "object") {
|
|
98
|
+
return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])]));
|
|
99
|
+
}
|
|
100
|
+
return value;
|
|
101
|
+
}
|
|
102
|
+
const schema = {
|
|
103
|
+
type: "object", additionalProperties: false,
|
|
104
|
+
properties: {
|
|
105
|
+
path: { type: "string" }, offset: { type: "integer" }, totalLines: { type: "integer" },
|
|
106
|
+
lines: { type: "array", items: {
|
|
107
|
+
type: "object", additionalProperties: false,
|
|
108
|
+
properties: { number: { type: "integer" }, text: { type: "string" } }, required: ["number", "text"],
|
|
109
|
+
} },
|
|
110
|
+
}, required: ["path", "offset", "lines", "totalLines"],
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
export function pinReadBinding(tools) {
|
|
114
|
+
const definition = tools.get("read");
|
|
115
|
+
if (!definition || definition.finalizeContent !== undefined || definition.projectContent !== undefined ||
|
|
116
|
+
typeof definition.execute !== "function" || typeof definition.output?.render !== "function" ||
|
|
117
|
+
typeof definition.output?.presentationMeta !== "function" ||
|
|
118
|
+
JSON.stringify(canonical(definition.output.schema)) !== JSON.stringify(canonical(schema))) {
|
|
119
|
+
throw new Error("[agent-guard] READ_GUARD_STARTUP_REFUSED");
|
|
120
|
+
}
|
|
121
|
+
const execute = definition.execute, render = definition.output.render, meta = definition.output.presentationMeta;
|
|
122
|
+
const schemaSnapshot = JSON.stringify(canonical(definition.output.schema));
|
|
123
|
+
// Conformance check against the pinned read projectors. Plugin composition
|
|
124
|
+
// is trusted; this check is not authentication of arbitrary plugin code.
|
|
125
|
+
const value = { path: "guard-probe.ini", offset: 1, lines: [{ number: 1, text: "PORT=8080" }], totalLines: 1 };
|
|
126
|
+
const rendered = render({ file_path: value.path }, value);
|
|
127
|
+
const expected = "<path>guard-probe.ini</path>\n<type>file</type>\n<content>\n1: PORT=8080\n\n(End of file - total 1 lines)\n</content>";
|
|
128
|
+
const projected = meta({ file_path: value.path }, value);
|
|
129
|
+
if (JSON.stringify(rendered) !== JSON.stringify([{ type: "text", text: expected }]) ||
|
|
130
|
+
JSON.stringify(canonical(projected)) !== JSON.stringify(canonical({ ...value, lang: "ini" }))) {
|
|
131
|
+
throw new Error("[agent-guard] READ_GUARD_STARTUP_REFUSED");
|
|
132
|
+
}
|
|
133
|
+
return (exec) => {
|
|
134
|
+
const current = tools.get("read", exec.agent);
|
|
135
|
+
return current === definition && current.execute === execute && current.output.render === render &&
|
|
136
|
+
current.output.presentationMeta === meta && current.finalizeContent === undefined &&
|
|
137
|
+
current.projectContent === undefined && JSON.stringify(canonical(current.output.schema)) === schemaSnapshot;
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export async function verifyReadRuntime(root, ctx) {
|
|
142
|
+
try {
|
|
143
|
+
if (!path.isAbsolute(root)) throw new Error();
|
|
144
|
+
const selected = fs.realpathSync(root);
|
|
145
|
+
const host = JSON.parse(fs.readFileSync(path.join(selected, "package.json"), "utf8"));
|
|
146
|
+
const runtime = Object.hasOwn(RUNTIMES, host.version) ? RUNTIMES[host.version] : undefined;
|
|
147
|
+
if (host.name !== "@deepseek-ai/dsh" || !runtime ||
|
|
148
|
+
Number(process.versions.node.split(".")[0]) !== 22) throw new Error();
|
|
149
|
+
const url = (name) => pathToFileURL(path.join(selected, "node_modules", "@deepseek-ai", name, "lib/index.js")).href;
|
|
150
|
+
for (const [name, hash] of Object.entries(runtime.artifacts)) {
|
|
151
|
+
const directory = path.join(selected, "node_modules", "@deepseek-ai", name);
|
|
152
|
+
const manifest = JSON.parse(fs.readFileSync(path.join(directory, "package.json"), "utf8"));
|
|
153
|
+
if (manifest.name !== "@deepseek-ai/" + name || manifest.version !== runtime.dependencyVersion ||
|
|
154
|
+
createHash("sha256").update(fs.readFileSync(path.join(directory, "lib/index.js"))).digest("hex") !== hash) {
|
|
155
|
+
throw new Error();
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
const { ToolRuntime } = await import(url("dsh-tools"));
|
|
159
|
+
const { LocalFileSystem } = await import(url("dsh-fs-local"));
|
|
160
|
+
if (!(ctx.get("tools") instanceof ToolRuntime) || !(ctx.get("fs") instanceof LocalFileSystem)) throw new Error();
|
|
161
|
+
if (host.version === "0.2.0-rc.2") {
|
|
162
|
+
const { SandboxedFileSystem } = await import(url("dsh-fs-sandbox"));
|
|
163
|
+
// Cordis wraps service methods, including constructor; the prototype
|
|
164
|
+
// retains the owning provider's identity without invoking a method.
|
|
165
|
+
if (![LocalFileSystem.prototype, SandboxedFileSystem.prototype].includes(Object.getPrototypeOf(ctx.get("fs")))) throw new Error();
|
|
166
|
+
}
|
|
167
|
+
} catch { throw new Error("[agent-guard] READ_GUARD_STARTUP_REFUSED"); }
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export async function installReadResultGuard(ctx, config, repoRoot) {
|
|
171
|
+
try {
|
|
172
|
+
// The worker and Core must belong to the same checkout/package.
|
|
173
|
+
const ownRoot = fs.realpathSync(path.resolve(path.dirname(WORKER), "..", "..", ".."));
|
|
174
|
+
if (fs.realpathSync(repoRoot) !== ownRoot || !path.isAbsolute(config.defaultCwd)) throw new Error();
|
|
175
|
+
const workspace = fs.realpathSync(config.defaultCwd);
|
|
176
|
+
await verifyReadRuntime(config.readGuardDshRoot, ctx);
|
|
177
|
+
const tools = ctx.get("tools");
|
|
178
|
+
const matches = pinReadBinding(tools);
|
|
179
|
+
const readiness = await scanReadValue({ path: "guard-probe.ini", offset: 1, lines: [], totalLines: 0 }, workspace);
|
|
180
|
+
if (readiness.kind !== "accept") throw new Error();
|
|
181
|
+
ctx.effect(() => {
|
|
182
|
+
const disposeGuard = tools.guard((exec) => {
|
|
183
|
+
if (exec.name !== "read") return;
|
|
184
|
+
if (exec.parent !== undefined || !matches(exec)) return "[agent-guard] READ_RESULT_BINDING";
|
|
185
|
+
});
|
|
186
|
+
const disposePost = ctx.on("tools/post-execute", async (exec, result, next) => {
|
|
187
|
+
if (exec.name !== "read") return next();
|
|
188
|
+
try {
|
|
189
|
+
const decision = await next();
|
|
190
|
+
if (!matches(exec) || exec.parent !== undefined) return blockRead("READ_RESULT_BINDING");
|
|
191
|
+
if (decision.kind === "block") return blockRead("READ_RESULT_POLICY");
|
|
192
|
+
const emptyContexts = (contexts) => contexts === undefined || (Array.isArray(contexts) && contexts.length === 0);
|
|
193
|
+
if (decision.kind !== "accept" || Object.hasOwn(decision, "content") ||
|
|
194
|
+
!emptyContexts(decision.additionalContexts) || !emptyContexts(result.additionalContexts)) {
|
|
195
|
+
return blockRead("READ_RESULT_CONTEXT");
|
|
196
|
+
}
|
|
197
|
+
if (exec.agent?.session?.header?.cwd && fs.realpathSync(exec.agent.session.header.cwd) !== workspace) {
|
|
198
|
+
return blockRead("READ_RESULT_BINDING");
|
|
199
|
+
}
|
|
200
|
+
if (result.isError) return blockRead("READ_RESULT_SCAN_FAILED");
|
|
201
|
+
return await scanReadValue(Object.hasOwn(decision, "value") ? decision.value : result.value, workspace, exec.signal);
|
|
202
|
+
} catch { return blockRead("READ_RESULT_SCAN_FAILED"); }
|
|
203
|
+
}, { prepend: true });
|
|
204
|
+
return () => { disposePost(); disposeGuard(); };
|
|
205
|
+
});
|
|
206
|
+
} catch { throw new Error("[agent-guard] READ_GUARD_STARTUP_REFUSED"); }
|
|
207
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Bounded stdin/stdout worker for the opt-in DSH text-read prototype.
|
|
3
|
+
|
|
4
|
+
Only the shared Core decides what is secret. No raw data in argv, files,
|
|
5
|
+
diagnostics or policy explanations. Successful stdout belongs to the adapter.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import sys
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
ROOT = Path(__file__).resolve().parents[3]
|
|
14
|
+
sys.path.insert(0, str(ROOT))
|
|
15
|
+
sys.path.insert(0, str(ROOT / "skills" / "exfil-guard" / "scripts"))
|
|
16
|
+
|
|
17
|
+
from core import policy # noqa: E402
|
|
18
|
+
from sanitize import apply_plan, sanitize_text # noqa: E402
|
|
19
|
+
|
|
20
|
+
MAX_INPUT_BYTES = 1024 * 1024
|
|
21
|
+
MAX_OUTPUT_BYTES = 2 * MAX_INPUT_BYTES
|
|
22
|
+
MAX_INTEGER = 2 ** 53 - 1
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def blocked(code):
|
|
26
|
+
return {"kind": "block", "code": code}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def integer(value, minimum=0):
|
|
30
|
+
return type(value) is int and minimum <= value <= MAX_INTEGER
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def validate_value(value):
|
|
34
|
+
if not isinstance(value, dict) or set(value) != {"path", "offset", "lines", "totalLines"}:
|
|
35
|
+
raise ValueError("schema")
|
|
36
|
+
if not isinstance(value["path"], str) or any(c in value["path"] for c in "\n\r\x00"):
|
|
37
|
+
raise ValueError("schema")
|
|
38
|
+
if not integer(value["offset"], 1) or not integer(value["totalLines"]):
|
|
39
|
+
raise ValueError("schema")
|
|
40
|
+
lines = value["lines"]
|
|
41
|
+
if not isinstance(lines, list) or len(lines) > 20000:
|
|
42
|
+
raise ValueError("schema")
|
|
43
|
+
for index, line in enumerate(lines):
|
|
44
|
+
if not isinstance(line, dict) or set(line) != {"number", "text"}:
|
|
45
|
+
raise ValueError("schema")
|
|
46
|
+
if not integer(line["number"], 1) or line["number"] != value["offset"] + index:
|
|
47
|
+
raise ValueError("schema")
|
|
48
|
+
if not isinstance(line["text"], str) or "\n" in line["text"]:
|
|
49
|
+
raise ValueError("schema")
|
|
50
|
+
# Strict UTF-8; escaped lone surrogates must never become a clean result.
|
|
51
|
+
value["path"].encode("utf-8", errors="strict")
|
|
52
|
+
for line in lines:
|
|
53
|
+
line["text"].encode("utf-8", errors="strict")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def redact(text, workspace, keep_lines=False):
|
|
57
|
+
result = sanitize_text(text, "llm-request", workspace=workspace)
|
|
58
|
+
if result["decision"] not in (policy.DECISION_ALLOW, policy.DECISION_SANITIZE):
|
|
59
|
+
raise PermissionError("policy")
|
|
60
|
+
plan = result["plan"]
|
|
61
|
+
if keep_lines:
|
|
62
|
+
# Keep DSH's original line numbers, including multiline key blocks.
|
|
63
|
+
# The entire original span is removed; blank continuation lines only
|
|
64
|
+
# preserve layout. The Core applicator owns all offset replacement.
|
|
65
|
+
plan = [dict(entry, placeholder=entry["placeholder"] +
|
|
66
|
+
"\n" * text[entry["start"]:entry["end"]].count("\n"))
|
|
67
|
+
for entry in plan]
|
|
68
|
+
replaced = apply_plan(text, plan)
|
|
69
|
+
checked = sanitize_text(replaced, "llm-request", workspace=workspace)
|
|
70
|
+
if checked["decision"] != policy.DECISION_ALLOW or checked["plan"]:
|
|
71
|
+
raise PermissionError("verification")
|
|
72
|
+
return replaced, len(plan)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def protect(request):
|
|
76
|
+
try:
|
|
77
|
+
if not isinstance(request, dict) or set(request) != {"workspace", "value"}:
|
|
78
|
+
return blocked("READ_RESULT_SCHEMA")
|
|
79
|
+
workspace = request["workspace"]
|
|
80
|
+
if not isinstance(workspace, str) or not Path(workspace).is_absolute():
|
|
81
|
+
return blocked("READ_RESULT_SCHEMA")
|
|
82
|
+
workspace.encode("utf-8", errors="strict")
|
|
83
|
+
value = request["value"]
|
|
84
|
+
validate_value(value)
|
|
85
|
+
if value["offset"] != 1 or len(value["lines"]) != value["totalLines"]:
|
|
86
|
+
return blocked("READ_RESULT_INCOMPLETE")
|
|
87
|
+
# Native read truncates long lines before policy receives them.
|
|
88
|
+
if any("... (line truncated to " in line["text"] for line in value["lines"]):
|
|
89
|
+
return blocked("READ_RESULT_INCOMPLETE")
|
|
90
|
+
filename, path_count = redact(value["path"], workspace)
|
|
91
|
+
text = "\n".join(line["text"] for line in value["lines"])
|
|
92
|
+
text, line_count = redact(text, workspace, keep_lines=True)
|
|
93
|
+
texts = text.split("\n") if value["lines"] else []
|
|
94
|
+
if len(texts) != len(value["lines"]):
|
|
95
|
+
return blocked("READ_RESULT_SCHEMA")
|
|
96
|
+
output = dict(value, path=filename, lines=[
|
|
97
|
+
{"number": line["number"], "text": sanitized}
|
|
98
|
+
for line, sanitized in zip(value["lines"], texts)])
|
|
99
|
+
count = path_count + line_count
|
|
100
|
+
return {"kind": "accept", "value": output,
|
|
101
|
+
"decision": "SANITIZE" if count else "ALLOW", "redactions": count}
|
|
102
|
+
except PermissionError:
|
|
103
|
+
return blocked("READ_RESULT_POLICY")
|
|
104
|
+
except (ValueError, TypeError, UnicodeError):
|
|
105
|
+
return blocked("READ_RESULT_SCHEMA")
|
|
106
|
+
except Exception:
|
|
107
|
+
return blocked("READ_RESULT_SCAN_FAILED")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def unique_object(pairs):
|
|
111
|
+
value = {}
|
|
112
|
+
for key, item in pairs:
|
|
113
|
+
if key in value:
|
|
114
|
+
raise ValueError("duplicate field")
|
|
115
|
+
value[key] = item
|
|
116
|
+
return value
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def main():
|
|
120
|
+
try:
|
|
121
|
+
payload = sys.stdin.buffer.read(MAX_INPUT_BYTES + 1)
|
|
122
|
+
if len(payload) > MAX_INPUT_BYTES:
|
|
123
|
+
result = blocked("READ_RESULT_SIZE")
|
|
124
|
+
else:
|
|
125
|
+
request = json.loads(payload.decode("utf-8", errors="strict"),
|
|
126
|
+
object_pairs_hook=unique_object,
|
|
127
|
+
parse_constant=lambda _: (_ for _ in ()).throw(ValueError("constant")))
|
|
128
|
+
result = protect(request)
|
|
129
|
+
encoded = json.dumps(result, ensure_ascii=False, allow_nan=False).encode("utf-8")
|
|
130
|
+
if len(encoded) > MAX_OUTPUT_BYTES:
|
|
131
|
+
encoded = json.dumps(blocked("READ_RESULT_SIZE")).encode("ascii")
|
|
132
|
+
except Exception:
|
|
133
|
+
encoded = json.dumps(blocked("READ_RESULT_SCAN_FAILED")).encode("ascii")
|
|
134
|
+
sys.stdout.buffer.write(encoded + b"\n")
|
|
135
|
+
return 0
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
if __name__ == "__main__":
|
|
139
|
+
sys.exit(main())
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Bounded POSIX process capture shared by the Lab harness runners."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import selectors
|
|
10
|
+
import signal
|
|
11
|
+
import subprocess
|
|
12
|
+
import time
|
|
13
|
+
from typing import Sequence
|
|
14
|
+
|
|
15
|
+
from core.lab import LabError, MAX_SCAN_BYTES
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def digest(payload: bytes) -> str:
|
|
19
|
+
return hashlib.sha256(payload).hexdigest()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def read_regular(path: Path, limit: int) -> bytes:
|
|
23
|
+
if path.is_symlink() or not path.is_file():
|
|
24
|
+
raise LabError("expected a regular non-symlink input file")
|
|
25
|
+
with path.open("rb") as stream:
|
|
26
|
+
payload = stream.read(limit + 1)
|
|
27
|
+
if len(payload) > limit:
|
|
28
|
+
raise LabError("input exceeds its supported size limit")
|
|
29
|
+
return payload
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def write_new(path: Path, payload: bytes) -> None:
|
|
33
|
+
descriptor = os.open(
|
|
34
|
+
path, os.O_WRONLY | os.O_CREAT | os.O_EXCL
|
|
35
|
+
| getattr(os, "O_NOFOLLOW", 0), 0o600,
|
|
36
|
+
)
|
|
37
|
+
with os.fdopen(descriptor, "wb") as stream:
|
|
38
|
+
stream.write(payload)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def write_json(path: Path, value: dict) -> None:
|
|
42
|
+
write_new(path, (json.dumps(value, sort_keys=True, indent=2) + "\n").encode())
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def capture_process(
|
|
46
|
+
argv: Sequence[str], cwd: Path, environment: dict[str, str], timeout: float,
|
|
47
|
+
) -> tuple[dict, dict[str, bytes]]:
|
|
48
|
+
if os.name != "posix":
|
|
49
|
+
raise LabError("Lab process capture currently supports POSIX hosts only")
|
|
50
|
+
streams = {"stdout": bytearray(), "stderr": bytearray()}
|
|
51
|
+
result = {
|
|
52
|
+
"exit_code": None, "timed_out": False, "output_limit_exceeded": False,
|
|
53
|
+
"start_failed": False,
|
|
54
|
+
}
|
|
55
|
+
try:
|
|
56
|
+
process = subprocess.Popen(
|
|
57
|
+
list(argv), cwd=cwd, env=environment, stdin=subprocess.DEVNULL,
|
|
58
|
+
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
|
59
|
+
start_new_session=True, close_fds=True,
|
|
60
|
+
)
|
|
61
|
+
except OSError:
|
|
62
|
+
result["start_failed"] = True
|
|
63
|
+
return result, {name: bytes(value) for name, value in streams.items()}
|
|
64
|
+
deadline = time.monotonic() + timeout
|
|
65
|
+
try:
|
|
66
|
+
with selectors.DefaultSelector() as selector:
|
|
67
|
+
selector.register(process.stdout, selectors.EVENT_READ, "stdout")
|
|
68
|
+
selector.register(process.stderr, selectors.EVENT_READ, "stderr")
|
|
69
|
+
while selector.get_map():
|
|
70
|
+
if time.monotonic() >= deadline:
|
|
71
|
+
result["timed_out"] = True
|
|
72
|
+
break
|
|
73
|
+
for key, _ in selector.select(timeout=0.05):
|
|
74
|
+
chunk = os.read(key.fileobj.fileno(), 65536)
|
|
75
|
+
if not chunk:
|
|
76
|
+
selector.unregister(key.fileobj)
|
|
77
|
+
continue
|
|
78
|
+
output = streams[key.data]
|
|
79
|
+
remaining = MAX_SCAN_BYTES - len(output)
|
|
80
|
+
output.extend(chunk[:remaining])
|
|
81
|
+
if len(chunk) > remaining:
|
|
82
|
+
result["output_limit_exceeded"] = True
|
|
83
|
+
break
|
|
84
|
+
if result["output_limit_exceeded"]:
|
|
85
|
+
break
|
|
86
|
+
if not result["timed_out"] and not result["output_limit_exceeded"]:
|
|
87
|
+
try:
|
|
88
|
+
process.wait(timeout=max(0.01, deadline - time.monotonic()))
|
|
89
|
+
except subprocess.TimeoutExpired:
|
|
90
|
+
result["timed_out"] = True
|
|
91
|
+
finally:
|
|
92
|
+
# Only this invocation's fresh process group is signalled.
|
|
93
|
+
try:
|
|
94
|
+
os.killpg(process.pid, signal.SIGTERM)
|
|
95
|
+
except ProcessLookupError:
|
|
96
|
+
pass
|
|
97
|
+
try:
|
|
98
|
+
process.wait(timeout=1)
|
|
99
|
+
except subprocess.TimeoutExpired:
|
|
100
|
+
pass
|
|
101
|
+
try:
|
|
102
|
+
os.killpg(process.pid, signal.SIGKILL)
|
|
103
|
+
except ProcessLookupError:
|
|
104
|
+
pass
|
|
105
|
+
process.wait(timeout=2)
|
|
106
|
+
process.stdout.close()
|
|
107
|
+
process.stderr.close()
|
|
108
|
+
result["exit_code"] = process.returncode
|
|
109
|
+
return result, {name: bytes(value) for name, value in streams.items()}
|
|
@@ -13,10 +13,17 @@ Code's hooks, so `pre_tool_use.py` here delegates to
|
|
|
13
13
|
Verified against **@moonshot-ai/kimi-code 0.42.0 and 2.1.1**. The detailed
|
|
14
14
|
contract comparison below was established against 0.42.0; the 2.1.1 trials
|
|
15
15
|
independently observed authenticated root `Bash` blocks through the same
|
|
16
|
-
exit-2 hook path on an OAuth official
|
|
17
|
-
|
|
16
|
+
exit-2 hook path on an OAuth official model and a second configured model
|
|
17
|
+
route. Connection details and private route identifiers are omitted. See the
|
|
18
18
|
[bounded report](../../docs/test-report-kimi-code-block.md).
|
|
19
19
|
|
|
20
|
+
For the separate honeytoken experiment, see the
|
|
21
|
+
[guard-lab pair and local follow-up](../../docs/test-report-kimi-guard-lab.md).
|
|
22
|
+
Its recorded tool-channel exposure and matched guarded observation are distinct
|
|
23
|
+
from native Bash interception. A local doctor pass does not rerun that pair.
|
|
24
|
+
Use the [private capture/review helper](harness/README.md) to repeat the Lab
|
|
25
|
+
workflow with a pinned executable and separate role-channel scans.
|
|
26
|
+
|
|
20
27
|
## Contract (what was checked, not assumed)
|
|
21
28
|
|
|
22
29
|
| Surface | Kimi Code 0.42.0 | Claude Code | Match |
|
|
@@ -111,17 +118,18 @@ It does not describe a missing hook or a failed hook command.
|
|
|
111
118
|
`BLOCK / BLOCK_UNDETERMINABLE_EFFECT`. A shape rule describes
|
|
112
119
|
*compensation* difficulty rather than effect scope, so it no longer
|
|
113
120
|
returns before the hard boundaries are evaluated. Regression suite:
|
|
114
|
-
`tests/test_incident_regression.py`. A
|
|
121
|
+
`tests/test_incident_regression.py`. A shape-only ASK now asks
|
|
115
122
|
the agent to split and retry instead of proceeding without compensation.
|
|
116
123
|
The 2.1.1 live sentinel exercised a hard `BLOCK`, not a live ASK path, so
|
|
117
124
|
this conservative mapping is not advertised as a 2.1.1 approval-UI test.
|
|
118
125
|
- **Subagent inheritance is observational, not a blanket guarantee.** In two
|
|
119
|
-
isolated
|
|
120
|
-
calls reached the native hook and produced recoverable audit
|
|
126
|
+
isolated sandboxes using one configured model route, single and concurrent
|
|
127
|
+
subagent Bash calls reached the native hook and produced recoverable audit
|
|
128
|
+
records.
|
|
121
129
|
A third isolated project then showed [execution-level `BLOCK` enforcement](../../docs/test-report-kimi-code-block.md)
|
|
122
130
|
for one root and one single-subagent inert Bash probe. Its separate root
|
|
123
131
|
`ASK` probe was denied. A fourth isolated project reproduced these bounded
|
|
124
|
-
paths using
|
|
132
|
+
paths using a second configured request model ID and
|
|
125
133
|
verified a recoverable deletion/restore cycle. Two same-turn subagents
|
|
126
134
|
each received `BLOCK`, but their Bash calls reached the hook seconds apart;
|
|
127
135
|
simultaneous hook execution, other tools/routes, backend model identity,
|
|
@@ -141,7 +149,7 @@ It does not describe a missing hook or a failed hook command.
|
|
|
141
149
|
matcher, fails to spawn, or times out. The host remains fail-open for those
|
|
142
150
|
cases; a verified interpreter path is risk reduction, not a hard boundary.
|
|
143
151
|
- **The bridge was exercised through a new Kimi 0.42.0 host session** using
|
|
144
|
-
the
|
|
152
|
+
the second configured request model ID: one harmless Bash call was
|
|
145
153
|
blocked under a process-local invalid dialect, and a separate harmless
|
|
146
154
|
Bash call ran under the normal dialect. The denied sentinel was absent,
|
|
147
155
|
the allowed sentinel was present, and the block was audited. A later
|