@scrylog/cli 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/dist/assets/highlights-eq9cgrbb.scm +604 -0
  2. package/dist/assets/highlights-ghv9g403.scm +205 -0
  3. package/dist/assets/highlights-hk7bwhj4.scm +284 -0
  4. package/dist/assets/highlights-r812a2qc.scm +150 -0
  5. package/dist/assets/highlights-x6tmsnaa.scm +115 -0
  6. package/dist/assets/injections-73j83es3.scm +27 -0
  7. package/dist/assets/parser.worker-xyhf83rf.js +4563 -0
  8. package/dist/assets/tree-sitter-3jzf13jk.wasm +0 -0
  9. package/dist/assets/tree-sitter-javascript-nd0q4pe9.wasm +0 -0
  10. package/dist/assets/tree-sitter-markdown-411r6y9b.wasm +0 -0
  11. package/dist/assets/tree-sitter-markdown_inline-j5349f42.wasm +0 -0
  12. package/dist/assets/tree-sitter-typescript-zxjzwt75.wasm +0 -0
  13. package/dist/assets/tree-sitter-zig-e78zbjpm.wasm +0 -0
  14. package/dist/cli/index.js +499 -0
  15. package/dist/cli/index.js.map +61 -0
  16. package/dist/daemon/index.js +670 -0
  17. package/dist/daemon/index.js.map +1475 -0
  18. package/dist/hooks/claude.js +6 -0
  19. package/dist/hooks/claude.js.map +11 -0
  20. package/dist/hooks/codex.js +10 -0
  21. package/dist/hooks/codex.js.map +11 -0
  22. package/dist/mcp/index.js +100 -0
  23. package/dist/mcp/index.js.map +231 -0
  24. package/dist/oc/index.js +21 -0
  25. package/dist/oc/index.js.map +10 -0
  26. package/package.json +16 -13
  27. package/src/api/docs/sessions.keys.ts +0 -6
  28. package/src/api/docs/sessions.ts +0 -82
  29. package/src/api/docs/system.keys.ts +0 -5
  30. package/src/api/docs/system.ts +0 -69
  31. package/src/api/docs/usage.keys.ts +0 -3
  32. package/src/api/docs/usage.ts +0 -24
  33. package/src/api/docs/webhooks.keys.ts +0 -5
  34. package/src/api/docs/webhooks.ts +0 -78
  35. package/src/api/index.ts +0 -18
  36. package/src/api/lib/auth.ts +0 -43
  37. package/src/api/lib/errors.ts +0 -28
  38. package/src/api/lib/route.ts +0 -18
  39. package/src/api/models/claude.ts +0 -4
  40. package/src/api/models/codex.ts +0 -4
  41. package/src/api/models/opencode.ts +0 -11
  42. package/src/api/routes/sessions.ts +0 -51
  43. package/src/api/routes/system.ts +0 -106
  44. package/src/api/routes/usage.ts +0 -15
  45. package/src/api/routes/webhooks/claude.ts +0 -149
  46. package/src/api/routes/webhooks/codex.ts +0 -175
  47. package/src/api/routes/webhooks/opencode.ts +0 -112
  48. package/src/api/routes.ts +0 -93
  49. package/src/api/schemas/common.ts +0 -29
  50. package/src/api/schemas/sessions.ts +0 -86
  51. package/src/api/schemas/usage.ts +0 -51
  52. package/src/api/schemas/webhooks/claude.ts +0 -32
  53. package/src/api/schemas/webhooks/codex.ts +0 -34
  54. package/src/api/schemas/webhooks/opencode.ts +0 -29
  55. package/src/api/services/claude-session.ts +0 -9
  56. package/src/api/services/codex-session.ts +0 -8
  57. package/src/api/services/opencode-session.ts +0 -73
  58. package/src/classifier.ts +0 -206
  59. package/src/cli/commands.ts +0 -714
  60. package/src/cli/index.ts +0 -18
  61. package/src/cli/program.ts +0 -175
  62. package/src/cli/prompt.ts +0 -44
  63. package/src/daemon/cli.ts +0 -27
  64. package/src/daemon/collectors/claude/README.md +0 -108
  65. package/src/daemon/collectors/claude/collector.ts +0 -423
  66. package/src/daemon/collectors/claude/discovery.ts +0 -127
  67. package/src/daemon/collectors/claude/hooks.ts +0 -181
  68. package/src/daemon/collectors/claude/index.ts +0 -8
  69. package/src/daemon/collectors/claude/jsonl.ts +0 -85
  70. package/src/daemon/collectors/claude/transcript.ts +0 -246
  71. package/src/daemon/collectors/codex/README.md +0 -147
  72. package/src/daemon/collectors/codex/collector.ts +0 -661
  73. package/src/daemon/collectors/codex/discovery.ts +0 -104
  74. package/src/daemon/collectors/codex/hooks.ts +0 -179
  75. package/src/daemon/collectors/codex/index.ts +0 -7
  76. package/src/daemon/collectors/codex/jsonl.ts +0 -108
  77. package/src/daemon/collectors/codex/transcript.ts +0 -299
  78. package/src/daemon/collectors/git.ts +0 -353
  79. package/src/daemon/collectors/herdr/collector.ts +0 -128
  80. package/src/daemon/collectors/herdr/index.ts +0 -2
  81. package/src/daemon/collectors/herdr/normalization.ts +0 -111
  82. package/src/daemon/collectors/opencode/README.md +0 -106
  83. package/src/daemon/collectors/opencode/collector.ts +0 -545
  84. package/src/daemon/collectors/opencode/discovery.ts +0 -257
  85. package/src/daemon/collectors/opencode/index.ts +0 -5
  86. package/src/daemon/collectors/opencode/session-builder.ts +0 -59
  87. package/src/daemon/collectors/opencode-db.ts +0 -294
  88. package/src/daemon/collectors/process.ts +0 -201
  89. package/src/daemon/collectors/tmux/README.md +0 -128
  90. package/src/daemon/collectors/tmux/collector.ts +0 -492
  91. package/src/daemon/collectors/tmux/enrichment.ts +0 -242
  92. package/src/daemon/collectors/tmux/index.ts +0 -4
  93. package/src/daemon/collectors/tmux/parse.ts +0 -128
  94. package/src/daemon/collectors/usage.ts +0 -259
  95. package/src/daemon/index.ts +0 -209
  96. package/src/daemon/scheduler.ts +0 -86
  97. package/src/daemon/store.ts +0 -630
  98. package/src/detect.ts +0 -143
  99. package/src/hooks/claude.ts +0 -596
  100. package/src/hooks/codex.ts +0 -517
  101. package/src/legacy/classifier.ts +0 -215
  102. package/src/legacy/detect.ts +0 -143
  103. package/src/mcp/client-server.ts +0 -21
  104. package/src/mcp/http-handler.ts +0 -126
  105. package/src/mcp/index.ts +0 -61
  106. package/src/mcp/resources/config-current.ts +0 -19
  107. package/src/mcp/resources/index.ts +0 -11
  108. package/src/mcp/resources/sessions-active.ts +0 -19
  109. package/src/mcp/resources/sessions-all.ts +0 -19
  110. package/src/mcp/schemas/sessions.ts +0 -3
  111. package/src/mcp/server.ts +0 -17
  112. package/src/mcp/services/api-adapter.ts +0 -48
  113. package/src/mcp/services/data-source.ts +0 -22
  114. package/src/mcp/services/store-adapter.ts +0 -40
  115. package/src/mcp/tools/get-active-sessions.ts +0 -16
  116. package/src/mcp/tools/get-session-children.ts +0 -24
  117. package/src/mcp/tools/get-session-messages.ts +0 -24
  118. package/src/mcp/tools/get-session.ts +0 -23
  119. package/src/mcp/tools/index.ts +0 -15
  120. package/src/mcp/tools/list-sessions.ts +0 -16
  121. package/src/oc/index.ts +0 -302
  122. package/src/service/manager.ts +0 -284
  123. package/src/shared/config.ts +0 -511
  124. package/src/shared/ipc.ts +0 -80
  125. package/src/shared/logger.ts +0 -248
  126. package/src/shared/paths.ts +0 -73
  127. package/src/shared/platform.ts +0 -110
  128. package/src/shared/session-exclusions.ts +0 -5
  129. package/src/shared/session-view.ts +0 -302
  130. package/src/shared/terminal-capabilities.ts +0 -130
  131. package/src/shared/types.ts +0 -330
  132. package/src/shared/utils.ts +0 -339
  133. package/src/shared/version.ts +0 -44
  134. package/src/tui/App.tsx +0 -240
  135. package/src/tui/client.ts +0 -163
  136. package/src/tui/components/BindingsModal.tsx +0 -82
  137. package/src/tui/components/DashboardHeader.tsx +0 -256
  138. package/src/tui/components/KeyBar.tsx +0 -67
  139. package/src/tui/components/SessionDetailModal.tsx +0 -169
  140. package/src/tui/components/SessionsView.tsx +0 -184
  141. package/src/tui/components/TabBar.tsx +0 -40
  142. package/src/tui/components/UsageSummaryPane.tsx +0 -272
  143. package/src/tui/components/UsageView.tsx +0 -242
  144. package/src/tui/components/tool-icons.ts +0 -24
  145. package/src/tui/index.tsx +0 -106
  146. package/src/tui/keybindings.ts +0 -49
  147. package/src/tui/model.ts +0 -295
  148. package/src/tui/state.ts +0 -77
  149. package/src/tui/theme.ts +0 -110
  150. package/src/types.ts +0 -113
  151. package/src/usage/README.md +0 -323
  152. package/src/usage/api.ts +0 -99
  153. package/src/usage/client.ts +0 -3
  154. package/src/usage/clients/anthropic-oauth-usage.ts +0 -258
  155. package/src/usage/clients/anthropic-web-usage.ts +0 -329
  156. package/src/usage/clients/claude-cli-probe.ts +0 -513
  157. package/src/usage/clients/codex-app-server.ts +0 -354
  158. package/src/usage/clients/codex-oauth-usage.ts +0 -240
  159. package/src/usage/clients/opencode-go-api.ts +0 -100
  160. package/src/usage/clients/opencode-go-usage.ts +0 -577
  161. package/src/usage/errors.ts +0 -33
  162. package/src/usage/index.ts +0 -20
  163. package/src/usage/local/opencode-go-local.ts +0 -194
  164. package/src/usage/mappers.ts +0 -282
  165. package/src/usage/planner.ts +0 -118
  166. package/src/usage/providers/claude.ts +0 -233
  167. package/src/usage/providers/codex.ts +0 -115
  168. package/src/usage/providers/opencode-go.ts +0 -115
  169. package/src/usage/resolver.ts +0 -4
  170. package/src/usage/resolvers/browser-cookies.ts +0 -808
  171. package/src/usage/resolvers/claude-auth.ts +0 -208
  172. package/src/usage/resolvers/claude-cli.ts +0 -24
  173. package/src/usage/resolvers/claude-desktop-auth.ts +0 -170
  174. package/src/usage/resolvers/claude-web.ts +0 -82
  175. package/src/usage/resolvers/codex-auth.ts +0 -174
  176. package/src/usage/resolvers/keychain-coordinator.ts +0 -397
  177. package/src/usage/resolvers/opencode-go-web.ts +0 -55
  178. package/src/usage/types.ts +0 -225
  179. package/src/usage/web-session-cache.ts +0 -37
  180. /package/{src/tui → dist/cli}/assets/providers/SOURCES.md +0 -0
  181. /package/{src/tui → dist/cli}/assets/providers/claude-terminal.png +0 -0
  182. /package/{src/tui → dist/cli}/assets/providers/claude-terminal.svg +0 -0
  183. /package/{src/tui → dist/cli}/assets/providers/claude.png +0 -0
  184. /package/{src/tui → dist/cli}/assets/providers/copilot.png +0 -0
  185. /package/{src/tui → dist/cli}/assets/providers/copilot.svg +0 -0
  186. /package/{src/tui → dist/cli}/assets/providers/openai-terminal.png +0 -0
  187. /package/{src/tui → dist/cli}/assets/providers/openai-terminal.svg +0 -0
  188. /package/{src/tui → dist/cli}/assets/providers/openai.png +0 -0
  189. /package/{src/tui → dist/cli}/assets/providers/opencode-terminal.png +0 -0
  190. /package/{src/tui → dist/cli}/assets/providers/opencode-terminal.svg +0 -0
  191. /package/{src/tui → dist/cli}/assets/providers/opencode.png +0 -0
  192. /package/{src/tui → dist/cli}/assets/providers/shell.png +0 -0
  193. /package/{src/tui → dist/cli}/assets/providers/shell.svg +0 -0
  194. /package/{src/tui → dist/cli}/assets/providers/unknown.png +0 -0
  195. /package/{src/tui → dist/cli}/assets/providers/unknown.svg +0 -0
