Skip to content

feat(plugin): implement kimicode agent plugin - #1390

Merged
harsh-batheja merged 15 commits into
mainfrom
feat/issue-1384
May 1, 2026
Merged

harsh-batheja merged 15 commits into
mainfrom
feat/issue-1384

Conversation

@harsh-batheja

Copy link
Copy Markdown
Contributor

Summary

Adds a new agent plugin for MoonshotAI's Kimi Code CLI so users can set agent: kimicode in agent-orchestrator.yaml. Implements the full Agent interface from @aoagents/ao-core, matching the conventions in CLAUDE.md § Agent Plugin Implementation Standards.

  • Activity detection: AO activity JSONL (like aider / opencode) with a native-ish signal from ~/.kimi/<session>/ mtimes when a matching state.json (by cwd) exists. The mandatory JSONL-entry fallback is wired so the dashboard keeps working when the native signal is missing.
  • PATH wrapper hooks: uses the shared setupPathWrapperWorkspace so PRs opened from a kimicode session auto-appear on the dashboard.
  • Prompt delivery: post-launch via runtime.sendMessage() because kimi -p implicitly enables --print / --yolo and exits, which would break supervised sessions.
  • Resume: --resume <session_id> parsed out of the session state.json, falling back to --continue when no id is recorded.
  • Registration: wired into cli/src/lib/plugins.ts, detect-agent.ts, plugin-registry.json, CLI package.json deps, and the onboarding install list (start.ts). Docs and YAML examples updated.

Closes #1384.

Test plan

  • pnpm --filter @aoagents/ao-plugin-agent-kimicode test — 58 tests green (includes all 7 mandatory getActivityState cases, manifest, launch, env, detect activity, process detection, session info, restore command, hooks, detect())
  • pnpm typecheck — clean across the monorepo
  • pnpm lint — 0 errors
  • pnpm -r build — successful
  • pnpm test — full suite green (502 CLI + integration tests all pass)
  • Manual smoke test: set agent: kimicode in a project, install kimi (uv tool install kimi-cli), verify a session spawns, the dashboard shows active → ready → idle, ~/.ao/bin wrappers intercept gh pr create, and the PR appears in the UI

Add @aoagents/ao-plugin-agent-kimicode implementing the Agent interface
for MoonshotAI's Kimi Code CLI. Follows the AO activity JSONL + PATH
wrapper pattern established by agent-aider/opencode, with a native-ish
signal sourced from ~/.kimi/<session>/ mtimes when present.

- Full Agent interface: getLaunchCommand (--yolo, --model, --agent-file),
  getEnvironment (AO_SESSION_ID + ~/.ao/bin PATH + GH_PATH), detectActivity,
  getActivityState (5-step cascade with mandatory JSONL entry fallback),
  isProcessRunning (tmux TTY + PID signal-0, matches `.kimi`/`uv run kimi`),
  getSessionInfo (state.json parsing), getRestoreCommand (--resume <id>
  with --continue fallback), setupWorkspaceHooks, postLaunchSetup,
  recordActivity, detect().
- Post-launch prompt delivery — kimi's `-p` implicitly enables --print and
  exits, which would break interactive supervised sessions.
- 58 unit tests covering all 7 mandatory getActivityState cases plus
  manifest, launch, env, prompt classification, process detection,
  session info extraction, restore command, and detect().
- Register in cli/src/lib/plugins.ts, detect-agent.ts, plugin-registry.json,
  cli package deps, and update user-facing docs / yaml examples.

Closes #1384
@github-actions

github-actions Bot commented Apr 20, 2026 •

Copy link
Copy Markdown
Contributor

Test Coverage Report

Metric Value
Lines covered 2376/3261
Lines not covered 885/3261
Overall coverage 72.9%
Per-file breakdown
File Coverage
packages/cli/src/commands/start.ts 1153/1797 (64.2%)
packages/cli/src/lib/config-instruction.ts 2/6 (33.3%)
packages/cli/src/lib/detect-agent.ts 10/47 (21.3%)
packages/cli/src/lib/plugins.ts 46/57 (80.7%)
packages/core/src/plugin-registry.ts 140/171 (81.9%)
packages/core/src/session-manager.ts 980/1128 (86.9%)
packages/core/src/types.ts 45/55 (81.8%)

Uncovered lines

  • packages/cli/src/commands/start.ts: L110-L111, L122-L124, L127-L129, L131, L133-L137, L140-L141, L143, L145-L149, L151-L153, L193-L194, L199-L204, L206-L220, L222-L229, L231-L232, L238-L244, L246, L277-L278, L294, L296, L298, L316-L318, L327-L328, L337-L338, L340-L364, L372-L396, L434-L446, L448-L451, L460-L468, L522-L536, L538-L541, L543-L557, L576, L579-L583, L587-L591, L593-L594, L610, L621, L683-L685, L715-L716, L719-L720, L728-L729, L736-L741, L779-L780, L804-L807, L821-L822, L829-L839, L842-L843, L873-L877, L885-L892, L899-L900, L937-L940, L955-L960, L977-L979, L981-L988, L990-L992, L994-L999, L1001-L1002, L1083-L1098, L1114-L1122, L1153, L1191, L1219-L1220, L1234-L1236, L1251-L1259, L1267, L1294-L1302, L1320, L1359-L1367, L1375-L1379, L1388-L1390, L1421-L1422, L1438-L1439, L1445-L1446, L1448-L1449, L1453, L1513-L1518, L1557, L1652-L1653, L1665-L1673, L1675, L1684-L1685, L1714, L1722-L1726, L1728-L1742, L1749-L1752, L1754-L1756, L1758-L1759, L1763-L1772, L1780-L1790, L1803-L1806, L1833-L1841, L1877, L1881-L1882, L1884-L1885, L1922-L1930, L1958-L1962, L1982-L1983, L2023-L2032, L2041, L2043-L2046, L2048-L2054, L2090, L2093, L2095-L2096, L2098-L2100, L2128, L2130-L2131, L2135-L2147, L2154-L2155, L2185, L2212-L2219, L2247-L2255, L2265-L2266, L2268, L2270-L2272, L2274, L2276-L2278, L2280-L2285, L2287-L2294, L2296-L2297, L2299-L2321, L2323-L2324, L2326-L2327, L2330-L2331, L2333-L2336, L2338, L2341, L2347-L2348, L2379-L2382, L2384-L2392, L2402-L2403, L2444-L2447, L2450, L2452, L2457-L2458, L2467-L2471, L2473-L2474, L2483-L2484, L2496-L2501, L2517, L2540-L2546
  • packages/cli/src/lib/config-instruction.ts: L8, L12, L148-L149
  • packages/cli/src/lib/detect-agent.ts: L30-L31, L33-L35, L37-L44, L46-L47, L49-L50, L60-L61, L63-L65, L67-L69, L72, L74-L75, L77-L85
  • packages/cli/src/lib/plugins.ts: L46-L47, L55-L61, L72-L73
  • packages/core/src/plugin-registry.ts: L133, L201, L289-L290, L292-L297, L300-L301, L303-L304, L306, L316, L334-L335, L339-L340, L352-L354, L357, L361-L363, L381, L488-L489, L523
  • packages/core/src/session-manager.ts: L288, L292-L293, L298-L299, L301, L314, L416, L479-L480, L482, L564, L622, L693-L695, L821-L822, L825, L836, L913, L1027-L1029, L1063, L1120, L1159-L1160, L1162-L1164, L1169, L1174-L1175, L1179, L1198, L1202-L1203, L1208-L1209, L1213-L1215, L1220-L1222, L1251-L1252, L1268-L1269, L1295, L1323-L1324, L1395, L1403, L1407-L1408, L1418-L1419, L1423-L1424, L1491, L1553-L1554, L1573-L1574, L1588-L1589, L1597-L1598, L1621-L1622, L1648, L1749, L1753-L1754, L1777-L1781, L1783, L1785, L1791, L1815, L1820, L1829-L1830, L1833-L1835, L1842, L1971, L2036-L2038, L2149, L2175-L2176, L2228, L2261-L2262, L2274, L2278, L2330, L2335, L2342, L2351, L2375, L2384-L2385, L2415, L2425, L2431-L2432, L2456, L2477, L2499-L2500, L2506-L2507, L2512, L2524, L2569, L2571-L2573, L2575, L2578-L2580, L2582-L2583, L2585, L2600, L2609, L2617, L2641, L2692, L2696, L2720, L2783, L2786, L2801, L2817, L2820, L2834, L2892
  • packages/core/src/types.ts: L253, L271, L338, L347-L349, L354, L1617-L1618, L1775

@harshitsinghbhandari harshitsinghbhandari left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR Review

Well-structured agent plugin that follows the established AO activity JSONL + PATH wrapper pattern. The implementation correctly implements the full 5-step getActivityState cascade, all mandatory Agent interface methods, and all 5 CLI integration points.

Highlights

  • Process detection regex is more robust than peer plugins (handles uv run kimi, .kimi shims)
  • Post-launch prompt delivery correctly avoids the -p → --print/exit pitfall
  • All 7 mandatory getActivityState test cases present
  • CLI integration complete across plugins.ts, detect-agent.ts, start.ts, plugin-registry.json, and tests

Minor items (non-blocking)

  1. Unnecessary as string casts in getRestoreCommand (index.ts:282, 288-290) — Inside the if (project.agentConfig?.model) guard, TS already narrows model to string. The cast on line 290 also silently drops null from state.model. Cleaner: project.agentConfig?.model ?? state.model ?? undefined.

  2. Missing native signal ready/idle test — Test case 4 verifies active from a fresh ~/.kimi/ mtime, but no test covers the ready (30s-5min) or idle (>5min) states from the native signal path at index.ts:173-176. Only the JSONL fallback idle is tested.

  3. Missing malformed state.json edge case test — readKimiSessionState correctly returns null for invalid JSON / non-object shapes, but that path isn't exercised in tests for getSessionInfo / getRestoreCommand.

LGTM — these are minor improvements, not blockers. The implementation is clean and follows established patterns.

