@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,26 @@
1
+ # Kimi Code adapter - agent-guard
2
+ #
3
+ # Append to ~/.kimi-code/config.toml. Hooks are read at session start, so
4
+ # restart the session after editing.
5
+ #
6
+ # `matcher` is a REGULAR EXPRESSION tested against the tool name
7
+ # (`matches()` in the Kimi Code bundle uses `new RegExp(pattern).test(value)`;
8
+ # an empty pattern matches everything). Anchor it to the shell tool.
9
+
10
+ # Give the model the delete-guard / exfil-guard / recovery-audit skills too,
11
+ # so it learns the discipline instead of only meeting the enforcement.
12
+ # Keep this pointed at the checkout rather than copying, so there is one
13
+ # source of truth for the rule engine.
14
+ extraSkillDirs = ["/absolute/path/to/agent-guard/skills"]
15
+
16
+ [[hooks]]
17
+ event = "PreToolUse"
18
+ matcher = "^Bash$"
19
+ # Replace all three paths for your machine. Use an absolute POSIX sh and Python.
20
+ # The shell bridge turns Python launch failures into Kimi's blocking exit 2.
21
+ command = "/bin/sh /absolute/path/to/agent-guard/adapters/kimi-code/hook_bridge.sh /absolute/path/to/python3"
22
+ timeout = 90
23
+
24
+ # Optional: surface the raw Core verdict on stderr for troubleshooting.
25
+ # [experimental]
26
+ # agent_guard_debug = true
@@ -0,0 +1,32 @@
1
+ #!/bin/sh
2
+ # Kimi treats hook failures other than exit 2 as allow. Keep this POSIX shell
3
+ # bridge alive long enough to turn a failed Python launch into an explicit 2.
4
+ # A missing/unmatched hook or a host timeout is still fail-open.
5
+
6
+ if [ "$#" -ne 1 ]; then
7
+ printf '%s\n' '[agent-guard] Kimi hook bridge needs one absolute Python path' >&2
8
+ exit 2
9
+ fi
10
+
11
+ case "$1" in
12
+ /*) python_bin=$1 ;;
13
+ *)
14
+ printf '%s\n' '[agent-guard] Kimi hook Python path must be absolute' >&2
15
+ exit 2
16
+ ;;
17
+ esac
18
+
19
+ bridge_dir=$(CDPATH= cd -P "$(dirname "$0")" 2>/dev/null && pwd -P) || {
20
+ printf '%s\n' '[agent-guard] Kimi hook bridge directory unavailable' >&2
21
+ exit 2
22
+ }
23
+
24
+ "$python_bin" "$bridge_dir/pre_tool_use.py"
25
+ status=$?
26
+ case "$status" in
27
+ 0|2) exit "$status" ;;
28
+ *)
29
+ printf '[agent-guard] Kimi hook process failed (exit %s); refusing tool call\n' "$status" >&2
30
+ exit 2
31
+ ;;
32
+ esac
@@ -0,0 +1,72 @@
1
+ #!/usr/bin/env python3
2
+ """Kimi Code PreToolUse hook - agent-guard adapter (Decision Protocol).
3
+
4
+ Kimi Code's external-hook contract is **field-compatible** with Claude Code's
5
+ PreToolUse hook. Verified against @moonshot-ai/kimi-code 0.42.0
6
+ (`packages/agent-core-v2/src/features/externalHooks`):
7
+
8
+ payload (stdin, snake_case JSON)
9
+ hook_event_name, session_id, cwd, client_type, session_title,
10
+ tool_name, tool_input, tool_call_id
11
+ - the harness camelCases internally and converts to snake_case at the
12
+ boundary (`toHookInputData` -> `camelToSnake`), so field names land
13
+ exactly where Claude Code puts them.
14
+
15
+ decision contract
16
+ exit 2 -> BLOCK, stderr fed back to the model
17
+ exit 0 + hookSpecificOutput -> permissionDecision allow
18
+
19
+ Kimi Code 0.42.0 treats permissionDecision="ask" as allow. The shared
20
+ adapter therefore runs with ask_is_block=True: a Core ASK is refused
21
+ until the agent restates it as separately checkable commands.
22
+ Kimi also opts into strict_payload=True: a malformed PreToolUse payload
23
+ received by this hook is refused instead of silently accepted.
24
+
25
+ Authenticated Kimi Code 2.1.1 live sentinels later observed the same
26
+ PreToolUse Bash exit-2 block path on an OAuth official model and on official
27
+ K3 through a maintainer-confirmed relay. The detailed field/source comparison
28
+ above remains versioned to 0.42.0; each 2.1.1 claim is deliberately limited
29
+ to the observed root Bash call recorded in the public test report.
30
+
31
+ config (TOML, ~/.kimi-code/config.toml)
32
+ [[hooks]]
33
+ event = "PreToolUse"
34
+ matcher = "^Bash$" # regular expression over the tool name
35
+ command = "/bin/sh /path/to/agent-guard/adapters/kimi-code/hook_bridge.sh /absolute/path/to/python3"
36
+ timeout = 90
37
+
38
+ Because the two contracts match, this adapter **delegates to the shared
39
+ Claude adapter** rather than reimplementing the payload -> core -> decision
40
+ mapping. The repository rule is one implementation per decision surface; a
41
+ second copy here would drift the first time either harness changes.
42
+
43
+ What is Kimi-specific and therefore lives here or in README.md:
44
+ - the config file location and the `[[hooks]]` TOML shape;
45
+ - `matcher` is a **regular expression** (empty matches every tool);
46
+ - subagent inheritance: Kimi Code runs hooks from the same runner for
47
+ `SubagentStart`/`SubagentStop`, and PreToolUse is triggered from the
48
+ shared tool executor. Whether a *subagent's* Bash call reaches this hook
49
+ must be proven by observing the event, not assumed - see README.md.
50
+
51
+ Set AGENT_GUARD_DEBUG=1 to surface the raw core verdict on stderr.
52
+ """
53
+ from __future__ import annotations
54
+
55
+ import os
56
+ import runpy
57
+ import sys
58
+
59
+ _HERE = os.path.dirname(os.path.abspath(__file__))
60
+ _REPO_ROOT = os.path.dirname(os.path.dirname(_HERE))
61
+ _CLAUDE_ADAPTER = os.path.join(_REPO_ROOT, "adapters", "claude", "pre_tool_use.py")
62
+
63
+ if __name__ == "__main__":
64
+ try:
65
+ if not os.path.isfile(_CLAUDE_ADAPTER):
66
+ raise FileNotFoundError(_CLAUDE_ADAPTER)
67
+ shared = runpy.run_path(_CLAUDE_ADAPTER)
68
+ sys.exit(shared["main"](ask_is_block=True, strict_payload=True))
69
+ except Exception as exc: # never fail open on adapter bugs
70
+ sys.stderr.write(
71
+ f"[agent-guard] Kimi adapter error (fail-closed): {exc}\n")
72
+ sys.exit(2)
@@ -0,0 +1,47 @@
1
+ """agent-guard core: a reliability layer for autonomous AI agents.
2
+
3
+ Four pillars (see docs/architecture.md):
4
+
5
+ Scope - where the agent may act -> policy.py
6
+ Recoverability - whether mistakes can be undone -> recovery.py
7
+ Authorization - who decides what -> policy.py (mode state)
8
+ Auditability - what actually happened -> audit.py
9
+
10
+ classifier.py turns shell commands or explicit path lists into structured
11
+ operation facts; policy.py turns facts into verdicts; recovery.py executes
12
+ compensations (relocate / snapshot); audit.py records everything.
13
+
14
+ Guiding principle: uncertainty increases restriction (fail closed).
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import json as _json
19
+ import os as _os
20
+
21
+
22
+ def _package_version() -> str:
23
+ """The single source of truth for the version: the package manifest.
24
+
25
+ This used to be a hand-maintained literal, which drifted from
26
+ `package.json` the moment a release candidate was cut (the manifest said
27
+ 0.2.0 while this module still said 0.1.1). Reading the manifest removes
28
+ the second place to forget. When the core is vendored without one, say
29
+ so explicitly instead of reporting a version that may be wrong.
30
+ """
31
+ manifest = _os.path.join(
32
+ _os.path.dirname(_os.path.dirname(_os.path.abspath(__file__))),
33
+ "package.json")
34
+ try:
35
+ with open(manifest, "r", encoding="utf-8") as fh:
36
+ version = _json.load(fh).get("version")
37
+ except (OSError, ValueError):
38
+ return "0.0.0+unknown"
39
+ return version if isinstance(version, str) and version else "0.0.0+unknown"
40
+
41
+
42
+ __version__ = _package_version()
43
+
44
+ TRASH_DIRNAME = ".agent-trash"
45
+ MANIFEST_NAME = "manifest.jsonl"
46
+ AUDIT_NAME = "audit.jsonl"
47
+ STATE_NAME = "state.json"
package/core/audit.py ADDED
@@ -0,0 +1,86 @@
1
+ """Auditability pillar: append-only JSONL evidence log.
2
+
3
+ Every decision the guard makes - allow, relocate, compensate, block - is
4
+ appended as one JSON object per line. The log is intentionally dumb: no
5
+ rotation, no aggregation, no mutation. Post-hoc verification reads it
6
+ sequentially. A torn or corrupt line is skipped on read, never rewritten.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import getpass
11
+ import json
12
+ import os
13
+ import platform
14
+ import threading
15
+ import time
16
+ import uuid
17
+ from typing import Any, Dict, List, Optional
18
+
19
+ _APPEND_LOCK = threading.Lock()
20
+
21
+
22
+ def utc_now_iso() -> str:
23
+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
24
+
25
+
26
+ def new_txid() -> str:
27
+ """Compensation transaction id: sortable timestamp + random suffix."""
28
+ return time.strftime("%Y%m%d-%H%M%S", time.gmtime()) + "-" + uuid.uuid4().hex[:8]
29
+
30
+
31
+ def session_id() -> str:
32
+ """Best-effort identity of the acting session.
33
+
34
+ An agent harness may identify itself through AGENT_GUARD_SESSION.
35
+ This is correlation metadata, not authentication.
36
+ """
37
+ env = os.environ.get("AGENT_GUARD_SESSION")
38
+ if env:
39
+ return env
40
+ try:
41
+ user = getpass.getuser()
42
+ except Exception: # pragma: no cover - exotic passwd setups
43
+ user = "unknown"
44
+ # platform.node() is the cross-platform form of os.uname().nodename
45
+ # (os.uname does not exist on Windows); empty on exotic setups.
46
+ host = platform.node() or "localhost"
47
+ return f"{user}@{host}:{os.getpid()}"
48
+
49
+
50
+ def append(record: Dict[str, Any], audit_path: str) -> Dict[str, Any]:
51
+ """Append one record; returns the stored record (with defaults filled)."""
52
+ stored = dict(record)
53
+ stored.setdefault("ts", utc_now_iso())
54
+ stored.setdefault("session", session_id())
55
+ line = json.dumps(stored, ensure_ascii=False, sort_keys=True)
56
+ directory = os.path.dirname(audit_path)
57
+ if directory:
58
+ os.makedirs(directory, exist_ok=True)
59
+ with _APPEND_LOCK:
60
+ with open(audit_path, "a", encoding="utf-8") as fh:
61
+ fh.write(line + "\n")
62
+ fh.flush()
63
+ os.fsync(fh.fileno())
64
+ return stored
65
+
66
+
67
+ def tail(audit_path: str, n: int = 20) -> List[Dict[str, Any]]:
68
+ """Read the last n valid records. Corrupt/torn lines are skipped."""
69
+ if not os.path.exists(audit_path):
70
+ return []
71
+ records: List[Dict[str, Any]] = []
72
+ with open(audit_path, "r", encoding="utf-8") as fh:
73
+ for raw in fh:
74
+ raw = raw.strip()
75
+ if not raw:
76
+ continue
77
+ try:
78
+ records.append(json.loads(raw))
79
+ except json.JSONDecodeError:
80
+ continue
81
+ return records[-max(n, 0):]
82
+
83
+
84
+ def find_by_txid(audit_path: str, txid: str) -> List[Dict[str, Any]]:
85
+ """All audit records belonging to one compensation transaction."""
86
+ return [r for r in tail(audit_path, n=100_000) if r.get("txid") == txid]