@shidesheng0218/agentguard 0.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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +403 -0
  3. package/dist/cli.js +2857 -0
  4. package/package.json +60 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 kimi-guard contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,403 @@
1
+ <div align="center">
2
+
3
+ # ๐Ÿ›ก๏ธ agent-guard (formerly kimi-guard)
4
+
5
+ **A runtime behavior guard for coding agents โ€” [Kimi Code CLI](https://github.com/MoonshotAI/kimi-code) and [Claude Code](https://code.claude.com) โ€” stop runaway agent loops before they burn your quota.**
6
+
7
+ `npm i -g @shidesheng0218/agentguard && agentguard install` โ†’ done. (Existing users: `kguard`/`kimi-guard` keep working as aliases.)
8
+
9
+ [![npm](https://img.shields.io/npm/v/@shidesheng0218/agentguard?style=flat-square)](https://www.npmjs.com/package/@shidesheng0218/agentguard)
10
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](/LICENSE)
11
+ [![CI](https://img.shields.io/github/actions/workflow/status/shidesheng0218/kimi-guard/ci.yml?style=flat-square&label=CI)](/.github/workflows/ci.yml)
12
+
13
+ <img src="https://raw.githubusercontent.com/shidesheng0218/kimi-guard/main/assets/banner.svg" alt="kimi-guard banner" width="100%"/>
14
+
15
+ **[English](README.md) ยท [ไธญๆ–‡ๆ–‡ๆกฃ](docs/README.zh-CN.md)**
16
+
17
+ <div align="center">
18
+
19
+ ![kimi-guard demo](https://raw.githubusercontent.com/shidesheng0218/kimi-guard/main/assets/demo.gif?v=0.6.1)
20
+
21
+ *Real terminal session: install โ†’ verify โ†’ a supervised run where the circuit breaker catches a looping tool call โ†’ live status & budget panels. Recorded with [vhs](https://github.com/charmbracelet/vhs) from actual commands ([demo.tape](assets/demo.tape)).*
22
+
23
+ </div>
24
+
25
+ </div>
26
+
27
+ ---
28
+
29
+ ## Why
30
+
31
+ Kimi Code CLI is a great open-source coding agent, but its subagent system has known reliability gaps (see issues [#2142](https://github.com/MoonshotAI/kimi-cli/issues/2142), [#2368](https://github.com/MoonshotAI/kimi-cli/issues/2368), [#2578](https://github.com/MoonshotAI/kimi-cli/issues/2578)):
32
+
33
+ - The model repeats the **exact same tool call** dozens of times (76ร—, 112ร— observed in the wild), silently burning tokens โ€” fatal for headless/CI runs where nobody presses Ctrl+C.
34
+ - All subagents share **one API key**, so a burst of parallel dispatches exhausts TPM/RPM and everything hangs.
35
+ - A mid-batch quota error leaves **half-written workspaces** that poison the whole run.
36
+
37
+ kimi-guard is a local, zero-daemon guard that sits on the CLI's official [hooks system](https://www.kimi.com/code/docs/en/kimi-code-cli/customization/hooks.html) and enforces hard caps โ€” no source forking, no proxy, no account access.
38
+
39
+ Since v0.8 the same engine also guards **Claude Code** via its [hooks system](https://code.claude.com/docs/en/hooks) (`agentguard install` auto-detects installed harnesses). Wire-mode supervision (`agentguard run`), mid-turn steering and official-API quota metering remain Kimi-exclusive; loop/churn/explore detection, quota gates, the completion gate, kill switch and checkpoints work on both.
40
+
41
+ ## Features
42
+
43
+ kimi-guard is not a preset pack โ€” it is a **runtime behavior analysis and enforcement engine**. Every tool call flows through a normalization layer, a set of pure analyzers, and a policy engine that maps findings to actions (observe / warn / block / full stop).
44
+
45
+ | Guard | Signal it detects | Action |
46
+ |---|---|---|
47
+ | ๐Ÿ” **Repetition** | same `(tool, args)` signature re-run N times (whitespace-tolerant fingerprinting) | block |
48
+ | ๐Ÿ”„ **Cycle detection** | oscillating loops: `Aโ†’Bโ†’Aโ†’Bโ€ฆ` up to period-3, regardless of tool | block |
49
+ | ๐Ÿ“‰ **No-information-gain** | different arguments, byte-identical output โ€” the model is spinning without new data (the real root cause of upstream [#2142](https://github.com/MoonshotAI/kimi-cli/issues/2142) Case B) | warn โ†’ block |
50
+ | โœ๏ธ **Edit churn** | the same file edited over and over without converging ("thrashing") | warn โ†’ block |
51
+ | ๐Ÿข **No-progress stretch** | long run of tool calls with no successful edit landing โ€” motion without progress | warn โ†’ block |
52
+ | ๐Ÿ”ญ **Exploration drift** | long streak of read/search calls with no action in between โ€” exploring without implementing | warn โ†’ block |
53
+ | ๐ŸŽฏ **Goal anchor** | re-injects the original task verbatim every N prompts/steps and always after compaction โ€” the two moments a long session drifts off-target | context injection |
54
+ | ๐Ÿšฆ **Quota gate** | request accounting against Kimi Coding Plan windows (5h/weekly) with burn-rate projection; dispatches are blocked before the window is exhausted | warn โ†’ block |
55
+ | ๐Ÿ”Œ **Kill switch** | after N interventions in a session, block ALL tools and order the model to summarize and end its turn โ€” the fuse for unattended/CI runs | full stop |
56
+ | ๐Ÿงฏ **Context-fill gate** | when the context window crosses the threshold (Wire mode reads `StatusUpdate.context_usage`), steers a wrap-up warning before compaction hits | mid-turn steer |
57
+ | ๐Ÿงพ **Completion gate** | deterministic claim-vs-evidence check: "tests pass" claims are matched against the locally recorded command history โ€” an unbacked claim triggers a corrective round (Wire) or blocks the turn end (hooks, opt-in). Optionally an **LLM veto vote** (self-critic style: the LLM only votes to suppress false positives, never authors a critique) | verify round / block / veto |
58
+ | ๐Ÿง  **Thinking dominance** | flags turns that burned โ‰ฅ20k chars of pure reasoning with โ‰ค10% visible action โ€” fed back as "act more, think less" on the next resume | flag + resume note |
59
+ | ๐Ÿ” **Near-duplicate matching** | fuzzy loop detection: arguments differing only in punctuation, case, spacing or order still collapse to one signature | warn โ†’ block |
60
+ | ๐Ÿ’พ **Checkpoint / resume** | auto-captures an observed "research state" brief (files touched, commands, searches, failed calls) on failure/interrupt/session-end; `kguard resume` prints a paste-ready context block so a resumed session skips re-exploration | recovery |
61
+ | ๐ŸŽฎ **`kguard run` (Wire supervisor)** | spawns the agent in Wire mode (JSON-RPC) and supervises it *in-process*: hook decisions with zero exit-code overhead, **mid-turn steering** on warn findings, **exact per-step token metering** from `StatusUpdate`, retry observability (`StepRetry` status codes), approval policy for headless runs, hard step/time caps with `cancel`, auto-resume with checkpoint injection, and a full run report + raw wire log | CI / unattended runs |
62
+
63
+ Warn-level findings are injected into the model's context (official hooks stdout mechanism) so the agent can correct itself *before* a block becomes necessary. Blocks feed a structured reason back to the model (official exit-code-2 mechanism).
64
+
65
+ Everything is **fail-open**: if kimi-guard itself errors, the agent keeps working. It is a safety net, not a single point of failure.
66
+
67
+ ## Install
68
+
69
+ ```sh
70
+ npm i -g @shidesheng0218/agentguard
71
+ agentguard install # writes managed hooks into every detected harness
72
+ # (Kimi Code: ~/.kimi-code/config.toml ยท Claude Code: ~/.claude/settings.json)
73
+ agentguard doctor # verify
74
+ ```
75
+
76
+ Requires Node >= 22.13. Restart the agent CLI (or `/reload`) after installing.
77
+
78
+ Claude Code users can also install via the plugin channel (this repo is a self-hosted marketplace):
79
+
80
+ ```
81
+ /plugin marketplace add shidesheng0218/kimi-guard
82
+ /plugin install agent-guard@agentguard
83
+ ```
84
+
85
+ (The plugin's hooks call the `agentguard` CLI โ€” install it globally first; without it the hooks fail-open.)
86
+
87
+ ### Harness support
88
+
89
+ | Capability | Kimi Code CLI | Claude Code |
90
+ |---|---|---|
91
+ | Loop / churn / explore detection, kill switch | โœ… hooks | โœ… hooks |
92
+ | Quota gates | โœ… event-based + official-API precise (`[budget] precise`) | โœ… event-based estimates |
93
+ | Completion gate (claim vs evidence) | โœ… | โœ… |
94
+ | Checkpoints / resume, feedback loop, reports | โœ… | โœ… |
95
+ | `agentguard run` Wire supervision, mid-turn steer | โœ… | โ€” (hooks only) |
96
+
97
+ <details>
98
+ <summary>What <code>agentguard install</code> writes</summary>
99
+
100
+ Kimi Code (`~/.kimi-code/config.toml`):
101
+
102
+ ```toml
103
+ # >>> kimi-guard managed >>> DO NOT EDIT
104
+ [[hooks]]
105
+ event = "PreToolUse"
106
+ command = "agentguard hook PreToolUse"
107
+ timeout = 5
108
+
109
+ [[hooks]]
110
+ event = "PostToolUse"
111
+ command = "agentguard hook PostToolUse"
112
+ timeout = 5
113
+
114
+ [[hooks]]
115
+ event = "PostToolUseFailure"
116
+ command = "agentguard hook PostToolUseFailure"
117
+ timeout = 5
118
+
119
+ # + observation hooks: TurnStarted, SubagentStart, StopFailure, Interrupt, SessionEnd
120
+ # (these feed the budget metering and auto-checkpointing engines)
121
+ # <<< kimi-guard <<<
122
+ ```
123
+
124
+ Claude Code (`~/.claude/settings.json`):
125
+
126
+ ```json
127
+ {
128
+ "hooks": {
129
+ "PreToolUse": [
130
+ { "matcher": "", "hooks": [{ "type": "command", "command": "agentguard hook PreToolUse --harness claude", "timeout": 5 }] }
131
+ ]
132
+ }
133
+ }
134
+ ```
135
+
136
+ (+ PostToolUse, PostToolUseFailure, UserPromptSubmit, Stop, SubagentStart, SessionStart/End, PreCompact/PostCompact, StopFailure โ€” the events the guard handles.)
137
+
138
+ - Analyzers decide *which* tools to watch internally โ€” the hooks observe everything, so the watch lists stay configurable without reinstalling.
139
+ - A backup is created before the first install (`config.toml.kimi-guard.bak` / `settings.json.agentguard.bak`). `agentguard uninstall` removes the entries cleanly from both harnesses. The Kimi block coexists with other tools' managed blocks (e.g. kimi-boost).
140
+ - **Legacy compatibility**: if your CLI version rejects unknown hook events (older kimi-cli builds), run `agentguard install --compat` to write only the 3 universally supported events. You keep loop guarding; you lose auto-checkpointing and event-based metering.
141
+
142
+ </details>
143
+
144
+ ## Commands
145
+
146
+ ```sh
147
+ # binary is `agentguard`; `kguard` / `kimi-guard` remain as aliases โ€” all commands work with either name
148
+ kguard install # add hook rules to detected agent CLIs (idempotent)
149
+ kguard uninstall # remove the managed hook block
150
+ kguard status # calls, interventions, sessions, budget windows + intervention quality
151
+ kguard budget # quota metering snapshot: windows, burn rate, projection
152
+ kguard blocks [-n N] # recent blocks with ids
153
+ kguard feedback fp|tp <id> # mark a block false-positive / confirmed โ€” calibrates detectors
154
+ kguard report [--json] # anonymized aggregate export (safe to share)
155
+ kguard checkpoint # capture a research-state checkpoint now
156
+ kguard resume # print a paste-ready context block from the latest checkpoint
157
+ kguard run -- <prompt> # supervised headless run in Wire mode (see below)
158
+ kguard doctor # verify node/state db/config/PATH/probe
159
+ kguard probe on|off|show [โˆ’n N] # capture raw hook payloads
160
+ kguard config init|show|get <key> # manage ~/.kimi-guard/config.toml
161
+ kguard hook <event> # (used by the CLI, reads JSON from stdin)
162
+ ```
163
+
164
+ ### `kguard run` โ€” supervised headless runs
165
+
166
+ This is the tool for CI, cron jobs and unattended agents โ€” the exact scenario where a
167
+ repeating tool call burns the full timeout (upstream issue #2142 was a headless run).
168
+
169
+ ```sh
170
+ kguard run "refactor the auth module and make tests pass" \
171
+ --max-steps 100 --max-minutes 20 --auto-resume 1 --json
172
+ ```
173
+
174
+ What the supervisor does in-process (no shell hooks, no exit codes):
175
+
176
+ - subscribes to `PreToolUse` over the Wire protocol and returns `allow/block` decisions โ€” the same analyzers, zero-latency
177
+ - **steers** the agent mid-turn (`steer`) when a warn-level pattern appears, before a hard block is needed
178
+ - meters **exact token usage per step** from `StatusUpdate.token_usage`
179
+ - observes retry storms (`StepRetry` with status codes โ†’ 429 visibility)
180
+ - enforces hard caps: `--max-steps` (cancel via official `cancel` method), `--max-minutes`
181
+ - **kill switch**: after N blocks it cancels the turn and checkpoints
182
+ - approval policy: default rejects with feedback (headless-safe), `--yolo` approves
183
+ - writes a run report (`report.json`) + raw wire log (`wire.jsonl`) under `~/.kimi-guard/runs/`
184
+ - exit code 0 on clean finish, 2 on any intervention-triggered end โ€” CI-friendly
185
+
186
+ ## Configuration
187
+
188
+ `~/.kimi-guard/config.toml` (see `kguard config init`; full annotated template included):
189
+
190
+ ```toml
191
+ [tools] # canonical tool-name taxonomy โ€” if your CLI renames tools, fix it HERE
192
+ edit = ["WriteFile", "StrReplaceFile", "Edit", "Write", "MultiEdit", "NotebookEdit"]
193
+ read = ["ReadFile", "Read"]
194
+ search = ["Grep", "Glob"]
195
+ shell = ["Shell", "Bash"] # verify evidence + veto context read this (legacy [verify] shellTools still works)
196
+
197
+ [repeat] # exact/near-duplicate repetition
198
+ maxRepeats = 3
199
+ warnAt = 2 # soft context warning before the hard block
200
+ windowMinutes = 30
201
+ # exemptPatterns = [...] # regexes over JSON-serialized args; matching calls are never repeat-blocked (polling commands)
202
+
203
+ [cycle] # A->B->A->B oscillation detection
204
+ enabled = true
205
+
206
+ [noGain] # different args, identical output
207
+ warnAt = 3
208
+ blockAt = 4
209
+
210
+ [churn] # same-file edit thrashing
211
+ warnAt = 5
212
+ blockAt = 10
213
+
214
+ [noProgress] # long stretch of calls with no landed edit
215
+ warnAt = 15
216
+ blockAt = 25
217
+
218
+ [anchor] # goal anchoring (anti-drift)
219
+ everyNPrompts = 5
220
+ maxChars = 1000
221
+
222
+ [context]
223
+ warnPercent = 85 # steer a wrap-up warning when the context is this full
224
+
225
+ [nearRepeat] # fuzzy near-duplicates (punctuation/case/order differences)
226
+ warnAt = 6
227
+ blockAt = 10
228
+
229
+ [explore] # pure-exploration streak: reads/searches with no action in between
230
+ warnAt = 10
231
+ blockAt = 15
232
+
233
+ [verify] # completion-claim gate
234
+ enabled = true
235
+ blockOnNoEvidence = false # hooks path: block Stop when edits landed but nothing was verified
236
+ evidenceWindowMinutes = 60
237
+
238
+ [verify.veto] # optional false-positive suppression vote (off by default, zero deps when off)
239
+ enabled = false # requires KIMI_GUARD_VETO_API_KEY in the environment (any OpenAI-compatible endpoint)
240
+ model = "kimi-k3" # use a cheap fast model โ€” the vote costs a few hundred tokens
241
+ maxCallsPerSession = 3 # the model cannot retry its way out of the gate
242
+
243
+ [thinking] # thinking-dominance detection (Wire mode)
244
+ minThinkChars = 20000
245
+ maxTextRatio = 0.1
246
+
247
+ [policy]
248
+ killSwitch = true # after maxBlocksPerSession interventions, block ALL tools
249
+ maxBlocksPerSession = 5
250
+
251
+ [budget] # request accounting for Kimi Coding Plans
252
+ plan = "tier1" # tier1: 1024/week | tier2: 2048 | tier3: 7168 (200 per 5h)
253
+ reservePercent = 10 # headroom the agent is never allowed to eat
254
+ subagentWeight = 5 # ~requests each dispatched subagent costs
255
+ precise = false # poll the official Kimi usage API for exact windows (needs KIMI_API_KEY, sk-kimi-...)
256
+ # falls back to event-based estimates on any error โ€” fail-open
257
+ ```
258
+
259
+ ## How it works
260
+
261
+ ```mermaid
262
+ flowchart LR
263
+ subgraph KIMI["Kimi Code CLI"]
264
+ A["tool call"] -->|"hook event / Wire msg"| B
265
+ end
266
+ subgraph GUARD["kimi-guard"]
267
+ B["Normalization layer<br/>schema-variant tolerant<br/>+ output hashing"] --> C["Analyzers (pure functions)<br/>repeat ยท cycle ยท no-gain ยท churn<br/>no-progress ยท near-repeat ยท explore"]
268
+ M["Budget engine<br/>5h/weekly windows<br/>burn-rate projection"] --> C
269
+ C --> D["Policy engine<br/>findings โ†’ action<br/>+ kill switch"]
270
+ end
271
+ D -->|"allow"| E["exit 0"]
272
+ D -->|"warn"| F["context hint (stdout/steer)<br/>agent self-corrects first"]
273
+ D -->|"block"| G["exit 2 / HookRequest<br/>reason fed back to model"]
274
+ D -->|"kill"| H["cancel + checkpoint<br/>summarize and stop"]
275
+ ```
276
+
277
+ The completion gate adds a claim-vs-evidence loop on top:
278
+
279
+ ```mermaid
280
+ sequenceDiagram
281
+ participant A as Agent
282
+ participant G as kimi-guard
283
+ participant DB as local evidence (state.db)
284
+ A->>A: runs tools (Shell, edits...)
285
+ A->>G: turn ends, claims "all tests pass"
286
+ G->>DB: any successful test/build/lint command?
287
+ alt evidence found
288
+ G->>A: accept โœ…
289
+ else no evidence
290
+ opt LLM veto enabled (fail-closed, budget-capped)
291
+ G->>G: one vote: VETO yes/no
292
+ end
293
+ G->>A: corrective round โ€” "actually run verification"
294
+ end
295
+ ```
296
+
297
+ ```
298
+ Kimi Code CLI โ”€โ”€hook eventโ”€โ”€โ–ถ kguard hook <event> (JSON on stdin)
299
+ โ”‚
300
+ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
301
+ โ”‚ normalization layer โ”‚ schema-variant tolerant payload
302
+ โ”‚ (src/events.ts) โ”‚ โ†’ canonical call record + output hash
303
+ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
304
+ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
305
+ โ”‚ analyzers (pure functions) โ”‚ repetition ยท cycles ยท no-gain ยท churn
306
+ โ”‚ (src/analysis.ts) โ”‚ + budget gate (src/meter.ts)
307
+ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
308
+ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
309
+ โ”‚ policy engine โ”‚ findings โ†’ allow / warn / block
310
+ โ”‚ (src/policy.ts) โ”‚ + kill switch
311
+ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
312
+ โ”‚
313
+ allow (exit 0) ยท warn (exit 0 + context hint) ยท block (exit 2 + reason)
314
+ โ”‚
315
+ ~/.kimi-guard/state.db (SQLite via node:sqlite)
316
+ checkpoints/<session>/<ts>.md
317
+ ```
318
+
319
+ - `PreToolUse` **exit 2** is the official blocking mechanism: the CLI feeds stderr back to the model as a correction.
320
+ - `PreToolUse` **stdout** on warn is appended to the model context โ€” a soft nudge before a hard block.
321
+ - `TurnStarted`/`SubagentStart`/`StopFailure`/`Interrupt`/`SessionEnd` hooks feed the metering and checkpoint engines.
322
+
323
+ ## Roadmap
324
+
325
+ - [ ] **v0.7** โ€” per-agent model routing (needs upstream `model` field on subagent dispatch, [#2533](https://github.com/MoonshotAI/kimi-cli/issues/2533)); git-worktree partial-work isolation for parallel agents
326
+ - [x] exact plan-usage windows via the official Kimi usage API (v0.6.2, `[budget] precise = true`; event-based estimates remain the fail-open fallback)
327
+ - [ ] cross-harness adapters โ€” see [docs/PORTING.md](docs/PORTING.md) for the reusable-core checklist
328
+
329
+ ## Ecosystem fit
330
+
331
+ The agent-runtime tooling space is crowded, and pretending every tool competes with every other one helps nobody. kimi-guard occupies one specific layer โ€” here is the honest map:
332
+
333
+ ```
334
+ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
335
+ โ”‚ your agent (Kimi Code CLI) โ”‚
336
+ โ”‚ โ”‚
337
+ โ”‚ built-in loop_control step/attempt caps + compaction โ”‚
338
+ โ”‚ โ”œโ”€ mechanical counter โ€” stops the loop, explains nothing โ”‚
339
+ โ”‚ โ”‚
340
+ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚
341
+ โ”‚ โ”‚ kimi-guard (this project) โ€” the enforcement layer โ”‚ โ”‚
342
+ โ”‚ โ”‚ semantic loop detection ยท quota gates ยท steering ยท โ”‚ โ”‚
343
+ โ”‚ โ”‚ checkpoints ยท goal anchoring โ€” the agent cannot bypass โ”‚ โ”‚
344
+ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚
345
+ โ”‚ โ”‚
346
+ โ”‚ kimi-session-orchestrator voluntary orchestration layer โ”‚
347
+ โ”‚ โ”œโ”€ MCP tools the AGENT chooses to call (grade_step, retire) โ”‚
348
+ โ”‚ โ”œโ”€ great when the agent cooperates; has no veto power โ”‚
349
+ โ”‚ โ”‚
350
+ โ”‚ kimi-boost security preset installer โ”‚
351
+ โ”‚ โ”œโ”€ dangerous-command guards, branch protection, skills โ”‚
352
+ โ”‚ โ”œโ”€ WHAT the agent may do (security) โ€” different axis from โ”‚
353
+ โ”‚ โ”‚ kimi-guard's HOW it behaves (runtime loops/budget) โ”‚
354
+ โ”‚ โ”‚
355
+ โ”‚ cli-agent-runner lifecycle supervisor โ”‚
356
+ โ”‚ โ”œโ”€ 7ร—24 restart loops, log-level anomaly detection โ”‚
357
+ โ”‚ โ”œโ”€ between-rounds layer โ€” complements our within-round layer โ”‚
358
+ โ”‚ โ”‚
359
+ โ”‚ ccusage / kimi-code-usage read-only usage monitors โ”‚
360
+ โ”‚ โ”œโ”€ tell you what happened AFTER โ€” never block anything โ”‚
361
+ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
362
+ ```
363
+
364
+ **Three lines of positioning:**
365
+
366
+ 1. **Monitors are plentiful, voluntary orchestrators exist โ€” but a non-bypassable enforcement layer, kimi-guard is the first in the Kimi ecosystem.** (ccusage-family tools are read-only; kimi-session-orchestrator relies on the agent choosing to call it; kimi-guard intercepts.)
367
+ 2. **Mid-turn steering is an intervention outside the hook-lifecycle boundary โ€” no verified analog does it: external supervisors (e.g. [loop-eng/loopguard](https://github.com/loop-eng/loopguard)) can only SIGSTOP-pause the process and post a desktop notification; in-process detector libraries ([LoopBuster](https://github.com/liuchunwei732-cmyk/loopbuster)) need the host app to honor them; security-hook suites (cc-safety-net) act pre-execution only. We do it natively over the official Wire protocol.**
368
+ 3. **The budget model understands Kimi's subscription semantics: 5h/weekly request windows, reserved headroom, burn-rate projection โ€” USD-billing competitors don't reconcile against plan-based users.**
369
+
370
+ **What we deliberately do NOT do** (so you know where to look):
371
+
372
+ - Security scanning / destructive-command guards โ†’ use **kimi-boost** presets (different axis: authorization vs behavior). `kguard doctor` detects whether a security layer is present and points you there if not.
373
+ - Completion verification exists in kimi-guard as a **deterministic claim-vs-evidence gate** (no LLM in the loop), with an *opt-in* single-vote LLM veto for false positives (`VETO: yes|no` protocol, per-session budget cap, fail-closed on any error). For richer semantic verification (refute-by-default judges, LLM grading), see kimi-session-orchestrator's `grade_step` or the refute-by-default pattern in multi-runtime governance suites.
374
+ - Multi-runtime portability (Claude Code / Codex / Gemini) โ†’ by design, our leverage is Kimi's Wire protocol. The analyzer core (`src/analysis.ts`) is pure functions and reusable if you want to build adapters
375
+ - Daemon-style process supervision (SIGSTOP/SIGCONT, systemd) โ†’ **cli-agent-runner** owns that layer; ours is semantic in-harness intervention
376
+
377
+ Related Kimi-ecosystem projects worth knowing: [kimi-session-orchestrator](https://github.com/FirenzeClaw/kimi-session-orchestrator) (multi-session orchestration), [oh-my-kimi](https://github.com/xz1220/oh-my-kimi) (skill/hook presets), [cli-agent-runner](https://github.com/wan9yu/cli-agent-runner) (lifecycle supervision with a kimi preset), [kimi-code-usage](https://github.com/Golden0Voyager/kimi-code-usage) (read-only usage reporting). kimi-guard and [kimi-boost](https://github.com/shidesheng0218/kimi-boost) come from the same author and are designed as a pair: boost covers the authorization axis, guard the behavior axis.
378
+
379
+ ### The cross-ecosystem landscape (verified 2026-09)
380
+
381
+ The behavioral-enforcement niche is not just empty in the Kimi ecosystem โ€” a survey of the wider coding-agent tooling space found no shipped equivalent:
382
+
383
+ | Tool | Mechanism | What it can/cannot do vs kimi-guard |
384
+ |---|---|---|
385
+ | [cc-safety-net](https://github.com/kenryu42/cc-safety-net) (1.5kโ˜…, 13 CLIs incl. Kimi Code) | pre-execution hooks | Blocks dangerous commands/secret access โ€” the authorization axis. No loop detection, no quotas, no steering. Proves multi-runtime hooks appetite. |
386
+ | [ccusage](https://github.com/ccusage/ccusage) (18kโ˜…) | log analytics | Read-only cost/token reports over 18 agent CLIs. Never blocks. The usage-data layer is commoditized; enforcement is the open layer. |
387
+ | [LoopBuster](https://github.com/liuchunwei732-cmyk/loopbuster) (83โ˜…) | in-process library | Detector set nearly identical to ours (fuzzy repeat / cycles / output stagnation) โ€” but inside LangGraph/CrewAI apps, not CLIs. Independent convergent evidence the detector taxonomy is right. |
388
+ | [loop-eng/loopguard](https://github.com/loop-eng/loopguard) (0โ˜…) | supervisor daemon (SIGSTOP) | Multi-runtime loop watching with $-caps, but freezes the process and posts a desktop notification โ€” useless headless, no steering, no semantics. |
389
+ | [claudewatch](https://github.com/blackwell-systems/claudewatch) (9โ˜…, stalled) | PostToolUse hooks + MCP | Closest prior art for hook-feedback steering ("you're looping, call get_blockers()") โ€” Claude Code only, inactive since 2026-03. |
390
+ | [ralph](https://github.com/frankbria/ralph-claude-code) (9.6kโ˜…) | shell wrapper loop | Exit gates and rate limits at iteration boundaries only โ€” works around runaway agents by restarting, doesn't govern them. |
391
+ | NeMo Guardrails / Guardrails AI / Langfuse / LangSmith / Helicone | content rails / SDK / proxy / SaaS | Structurally cannot intercept a local CLI's tool calls: proxies see only model HTTP traffic, content validators see text, observability is after-the-fact. |
392
+
393
+ **The takeaway:** monitors are commoditized, security hooks are crowded, orchestration is well-served โ€” behavioral, semantic, mid-run enforcement of a local coding CLI is the layer nobody ships. kimi-guard's moat is the combination, not any single feature: hook/Wire access point ร— semantic detectors ร— subscription-aware budgeting. The main strategic risk is single-runtime binding; the analyzer core is pure functions ([PORTING.md](docs/PORTING.md)) precisely so adapters can widen it.
394
+
395
+ ## Compatibility
396
+
397
+ - Kimi Code CLI hooks (Beta) and Claude Code hooks (33 events; we use the 11 the guard handles). Hook payloads are parsed defensively; run `agentguard probe on` + `agentguard doctor` to see the exact fields your CLI version sends.
398
+ - Config detection: `$KIMI_CONFIG_PATH` โ†’ `~/.kimi-code/config.toml` โ†’ `~/.kimi/config.toml`; Claude: `$CLAUDE_SETTINGS_PATH` โ†’ `~/.claude/settings.json`.
399
+ - Guard state dir: `$AGENT_GUARD_HOME` โ†’ `$KIMI_GUARD_HOME` โ†’ `~/.agent-guard` (existing `~/.kimi-guard` keeps working in place).
400
+
401
+ ## License
402
+
403
+ MIT