dsh-context-mode 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/LICENSING.md +37 -0
  2. package/README.md +40 -14
  3. package/lib/types/cjk.d.ts +54 -0
  4. package/lib/types/cjk.d.ts.map +1 -0
  5. package/lib/types/cjk.js +64 -0
  6. package/lib/types/index.d.ts.map +1 -1
  7. package/lib/types/index.js +71 -22
  8. package/lib/types/output-containment.d.ts +35 -0
  9. package/lib/types/output-containment.d.ts.map +1 -0
  10. package/lib/types/output-containment.js +103 -0
  11. package/lib/types/routing.d.ts +3 -1
  12. package/lib/types/routing.d.ts.map +1 -1
  13. package/lib/types/routing.js +81 -6
  14. package/lib/types/session-memory.d.ts.map +1 -1
  15. package/lib/types/session-memory.js +14 -3
  16. package/package.json +9 -5
  17. package/skills/context-mode/SKILL.md +104 -11
  18. package/vendor/context-mode/LICENSE +94 -0
  19. package/vendor/context-mode/server.bundle.mjs +1126 -0
  20. package/vendor/context-mode/src/cli.ts +2040 -0
  21. package/vendor/context-mode/src/db-base.ts +617 -0
  22. package/vendor/context-mode/src/executor.ts +785 -0
  23. package/vendor/context-mode/src/exit-classify.ts +33 -0
  24. package/vendor/context-mode/src/fetch-cache.ts +15 -0
  25. package/vendor/context-mode/src/lifecycle.ts +305 -0
  26. package/vendor/context-mode/src/platform/client-map.ts +45 -0
  27. package/vendor/context-mode/src/platform/detect.ts +645 -0
  28. package/vendor/context-mode/src/platform/dsh.ts +206 -0
  29. package/vendor/context-mode/src/platform/types.ts +503 -0
  30. package/vendor/context-mode/src/runPool.ts +81 -0
  31. package/vendor/context-mode/src/runtime.ts +765 -0
  32. package/vendor/context-mode/src/search/auto-memory.ts +200 -0
  33. package/vendor/context-mode/src/search/ctx-search-schema.ts +143 -0
  34. package/vendor/context-mode/src/search/flood-guard.ts +111 -0
  35. package/vendor/context-mode/src/search/unified.ts +176 -0
  36. package/vendor/context-mode/src/security.ts +889 -0
  37. package/vendor/context-mode/src/server.ts +4991 -0
  38. package/vendor/context-mode/src/session/analytics.ts +3085 -0
  39. package/vendor/context-mode/src/session/db.ts +1726 -0
  40. package/vendor/context-mode/src/session/error-classifier.ts +392 -0
  41. package/vendor/context-mode/src/session/event-emit.ts +132 -0
  42. package/vendor/context-mode/src/session/extract.ts +2958 -0
  43. package/vendor/context-mode/src/session/index.ts +130 -0
  44. package/vendor/context-mode/src/session/model-prices.json +429 -0
  45. package/vendor/context-mode/src/session/persist-tool-calls.ts +128 -0
  46. package/vendor/context-mode/src/session/pricing.ts +191 -0
  47. package/vendor/context-mode/src/session/project-attribution.ts +309 -0
  48. package/vendor/context-mode/src/session/purge.ts +338 -0
  49. package/vendor/context-mode/src/session/retrieval-marker.ts +65 -0
  50. package/vendor/context-mode/src/session/snapshot.ts +577 -0
  51. package/vendor/context-mode/src/store-directory.ts +290 -0
  52. package/vendor/context-mode/src/store.ts +2071 -0
  53. package/vendor/context-mode/src/truncate.ts +154 -0
  54. package/vendor/context-mode/src/types.ts +147 -0
  55. package/vendor/context-mode/src/util/claude-config.ts +95 -0
  56. package/vendor/context-mode/src/util/hook-config.ts +78 -0
  57. package/vendor/context-mode/src/util/jsonc.ts +70 -0
  58. package/vendor/context-mode/src/util/plugin-cache-integrity.ts +167 -0
  59. package/vendor/context-mode/src/util/project-dir.ts +347 -0
  60. package/vendor/context-mode/src/util/sibling-mcp.ts +228 -0
