|
| 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). |
0 commit comments