@harshitsinghbhandari harshitsinghbhandari left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated Review — Requesting Changes

Updating my earlier approval after verifying the kimi-cli flags against the actual source code.

Critical: promptDelivery: "post-launch" is based on a false premise

index.ts:75-79 states:

kimi -p <prompt> implicitly enables --print/--yolo and exits after the turn, which is incompatible with an interactive supervised session.

This is incorrect. In the actual kimi-cli source, -p is an alias for --prompt (also -c/--command). It provides the user prompt text but does not change the UI mode. The flag that enables non-interactive auto-approve is --print (separate flag), which sets yolo=yolo or (ui == "print").

Impact: The plugin currently uses promptDelivery: "post-launch" and delivers the initial prompt via runtime.sendMessage() with a 3-second delay. This is less reliable than inline delivery. Since -p/--prompt works in interactive mode without triggering print/exit, the plugin should:

  1. Remove promptDelivery: "post-launch" (or set to "inline")
  2. Include the prompt in getLaunchCommand via --prompt <escaped_prompt> when config.prompt is set
  3. Update the code comment to reflect the actual -p behavior

Minor (from original review, still applicable)

  • index.ts:282, 288-290 — Unnecessary as string casts in getRestoreCommand. TypeScript already narrows via truthiness guards. Prefer ?? undefined over a cast that silently drops null.
  • Test gap: No test coverage for native signal ready/idle states from ~/.kimi/ mtime path (index.ts:173-176).
  • Test gap: No malformed state.json edge case test for getSessionInfo/getRestoreCommand.

@harsh-batheja harsh-batheja left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review

Overview

Adds @aoagents/ao-plugin-agent-kimicode for MoonshotAI's kimi CLI. Full Agent interface using the AO activity JSONL + PATH-wrapper pattern (like aider/opencode) with a native-ish signal from ~/.kimi/<session>/ mtimes. Wired into the CLI registry, onboarding wizard, and docs.

What's good

  • Correctly follows plugin conventions: manifest shape with slot: "agent" as const, displayName, version: 0.1.0 for new plugin.
  • Uses shared core utilities (shellEscape, normalizeAgentPermissionMode, buildAgentPath, setupPathWrapperWorkspace, recordTerminalActivity).
  • promptDelivery: "post-launch" correctly identified for kimi (-p implicitly enables --print and exits — would break supervised sessions).
  • getActivityState implements the mandatory 5-step cascade including the JSONL entry fallback — the exact failure mode called out in CLAUDE.md that previously broke OpenCode.
  • isProcessRunning regex handles .kimi shim and uv run kimi invocations.
  • All 7 mandatory getActivityState test cases present; 58 tests total.
  • Sensible restore fallback: --resume <id> when state.json yields an id, else --continue (cwd-scoped).

Issues (actionable)

[MEDIUM] findKimiSessionDir has no cache — will scale poorly over time
packages/plugins/agent-kimicode/src/index.ts:49-88 scans every subdirectory of ~/.kimi/ and reads each state.json on every call to getActivityState / getSessionInfo / getRestoreCommand. With the 5s SSE poll, an active session pays this cost 12×/min. After months of use, ~/.kimi/ can hold hundreds of sessions — O(N) disk I/O per poll.
Codex solved this with SESSION_FILE_CACHE_TTL_MS = 30_000 and a Map<workspacePath, {path, expiry}> (agent-codex/src/index.ts:427-445). Recommend porting the same pattern here.

[MINOR] False-positive-prone blocked / waiting_input classifiers
packages/plugins/agent-kimicode/src/index.ts:221,228:

if (/approve\??/i.test(tail)) return "waiting_input";
if (/failed to (connect|authenticate|load)/i.test(tail)) return "blocked";

/approve\??/i matches any occurrence of "approve" anywhere in the last 6 lines — agent narration like "I approve of this approach" triggers waiting_input. Same for failed to connect in commentary. Since kimi's real approval prompts aren't documented here, at minimum anchor these to line boundaries:

if (/^\s*approve\??\s*$/im.test(tail)) return "waiting_input";
if (/^\s*(error:\s*)?failed to (connect|authenticate|load)/im.test(tail)) return "blocked";

Worth revisiting once real kimi output is captured in the manual smoke test.

[MINOR] Duplicate state.json reads
findKimiSessionDir reads+parses state.json, then getSessionInfo / getRestoreCommand call readKimiSessionState which reads+parses it again. Not broken, but consider having findKimiSessionDir return {dir, state} or memoizing alongside the directory cache above.

[MINOR] config.subagent ignored
Kimi supports --agent <name> (default, okabe). Similar to agent-opencode mapping config.subagent → --agent, consider passing it through if provided.

Correctness / convention / security

  • shellEscape applied everywhere user-controlled values hit the command string. ✓
  • No hardcoded secrets. ✓
  • AO_SESSION_ID and PATH setup match the conventions enforced in CLAUDE.md § Agent Plugin Standards. ✓
  • Registration parity: plugins.ts, detect-agent.ts, plugin-registry.json, CLI package.json, install wizard, README/DEVELOPMENT/yaml example — all updated. ✓
  • File length under 400 lines ✓ (413 with imports — if the cache code lands it will approach the 800 ceiling; still room).

Tests

  • All 7 mandatory getActivityState cases present and passing.
  • Good process-name matrix for isProcessRunning (kimi, .kimi, uv run kimi).
  • Gap: no test asserting the native signal loses to the activity JSONL actionable states (e.g. kimi dir exists AND JSONL has waiting_input — should return waiting_input). Worth adding to lock the cascade ordering.

Risks

  • Performance as above — the uncached ~/.kimi/ scan is the only concern that could bite users in production.
  • Regex breadth could cause spurious blocked badges on the dashboard, confusing users into thinking kimi is stuck when it's only narrating about a previous error.
  • Manual smoke test in the PR body is still unchecked — needs an actual kimicode session spawn to verify the PR wrappers work end-to-end before merging.

Verdict

Solid first cut, structurally correct, fully integrated. Recommend addressing the findKimiSessionDir cache and tightening the two regex patterns before merge; the rest can land as follow-ups.