@@ -1,596 +0,0 @@
1
- #!/usr/bin/env bun
2
- /**
3
- * scrylog-claude-hook — Claude Code lifecycle hook handler.
4
- *
5
- * Claude Code calls this binary at each lifecycle event (Stop, PreToolUse,
6
- * PostToolUse, Notification, SubagentStop) with a JSON payload on stdin.
7
- * This script writes a state file for the ClaudeCollector to pick up and,
8
- * when running inside tmux, sets the @claude-session pane option so the
9
- * TmuxCollector can link the pane to the Claude session.
10
- *
11
- * Configure in ~/.claude/settings.json via:
12
- * scrylog claude hooks install
13
- */
14
-
15
- import { writeFileSync, renameSync, readFileSync, existsSync, rmSync } from "node:fs";
16
- import { join, basename } from "node:path";
17
- import { spawnSync } from "node:child_process";
18
- import { getHooksDir, ensureHooksDirSafe } from "../shared/platform";
19
- import type { SessionState } from "../shared/types";
20
-
21
- type AttentionKind = "permission" | "question" | "turn" | "none";
22
- type ToolResultStatus = "started" | "completed" | "error" | "blocked" | "denied" | "unknown";
23
-
24
- // ── Hook payload ──────────────────────────────────────────────────────────────
25
-
26
- interface ClaudeHookPayload {
27
- session_id: string;
28
- transcript_path?: string;
29
- cwd?: string;
30
- permission_mode?: string;
31
- hook_event_name?: string;
32
- source?: string;
33
- model?: string;
34
- prompt?: string;
35
- stop_hook_active?: boolean;
36
- last_assistant_message?: string;
37
- // PreToolUse / PostToolUse
38
- tool_name?: string;
39
- tool_input?: Record<string, unknown>;
40
- tool_response?: unknown;
41
- tool_use_id?: string;
42
- duration_ms?: number;
43
- error?: string;
44
- error_details?: string;
45
- is_interrupt?: boolean;
46
- reason?: string;
47
- old_cwd?: string;
48
- new_cwd?: string;
49
- permission_suggestions?: unknown[];
50
- tool_calls?: Array<{
51
- tool_name?: string;
52
- tool_input?: Record<string, unknown>;
53
- tool_use_id?: string;
54
- tool_response?: unknown;
55
- }>;
56
- // Notification / async events
57
- message?: string;
58
- title?: string;
59
- // Subagents
60
- agent_id?: string;
61
- agent_type?: string;
62
- agent_transcript_path?: string;
63
- subagent_session_id?: string;
64
- subagent_transcript_path?: string;
65
- }
66
-
67
- interface DerivedHookState {
68
- state: SessionState;
69
- hasAttention: boolean;
70
- attentionKind: AttentionKind;
71
- activeTool?: string;
72
- toolName?: string;
73
- toolInputSummary?: string;
74
- toolResultStatus?: ToolResultStatus;
75
- summary?: string;
76
- }
77
-
78
- // ── Config resolution ─────────────────────────────────────────────────────────
79
-
80
- function resolveHooksDir(): string {
81
- const envConfig = process.env["SCRYLOG_CONFIG"];
82
- if (envConfig && existsSync(envConfig)) {
83
- try {
84
- const raw = JSON.parse(readFileSync(envConfig, "utf8")) as Record<string, unknown>;
85
- const claude = raw["claude"] as Record<string, unknown> | undefined;
86
- if (typeof claude?.["hooksDir"] === "string") return claude["hooksDir"];
87
- } catch {
88
- // fall through to default
89
- }
90
- }
91
- return getHooksDir("claude-hooks");
92
- }
93
-
94
- function resolveDaemonPort(): number {
95
- const envConfig = process.env["SCRYLOG_CONFIG"];
96
- if (envConfig && existsSync(envConfig)) {
97
- try {
98
- const raw = JSON.parse(readFileSync(envConfig, "utf8")) as Record<string, unknown>;
99
- const api = raw["api"] as Record<string, unknown> | undefined;
100
- if (typeof api?.["port"] === "number") return api["port"] as number;
101
- } catch {
102
- // fall through to default
103
- }
104
- }
105
- return 7788;
106
- }
107
-
108
- async function tryHttpDelivery(payload: HookStateFile & { sessionId: string }): Promise<boolean> {
109
- try {
110
- const port = resolveDaemonPort();
111
- const res = await fetch(`http://127.0.0.1:${port}/api/webhook/claude`, {
112
- method: "POST",
113
- headers: { "Content-Type": "application/json" },
114
- body: JSON.stringify(payload),
115
- signal: AbortSignal.timeout(1500),
116
- });
117
- return res.ok;
118
- } catch {
119
- return false;
120
- }
121
- }
122
-
123
- // ── Transcript inspection ─────────────────────────────────────────────────────
124
-
125
- function inferPermissionModeFromTranscript(transcriptPath?: string): string | undefined {
126
- if (!transcriptPath) return undefined;
127
- try {
128
- const content = readFileSync(transcriptPath, "utf8");
129
- const lines = content.split(/\r?\n/).filter(Boolean);
130
- for (let i = lines.length - 1; i >= 0; i--) {
131
- let entry: Record<string, unknown>;
132
- try {
133
- entry = JSON.parse(lines[i]!) as Record<string, unknown>;
134
- } catch {
135
- continue;
136
- }
137
- if (entry["type"] !== "permission-mode") continue;
138
- const mode = entry["permissionMode"];
139
- if (typeof mode === "string" && mode.length > 0) return mode;
140
- }
141
- } catch {
142
- // Ignore transcript read issues
143
- }
144
- return undefined;
145
- }
146
-
147
- function summarizeToolInput(toolName?: string, input?: Record<string, unknown>): string | undefined {
148
- if (!toolName) return undefined;
149
- const command = typeof input?.["command"] === "string" ? input["command"].slice(0, 120) : undefined;
150
- if (command) return command;
151
- const filePath = typeof input?.["file_path"] === "string" ? input["file_path"] : undefined;
152
- if (filePath) return filePath;
153
- const description = typeof input?.["description"] === "string" ? input["description"] : undefined;
154
- if (description) return description.slice(0, 120);
155
- return undefined;
156
- }
157
-
158
- function summarizeText(text?: string): string | undefined {
159
- if (!text) return undefined;
160
- const first = text.trim().split("\n")[0] ?? "";
161
- return first.length > 0 ? first.slice(0, 120) : undefined;
162
- }
163
-
164
- function isQuestion(text?: string): boolean {
165
- if (!text) return false;
166
- const trimmed = text.trim();
167
- return /\?/.test(trimmed) || /^(would you|do you|can you|should i|which|what|how|please confirm|shall i|want me to)/i.test(trimmed);
168
- }
169
-
170
- function isInterruptedRequestText(text: string): boolean {
171
- return /^\[Request interrupted by user(?: for tool use)?\]$/i.test(text.trim());
172
- }
173
-
174
- function classifyAttention(message?: string, title?: string): AttentionKind {
175
- const text = `${title ?? ""} ${message ?? ""}`.trim();
176
- if (!text) return "turn";
177
- if (/(approval|approve|permission|confirm|proceed|allow)/i.test(text)) return "permission";
178
- if (/[?]/.test(text) || /^(would you|do you|can you|should i|which|what|how|shall i|want me to)/i.test(text)) {
179
- return "question";
180
- }
181
- return "turn";
182
- }
183
-
184
- function inferStopState(payload: ClaudeHookPayload): SessionState {
185
- if (isQuestion(payload.last_assistant_message)) return "waiting-input";
186
- return "idle";
187
- }
188
-
189
- // ── State derivation ──────────────────────────────────────────────────────────
190
-
191
- interface PreviousState {
192
- state?: SessionState;
193
- hasAttention?: boolean;
194
- attentionKind?: AttentionKind;
195
- }
196
-
197
- function deriveHookState(event: string, payload: ClaudeHookPayload, previous?: PreviousState | null): DerivedHookState {
198
- const toolInputSummary = summarizeToolInput(payload.tool_name, payload.tool_input);
199
- switch (event) {
200
- case "SessionStart":
201
- return {
202
- state: "idle",
203
- hasAttention: false,
204
- attentionKind: "none",
205
- summary: payload.source ? `Claude session ${payload.source}` : "Claude session started",
206
- };
207
- case "UserPromptSubmit":
208
- return {
209
- state: "working",
210
- hasAttention: false,
211
- attentionKind: "none",
212
- summary: summarizeText(payload.prompt) ?? "Claude is working",
213
- };
214
- case "PreToolUse":
215
- return {
216
- state: "working",
217
- hasAttention: false,
218
- attentionKind: "none",
219
- activeTool: payload.tool_name,
220
- toolName: payload.tool_name,
221
- toolInputSummary,
222
- toolResultStatus: "started",
223
- summary: payload.tool_name ? `Using ${payload.tool_name}${toolInputSummary ? `: ${toolInputSummary}` : ""}` : undefined,
224
- };
225
- case "PermissionRequest":
226
- return {
227
- state: "waiting-input",
228
- hasAttention: true,
229
- attentionKind: "permission",
230
- activeTool: payload.tool_name,
231
- toolName: payload.tool_name,
232
- toolInputSummary,
233
- toolResultStatus: "blocked",
234
- summary: payload.tool_name ? `Permission required for ${payload.tool_name}${toolInputSummary ? `: ${toolInputSummary}` : ""}` : "Permission required",
235
- };
236
- case "PermissionDenied":
237
- return {
238
- state: "working",
239
- hasAttention: false,
240
- attentionKind: "none",
241
- activeTool: payload.tool_name,
242
- toolName: payload.tool_name,
243
- toolInputSummary,
244
- toolResultStatus: "denied",
245
- summary: payload.reason?.slice(0, 120) ?? (payload.tool_name ? `Permission denied for ${payload.tool_name}` : "Permission denied"),
246
- };
247
- case "PostToolUse":
248
- return {
249
- state: "working",
250
- hasAttention: false,
251
- attentionKind: "none",
252
- activeTool: payload.tool_name,
253
- toolName: payload.tool_name,
254
- toolInputSummary,
255
- toolResultStatus: typeof payload.tool_response === "object" && payload.tool_response !== null && "is_error" in (payload.tool_response as Record<string, unknown>)
256
- ? ((payload.tool_response as Record<string, unknown>)["is_error"] === true ? "error" : "completed")
257
- : "completed",
258
- summary: payload.tool_name ? `Using ${payload.tool_name}${toolInputSummary ? `: ${toolInputSummary}` : ""}` : undefined,
259
- };
260
- case "PostToolUseFailure":
261
- return {
262
- state: payload.is_interrupt ? "idle" : "working",
263
- hasAttention: false,
264
- attentionKind: "none",
265
- activeTool: payload.tool_name,
266
- toolName: payload.tool_name,
267
- toolInputSummary,
268
- toolResultStatus: "error",
269
- summary: payload.error?.slice(0, 120) ?? (payload.tool_name ? `Failed ${payload.tool_name}` : "Tool failed"),
270
- };
271
- case "PostToolBatch":
272
- return {
273
- state: "working",
274
- hasAttention: false,
275
- attentionKind: "none",
276
- summary: "Processing tool results",
277
- };
278
- case "Stop": {
279
- const state = inferStopState(payload);
280
- return {
281
- state,
282
- hasAttention: state === "waiting-input",
283
- attentionKind: state === "waiting-input" ? "question" : "none",
284
- summary: summarizeText(payload.last_assistant_message),
285
- };
286
- }
287
- case "StopFailure":
288
- return {
289
- state: "error",
290
- hasAttention: true,
291
- attentionKind: "turn",
292
- summary: summarizeText(payload.last_assistant_message) ?? payload.error_details?.slice(0, 120) ?? payload.error?.slice(0, 120),
293
- };
294
- case "CwdChanged":
295
- return {
296
- state: previous?.state ?? "idle",
297
- hasAttention: previous?.hasAttention ?? false,
298
- attentionKind: previous?.attentionKind ?? "none",
299
- };
300
- case "SubagentStart":
301
- return {
302
- state: "working",
303
- hasAttention: false,
304
- attentionKind: "none",
305
- summary: payload.agent_type ? `Subagent ${payload.agent_type}` : "Subagent started",
306
- };
307
- case "SubagentStop":
308
- return {
309
- state: "idle",
310
- hasAttention: false,
311
- attentionKind: "none",
312
- summary: summarizeText(payload.last_assistant_message),
313
- };
314
- case "SessionEnd":
315
- return {
316
- state: "idle",
317
- hasAttention: false,
318
- attentionKind: "none",
319
- summary: payload.reason ? `Claude session ended: ${payload.reason}` : "Claude session ended",
320
- };
321
- case "Notification":
322
- return {
323
- state: previous?.state ?? "idle",
324
- hasAttention: true,
325
- attentionKind: classifyAttention(payload.message, payload.title),
326
- summary: summarizeText(payload.message ?? payload.title),
327
- };
328
- default:
329
- return {
330
- state: previous?.state ?? "idle",
331
- hasAttention: previous?.hasAttention ?? false,
332
- attentionKind: previous?.attentionKind ?? "none",
333
- };
334
- }
335
- }
336
-
337
- function deriveSummary(event: string, payload: ClaudeHookPayload): string | undefined {
338
- if (event === "UserPromptSubmit" && payload.prompt) {
339
- return summarizeText(payload.prompt);
340
- }
341
- if (event === "SessionStart" && payload.source) {
342
- return `Claude session ${payload.source}`;
343
- }
344
- if (event === "PermissionRequest" && payload.tool_name) {
345
- const target = summarizeToolInput(payload.tool_name, payload.tool_input);
346
- return `Permission required for ${payload.tool_name}${target ? `: ${target}` : ""}`;
347
- }
348
- if (event === "PermissionDenied") {
349
- return payload.reason?.slice(0, 120);
350
- }
351
- if ((event === "PreToolUse" || event === "PostToolUse") && payload.tool_name) {
352
- const cmd = (payload.tool_input?.["command"] as string | undefined)?.slice(0, 60);
353
- return cmd ? `Using ${payload.tool_name}: ${cmd}` : `Using ${payload.tool_name}`;
354
- }
355
- if (event === "PostToolUseFailure") {
356
- return payload.error?.slice(0, 120);
357
- }
358
- if (event === "Stop" || event === "StopFailure" || event === "SubagentStop") {
359
- return summarizeText(payload.last_assistant_message);
360
- }
361
- if (event === "SessionEnd" && payload.reason) {
362
- return `Claude session ended: ${payload.reason}`;
363
- }
364
- return undefined;
365
- }
366
-
367
- // ── Tmux integration ──────────────────────────────────────────────────────────
368
-
369
- function setTmuxPaneOption(sessionId: string): void {
370
- const tmuxPane = process.env["TMUX_PANE"];
371
- if (!tmuxPane) return;
372
-
373
- const result = spawnSync("tmux", ["set-option", "-p", "-t", tmuxPane, "@claude-session", sessionId], {
374
- stdio: "ignore",
375
- timeout: 2000,
376
- });
377
-
378
- if (result.error || result.status !== 0) {
379
- // Non-fatal — tmux may not be available or the pane might have closed
380
- }
381
- }
382
-
383
- function clearTmuxPaneOption(): void {
384
- const tmuxPane = process.env["TMUX_PANE"];
385
- if (!tmuxPane) return;
386
-
387
- spawnSync("tmux", ["set-option", "-up", "-t", tmuxPane, "@claude-session"], {
388
- stdio: "ignore",
389
- timeout: 2000,
390
- });
391
- }
392
-
393
- // ── File writing ──────────────────────────────────────────────────────────────
394
-
395
- interface HookStateFile {
396
- eventType: string;
397
- eventTime: number;
398
- hookSeq: number;
399
- state: SessionState;
400
- hasAttention: boolean;
401
- attentionKind: AttentionKind;
402
- summary?: string;
403
- activeTool?: string;
404
- toolName?: string;
405
- toolInputSummary?: string;
406
- toolResultStatus?: ToolResultStatus;
407
- permissionMode?: string;
408
- startSource?: string;
409
- endReason?: string;
410
- errorType?: string;
411
- agentId?: string;
412
- agentType?: string;
413
- transcriptPath?: string;
414
- currentPath?: string;
415
- lastActivity: number;
416
- parentSessionId?: string;
417
- detectionSource: "claude-hook";
418
- }
419
-
420
- function readExistingHookState(hooksDir: string, sessionId: string): HookStateFile | null {
421
- const path = join(hooksDir, `${sessionId}.json`);
422
- if (!existsSync(path)) return null;
423
- try {
424
- return JSON.parse(readFileSync(path, "utf8")) as HookStateFile;
425
- } catch {
426
- return null;
427
- }
428
- }
429
-
430
- function writeHookFile(hooksDir: string, sessionId: string, data: HookStateFile): void {
431
- ensureHooksDirSafe(hooksDir);
432
- const targetPath = join(hooksDir, `${sessionId}.json`);
433
- const tmpPath = join(hooksDir, `${sessionId}.json.tmp`);
434
- writeFileSync(tmpPath, JSON.stringify(data), "utf8");
435
- try {
436
- renameSync(tmpPath, targetPath);
437
- } catch {
438
- writeFileSync(targetPath, JSON.stringify(data), "utf8");
439
- }
440
- }
441
-
442
- // ── Main ──────────────────────────────────────────────────────────────────────
443
-
444
- async function main(): Promise<void> {
445
- let raw = "";
446
- for await (const chunk of Bun.stdin.stream()) {
447
- raw += new TextDecoder().decode(chunk);
448
- }
449
-
450
- let payload: ClaudeHookPayload;
451
- try {
452
- payload = JSON.parse(raw) as ClaudeHookPayload;
453
- } catch {
454
- process.exit(0); // Malformed input — exit cleanly so Claude Code is not disrupted
455
- }
456
-
457
- const event = payload.hook_event_name ?? "";
458
- const sessionId = payload.session_id;
459
- if (!sessionId) process.exit(0);
460
-
461
- const hooksDir = resolveHooksDir();
462
- const now = Date.now();
463
-
464
- if (event === "SessionEnd") {
465
- await tryHttpDelivery({
466
- sessionId,
467
- eventType: event,
468
- eventTime: now,
469
- hookSeq: 0,
470
- state: "idle",
471
- hasAttention: false,
472
- attentionKind: "none",
473
- summary: deriveSummary(event, payload),
474
- ...(payload.reason ? { endReason: payload.reason } : {}),
475
- ...(payload.transcript_path ? { transcriptPath: payload.transcript_path } : {}),
476
- currentPath: payload.cwd,
477
- lastActivity: now,
478
- detectionSource: "claude-hook",
479
- });
480
- try {
481
- rmSync(join(hooksDir, `${sessionId}.json`), { force: true });
482
- } catch {
483
- // Ignore cleanup issues
484
- }
485
- clearTmuxPaneOption();
486
- process.exit(0);
487
- }
488
-
489
- if (event === "SubagentStart" || event === "SubagentStop") {
490
- const subTranscriptPath = payload.agent_transcript_path ?? payload.subagent_transcript_path;
491
- const subId = payload.agent_id ?? payload.subagent_session_id ?? (subTranscriptPath ? basename(subTranscriptPath, ".jsonl") : undefined);
492
-
493
- if (subId) {
494
- const previous = readExistingHookState(hooksDir, subId);
495
- const derived = deriveHookState(event, payload, previous);
496
- const subBaseSeq = previous?.hookSeq ?? 0;
497
- const subNowMs = Math.floor(Date.now() / 100);
498
- const subHookSeq = Math.max(subBaseSeq + 1, subNowMs);
499
- const subData: HookStateFile = {
500
- eventType: event,
501
- eventTime: now,
502
- hookSeq: subHookSeq,
503
- state: derived.state,
504
- hasAttention: derived.hasAttention,
505
- attentionKind: derived.attentionKind,
506
- ...(derived.summary ?? deriveSummary(event, payload) ? { summary: (derived.summary ?? deriveSummary(event, payload)) } : {}),
507
- ...(payload.permission_mode ? { permissionMode: payload.permission_mode } : {}),
508
- ...(payload.agent_id ? { agentId: payload.agent_id } : {}),
509
- ...(payload.agent_type ? { agentType: payload.agent_type } : {}),
510
- ...(subTranscriptPath ? { transcriptPath: subTranscriptPath } : {}),
511
- currentPath: payload.cwd,
512
- lastActivity: now,
513
- parentSessionId: `claude:${sessionId}`,
514
- detectionSource: "claude-hook",
515
- };
516
- writeHookFile(hooksDir, subId, subData);
517
- await tryHttpDelivery({ sessionId: subId, ...subData });
518
- }
519
-
520
- if (event === "SubagentStop") {
521
- // Update the parent session metadata (summary, lastActivity) but preserve
522
- // its state — SubagentStop is a sub-agent event, not a parent state change.
523
- // deriveHookState("SubagentStop") returns "idle" which would incorrectly
524
- // set the parent to idle while it may still be working.
525
- const parentPrevious = readExistingHookState(hooksDir, sessionId);
526
- const parentBaseSeq = parentPrevious?.hookSeq ?? 0;
527
- const parentNowMs = Math.floor(Date.now() / 100);
528
- const parentHookSeq = Math.max(parentBaseSeq + 1, parentNowMs);
529
- const parentSummary = deriveSummary("SubagentStop", payload);
530
- const parentData: HookStateFile = {
531
- eventType: "SubagentStop",
532
- eventTime: now,
533
- hookSeq: parentHookSeq,
534
- state: parentPrevious?.state ?? "working",
535
- hasAttention: parentPrevious?.hasAttention ?? false,
536
- attentionKind: parentPrevious?.attentionKind ?? "none",
537
- ...(parentSummary ? { summary: parentSummary } : {}),
538
- currentPath: payload.new_cwd ?? payload.cwd,
539
- lastActivity: now,
540
- detectionSource: "claude-hook",
541
- };
542
- writeHookFile(hooksDir, sessionId, parentData);
543
- await tryHttpDelivery({ sessionId, ...parentData });
544
- // Ensure tmux pane option is refreshed so the parent session remains linked
545
- setTmuxPaneOption(sessionId);
546
- process.exit(0);
547
- }
548
- }
549
-
550
- // For all other events: write state for the current session
551
- const previous = readExistingHookState(hooksDir, sessionId);
552
- const derived = deriveHookState(event, payload, previous);
553
- const summary = derived.summary ?? deriveSummary(event, payload) ?? previous?.summary;
554
-
555
- // Use a timestamp-based hookSeq to avoid collisions when multiple hooks
556
- // fire concurrently. The previous seq is used as a floor to ensure monotonicity.
557
- const baseSeq = previous?.hookSeq ?? 0;
558
- const nowMs = Math.floor(Date.now() / 100);
559
- const hookSeq = Math.max(baseSeq + 1, nowMs);
560
-
561
- const hookData: HookStateFile = {
562
- eventType: event,
563
- eventTime: now,
564
- hookSeq,
565
- state: derived.state,
566
- hasAttention: derived.hasAttention,
567
- attentionKind: derived.attentionKind,
568
- ...(summary ? { summary } : {}),
569
- ...(derived.activeTool ? { activeTool: derived.activeTool } : {}),
570
- ...(derived.toolName ? { toolName: derived.toolName } : {}),
571
- ...(derived.toolInputSummary ? { toolInputSummary: derived.toolInputSummary } : {}),
572
- ...(derived.toolResultStatus ? { toolResultStatus: derived.toolResultStatus } : {}),
573
- ...(payload.permission_mode ? { permissionMode: payload.permission_mode } : {}),
574
- ...(payload.source ? { startSource: payload.source } : {}),
575
- ...(payload.reason ? { endReason: payload.reason } : {}),
576
- ...(payload.error ? { errorType: payload.error } : {}),
577
- ...(payload.agent_id ? { agentId: payload.agent_id } : {}),
578
- ...(payload.agent_type ? { agentType: payload.agent_type } : {}),
579
- ...(payload.transcript_path ? { transcriptPath: payload.transcript_path } : {}),
580
- currentPath: payload.new_cwd ?? payload.cwd,
581
- lastActivity: now,
582
- detectionSource: "claude-hook",
583
- };
584
-
585
- writeHookFile(hooksDir, sessionId, hookData);
586
- await tryHttpDelivery({ sessionId, ...hookData });
587
-
588
- // Update tmux binding for the main session, especially on SessionStart or resume.
589
- if (event === "SessionStart" || event === "UserPromptSubmit" || event === "PermissionRequest" || event === "PreToolUse") {
590
- setTmuxPaneOption(sessionId);
591
- }
592
-
593
- process.exit(0);
594
- }
595
-
596
- main().catch(() => process.exit(0));