@@ -0,0 +1,2958 @@
1
+ /**
2
+ * Session event extraction — pure functions, zero side effects.
3
+ * Extracts structured events from Claude Code tool calls and user messages.
4
+ *
5
+ * All 13 event categories as specified in PRD Section 3.
6
+ */
7
+
8
+ import {
9
+ lookupPrice as catalogLookupPrice,
10
+ computeCostUsd as catalogComputeCostUsd,
11
+ } from "./pricing.js";
12
+
13
+ // ── Public interfaces ──────────────────────────────────────────────────────
14
+
15
+ export interface SessionEvent {
16
+ /** e.g. "file_read", "file_write", "cwd", "error_tool", "git", "task",
17
+ * "decision", "rule", "env", "role", "skill", "subagent", "data", "intent" */
18
+ type: string;
19
+ /** e.g. "file", "cwd", "error", "git", "task", "decision",
20
+ * "rule", "env", "role", "skill", "subagent", "data", "intent" */
21
+ category: string;
22
+ /** Extracted payload — full data, no truncation */
23
+ data: string;
24
+ /** 1=critical (rules, files, tasks) … 5=low */
25
+ priority: number;
26
+ /**
27
+ * Optional — bytes context-mode prevented from entering the model context
28
+ * window for this event. Currently populated by external_ref when a
29
+ * ctx_fetch_and_index tool_response carries the
30
+ * `Fetched and indexed N sections (XKB)` preamble.
31
+ */
32
+ bytes_avoided?: number;
33
+ /**
34
+ * Optional — bytes the model PAID to ACCESS kept-out content for this event:
35
+ * the tool_response byte length of a `ctx_search` / `ctx_fetch_and_index`
36
+ * call. This is the OTHER half of the with/without ratio (bytes_avoided is
37
+ * the kept-out half). Sandbox compute (ctx_execute/batch/file) is work-output
38
+ * and is excluded. Present only when the call is a retrieval call and its
39
+ * tool_response is non-empty.
40
+ */
41
+ bytes_retrieved?: number;
42
+ /**
43
+ * Optional structured cost/usage fields (Wave 2b). Emitted by
44
+ * extractAgentUsage alongside the colon-string `data` so the forward
45
+ * envelope can spread them to the platform as typed columns instead of an
46
+ * opaque blob. Present only when the source signal is present; cost_usd is
47
+ * omitted on a price miss or a zero-token turn.
48
+ */
49
+ model_id?: string;
50
+ input_tokens?: number;
51
+ output_tokens?: number;
52
+ cache_read_tokens?: number;
53
+ cache_creation_tokens?: number;
54
+ cost_usd?: number;
55
+ /**
56
+ * "task_cumulative" on agent_usage events whose tokens are a Task sub-agent's
57
+ * usage SUMMED across its whole run (not one turn). The platform buckets these
58
+ * as lifetime spend and never prices them per-turn — see
59
+ * docs/handoff/cumulative-cost-bug.md.
60
+ */
61
+ usage_scope?: string;
62
+ }
63
+
64
+ export interface ToolCall {
65
+ toolName: string;
66
+ toolInput: Record<string, unknown>;
67
+ toolResponse?: string;
68
+ isError?: boolean;
69
+ }
70
+
71
+ /**
72
+ * Hook input shape as received from Claude Code PostToolUse hook stdin.
73
+ * Uses snake_case to match the raw hook JSON.
74
+ */
75
+ export interface HookInput {
76
+ tool_name: string;
77
+ tool_input: Record<string, unknown>;
78
+ tool_response?: string;
79
+ /** Optional structured output from the tool (may carry isError) */
80
+ tool_output?: { isError?: boolean; is_error?: boolean };
81
+ }
82
+
83
+ // ── Internal helpers ───────────────────────────────────────────────────────
84
+
85
+ /** Null-safe string coercion — no truncation, preserves full data. */
86
+ function safeString(value: string | null | undefined): string {
87
+ if (value == null) return "";
88
+ return String(value);
89
+ }
90
+
91
+ /** Serialise an unknown value to a string — no truncation. */
92
+ function safeStringAny(value: unknown): string {
93
+ if (value == null) return "";
94
+ return typeof value === "string" ? value : JSON.stringify(value);
95
+ }
96
+
97
+ function isToolError(input: HookInput): boolean {
98
+ const response = String(input.tool_response ?? "");
99
+ // PreToolUse rewrites curl/wget/inline-HTTP/WebFetch commands into
100
+ // echo "context-mode: <guidance text including 'retry', 'fails', 'error'>"
101
+ // The user-facing copy legitimately mentions failure modes ("retry if it
102
+ // fails with a transient DNS error"), but those words must NOT classify
103
+ // our OWN guidance message as a tool error or it gets captured into
104
+ // session_resume and surfaces as a fake error in the next chat.
105
+ // We check BOTH sides because:
106
+ // - real shell run → response starts with `context-mode:` (echo stdout)
107
+ // - test/captured-output path → response is the raw command itself
108
+ // (`echo "context-mode: …"`), so we also match the command shape
109
+ const command = String(input.tool_input?.command ?? "");
110
+ if (
111
+ response.startsWith("context-mode:") ||
112
+ command.startsWith('echo "context-mode:') ||
113
+ command.startsWith("echo 'context-mode:")
114
+ ) {
115
+ return false;
116
+ }
117
+ const isErrorFlag = input.tool_output?.isError === true || input.tool_output?.is_error === true;
118
+ const isBashError =
119
+ input.tool_name === "Bash" &&
120
+ /exit code [1-9]|error:|Error:|FAIL|failed/i.test(response);
121
+ return isBashError || isErrorFlag;
122
+ }
123
+
124
+ interface ApplyPatchTarget {
125
+ path: string;
126
+ type: "file_write" | "file_edit";
127
+ }
128
+
129
+ function extractApplyPatchTargets(command: string): ApplyPatchTarget[] {
130
+ if (!command) return [];
131
+
132
+ const targets: ApplyPatchTarget[] = [];
133
+ for (const line of command.split(/\r?\n/)) {
134
+ if (line.startsWith("*** Add File: ")) {
135
+ targets.push({ path: line.slice(14).trim(), type: "file_write" });
136
+ continue;
137
+ }
138
+ if (line.startsWith("*** Update File: ")) {
139
+ targets.push({ path: line.slice(17).trim(), type: "file_edit" });
140
+ continue;
141
+ }
142
+ if (line.startsWith("*** Delete File: ")) {
143
+ targets.push({ path: line.slice(17).trim(), type: "file_edit" });
144
+ continue;
145
+ }
146
+ if (line.startsWith("*** Move to: ")) {
147
+ targets.push({ path: line.slice(13).trim(), type: "file_edit" });
148
+ }
149
+ }
150
+
151
+ const seen = new Set<string>();
152
+ return targets.filter((target) => {
153
+ if (!target.path) return false;
154
+ const key = `${target.type}:${target.path}`;
155
+ if (seen.has(key)) return false;
156
+ seen.add(key);
157
+ return true;
158
+ });
159
+ }
160
+
161
+ function isPlanFilePath(filePath: string): boolean {
162
+ return /(?:^|[/\\])\.claude[/\\]plans[/\\]/.test(filePath);
163
+ }
164
+
165
+ // ── Category extractors ────────────────────────────────────────────────────
166
+
167
+ /**
168
+ * Category 1 & 2: rule + file
169
+ *
170
+ * CLAUDE.md / .claude/ reads → emit both a "rule" event (priority 1) AND a
171
+ * "file_read" event (priority 1) because the file is being actively accessed.
172
+ *
173
+ * Other Edit/Write/Read tool calls → emit a file_edit / file_write / file_read
174
+ * event (priority 1).
175
+ */
176
+ function extractFileAndRule(input: HookInput): SessionEvent[] {
177
+ const { tool_name, tool_input, tool_response } = input;
178
+ const events: SessionEvent[] = [];
179
+
180
+ if (tool_name === "Read") {
181
+ const filePath = String(tool_input["file_path"] ?? "");
182
+
183
+ // Rule detection — covers every supported platform's instruction
184
+ // file convention plus per-user memory directories. Hardcoding here
185
+ // (instead of dispatching through the adapter) keeps extract.ts
186
+ // pure / sync / hot-path-safe — the tradeoff is that adding a new
187
+ // platform requires updating this regex.
188
+ //
189
+ // Filenames: CLAUDE.md, AGENTS.md, AGENTS.override.md, GEMINI.md,
190
+ // QWEN.md, KIRO.md, copilot-instructions.md,
191
+ // context-mode.mdc
192
+ // Directories: .claude/, .codex/memories/, .qwen/memory/,
193
+ // .gemini/memory/, .config/<plat>/memory/, .cursor/memory/,
194
+ // .github/memory/, .kiro/memory/, etc.
195
+ const isRuleFile =
196
+ /(?:CLAUDE|AGENTS(?:\.override)?|GEMINI|QWEN|KIRO)\.md$/i.test(filePath)
197
+ || /\/copilot-instructions\.md$/i.test(filePath)
198
+ || /\/context-mode\.mdc$/i.test(filePath)
199
+ || /\.claude[\\/]/i.test(filePath)
200
+ || /[\\/]memor(?:y|ies)[\\/][^\\/]+\.md$/i.test(filePath);
201
+ if (isRuleFile) {
202
+ events.push({
203
+ type: "rule",
204
+ category: "rule",
205
+ data: safeString(filePath),
206
+ priority: 1,
207
+ });
208
+
209
+ // Capture rule content so it survives context compaction
210
+ if (tool_response && tool_response.length > 0) {
211
+ events.push({
212
+ type: "rule_content",
213
+ category: "rule",
214
+ data: safeString(tool_response),
215
+ priority: 1,
216
+ });
217
+ }
218
+ }
219
+
220
+ // Always emit file_read for any Read call
221
+ events.push({
222
+ type: "file_read",
223
+ category: "file",
224
+ data: safeString(filePath),
225
+ priority: 1,
226
+ });
227
+
228
+ return events;
229
+ }
230
+
231
+ if (tool_name === "Edit") {
232
+ const filePath = String(tool_input["file_path"] ?? "");
233
+ events.push({
234
+ type: "file_edit",
235
+ category: "file",
236
+ data: safeString(filePath),
237
+ priority: 1,
238
+ });
239
+ return events;
240
+ }
241
+
242
+ if (tool_name === "NotebookEdit") {
243
+ const notebookPath = String(tool_input["notebook_path"] ?? "");
244
+ events.push({
245
+ type: "file_edit",
246
+ category: "file",
247
+ data: safeString(notebookPath),
248
+ priority: 1,
249
+ });
250
+ return events;
251
+ }
252
+
253
+ if (tool_name === "Write") {
254
+ const filePath = String(tool_input["file_path"] ?? "");
255
+ events.push({
256
+ type: "file_write",
257
+ category: "file",
258
+ data: safeString(filePath),
259
+ priority: 1,
260
+ });
261
+ return events;
262
+ }
263
+
264
+ if (tool_name === "apply_patch") {
265
+ if (isToolError(input)) return [];
266
+ const patchTargets = extractApplyPatchTargets(
267
+ String(tool_input["command"] ?? tool_input["patch"] ?? ""),
268
+ );
269
+ for (const target of patchTargets) {
270
+ events.push({
271
+ type: target.type,
272
+ category: "file",
273
+ data: safeString(target.path),
274
+ priority: 1,
275
+ });
276
+ }
277
+ return events;
278
+ }
279
+
280
+ // Glob — file pattern exploration
281
+ if (tool_name === "Glob") {
282
+ const pattern = String(tool_input["pattern"] ?? "");
283
+ events.push({
284
+ type: "file_glob",
285
+ category: "file",
286
+ data: safeString(pattern),
287
+ priority: 3,
288
+ });
289
+ return events;
290
+ }
291
+
292
+ // Grep — code search
293
+ if (tool_name === "Grep") {
294
+ const searchPattern = String(tool_input["pattern"] ?? "");
295
+ const searchPath = String(tool_input["path"] ?? "");
296
+ events.push({
297
+ type: "file_search",
298
+ category: "file",
299
+ data: safeString(`${searchPattern} in ${searchPath}`),
300
+ priority: 3,
301
+ });
302
+ return events;
303
+ }
304
+
305
+ return events;
306
+ }
307
+
308
+ /**
309
+ * Category 4: cwd
310
+ * Matches the first `cd <path>` in a Bash command (handles quoted paths).
311
+ */
312
+ function extractCwd(input: HookInput): SessionEvent[] {
313
+ if (input.tool_name !== "Bash") return [];
314
+
315
+ const cmd = String(input.tool_input["command"] ?? "");
316
+ // Match: cd "path" | cd 'path' | cd path
317
+ const cdMatch = cmd.match(/\bcd\s+("([^"]+)"|'([^']+)'|(\S+))/);
318
+ if (!cdMatch) return [];
319
+
320
+ const dir = cdMatch[2] ?? cdMatch[3] ?? cdMatch[4] ?? "";
321
+ return [{
322
+ type: "cwd",
323
+ category: "cwd",
324
+ data: safeString(dir),
325
+ priority: 2,
326
+ }];
327
+ }
328
+
329
+ /**
330
+ * Category 5: error
331
+ * Detects failures from bash exit codes / error patterns, or an explicit
332
+ * isError flag in tool_output.
333
+ */
334
+ function extractError(input: HookInput): SessionEvent[] {
335
+ const { tool_response } = input;
336
+ const response = String(tool_response ?? "");
337
+ if (!isToolError(input)) return [];
338
+
339
+ return [{
340
+ type: "error_tool",
341
+ category: "error",
342
+ data: safeString(response),
343
+ priority: 2,
344
+ }];
345
+ }
346
+
347
+ /**
348
+ * Category 11: git
349
+ * Matches common git operations from Bash commands.
350
+ */
351
+
352
+ const GIT_PATTERNS: Array<{ pattern: RegExp; operation: string }> = [
353
+ { pattern: /\bgit\s+checkout\b/, operation: "branch" },
354
+ { pattern: /\bgit\s+commit\b/, operation: "commit" },
355
+ { pattern: /\bgit\s+merge\s+\S+/, operation: "merge" },
356
+ { pattern: /\bgit\s+rebase\b/, operation: "rebase" },
357
+ { pattern: /\bgit\s+stash\b/, operation: "stash" },
358
+ { pattern: /\bgit\s+push\b/, operation: "push" },
359
+ { pattern: /\bgit\s+pull\b/, operation: "pull" },
360
+ { pattern: /\bgit\s+log\b/, operation: "log" },
361
+ { pattern: /\bgit\s+diff\b/, operation: "diff" },
362
+ { pattern: /\bgit\s+status\b/, operation: "status" },
363
+ { pattern: /\bgit\s+branch\b/, operation: "branch" },
364
+ { pattern: /\bgit\s+reset\b/, operation: "reset" },
365
+ { pattern: /\bgit\s+add\b/, operation: "add" },
366
+ { pattern: /\bgit\s+cherry-pick\b/, operation: "cherry-pick" },
367
+ { pattern: /\bgit\s+tag\b/, operation: "tag" },
368
+ { pattern: /\bgit\s+fetch\b/, operation: "fetch" },
369
+ { pattern: /\bgit\s+clone\b/, operation: "clone" },
370
+ { pattern: /\bgit\s+worktree\b/, operation: "worktree" },
371
+ ];
372
+
373
+ function extractGit(input: HookInput): SessionEvent[] {
374
+ if (input.tool_name !== "Bash") return [];
375
+
376
+ const cmd = String(input.tool_input["command"] ?? "");
377
+
378
+ // Bug 8 (v1.0.162) — parse the git invocation algorithmically so flags
379
+ // between `git` and the operation token are tolerated (`git -C /path
380
+ // status`, `git --no-pager log`, etc.). Falls back to the legacy regex
381
+ // pattern scan when the algorithmic parse cannot locate a `git` token —
382
+ // preserves backward compat for commands like `cd /repo && git status`
383
+ // where the algorithmic parse sees `cd` as the first token instead.
384
+ const parsed = parseGitInvocation(cmd);
385
+ let match: { pattern: RegExp; operation: string } | undefined;
386
+ if (parsed && parsed.operation) {
387
+ match = GIT_PATTERNS.find(p => p.operation === parsed.operation);
388
+ }
389
+ if (!match) {
390
+ match = GIT_PATTERNS.find(p => p.pattern.test(cmd));
391
+ }
392
+ if (!match) return [];
393
+
394
+ // Bug 1 (v1.0.161) — for `git commit` operations, parse -m / -am / --message=
395
+ // from the Bash command via shell-like argv tokenization so downstream
396
+ // consumers receive the actual commit subject in `data`. Falls back to the
397
+ // operation name when no message argument is present (--amend / --no-edit /
398
+ // -F file / interactive editor flow). Tokenizer is hand-rolled char-by-char
399
+ // (no regex) to mirror real shell quoting/cluster-flag semantics.
400
+ //
401
+ // When a message is captured, the event surfaces as type='git_commit' so the
402
+ // rollup aggregator can distinguish ACTUAL commits from other git operations
403
+ // (status/diff/log were inflating has_commit on every event — see
404
+ // session-loaders.mjs rollup stamp + Bug 2).
405
+ // Bug 8 cwd hint — when `-C <dir>` is present in the git invocation, emit
406
+ // a leading cwd event so the attribution carry-forward (LAST_SEEN source)
407
+ // routes downstream events in the same batch to the scoped directory's
408
+ // project. Without the hint, `git -C /projB status` while cwd=/projA
409
+ // misattributes to /projA.
410
+ const out: SessionEvent[] = [];
411
+ if (parsed?.scopedDir) {
412
+ out.push({
413
+ type: "cwd",
414
+ category: "cwd",
415
+ data: safeString(parsed.scopedDir),
416
+ priority: 2,
417
+ });
418
+ }
419
+
420
+ if (match.operation === "commit") {
421
+ const msg = extractCommitMessageFromCommand(cmd);
422
+ if (msg) {
423
+ out.push({
424
+ type: "git_commit",
425
+ category: "git",
426
+ data: safeString(msg),
427
+ priority: 2,
428
+ });
429
+ return out;
430
+ }
431
+ }
432
+
433
+ out.push({
434
+ type: "git",
435
+ category: "git",
436
+ data: safeString(match.operation),
437
+ priority: 2,
438
+ });
439
+ return out;
440
+ }
441
+
442
+ // Algorithmic git invocation parser — tokenizes the Bash command and walks
443
+ // argv to extract the `-C <dir>` scope hint and the operation subcommand.
444
+ // Tolerates env-prefix assignments and any number of flags between `git`
445
+ // and the operation. Returns null when no `git` token is found (caller
446
+ // falls back to the legacy regex pattern scan).
447
+ interface ParsedGit {
448
+ scopedDir: string | null;
449
+ operation: string | null;
450
+ }
451
+
452
+ /**
453
+ * Gap #2 (16-oss-verify-gap-prd) — expand leading `~` / `~/` to homedir.
454
+ * Does NOT support `~user/path` (no current-user resolution at bridge
455
+ * layer; that requires a passwd lookup). Returns input unchanged when
456
+ * there is no tilde or the path starts with `~<otheruser>`.
457
+ */
458
+ function expandHomeTilde(path: string): string {
459
+ if (typeof path !== "string" || path.length === 0) return path;
460
+ if (path === "~") return getHomedirSafe();
461
+ if (path.startsWith("~/")) return getHomedirSafe() + path.slice(1);
462
+ return path;
463
+ }
464
+
465
+ /**
466
+ * Lazily-resolved homedir — avoids a require/import at module init time.
467
+ * Falls back to "~" (no-op expansion) when the environment is sandboxed
468
+ * without HOME / USERPROFILE.
469
+ */
470
+ function getHomedirSafe(): string {
471
+ try {
472
+ const home = process.env.HOME
473
+ || process.env.USERPROFILE
474
+ || (process.env.HOMEDRIVE && process.env.HOMEPATH
475
+ ? process.env.HOMEDRIVE + process.env.HOMEPATH
476
+ : "");
477
+ return home || "~";
478
+ } catch {
479
+ return "~";
480
+ }
481
+ }
482
+
483
+ function parseGitInvocation(cmd: string): ParsedGit | null {
484
+ const tokens = tokenizeCommand(cmd);
485
+ let i = 0;
486
+ // Skip env-style assignments at the head (FOO=bar git ...)
487
+ while (i < tokens.length && isEnvAssignment(tokens[i])) i++;
488
+ // Locate the `git` token (allow common runners like `sudo git ...`)
489
+ while (i < tokens.length && tokens[i] !== "git" && !tokens[i].endsWith("/git")) {
490
+ // Stop runner-skipping at the first non-assignment, non-runner token
491
+ if (!isCommonRunner(tokens[i])) break;
492
+ i++;
493
+ }
494
+ if (i >= tokens.length) return null;
495
+ if (tokens[i] !== "git" && !tokens[i].endsWith("/git")) return null;
496
+ i++; // consume `git`
497
+
498
+ let scopedDir: string | null = null;
499
+ let operation: string | null = null;
500
+ while (i < tokens.length) {
501
+ const t = tokens[i];
502
+ if (t === "-C" || t === "--directory") {
503
+ scopedDir = tokens[i + 1] ?? null;
504
+ i += 2;
505
+ continue;
506
+ }
507
+ // Gap #2 — `--directory=/path` equals-form (tokenizer keeps it as one)
508
+ if (t.startsWith("--directory=")) {
509
+ scopedDir = t.slice("--directory=".length);
510
+ i++;
511
+ continue;
512
+ }
513
+ if (t.length > 0 && t[0] === "-") {
514
+ // Generic flag — skip the flag itself. We do NOT consume the next
515
+ // token as its value generically because git's per-flag arg shape
516
+ // varies; the dedicated extractCommitMessageFromCommand handles -m
517
+ // separately.
518
+ i++;
519
+ continue;
520
+ }
521
+ // First bare (non-flag) token after `git` = operation
522
+ operation = t;
523
+ break;
524
+ }
525
+ if (scopedDir) scopedDir = expandHomeTilde(scopedDir);
526
+ return { scopedDir, operation };
527
+ }
528
+
529
+ function isEnvAssignment(token: string): boolean {
530
+ if (token.length === 0) return false;
531
+ // FOO=bar shape: starts with an uppercase letter, contains an `=`
532
+ let sawEq = false;
533
+ for (let j = 0; j < token.length; j++) {
534
+ const c = token.charCodeAt(j);
535
+ if (j === 0) {
536
+ // First char must be A-Z or underscore
537
+ if (!((c >= 65 && c <= 90) || c === 95)) return false;
538
+ } else if (c === 61 /* = */) {
539
+ sawEq = true;
540
+ break;
541
+ } else if (!((c >= 65 && c <= 90) || (c >= 48 && c <= 57) || c === 95)) {
542
+ // Body chars must be A-Z, 0-9, or _
543
+ return false;
544
+ }
545
+ }
546
+ return sawEq;
547
+ }
548
+
549
+ function isCommonRunner(token: string): boolean {
550
+ // Runners that wrap real commands. We skip them when locating `git`
551
+ // so `sudo git status` works the same as `git status`.
552
+ switch (token) {
553
+ case "sudo":
554
+ case "doas":
555
+ case "env":
556
+ case "exec":
557
+ case "time":
558
+ return true;
559
+ default:
560
+ return false;
561
+ }
562
+ }
563
+
564
+ // Shell-like argv tokenizer — handles single/double quotes, backslash escapes,
565
+ // and merges adjacent quoted/unquoted segments per POSIX shell behavior
566
+ // (`echo a"b c"d` → ["ab cd"]). Pure char loop; no regex.
567
+ function tokenizeCommand(cmd: string): string[] {
568
+ const tokens: string[] = [];
569
+ const n = cmd.length;
570
+ let i = 0;
571
+ while (i < n) {
572
+ while (i < n && (cmd[i] === " " || cmd[i] === "\t")) i++;
573
+ if (i >= n) break;
574
+ let buf = "";
575
+ while (i < n && cmd[i] !== " " && cmd[i] !== "\t") {
576
+ const ch = cmd[i];
577
+ if (ch === '"' || ch === "'") {
578
+ const quote = ch;
579
+ i++;
580
+ while (i < n && cmd[i] !== quote) {
581
+ if (cmd[i] === "\\" && i + 1 < n) {
582
+ buf += cmd[i + 1];
583
+ i += 2;
584
+ } else {
585
+ buf += cmd[i];
586
+ i++;
587
+ }
588
+ }
589
+ if (i < n) i++; // consume closing quote
590
+ } else if (ch === "\\" && i + 1 < n) {
591
+ buf += cmd[i + 1];
592
+ i += 2;
593
+ } else {
594
+ buf += ch;
595
+ i++;
596
+ }
597
+ }
598
+ tokens.push(buf);
599
+ }
600
+ return tokens;
601
+ }
602
+
603
+ // Linear scan over argv looking for a commit-message-bearing flag:
604
+ // --message=<value> long form, attached value
605
+ // --message <value> long form, separate token
606
+ // -m / -am / -cm ... short cluster ending in 'm', value in next token
607
+ // Returns null when no message arg is present — caller falls back to
608
+ // operation name. Pure char checks; no regex.
609
+ function extractCommitMessageFromCommand(cmd: string): string | null {
610
+ const argv = tokenizeCommand(cmd);
611
+ const longPrefix = "--message=";
612
+ for (let i = 0; i < argv.length; i++) {
613
+ const arg = argv[i];
614
+ // Long form: --message=VALUE
615
+ if (arg.length > longPrefix.length && arg.startsWith(longPrefix)) {
616
+ const v = arg.slice(longPrefix.length);
617
+ return v.length > 0 ? v : null;
618
+ }
619
+ // Long form: --message VALUE
620
+ if (arg === "--message") {
621
+ const v = argv[i + 1];
622
+ return v && v.length > 0 ? v : null;
623
+ }
624
+ // Short cluster ending in 'm' (e.g. -m, -am, -cm). Cluster must be
625
+ // single-dash followed by only lowercase letters, last letter 'm'.
626
+ if (
627
+ arg.length >= 2 &&
628
+ arg[0] === "-" &&
629
+ arg[1] !== "-" &&
630
+ arg[arg.length - 1] === "m" &&
631
+ isLowerAlphaRun(arg, 1)
632
+ ) {
633
+ const v = argv[i + 1];
634
+ return v && v.length > 0 ? v : null;
635
+ }
636
+ }
637
+ return null;
638
+ }
639
+
640
+ function isLowerAlphaRun(s: string, start: number): boolean {
641
+ if (start >= s.length) return false;
642
+ for (let i = start; i < s.length; i++) {
643
+ const c = s.charCodeAt(i);
644
+ if (c < 97 || c > 122) return false; // not a-z
645
+ }
646
+ return true;
647
+ }
648
+
649
+ /**
650
+ * Category 3: task
651
+ * TodoWrite / TaskCreate / TaskUpdate tool calls.
652
+ */
653
+ function extractTask(input: HookInput): SessionEvent[] {
654
+ const TASK_TOOLS = new Set(["TodoWrite", "TaskCreate", "TaskUpdate"]);
655
+ if (!TASK_TOOLS.has(input.tool_name)) return [];
656
+
657
+ // Store tool name as type so create vs update can be reliably distinguished
658
+ const type = input.tool_name === "TaskUpdate" ? "task_update"
659
+ : input.tool_name === "TaskCreate" ? "task_create"
660
+ : "task"; // TodoWrite fallback
661
+
662
+ return [{
663
+ type,
664
+ category: "task",
665
+ data: safeString(JSON.stringify(input.tool_input)),
666
+ priority: 1,
667
+ }];
668
+ }
669
+
670
+ /**
671
+ * Category 15: plan
672
+ * Tracks the full plan mode lifecycle:
673
+ * - EnterPlanMode → plan_enter
674
+ * - Write/Edit to ~/.claude/plans/ → plan_file_write
675
+ * - ExitPlanMode → plan_exit (with allowedPrompts)
676
+ * - ExitPlanMode tool_response → plan_approved / plan_rejected
677
+ *
678
+ * Note: Shift+Tab and /plan command do NOT fire PostToolUse hooks
679
+ * (Claude Code bug #15660). Only programmatic EnterPlanMode is tracked.
680
+ */
681
+ /**
682
+ * FNV-1a 32-bit hash → 8-char lowercase hex. Stable across runs/platforms.
683
+ * Used for plan_hash so identical plans dedupe at the platform side.
684
+ */
685
+ function fnv1a32Hex(s: string): string {
686
+ let hash = 0x811c9dc5;
687
+ for (let i = 0; i < s.length; i++) {
688
+ hash ^= s.charCodeAt(i);
689
+ hash = Math.imul(hash, 0x01000193);
690
+ }
691
+ return (hash >>> 0).toString(16).padStart(8, "0");
692
+ }
693
+
694
+ /**
695
+ * Read the plan text from the ExitPlanMode envelope. SDK carries it on
696
+ * the OUTPUT (ExitPlanModeOutput @ :2222), but the PRD body cites input.
697
+ * Try both so we are spec-flexible.
698
+ */
699
+ function extractExitPlanText(input: HookInput): string | null {
700
+ const inputPlan = input.tool_input["plan"];
701
+ if (typeof inputPlan === "string" && inputPlan.length > 0) return inputPlan;
702
+ const resp = input.tool_response;
703
+ if (typeof resp === "string" && resp.length > 0) {
704
+ try {
705
+ const parsed = JSON.parse(resp);
706
+ if (parsed && typeof parsed === "object" && typeof (parsed as Record<string, unknown>).plan === "string") {
707
+ return (parsed as Record<string, unknown>).plan as string;
708
+ }
709
+ } catch { /* fall through */ }
710
+ }
711
+ return null;
712
+ }
713
+
714
+ function extractPlan(input: HookInput): SessionEvent[] {
715
+ if (input.tool_name === "EnterPlanMode") {
716
+ return [{
717
+ type: "plan_enter",
718
+ category: "plan",
719
+ data: "entered plan mode",
720
+ priority: 2,
721
+ }];
722
+ }
723
+
724
+ if (input.tool_name === "ExitPlanMode") {
725
+ const events: SessionEvent[] = [];
726
+
727
+ // Plan exit event with allowedPrompts detail
728
+ const prompts = input.tool_input["allowedPrompts"];
729
+ let detail = Array.isArray(prompts) && prompts.length > 0
730
+ ? `exited plan mode (allowed: ${safeStringAny(prompts.map((p: unknown) => {
731
+ if (typeof p === "object" && p !== null && "prompt" in p) return String((p as Record<string, unknown>).prompt);
732
+ return String(p);
733
+ }).join(", "))})`
734
+ : "exited plan mode";
735
+
736
+ // §11 / PRD #6 — append plan_bytes + plan_hash so the platform can
737
+ // dedupe identical plans across sessions and JOIN plan_mode_authorized
738
+ // writes against a stable plan id. Plan source: tool_input.plan first
739
+ // (per PRD), fall back to tool_response.plan (SDK actually carries it
740
+ // there per ExitPlanModeOutput @ sdk-tools.d.ts:2222).
741
+ const plan = extractExitPlanText(input);
742
+ if (typeof plan === "string" && plan.length > 0) {
743
+ detail += ` plan_bytes:${plan.length} plan_hash:${fnv1a32Hex(plan)}`;
744
+ }
745
+
746
+ events.push({
747
+ type: "plan_exit",
748
+ category: "plan",
749
+ data: safeString(detail),
750
+ priority: 2,
751
+ });
752
+
753
+ // Detect approval/rejection from tool_response
754
+ const response = String(input.tool_response ?? "").toLowerCase();
755
+ if (response.includes("approved") || response.includes("approve")) {
756
+ events.push({
757
+ type: "plan_approved",
758
+ category: "plan",
759
+ data: "plan approved by user",
760
+ priority: 1,
761
+ });
762
+ } else if (response.includes("rejected") || response.includes("decline") || response.includes("denied")) {
763
+ events.push({
764
+ type: "plan_rejected",
765
+ category: "plan",
766
+ data: safeString(`plan rejected: ${input.tool_response ?? ""}`),
767
+ priority: 2,
768
+ });
769
+ }
770
+
771
+ return events;
772
+ }
773
+
774
+ // Detect plan file writes (Write/Edit to ~/.claude/plans/)
775
+ if (input.tool_name === "Write" || input.tool_name === "Edit") {
776
+ const filePath = String(input.tool_input["file_path"] ?? "");
777
+ if (isPlanFilePath(filePath)) {
778
+ return [{
779
+ type: "plan_file_write",
780
+ category: "plan",
781
+ data: safeString(`plan file: ${filePath.split(/[/\\]/).pop() ?? filePath}`),
782
+ priority: 2,
783
+ }];
784
+ }
785
+ }
786
+
787
+ if (input.tool_name === "apply_patch") {
788
+ if (isToolError(input)) return [];
789
+ const patchTargets = extractApplyPatchTargets(
790
+ String(input.tool_input["command"] ?? input.tool_input["patch"] ?? ""),
791
+ );
792
+ return patchTargets
793
+ .filter((target) => isPlanFilePath(target.path))
794
+ .map((target) => ({
795
+ type: "plan_file_write",
796
+ category: "plan",
797
+ data: safeString(`plan file: ${target.path.split(/[/\\]/).pop() ?? target.path}`),
798
+ priority: 2,
799
+ }));
800
+ }
801
+
802
+ return [];
803
+ }
804
+
805
+ /**
806
+ * Category 8: env
807
+ * Environment setup commands in Bash: venv, export, nvm, pyenv, conda, rbenv.
808
+ */
809
+
810
+ const ENV_PATTERNS: RegExp[] = [
811
+ /\bsource\s+\S*activate\b/,
812
+ /\bexport\s+\w+=/,
813
+ /\bnvm\s+use\b/,
814
+ /\bpyenv\s+(shell|local|global)\b/,
815
+ /\bconda\s+activate\b/,
816
+ /\brbenv\s+(shell|local|global)\b/,
817
+ /\bnpm\s+install\b/,
818
+ /\bnpm\s+ci\b/,
819
+ /\bpip\s+install\b/,
820
+ /\bbun\s+install\b/,
821
+ /\byarn\s+(add|install)\b/,
822
+ /\bpnpm\s+(add|install)\b/,
823
+ /\bcargo\s+(install|add)\b/,
824
+ /\bgo\s+(install|get)\b/,
825
+ /\brustup\b/,
826
+ /\basdf\b/,
827
+ /\bvolta\b/,
828
+ /\bdeno\s+install\b/,
829
+ ];
830
+
831
+ function extractEnv(input: HookInput): SessionEvent[] {
832
+ if (input.tool_name !== "Bash") return [];
833
+
834
+ const cmd = String(input.tool_input["command"] ?? "");
835
+ const isEnvCmd = ENV_PATTERNS.some(p => p.test(cmd));
836
+ if (!isEnvCmd) return [];
837
+
838
+ // Sanitize export commands to prevent secret leakage
839
+ const sanitized = cmd.replace(/\bexport\s+(\w+)=\S*/g, "export $1=***");
840
+
841
+ return [{
842
+ type: "env",
843
+ category: "env",
844
+ data: safeString(sanitized),
845
+ priority: 2,
846
+ }];
847
+ }
848
+
849
+ /**
850
+ * Category 10: skill
851
+ * Skill tool invocations.
852
+ */
853
+ function extractSkill(input: HookInput): SessionEvent[] {
854
+ if (input.tool_name !== "Skill") return [];
855
+
856
+ const skillName = String(input.tool_input["skill"] ?? "");
857
+ return [{
858
+ type: "skill",
859
+ category: "skill",
860
+ data: safeString(skillName),
861
+ priority: 2,
862
+ }];
863
+ }
864
+
865
+ /**
866
+ * Category 16: constraint
867
+ * Constraints discovered through error events — tool failures reveal
868
+ * platform/environment limitations worth remembering.
869
+ */
870
+ function extractConstraint(input: HookInput): SessionEvent[] {
871
+ // Only fire on error events — constraints are discovered through failures
872
+ if (!input.tool_response?.includes("Error") && !input.tool_output?.isError) return [];
873
+
874
+ const response = String(input.tool_response || "");
875
+ const patterns = [/not supported/i, /cannot/i, /does not support/i, /FAIL/i, /refused/i, /permission denied/i, /incompatible/i];
876
+
877
+ for (const pattern of patterns) {
878
+ const match = response.match(pattern);
879
+ if (match) {
880
+ // Extract context around the match
881
+ const idx = response.toLowerCase().indexOf(match[0].toLowerCase());
882
+ const context = response.slice(Math.max(0, idx - 50), Math.min(response.length, idx + 200)).trim();
883
+ return [{
884
+ type: "constraint_discovered",
885
+ category: "constraint",
886
+ data: safeString(context),
887
+ priority: 2,
888
+ }];
889
+ }
890
+ }
891
+ return [];
892
+ }
893
+
894
+ /**
895
+ * Category 9: subagent
896
+ * Agent tool calls — tracks both launch and completion.
897
+ * When tool_response is present, the agent has completed and the result
898
+ * is captured at higher priority (P2) so it survives budget trimming.
899
+ */
900
+ function extractSubagent(input: HookInput): SessionEvent[] {
901
+ if (input.tool_name !== "Agent") return [];
902
+
903
+ const prompt = safeString(String(input.tool_input["prompt"] ?? input.tool_input["description"] ?? ""));
904
+ const response = input.tool_response ? safeString(String(input.tool_response)) : "";
905
+ const isCompleted = response.length > 0;
906
+
907
+ return [{
908
+ type: isCompleted ? "subagent_completed" : "subagent_launched",
909
+ category: "subagent",
910
+ data: isCompleted
911
+ ? safeString(`[completed] ${prompt} → ${response}`)
912
+ : safeString(`[launched] ${prompt}`),
913
+ priority: isCompleted ? 2 : 3,
914
+ }];
915
+ }
916
+
917
+ /**
918
+ * Category 14: mcp
919
+ * MCP tool calls (context7, playwright, claude-mem, ctx-stats, etc.).
920
+ */
921
+ function extractMcp(input: HookInput): SessionEvent[] {
922
+ const { tool_name, tool_input, tool_response } = input;
923
+ if (!tool_name.startsWith("mcp__")) return [];
924
+
925
+ // Extract readable tool name: last segment after __
926
+ const parts = tool_name.split("__");
927
+ const toolShort = parts[parts.length - 1] || tool_name;
928
+
929
+ // Extract first string argument for context
930
+ const firstArg = Object.values(tool_input).find((v): v is string => typeof v === "string");
931
+ const argStr = firstArg ? `: ${safeString(String(firstArg))}` : "";
932
+
933
+ // Append tool_response so ctx_search can find what the MCP returned — not
934
+ // just the call shape. Without this, bodies from external MCPs (jira tickets,
935
+ // grafana loki lines, sentry issues, context7 docs) are invisible to search.
936
+ // No truncation: matches the rule_content precedent above — SQLite TEXT is
937
+ // unbounded and large responses are the ones a cache most wants to preserve.
938
+ const responseStr = tool_response && tool_response.length > 0
939
+ ? `\nresponse: ${safeString(tool_response)}`
940
+ : "";
941
+
942
+ return [{
943
+ type: "mcp",
944
+ category: "mcp",
945
+ data: safeString(`${toolShort}${argStr}${responseStr}`),
946
+ priority: 3,
947
+ }];
948
+ }
949
+
950
+ /**
951
+ * Category 27: mcp_tool_call
952
+ * Records the raw MCP call shape (tool_name + tool_input) so analytics
953
+ * can compute usage patterns like batch concurrency.
954
+ *
955
+ * Distinct from `extractMcp` (category "mcp"), which captures the textual
956
+ * call+response for FTS5 search. This emits a structured JSON payload
957
+ * keyed by tool_name + params, capped to ~2KB to keep SQLite rows small.
958
+ *
959
+ * Priority 4 (informational) — should not crowd out high-signal events
960
+ * during FIFO eviction.
961
+ */
962
+ const MCP_PARAMS_BUDGET_BYTES = 2048;
963
+
964
+ /**
965
+ * UTF-8-aware string truncation. Returns the longest prefix of `s` whose
966
+ * UTF-8 byte length is <= `maxBytes`, never landing mid-multibyte-codepoint.
967
+ *
968
+ * Naive `s.slice(0, N)` operates on UTF-16 code units, so a 2KB cap could
969
+ * either over-shoot (multi-byte codepoints occupy fewer code units than
970
+ * bytes — e.g. a chunk of CJK / emoji-heavy JSON would silently exceed
971
+ * the byte budget) or land mid surrogate pair (corrupt JSON downstream).
972
+ */
973
+ function truncateToBytes(s: string, maxBytes: number): { value: string; truncated: boolean } {
974
+ if (Buffer.byteLength(s, "utf8") <= maxBytes) return { value: s, truncated: false };
975
+ const buf = Buffer.from(s, "utf8");
976
+ // Walk back from maxBytes until the byte starts a fresh codepoint:
977
+ // 0xxxxxxx → ASCII (start)
978
+ // 11xxxxxx → start of multi-byte
979
+ // 10xxxxxx → continuation; keep walking
980
+ let cut = maxBytes;
981
+ while (cut > 0 && (buf[cut] & 0xc0) === 0x80) cut--;
982
+ return { value: buf.subarray(0, cut).toString("utf8"), truncated: true };
983
+ }
984
+
985
+ /**
986
+ * Keys whose VALUES must be redacted before persisting tool_input — secrets,
987
+ * tokens, credentials, signatures. Match is on the LAST path segment of the
988
+ * key (case-insensitive substring), so `headers.Authorization`, `auth.token`,
989
+ * `apiKey`, `API_KEY`, `password`, `secret`, `cookie`, `set-cookie`, `signature`,
990
+ * `private_key`, etc. all redact. False-positive risk acceptable — we'd rather
991
+ * over-redact than ship a Bearer token to SQLite.
992
+ */
993
+ const SECRET_KEY_PATTERN =
994
+ /(authorization|auth_token|access_token|refresh_token|bearer|token|secret|password|passwd|pwd|api[-_]?key|apikey|cookie|set-cookie|signature|private[-_]?key|client[-_]?secret|x[-_]?api[-_]?key)/i;
995
+
996
+ const REDACTED = "[REDACTED]";
997
+
998
+ /**
999
+ * Walk an arbitrary JSON-serializable value and return a clone with values
1000
+ * redacted under any key matching SECRET_KEY_PATTERN. Cycle-safe.
1001
+ */
1002
+ function redactSecrets(value: unknown, ancestors: WeakSet<object> = new WeakSet()): unknown {
1003
+ if (value == null || typeof value !== "object") return value;
1004
+ // Path-based ancestor check: only flag TRUE cycles, not DAG / shared refs
1005
+ // (e.g., a single `headers` object passed to multiple sub-requests must
1006
+ // be processed at every reference site, not flagged as circular).
1007
+ if (ancestors.has(value as object)) return "[CIRCULAR]";
1008
+ ancestors.add(value as object);
1009
+
1010
+ let out: unknown;
1011
+ if (Array.isArray(value)) {
1012
+ out = value.map((v) => redactSecrets(v, ancestors));
1013
+ } else {
1014
+ const obj: Record<string, unknown> = {};
1015
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
1016
+ if (SECRET_KEY_PATTERN.test(k)) {
1017
+ obj[k] = REDACTED;
1018
+ } else {
1019
+ obj[k] = redactSecrets(v, ancestors);
1020
+ }
1021
+ }
1022
+ out = obj;
1023
+ }
1024
+
1025
+ ancestors.delete(value as object); // pop ancestor — siblings can re-visit
1026
+ return out;
1027
+ }
1028
+
1029
+ function extractMcpToolCall(input: HookInput): SessionEvent[] {
1030
+ const { tool_name, tool_input } = input;
1031
+ if (!tool_name.startsWith("mcp__")) return [];
1032
+
1033
+ // Redact secrets BEFORE serialization. Any `tool_input` carrying
1034
+ // `Authorization: Bearer …`, `api_key: "sk-…"`, cookies, signatures, etc.
1035
+ // is masked before it touches SQLite. Over-redaction acceptable — under-
1036
+ // redaction is a credential leak to SessionDB.
1037
+ const redactedInput = redactSecrets(tool_input ?? {});
1038
+
1039
+ // Serialize the redacted shape, then truncate the *string* (not the object)
1040
+ // so the diagnosable shape survives huge payloads.
1041
+ let paramsStr: string;
1042
+ try {
1043
+ paramsStr = JSON.stringify(redactedInput);
1044
+ } catch {
1045
+ paramsStr = "{}";
1046
+ }
1047
+ const { value: cappedStr, truncated } = truncateToBytes(paramsStr, MCP_PARAMS_BUDGET_BYTES);
1048
+
1049
+ const payload = truncated
1050
+ ? `{"tool_name":${JSON.stringify(tool_name)},"params_raw":${JSON.stringify(cappedStr)},"truncated":true}`
1051
+ : `{"tool_name":${JSON.stringify(tool_name)},"params":${cappedStr}}`;
1052
+
1053
+ const event: SessionEvent = {
1054
+ type: "mcp_tool_call",
1055
+ category: "mcp_tool_call",
1056
+ data: safeString(payload),
1057
+ priority: 4,
1058
+ };
1059
+
1060
+ // Retrieval cost (the OTHER half of the with/without ratio): when this MCP
1061
+ // call is a `ctx_search` or `ctx_fetch_and_index` retrieval, the tool_response
1062
+ // IS the kept-out content the model paid to access — record its byte length.
1063
+ // Sandbox compute (ctx_execute/batch/file) is work-output, NOT retrieval, so
1064
+ // it is intentionally excluded. Match by suffix char-algorithmically (host
1065
+ // prefixes the name like `mcp__plugin_…__ctx_search`); NO regex.
1066
+ if (isRetrievalToolName(tool_name)) {
1067
+ const response = safeString(input.tool_response);
1068
+ if (response.length > 0) {
1069
+ event.bytes_retrieved = Buffer.byteLength(response, "utf8");
1070
+ }
1071
+ }
1072
+
1073
+ return [event];
1074
+ }
1075
+
1076
+ /** Tool-name suffixes that denote a RETRIEVAL call (kept-out content accessed). */
1077
+ const RETRIEVAL_TOOL_SUFFIXES = ["ctx_search", "ctx_fetch_and_index"];
1078
+
1079
+ /**
1080
+ * True when `toolName` ends with one of the retrieval suffixes. Char-level
1081
+ * suffix comparison via String.prototype.endsWith — no regex. MCP host names
1082
+ * arrive prefixed (e.g. `mcp__plugin_context-mode_context-mode__ctx_search`),
1083
+ * so an exact-name check would miss them; suffix match is host-agnostic.
1084
+ */
1085
+ function isRetrievalToolName(toolName: string): boolean {
1086
+ for (const suffix of RETRIEVAL_TOOL_SUFFIXES) {
1087
+ if (toolName.endsWith(suffix)) return true;
1088
+ }
1089
+ return false;
1090
+ }
1091
+
1092
+ /**
1093
+ * Category 6 (tool-based): decision
1094
+ * AskUserQuestion tool — tracks questions posed to user and their answers.
1095
+ */
1096
+ function extractDecision(input: HookInput): SessionEvent[] {
1097
+ if (input.tool_name !== "AskUserQuestion") return [];
1098
+
1099
+ const questions = input.tool_input["questions"];
1100
+ const questionText = Array.isArray(questions) && questions.length > 0
1101
+ ? String((questions[0] as Record<string, unknown>)["question"] ?? "")
1102
+ : "";
1103
+
1104
+ // tool_response is a JSON string that echoes the full request payload
1105
+ // alongside the answers map: {"questions":[...],"answers":{"<q>":"<label>"}}.
1106
+ // Stringifying the raw blob leaks the echoed questions/options into the
1107
+ // event row and surfaces as "Unhandled case: [object Object]" downstream.
1108
+ const rawResponse = String(input.tool_response ?? "");
1109
+ let answerText = "";
1110
+ try {
1111
+ const parsed = JSON.parse(rawResponse) as { answers?: Record<string, unknown> };
1112
+ const answers = parsed?.answers;
1113
+ if (answers && typeof answers === "object") {
1114
+ // multiSelect: true answers arrive as string[]; single-select arrive as
1115
+ // string. Normalize both into a `" | "`-joined string so neither shape
1116
+ // silently produces an empty answer.
1117
+ const toAnswerText = (value: unknown): string => {
1118
+ if (typeof value === "string") return value;
1119
+ if (Array.isArray(value)) {
1120
+ return value.filter((v): v is string => typeof v === "string").join(" | ");
1121
+ }
1122
+ return "";
1123
+ };
1124
+
1125
+ const matched = questionText ? toAnswerText(answers[questionText]) : "";
1126
+ if (matched) {
1127
+ answerText = matched;
1128
+ } else {
1129
+ const values = Object.values(answers)
1130
+ .map(toAnswerText)
1131
+ .filter((v) => v.length > 0);
1132
+ answerText = values.join(" | ");
1133
+ }
1134
+ }
1135
+ } catch {
1136
+ // Non-JSON tool_response — fail safe with empty answer rather than
1137
+ // leaking the raw text (which would re-introduce the original bug
1138
+ // for any future caller that sends a non-JSON payload).
1139
+ }
1140
+
1141
+ const answer = safeString(answerText);
1142
+ const summary = questionText
1143
+ ? `Q: ${safeString(questionText)} → A: ${answer}`
1144
+ : `answer: ${answer}`;
1145
+
1146
+ return [{
1147
+ type: "decision_question",
1148
+ category: "decision",
1149
+ data: safeString(summary),
1150
+ priority: 2,
1151
+ }];
1152
+ }
1153
+
1154
+ /**
1155
+ * Category 22: agent-finding
1156
+ * When the Agent tool completes (subagent returns), capture a structured
1157
+ * summary of its findings (first 500 chars of tool_response).
1158
+ */
1159
+ function extractAgentFinding(input: HookInput): SessionEvent[] {
1160
+ if (input.tool_name !== "Agent") return [];
1161
+ if (!input.tool_response || input.tool_response.length === 0) return [];
1162
+
1163
+ const summary = input.tool_response.length > 500
1164
+ ? input.tool_response.slice(0, 500)
1165
+ : input.tool_response;
1166
+
1167
+ return [{
1168
+ type: "agent_finding",
1169
+ category: "agent-finding",
1170
+ data: safeString(summary),
1171
+ priority: 2,
1172
+ }];
1173
+ }
1174
+
1175
+ /**
1176
+ * Category 24: external-ref
1177
+ * Scan tool_input and tool_response for external URLs, GitHub issues, and PRs.
1178
+ * Deduplicates found refs and skips internal URLs (localhost, 127.0.0.1).
1179
+ */
1180
+ function extractExternalRef(input: HookInput): SessionEvent[] {
1181
+ const haystack = [
1182
+ safeStringAny(input.tool_input),
1183
+ safeString(input.tool_response),
1184
+ ].join(" ");
1185
+
1186
+ if (haystack.length === 0) return [];
1187
+
1188
+ const refs = new Set<string>();
1189
+
1190
+ // URLs — skip localhost / 127.0.0.1
1191
+ const urlMatches = haystack.match(/https?:\/\/[^\s)]+/g);
1192
+ if (urlMatches) {
1193
+ for (let url of urlMatches) {
1194
+ // Strip trailing punctuation that gets captured from JSON/prose
1195
+ url = url.replace(/["'})\],;.]+$/, "");
1196
+ if (!/localhost|127\.0\.0\.1/i.test(url)) {
1197
+ refs.add(url);
1198
+ }
1199
+ }
1200
+ }
1201
+
1202
+ // Full GitHub issue/PR URLs are already captured above.
1203
+ // Shorthand GitHub issue refs: #123 (only bare, not inside a URL)
1204
+ const issueMatches = haystack.match(/(?<!\w)#(\d+)/g);
1205
+ if (issueMatches) {
1206
+ for (const m of issueMatches) {
1207
+ refs.add(m);
1208
+ }
1209
+ }
1210
+
1211
+ if (refs.size === 0) return [];
1212
+
1213
+ // ctx_fetch_and_index returns a preamble like
1214
+ // "Fetched and indexed **5 sections** (47.50KB) from: <label>"
1215
+ // Parse the size to credit bytes_avoided on the event so per-session
1216
+ // honest-savings stats reflect what was kept out of the context window.
1217
+ // KB literal in the preamble is decimal (KB = 1024 bytes per the formatter).
1218
+ let bytesAvoided: number | undefined;
1219
+ const preambleMatch = safeString(input.tool_response).match(
1220
+ /Fetched and indexed[^\(]*\(([\d.]+)\s*KB\)/i,
1221
+ );
1222
+ if (preambleMatch) {
1223
+ const kb = Number(preambleMatch[1]);
1224
+ if (Number.isFinite(kb) && kb > 0) {
1225
+ bytesAvoided = Math.round(kb * 1024);
1226
+ }
1227
+ }
1228
+
1229
+ const event: SessionEvent = {
1230
+ type: "external_ref",
1231
+ category: "external-ref",
1232
+ data: safeString(Array.from(refs).join(", ")),
1233
+ priority: 3,
1234
+ };
1235
+ if (bytesAvoided !== undefined) event.bytes_avoided = bytesAvoided;
1236
+ return [event];
1237
+ }
1238
+
1239
+ /**
1240
+ * Category 8: env (worktree)
1241
+ * EnterWorktree + ExitWorktree tools — tracks worktree lifecycle.
1242
+ */
1243
+ function extractWorktree(input: HookInput): SessionEvent[] {
1244
+ if (input.tool_name === "EnterWorktree") {
1245
+ const name = String(input.tool_input["name"] ?? "unnamed");
1246
+ return [{
1247
+ type: "worktree",
1248
+ category: "env",
1249
+ data: safeString(`entered worktree: ${name}`),
1250
+ priority: 2,
1251
+ }];
1252
+ }
1253
+
1254
+ if (input.tool_name === "ExitWorktree") {
1255
+ const discard = Boolean(input.tool_input["discard_changes"]);
1256
+ return [{
1257
+ type: "worktree_exit",
1258
+ category: "env",
1259
+ data: safeString(`exited worktree (discard_changes:${discard})`),
1260
+ priority: 2,
1261
+ }];
1262
+ }
1263
+
1264
+ return [];
1265
+ }
1266
+
1267
+ /**
1268
+ * Algorithmic URL host extraction — no regex.
1269
+ * Skips scheme, returns everything up to the first path/query/fragment marker.
1270
+ * Port is preserved as part of the host signature.
1271
+ */
1272
+ function extractHostFromUrl(url: string): string | null {
1273
+ if (typeof url !== "string" || url.length === 0) return null;
1274
+ const protoEnd = url.indexOf("://");
1275
+ if (protoEnd < 0) return null;
1276
+ const start = protoEnd + 3;
1277
+ if (start >= url.length) return null;
1278
+ let end = url.length;
1279
+ for (let i = start; i < url.length; i++) {
1280
+ const c = url.charCodeAt(i);
1281
+ if (c === 47 || c === 63 || c === 35) { end = i; break; }
1282
+ }
1283
+ const host = url.slice(start, end);
1284
+ return host.length > 0 ? host : null;
1285
+ }
1286
+
1287
+ /**
1288
+ * WebFetch response metadata — captures bytes/code/durationMs and host
1289
+ * (privacy: never the full URL or query string). Redirect-loop detection
1290
+ * is temporal, not single-field — SDK has no redirect_url.
1291
+ */
1292
+ function extractWebFetchMetadata(input: HookInput): SessionEvent[] {
1293
+ if (input.tool_name !== "WebFetch") return [];
1294
+ const resp = input.tool_response;
1295
+ if (typeof resp !== "string" || resp.length === 0) return [];
1296
+
1297
+ let parsed: unknown;
1298
+ try { parsed = JSON.parse(resp); } catch { return []; }
1299
+ if (!parsed || typeof parsed !== "object") return [];
1300
+
1301
+ const obj = parsed as Record<string, unknown>;
1302
+ const parts: string[] = [];
1303
+
1304
+ if (typeof obj.code === "number") parts.push(`code:${obj.code}`);
1305
+ if (typeof obj.bytes === "number") parts.push(`bytes:${obj.bytes}`);
1306
+ if (typeof obj.durationMs === "number") parts.push(`durMs:${obj.durationMs}`);
1307
+ if (typeof obj.url === "string") {
1308
+ const host = extractHostFromUrl(obj.url);
1309
+ if (host) parts.push(`host:${host}`);
1310
+ }
1311
+
1312
+ if (parts.length === 0) return [];
1313
+
1314
+ return [{
1315
+ type: "webfetch_metadata",
1316
+ category: "data",
1317
+ data: safeString(parts.join(" ")),
1318
+ priority: 3,
1319
+ }];
1320
+ }
1321
+
1322
+ /**
1323
+ * Bash outcome signals — captures the three fields that DO exist on
1324
+ * BashOutput (SDK :2160-2200): interrupted (boolean), stderr (length-only
1325
+ * for privacy), returnCodeInterpretation (semantic non-zero exit hint).
1326
+ * NO exit_code field exists in the SDK.
1327
+ */
1328
+ function extractBashOutcome(input: HookInput): SessionEvent[] {
1329
+ if (input.tool_name !== "Bash") return [];
1330
+ const resp = input.tool_response;
1331
+ if (typeof resp !== "string" || resp.length === 0) return [];
1332
+
1333
+ let parsed: unknown;
1334
+ try { parsed = JSON.parse(resp); } catch { return []; }
1335
+ if (!parsed || typeof parsed !== "object") return [];
1336
+
1337
+ const obj = parsed as Record<string, unknown>;
1338
+ const hasSignal =
1339
+ typeof obj.interrupted === "boolean" ||
1340
+ typeof obj.stderr === "string" ||
1341
+ typeof obj.returnCodeInterpretation === "string";
1342
+ if (!hasSignal) return [];
1343
+
1344
+ const parts: string[] = [];
1345
+ if (typeof obj.interrupted === "boolean") {
1346
+ parts.push(`interrupted:${obj.interrupted}`);
1347
+ }
1348
+ if (typeof obj.returnCodeInterpretation === "string") {
1349
+ parts.push(`rcInterp:${obj.returnCodeInterpretation.slice(0, 80)}`);
1350
+ }
1351
+ if (typeof obj.stderr === "string") {
1352
+ parts.push(`stderrBytes:${obj.stderr.length}`);
1353
+ }
1354
+
1355
+ return [{
1356
+ type: "bash_outcome",
1357
+ category: "data",
1358
+ data: safeString(parts.join(" ")),
1359
+ priority: 3,
1360
+ }];
1361
+ }
1362
+
1363
+ /**
1364
+ * FileReadOutput size metadata — branches on the text/image variant.
1365
+ * Captures sizes/line counts only; never file content. Image dimensions
1366
+ * are formatted as "WxH" when both width/height are numeric.
1367
+ */
1368
+ function extractFileReadMetadata(input: HookInput): SessionEvent[] {
1369
+ if (input.tool_name !== "Read") return [];
1370
+ const resp = input.tool_response;
1371
+ if (typeof resp !== "string" || resp.length === 0) return [];
1372
+
1373
+ let parsed: unknown;
1374
+ try { parsed = JSON.parse(resp); } catch { return []; }
1375
+ if (!parsed || typeof parsed !== "object") return [];
1376
+
1377
+ const obj = parsed as Record<string, unknown>;
1378
+ const variant = obj.type;
1379
+ if (variant !== "text" && variant !== "image") return [];
1380
+
1381
+ const parts: string[] = [`type:${variant}`];
1382
+
1383
+ if (variant === "text") {
1384
+ if (typeof obj.numLines === "number") parts.push(`lines:${obj.numLines}`);
1385
+ if (typeof obj.totalLines === "number") parts.push(`totalLines:${obj.totalLines}`);
1386
+ if (typeof obj.startLine === "number") parts.push(`start:${obj.startLine}`);
1387
+ } else {
1388
+ if (typeof obj.originalSize === "number") parts.push(`origSize:${obj.originalSize}`);
1389
+ const dims = obj.dimensions;
1390
+ if (dims && typeof dims === "object") {
1391
+ const d = dims as Record<string, unknown>;
1392
+ if (typeof d.width === "number" && typeof d.height === "number") {
1393
+ parts.push(`dims:${d.width}x${d.height}`);
1394
+ }
1395
+ }
1396
+ }
1397
+
1398
+ return [{
1399
+ type: "file_read_metadata",
1400
+ category: "data",
1401
+ data: safeString(parts.join(" ")),
1402
+ priority: 3,
1403
+ }];
1404
+ }
1405
+
1406
+ /**
1407
+ * Per-model USD pricing now lives in the curated multi-vendor catalog
1408
+ * (src/pricing/catalog.ts), which prices each model from ITS OWN row across
1409
+ * Anthropic / OpenAI / Google / Chinese / other vendors. This kills the old
1410
+ * bug where the hardcoded Anthropic-only table here billed every non-Claude
1411
+ * model at Claude-Sonnet's `default` rate. Unknown ids now resolve to a null
1412
+ * cost (one console.warn) instead of a silently wrong Claude rate.
1413
+ *
1414
+ * resolveModelId picks the first non-empty model id from the hook candidates;
1415
+ * date-suffixed ids (e.g. claude-haiku-4-5-20251001) are reduced to a catalog
1416
+ * hit by progressively dropping trailing `-segment` suffixes (NO regex).
1417
+ */
1418
+ function resolveModelId(input: HookInput, parsedResp: Record<string, unknown>): string {
1419
+ const candidates: unknown[] = [
1420
+ input.tool_input?.model,
1421
+ (input as unknown as Record<string, unknown>).model,
1422
+ parsedResp.model,
1423
+ ];
1424
+ for (const c of candidates) {
1425
+ if (typeof c === "string" && c.length > 0) return c;
1426
+ }
1427
+ return "";
1428
+ }
1429
+
1430
+ /**
1431
+ * Drop one trailing `-<segment>` from a model id, char-algorithmically (no
1432
+ * regex): walks back to the last '-' and returns the head, or null when there
1433
+ * is no usable separator. Lets a date-suffixed id fall back to its base id
1434
+ * (claude-haiku-4-5-20251001 → claude-haiku-4-5 → … ) one segment at a time.
1435
+ */
1436
+ function dropTrailingSegment(id: string): string | null {
1437
+ for (let i = id.length - 1; i > 0; i--) {
1438
+ if (id.charCodeAt(i) === 45 /* '-' */) return id.slice(0, i);
1439
+ }
1440
+ return null;
1441
+ }
1442
+
1443
+ /**
1444
+ * Resolve a model id to one the catalog can price: try the raw id, then
1445
+ * progressively trim trailing `-segment` suffixes so a date-suffixed id still
1446
+ * prices off its base model. Probes with lookupPrice (no warn) and returns the
1447
+ * first id that hits, or "" on a full miss — so cost compute warns at most once.
1448
+ */
1449
+ function resolveCatalogId(modelId: string): string {
1450
+ let candidate: string | null = modelId;
1451
+ while (candidate && candidate.length > 0) {
1452
+ if (catalogLookupPrice(candidate) !== null) return candidate;
1453
+ candidate = dropTrailingSegment(candidate);
1454
+ }
1455
+ return "";
1456
+ }
1457
+
1458
+ /**
1459
+ * Cost for a turn via the catalog. Returns null on a price miss (catalog emits
1460
+ * one console.warn of the unmatched id) or when all token buckets are zero.
1461
+ */
1462
+ function computeTurnCostUsd(
1463
+ modelId: string,
1464
+ inputTokens: number,
1465
+ outputTokens: number,
1466
+ cacheCreationTokens: number,
1467
+ cacheReadTokens: number,
1468
+ ): number | null {
1469
+ const resolved = resolveCatalogId(modelId);
1470
+ // Feed the resolved id when found; otherwise pass the raw id so the catalog's
1471
+ // single miss-warning carries the id the operator actually saw.
1472
+ return catalogComputeCostUsd(resolved || modelId, {
1473
+ input_tokens: inputTokens,
1474
+ output_tokens: outputTokens,
1475
+ cache_creation_tokens: cacheCreationTokens,
1476
+ cache_read_tokens: cacheReadTokens,
1477
+ });
1478
+ }
1479
+
1480
+ /**
1481
+ * Format a cost to a compact `cost_usd` string, char-algorithmically (no
1482
+ * regex). Renders 6 decimals, drops trailing zeros, and keeps a single `.0`
1483
+ * when the fraction trims to empty (e.g. 0 → "0.0"), matching the prior
1484
+ * `.toFixed(6).replace(...)` output exactly.
1485
+ */
1486
+ function formatCostUsd(cost: number): string {
1487
+ let s = cost.toFixed(6);
1488
+ let end = s.length;
1489
+ while (end > 0 && s.charCodeAt(end - 1) === 48 /* '0' */) end--;
1490
+ s = s.slice(0, end);
1491
+ if (s.length > 0 && s.charCodeAt(s.length - 1) === 46 /* '.' */) s += "0";
1492
+ return s;
1493
+ }
1494
+
1495
+ /**
1496
+ * AgentOutput.usage capture — fires on the Task sub-agent dispatcher.
1497
+ * Captures the 7 cost/perf fields from sdk-tools.d.ts:64-75. Derives
1498
+ * cost_usd from per-model pricing (Gap #1 fix). The platform persists
1499
+ * these as typed columns post-release; the bridge emits them as
1500
+ * structured tokens in event.data for forward-compatible ingestion.
1501
+ */
1502
+ function extractAgentUsage(input: HookInput): SessionEvent[] {
1503
+ if (input.tool_name !== "Task") return [];
1504
+ const resp = input.tool_response;
1505
+ if (typeof resp !== "string" || resp.length === 0) return [];
1506
+
1507
+ let parsed: unknown;
1508
+ try { parsed = JSON.parse(resp); } catch { return []; }
1509
+ if (!parsed || typeof parsed !== "object") return [];
1510
+
1511
+ const out = parsed as Record<string, unknown>;
1512
+ const usage = (out.usage && typeof out.usage === "object")
1513
+ ? out.usage as Record<string, unknown>
1514
+ : {};
1515
+
1516
+ const hasSignal =
1517
+ typeof out.totalTokens === "number" ||
1518
+ typeof out.totalDurationMs === "number" ||
1519
+ typeof usage.input_tokens === "number" ||
1520
+ typeof usage.output_tokens === "number" ||
1521
+ typeof usage.service_tier === "string";
1522
+ if (!hasSignal) return [];
1523
+
1524
+ const parts: string[] = [];
1525
+ if (typeof out.totalTokens === "number") parts.push(`totalTokens:${out.totalTokens}`);
1526
+ if (typeof out.totalDurationMs === "number") parts.push(`totalDurMs:${out.totalDurationMs}`);
1527
+ if (typeof usage.input_tokens === "number") parts.push(`tokens_in:${usage.input_tokens}`);
1528
+ if (typeof usage.output_tokens === "number") parts.push(`tokens_out:${usage.output_tokens}`);
1529
+ if (typeof usage.cache_creation_input_tokens === "number") {
1530
+ parts.push(`cache_create:${usage.cache_creation_input_tokens}`);
1531
+ }
1532
+ if (typeof usage.cache_read_input_tokens === "number") {
1533
+ parts.push(`cache_read:${usage.cache_read_input_tokens}`);
1534
+ }
1535
+ if (typeof usage.service_tier === "string") {
1536
+ parts.push(`tier:${usage.service_tier.slice(0, 32)}`);
1537
+ }
1538
+
1539
+ // CUMULATIVE-USAGE GUARD (docs/handoff/cumulative-cost-bug.md): a Task
1540
+ // tool_response carries the sub-agent's usage SUMMED across its entire run —
1541
+ // every internal turn re-reads the cache, so cache_read reaches the billions.
1542
+ // Pricing that cumulative figure as a single turn produced four-figure
1543
+ // per-event costs ($3,532 with cache_read 4.7B) that poisoned every FinOps
1544
+ // aggregate. We therefore do NOT derive cost_usd here. The raw token counts
1545
+ // stay, tagged usage_scope="task_cumulative", so the platform buckets them as
1546
+ // lifetime spend; real per-turn cost comes only from per-turn signals
1547
+ // (extractTranscriptUsage + each adapter's own session).
1548
+ const modelId = resolveModelId(input, out);
1549
+
1550
+ // Wave 2b — emit structured top-level fields alongside the colon-string so
1551
+ // the forward envelope (which spreads `...event`) hands the platform typed
1552
+ // columns. Each field is set only when its source signal is present, so the
1553
+ // forward payload stays minimal; cost_usd is omitted on a price miss or a
1554
+ // zero-token turn. The colon-string `data` stays for human/debug + back-compat.
1555
+ const event: SessionEvent = {
1556
+ type: "agent_usage",
1557
+ category: "cost",
1558
+ data: safeString(parts.join(" ")),
1559
+ priority: 2,
1560
+ };
1561
+ if (modelId.length > 0) event.model_id = modelId;
1562
+ if (typeof usage.input_tokens === "number") event.input_tokens = usage.input_tokens;
1563
+ if (typeof usage.output_tokens === "number") event.output_tokens = usage.output_tokens;
1564
+ if (typeof usage.cache_read_input_tokens === "number") {
1565
+ event.cache_read_tokens = usage.cache_read_input_tokens;
1566
+ }
1567
+ if (typeof usage.cache_creation_input_tokens === "number") {
1568
+ event.cache_creation_tokens = usage.cache_creation_input_tokens;
1569
+ }
1570
+ event.usage_scope = "task_cumulative";
1571
+
1572
+ return [event];
1573
+ }
1574
+
1575
+ /** Input shape `buildAgentUsageEvent` consumes — re-exported for parser typing. */
1576
+ export interface AgentUsageCounts {
1577
+ model_id: string;
1578
+ input_tokens: number;
1579
+ output_tokens: number;
1580
+ cache_creation_tokens: number;
1581
+ cache_read_tokens: number;
1582
+ native_cost_usd?: number | null;
1583
+ }
1584
+
1585
+ // ── Kimi Code (kimi-code) usage parsers ────────────────────────────────────
1586
+ // Implementation lives in src/adapters/kimi/usage.ts (per adapter ownership);
1587
+ // re-exported here so the hook-reachable session-extract bundle can import the
1588
+ // cursor-gated wire.jsonl reader without a separate per-adapter bundle. The
1589
+ // import is type-only-free (runtime callees buildAgentUsageEvent are hoisted),
1590
+ // so the extract.ts <-> usage.ts cycle is load-order safe.
1591
+
1592
+ // ── Qwen Code (qwen-code) usage parsers ────────────────────────────────────
1593
+ // Implementation lives in src/adapters/qwen-code/usage.ts (per adapter
1594
+ // ownership); re-exported here so the hook-reachable session-extract bundle can
1595
+ // import the cursor-gated chats/<sessionId>.jsonl reader via the shared
1596
+ // loadExtract() loader, exactly like the kimi re-export above. Same load-order
1597
+ // safety: runtime callee buildAgentUsageEvent is hoisted within this module.
1598
+
1599
+ /**
1600
+ * Pi (oh-my-pi) per-turn usage parser.
1601
+ *
1602
+ * Maps a Pi `turn_end` payload (`{ message: AssistantMessage }`) to the
1603
+ * `buildAgentUsageEvent` input shape, or null when there is nothing to record.
1604
+ *
1605
+ * Field provenance (adapter-matrix/pi.md @320261f + cited refs):
1606
+ * - usage: AssistantMessage.usage (ai/src/types.ts:521 -> catalog/src/types.ts:100-145)
1607
+ * - model_id: AssistantMessage.model (ai/src/types.ts:510; kept "provider/model" — builder normalizes)
1608
+ * - input: Usage.input -> input_tokens
1609
+ * - output: Usage.output -> output_tokens
1610
+ * - cacheWrite: Usage.cacheWrite -> cache_creation_tokens
1611
+ * - cacheRead: Usage.cacheRead -> cache_read_tokens
1612
+ * - native USD: Usage.cost.total -> native_cost_usd (HIGH confidence; no price-table needed)
1613
+ *
1614
+ * The event is per-turn incremental (per-response usage; anthropic.ts:1893-1901;
1615
+ * "for the turn" catalog/types.ts:103), so each turn_end maps to exactly one
1616
+ * agent_usage event with no cross-turn accumulation.
1617
+ *
1618
+ * Algorithmic + null-safe, NO regex. Accepts either the full TurnEndEvent
1619
+ * (`{ message }`) or a bare AssistantMessage (`{ usage, model }`) so callers
1620
+ * can pass `event` or `event.message` interchangeably. Returns null when the
1621
+ * payload is not an assistant message, carries no usage object, or every token
1622
+ * bucket is zero/absent (an all-zero turn emits no event — matches
1623
+ * buildAgentUsageEvent's own zero->null contract).
1624
+ */
1625
+ export function parsePiUsage(payload: unknown): AgentUsageCounts | null {
1626
+ if (!payload || typeof payload !== "object") return null;
1627
+ const root = payload as Record<string, unknown>;
1628
+
1629
+ // Unwrap TurnEndEvent.message when present; otherwise treat the payload as
1630
+ // the AssistantMessage itself.
1631
+ const maybeMessage = root.message;
1632
+ const message: Record<string, unknown> =
1633
+ maybeMessage && typeof maybeMessage === "object"
1634
+ ? (maybeMessage as Record<string, unknown>)
1635
+ : root;
1636
+
1637
+ // Only assistant turns carry LLM usage. Custom/non-LLM turns are skipped.
1638
+ // Tolerate a missing role (some payloads omit it) but reject an explicit
1639
+ // non-assistant role.
1640
+ if (typeof message.role === "string" && message.role !== "assistant") {
1641
+ return null;
1642
+ }
1643
+
1644
+ const usageRaw = message.usage;
1645
+ if (!usageRaw || typeof usageRaw !== "object") return null;
1646
+ const usage = usageRaw as Record<string, unknown>;
1647
+
1648
+ const num = (v: unknown): number =>
1649
+ typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0;
1650
+
1651
+ const input_tokens = num(usage.input);
1652
+ const output_tokens = num(usage.output);
1653
+ const cache_creation_tokens = num(usage.cacheWrite);
1654
+ const cache_read_tokens = num(usage.cacheRead);
1655
+
1656
+ // Zero-everything turn → null (mirrors buildAgentUsageEvent's contract; keeps
1657
+ // the DB free of no-op cost events).
1658
+ if (
1659
+ input_tokens <= 0 &&
1660
+ output_tokens <= 0 &&
1661
+ cache_creation_tokens <= 0 &&
1662
+ cache_read_tokens <= 0
1663
+ ) {
1664
+ return null;
1665
+ }
1666
+
1667
+ // Pi-native USD cost lives on usage.cost.total. Preserve it only when finite;
1668
+ // omit (null) on absence so the builder falls back to the pricing catalog.
1669
+ let native_cost_usd: number | null = null;
1670
+ const costRaw = usage.cost;
1671
+ if (costRaw && typeof costRaw === "object") {
1672
+ const total = (costRaw as Record<string, unknown>).total;
1673
+ if (typeof total === "number" && Number.isFinite(total)) {
1674
+ native_cost_usd = total;
1675
+ }
1676
+ }
1677
+
1678
+ const model_id = typeof message.model === "string" ? message.model : "";
1679
+
1680
+ return {
1681
+ model_id,
1682
+ input_tokens,
1683
+ output_tokens,
1684
+ cache_creation_tokens,
1685
+ cache_read_tokens,
1686
+ native_cost_usd,
1687
+ };
1688
+ }
1689
+
1690
+ /**
1691
+ * openclaw `model.usage` diagnostic-event capture — parseOpenclawUsage.
1692
+ *
1693
+ * openclaw exposes a first-class `model.usage` diagnostic event
1694
+ * (`DiagnosticUsageEvent`, refs/platforms/openclaw/src/infra/diagnostic-events.ts:18-47),
1695
+ * emitted once per turn and consumed via `onDiagnosticEvent(listener)`
1696
+ * (diagnostic-events.ts:1156) — the same bus the first-party diagnostics-otel /
1697
+ * diagnostics-prometheus extensions read.
1698
+ *
1699
+ * Field mapping (openclaw → AgentUsageCounts):
1700
+ * evt.usage.input → input_tokens
1701
+ * evt.usage.output → output_tokens
1702
+ * evt.usage.cacheWrite→ cache_creation_tokens (cache-creation)
1703
+ * evt.usage.cacheRead → cache_read_tokens (cache-read)
1704
+ * evt.costUsd → native_cost_usd (pre-computed via estimateUsageCost,
1705
+ * agent-runner.ts:1995 — preferred over catalog)
1706
+ * evt.model → model_id
1707
+ *
1708
+ * CRITICAL: read `evt.usage` (the PER-TURN TOTAL — "Last Turn Total"
1709
+ * agent-runner.ts:943), NEVER `evt.lastCallUsage` (the last-model-call DELTA,
1710
+ * diagnostic-events.ts:34-40). Summing both would double-count.
1711
+ *
1712
+ * Returns AgentUsageCounts (the buildAgentUsageEvent input shape) or null when
1713
+ * the event is not a usage event / carries no usage / sums to zero. Pure,
1714
+ * null-safe, algorithmic — NO regex.
1715
+ */
1716
+ export function parseOpenclawUsage(payload: unknown): AgentUsageCounts | null {
1717
+ if (!payload || typeof payload !== "object") return null;
1718
+ const evt = payload as Record<string, unknown>;
1719
+
1720
+ // Only the `model.usage` diagnostic carries token usage. Tolerate an absent
1721
+ // type (defensive against a thinner payload variant) but reject any explicit
1722
+ // non-usage diagnostic (model.failover, log.record, …).
1723
+ if (typeof evt.type === "string" && evt.type !== "model.usage") {
1724
+ return null;
1725
+ }
1726
+
1727
+ // PER-TURN TOTAL lives on `usage`. `lastCallUsage` is the last-call delta and
1728
+ // must NOT be consumed — reading it instead would understate (or, when summed
1729
+ // with usage, double-count) the turn.
1730
+ const usageRaw = evt.usage;
1731
+ if (!usageRaw || typeof usageRaw !== "object") return null;
1732
+ const usage = usageRaw as Record<string, unknown>;
1733
+
1734
+ const num = (v: unknown): number =>
1735
+ typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0;
1736
+
1737
+ const input_tokens = num(usage.input);
1738
+ const output_tokens = num(usage.output);
1739
+ const cache_creation_tokens = num(usage.cacheWrite);
1740
+ const cache_read_tokens = num(usage.cacheRead);
1741
+
1742
+ // Zero-everything turn → null (mirrors buildAgentUsageEvent's contract; keeps
1743
+ // the DB free of no-op cost events).
1744
+ if (
1745
+ input_tokens <= 0 &&
1746
+ output_tokens <= 0 &&
1747
+ cache_creation_tokens <= 0 &&
1748
+ cache_read_tokens <= 0
1749
+ ) {
1750
+ return null;
1751
+ }
1752
+
1753
+ // openclaw ships a pre-computed USD cost at the TOP LEVEL (`evt.costUsd`, not
1754
+ // nested under usage). Preserve it only when finite; omit (null) on absence so
1755
+ // the builder falls back to the pricing catalog.
1756
+ const costRaw = evt.costUsd;
1757
+ const native_cost_usd: number | null =
1758
+ typeof costRaw === "number" && Number.isFinite(costRaw) ? costRaw : null;
1759
+
1760
+ const model_id = typeof evt.model === "string" ? evt.model : "";
1761
+
1762
+ return {
1763
+ model_id,
1764
+ input_tokens,
1765
+ output_tokens,
1766
+ cache_creation_tokens,
1767
+ cache_read_tokens,
1768
+ native_cost_usd,
1769
+ };
1770
+ }
1771
+
1772
+ /**
1773
+ * opencode per-turn usage parser.
1774
+ *
1775
+ * Ground truth: context-mode-platform/docs/prds/2026-06-paid-observability/
1776
+ * adapter-matrix/opencode.md. opencode tracks usage per *assistant message*; the
1777
+ * usage-bearing payload reaches a plugin via the `message.updated` bus event,
1778
+ * whose `event.properties.info` is the full Message. The assistant token shape
1779
+ * (refs platforms/opencode .../session/message.ts) is:
1780
+ * info.tokens = { input, output, reasoning, cache: { read, write } }
1781
+ * info.cost = USD cost for this message
1782
+ * info.modelID / info.providerID (older refs may expose a single info.model)
1783
+ *
1784
+ * Field mapping (refs message.ts):
1785
+ * tokens.input -> input_tokens
1786
+ * tokens.output -> output_tokens
1787
+ * tokens.cache.read -> cache_read_tokens
1788
+ * tokens.cache.write -> cache_creation_tokens
1789
+ * modelID/providerID -> model_id (`${providerID}/${modelID}` when both present)
1790
+ * cost -> native_cost_usd
1791
+ *
1792
+ * LAST-STEP-SNAPSHOT CAVEAT (refs processor.ts:717-718): message-level
1793
+ * `.tokens` is OVERWRITTEN every step-finish, so it holds the LAST step's usage
1794
+ * — not the turn total. `.cost`, however, ACCUMULATES (`cost += usage.cost`) and
1795
+ * is the correct cumulative turn cost. We therefore pass `info.cost` through as
1796
+ * native_cost_usd so the billed $ is exact even though the token snapshot is
1797
+ * imprecise; the token columns remain best-effort (last-step) telemetry. A true
1798
+ * turn-total token sum would require summing per-step Step.Ended parts, which the
1799
+ * `message.updated` payload does not carry — out of scope for this snapshot-based
1800
+ * capture.
1801
+ *
1802
+ * Accepts either the bus event (`{ properties: { info } }`), the wrapped
1803
+ * `{ event: { properties: { info } } }`, or the bare Message (`info`) so the
1804
+ * caller can hand us whatever the SDK surfaces. NO regex — pure algorithmic,
1805
+ * null-safe traversal. Returns null when the payload is not an assistant
1806
+ * message, carries no tokens object, or every token bucket is zero/absent
1807
+ * (mirrors buildAgentUsageEvent's zero->null contract).
1808
+ */
1809
+ export function parseOpencodeUsage(payload: unknown): AgentUsageCounts | null {
1810
+ if (!payload || typeof payload !== "object") return null;
1811
+ const root = payload as Record<string, unknown>;
1812
+
1813
+ // Unwrap, most-specific first: { event: { properties: { info } } } →
1814
+ // { properties: { info } } → bare message. Each hop is guarded so a missing
1815
+ // layer simply falls through to treating the current object as the message.
1816
+ const eventLayer =
1817
+ root.event && typeof root.event === "object"
1818
+ ? (root.event as Record<string, unknown>)
1819
+ : root;
1820
+ const propsLayer =
1821
+ eventLayer.properties && typeof eventLayer.properties === "object"
1822
+ ? (eventLayer.properties as Record<string, unknown>)
1823
+ : eventLayer;
1824
+ const message: Record<string, unknown> =
1825
+ propsLayer.info && typeof propsLayer.info === "object"
1826
+ ? (propsLayer.info as Record<string, unknown>)
1827
+ : root;
1828
+
1829
+ // Only assistant messages carry token usage. Tolerate a missing role but
1830
+ // reject an explicit non-assistant one.
1831
+ if (typeof message.role === "string" && message.role !== "assistant") {
1832
+ return null;
1833
+ }
1834
+
1835
+ const tokensRaw = message.tokens;
1836
+ if (!tokensRaw || typeof tokensRaw !== "object") return null;
1837
+ const tokens = tokensRaw as Record<string, unknown>;
1838
+
1839
+ const num = (v: unknown): number =>
1840
+ typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0;
1841
+
1842
+ const cacheRaw = tokens.cache;
1843
+ const cache =
1844
+ cacheRaw && typeof cacheRaw === "object"
1845
+ ? (cacheRaw as Record<string, unknown>)
1846
+ : {};
1847
+
1848
+ const input_tokens = num(tokens.input);
1849
+ const output_tokens = num(tokens.output);
1850
+ const cache_read_tokens = num(cache.read);
1851
+ const cache_creation_tokens = num(cache.write);
1852
+
1853
+ // Zero-everything turn → null (keeps the DB free of no-op cost events).
1854
+ if (
1855
+ input_tokens <= 0 &&
1856
+ output_tokens <= 0 &&
1857
+ cache_creation_tokens <= 0 &&
1858
+ cache_read_tokens <= 0
1859
+ ) {
1860
+ return null;
1861
+ }
1862
+
1863
+ // Native cumulative USD cost (preferred — exact, immune to the last-step
1864
+ // token-snapshot imprecision). Omit (null) on absence so the builder falls
1865
+ // back to the pricing catalog over the last-step token columns.
1866
+ const costRaw = message.cost;
1867
+ const native_cost_usd =
1868
+ typeof costRaw === "number" && Number.isFinite(costRaw) ? costRaw : null;
1869
+
1870
+ // Billed model id. Prefer the `${providerID}/${modelID}` pair (how opencode
1871
+ // itself addresses the model); fall back to a bare modelID, then a single
1872
+ // `model` string (older refs shape). Empty when none present.
1873
+ const modelID = typeof message.modelID === "string" ? message.modelID : "";
1874
+ const providerID =
1875
+ typeof message.providerID === "string" ? message.providerID : "";
1876
+ let model_id = "";
1877
+ if (modelID.length > 0) {
1878
+ model_id = providerID.length > 0 ? `${providerID}/${modelID}` : modelID;
1879
+ } else if (typeof message.model === "string") {
1880
+ model_id = message.model;
1881
+ }
1882
+
1883
+ return {
1884
+ model_id,
1885
+ input_tokens,
1886
+ output_tokens,
1887
+ cache_creation_tokens,
1888
+ cache_read_tokens,
1889
+ native_cost_usd,
1890
+ };
1891
+ }
1892
+
1893
+ /**
1894
+ * Build a structured `agent_usage` event from summed per-model token counts.
1895
+ * Emits the colon-string `data` (human/debug + back-compat) AND the structured
1896
+ * top-level fields the forward envelope spreads to the platform. cost_usd via
1897
+ * the pricing catalog — omitted on a price miss. Returns null when every token
1898
+ * bucket is zero/absent (so an all-zero model emits no event).
1899
+ */
1900
+ export function buildAgentUsageEvent(counts: {
1901
+ model_id: string;
1902
+ input_tokens: number;
1903
+ output_tokens: number;
1904
+ cache_creation_tokens: number;
1905
+ cache_read_tokens: number;
1906
+ /**
1907
+ * Provider-supplied USD cost for this turn. When a finite number, it is
1908
+ * preferred over the catalog computation (openclaw / pi / omp / opencode
1909
+ * ship a native cost — trust the source over our price table). Omit/null to
1910
+ * derive cost_usd from the pricing catalog.
1911
+ */
1912
+ native_cost_usd?: number | null;
1913
+ }): SessionEvent | null {
1914
+ const { model_id, input_tokens, output_tokens, cache_creation_tokens, cache_read_tokens, native_cost_usd } = counts;
1915
+ if (input_tokens <= 0 && output_tokens <= 0 && cache_creation_tokens <= 0 && cache_read_tokens <= 0) {
1916
+ return null;
1917
+ }
1918
+
1919
+ const parts: string[] = [`tokens_in:${input_tokens}`, `tokens_out:${output_tokens}`];
1920
+ if (cache_creation_tokens > 0) parts.push(`cache_create:${cache_creation_tokens}`);
1921
+ if (cache_read_tokens > 0) parts.push(`cache_read:${cache_read_tokens}`);
1922
+
1923
+ const cost = (typeof native_cost_usd === "number" && Number.isFinite(native_cost_usd))
1924
+ ? native_cost_usd
1925
+ : computeTurnCostUsd(model_id, input_tokens, output_tokens, cache_creation_tokens, cache_read_tokens);
1926
+ if (cost !== null) parts.push(`cost_usd:${formatCostUsd(cost)}`);
1927
+
1928
+ const event: SessionEvent = {
1929
+ type: "agent_usage",
1930
+ category: "cost",
1931
+ data: safeString(parts.join(" ")),
1932
+ priority: 2,
1933
+ };
1934
+ if (model_id.length > 0) event.model_id = model_id;
1935
+ event.input_tokens = input_tokens;
1936
+ event.output_tokens = output_tokens;
1937
+ if (cache_read_tokens > 0) event.cache_read_tokens = cache_read_tokens;
1938
+ if (cache_creation_tokens > 0) event.cache_creation_tokens = cache_creation_tokens;
1939
+ if (cost !== null) event.cost_usd = cost;
1940
+ return event;
1941
+ }
1942
+
1943
+ /**
1944
+ * gemini-cli AfterModel usage capture — parse ONE AfterModel hook payload into
1945
+ * a builder `agent_usage` event (or null). Pure, null-safe, struct-only — NO regex.
1946
+ *
1947
+ * Refs (docs/prds/2026-06-paid-observability/adapter-matrix/gemini-cli.md):
1948
+ * - AfterModel fires per model call inside the gemini-cli stream loop
1949
+ * (geminiChat.ts:1213); the hook input carries `llm_request` + `llm_response`
1950
+ * (hooks/types.ts:692-695).
1951
+ * - `llm_response.usageMetadata` exposes promptTokenCount / candidatesTokenCount
1952
+ * / totalTokenCount (hookTranslator.ts:60-64).
1953
+ * - model_id = `response.modelVersion || req.model` (loggingContentGenerator.ts:405,553).
1954
+ *
1955
+ * Mapping → builder shape:
1956
+ * promptTokenCount → input_tokens
1957
+ * candidatesTokenCount → output_tokens
1958
+ * thoughtsTokenCount → ADDED into output_tokens (Gemini bills reasoning as output)
1959
+ * cachedContentTokenCount → cache_read_tokens (when present)
1960
+ * model_id → response.modelVersion || llm_request.model
1961
+ *
1962
+ * CAVEAT — the DECOUPLED AfterModel payload (hookTranslator.ts:60-64) forwards
1963
+ * only prompt/candidates/total and DROPS cachedContentTokenCount +
1964
+ * thoughtsTokenCount. We map those two defensively WHEN PRESENT (richer payload
1965
+ * variant / future fix / OTel-fed input) but never depend on them — the common
1966
+ * case is input+output only. For full cached/thoughts fidelity the OTel
1967
+ * `api_response` exporter or the chat-recording JSON is the source of record.
1968
+ *
1969
+ * MULTI-CALL TURNS — one user turn that triggers tool calls spans MULTIPLE
1970
+ * model calls, each AfterModel cumulative within itself. This fn emits ONE
1971
+ * priced event PER AfterModel call (each call is one billed round-trip).
1972
+ * Per-userPromptId summation into a single per-turn total is DEFERRED — emitting
1973
+ * per-call never double-counts, since each call's usageMetadata is the
1974
+ * authoritative total for that call.
1975
+ */
1976
+ export function parseGeminiUsage(afterModelPayload: unknown): SessionEvent | null {
1977
+ if (!afterModelPayload || typeof afterModelPayload !== "object") return null;
1978
+ const payload = afterModelPayload as Record<string, unknown>;
1979
+
1980
+ const resp = payload.llm_response;
1981
+ if (!resp || typeof resp !== "object") return null;
1982
+ const response = resp as Record<string, unknown>;
1983
+
1984
+ const um = response.usageMetadata;
1985
+ if (!um || typeof um !== "object") return null;
1986
+ const usage = um as Record<string, unknown>;
1987
+
1988
+ const num = (v: unknown): number => (typeof v === "number" && Number.isFinite(v) ? v : 0);
1989
+
1990
+ const input = num(usage.promptTokenCount);
1991
+ const candidates = num(usage.candidatesTokenCount);
1992
+ const thoughts = num(usage.thoughtsTokenCount);
1993
+ const cached = num(usage.cachedContentTokenCount);
1994
+ // Gemini bills reasoning (thoughts) as output tokens — fold into output.
1995
+ const output = candidates + thoughts;
1996
+
1997
+ // model_id = response.modelVersion (server-confirmed) || llm_request.model.
1998
+ const req = payload.llm_request;
1999
+ const reqModel =
2000
+ req && typeof req === "object" && typeof (req as Record<string, unknown>).model === "string"
2001
+ ? ((req as Record<string, unknown>).model as string)
2002
+ : "";
2003
+ const modelVersion = typeof response.modelVersion === "string" ? response.modelVersion : "";
2004
+ const modelId = modelVersion.length > 0 ? modelVersion : reqModel;
2005
+
2006
+ // gemini exposes no native cost — cost_usd is derived from the pricing catalog
2007
+ // inside buildAgentUsageEvent (native_cost_usd omitted). All-zero ⇒ null.
2008
+ return buildAgentUsageEvent({
2009
+ model_id: modelId,
2010
+ input_tokens: input,
2011
+ output_tokens: output,
2012
+ cache_creation_tokens: 0,
2013
+ cache_read_tokens: cached,
2014
+ });
2015
+ }
2016
+
2017
+ /**
2018
+ * claude-code MAIN-turn usage capture — the dominant-spend path the Task
2019
+ * subagent capture (extractAgentUsage) misses. Parses the session transcript
2020
+ * JSONL char-algorithmically (NO regex): each `type:"assistant"` line carries
2021
+ * `message.usage` + `message.model`, and usage is a per-turn DELTA, so summing
2022
+ * the assistant turns per model = the exact billed total. `isSidechain:true`
2023
+ * lines are Task-subagent sidechains written to a SEPARATE transcript (refs:
2024
+ * sessionStorage.ts:1042) — excluding them keeps the main-turn sum from
2025
+ * double-counting the separate Task-subagent capture. Emits one structured
2026
+ * `agent_usage` event per distinct model.
2027
+ */
2028
+ export function extractTranscriptUsage(transcript: string): SessionEvent[] {
2029
+ if (typeof transcript !== "string" || transcript.length === 0) return [];
2030
+ const sums = new Map<string, { input: number; output: number; cacheCreate: number; cacheRead: number }>();
2031
+ let start = 0;
2032
+ for (let i = 0; i <= transcript.length; i++) {
2033
+ if (i !== transcript.length && transcript.charCodeAt(i) !== 10 /* \n */) continue;
2034
+ const line = transcript.slice(start, i).trim();
2035
+ start = i + 1;
2036
+ if (line.length === 0) continue;
2037
+ let obj: Record<string, unknown>;
2038
+ try {
2039
+ const p = JSON.parse(line);
2040
+ if (!p || typeof p !== "object") continue;
2041
+ obj = p as Record<string, unknown>;
2042
+ } catch { continue; }
2043
+ if (obj.type !== "assistant" || obj.isSidechain === true) continue;
2044
+ const msg = obj.message;
2045
+ if (!msg || typeof msg !== "object") continue;
2046
+ const m = msg as Record<string, unknown>;
2047
+ const model = typeof m.model === "string" ? m.model : "";
2048
+ if (model.length === 0) continue;
2049
+ const u = m.usage;
2050
+ if (!u || typeof u !== "object") continue;
2051
+ const usage = u as Record<string, unknown>;
2052
+ const cur = sums.get(model) ?? { input: 0, output: 0, cacheCreate: 0, cacheRead: 0 };
2053
+ if (typeof usage.input_tokens === "number") cur.input += usage.input_tokens;
2054
+ if (typeof usage.output_tokens === "number") cur.output += usage.output_tokens;
2055
+ if (typeof usage.cache_creation_input_tokens === "number") cur.cacheCreate += usage.cache_creation_input_tokens;
2056
+ if (typeof usage.cache_read_input_tokens === "number") cur.cacheRead += usage.cache_read_input_tokens;
2057
+ sums.set(model, cur);
2058
+ }
2059
+ const events: SessionEvent[] = [];
2060
+ for (const [model, s] of sums) {
2061
+ const ev = buildAgentUsageEvent({
2062
+ model_id: model,
2063
+ input_tokens: s.input,
2064
+ output_tokens: s.output,
2065
+ cache_creation_tokens: s.cacheCreate,
2066
+ cache_read_tokens: s.cacheRead,
2067
+ });
2068
+ if (ev) events.push(ev);
2069
+ }
2070
+ return events;
2071
+ }
2072
+
2073
+ /**
2074
+ * Cursor-aware variant of extractTranscriptUsage for the Stop hook.
2075
+ *
2076
+ * The transcript grows every turn and the forward loop forwards ALL passed
2077
+ * events unconditionally, so re-running extractTranscriptUsage on the whole
2078
+ * transcript each Stop would double-count every prior turn. This walks only
2079
+ * the turns NEW since the last Stop, keyed by a per-session high-water cursor
2080
+ * (the `uuid` of the last assistant turn seen).
2081
+ *
2082
+ * - sinceUuid null/empty → process ALL non-sidechain assistant turns.
2083
+ * - sinceUuid found → process only turns AFTER it (exclusive).
2084
+ * - sinceUuid set but NOT found (transcript compaction dropped it) → process
2085
+ * ONLY THE LAST non-sidechain assistant turn. Bounded by design: we never
2086
+ * re-emit the whole history when the cursor falls off the front.
2087
+ *
2088
+ * `cursor` returns the uuid of the LAST non-sidechain assistant turn in the
2089
+ * transcript (whether or not it carried usage), so the next Stop resumes
2090
+ * exactly past it. When the transcript has no such turn, the input cursor is
2091
+ * returned unchanged. Same char-algorithmic JSONL parse (NO regex), same
2092
+ * sidechain exclusion, same buildAgentUsageEvent emission path.
2093
+ */
2094
+ export function extractTranscriptUsageSince(
2095
+ transcript: string,
2096
+ sinceUuid: string | null,
2097
+ ): { events: SessionEvent[]; cursor: string | null } {
2098
+ const inputCursor = typeof sinceUuid === "string" && sinceUuid.length > 0 ? sinceUuid : null;
2099
+ if (typeof transcript !== "string" || transcript.length === 0) {
2100
+ return { events: [], cursor: inputCursor };
2101
+ }
2102
+
2103
+ // Pass 1: materialize the ordered non-sidechain assistant turns (uuid + the
2104
+ // usage signal we need). One linear walk, JSON.parse per line, no regex.
2105
+ type Turn = {
2106
+ uuid: string | null;
2107
+ model: string;
2108
+ input: number;
2109
+ output: number;
2110
+ cacheCreate: number;
2111
+ cacheRead: number;
2112
+ };
2113
+ const turns: Turn[] = [];
2114
+ let start = 0;
2115
+ for (let i = 0; i <= transcript.length; i++) {
2116
+ if (i !== transcript.length && transcript.charCodeAt(i) !== 10 /* \n */) continue;
2117
+ const line = transcript.slice(start, i).trim();
2118
+ start = i + 1;
2119
+ if (line.length === 0) continue;
2120
+ let obj: Record<string, unknown>;
2121
+ try {
2122
+ const p = JSON.parse(line);
2123
+ if (!p || typeof p !== "object") continue;
2124
+ obj = p as Record<string, unknown>;
2125
+ } catch { continue; }
2126
+ if (obj.type !== "assistant" || obj.isSidechain === true) continue;
2127
+ const msg = obj.message;
2128
+ if (!msg || typeof msg !== "object") continue;
2129
+ const m = msg as Record<string, unknown>;
2130
+ const model = typeof m.model === "string" ? m.model : "";
2131
+ if (model.length === 0) continue;
2132
+ const uuid = typeof obj.uuid === "string" && obj.uuid.length > 0 ? obj.uuid : null;
2133
+ const u = m.usage;
2134
+ const usage = u && typeof u === "object" ? (u as Record<string, unknown>) : {};
2135
+ turns.push({
2136
+ uuid,
2137
+ model,
2138
+ input: typeof usage.input_tokens === "number" ? usage.input_tokens : 0,
2139
+ output: typeof usage.output_tokens === "number" ? usage.output_tokens : 0,
2140
+ cacheCreate: typeof usage.cache_creation_input_tokens === "number" ? usage.cache_creation_input_tokens : 0,
2141
+ cacheRead: typeof usage.cache_read_input_tokens === "number" ? usage.cache_read_input_tokens : 0,
2142
+ });
2143
+ }
2144
+
2145
+ // No assistant turns at all → nothing to emit, cursor unchanged.
2146
+ if (turns.length === 0) return { events: [], cursor: inputCursor };
2147
+
2148
+ // Cursor always advances to the last assistant turn's uuid (or stays as the
2149
+ // input cursor if that last turn has no uuid).
2150
+ const lastUuid = turns[turns.length - 1].uuid;
2151
+ const cursor = lastUuid !== null ? lastUuid : inputCursor;
2152
+
2153
+ // Select the slice to process.
2154
+ let slice: Turn[];
2155
+ if (inputCursor === null) {
2156
+ slice = turns; // all turns
2157
+ } else {
2158
+ let foundAt = -1;
2159
+ for (let i = 0; i < turns.length; i++) {
2160
+ if (turns[i].uuid === inputCursor) { foundAt = i; break; }
2161
+ }
2162
+ if (foundAt >= 0) {
2163
+ slice = turns.slice(foundAt + 1); // strictly after the cursor
2164
+ } else {
2165
+ // Compaction: cursor fell off the front. Bounded fallback — last turn only.
2166
+ slice = turns.slice(turns.length - 1);
2167
+ }
2168
+ }
2169
+
2170
+ // Sum the selected turns per model and emit via the shared event builder.
2171
+ const sums = new Map<string, { input: number; output: number; cacheCreate: number; cacheRead: number }>();
2172
+ for (const t of slice) {
2173
+ const cur = sums.get(t.model) ?? { input: 0, output: 0, cacheCreate: 0, cacheRead: 0 };
2174
+ cur.input += t.input;
2175
+ cur.output += t.output;
2176
+ cur.cacheCreate += t.cacheCreate;
2177
+ cur.cacheRead += t.cacheRead;
2178
+ sums.set(t.model, cur);
2179
+ }
2180
+ const events: SessionEvent[] = [];
2181
+ for (const [model, s] of sums) {
2182
+ const ev = buildAgentUsageEvent({
2183
+ model_id: model,
2184
+ input_tokens: s.input,
2185
+ output_tokens: s.output,
2186
+ cache_creation_tokens: s.cacheCreate,
2187
+ cache_read_tokens: s.cacheRead,
2188
+ });
2189
+ if (ev) events.push(ev);
2190
+ }
2191
+ return { events, cursor };
2192
+ }
2193
+
2194
+ // ── User-message extractors ────────────────────────────────────────────────
2195
+
2196
+ /**
2197
+ * Category 6: decision
2198
+ * User corrections / approach selections.
2199
+ *
2200
+ * Universal-rule detector (Hybrid C, issue #535):
2201
+ * A decision message typically takes the structural shape
2202
+ * "{negation/rejection} X {separator} Y" — across every human language.
2203
+ *
2204
+ * We treat the following as the structural shape:
2205
+ * - contains a clause separator (ASCII `,` `;`, fullwidth `,` `;`,
2206
+ * Japanese ideographic `、`, Arabic `،`), AND
2207
+ * - codepoint length is in the corrective range (15..500), AND
2208
+ * - the message is not a question (no cross-script `?`), AND
2209
+ * - contains at least one alphabetic codepoint.
2210
+ *
2211
+ * The renderer prints the raw message back to the next LLM, so the gate
2212
+ * only needs to be a coarse "looks like a correction" filter — the LLM
2213
+ * handles fine-grained interpretation. No per-language keyword list.
2214
+ */
2215
+
2216
+ const CLAUSE_SEPARATOR_PATTERN = /[,;,;、،]/u;
2217
+ const DECISION_MIN_CHARS = 15;
2218
+ const DECISION_MAX_CHARS = 500;
2219
+
2220
+ function looksLikeDecision(trimmed: string): boolean {
2221
+ if (QUESTION_MARK_PATTERN.test(trimmed)) return false;
2222
+ if (!ALPHABETIC_PATTERN.test(trimmed)) return false;
2223
+ if (!CLAUSE_SEPARATOR_PATTERN.test(trimmed)) return false;
2224
+ const codepointLength = [...trimmed].length;
2225
+ return codepointLength >= DECISION_MIN_CHARS && codepointLength <= DECISION_MAX_CHARS;
2226
+ }
2227
+
2228
+ function extractUserDecision(message: string): SessionEvent[] {
2229
+ const trimmed = message.trim();
2230
+ if (!looksLikeDecision(trimmed)) return [];
2231
+
2232
+ return [{
2233
+ type: "decision",
2234
+ category: "decision",
2235
+ data: safeString(message),
2236
+ priority: 2,
2237
+ }];
2238
+ }
2239
+
2240
+ /**
2241
+ * Category 7: role
2242
+ * Persona / behavioral directive patterns.
2243
+ *
2244
+ * Universal-rule detector (Hybrid C, issue #535):
2245
+ * A persona/role statement is structurally a single non-question clause
2246
+ * of moderate length containing more than one lexical token — e.g.
2247
+ * "You are a senior engineer", "Tu es développeur",
2248
+ * "あなたは経験豊富なエンジニアです", "Sen kıdemli mühendisisin".
2249
+ *
2250
+ * We treat the following as the structural shape:
2251
+ * - codepoint length is in the persona range (12..120), AND
2252
+ * - is not a question (no cross-script `?`), AND
2253
+ * - is a single clause (no clause separator that would mark it as a
2254
+ * decision), AND
2255
+ * - carries enough lexical density: either two whitespace-separated
2256
+ * runs of letters, OR a continuous Unicode-letter run of ≥6
2257
+ * codepoints (a fallback for scripts without word spaces — Japanese,
2258
+ * Chinese, Thai).
2259
+ *
2260
+ * The renderer prints the raw message back to the next LLM verbatim,
2261
+ * so the gate only needs a coarse "looks like a persona statement"
2262
+ * filter — no per-language keyword list.
2263
+ */
2264
+
2265
+ // Lower bound accommodates information-dense scripts (Chinese, Japanese,
2266
+ // Korean) where a complete persona sentence may use as few as 8 codepoints
2267
+ // — e.g. "你是高级工程师" — while still excluding bare single-token noise.
2268
+ const ROLE_MIN_CHARS = 8;
2269
+ const ROLE_MAX_CHARS = 120;
2270
+ const TWO_LEXICAL_TOKENS_PATTERN = /\p{L}+\s+\p{L}+/u;
2271
+ const CONTINUOUS_LETTER_RUN_PATTERN = /\p{L}{6,}/u;
2272
+
2273
+ // Issue #856 — persona / standing-directive cue gate.
2274
+ //
2275
+ // The structural test below ("two lexical tokens OR a 6-codepoint letter run,
2276
+ // 8..120 chars, no '?', no clause separator") is intentionally coarse and
2277
+ // matches ANY short declarative sentence. That let casual conversational
2278
+ // acknowledgements ("that's fine for now", "go with the second option") freeze
2279
+ // as a priority-3 `role`, which the Pi adapter then re-injected as a standing
2280
+ // behavioral_directive every turn → do-nothing loop.
2281
+ //
2282
+ // A genuine role/behavioral prompt always LEADS with a persona declaration
2283
+ // ("You are X", "Tu es X", "あなたは…", "你是…") or a standing-directive verb
2284
+ // ("always respond…", "act as…"). Casual phrases never do, so we require that
2285
+ // cue as a NECESSARY condition. This preserves legitimate role persistence
2286
+ // (issue #535 multilingual corpus) while killing the casual-phrase loop.
2287
+ //
2288
+ // ALGORITHMIC ONLY — pure lowercase + prefix membership, no regex (project
2289
+ // hard rule). Multilingual openers are matched by `startsWith` on the
2290
+ // normalized first clause; leading conversational filler tokens are stripped
2291
+ // by array operations before the check.
2292
+ const ROLE_FILLER_TOKENS = new Set([
2293
+ "ok", "okay", "sure", "yeah", "yep", "yup", "alright", "fine",
2294
+ "well", "so", "hmm", "right", "please",
2295
+ ]);
2296
+
2297
+ // Second-person persona openers across the supported-language corpus
2298
+ // (issue #535 multilingual role test set) plus common English persona framings.
2299
+ const ROLE_PERSONA_PREFIXES = [
2300
+ "you are", "you're", "your role", "you will be", "you act", "you will act",
2301
+ "act as", "act like", "behave as", "behave like", "imagine you", "pretend you",
2302
+ "assume the role", "take the role", "play the role", "respond as",
2303
+ "tu es", "tu est", "vous etes", "vous êtes", // French
2304
+ "sen ", "siz ", // Turkish (Sen kıdemli…)
2305
+ "eres ", "tú eres", "usted es", // Spanish (Eres…)
2306
+ "ты ", "вы ", // Russian (Ты опытный…)
2307
+ "あなたは", "君は", "お前は", "あなたが", // Japanese (あなたは…)
2308
+ "你是", "您是", // Chinese (你是…)
2309
+ "तुम ", "आप ", "तू ", // Hindi (तुम…)
2310
+ "أنت ", "انت ", "أنتَ ", // Arabic (أنت…)
2311
+ ];
2312
+
2313
+ // Standing-directive verb openers — imperative behavioral rules that should
2314
+ // persist ("always respond in TypeScript", "never use emojis").
2315
+ const ROLE_DIRECTIVE_PREFIXES = [
2316
+ "always ", "never ", "respond ", "reply ", "answer ", "speak ",
2317
+ "write ", "prefer ", "format ", "output ", "communicate ", "use only ",
2318
+ ];
2319
+
2320
+ function hasRoleCue(firstClause: string): boolean {
2321
+ const lower = firstClause.toLowerCase().trim();
2322
+ if (!lower) return false;
2323
+ // Strip leading conversational filler tokens via array ops (no regex).
2324
+ const tokens = lower.split(" ").filter((t) => t.length > 0);
2325
+ while (tokens.length > 0 && ROLE_FILLER_TOKENS.has(tokens[0])) {
2326
+ tokens.shift();
2327
+ }
2328
+ const normalized = tokens.join(" ");
2329
+ if (!normalized) return false;
2330
+ for (const prefix of ROLE_PERSONA_PREFIXES) {
2331
+ if (normalized.startsWith(prefix)) return true;
2332
+ }
2333
+ for (const prefix of ROLE_DIRECTIVE_PREFIXES) {
2334
+ if (normalized.startsWith(prefix)) return true;
2335
+ }
2336
+ return false;
2337
+ }
2338
+
2339
+ function looksLikeRole(trimmed: string): boolean {
2340
+ // Role prompts are persona-prefix shaped: the FIRST SENTENCE declares the
2341
+ // role (e.g. "You are a senior backend engineer. <long context...>").
2342
+ // Apply the structural test to the first clause only — real-world role
2343
+ // prompts often append context paragraphs that would blow the length cap
2344
+ // if we tested the whole message. First-clause shape is the load-bearing
2345
+ // signal across languages (English "You are X.", French "Tu es X.",
2346
+ // Japanese "あなたは X です。" all parse the same way under a period split).
2347
+ const firstClause = trimmed.split(/[.!\n。!]/u)[0].trim();
2348
+ if (QUESTION_MARK_PATTERN.test(firstClause)) return false;
2349
+ if (CLAUSE_SEPARATOR_PATTERN.test(firstClause)) return false;
2350
+ if (!ALPHABETIC_PATTERN.test(firstClause)) return false;
2351
+ const codepointLength = [...firstClause].length;
2352
+ if (codepointLength < ROLE_MIN_CHARS || codepointLength > ROLE_MAX_CHARS) return false;
2353
+ // Issue #856 — require a persona / standing-directive cue so casual
2354
+ // conversational acknowledgements do not freeze as a role directive.
2355
+ if (!hasRoleCue(firstClause)) return false;
2356
+ return (
2357
+ TWO_LEXICAL_TOKENS_PATTERN.test(firstClause) ||
2358
+ CONTINUOUS_LETTER_RUN_PATTERN.test(firstClause)
2359
+ );
2360
+ }
2361
+
2362
+ function extractRole(message: string): SessionEvent[] {
2363
+ const trimmed = message.trim();
2364
+ if (!looksLikeRole(trimmed)) return [];
2365
+
2366
+ return [{
2367
+ type: "role",
2368
+ category: "role",
2369
+ data: safeString(message),
2370
+ priority: 3,
2371
+ }];
2372
+ }
2373
+
2374
+ /**
2375
+ * Category 13: intent
2376
+ * Session mode classification from user messages.
2377
+ *
2378
+ * Universal-rule detector (Hybrid C, issue #535):
2379
+ * investigate — message contains a question mark from any script:
2380
+ * ASCII `?` U+003F, fullwidth `?` U+FF1F, Arabic `؟` U+061F,
2381
+ * Spanish opening `¿` U+00BF.
2382
+ * (Greek `;` U+037E and Armenian `՞` U+055E are excluded —
2383
+ * Greek shares its codepoint with ASCII semicolon, which
2384
+ * would produce false positives across the corpus.)
2385
+ *
2386
+ * Structural / Unicode-aware — no per-language keyword list.
2387
+ */
2388
+
2389
+ const QUESTION_MARK_PATTERN = /[??؟¿]/u;
2390
+
2391
+ /**
2392
+ * "Imperative tone" structural heuristic for implement intent:
2393
+ * - trimmed length < IMPERATIVE_MAX_CHARS codepoints (short directive,
2394
+ * not a discursive paragraph)
2395
+ * - contains no question mark from any script
2396
+ * - contains at least one alphabetic codepoint (filters pure punctuation noise)
2397
+ *
2398
+ * `[...str]` walks Unicode codepoints so CJK / Indic scripts are measured
2399
+ * fairly against the budget rather than penalised by UTF-16 unit count.
2400
+ */
2401
+ const ALPHABETIC_PATTERN = /\p{L}/u;
2402
+ const IMPERATIVE_MAX_CHARS = 60;
2403
+
2404
+ function isImperativeTone(trimmed: string): boolean {
2405
+ if (QUESTION_MARK_PATTERN.test(trimmed)) return false;
2406
+ if (!ALPHABETIC_PATTERN.test(trimmed)) return false;
2407
+ const codepointLength = [...trimmed].length;
2408
+ return codepointLength > 0 && codepointLength < IMPERATIVE_MAX_CHARS;
2409
+ }
2410
+
2411
+ function extractIntent(message: string): SessionEvent[] {
2412
+ const trimmed = message.trim();
2413
+ if (!trimmed) return [];
2414
+
2415
+ let mode: string | undefined;
2416
+
2417
+ if (QUESTION_MARK_PATTERN.test(trimmed)) {
2418
+ mode = "investigate";
2419
+ } else if (isImperativeTone(trimmed)) {
2420
+ mode = "implement";
2421
+ }
2422
+
2423
+ if (!mode) return [];
2424
+
2425
+ return [{
2426
+ type: "intent",
2427
+ category: "intent",
2428
+ data: safeString(mode),
2429
+ priority: 4,
2430
+ }];
2431
+ }
2432
+
2433
+ /**
2434
+ * Category: session goal (objective).
2435
+ *
2436
+ * Captures the user's stated objective so it survives compaction and resume —
2437
+ * unlike `intent`, which stores only the coarse mode (investigate/implement)
2438
+ * and discards the goal text. Triggered by the `/goal <text>` command or an
2439
+ * explicit `goal:` / `objective:` marker, so the FULL goal text is preserved
2440
+ * (priority 4 = critical in the DB eviction contract) and restored at the top
2441
+ * of the resume snapshot.
2442
+ * Without this, a `/goal` directive is lost across compaction/resume.
2443
+ */
2444
+ const GOAL_DIRECTIVE_PATTERN =
2445
+ /^(?:\/goal\s+|(?:goal|objective)\s*:\s*)(.+)$/is;
2446
+
2447
+ function extractGoal(message: string): SessionEvent[] {
2448
+ const trimmed = message.trim();
2449
+ if (!trimmed) return [];
2450
+ const match = trimmed.match(GOAL_DIRECTIVE_PATTERN);
2451
+ if (!match) return [];
2452
+ const goalText = match[1].trim();
2453
+ if (!goalText) return [];
2454
+ return [{
2455
+ type: "goal",
2456
+ category: "goal",
2457
+ data: safeString(goalText),
2458
+ priority: 4,
2459
+ }];
2460
+ }
2461
+
2462
+ /**
2463
+ * Category 25: blocked-on
2464
+ * Detect when work is blocked on something, or when a blocker is resolved.
2465
+ *
2466
+ * Universal-rule detector (Hybrid C, issue #535):
2467
+ * Programming-domain error markers are script-agnostic — they are
2468
+ * emitted by tooling regardless of the user's spoken language. The
2469
+ * words "Error", "Exception", "Traceback" stay in their original
2470
+ * English form inside a Chinese / Arabic / Russian terminal log.
2471
+ *
2472
+ * blocker matches:
2473
+ * - the literal "Error:" / "Exception:" / "Traceback" tokens, OR
2474
+ * - a Python-style frame line ("File ", `line:col`), OR
2475
+ * - a JS / Java-style stack frame ("at <ident>(...)" with a
2476
+ * `:line:col` suffix).
2477
+ *
2478
+ * blocker_resolved matches:
2479
+ * - a Unicode check-mark glyph (✓ U+2713, ✔ U+2714, ✅ U+2705,
2480
+ * ☑ U+2611, 🎉 U+1F389), OR
2481
+ * - the structural marker "fixed: …" / "resolved: …" — these are
2482
+ * programming-domain conventions (git log, PR titles, CHANGELOG
2483
+ * entries) rather than natural-language phrases.
2484
+ */
2485
+
2486
+ const BLOCKER_MARKERS_PATTERN = /(?:\bError\s*:|\bException\s*:|\bTraceback\b|\bat\s+\S+\s*\([^)]*:\d+:\d+\))/u;
2487
+ const BLOCKER_RESOLVED_CHECKMARK_PATTERN = /[✓✔✅☑🎉]/u;
2488
+ const BLOCKER_RESOLVED_MARKER_PATTERN = /^\s*(?:fixed|resolved)\s*:/iu;
2489
+
2490
+ function extractBlocker(message: string): SessionEvent[] {
2491
+ const events: SessionEvent[] = [];
2492
+
2493
+ // Resolution takes precedence — if both shapes match, render the
2494
+ // happier signal so the snapshot reflects the latest state.
2495
+ const isResolved =
2496
+ BLOCKER_RESOLVED_CHECKMARK_PATTERN.test(message) ||
2497
+ BLOCKER_RESOLVED_MARKER_PATTERN.test(message);
2498
+ if (isResolved) {
2499
+ events.push({
2500
+ type: "blocker_resolved",
2501
+ category: "blocked-on",
2502
+ data: safeString(message),
2503
+ priority: 2,
2504
+ });
2505
+ return events;
2506
+ }
2507
+
2508
+ if (BLOCKER_MARKERS_PATTERN.test(message)) {
2509
+ events.push({
2510
+ type: "blocker",
2511
+ category: "blocked-on",
2512
+ data: safeString(message),
2513
+ priority: 2,
2514
+ });
2515
+ }
2516
+
2517
+ return events;
2518
+ }
2519
+
2520
+ /**
2521
+ * Category 12: data
2522
+ * Large user-pasted data references (message > 1KB).
2523
+ */
2524
+ function extractData(message: string): SessionEvent[] {
2525
+ if (message.length <= 1024) return [];
2526
+
2527
+ return [{
2528
+ type: "data",
2529
+ category: "data",
2530
+ data: safeString(message),
2531
+ priority: 4,
2532
+ }];
2533
+ }
2534
+
2535
+ // ── Cross-event stateful extractors ───────────────────────────────────────
2536
+
2537
+ /**
2538
+ * Category 23: error-resolution
2539
+ * Detects when an error is followed by a successful fix (cross-event state).
2540
+ */
2541
+
2542
+ let lastError: { tool: string; error: string; callsSince: number } | null = null;
2543
+
2544
+ function extractErrorResolution(input: HookInput): SessionEvent[] {
2545
+ const { tool_name, tool_response } = input;
2546
+ const response = String(tool_response ?? "");
2547
+
2548
+ // If this call is an error, store it and return
2549
+ if (isToolError(input)) {
2550
+ lastError = { tool: tool_name, error: response.slice(0, 200), callsSince: 0 };
2551
+ return [];
2552
+ }
2553
+
2554
+ // No pending error → nothing to resolve
2555
+ if (!lastError) return [];
2556
+
2557
+ // Increment staleness counter
2558
+ lastError.callsSince++;
2559
+
2560
+ // Timeout: clear after 10 calls without resolution
2561
+ if (lastError.callsSince > 10) {
2562
+ lastError = null;
2563
+ return [];
2564
+ }
2565
+
2566
+ const callSucceeded = !isToolError(input);
2567
+ if (!callSucceeded) return [];
2568
+
2569
+ // Check if this is a resolution: same tool, or Edit/Write after a Read error
2570
+ const sameTool = tool_name === lastError.tool;
2571
+ const editAfterReadError =
2572
+ lastError.tool === "Read"
2573
+ && (tool_name === "Edit" || tool_name === "Write" || tool_name === "apply_patch");
2574
+
2575
+ if (sameTool || editAfterReadError) {
2576
+ const event: SessionEvent = {
2577
+ type: "error_resolved",
2578
+ category: "error-resolution",
2579
+ data: safeString(`Error in ${lastError.tool}: ${lastError.error} → Fixed`),
2580
+ priority: 2,
2581
+ };
2582
+ lastError = null;
2583
+ return [event];
2584
+ }
2585
+
2586
+ return [];
2587
+ }
2588
+
2589
+ /** Reset error-resolution state (for testing). */
2590
+ export function resetErrorResolutionState(): void {
2591
+ lastError = null;
2592
+ }
2593
+
2594
+ /**
2595
+ * Category 26: iteration-loop
2596
+ * Detects when the same tool is called repeatedly with similar input (stuck loop).
2597
+ */
2598
+
2599
+ const callHistory: Array<{ tool: string; inputHash: string }> = [];
2600
+
2601
+ function simpleHash(str: string): string {
2602
+ return `${str.length}:${str.slice(0, 20)}`;
2603
+ }
2604
+
2605
+ function extractIterationLoop(input: HookInput): SessionEvent[] {
2606
+ const { tool_name, tool_input } = input;
2607
+ const inputHash = simpleHash(JSON.stringify(tool_input).slice(0, 200));
2608
+
2609
+ callHistory.push({ tool: tool_name, inputHash });
2610
+
2611
+ // Keep history bounded
2612
+ if (callHistory.length > 50) {
2613
+ callHistory.splice(0, callHistory.length - 50);
2614
+ }
2615
+
2616
+ // Check last N entries for repeated pattern (minimum 3)
2617
+ if (callHistory.length < 3) return [];
2618
+
2619
+ let count = 0;
2620
+ for (let i = callHistory.length - 1; i >= 0; i--) {
2621
+ if (callHistory[i].tool === tool_name && callHistory[i].inputHash === inputHash) {
2622
+ count++;
2623
+ } else {
2624
+ break;
2625
+ }
2626
+ }
2627
+
2628
+ if (count >= 3) {
2629
+ // Reset the matching tail to avoid duplicate emissions
2630
+ callHistory.splice(callHistory.length - count);
2631
+ return [{
2632
+ type: "retry_detected",
2633
+ category: "iteration-loop",
2634
+ data: safeString(`${tool_name} called ${count} times with similar input`),
2635
+ priority: 2,
2636
+ }];
2637
+ }
2638
+
2639
+ return [];
2640
+ }
2641
+
2642
+ /** Reset iteration-loop state (for testing). */
2643
+ export function resetIterationLoopState(): void {
2644
+ callHistory.length = 0;
2645
+ }
2646
+
2647
+ // ── Public API ─────────────────────────────────────────────────────────────
2648
+
2649
+ /**
2650
+ * Map platform-native tool names (Qwen Code, Gemini CLI, OpenCode, etc.) to the
2651
+ * canonical Claude Code names this extractor branches on. Without this, Qwen's
2652
+ * `run_shell_command` events would silently produce zero git/cwd/env extractions.
2653
+ *
2654
+ * Evidence: refs/platforms/qwen-code/packages/core/src/tools/tool-names.ts
2655
+ */
2656
+ const TOOL_NAME_NORMALIZE: Record<string, string> = {
2657
+ // Qwen Code / Gemini CLI native names
2658
+ run_shell_command: "Bash",
2659
+ read_file: "Read",
2660
+ read_many_files: "Read",
2661
+ grep_search: "Grep",
2662
+ search_file_content: "Grep",
2663
+ web_fetch: "WebFetch",
2664
+ write_file: "Write",
2665
+ edit: "Edit",
2666
+ glob: "Glob",
2667
+ todo_write: "TodoWrite",
2668
+ ask_user_question: "AskUserQuestion",
2669
+ list_directory: "LS",
2670
+ save_memory: "Memory",
2671
+ skill: "Skill",
2672
+ exit_plan_mode: "ExitPlanMode",
2673
+ agent: "Agent",
2674
+ // OpenCode native names
2675
+ bash: "Bash",
2676
+ view: "Read",
2677
+ grep: "Grep",
2678
+ fetch: "WebFetch",
2679
+ // Codex CLI
2680
+ shell: "Bash",
2681
+ shell_command: "Bash",
2682
+ exec_command: "Bash",
2683
+ "container.exec": "Bash",
2684
+ local_shell: "Bash",
2685
+ grep_files: "Grep",
2686
+ // Antigravity CLI (`agy`) native names. Keep in sync with the two other agy
2687
+ // maps: hooks/antigravity-cli/payload.mjs (normalizeAgyToolName) and
2688
+ // hooks/core/routing.mjs (TOOL_ALIASES).
2689
+ run_command: "Bash",
2690
+ view_file: "Read",
2691
+ read_url_content: "WebFetch",
2692
+ list_dir: "LS",
2693
+ search_web: "WebSearch",
2694
+ };
2695
+
2696
+ function normalizeHookInput(input: HookInput): HookInput {
2697
+ const normalized = TOOL_NAME_NORMALIZE[input.tool_name];
2698
+ if (!normalized || normalized === input.tool_name) return input;
2699
+ return { ...input, tool_name: normalized };
2700
+ }
2701
+
2702
+ /**
2703
+ * Extract session events from a PostToolUse hook input.
2704
+ *
2705
+ * Accepts the raw hook JSON shape (snake_case keys) as received from stdin.
2706
+ * Returns an array of zero or more SessionEvents. Never throws.
2707
+ */
2708
+ export function extractEvents(rawInput: HookInput): SessionEvent[] {
2709
+ try {
2710
+ const input = normalizeHookInput(rawInput);
2711
+ const events: SessionEvent[] = [];
2712
+
2713
+ // File + Rule (handles Read/Edit/Write)
2714
+ events.push(...extractFileAndRule(input));
2715
+
2716
+ // Bash-based extractors (may overlap on the same command)
2717
+ events.push(...extractCwd(input));
2718
+ events.push(...extractError(input));
2719
+ events.push(...extractGit(input));
2720
+ events.push(...extractEnv(input));
2721
+
2722
+ // Tool-specific extractors
2723
+ events.push(...extractTask(input));
2724
+ events.push(...extractPlan(input));
2725
+ events.push(...extractSkill(input));
2726
+ events.push(...extractSubagent(input));
2727
+ events.push(...extractMcp(input));
2728
+ events.push(...extractMcpToolCall(input));
2729
+ events.push(...extractDecision(input));
2730
+ events.push(...extractConstraint(input));
2731
+ events.push(...extractWorktree(input));
2732
+ events.push(...extractWebFetchMetadata(input));
2733
+ events.push(...extractBashOutcome(input));
2734
+ events.push(...extractFileReadMetadata(input));
2735
+ events.push(...extractAgentUsage(input));
2736
+ events.push(...extractAgentFinding(input));
2737
+ events.push(...extractExternalRef(input));
2738
+
2739
+ // Cross-event stateful extractors
2740
+ events.push(...extractErrorResolution(input));
2741
+ events.push(...extractIterationLoop(input));
2742
+
2743
+ return events;
2744
+ } catch {
2745
+ // Graceful degradation: if extraction fails, session continues normally
2746
+ return [];
2747
+ }
2748
+ }
2749
+
2750
+ /**
2751
+ * Extract session events from a UserPromptSubmit hook input (user message text).
2752
+ *
2753
+ * Handles: decision, role, intent, data categories.
2754
+ * Returns an array of zero or more SessionEvents. Never throws.
2755
+ */
2756
+ export function extractUserEvents(message: string): SessionEvent[] {
2757
+ try {
2758
+ const events: SessionEvent[] = [];
2759
+
2760
+ events.push(...extractUserPlan(message));
2761
+ events.push(...extractUserDecision(message));
2762
+ events.push(...extractRole(message));
2763
+ events.push(...extractIntent(message));
2764
+ events.push(...extractGoal(message));
2765
+ events.push(...extractBlocker(message));
2766
+ events.push(...extractData(message));
2767
+
2768
+ return events;
2769
+ } catch {
2770
+ return [];
2771
+ }
2772
+ }
2773
+
2774
+ /**
2775
+ * Issue #4 (new PRD) — SessionStart settings + MCP servers snapshot.
2776
+ *
2777
+ * Emits ONE session_settings_snapshot event when ≥1 setting is available
2778
+ * on the SessionStart input. The data field carries key:value tokens
2779
+ * (mcp_count, mcp_servers, model, permission_mode) so the platform can
2780
+ * compute MCP integration counts and primary-model adoption per org.
2781
+ * mcp_servers list is truncated to first 8 names.
2782
+ */
2783
+ export function extractSessionSettings(input: unknown): SessionEvent[] {
2784
+ if (!input || typeof input !== "object") return [];
2785
+
2786
+ const obj = input as Record<string, unknown>;
2787
+ const parts: string[] = [];
2788
+
2789
+ const mcpServers = obj.mcp_servers;
2790
+ let mcpKeys: string[] | null = null;
2791
+ if (mcpServers && typeof mcpServers === "object" && !Array.isArray(mcpServers)) {
2792
+ mcpKeys = Object.keys(mcpServers as Record<string, unknown>);
2793
+ parts.push(`mcp_count:${mcpKeys.length}`);
2794
+ if (mcpKeys.length > 0) {
2795
+ parts.push(`mcp_servers:${mcpKeys.slice(0, 8).join(",")}`);
2796
+ }
2797
+ }
2798
+
2799
+ if (typeof obj.model === "string") {
2800
+ parts.push(`model:${obj.model.slice(0, 64)}`);
2801
+ }
2802
+
2803
+ if (typeof obj.permission_mode === "string") {
2804
+ parts.push(`permission_mode:${obj.permission_mode.slice(0, 32)}`);
2805
+ }
2806
+
2807
+ if (parts.length === 0) return [];
2808
+
2809
+ return [{
2810
+ type: "session_settings_snapshot",
2811
+ category: "env",
2812
+ data: safeString(parts.join(" ")),
2813
+ priority: 2,
2814
+ }];
2815
+ }
2816
+
2817
+ /**
2818
+ * §11 Layer 1 + Layer 3 — multilingual prompt features.
2819
+ *
2820
+ * Reference: context-mode-platform/docs/prds/2026-06-insight-data-flow/
2821
+ * 11-multilingual-prompt-algorithm.md
2822
+ *
2823
+ * Script-agnostic via Unicode property regex (`\p{L}`, `\p{Lu}`,
2824
+ * `\p{Script=X}`). No per-language tables, no franc/fasttext deps.
2825
+ * Layer 1 returns 10 numeric/string features; Layer 3 appends a
2826
+ * `prompt_word_tokens: string[]` array for the platform's streaming
2827
+ * word-frequency UPSERT.
2828
+ *
2829
+ * Privacy: features carry no prose. Layer 3 tokens are deduped
2830
+ * letter-only words ≥3 chars; platform aggregates by (org_id, week,
2831
+ * word) so no individual token surfaces in UI.
2832
+ */
2833
+ export interface PromptFeatures {
2834
+ prompt_length: number;
2835
+ prompt_word_count: number;
2836
+ prompt_uppercase_ratio: number;
2837
+ prompt_file_ref_count: number;
2838
+ prompt_path_ref_count: number;
2839
+ prompt_script_primary: string | null;
2840
+ prompt_script_count: number;
2841
+ prompt_question_glyph_count: number;
2842
+ prompt_code_block_count: number;
2843
+ prompt_url_count: number;
2844
+ prompt_word_tokens: string[];
2845
+ }
2846
+
2847
+ const PROMPT_SCRIPT_NAMES = [
2848
+ "Latin", "Cyrillic", "Arabic", "Han", "Hangul",
2849
+ "Hiragana", "Katakana", "Devanagari", "Hebrew", "Thai", "Greek",
2850
+ ] as const;
2851
+
2852
+ const EMPTY_PROMPT_FEATURES: PromptFeatures = {
2853
+ prompt_length: 0,
2854
+ prompt_word_count: 0,
2855
+ prompt_uppercase_ratio: 0,
2856
+ prompt_file_ref_count: 0,
2857
+ prompt_path_ref_count: 0,
2858
+ prompt_script_primary: null,
2859
+ prompt_script_count: 0,
2860
+ prompt_question_glyph_count: 0,
2861
+ prompt_code_block_count: 0,
2862
+ prompt_url_count: 0,
2863
+ prompt_word_tokens: [],
2864
+ };
2865
+
2866
+ /**
2867
+ * Verbatim mirror of §11 Layer 1 reference implementation + Layer 3
2868
+ * token extraction. Uses Unicode property regex per the spec — the
2869
+ * "no regex" project default does NOT apply here because the spec
2870
+ * explicitly mandates `\p{Script=X}` for script-agnostic classification.
2871
+ */
2872
+ export function extractUserPromptFeatures(prompt: unknown): PromptFeatures {
2873
+ if (typeof prompt !== "string" || prompt.length === 0) {
2874
+ return { ...EMPTY_PROMPT_FEATURES, prompt_word_tokens: [] };
2875
+ }
2876
+
2877
+ const letters = prompt.match(/\p{L}+/gu) ?? [];
2878
+ const upperCount = (prompt.match(/\p{Lu}/gu) ?? []).length;
2879
+ const totalLetters = letters.join("").length;
2880
+ const fences = (prompt.match(/```/g) ?? []).length;
2881
+
2882
+ const scripts: Record<string, number> = {};
2883
+ for (const name of PROMPT_SCRIPT_NAMES) {
2884
+ const re = new RegExp(`\\p{Script=${name}}`, "gu");
2885
+ const n = (prompt.match(re) ?? []).length;
2886
+ if (n > 0) scripts[name] = n;
2887
+ }
2888
+ const primary =
2889
+ Object.entries(scripts).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null;
2890
+
2891
+ const seen = new Set<string>();
2892
+ const tokens: string[] = [];
2893
+ for (const word of letters) {
2894
+ if (word.length < 3) continue;
2895
+ const lower = word.toLowerCase();
2896
+ if (seen.has(lower)) continue;
2897
+ seen.add(lower);
2898
+ tokens.push(lower);
2899
+ }
2900
+
2901
+ return {
2902
+ prompt_length: prompt.length,
2903
+ prompt_word_count: letters.length,
2904
+ prompt_uppercase_ratio: totalLetters === 0 ? 0 : upperCount / totalLetters,
2905
+ prompt_file_ref_count: (prompt.match(/(\w+\/)+\w+\.\w+/g) ?? []).length,
2906
+ prompt_path_ref_count: (prompt.match(/\.{0,2}\/[\w\/.-]+/g) ?? []).length,
2907
+ prompt_script_primary: primary,
2908
+ prompt_script_count: Object.keys(scripts).length,
2909
+ prompt_question_glyph_count: (prompt.match(/[??؟]/gu) ?? []).length,
2910
+ prompt_code_block_count: Math.floor(fences / 2),
2911
+ prompt_url_count: (prompt.match(/https?:\/\/[^\s]+/gu) ?? []).length,
2912
+ prompt_word_tokens: tokens,
2913
+ };
2914
+ }
2915
+
2916
+ /**
2917
+ * UserPromptSubmit-driven `/plan` slash detector.
2918
+ *
2919
+ * Compensates for Claude Code Bug #15660: programmatic EnterPlanMode tool
2920
+ * calls fire PostToolUse, but the `/plan` slash command and Shift+Tab do
2921
+ * NOT. Shift+Tab is unrecoverable from the OSS bridge without an upstream
2922
+ * SDK change; this detector handles the slash case.
2923
+ *
2924
+ * Algorithmic (no regex): tolerate leading whitespace, require lowercase
2925
+ * "/plan", reject longer slashes like "/plans" via the next-char check.
2926
+ */
2927
+ function extractUserPlan(message: string): SessionEvent[] {
2928
+ if (typeof message !== "string" || message.length === 0) return [];
2929
+
2930
+ let i = 0;
2931
+ while (i < message.length) {
2932
+ const c = message.charCodeAt(i);
2933
+ if (c !== 32 && c !== 9) break;
2934
+ i++;
2935
+ }
2936
+
2937
+ if (i + 5 > message.length) return [];
2938
+ if (message.slice(i, i + 5) !== "/plan") return [];
2939
+
2940
+ if (i + 5 < message.length) {
2941
+ const next = message.charCodeAt(i + 5);
2942
+ const isWordBoundary =
2943
+ next === 32 || next === 9 || next === 10 || next === 13;
2944
+ if (!isWordBoundary) return [];
2945
+ }
2946
+
2947
+ const arg = message.slice(i + 5).trim();
2948
+ const detail = arg.length > 0
2949
+ ? `plan via /plan slash: ${arg.slice(0, 120)}`
2950
+ : "plan via /plan slash";
2951
+
2952
+ return [{
2953
+ type: "plan_enter",
2954
+ category: "plan",
2955
+ data: safeString(detail),
2956
+ priority: 2,
2957
+ }];
2958
+ }