@mokuyoaxis/agent-guard 0.2.2

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.
Files changed (77) hide show
  1. package/CONTRIBUTING.md +101 -0
  2. package/LICENSE +21 -0
  3. package/README.md +558 -0
  4. package/README.zh-CN.md +488 -0
  5. package/adapters/INTEGRATION.md +94 -0
  6. package/adapters/claude/README.md +141 -0
  7. package/adapters/claude/compatibility.json +17 -0
  8. package/adapters/claude/harness/README.md +59 -0
  9. package/adapters/claude/harness/mock_anthropic_api.mjs +47 -0
  10. package/adapters/claude/harness/run_scenario.sh +79 -0
  11. package/adapters/claude/harness/run_scenario_no_python3.sh +49 -0
  12. package/adapters/claude/hook_bridge.sh +33 -0
  13. package/adapters/claude/pre_tool_use.py +264 -0
  14. package/adapters/claude/settings.example.json +16 -0
  15. package/adapters/codex/harness/README.md +53 -0
  16. package/adapters/codex/harness/acceptance.py +226 -0
  17. package/adapters/dsh/README.md +62 -0
  18. package/adapters/dsh/cordis.patch.yml +30 -0
  19. package/adapters/dsh/lib/index.js +500 -0
  20. package/adapters/kimi-code/README.md +169 -0
  21. package/adapters/kimi-code/compatibility.json +17 -0
  22. package/adapters/kimi-code/config.example.toml +26 -0
  23. package/adapters/kimi-code/hook_bridge.sh +32 -0
  24. package/adapters/kimi-code/pre_tool_use.py +72 -0
  25. package/core/__init__.py +47 -0
  26. package/core/audit.py +86 -0
  27. package/core/classifier.py +1175 -0
  28. package/core/dialects.py +898 -0
  29. package/core/policy.py +817 -0
  30. package/core/recovery.py +700 -0
  31. package/core/redaction.py +1096 -0
  32. package/core/safe_view.py +212 -0
  33. package/docs/architecture.md +223 -0
  34. package/docs/compatibility.md +142 -0
  35. package/docs/development-note-unguarded-deletion.md +187 -0
  36. package/docs/friction.md +266 -0
  37. package/docs/harness-capabilities.md +72 -0
  38. package/docs/host-drift.md +142 -0
  39. package/docs/publishing-from-ephemeral-environments.md +104 -0
  40. package/docs/release-notes-0.2.0-rc1.md +46 -0
  41. package/docs/release-notes-0.2.0.md +72 -0
  42. package/docs/release-notes-0.2.1.md +78 -0
  43. package/docs/release-notes-0.2.2.md +120 -0
  44. package/docs/secret-guard-analysis.md +416 -0
  45. package/docs/secret-guard-architecture.md +93 -0
  46. package/docs/secret-guard-design.md +649 -0
  47. package/docs/test-report-claude-code-harness.md +462 -0
  48. package/docs/test-report-codex-gpt-5.6-sol.md +335 -0
  49. package/docs/test-report-codex-gpt-6-astra-high.md +129 -0
  50. package/docs/test-report-dsh-0.1.5-rc.1.md +84 -0
  51. package/docs/test-report-dsh-v0.1.1.md +126 -0
  52. package/docs/test-report-kimi-code-block.md +198 -0
  53. package/docs/test-report-zcode-glm-flash.md +241 -0
  54. package/docs/threat-model.md +44 -0
  55. package/doctor.py +756 -0
  56. package/live_sentinel.py +339 -0
  57. package/package.json +69 -0
  58. package/skills/delete-guard/SKILL.md +109 -0
  59. package/skills/delete-guard/agents/openai.yaml +4 -0
  60. package/skills/delete-guard/references/policy.md +161 -0
  61. package/skills/delete-guard/scripts/_bootstrap.py +8 -0
  62. package/skills/delete-guard/scripts/check.py +370 -0
  63. package/skills/delete-guard/scripts/gc.py +103 -0
  64. package/skills/delete-guard/scripts/restore.py +98 -0
  65. package/skills/delete-guard/scripts/safe_delete.py +256 -0
  66. package/skills/delete-guard/scripts/status.py +130 -0
  67. package/skills/exfil-guard/SKILL.md +143 -0
  68. package/skills/exfil-guard/agents/openai.yaml +4 -0
  69. package/skills/exfil-guard/references/channels.md +58 -0
  70. package/skills/exfil-guard/references/rules.md +194 -0
  71. package/skills/exfil-guard/scripts/_bootstrap.py +8 -0
  72. package/skills/exfil-guard/scripts/check_span.py +250 -0
  73. package/skills/exfil-guard/scripts/sanitize.py +155 -0
  74. package/skills/exfil-guard/scripts/view.py +44 -0
  75. package/skills/recovery-audit/SKILL.md +283 -0
  76. package/skills/recovery-audit/agents/openai.yaml +4 -0
  77. package/skills/recovery-audit/references/evidence-records.md +85 -0
