Skip to content

Commit 172ef94

Browse files
feat(channel): forward Claude tool invocations to Telegram via PreToolUse hook (#126)
1 parent 17e9c5c commit 172ef94

16 files changed

Lines changed: 1296 additions & 37 deletions

File tree

Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
---
2+
phase: design
3+
title: System Design & Architecture
4+
description: Define the technical architecture, components, and data models
5+
---
6+
7+
# System Design & Architecture
8+
9+
## Verified Hook Assumptions
10+
11+
| Assumption | Status | Evidence |
12+
|---|---|---|
13+
| A1: `Notification` hook exists | ❌ FALSE | Real Claude plugin hooks.json files show only: `PreToolUse`, `PostToolUse`, `Stop`, `UserPromptSubmit`, `SessionStart` |
14+
| A2: payload includes `session_id` | ✅ CONFIRMED (PreToolUse) | `security_reminder_hook.py:529`: `session_id = input_data.get("session_id")` |
15+
| A3: settings.json hooks schema | ✅ CONFIRMED | Multiple plugin hooks.json files confirm `{ hooks: { Event: [{ matcher?, hooks: [{type,command,timeout}] }] } }` |
16+
17+
**Chosen event**: `PreToolUse` with `matcher: "Bash|Edit|Write|MultiEdit|NotebookEdit|AskUserQuestion"`.
18+
19+
### Interactive prompt types and how they surface
20+
21+
| Prompt type | How it surfaces | Captured? |
22+
|---|---|---|
23+
| Tool approval prompt (Bash, Edit, Write, MultiEdit, NotebookEdit) | `PreToolUse` hook fires before tool execution | Yes — hook writes to agent-request store |
24+
| Question / single-select / multi-select prompt (`AskUserQuestion` tool) | `PreToolUse` hook fires with `tool_name: "AskUserQuestion"` and `tool_input.questions` array | Yes — included in hook matcher; forwarded as `[Question] <raw JSON>` (richer formatting is a future PR) |
25+
| Claude Code TUI selection dialog (generated by Claude Code UI layer, not the model) | No hook event fired | No — not hookable; limitation |
26+
27+
## Architecture Overview
28+
29+
```mermaid
30+
graph TD
31+
CC[Claude Code process] -->|fires PreToolUse for Bash/Edit/Write/MultiEdit/NotebookEdit/AskUserQuestion| HK[claude-prompt-hook.js\n~/.claude/hooks/]
32+
HK -->|overwrites| AR[Agent-Request Store\n~/.ai-devkit/agent-requests/session-id.json]
33+
34+
subgraph channel-runner [channel-runner.ts — startOutputPolling tick]
35+
JSONL[1. poll JSONL via getConversation] -->|new assistant/system msgs| TG[Telegram sendMessage]
36+
ASTORE[2. read agent-request store file]
37+
ASTORE -->|timestamp changed: send| TG
38+
ASTORE -->|timestamp unchanged: skip| NOOP[no-op]
39+
end
40+
41+
AR -->|read| ASTORE
42+
CC2[Claude Code JSONL] -->|read| JSONL
43+
44+
subgraph setup [ai-devkit setup --agent claude]
45+
SS[setup.service.ts] -->|copy script| HK
46+
SS -->|merge hook entry| SETTINGS[~/.claude/settings.json]
47+
end
48+
```
49+
50+
**Per-tick flow:**
51+
1. If `sessionFilePath` known: read JSONL, forward new assistant/system messages to Telegram.
52+
2. If `sessionId` known: read `~/.ai-devkit/agent-requests/<sessionId>.json`. If `entry.timestamp` differs from `lastAgentRequestTimestamp`, send the formatted message and update the cursor.
53+
54+
**Deduplication**: The agent-request file is overwritten on every hook invocation. The channel runner tracks `lastAgentRequestTimestamp` and only forwards entries whose `timestamp` field has changed since the previous tick.
55+
56+
## Data Models
57+
58+
### Agent-Request Store Entry (`~/.ai-devkit/agent-requests/<session-id>.json`)
59+
```ts
60+
// @ai-devkit/agent-manager — AgentRequest
61+
interface AgentRequest {
62+
sessionId: string;
63+
toolName: string; // e.g. "Bash", "AskUserQuestion"
64+
toolInput: Record<string, unknown>; // e.g. { command: "ls /tmp" } for Bash; { questions: [{question, header, options: [{label, description}], multiSelect}] } for AskUserQuestion
65+
timestamp: string; // ISO 8601 — used as the dedup key
66+
}
67+
```
68+
One flat file per session; the hook script overwrites it on each invocation. The `timestamp` field distinguishes distinct tool calls.
69+
70+
### Claude Code `PreToolUse` Hook Payload (stdin JSON)
71+
```ts
72+
interface PreToolUsePayload {
73+
session_id: string; // UUID, confirmed present
74+
tool_name: string; // e.g. "Bash", "AskUserQuestion"
75+
tool_input: Record<string, unknown>; // e.g. { command: "ls /tmp" }
76+
}
77+
```
78+
79+
### `~/.claude/settings.json` after setup
80+
```json
81+
{
82+
"hooks": {
83+
"PreToolUse": [
84+
{
85+
"matcher": "Bash|Edit|Write|MultiEdit|NotebookEdit|AskUserQuestion",
86+
"hooks": [{ "type": "command", "command": "node ~/.claude/hooks/claude-prompt-hook.js", "timeout": 10 }]
87+
}
88+
]
89+
}
90+
}
91+
```
92+
93+
## Component Breakdown
94+
95+
### 1. `hooks/claude/claude-prompt-hook.js` (also copied to `packages/cli/assets/claude/`)
96+
CJS script, dependency-free:
97+
- Reads `process.stdin`; skips if TTY.
98+
- Parses JSON; extracts `session_id`, `tool_name`, `tool_input`.
99+
- Sanitizes `session_id` (alphanumeric + hyphens only).
100+
- Creates `~/.ai-devkit/agent-requests/` directory.
101+
- Overwrites `~/.ai-devkit/agent-requests/<session-id>.json` with the current entry.
102+
- **Always exits 0** — never disrupts Claude Code.
103+
104+
### 2. `packages/cli/assets/claude/settings-hook.json`
105+
Settings fragment for the `PreToolUse` hook (merged during setup):
106+
```json
107+
{ "matcher": "Bash|Edit|Write|MultiEdit|NotebookEdit|AskUserQuestion", "hooks": [{ "type": "command", "command": "node ~/.claude/hooks/claude-prompt-hook.js", "timeout": 10 }] }
108+
```
109+
110+
### 3. `setup.service.ts` — `claude` agent definition
111+
```
112+
agent: 'claude', dotFolder: '.claude'
113+
steps:
114+
- claude-prompt-hook // copy script + merge PreToolUse entry (idempotent)
115+
- built-in-skills
116+
```
117+
118+
### 4. `packages/agent-manager/src/utils/agent-requests.ts`
119+
Agent/session infrastructure — lives in `agent-manager`, not the CLI:
120+
```ts
121+
interface AgentRequest { sessionId, toolName, toolInput, timestamp }
122+
123+
function getAgentRequestPath(homeDir: string, sessionId: string): string
124+
// returns path.join(homeDir, '.ai-devkit', 'agent-requests', `${sessionId}.json`)
125+
126+
function readLatestAgentRequest(homeDir: string, sessionId: string): AgentRequest | null
127+
// reads the single flat file; returns null if absent or malformed
128+
129+
function writeAgentRequest(homeDir: string, entry: AgentRequest): void
130+
// creates directory if needed; overwrites the file
131+
```
132+
All three are exported from `@ai-devkit/agent-manager`.
133+
134+
### 5. `channel-runner.ts` — `startOutputPolling()` extension
135+
136+
New state:
137+
- `lastAgentRequestTimestamp: string | undefined`
138+
- `home = options.homeDir ?? homedir()`
139+
140+
Per tick, after JSONL polling:
141+
```
142+
if agent.sessionId:
143+
agentRequest = readLatestAgentRequest(home, agent.sessionId)
144+
if agentRequest && agentRequest.timestamp !== lastAgentRequestTimestamp:
145+
send formatPromptMessage(agentRequest.toolName, agentRequest.toolInput)
146+
lastAgentRequestTimestamp = agentRequest.timestamp
147+
```
148+
149+
`formatPromptMessage` output:
150+
- `AskUserQuestion` with direct `question` field: `[Question] <question text>`
151+
- `AskUserQuestion` with `questions` array (actual Claude Code payload): `[Question] <raw JSON>`
152+
- Other tools: `[Tool prompt] <toolName>:\n<command or JSON>`
153+
154+
## Design Decisions
155+
156+
| Decision | Choice | Rationale |
157+
|---|---|---|
158+
| Hook event | `PreToolUse` (Bash, Edit, Write, MultiEdit, NotebookEdit, AskUserQuestion) | Covers approval prompts for shell/file ops and question/selection prompts; read-only ops excluded to avoid noise |
159+
| Agent-request store location | `packages/agent-manager` | Agent/session infrastructure belongs with the agent layer, not Telegram-specific CLI code |
160+
| Store layout | Single flat file per session (`<sessionId>.json`) | Simpler than per-session directory; overwrite semantics natural for "latest invocation" |
161+
| Deduplication | `timestamp` field comparison | Reliable; distinct hook invocations always produce distinct ISO timestamps |
162+
| No PID guard | Removed | Claude-specific; makes the polling logic agent-agnostic and simpler to extend |
163+
| Send ordering | JSONL first, agent-request store second | Avoids interleaving; assistant responses always precede the tool notification that caused them |
164+
| `OutputPollingOptions.homeDir` | Injectable for tests | Keeps prod code clean; tests use temp dirs without touching real `~/.ai-devkit/` |
165+
166+
## Non-Functional Requirements
167+
168+
- **Latency**: Agent-request notification reaches Telegram within ≤ 4 s (hook write + one poll tick).
169+
- **Reliability**: Hook always exits 0; errors silently swallowed.
170+
- **Idempotency**: `ai-devkit setup --agent claude` re-run does not duplicate hook entry.
171+
- **Security**: `session_id` sanitized before use as filename; writes only to `~/.ai-devkit/`.
172+
- **No regression**: Existing JSONL polling path unchanged.
173+
- **Agent-agnostic**: Polling logic uses no Claude-specific APIs (no PID files).
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
---
2+
phase: implementation
3+
title: Implementation Guide
4+
description: Technical implementation notes, patterns, and code guidelines
5+
---
6+
7+
# Implementation Guide
8+
9+
## Changed Files
10+
11+
| File | Change |
12+
|---|---|
13+
| `hooks/claude/claude-prompt-hook.js` | NEW — CJS hook; overwrites `~/.ai-devkit/agent-requests/<sessionId>.json` |
14+
| `packages/cli/assets/claude/claude-prompt-hook.js` | NEW — identical copy (installer asset) |
15+
| `packages/cli/assets/claude/settings-hook.json` | NEW — `PreToolUse` hook entry fragment (matcher: all tool types + AskUserQuestion) |
16+
| `packages/agent-manager/src/utils/agent-requests.ts` | NEW — `getAgentRequestPath`, `readLatestAgentRequest`, `writeAgentRequest` |
17+
| `packages/agent-manager/src/__tests__/utils/agent-requests.test.ts` | NEW — 6 unit tests |
18+
| `packages/agent-manager/src/index.ts` | MODIFIED — exports `AgentRequest`, `getAgentRequestPath`, `readLatestAgentRequest`, `writeAgentRequest` |
19+
| `packages/cli/src/services/setup/setup.service.ts` | MODIFIED — `claude` agent; `setupClaudePromptHook()` |
20+
| `packages/cli/src/services/channel/channel-runner.ts` | MODIFIED — `startOutputPolling()` extended with agent-request polling |
21+
| `packages/cli/src/__tests__/services/channel/channel-runner.test.ts` | NEW — agent-request polling tests + AskUserQuestion fixture tests |
22+
| `packages/cli/src/__tests__/services/setup/setup.service.test.ts` | MODIFIED — claude-agent tests appended |
23+
24+
## Key Implementation Notes
25+
26+
### Hook Script — flat file overwrite
27+
Writes to `~/.ai-devkit/agent-requests/<sessionId>.json`. Each invocation overwrites the previous entry. The `timestamp` field (ISO 8601) distinguishes distinct calls and is the dedup key.
28+
29+
### Agent-Request Store — `packages/agent-manager`
30+
Owned by `agent-manager` (agent/session infrastructure), not the CLI. Three exports:
31+
- `getAgentRequestPath(homeDir, sessionId)` — returns the flat file path
32+
- `readLatestAgentRequest(homeDir, sessionId)` — reads the file; null on missing or malformed JSON
33+
- `writeAgentRequest(homeDir, entry)` — creates dir if needed; overwrites file
34+
35+
The CLI imports these from `@ai-devkit/agent-manager`.
36+
37+
### `startOutputPolling()` — ordered sends, timestamp dedupe
38+
1. JSONL block runs first (`if agent.sessionFilePath`).
39+
2. Agent-request block runs second (`if agent.sessionId`).
40+
3. `lastAgentRequestTimestamp` tracks the last forwarded entry; no send if timestamp unchanged.
41+
4. Init seeds `lastAgentRequestTimestamp` from the pre-existing file so pre-existing entries are not replayed on connect.
42+
5. No PID file / `waitingFor` guard — agent-agnostic by design.
43+
44+
### `formatPromptMessage` — AskUserQuestion stays raw
45+
- `AskUserQuestion` with direct `question` string field: `[Question] <question text>`
46+
- `AskUserQuestion` with `questions` array (actual Claude Code payload): `[Question] <raw JSON>` — richer formatting deferred to a future PR
47+
- Other tools: `[Tool prompt] <toolName>:\n<command or JSON>`
48+
49+
### Settings matcher
50+
`"Bash|Edit|Write|MultiEdit|NotebookEdit|AskUserQuestion"` — covers all tool approval prompts and question/selection dialogs.
51+
52+
### Setup idempotency
53+
`setupClaudePromptHook` checks whether any existing `hooks.PreToolUse[].hooks[].command` equals the hook command string before appending.
54+
55+
## Edge Cases
56+
57+
- `agent.sessionFilePath` undefined → JSONL block skipped; agent-request block still runs.
58+
- Agent-request file absent → `readLatestAgentRequest` returns null; no send.
59+
- Agent-request file malformed → returns null; no send; no crash.
60+
- Same `timestamp` across ticks → `lastAgentRequestTimestamp` guard prevents duplicate sends.
61+
- `agent.sessionId` absent → agent-request block skipped entirely.
62+
- Non-Claude agents → no hook writes to `~/.ai-devkit/agent-requests/`; reads return null silently.
63+
64+
## Security
65+
66+
- `session_id` sanitized (`[a-zA-Z0-9\-]` only) before use as filename — prevents path traversal.
67+
- All writes to `~/.ai-devkit/agent-requests/` (user's own home dir only).
68+
- Hook always exits 0; errors swallowed — cannot disrupt Claude Code.
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
---
2+
phase: planning
3+
title: Project Planning & Task Breakdown
4+
description: Break down work into actionable tasks and estimate timeline
5+
---
6+
7+
# Project Planning & Task Breakdown
8+
9+
## Milestones
10+
11+
- [x] M1: Hook script + assets — standalone Claude hook script, asset files in place
12+
- [x] M2: Agent-request store — `agent-requests.ts` in `agent-manager`, unit-tested
13+
- [x] M3: Setup service — `claude` agent added, idempotent settings.json merge
14+
- [x] M4: Channel runner — agent-request store polling wired into `startOutputPolling`
15+
- [x] M5: Tests green — all new and existing tests passing; no regressions
16+
17+
## Task Breakdown
18+
19+
### M1: Hook Script + Assets
20+
21+
- [x] **T1.1** — Create `hooks/claude/claude-prompt-hook.js`
22+
- CJS, dependency-free; reads stdin JSON; extracts `session_id`, `tool_name`, `tool_input`
23+
- Sanitizes `session_id` (strip non-`[a-zA-Z0-9\-]`); overwrites `~/.ai-devkit/agent-requests/<id>.json`
24+
- Creates dir recursively; always exits 0
25+
- Outcome: runnable standalone via `echo '{"session_id":"abc","tool_name":"Bash","tool_input":{"command":"ls"}}' | node hooks/claude/claude-prompt-hook.js`
26+
27+
- [x] **T1.2** — Copy hook script to `packages/cli/assets/claude/claude-prompt-hook.js`
28+
29+
- [x] **T1.3** — Create `packages/cli/assets/claude/settings-hook.json`
30+
- `PreToolUse` hook entry; matcher: `"Bash|Edit|Write|MultiEdit|NotebookEdit|AskUserQuestion"`
31+
32+
### M2: Agent-Request Store Module
33+
34+
- [x] **T2.1** — Create `packages/agent-manager/src/utils/agent-requests.ts`
35+
- Export `AgentRequest` interface: `{ sessionId, toolName, toolInput, timestamp }`
36+
- Export `getAgentRequestPath(homeDir, sessionId): string` → `~/.ai-devkit/agent-requests/<sessionId>.json`
37+
- Export `readLatestAgentRequest(homeDir, sessionId): AgentRequest | null` — reads flat file; null on missing/malformed
38+
- Export `writeAgentRequest(homeDir, entry): void` — creates dir; overwrites file
39+
- All three exported from `@ai-devkit/agent-manager`
40+
41+
- [x] **T2.2** — Write unit tests for `agent-requests.ts`
42+
- File: `packages/agent-manager/src/__tests__/utils/agent-requests.test.ts`
43+
- Covers: path shape, write creates dir + file, overwrite replaces, read returns null for missing, null for malformed, correct entry for valid
44+
- Outcome: `npx nx run agent-manager:test` passes
45+
46+
### M3: Setup Service — Claude Agent
47+
48+
- [x] **T3.1** — Add `claude` to `SUPPORTED_SETUP_AGENTS` in `setup.service.ts`
49+
50+
- [x] **T3.2** — Implement `setupClaudePromptHook(context, agent)` in `setup.service.ts`
51+
- Copy `assets/claude/claude-prompt-hook.js` → `~/.claude/hooks/claude-prompt-hook.js`
52+
- Idempotent merge of `settings-hook.json` entry into `~/.claude/settings.json`
53+
54+
- [x] **T3.3** — Add `claude` agent setup definition with steps `[claude-prompt-hook, built-in-skills]`
55+
56+
- [x] **T3.4** — Write/extend setup service tests for claude agent
57+
58+
### M4: Channel Runner — Agent-Request Store Polling
59+
60+
- [x] **T4.1** — Import `readLatestAgentRequest` from `@ai-devkit/agent-manager` in `channel-runner.ts`
61+
62+
- [x] **T4.2** — Extend `startOutputPolling()` with agent-request polling
63+
- New state: `lastAgentRequestTimestamp: string | undefined`
64+
- On each tick (after JSONL block): `readLatestAgentRequest(home, agent.sessionId)`
65+
- If entry exists and `entry.timestamp !== lastAgentRequestTimestamp`: send `formatPromptMessage(toolName, toolInput)` and update cursor
66+
- Init seeds `lastAgentRequestTimestamp` from pre-existing file (skip replay on connect)
67+
- `formatPromptMessage`: `AskUserQuestion` → `[Question] <question or raw JSON>`; others → `[Tool prompt] ToolName:\n<command or JSON>`
68+
69+
- [x] **T4.3** — Write unit tests for agent-request store polling in `channel-runner.test.ts`
70+
71+
### M5: Validate & Tidy
72+
73+
- [x] **T5.1** — Full test suite passes (1,465 tests across 5 packages)
74+
- [x] **T5.2** — TypeScript build clean across all packages
75+
- [x] **T5.3** — All feature docs updated to match final implementation
76+
77+
## Dependencies & Sequencing
78+
79+
```
80+
T1.1 → T1.2
81+
T1.3 (independent)
82+
T2.1 → T2.2
83+
T3.1 → T3.2 → T3.3 → T3.4 (after T1 assets)
84+
T4.1 → T4.2 → T4.3 (after T2)
85+
T5.x after all above
86+
```
87+
88+
## Risks & Mitigation
89+
90+
| Risk | Likelihood | Mitigation |
91+
|---|---|---|
92+
| Claude Code version changes `PreToolUse` payload shape | Low | Defensive key reads; `session_id` confirmed present |
93+
| `~/.claude/settings.json` malformed on user's machine | Low | Try/catch; treat as `{}`; no destructive writes |
94+
| Existing setup tests broken by adding claude agent | Very low | Existing tests use `agents: ['codex']` or `agents: ['pi']`; new tests use `agents: ['claude']` |
95+
96+
## Progress Summary
97+
98+
**All tasks complete.** Implementation shipped: M1 hook script + assets, M2 agent-request store in `agent-manager`, M3 claude setup agent, M4 channel-runner agent-request polling. 1,465 tests pass across 5 packages. TypeScript build clean.
99+
100+
**Key scope changes from initial design:**
101+
- `Notification` hook event does not exist in Claude Code; pivoted to `PreToolUse` with matcher `Bash|Edit|Write|MultiEdit|NotebookEdit|AskUserQuestion`.
102+
- Agent-request store moved from CLI to `agent-manager` package (agent/session infrastructure).
103+
- PID file / `waitingFor` guard removed (Claude-specific, complicates multi-agent support).
104+
- `AskUserQuestion` rich formatting deferred; raw JSON forwarded for now.

0 commit comments

Comments
 (0)