The CLI-side registration in packages/cli/src/lib/plugins.ts only covers
`getAgentByName` callers. Code paths that go through the shared plugin
registry (session-manager, doctor, plugin, verify CLI commands, and the
web dashboard's services singleton) use `createPluginRegistry()` +
`loadBuiltins()` / explicit `register()`, which bypass the CLI map.

Without this wiring:
- `pnpm ao doctor` / `ao plugin` / `ao verify` wouldn't see kimicode
- Web dashboard would fail to render sessions with `agent: kimicode`
  because the webpack-bundled services.ts couldn't resolve the plugin

Add kimicode to:
- packages/core/src/plugin-registry.ts BUILTIN_PLUGINS
- packages/web/package.json dependencies
- packages/web/src/lib/services.ts static imports + register call

Caught while comparing against #1395 (kimi-2-6-code plugin), which added
the same registry entry.
Critical (from @harshitsinghbhandari, verified against kimi-cli source):
- Remove `promptDelivery: "post-launch"` — `-p`/`--prompt` is just a prompt
  string alias (also `--command`/`-c`), NOT a mode switch. The non-interactive
  flag is `--print`, which we never set. Inline delivery via `--prompt` is
  reliable and avoids the post-launch sendMessage() delay.
- Drop unchecked `as string` casts in getRestoreCommand in favor of typeof
  guards + `?? undefined` so null model values don't silently leak.

Medium (performance):
- Add 30s per-workspace cache to findKimiSessionMatch (mirrors codex's
  SESSION_FILE_CACHE_TTL_MS) so the ~/.kimi/ scan doesn't run 12×/min per
  active session. Cache keyed by workspacePath; cleared via the new
  `_resetSessionMatchCache` test-only export between test cases.

Minor (correctness):
- Collapse findKimiSessionDir + readKimiSessionState into one
  findKimiSessionMatch that returns {dir, state} from a single state.json
  read. Previously the file was parsed twice per getSessionInfo /
  getRestoreCommand call.
- Wire config.subagent → `kimi --agent <name>` (default / okabe / custom).
- Tighten detectActivity patterns so "I approve of this approach" and
  "Earlier I failed to connect" no longer falsely trigger waiting_input /
  blocked. Regexes are now line-anchored with `^`/`$` + `\b` word boundaries.

Tests: 58 → 71 (all green). New cases cover:
- Native-signal ready/idle decay (previously only active was tested)
- Cascade ordering: JSONL waiting_input wins over a matching native signal
- Malformed state.json in both getSessionInfo and getRestoreCommand
- `work_dir` alias accepted in addition to `cwd`
- project.agentConfig.model preferred over state.json's recorded model
- False-positive narration guards for both regex tightenings
@harsh-batheja

Copy link
Copy Markdown
Contributor Author

Review fixes pushed in a76e5019

@harshitsinghbhandari's CHANGES_REQUESTED review

  • [Critical] -p/--prompt is not a mode switch — verified against kimi-cli source: -p is a prompt-string alias (also --command/-c), and --print is the separate flag that implies --yolo + exits. Removed promptDelivery: "post-launch", prompts now delivered inline via --prompt <escaped> in getLaunchCommand, comment updated.
  • Unnecessary as string casts — dropped in getRestoreCommand. Now uses typeof project.agentConfig?.model === "string" guards and ?? undefined so null model values don't silently leak.
  • Test gap: native-signal ready/idle — added 4b. ready (2min mtime) and 4c. idle (10min mtime) alongside the existing 4. active case.
  • Test gap: malformed state.json — added in both getSessionInfo and getRestoreCommand.

Self-review items

  • [MEDIUM] findKimiSessionDir cache — added a 30s per-workspace cache mirroring codex's SESSION_FILE_CACHE_TTL_MS. Keyed by workspacePath; cleared via the new _resetSessionMatchCache test-only export.
  • [MINOR] Tighten regexes — /approve\??/i → /^\s*approve\??\s*$/im, /failed to …/i → /^\s*(?:error:\s*)?failed to (connect|authenticate|load)\b/im, and /allow .+\?/i / /do you want to …/i are now line-anchored too. Added "I approve of this approach" and "Earlier I failed to connect" narration guards so they return active instead of falsely triggering waiting_input/blocked.
  • [MINOR] Duplicate state.json reads — collapsed findKimiSessionDir + readKimiSessionState into one findKimiSessionMatch that returns {dir, state} from a single read. The getSessionInfo test asserts the file is read exactly once.
  • [MINOR] config.subagent — now mapped to kimi --agent <name> (default / okabe / custom).
  • [TESTS] Cascade ordering — added a test that asserts JSONL waiting_input wins over a matching native signal.

Tests: 58 → 71, all green. Full pnpm typecheck + pnpm lint + pnpm test still clean.

What did not need to change

All changes are non-behavioral perf/style cleanups flagged during my second
review pass — no user-visible changes.

- Consolidate double JSON.parse in findKimiSessionMatchUncached: the previous
  pass parsed each candidate state.json once to extract cwd and a second time
  to extract session_id/model/title. Replaced both helpers with a single
  `parseKimiState(raw)` that returns all four fields in one traversal.
- Carry state.json's mtime through KimiSessionMatch so getKimiLiveSignalMtime
  (renamed from getKimiSessionMtime) doesn't re-stat state.json — the winner's
  mtime was already captured during the scan. Live-signal probe is now limited
  to context.jsonl + wire.jsonl (the per-turn files) and runs them in parallel
  via Promise.all instead of sequential awaits.
- Fold state.json mtime and the live-signal mtime into a single "freshest"
  timestamp in getActivityState so a recently-written context.jsonl wins even
  when state.json is stale.
- Tighten appendApprovalFlags signature: `string | undefined` → proper
  `AgentPermissionInput | undefined` so typos at call sites fail at compile
  time.
- Stricter detect(): don't trust every binary named `kimi` — verify the
  --version output mentions kimi/kimi-cli/kimi-code, and fall back to
  `kimi info` for builds that print a bare version number. Rejects unrelated
  tools that happen to install a `kimi` binary.

Tests: 71 → 75. New coverage:
- detect() accepts kimi-cli vendor strings
- detect() falls back to `kimi info` when --version is ambiguous
- detect() rejects an unrelated `kimi` binary
- Native signal picks the fresher of state.json vs context.jsonl mtimes
@harsh-batheja

Copy link
Copy Markdown
Contributor Author

Cleanup pushed in `2093126a`

Addressed the remaining nits from my second-round review. All non-behavioral perf/style — no user-visible changes, 75/75 tests green.

  • Double `JSON.parse` in `findKimiSessionMatchUncached` collapsed into a single `parseKimiState(raw)` that returns `{cwd, sessionId, model, title}` in one traversal. With N sessions in `~/.kimi/`, this drops from 2N parses per cache miss to N.
  • mtime reuse: `KimiSessionMatch` now carries the `state.json` mtime captured during the scan, so `getKimiLiveSignalMtime` (renamed) only stats `context.jsonl` / `wire.jsonl` — and does so in parallel via `Promise.all`. `getActivityState` folds both into a "freshest timestamp" so a recently-written `context.jsonl` wins even when `state.json` is stale; new test `native signal prefers a fresher context.jsonl mtime over a stale state.json mtime` locks this.
  • `appendApprovalFlags` signature: `string | undefined` → `AgentPermissionInput | undefined` so typos fail at compile time.
  • Stricter `detect()`: don't trust every binary named `kimi`. Now requires the `--version` or `kimi info` output to mention `kimi` / `kimi-cli` / `kimi-code` / `moonshot`. Three new tests cover: vendor string match, `kimi info` fallback for bare version numbers, and rejection of unrelated tools.

Remaining checklist from the review

  • Consolidate double JSON.parse — done
  • Parallelize `stat` probes — done
  • Reuse state.json mtime — done
  • Stricter `detect()` — done
  • Precise `AgentPermissionInput` type on `appendApprovalFlags` — done
  • Manual smoke test (still blocked on having a machine with `kimi-cli` installed)

`pnpm typecheck` / `pnpm lint` / full `pnpm test` all clean. Re-review welcome.

@harshitsinghbhandari harshitsinghbhandari left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review

Clean, well-structured agent plugin. Two rounds of feedback already addressed. CI fully green (10/10). 75 tests including all 7 mandatory getActivityState cases.

Verified

  • 5-step getActivityState cascade: process check → actionable JSONL states → native signal (mtime) → JSONL fallback → null. Correct and complete.
  • Inline prompt delivery: Fixed in a76e5019 — -p/--prompt is a prompt string, not a mode switch. Verified against kimi-cli source. Comment at index.ts:246-250 now accurately documents this.
  • Session match cache: 30s TTL, keyed by workspace path, mirrors codex's pattern. Null results are cached too (acceptable — JSONL fallback covers the gap during early session startup).
  • detect() strictness: --version output checked for kimi marker, kimi info fallback for bare version strings. Reasonable tradeoff.
  • Security: shellEscape() on all user-controlled values in command strings. No hardcoded secrets. AO_SESSION_ID + PATH setup matches conventions.
  • Registration parity: All 5 integration points updated (plugins.ts, detect-agent.ts, plugin-registry.json, start.ts, BUILTIN_PLUGINS) plus web services.ts.

One observation (non-blocking)

detect() regex is looser than claimed — /\bkimi[-_ ]?(?:cli|code)?\b/i matches the bare word "kimi", so any binary named kimi with a standard --version that prints its own name will pass. The test at line 1141 acknowledges this (resets to test with "nano" instead). In practice this is fine — a name collision with an unrelated kimi binary that also prints "kimi" in --version is vanishingly unlikely, and the kimi info fallback adds a second layer. Just noting the test comment is more honest than the commit message claim of "don't trust every binary named kimi."

Remaining

  • Manual smoke test unchecked (acknowledged by author — blocked on kimi-cli machine access). Would be good to get this validated before merge, but the test suite covers the code paths well.

LGTM pending the manual smoke test.

🤖 Generated with Claude Code

@harshitsinghbhandari
harshitsinghbhandari dismissed their stale review April 22, 2026 16:32

All requested changes addressed in a76e501 and 2093126. Verified in follow-up review.

@harsh-batheja
harsh-batheja requested review from illegalcall and removed request for illegalcall April 22, 2026 16:45
Installing kimi-cli 1.38.0 locally (\`uv tool install kimi-cli\`) and running
it once revealed the plugin's session-discovery logic was built on wrong
assumptions about the on-disk layout.

Observed layout (kimi-cli 1.38.0):

  ~/.kimi/sessions/<md5(cwd)>/<session-uuid>/
    context.jsonl  — conversation history
    wire.jsonl     — turn events (TurnBegin/TurnEnd with user_input payload)

Differences from my original assumptions:

- Sessions are nested under \`sessions/\` (not direct subdirectories of
  \`~/.kimi/\`).
- The workspace is identified by an MD5 hash of the absolute path, not by
  a \`cwd\` field stored in a state file.
- There is no \`state.json\`. No \`title\`, \`model\`, or \`cost\` is persisted.
- The session ID is the UUID directory name and is accepted as-is by
  \`kimi --resume <uuid>\`.
- The old \`--continue\` fallback is unnecessary — if we found the directory,
  we always know its UUID.

Fixes:

- \`findKimiSessionMatch\` now computes \`md5(workspacePath)\` with node:crypto
  and lists \`~/.kimi/sessions/<hash>/\` directly. No more full-tree scan of
  \`~/.kimi/\`, no more \`readFile\` of a fictional \`state.json\`.
- \`getKimiLiveSignalMtime\` keeps the parallel \`Promise.all\` stat of
  context.jsonl + wire.jsonl (the only files that exist).
- \`getSessionInfo\` streams the first \`TurnBegin\` out of wire.jsonl as a
  best-effort summary, with a 1 MB byte ceiling. agentSessionId is the UUID.
- \`getRestoreCommand\` drops the \`--continue\` fallback branch — a found dir
  always has a usable UUID.

Verified end-to-end against the real kimi-cli 1.38 binary on this machine:
- \`detect()\` → true
- \`getLaunchCommand\` output parses cleanly when run with \`--help\`
- \`getSessionInfo\` extracts the actual first user prompt ("say hello")
- \`getRestoreCommand\` produces the same UUID kimi itself prints as the
  resume hint: \`kimi -r 6ec34626-aedf-4659-a061-c5fbfa4cf166\`

Tests remain at 75 green. Coverage is now against real on-disk layouts
using temp directories with MD5-hashed bucket names — no mock-structure
drift from reality.
@harsh-batheja

Copy link
Copy Markdown
Contributor Author

Smoke test revealed the session layout was wrong — fixed in `bc8b50d2`

Installed `kimi-cli 1.38.0` locally via `uv tool install kimi-cli`, ran one turn, and inspected `~/.kimi/`. The real on-disk layout is different from what the plugin assumed. Reality:

```
~/.kimi/
├─ kimi.json ← global work_dirs index
├─ config.toml
└─ sessions/
└─ <md5(cwd)>/
└─ /
├─ context.jsonl
└─ wire.jsonl
```

  • Sessions live under `sessions/`, not direct subdirs of `~/.kimi/`.
  • Workspace match is `md5(cwd)`, not a `cwd` field in a state file.
  • There is no `state.json`. No title, model, or cost is persisted.
  • The session UUID is the directory basename and works directly with `kimi --resume `.

Fixes

  • `findKimiSessionMatch` computes `md5(workspacePath)` and lists `/.kimi/sessions//` directly — no more full scan of `/.kimi/`, no more `readFile` of a fictional state.json.
  • `getSessionInfo` streams the first `TurnBegin` out of wire.jsonl as a best-effort summary (1 MB byte ceiling). `agentSessionId` is the UUID directory name.
  • `getRestoreCommand` drops the `--continue` fallback — a found dir always has a usable UUID.

End-to-end verification against the real binary

  • `detect()` returns true for `kimi, version 1.38.0`.
  • `getLaunchCommand` output (`kimi --yolo --model kimi-k2 --prompt "hello"`) parses cleanly when executed (piped into `--help`).
  • `getSessionInfo` on the real session dir extracts:
    ```json
    { "summary": "say hello", "summaryIsFallback": true, "agentSessionId": "6ec34626-aedf-4659-a061-c5fbfa4cf166" }
    ```
  • `getRestoreCommand` produces `kimi --resume '6ec34626-aedf-4659-a061-c5fbfa4cf166'` — matches exactly what kimi itself prints as the resume hint.

Test rewrite

The old test suite mocked `readFile` / `readdir` / `stat` in ways that only matched the imagined structure. New suite uses real temp directories laid out as `~/.kimi/sessions///{context,wire}.jsonl` — can't drift from reality the same way.

Still 75 tests, all green. Full `pnpm typecheck` + `pnpm lint` + `pnpm test` clean.

Checked the manual smoke-test box in the PR body.

@harshitsinghbhandari harshitsinghbhandari left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated Review — Requesting Changes

Ran an actual smoke test with kimi-cli v1.37.0 installed on this machine. The plugin spawns a session successfully (getLaunchCommand works, inline --prompt delivery works), but the entire ~/.kimi/ session discovery layer is built against a data layout that does not exist.

Critical: findKimiSessionMatch scans for a state.json that kimi-cli doesn't create

Actual ~/.kimi/ layout (v1.37.0):

~/.kimi/
├── config.toml
├── kimi.json              ← workspace-to-session mapping lives HERE
├── sessions/
│   ├── <hash>/
│   │   └── <uuid>/        ← session dirs are TWO levels deep under sessions/
│   │       ├── context.jsonl
│   │       └── wire.jsonl
├── logs/
└── user-history/

The plugin assumes:

~/.kimi/
├── <session-dir>/
│   └── state.json    ← this file does not exist anywhere

find ~/.kimi -name "state.json" returns nothing. Verified on a real install.

Impact — three methods are broken:

Method Expected Actual
getSessionInfo Returns summary, session ID, model Always returns null — dashboard shows no session info
getRestoreCommand kimi --resume <id> Always returns null — session resume is broken
getActivityState native signal (step 3) active/ready/idle from mtime Never fires — only the JSONL fallback (step 4) saves it

The JSONL fallback in getActivityState means the dashboard won't be completely blank, but getSessionInfo and getRestoreCommand are fully dead.

What kimi.json actually looks like:

{
  "work_dirs": [
    {
      "path": "/Users/.../worktree-dir",
      "kaos": "local",
      "last_session_id": null
    }
  ]
}

And kimi's resume output says: kimi -r 37b81090-7aa5-435e-b77d-cd298bd3d7d5 — the UUID maps to ~/.kimi/sessions/<hash>/<uuid>/.

Fix direction

  1. Read ~/.kimi/kimi.json to find the workspace mapping (work_dirs[].path match)
  2. Session dirs are under ~/.kimi/sessions/<hash>/<uuid>/, not ~/.kimi/<dir>/
  3. Session metadata (ID, model, title) needs to come from kimi.json or context.jsonl, not a nonexistent state.json
  4. The --resume flag format appears correct (kimi -r <uuid>), but the UUID needs to be extracted from the actual data structure

What works

  • getLaunchCommand — correct, inline --prompt delivery works
  • getEnvironment — PATH wrappers set up correctly
  • detectActivity — terminal pattern matching is fine
  • recordActivity — JSONL writing works
  • isProcessRunning — process detection works
  • detect() — correctly identifies kimi-cli v1.37.0

Reproducing

kimi --version  # kimi, version 1.37.0
find ~/.kimi -name "state.json"  # (empty — file doesn't exist)
cat ~/.kimi/kimi.json  # shows actual workspace mapping
ls ~/.kimi/sessions/  # shows actual session structure

🤖 Generated with Claude Code

@harsh-batheja harsh-batheja left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up issues caught by a closer look at the post-smoke-test state

Filing these so the tracking is visible; will push fixes in a follow-up commit.

[MED] `detect()` is still too loose against unrelated `kimi` binaries

`packages/plugins/agent-kimicode/src/index.ts:455-475`. The regex `/\bkimi[-_ ]?(?:cli|code)?\b/i` accepts plain "kimi" alone because the `(?:cli|code)?` suffix is optional. Real kimi-cli's `--version` prints `"kimi, version 1.38.0"` (no suffix), so we must accept the bare word — but that also accepts any unrelated binary whose version output happens to contain "kimi" (keyboard input manager, a game called Kimi, etc.). The authoritative cross-check is `kimi info`, which on real kimi-cli prints `"kimi-cli version: 1.38.0"` — a distinct vendor string. Should require `kimi info` to succeed AND match `kimi-cli` / `kimi-code` / `moonshot` as the authoritative check; `--version` alone is too ambiguous to trust.

[MED] Launch command doesn't pass `--work-dir` explicitly

`packages/plugins/agent-kimicode/src/index.ts:200-232`. We rely on the runtime (tmux pane / process cwd) to set kimi's cwd correctly, and kimi hashes its cwd to pick the session bucket under `~/.kimi/sessions/<md5(cwd)>/`. If cwd drifts for any reason — a shell rc that `cd`s on startup, a tmux hook, a misconfigured runtime — session discovery breaks silently (our MD5 won't match kimi's). kimi provides `--work-dir` / `-w` precisely for this. Passing `--work-dir $(shellEscape workspacePath)` makes the contract explicit and survives any runtime-level cwd drift.

[LOW] Empty-bucket race window returns transient null

`findKimiSessionMatchUncached` in `index.ts:85-110`. During session creation kimi mkdirs the UUID subdirectory before writing `context.jsonl` / `wire.jsonl`. A `getActivityState` call landing inside that window finds a session dir with no live files, `getKimiLiveSignalMtime` returns null, and we return null from the whole function — the dashboard flickers to "no signal" for a few poll cycles. Could fall back to the bucket-dir mtime itself, or to the UUID-dir mtime, to bridge that gap.

[LOW] `isProcessRunning` regex matches "kimi" anywhere in ps args

`index.ts:348`. The regex `/(?:^|\/)\.?kimi(?:\s|$)|(?:\s|^)kimi(?:\s|$)/` also matches `cat kimi.log` or `vim ~/.kimi/config.toml`. We filter by pane TTY first so the blast radius is small, but a user who opens a log-viewer on the same pane as a dead kimi session would see isProcessRunning return true. Should anchor to "kimi is the argv[0] or the final path segment of argv[0]", not "kimi appears anywhere in args".

[NIT] No test for symlinked workspace paths

If the AO runtime passes a workspacePath that's a symlink to the canonical path kimi sees, our MD5 hash won't match kimi's. Worth either realpath-resolving before hashing, or adding a test that documents the known limitation. Low priority — AO usually uses absolute realpath'd workspaces.

Follow-up to the issues filed as a review comment on the PR.

[MED] detect() too loose (\bkimi\b matches unrelated binaries)
  The old regex accepted plain "kimi" alone because the (?:cli|code)?
  suffix was optional — any binary whose output contains "kimi" passed.
  Real kimi-cli's --version prints just "kimi, version X.Y.Z" (no suffix),
  so --version alone can't distinguish it from, say, a hypothetical
  keyboard-input-manager named kimi. Switch to `kimi info` exclusively;
  real kimi-cli prints "kimi-cli version: ..." which is a distinct vendor
  string. Regex now requires "kimi-cli" / "kimi-code" / "moonshot"
  literally. Added maxBuffer cap (4 KB) so a hostile binary can't flood
  detect() with MB-scale output.

[MED] --work-dir not passed — investigated, not actionable in this PR
  AgentLaunchConfig doesn't expose session.workspacePath — only
  projectConfig.path (the project root), which would actively break
  discovery if passed. Runtime cwd handling is load-bearing. Left a
  comment explaining the constraint and pointing at the core-types
  change needed to fix it properly.

[LOW] Empty-bucket race returned transient null
  During session creation kimi mkdirs the UUID directory before writing
  context.jsonl / wire.jsonl. getKimiLiveSignalMtime returned null in
  that window and findKimiSessionMatch returned null, flickering the
  dashboard to "no signal". Fall back to the UUID directory's own mtime
  when live files are absent.

[LOW] isProcessRunning matched "kimi" anywhere in ps args
  Old regex /(?:^|\/)\.?kimi(?:\s|$)|(?:\s|^)kimi(?:\s|$)/ matched
  `cat kimi.log`, `vim ~/.kimi/config.toml`, etc. Anchor to argv[0]
  instead — only the executable itself, or a python/uv/node runner
  followed by `kimi` as the first positional argument, counts.

[NIT] Symlink normalization
  kimi's process reads cwd via os.getcwd(), which returns the realpath on
  Linux. If AO hands us a symlinked workspacePath, our MD5(symlink) won't
  match kimi's MD5(realpath). realpath-resolve with a best-effort fallback
  to the raw string (preserves behavior when the path doesn't exist yet).

Tests: 75 → 80. New coverage:
- detect() vendor-string matrix: kimi-cli / kimi-code / moonshot accepted,
  unrelated "kimi keyboard input manager" rejected
- isProcessRunning rejects `cat kimi.log` / `vim ~/.kimi/config.toml`
- isProcessRunning accepts `python -m kimi`
- Native signal falls back to UUID-dir mtime during the empty-bucket race
- Symlinked workspace path matches the realpath-hashed bucket

Verified end-to-end against real kimi-cli 1.38.0:
- detect() → true (via `kimi info` vendor match)
- getSessionInfo → correct summary + UUID
- getRestoreCommand → matches kimi's own resume hint
@harsh-batheja

Copy link
Copy Markdown
Contributor Author

All filed issues addressed in `85821646`

Item Status
[MED] `detect()` too loose (`\bkimi\b` matches unrelated binaries) ✅ Fixed — switched to `kimi info` vendor-string match (kimi-cli / kimi-code / moonshot), 4 KB maxBuffer cap
[MED] Launch command doesn't pass `--work-dir` ⚠️ Investigated — `AgentLaunchConfig` exposes only `projectConfig.path` (project root), which would actively break discovery. Needs a core-types change to add `session.workspacePath`. Left a comment documenting the constraint
[LOW] Empty-bucket race returned transient null ✅ Fixed — fall back to UUID-dir mtime when live files aren't written yet
[LOW] `isProcessRunning` matched "kimi" anywhere in ps args ✅ Fixed — anchored to argv[0] (or python/uv/node runner followed by `kimi` as first positional)
[NIT] Symlink normalization ✅ Fixed — `realpath`-resolve workspacePath before MD5, best-effort fallback

Tests: 75 → 80, all green. New coverage: detect() vendor matrix (kimi-cli / kimi-code / moonshot accepted, unrelated "kimi keyboard input manager" rejected); isProcessRunning rejects `cat kimi.log` / `vim ~/.kimi/config.toml`; accepts `python -m kimi`; native signal falls back to UUID-dir mtime during the race window; symlinked workspace matches realpath-hashed bucket.

Verified end-to-end against real kimi-cli 1.38.0: detect() still true, getSessionInfo returns correct summary + UUID, getRestoreCommand matches kimi's own resume hint.

@illegalcall illegalcall left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Inline findings below. Priorities: session-identity + activity-ordering are the load-bearing ones.

Addresses all 10 inline comments on PR #1390.

Load-bearing fixes:

[#6 line 327] detectActivity ordering was wrong
  The old code checked the idle prompt (`^kimi>\s*$`) before approval/error
  patterns. Real kimi UI re-renders `kimi>` on the last line when asking for
  a confirmation, so \`(Y)es/(N)o\\nkimi>\` was misclassified as idle and the
  session would sit forever looking quiet while actually blocked on input.
  Reordered to: waiting_input → blocked → idle → active. Matches codex/aider.

[#2,#4,#8 lines 128,154,493] No stable AO↔Kimi session binding
  Discovery was pure (path-hash + recency). If the user ran kimi manually in
  the same repo, or two AO sessions shared a workspace hash, AO would attach
  to the wrong UUID — summary / activity / --resume target all corrupted.
  Now:
   - \`session.metadata.kimiSessionId\` pins a specific UUID when set; no
     fallback to recency when the pin misses (fails closed, no silent drift).
   - Unpinned lookups filter UUIDs by \`liveMtime >= session.createdAt - 60s\`
     so stray dirs from prior AO sessions don't attach.
   - findKimiSessionMatch now takes the whole Session (not just workspacePath)
     so createdAt + metadata are available.

[#3 line 141] Any recent subdir was treated as a real session
  Stray temp dirs and crash leftovers would match on mtime, producing
  \`kimi --resume <garbage>\` and bogus active states. Now require
  context.jsonl OR wire.jsonl to exist before trusting a dir. The race
  fallback (empty UUID dir → dir mtime) is removed — the JSONL activity
  fallback in getActivityState covers the startup window instead.

[#5 line 191] Symlink follow outside ~/.kimi/sessions/
  \`stat()\` / \`createReadStream()\` followed symlinks without rebinding, so
  a bucket entry that's a symlink to \`/dev/zero\` or \`/etc/passwd\` would
  hang forever or leak data. Added \`isInsideKimiSessions(path)\` that realpaths
  the candidate and rejects anything outside the sessions root. Every
  bucket entry is checked before use.

Smaller cleanups:

[#1 line 89] Cache: 30s negative TTL + unbounded growth
  Negative results now cached 2s so a session appearing mid-poll is picked
  up on the next cycle. Expired entries evicted on read. Cache capped at
  256 entries with oldest-expiry pruning. Key changed to (workspacePath,
  pinnedUuid) so two AO sessions in the same bucket can't poison each
  other's cache entry.

[#7 line 440] Duplicate argv0Re regex — use the const.

[#9 line 532] maxBuffer: 4096 → 65536. Future \`kimi info\` releases that add
  plugin listings or telemetry banners won't silently break detect() with
  swallowed ENOBUFS.

[#10 test line 650] macOS test breakage: /var/folders is a symlink to
  /private/var/folders, so fakeHome under tmpdir() is a symlink path, while
  the plugin realpaths before hashing. Wrap the mkdtempSync in realpathSync
  so tests agree with the plugin on the canonical path. Linux CI masked this.

Tests: 80 → 86. New coverage:
  - detectActivity classifies confirmation-then-prompt-rerender as waiting_input
  - detectActivity classifies error-then-prompt-rerender as blocked
  - createdAt floor filter (ignores UUIDs from before the AO session)
  - Pinned kimiSessionId wins over recency
  - Pinned UUID missing returns null (no silent fallback)
  - Negative cache TTL ~2s (session appearing mid-poll picked up next cycle)
  - Empty UUID dir without live files is rejected (no stray-dir attach)

Verified end-to-end against real kimi-cli 1.38.0: detect() true,
getSessionInfo extracts correct summary + UUID, getRestoreCommand matches
kimi's own resume hint.
@harsh-batheja

Copy link
Copy Markdown
Contributor Author

All 10 inline comments from @illegalcall addressed in `9795e8b8`

# Line Issue Status
1 89 Cache: 30s negative TTL → startup blind window; no eviction → unbounded growth ✅ Negative TTL 2s, positive TTL 30s, expired entries evicted on read, 256-entry soft cap with oldest-expiry pruning, key changed to `(workspace, pinnedUuid)`
2 128 No persisted Kimi session UUID — pure path-hash + recency ✅ `session.metadata.kimiSessionId` pins a specific UUID when set; unpinned lookups filter by `mtime >= session.createdAt - 60s`
3 141 Any recent subdir trusted (temp/crash leftovers) ✅ Require `context.jsonl` OR `wire.jsonl` to exist. Removed the bucket-dir mtime fallback — the JSONL activity fallback covers the startup race instead
4 154 No AO↔Kimi binding — two sessions in same bucket step on each other ✅ Solved by 2+3 together: pinned UUID is authoritative, stray UUIDs fail the createdAt floor
5 191 Symlinks in bucket could redirect reads to arbitrary files/FIFOs ✅ Added `isInsideKimiSessions(path)` sandbox check — realpath both the sessions root and the candidate, reject anything outside
6 327 `detectActivity` checked idle prompt before waiting_input/blocked — lost actionable signals ✅ Reordered: waiting_input → blocked → idle → active. Matches codex/aider. Tested against the real "confirmation-then-kimi>-rerender" pattern
7 440 Duplicate regex at line 440 ✅ Reuses `argv0Re` const
8 493 `getRestoreCommand` emitted bogus UUIDs ✅ Gated by #2+#3 — only reaches `kimi --resume ` when the UUID was either pinned or passed the createdAt+live-files checks
9 532 `maxBuffer: 4096` too small; future `kimi info` bloat → swallowed ENOBUFS ✅ Bumped to 65 536
10 test 650 macOS symlink test broke because `/var/folders` is a symlink ✅ `realpathSync(mkdtempSync(...))` so `fakeHome` is the canonical path; plugin and test agree

Tests: 80 → 86 (all green). New coverage:

  • `detectActivity` classifies `(Y)es/(N)o\nkimi>` as `waiting_input` (was `idle` — real bug)
  • `detectActivity` classifies `error:…\nkimi>` as `blocked`
  • `createdAt` floor filter ignores UUIDs from before the AO session
  • Pinned `kimiSessionId` wins over recency
  • Pinned UUID missing returns null (fails closed, no silent fallback)
  • Negative cache TTL ~2s — session appearing mid-poll picked up next cycle
  • Empty UUID dir without live files is rejected

Verified end-to-end against real `kimi-cli 1.38.0`: `detect()` → true, `getSessionInfo` extracts correct summary + UUID, `getRestoreCommand` matches kimi's own resume hint. Full `pnpm typecheck` / `pnpm lint` (0 errors) / `pnpm test` clean.

…ork-dir

Read ~/.kimi/kimi.json work_dirs[] as the authoritative workspace-to-session
mapping. When last_session_id is populated, prefer it over the directory-mtime
recency heuristic — kimi itself wrote it. Falls back gracefully to the existing
MD5 hash scan when kimi.json is absent or last_session_id is null.

Add --work-dir to getLaunchCommand using projectConfig.path to establish an
explicit cwd contract, preventing shell-rc / tmux-hook drift from causing the
MD5(cwd) hash to diverge from kimi's session bucket.
The kimicode plugin's --work-dir was passing projectConfig.path, which
breaks worktree-mode workspaces. In worktree mode, projectConfig.path is
the original repo root while session.workspacePath is the per-session
checkout — they differ. Either kimi would write to the project root
(breaking worktree isolation) or md5(projectConfig.path) would diverge
from md5(session.workspacePath), so getActivityState/getSessionInfo would
never find this session's bucket.

Fix:
- Add optional `workspacePath` field to AgentLaunchConfig.
- Plumb it through all 3 launch call sites in session-manager.ts.
- kimicode getLaunchCommand uses config.workspacePath, falling back to
  config.projectConfig.path when undefined.
- Tests for the divergent-paths case.

Public-interface change: AgentLaunchConfig grows one optional field.

Invariants preserved:
- Agent.getLaunchCommand signature unchanged — still takes one
  AgentLaunchConfig.
- Existing plugins (claude-code, aider, codex, opencode) compile and run
  unchanged; the new field is optional and they ignore it.
- Clone-mode workspaces (where workspacePath === projectConfig.path)
  produce the same launch command as before.
- Fallback to projectConfig.path keeps callers that don't pass the new
  field working — no flag day required.
captureKimiBaseline() previously ran in postLaunchSetup, which races
against kimi's own startup writes. If kimi created its UUID directory
before postLaunchSetup ran, that UUID landed in `preExistingUuids` and
was filtered out forever — so `findKimiSessionMatch` returned null
permanently for that session.

Fix:
- Add optional `preLaunchSetup(workspacePath)` to the Agent interface,
  invoked from session-manager AFTER the workspace exists but BEFORE
  `runtime.create()` spawns the agent.
- Move captureKimiBaseline from postLaunchSetup to preLaunchSetup in
  the kimicode plugin.
- Test asserts the new UUID is attached even when written immediately
  after preLaunchSetup runs (i.e. in the race window).

Public-interface change: Agent.preLaunchSetup is optional. Existing
plugins (claude-code, aider, codex, opencode) compile and behave
unchanged. Only kimicode opts in.

Invariants preserved:
- Workspace exists before preLaunchSetup runs (called after the
  worktree/clone is created, never before).
- Failures in preLaunchSetup propagate just like other launch-path
  failures — the existing try/catch covers it.
- captureKimiBaseline is still write-once (returns early if the
  baseline file already exists), so restore preserves the original
  partition.
The session.metadata.kimiSessionId branch was treated as the highest-
priority signal but nothing ever populated it. That left the entire
"AO↔kimi UUID binding" mechanism dead — discovery fell through to the
recency heuristic on every call, so a manual `kimi` run in the same
workspace, a sibling AO session sharing a bucket, or any drift in
kimi's directory layout could attach the wrong session.

Fix:
- Remove the dead session.metadata.kimiSessionId branch from
  findKimiSessionMatchUncached and the cache key.
- Add a workspace-local pin file (.ao/kimi-session-id.json). Once
  findKimiSessionMatchUncached identifies a winner via the recency
  heuristic (or via kimi.json's last_session_id soft-pin), it writes
  the UUID to the pin file. Subsequent calls read the pin file as the
  highest-priority signal and skip the heuristic entirely — locking
  in the AO↔kimi binding for the rest of the session lifetime.
- Cache key simplified to workspacePath alone since the pin is now
  persistent and cannot drift between calls.
- Tests cover: pin wins over recency, first match writes the pin,
  pin holds when a newer non-pinned UUID appears later.

Mechanism mirrors the existing .ao/kimi-baseline.json pattern (also
file-based, write-once, lives in the workspace).
index.ts had grown to 880 lines after the pin-file fix landed. The
discovery layer (kimi.json parsing, baseline capture, pin file, hash
bucket scan, cache) is one cohesive responsibility — pulling it out
keeps both files under the 500-line mark and makes the precedence
rules legible.

- New file: session-discovery.ts. Opens with a decision-table comment
  documenting the precedence (pin file → kimi.json soft-pin → recency
  heuristic) so future readers see the rule before the code.
- Public surface: captureKimiBaseline, findKimiSessionMatch,
  KimiSessionMatch, kimiShareDir, _resetSessionMatchCache.
- index.ts re-exports _resetSessionMatchCache so the existing test
  imports keep working.
- No behavioral change — all 98 tests pass unchanged.
Adds a test where workspacePath (per-session worktree) and
projectConfig.path (repo root) are different paths. Asserts that
discovery hashes workspacePath — not projectConfig.path — for the
kimi bucket lookup. Previously this scenario was untested; the bug
fixed in 9fcc1d9 (--work-dir using projectConfig.path) would have
been caught by this test.

Combined with the earlier --work-dir tests in 9fcc1d9, the worktree
divergent-paths case is now exercised at both the launch site
(getLaunchCommand) and the discovery site (getRestoreCommand) end
to end.
Addresses illegalcall's review comment (id 3127022353): the existing
isInsideKimiSessions check verified the session DIRECTORY but not its
children. A symlinked context.jsonl, wire.jsonl, or wire.jsonl pointing
at /etc/passwd, /dev/zero, or a FIFO would be silently followed by
stat() / createReadStream() — leaking reads, hanging on devices, or
escaping the kimi-sessions sandbox.

Fix:
- New isKimiSessionFile(path) helper using lstat + isFile() — rejects
  symlinks, sockets, FIFOs, block/char devices. lstat (not stat) so we
  see the symlink itself before the kernel resolves it.
- getKimiLiveSignalMtime swapped to lstat-based check; non-regular
  files contribute no mtime.
- extractKimiSummary refuses to open wire.jsonl when it isn't a
  regular file.
- Tests cover both paths: getActivityState rejects a session whose
  live-signal files are symlinked outside the bucket; getSessionInfo
  returns null summary when wire.jsonl is symlinked even if context.jsonl
  is real.
@harsh-batheja

Copy link
Copy Markdown
Contributor Author

@illegalcall — circling back on the 10 inline comments from your earlier review. Status of each:

  • 3127022353 (sandbox-check live-signal files against symlinks) — just fixed in 73082e5. New isKimiSessionFile helper uses lstat + isFile() to reject symlinks/sockets/FIFOs; both getKimiLiveSignalMtime and extractKimiSummary go through it now.
  • 3127022345 / 3127022350 (no persisted Kimi UUID, no stable AO↔Kimi binding) — addressed in 9285585. New .ao/kimi-session-id.json pin file, written on first successful match, locks the UUID for the session lifetime.
  • 3127022344 (negative cache TTL) — already 2s with prune-on-grow eviction (9795e8b).
  • 3127022349 (empty/temp dirs) — getKimiLiveSignalMtime requires context.jsonl or wire.jsonl to exist (9795e8b).
  • 3127022356 (detectActivity ordering) — fixed to waiting_input → blocked → idle → active (8582164).
  • 3127022359 (regex dup) — single argv0Re const (9795e8b).
  • 3127022362 (getRestoreCommand validation) — gated by the same discovery cascade (pin file + live-signal validation).
  • 3127022366 (execFileSync maxBuffer) — bumped to 65536 (9795e8b).
  • 3127022369 (macOS symlink test) — fakeHome is realpathSync(mkdtempSync(...)) in beforeEach.

Plus this round's structural fixes on top of bc6f1cf:

  • workspacePath now plumbed through AgentLaunchConfig so --work-dir matches the per-session worktree (9fcc1d9)
  • preLaunchSetup Agent hook to capture the baseline before kimi launches, closing the startup race (006f82c)
  • Discovery layer extracted into session-discovery.ts with a precedence decision-table comment (71600fa)

101 tests pass, typecheck + lint clean. Ready for another look when you have a moment.

… soft-pin

The kimi.json soft-pin used to record a candidate UUID before the baseline
and createdAt filters were applied, so a stale last_session_id pointing at
a pre-AO UUID (manual `kimi` run, kimi.json lag) would be captured into
.ao/kimi-session-id.json and route every later getActivityState /
getSessionInfo / getRestoreCommand call at the wrong conversation, with
no self-healing path.

Move the baseline + createdAt floor checks above the soft-pin branch so
the soft-pin candidate goes through the same gates as the recency contest.

Add two regression tests:
- soft-pin pointing at a baseline UUID is rejected and the AO pin file
  records the legitimate AO-spawned UUID instead
- soft-pin pointing at a UUID older than session.createdAt - 60s is
  rejected by the createdAt floor

Both tests fail on the prior code and pass after the fix.
@harsh-batheja
harsh-batheja dismissed harshitsinghbhandari’s stale review May 1, 2026 08:40

Solved, asking for re-review

@harsh-batheja
harsh-batheja merged commit 00176ab into main May 1, 2026
10 checks passed
alerios pushed a commit to AIMagicFlow/agent-orchestrator that referenced this pull request Oct 14, 2026
* feat(plugin): add kimicode agent plugin

Add @aoagents/ao-plugin-agent-kimicode implementing the Agent interface
for MoonshotAI's Kimi Code CLI. Follows the AO activity JSONL + PATH
wrapper pattern established by agent-aider/opencode, with a native-ish
signal sourced from ~/.kimi/<session>/ mtimes when present.

- Full Agent interface: getLaunchCommand (--yolo, --model, --agent-file),
  getEnvironment (AO_SESSION_ID + ~/.ao/bin PATH + GH_PATH), detectActivity,
  getActivityState (5-step cascade with mandatory JSONL entry fallback),
  isProcessRunning (tmux TTY + PID signal-0, matches `.kimi`/`uv run kimi`),
  getSessionInfo (state.json parsing), getRestoreCommand (--resume <id>
  with --continue fallback), setupWorkspaceHooks, postLaunchSetup,
  recordActivity, detect().
- Post-launch prompt delivery — kimi's `-p` implicitly enables --print and
  exits, which would break interactive supervised sessions.
- 58 unit tests covering all 7 mandatory getActivityState cases plus
  manifest, launch, env, prompt classification, process detection,
  session info extraction, restore command, and detect().
- Register in cli/src/lib/plugins.ts, detect-agent.ts, plugin-registry.json,
  cli package deps, and update user-facing docs / yaml examples.

Closes OrchestratorInc#1384

* fix(plugin): register kimicode in core BUILTIN_PLUGINS and web services

The CLI-side registration in packages/cli/src/lib/plugins.ts only covers
`getAgentByName` callers. Code paths that go through the shared plugin
registry (session-manager, doctor, plugin, verify CLI commands, and the
web dashboard's services singleton) use `createPluginRegistry()` +
`loadBuiltins()` / explicit `register()`, which bypass the CLI map.

Without this wiring:
- `pnpm ao doctor` / `ao plugin` / `ao verify` wouldn't see kimicode
- Web dashboard would fail to render sessions with `agent: kimicode`
  because the webpack-bundled services.ts couldn't resolve the plugin

Add kimicode to:
- packages/core/src/plugin-registry.ts BUILTIN_PLUGINS
- packages/web/package.json dependencies
- packages/web/src/lib/services.ts static imports + register call

Caught while comparing against OrchestratorInc#1395 (kimi-2-6-code plugin), which added
the same registry entry.

* fix(plugin-kimicode): address review feedback

Critical (from @harshitsinghbhandari, verified against kimi-cli source):
- Remove `promptDelivery: "post-launch"` — `-p`/`--prompt` is just a prompt
  string alias (also `--command`/`-c`), NOT a mode switch. The non-interactive
  flag is `--print`, which we never set. Inline delivery via `--prompt` is
  reliable and avoids the post-launch sendMessage() delay.
- Drop unchecked `as string` casts in getRestoreCommand in favor of typeof
  guards + `?? undefined` so null model values don't silently leak.

Medium (performance):
- Add 30s per-workspace cache to findKimiSessionMatch (mirrors codex's
  SESSION_FILE_CACHE_TTL_MS) so the ~/.kimi/ scan doesn't run 12×/min per
  active session. Cache keyed by workspacePath; cleared via the new
  `_resetSessionMatchCache` test-only export between test cases.

Minor (correctness):
- Collapse findKimiSessionDir + readKimiSessionState into one
  findKimiSessionMatch that returns {dir, state} from a single state.json
  read. Previously the file was parsed twice per getSessionInfo /
  getRestoreCommand call.
- Wire config.subagent → `kimi --agent <name>` (default / okabe / custom).
- Tighten detectActivity patterns so "I approve of this approach" and
  "Earlier I failed to connect" no longer falsely trigger waiting_input /
  blocked. Regexes are now line-anchored with `^`/`$` + `\b` word boundaries.

Tests: 58 → 71 (all green). New cases cover:
- Native-signal ready/idle decay (previously only active was tested)
- Cascade ordering: JSONL waiting_input wins over a matching native signal
- Malformed state.json in both getSessionInfo and getRestoreCommand
- `work_dir` alias accepted in addition to `cwd`
- project.agentConfig.model preferred over state.json's recorded model
- False-positive narration guards for both regex tightenings

* refactor(plugin-kimicode): clean up after second-round review

All changes are non-behavioral perf/style cleanups flagged during my second
review pass — no user-visible changes.

- Consolidate double JSON.parse in findKimiSessionMatchUncached: the previous
  pass parsed each candidate state.json once to extract cwd and a second time
  to extract session_id/model/title. Replaced both helpers with a single
  `parseKimiState(raw)` that returns all four fields in one traversal.
- Carry state.json's mtime through KimiSessionMatch so getKimiLiveSignalMtime
  (renamed from getKimiSessionMtime) doesn't re-stat state.json — the winner's
  mtime was already captured during the scan. Live-signal probe is now limited
  to context.jsonl + wire.jsonl (the per-turn files) and runs them in parallel
  via Promise.all instead of sequential awaits.
- Fold state.json mtime and the live-signal mtime into a single "freshest"
  timestamp in getActivityState so a recently-written context.jsonl wins even
  when state.json is stale.
- Tighten appendApprovalFlags signature: `string | undefined` → proper
  `AgentPermissionInput | undefined` so typos at call sites fail at compile
  time.
- Stricter detect(): don't trust every binary named `kimi` — verify the
  --version output mentions kimi/kimi-cli/kimi-code, and fall back to
  `kimi info` for builds that print a bare version number. Rejects unrelated
  tools that happen to install a `kimi` binary.

Tests: 71 → 75. New coverage:
- detect() accepts kimi-cli vendor strings
- detect() falls back to `kimi info` when --version is ambiguous
- detect() rejects an unrelated `kimi` binary
- Native signal picks the fresher of state.json vs context.jsonl mtimes

* fix(plugin-kimicode): correct session layout discovered via smoke test

Installing kimi-cli 1.38.0 locally (\`uv tool install kimi-cli\`) and running
it once revealed the plugin's session-discovery logic was built on wrong
assumptions about the on-disk layout.

Observed layout (kimi-cli 1.38.0):

  ~/.kimi/sessions/<md5(cwd)>/<session-uuid>/
    context.jsonl  — conversation history
    wire.jsonl     — turn events (TurnBegin/TurnEnd with user_input payload)

Differences from my original assumptions:

- Sessions are nested under \`sessions/\` (not direct subdirectories of
  \`~/.kimi/\`).
- The workspace is identified by an MD5 hash of the absolute path, not by
  a \`cwd\` field stored in a state file.
- There is no \`state.json\`. No \`title\`, \`model\`, or \`cost\` is persisted.
- The session ID is the UUID directory name and is accepted as-is by
  \`kimi --resume <uuid>\`.
- The old \`--continue\` fallback is unnecessary — if we found the directory,
  we always know its UUID.

Fixes:

- \`findKimiSessionMatch\` now computes \`md5(workspacePath)\` with node:crypto
  and lists \`~/.kimi/sessions/<hash>/\` directly. No more full-tree scan of
  \`~/.kimi/\`, no more \`readFile\` of a fictional \`state.json\`.
- \`getKimiLiveSignalMtime\` keeps the parallel \`Promise.all\` stat of
  context.jsonl + wire.jsonl (the only files that exist).
- \`getSessionInfo\` streams the first \`TurnBegin\` out of wire.jsonl as a
  best-effort summary, with a 1 MB byte ceiling. agentSessionId is the UUID.
- \`getRestoreCommand\` drops the \`--continue\` fallback branch — a found dir
  always has a usable UUID.

Verified end-to-end against the real kimi-cli 1.38 binary on this machine:
- \`detect()\` → true
- \`getLaunchCommand\` output parses cleanly when run with \`--help\`
- \`getSessionInfo\` extracts the actual first user prompt ("say hello")
- \`getRestoreCommand\` produces the same UUID kimi itself prints as the
  resume hint: \`kimi -r 6ec34626-aedf-4659-a061-c5fbfa4cf166\`

Tests remain at 75 green. Coverage is now against real on-disk layouts
using temp directories with MD5-hashed bucket names — no mock-structure
drift from reality.

* fix(plugin-kimicode): address follow-up review issues

Follow-up to the issues filed as a review comment on the PR.

[MED] detect() too loose (\bkimi\b matches unrelated binaries)
  The old regex accepted plain "kimi" alone because the (?:cli|code)?
  suffix was optional — any binary whose output contains "kimi" passed.
  Real kimi-cli's --version prints just "kimi, version X.Y.Z" (no suffix),
  so --version alone can't distinguish it from, say, a hypothetical
  keyboard-input-manager named kimi. Switch to `kimi info` exclusively;
  real kimi-cli prints "kimi-cli version: ..." which is a distinct vendor
  string. Regex now requires "kimi-cli" / "kimi-code" / "moonshot"
  literally. Added maxBuffer cap (4 KB) so a hostile binary can't flood
  detect() with MB-scale output.

[MED] --work-dir not passed — investigated, not actionable in this PR
  AgentLaunchConfig doesn't expose session.workspacePath — only
  projectConfig.path (the project root), which would actively break
  discovery if passed. Runtime cwd handling is load-bearing. Left a
  comment explaining the constraint and pointing at the core-types
  change needed to fix it properly.

[LOW] Empty-bucket race returned transient null
  During session creation kimi mkdirs the UUID directory before writing
  context.jsonl / wire.jsonl. getKimiLiveSignalMtime returned null in
  that window and findKimiSessionMatch returned null, flickering the
  dashboard to "no signal". Fall back to the UUID directory's own mtime
  when live files are absent.

[LOW] isProcessRunning matched "kimi" anywhere in ps args
  Old regex /(?:^|\/)\.?kimi(?:\s|$)|(?:\s|^)kimi(?:\s|$)/ matched
  `cat kimi.log`, `vim ~/.kimi/config.toml`, etc. Anchor to argv[0]
  instead — only the executable itself, or a python/uv/node runner
  followed by `kimi` as the first positional argument, counts.

[NIT] Symlink normalization
  kimi's process reads cwd via os.getcwd(), which returns the realpath on
  Linux. If AO hands us a symlinked workspacePath, our MD5(symlink) won't
  match kimi's MD5(realpath). realpath-resolve with a best-effort fallback
  to the raw string (preserves behavior when the path doesn't exist yet).

Tests: 75 → 80. New coverage:
- detect() vendor-string matrix: kimi-cli / kimi-code / moonshot accepted,
  unrelated "kimi keyboard input manager" rejected
- isProcessRunning rejects `cat kimi.log` / `vim ~/.kimi/config.toml`
- isProcessRunning accepts `python -m kimi`
- Native signal falls back to UUID-dir mtime during the empty-bucket race
- Symlinked workspace path matches the realpath-hashed bucket

Verified end-to-end against real kimi-cli 1.38.0:
- detect() → true (via `kimi info` vendor match)
- getSessionInfo → correct summary + UUID
- getRestoreCommand → matches kimi's own resume hint

* fix(plugin-kimicode): address inline review from illegalcall

Addresses all 10 inline comments on PR OrchestratorInc#1390.

Load-bearing fixes:

[OrchestratorInc#6 line 327] detectActivity ordering was wrong
  The old code checked the idle prompt (`^kimi>\s*$`) before approval/error
  patterns. Real kimi UI re-renders `kimi>` on the last line when asking for
  a confirmation, so \`(Y)es/(N)o\\nkimi>\` was misclassified as idle and the
  session would sit forever looking quiet while actually blocked on input.
  Reordered to: waiting_input → blocked → idle → active. Matches codex/aider.

[OrchestratorInc#2,OrchestratorInc#4,OrchestratorInc#8 lines 128,154,493] No stable AO↔Kimi session binding
  Discovery was pure (path-hash + recency). If the user ran kimi manually in
  the same repo, or two AO sessions shared a workspace hash, AO would attach
  to the wrong UUID — summary / activity / --resume target all corrupted.
  Now:
   - \`session.metadata.kimiSessionId\` pins a specific UUID when set; no
     fallback to recency when the pin misses (fails closed, no silent drift).
   - Unpinned lookups filter UUIDs by \`liveMtime >= session.createdAt - 60s\`
     so stray dirs from prior AO sessions don't attach.
   - findKimiSessionMatch now takes the whole Session (not just workspacePath)
     so createdAt + metadata are available.

[OrchestratorInc#3 line 141] Any recent subdir was treated as a real session
  Stray temp dirs and crash leftovers would match on mtime, producing
  \`kimi --resume <garbage>\` and bogus active states. Now require
  context.jsonl OR wire.jsonl to exist before trusting a dir. The race
  fallback (empty UUID dir → dir mtime) is removed — the JSONL activity
  fallback in getActivityState covers the startup window instead.

[OrchestratorInc#5 line 191] Symlink follow outside ~/.kimi/sessions/
  \`stat()\` / \`createReadStream()\` followed symlinks without rebinding, so
  a bucket entry that's a symlink to \`/dev/zero\` or \`/etc/passwd\` would
  hang forever or leak data. Added \`isInsideKimiSessions(path)\` that realpaths
  the candidate and rejects anything outside the sessions root. Every
  bucket entry is checked before use.

Smaller cleanups:

[OrchestratorInc#1 line 89] Cache: 30s negative TTL + unbounded growth
  Negative results now cached 2s so a session appearing mid-poll is picked
  up on the next cycle. Expired entries evicted on read. Cache capped at
  256 entries with oldest-expiry pruning. Key changed to (workspacePath,
  pinnedUuid) so two AO sessions in the same bucket can't poison each
  other's cache entry.

[OrchestratorInc#7 line 440] Duplicate argv0Re regex — use the const.

[OrchestratorInc#9 line 532] maxBuffer: 4096 → 65536. Future \`kimi info\` releases that add
  plugin listings or telemetry banners won't silently break detect() with
  swallowed ENOBUFS.

[OrchestratorInc#10 test line 650] macOS test breakage: /var/folders is a symlink to
  /private/var/folders, so fakeHome under tmpdir() is a symlink path, while
  the plugin realpaths before hashing. Wrap the mkdtempSync in realpathSync
  so tests agree with the plugin on the canonical path. Linux CI masked this.

Tests: 80 → 86. New coverage:
  - detectActivity classifies confirmation-then-prompt-rerender as waiting_input
  - detectActivity classifies error-then-prompt-rerender as blocked
  - createdAt floor filter (ignores UUIDs from before the AO session)
  - Pinned kimiSessionId wins over recency
  - Pinned UUID missing returns null (no silent fallback)
  - Negative cache TTL ~2s (session appearing mid-poll picked up next cycle)
  - Empty UUID dir without live files is rejected (no stray-dir attach)

Verified end-to-end against real kimi-cli 1.38.0: detect() true,
getSessionInfo extracts correct summary + UUID, getRestoreCommand matches
kimi's own resume hint.

* fix(plugin-kimicode): use kimi.json for workspace mapping and add --work-dir

Read ~/.kimi/kimi.json work_dirs[] as the authoritative workspace-to-session
mapping. When last_session_id is populated, prefer it over the directory-mtime
recency heuristic — kimi itself wrote it. Falls back gracefully to the existing
MD5 hash scan when kimi.json is absent or last_session_id is null.

Add --work-dir to getLaunchCommand using projectConfig.path to establish an
explicit cwd contract, preventing shell-rc / tmux-hook drift from causing the
MD5(cwd) hash to diverge from kimi's session bucket.

* fix(plugin-kimicode): plumb workspacePath into AgentLaunchConfig

The kimicode plugin's --work-dir was passing projectConfig.path, which
breaks worktree-mode workspaces. In worktree mode, projectConfig.path is
the original repo root while session.workspacePath is the per-session
checkout — they differ. Either kimi would write to the project root
(breaking worktree isolation) or md5(projectConfig.path) would diverge
from md5(session.workspacePath), so getActivityState/getSessionInfo would
never find this session's bucket.

Fix:
- Add optional `workspacePath` field to AgentLaunchConfig.
- Plumb it through all 3 launch call sites in session-manager.ts.
- kimicode getLaunchCommand uses config.workspacePath, falling back to
  config.projectConfig.path when undefined.
- Tests for the divergent-paths case.

Public-interface change: AgentLaunchConfig grows one optional field.

Invariants preserved:
- Agent.getLaunchCommand signature unchanged — still takes one
  AgentLaunchConfig.
- Existing plugins (claude-code, aider, codex, opencode) compile and run
  unchanged; the new field is optional and they ignore it.
- Clone-mode workspaces (where workspacePath === projectConfig.path)
  produce the same launch command as before.
- Fallback to projectConfig.path keeps callers that don't pass the new
  field working — no flag day required.

* fix(plugin-kimicode): capture baseline pre-launch to close startup race

captureKimiBaseline() previously ran in postLaunchSetup, which races
against kimi's own startup writes. If kimi created its UUID directory
before postLaunchSetup ran, that UUID landed in `preExistingUuids` and
was filtered out forever — so `findKimiSessionMatch` returned null
permanently for that session.

Fix:
- Add optional `preLaunchSetup(workspacePath)` to the Agent interface,
  invoked from session-manager AFTER the workspace exists but BEFORE
  `runtime.create()` spawns the agent.
- Move captureKimiBaseline from postLaunchSetup to preLaunchSetup in
  the kimicode plugin.
- Test asserts the new UUID is attached even when written immediately
  after preLaunchSetup runs (i.e. in the race window).

Public-interface change: Agent.preLaunchSetup is optional. Existing
plugins (claude-code, aider, codex, opencode) compile and behave
unchanged. Only kimicode opts in.

Invariants preserved:
- Workspace exists before preLaunchSetup runs (called after the
  worktree/clone is created, never before).
- Failures in preLaunchSetup propagate just like other launch-path
  failures — the existing try/catch covers it.
- captureKimiBaseline is still write-once (returns early if the
  baseline file already exists), so restore preserves the original
  partition.

* fix(plugin-kimicode): persist UUID pin to disk instead of dead metadata

The session.metadata.kimiSessionId branch was treated as the highest-
priority signal but nothing ever populated it. That left the entire
"AO↔kimi UUID binding" mechanism dead — discovery fell through to the
recency heuristic on every call, so a manual `kimi` run in the same
workspace, a sibling AO session sharing a bucket, or any drift in
kimi's directory layout could attach the wrong session.

Fix:
- Remove the dead session.metadata.kimiSessionId branch from
  findKimiSessionMatchUncached and the cache key.
- Add a workspace-local pin file (.ao/kimi-session-id.json). Once
  findKimiSessionMatchUncached identifies a winner via the recency
  heuristic (or via kimi.json's last_session_id soft-pin), it writes
  the UUID to the pin file. Subsequent calls read the pin file as the
  highest-priority signal and skip the heuristic entirely — locking
  in the AO↔kimi binding for the rest of the session lifetime.
- Cache key simplified to workspacePath alone since the pin is now
  persistent and cannot drift between calls.
- Tests cover: pin wins over recency, first match writes the pin,
  pin holds when a newer non-pinned UUID appears later.

Mechanism mirrors the existing .ao/kimi-baseline.json pattern (also
file-based, write-once, lives in the workspace).

* refactor(plugin-kimicode): extract session-discovery into its own module

index.ts had grown to 880 lines after the pin-file fix landed. The
discovery layer (kimi.json parsing, baseline capture, pin file, hash
bucket scan, cache) is one cohesive responsibility — pulling it out
keeps both files under the 500-line mark and makes the precedence
rules legible.

- New file: session-discovery.ts. Opens with a decision-table comment
  documenting the precedence (pin file → kimi.json soft-pin → recency
  heuristic) so future readers see the rule before the code.
- Public surface: captureKimiBaseline, findKimiSessionMatch,
  KimiSessionMatch, kimiShareDir, _resetSessionMatchCache.
- index.ts re-exports _resetSessionMatchCache so the existing test
  imports keep working.
- No behavioral change — all 98 tests pass unchanged.

* test(plugin-kimicode): worktree-mode end-to-end discovery test

Adds a test where workspacePath (per-session worktree) and
projectConfig.path (repo root) are different paths. Asserts that
discovery hashes workspacePath — not projectConfig.path — for the
kimi bucket lookup. Previously this scenario was untested; the bug
fixed in 9fcc1d9 (--work-dir using projectConfig.path) would have
been caught by this test.

Combined with the earlier --work-dir tests in 9fcc1d9, the worktree
divergent-paths case is now exercised at both the launch site
(getLaunchCommand) and the discovery site (getRestoreCommand) end
to end.

* fix(plugin-kimicode): sandbox-check live-signal files against symlinks

Addresses illegalcall's review comment (id 3127022353): the existing
isInsideKimiSessions check verified the session DIRECTORY but not its
children. A symlinked context.jsonl, wire.jsonl, or wire.jsonl pointing
at /etc/passwd, /dev/zero, or a FIFO would be silently followed by
stat() / createReadStream() — leaking reads, hanging on devices, or
escaping the kimi-sessions sandbox.

Fix:
- New isKimiSessionFile(path) helper using lstat + isFile() — rejects
  symlinks, sockets, FIFOs, block/char devices. lstat (not stat) so we
  see the symlink itself before the kernel resolves it.
- getKimiLiveSignalMtime swapped to lstat-based check; non-regular
  files contribute no mtime.
- extractKimiSummary refuses to open wire.jsonl when it isn't a
  regular file.
- Tests cover both paths: getActivityState rejects a session whose
  live-signal files are symlinked outside the bucket; getSessionInfo
  returns null summary when wire.jsonl is symlinked even if context.jsonl
  is real.

* fix(plugin-kimicode): apply baseline + createdAt filters to kimi.json soft-pin

The kimi.json soft-pin used to record a candidate UUID before the baseline
and createdAt filters were applied, so a stale last_session_id pointing at
a pre-AO UUID (manual `kimi` run, kimi.json lag) would be captured into
.ao/kimi-session-id.json and route every later getActivityState /
getSessionInfo / getRestoreCommand call at the wrong conversation, with
no self-healing path.

Move the baseline + createdAt floor checks above the soft-pin branch so
the soft-pin candidate goes through the same gates as the recency contest.

Add two regression tests:
- soft-pin pointing at a baseline UUID is rejected and the AO pin file
  records the legitimate AO-spawned UUID instead
- soft-pin pointing at a UUID older than session.createdAt - 60s is
  rejected by the createdAt floor

Both tests fail on the prior code and pass after the fix.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(plugin): implement kimicode agent plugin

3 participants