@@ -0,0 +1,500 @@
1
+ /**
2
+ * agent-guard - DSH host adapter (Decision Protocol).
3
+ *
4
+ * A Cordis plugin for the DeepSeek Harness launcher composition. Three
5
+ * contributions:
6
+ *
7
+ * 1. Interception: a `tools/pre-execute` waterfall runs every destructive-
8
+ * looking bash command through the shared Python core (check.py
9
+ * --enforce) BEFORE execution, and maps the Decision Protocol onto
10
+ * PreToolDecision: ALLOW -> run (compensation already applied),
11
+ * ASK -> native ask (degrades to deny on harnesses without ask),
12
+ * BLOCK -> deny with explanation and remediation.
13
+ * 2. Model tools: agent_guard_safe_delete / agent_guard_restore /
14
+ * agent_guard_status - the supported path is also the easiest path.
15
+ * 3. Prompt guidance: deletion discipline as a system-prompt section.
16
+ *
17
+ * The decision rules are NOT implemented here. This adapter only translates;
18
+ * the single rule engine lives in skills/delete-guard/scripts/check.py,
19
+ * shipped inside this package and resolved relative to this module unless
20
+ * config.repoRoot points at a live checkout (development mode).
21
+ *
22
+ * Positioning: automatic recovery system with human escalation - reliability
23
+ * infrastructure, not a security sandbox. See docs/threat-model.md.
24
+ */
25
+
26
+ import fs from "node:fs";
27
+ import path from "node:path";
28
+ import { fileURLToPath } from "node:url";
29
+
30
+ export const name = "agent_guard";
31
+
32
+ /** Services that must resolve before apply() runs. */
33
+ export const inject = ["tools", "shell", "systemPrompt"];
34
+
35
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
36
+ // lib -> adapters/dsh -> repository root (where core/ and skills/ live).
37
+ const PACKAGE_ROOT = path.resolve(__dirname, "..", "..", "..");
38
+ // Keep the configuration boundary aligned with core/dialects.py. Tool- or
39
+ // environment-supplied names still go to Core for a BLOCK_DIALECT_* verdict.
40
+ const CONFIG_DIALECTS = new Set([
41
+ "posix", "sh", "bash", "zsh", "cmd", "cmd.exe", "batch", "bat",
42
+ "powershell", "pwsh", "ps",
43
+ ]);
44
+ const CONFIG_FIELDS = new Set([
45
+ "repoRoot", "defaultCwd", "promptSection", "sectionOrder", "dialect",
46
+ ]);
47
+
48
+ // Keep the adapter installable without importing a host-private helper. DSH's
49
+ // public registry accepts plain Tool Definition objects; defineTool() only
50
+ // compiles this small authoring schema and wraps argument validation. Doing the
51
+ // same locally avoids coupling package resolution to DSH's internal dependency
52
+ // tree while retaining fail-closed validation at the tool boundary.
53
+ function compileParameters(spec) {
54
+ const properties = {};
55
+ const required = [];
56
+ for (const [key, value] of Object.entries(spec)) {
57
+ const { required: isRequired, ...schema } = value;
58
+ properties[key] = schema;
59
+ if (isRequired === true) required.push(key);
60
+ }
61
+ return {
62
+ type: "object",
63
+ properties,
64
+ ...(required.length > 0 ? { required } : {}),
65
+ additionalProperties: true,
66
+ };
67
+ }
68
+
69
+ function assertToolArgs(name, spec, args) {
70
+ if (args === null || typeof args !== "object" || Array.isArray(args)) {
71
+ throw new TypeError(`${name}: arguments must be an object`);
72
+ }
73
+ for (const [key, schema] of Object.entries(spec)) {
74
+ const value = args[key];
75
+ if (value === undefined) {
76
+ if (schema.required === true) {
77
+ throw new TypeError(`${name}: missing required argument ${key}`);
78
+ }
79
+ continue;
80
+ }
81
+ if (schema.type === "string" && typeof value !== "string") {
82
+ throw new TypeError(`${name}: ${key} must be a string`);
83
+ }
84
+ if (schema.type === "array") {
85
+ if (!Array.isArray(value)) {
86
+ throw new TypeError(`${name}: ${key} must be an array`);
87
+ }
88
+ if (schema.items?.type === "string" &&
89
+ value.some((item) => typeof item !== "string")) {
90
+ throw new TypeError(`${name}: ${key} items must be strings`);
91
+ }
92
+ }
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Composition-row configuration (cordis.patch.yml).
98
+ *
99
+ * The loader validates this export through the Standard Schema interface
100
+ * (`Config["~standard"].validate`), so a plain property bag cannot be used
101
+ * here - resolveConfig would read `undefined.validate` and the whole plugin
102
+ * tree would fail to load. Kept dependency-free on purpose: the guard ships
103
+ * with no third-party imports, so the tiny standard-schema surface is
104
+ * written by hand rather than pulling in schemastery.
105
+ */
106
+ export const Config = {
107
+ "~standard": {
108
+ version: 1,
109
+ vendor: "agent-guard",
110
+ validate(value) {
111
+ // Only an absent config gets defaults. An explicit null or wrong field
112
+ // must not quietly turn a requested Windows dialect into POSIX.
113
+ const input = value === undefined ? {} : value;
114
+ if (input === null || typeof input !== "object" || Array.isArray(input)) {
115
+ return { issues: [{ message: "agent-guard config must be an object" }] };
116
+ }
117
+ const issues = [];
118
+ const config = {
119
+ repoRoot: "",
120
+ defaultCwd: "",
121
+ promptSection: true,
122
+ sectionOrder: 105,
123
+ dialect: "",
124
+ };
125
+ for (const key of Object.keys(input)) {
126
+ if (!CONFIG_FIELDS.has(key)) {
127
+ issues.push({ message: `unknown agent-guard config field: ${key}`, path: [key] });
128
+ }
129
+ }
130
+ for (const key of ["repoRoot", "defaultCwd"]) {
131
+ if (!Object.prototype.hasOwnProperty.call(input, key)) continue;
132
+ if (typeof input[key] !== "string") {
133
+ issues.push({ message: `${key} must be a string`, path: [key] });
134
+ } else {
135
+ config[key] = input[key];
136
+ }
137
+ }
138
+ if (Object.prototype.hasOwnProperty.call(input, "promptSection")) {
139
+ if (typeof input.promptSection !== "boolean") {
140
+ issues.push({ message: "promptSection must be a boolean", path: ["promptSection"] });
141
+ } else {
142
+ config.promptSection = input.promptSection;
143
+ }
144
+ }
145
+ if (Object.prototype.hasOwnProperty.call(input, "sectionOrder")) {
146
+ if (typeof input.sectionOrder !== "number" || !Number.isFinite(input.sectionOrder)) {
147
+ issues.push({ message: "sectionOrder must be a finite number", path: ["sectionOrder"] });
148
+ } else {
149
+ config.sectionOrder = input.sectionOrder;
150
+ }
151
+ }
152
+ if (Object.prototype.hasOwnProperty.call(input, "dialect")) {
153
+ const requested = input.dialect;
154
+ if (typeof requested !== "string" ||
155
+ (requested !== "" && !CONFIG_DIALECTS.has(requested.trim().toLowerCase()))) {
156
+ issues.push({ message: "dialect must name a supported shell dialect", path: ["dialect"] });
157
+ } else {
158
+ config.dialect = requested;
159
+ }
160
+ }
161
+ return issues.length ? { issues } : { value: config };
162
+ },
163
+ },
164
+ };
165
+
166
+ // Aligned with core/classifier.py vocabulary (V1: Linux/macOS).
167
+ const DESTRUCTIVE_RE = new RegExp(
168
+ "\\b(rm|rmdir|unlink|shred)\\b" +
169
+ "|\\bfind\\b[^\\n|;&]*-delete\\b" +
170
+ "|\\bgit\\b[^\\n|;&]*\\b(clean|reset|restore|checkout|push)\\b"
171
+ );
172
+
173
+ // Windows-native vocabulary (cmd / PowerShell). Screen both vocabularies
174
+ // regardless of dialect: the selector chooses the lexer, not whether a
175
+ // destructive-looking command reaches the guard at all.
176
+ const DESTRUCTIVE_RE_WINDOWS = new RegExp(
177
+ "\\b(rm|ri|rd|rmdir|del|erase|remove-item)\\b" +
178
+ "|-\\s?(recurse|force|whatif|literalpath)\\b" +
179
+ "|\\bgit\\b[^\\n|;&]*\\b(clean|reset|restore|checkout|push)\\b",
180
+ "i"
181
+ );
182
+
183
+ function dialectSelector(args, config, env) {
184
+ const fromArgs = args && args.dialect;
185
+ if (typeof fromArgs === "string" && fromArgs.trim()) return fromArgs;
186
+ const fromEnv = env && env.AGENT_GUARD_DIALECT;
187
+ if (typeof fromEnv === "string" && fromEnv.trim()) return fromEnv;
188
+ if (typeof config.dialect === "string" && config.dialect.trim()) {
189
+ return config.dialect;
190
+ }
191
+ return undefined;
192
+ }
193
+
194
+ /**
195
+ * Build the adapter runtime for one apply() invocation.
196
+ * @param ctx - registrant context carrying injected services.
197
+ * @param config - validated composition-row configuration.
198
+ */
199
+ function buildRuntime(ctx, config, shell, systemPrompt) {
200
+ const repoRoot = config.repoRoot || PACKAGE_ROOT;
201
+ const scriptsDir = path.join(repoRoot, "skills", "delete-guard", "scripts");
202
+ const pythonReady = fs.existsSync(path.join(scriptsDir, "check.py"));
203
+
204
+ // The caller's sandbox policy travels with the session so guard
205
+ // invocations inherit exactly what the calling agent already has.
206
+ function policyFor(exec) {
207
+ const service = ctx.get ? ctx.get("sandboxPolicy") : undefined;
208
+ const session = exec && exec.agent && exec.agent.session;
209
+ if (!service || session === undefined) return undefined;
210
+ try {
211
+ return service.resolve({ session });
212
+ } catch (_) {
213
+ return undefined;
214
+ }
215
+ }
216
+
217
+ function shQuote(value) {
218
+ return "'" + String(value).replace(/'/g, "'\\''") + "'";
219
+ }
220
+
221
+ function outText(collected) {
222
+ if (collected === undefined || collected === null) return "";
223
+ if (typeof collected === "string") return collected;
224
+ return collected.text || "";
225
+ }
226
+
227
+ function runScript(scriptName, argString, workdir, timeoutMs, exec) {
228
+ const request = {
229
+ command:
230
+ "python3 " +
231
+ shQuote(path.join(scriptsDir, scriptName)) +
232
+ (argString ? " " + argString : ""),
233
+ timeoutMs: timeoutMs || 45000,
234
+ stdoutMaxBytes: 1048576,
235
+ sandboxPolicy: policyFor(exec),
236
+ };
237
+ const dir = workdir || config.defaultCwd || undefined;
238
+ if (dir) request.workdir = dir;
239
+ if (exec && exec.signal) request.signal = exec.signal;
240
+ return shell.run(shell.resolve(request));
241
+ }
242
+
243
+ function parseJson(text) {
244
+ try {
245
+ return JSON.parse(text);
246
+ } catch (_) {
247
+ return undefined;
248
+ }
249
+ }
250
+
251
+ return {
252
+ shell,
253
+ systemPrompt,
254
+ repoRoot,
255
+ scriptsDir,
256
+ pythonReady,
257
+ shQuote,
258
+ runScript,
259
+ outText,
260
+ parseJson,
261
+ };
262
+ }
263
+
264
+ export function apply(ctx, config) {
265
+ const shell = ctx.get ? ctx.get("shell") : undefined;
266
+ if (shell === undefined) {
267
+ console.error("[agent-guard] shell service unavailable; adapter disabled");
268
+ return;
269
+ }
270
+ const systemPrompt = ctx.get ? ctx.get("systemPrompt") : undefined;
271
+ const rt = buildRuntime(ctx, config, shell, systemPrompt);
272
+
273
+ if (!rt.pythonReady) {
274
+ console.error("[agent-guard] check.py not found under", rt.repoRoot);
275
+ return;
276
+ }
277
+
278
+ ctx.effect(() => {
279
+ const disposers = [];
280
+
281
+ // ---- 1) interception -------------------------------------------------
282
+ disposers.push(
283
+ ctx.on("tools/pre-execute", async (exec, next) => {
284
+ if (!exec || exec.name !== "bash") return next();
285
+ const args = exec.arguments || {};
286
+ const command =
287
+ typeof args.command === "string" ? args.command : "";
288
+ // A dialect selector is still forwarded to the Core for validation.
289
+ const selector = dialectSelector(args, config, process.env);
290
+ if (!command ||
291
+ !(DESTRUCTIVE_RE.test(command) || DESTRUCTIVE_RE_WINDOWS.test(command))) {
292
+ return next();
293
+ }
294
+
295
+ // An unusable selector is still forwarded: check.py owns the
296
+ // verdict and BLOCKs it explicitly instead of silently guessing
297
+ // a lexer.
298
+ const dialectFlag =
299
+ selector !== undefined ? "--dialect " + rt.shQuote(selector) : "";
300
+
301
+ let result;
302
+ try {
303
+ result = await rt.runScript(
304
+ "check.py",
305
+ "--enforce --json" +
306
+ (dialectFlag ? " " + dialectFlag : "") +
307
+ " -- " +
308
+ rt.shQuote(command),
309
+ typeof args.workdir === "string" ? args.workdir : undefined,
310
+ 90000,
311
+ exec
312
+ );
313
+ } catch (_err) {
314
+ console.error("[agent-guard] check.py infrastructure error");
315
+ return {
316
+ kind: "deny",
317
+ reason: "[agent-guard] guard infrastructure error (fail-closed)",
318
+ };
319
+ }
320
+ const verdict = rt.parseJson(rt.outText(result.stdout));
321
+ if (!verdict || !verdict.decision) {
322
+ console.error("[agent-guard] unparseable guard output");
323
+ return {
324
+ kind: "deny",
325
+ reason: "[agent-guard] unparseable guard output (fail-closed)",
326
+ };
327
+ }
328
+ if (verdict.decision === "ALLOW") {
329
+ const comps = verdict.compensations || [];
330
+ if (comps.length > 0) {
331
+ console.log(
332
+ "[agent-guard] compensated",
333
+ comps.length,
334
+ "check_id=" + (verdict.check_id || "unknown")
335
+ );
336
+ }
337
+ return next();
338
+ }
339
+ const reasons = Array.isArray(verdict.reasons)
340
+ ? verdict.reasons.join("; ")
341
+ : "";
342
+ if (verdict.decision === "ASK") {
343
+ return {
344
+ kind: "ask",
345
+ reason:
346
+ "[agent-guard] " +
347
+ verdict.code +
348
+ ": " +
349
+ (verdict.explanation || reasons),
350
+ };
351
+ }
352
+ return {
353
+ kind: "deny",
354
+ reason:
355
+ "[agent-guard] BLOCKED [" +
356
+ verdict.code +
357
+ "] " +
358
+ (verdict.explanation || "") +
359
+ (reasons ? " (" + reasons + ")" : "") +
360
+ " | Restate with explicit workspace-relative paths, or use " +
361
+ "agent_guard_safe_delete. Do NOT circumvent the guard.",
362
+ };
363
+ })
364
+ );
365
+
366
+ // ---- 2) model tools --------------------------------------------------
367
+ function renderJson(_args, value) {
368
+ return [
369
+ { type: "text", text: JSON.stringify(value, null, 2).slice(0, 4000) },
370
+ ];
371
+ }
372
+
373
+ const CWD_PROP = {
374
+ type: "string",
375
+ description:
376
+ "Working directory (repo root) for this operation; defaults to the session workspace.",
377
+ };
378
+
379
+ function makeTool(name, description, parameterSpec, buildArgs) {
380
+ return {
381
+ name,
382
+ description,
383
+ parameters: compileParameters(parameterSpec),
384
+ output: {
385
+ schema: { type: "object", additionalProperties: true },
386
+ render: renderJson,
387
+ },
388
+ execute: async (args, exec) => {
389
+ assertToolArgs(name, parameterSpec, args);
390
+ const plan = buildArgs(args);
391
+ const result = await rt.runScript(
392
+ plan.script,
393
+ plan.argString,
394
+ plan.workdir,
395
+ 120000,
396
+ exec
397
+ );
398
+ const parsed = rt.parseJson(rt.outText(result.stdout));
399
+ return {
400
+ ok: result.exitCode === 0,
401
+ exitCode: result.exitCode,
402
+ report: parsed === undefined ? rt.outText(result.stdout) : parsed,
403
+ stderr: rt.outText(result.stderr).slice(0, 2000),
404
+ };
405
+ },
406
+ };
407
+ }
408
+
409
+ disposers.push(
410
+ ctx.tools.register(
411
+ makeTool(
412
+ "agent_guard_status",
413
+ "Show agent-guard state: authorization mode, quarantine usage, retention/GC view, recent decisions.",
414
+ { cwd: CWD_PROP },
415
+ (args) => ({ script: "status.py", argString: "--json", workdir: args.cwd })
416
+ )
417
+ )
418
+ );
419
+ disposers.push(
420
+ ctx.tools.register(
421
+ makeTool(
422
+ "agent_guard_safe_delete",
423
+ "Recoverable delete: globs expanded explicitly, targets quarantined to .agent-trash/ with a manifest. Preferred over raw rm.",
424
+ {
425
+ paths: {
426
+ type: "array",
427
+ items: { type: "string" },
428
+ required: true,
429
+ description: "Paths or globs relative to the workspace root.",
430
+ },
431
+ reason: { type: "string", description: "Why this deletion is needed." },
432
+ cwd: CWD_PROP,
433
+ },
434
+ (args) => {
435
+ const parts = args.paths.map((p) => rt.shQuote(p));
436
+ parts.push("--json");
437
+ if (args.reason) parts.push("--reason " + rt.shQuote(args.reason));
438
+ return { script: "safe_delete.py", argString: parts.join(" "), workdir: args.cwd };
439
+ }
440
+ )
441
+ )
442
+ );
443
+ disposers.push(
444
+ ctx.tools.register(
445
+ makeTool(
446
+ "agent_guard_restore",
447
+ "List quarantine transactions, or restore one by txid. Refuses to overwrite an occupied origin path.",
448
+ {
449
+ txid: { type: "string", description: "Omit to list transactions." },
450
+ cwd: CWD_PROP,
451
+ },
452
+ (args) => {
453
+ if (!args.txid)
454
+ return { script: "restore.py", argString: "list --json", workdir: args.cwd };
455
+ return {
456
+ script: "restore.py",
457
+ argString: "restore " + rt.shQuote(args.txid) + " --json",
458
+ workdir: args.cwd,
459
+ };
460
+ }
461
+ )
462
+ )
463
+ );
464
+
465
+ // ---- 3) prompt guidance ----------------------------------------------
466
+ if (systemPrompt !== undefined && config.promptSection !== false) {
467
+ disposers.push(
468
+ systemPrompt.section({
469
+ name: "agent-guard-delete-discipline",
470
+ order: config.sectionOrder ?? 105,
471
+ text: [
472
+ "## Deletion discipline (agent-guard)",
473
+ "",
474
+ "This workspace runs agent-guard: an automatic recovery system with human escalation - not an approval system. Irreversible destruction is not a default capability.",
475
+ "",
476
+ "- To delete files/directories/globs, prefer the agent_guard_safe_delete tool: targets are quarantined under .agent-trash/ with a manifest and stay restorable. Pass cwd when operating in a repo below the workspace root.",
477
+ "- Raw rm / git clean / git reset --hard are intercepted before execution. Most are compensated automatically (relocate or snapshot) and simply proceed; note the txid.",
478
+ "- Shape rules: a command line that cds before deleting (COMPOUND_CWD_DELETE), or creates files and then deletes them (COMPOUND_CREATE_DELETE), triggers a single-execution user authorization. Splitting the deletion into its own standalone command avoids the prompt entirely.",
479
+ "- True effect-uncertainty ($VAR targets, bash -c, find -delete, xargs-fed lists) stays hard-BLOCKED: restating with explicit concrete paths is the only remedy.",
480
+ "- BLOCK_OUT_OF_WORKSPACE, BLOCK_PROTECTED_PATH (.git, workspace root) and BLOCK_FORCE_PUSH are policy violations and never askable: do not retry variants; ask the human if truly needed.",
481
+ "- In RESTRICTED mode only explicit single-file deletes inside the workspace are permitted; only a human can restore NORMAL.",
482
+ "- Never circumvent the guard (no /bin/rm, python os.unlink, node fs.rmSync, relocated scripts). Every decision is audit-logged; circumvention is a violation.",
483
+ "- Undo with agent_guard_restore(txid). Inspect state with agent_guard_status().",
484
+ ].join("\n"),
485
+ })
486
+ );
487
+ }
488
+
489
+ return () => {
490
+ while (disposers.length) {
491
+ const d = disposers.pop();
492
+ try {
493
+ d();
494
+ } catch (_) {
495
+ /* best effort */
496
+ }
497
+ }
498
+ };
499
+ }, "agent-guard-contributions");
500
+ }
@@ -0,0 +1,169 @@
1
+ # Kimi Code adapter
2
+
3
+ PreToolUse interception for [Kimi Code CLI](https://github.com/MoonshotAI/kimi-code),
4
+ built on the shared Core and Claude Code adapter with one conservative
5
+ host-specific difference: Core `ASK` is mapped to a hard refusal rather than
6
+ being allowed when the host cannot enforce an approval.
7
+ Kimi Code ships an external-hook system
8
+ (`packages/agent-core-v2/src/features/externalHooks`) whose event names,
9
+ payload field names and decision contract are field-compatible with Claude
10
+ Code's hooks, so `pre_tool_use.py` here delegates to
11
+ `../claude/pre_tool_use.py` instead of reimplementing the mapping.
12
+
13
+ Verified against **@moonshot-ai/kimi-code 0.42.0 and 2.1.1**. The detailed
14
+ contract comparison below was established against 0.42.0; the 2.1.1 trials
15
+ independently observed authenticated root `Bash` blocks through the same
16
+ exit-2 hook path on an OAuth official route and on official K3 through a
17
+ maintainer-confirmed trusted relay. See the
18
+ [bounded report](../../docs/test-report-kimi-code-block.md).
19
+
20
+ ## Contract (what was checked, not assumed)
21
+
22
+ | Surface | Kimi Code 0.42.0 | Claude Code | Match |
23
+ |---|---|---|---|
24
+ | Payload encoding | JSON on stdin, `camelToSnake` at the boundary | JSON on stdin | ✓ |
25
+ | Tool name field | `tool_name` | `tool_name` | ✓ |
26
+ | Arguments field | `tool_input` (object) | `tool_input` | ✓ |
27
+ | Working directory | `cwd` | `cwd` | ✓ |
28
+ | Session id | `session_id` | `session_id` | ✓ |
29
+ | Event name field | `hook_event_name` | `hook_event_name` | ✓ |
30
+ | Hard block | process exit code `2`, stderr fed back to the model | same | ✓ |
31
+ | Soft decision | Only `deny` blocks; `ask` is treated as allow | `ask` can request approval | **different** |
32
+ | Hook config | `~/.kimi-code/config.toml`, `[[hooks]]` array | `.claude/settings.json` | different shape |
33
+
34
+ `resultFromExitCode()` in the Kimi Code bundle maps `2` to
35
+ `{action: "block"}` and otherwise parses stdout through
36
+ `HookJsonOutputSchema`. Its `structuredOutput()` produces a block only for
37
+ `permissionDecision: "deny"`; every other value, including `"ask"`, is
38
+ allowed. `blockDecision()` collects any hook result with `action === "block"`.
39
+
40
+ ## Install
41
+
42
+ 1. Add the hook and the skill root to `~/.kimi-code/config.toml` — see
43
+ [`config.example.toml`](config.example.toml). `matcher` is a **regular
44
+ expression** matched against the tool name; an empty string matches every
45
+ tool. Use `^Bash$` to select only the shell tool. An unanchored `Bash`
46
+ pattern can also match future tool names containing that word. The example
47
+ invokes the POSIX [shell bridge](hook_bridge.sh) with absolute shell and
48
+ Python paths. Replace all three example paths with paths on your machine;
49
+ quote paths containing spaces for the shell command string. Directly
50
+ invoking `python3 pre_tool_use.py` leaves Python startup failures exposed
51
+ to Kimi's fail-open behavior.
52
+
53
+ 2. Keep `extraSkillDirs` pointing at this repository's `skills/` directory so
54
+ the model also gets the discipline, not just the enforcement:
55
+
56
+ ```toml
57
+ extraSkillDirs = ["/absolute/path/to/agent-guard/skills"]
58
+ ```
59
+
60
+ 3. Restart the session. Hooks are read at session start.
61
+
62
+ 4. From the repository root, run `python3 doctor.py kimi --probe`. The doctor
63
+ checks the configured matcher and command, then exercises the bridge with
64
+ harmless Bash payloads, a Bash→Core policy refusal, the host-specific
65
+ ASK→hard-refusal mapping, and a deliberately missing interpreter. `--json`
66
+ reports `configuration`, `local_probe`, and
67
+ `host_interception` separately; the latter remains `UNVERIFIED` even when
68
+ the local probe passes. The doctor also rejects an invalid
69
+ `AGENT_GUARD_DIALECT` in the current process. It does **not** invoke a
70
+ model, edit the configuration, inspect a running Kimi session, or prove
71
+ host-level interception. The optional Kimi doctor uses Python 3.11+ for
72
+ TOML parsing; the guard adapter itself continues to support Python 3.9+.
73
+ Add `--check-drift` to compare the installed Kimi Code version with the
74
+ shipped profile and compute privacy-safe configuration/runtime
75
+ fingerprints. `CURRENT` still does not prove live interception; see the
76
+ [drift status contract](../../docs/host-drift.md).
77
+ An explicit `--live-sentinel` may then use one configured model call in a
78
+ private fixture and requires adapter, audit, host-feedback, and marker
79
+ evidence. The selected file must be named `config.toml`; the runner does
80
+ not rewrite it. Kimi prompt mode uses its machine-readable stream; adding
81
+ `--auto` or `--yolo` is neither needed nor valid alongside `--prompt` in
82
+ Kimi 2.x.
83
+
84
+ ## Decision mapping
85
+
86
+ The shared Claude adapter supplies the Core call and normal mappings; Kimi
87
+ sets `ask_is_block=True` because this CLI cannot enforce a prompt:
88
+
89
+ | Core decision | Adapter output |
90
+ |---|---|
91
+ | `ALLOW`, no compensations | exit 0, silent |
92
+ | `ALLOW`, compensations applied | exit 0 + `permissionDecision: "allow"` (reason names the quarantine) |
93
+ | `ASK` | exit 2, stderr explains that the command must be split/restated |
94
+ | `BLOCK` | exit 2, stderr fed back to the model |
95
+ | Malformed `PreToolUse` JSON or missing required Bash fields | exit 2 (fail-closed) |
96
+ | guard failure / adapter bug caught after Python starts | exit 2 (fail-closed for that call) |
97
+ | Python fails to start, but the shell bridge runs | bridge converts the failure to exit 2 |
98
+
99
+ This table describes adapter output **when the adapter actually starts**.
100
+ It does not describe a missing hook or a failed hook command.
101
+
102
+ ## Known limitations — read before claiming interception
103
+
104
+ - **ASK is not supported by this host's hook contract.** Even outside
105
+ `kimi --auto`, Kimi 0.42.0 treats `permissionDecision: "ask"` as allow.
106
+ This adapter therefore maps Core ASK to exit 2 (BLOCK). The failure class
107
+ is described in the public
108
+ [`development note`](../../docs/development-note-unguarded-deletion.md),
109
+ and it is fixed:
110
+ `cd /tmp && rm -rf "$PWD/../home"` now classifies as
111
+ `BLOCK / BLOCK_UNDETERMINABLE_EFFECT`. A shape rule describes
112
+ *compensation* difficulty rather than effect scope, so it no longer
113
+ returns before the hard boundaries are evaluated. Regression suite:
114
+ `tests/test_incident_regression.py`. A genuinely shape-only ASK now asks
115
+ the agent to split and retry instead of proceeding without compensation.
116
+ The 2.1.1 live sentinel exercised a hard `BLOCK`, not a live ASK path, so
117
+ this conservative mapping is not advertised as a 2.1.1 approval-UI test.
118
+ - **Subagent inheritance is observational, not a blanket guarantee.** In two
119
+ isolated `local/kimi-k3` sandboxes, single and concurrent subagent Bash
120
+ calls reached the native hook and produced recoverable audit records.
121
+ A third isolated project then showed [execution-level `BLOCK` enforcement](../../docs/test-report-kimi-code-block.md)
122
+ for one root and one single-subagent inert Bash probe. Its separate root
123
+ `ASK` probe was denied. A fourth isolated project reproduced these bounded
124
+ paths using the separate `kimi-code/kimi-for-coding` request model ID and
125
+ verified a recoverable deletion/restore cycle. Two same-turn subagents
126
+ each received `BLOCK`, but their Bash calls reached the hook seconds apart;
127
+ simultaneous hook execution, other tools/routes, backend model identity,
128
+ and broader scheduling patterns remain untested.
129
+ - **Config is read at session start**, so a running session keeps its old hook
130
+ set until restarted.
131
+ - Strict payload refusal only applies **after this hook is invoked**. It cannot
132
+ detect or block a missing hook, a mismatched `Bash` matcher, or a host that
133
+ stops emitting `PreToolUse`.
134
+ - **Host fail-open was observed when the old direct-Python hook command failed
135
+ before Python started.** In an isolated Kimi 0.42.0 trial, a process-local failing
136
+ `python3` shim made a Bash call execute even though the correctly started
137
+ adapter would have returned `BLOCK_DIALECT_UNKNOWN`. The sentinel appeared
138
+ and no guard audit event was added. See the [bounded report](../../docs/test-report-kimi-code-block.md).
139
+ The bridge changes this particular failure into exit 2 **if the bridge
140
+ itself starts**. It cannot block a hook that is absent, skipped by the
141
+ matcher, fails to spawn, or times out. The host remains fail-open for those
142
+ cases; a verified interpreter path is risk reduction, not a hard boundary.
143
+ - **The bridge was exercised through a new Kimi 0.42.0 host session** using
144
+ the `kimi-code/kimi-for-coding` request model ID: one harmless Bash call was
145
+ blocked under a process-local invalid dialect, and a separate harmless
146
+ Bash call ran under the normal dialect. The denied sentinel was absent,
147
+ the allowed sentinel was present, and the block was audited. A later
148
+ process-local Python startup fault returned exit 1 before the adapter ran;
149
+ the bridge converted it to Kimi's hard refusal, and the sentinel stayed
150
+ absent. This does not test a bridge-spawn failure or timeout; see the
151
+ [bounded report](../../docs/test-report-kimi-code-block.md).
152
+ - Kimi's `doctor config` accepted a hook-free test config and an invalid
153
+ regex matcher; it checks configuration validity, not live interception.
154
+ In the installed 0.42.0 bundle, a matcher regex error yields no match.
155
+ - This adapter covers `Bash` only, matching the Claude adapter's scope.
156
+
157
+ ## Verification
158
+
159
+ ```sh
160
+ # Should exit 2 with a BLOCK code (the string is data, never executed):
161
+ printf '%s' '{"hook_event_name":"PreToolUse","session_id":"t","cwd":"/tmp/agent-guard-kimi-sandbox-20260921","tool_name":"Bash","tool_input":{"command":"rm -rf /"},"tool_call_id":"c1"}' \
162
+ | python3 adapters/kimi-code/pre_tool_use.py; echo "exit=$?"
163
+
164
+ # Should exit 0 silently:
165
+ printf '%s' '{"hook_event_name":"PreToolUse","session_id":"t","cwd":"/tmp/agent-guard-kimi-sandbox-20260921","tool_name":"Bash","tool_input":{"command":"ls -la"},"tool_call_id":"c2"}' \
166
+ | python3 adapters/kimi-code/pre_tool_use.py; echo "exit=$?"
167
+ ```
168
+
169
+ Set `AGENT_GUARD_DEBUG=1` to print the raw Core verdict JSON to stderr.
@@ -0,0 +1,17 @@
1
+ {
2
+ "schema_version": 1,
3
+ "profile_id": "kimi-code-pretooluse-bash-v1",
4
+ "harness": "kimi",
5
+ "display_name": "Kimi Code",
6
+ "executable_candidates": ["kimi", "kimi-code"],
7
+ "version_args": ["--version"],
8
+ "version_pattern": "(?<![0-9])([0-9]+\\.[0-9]+\\.[0-9]+)(?![0-9])",
9
+ "tested_versions": ["0.42.0", "2.1.1"],
10
+ "contract": {
11
+ "event": "PreToolUse",
12
+ "tools": ["Bash"],
13
+ "blocking": true,
14
+ "ask": "hard-deny",
15
+ "configuration_scope": "selected-file-only"
16
+ }
17
+ }