@ken-jo/agent-connector 0.1.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 (203) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +6 -0
  3. package/README.md +348 -0
  4. package/dist/amp-QSFH2V7Y.js +217 -0
  5. package/dist/amp-QSFH2V7Y.js.map +1 -0
  6. package/dist/amp-TULUPXXL.js +237 -0
  7. package/dist/amp-TULUPXXL.js.map +1 -0
  8. package/dist/antigravity-CX2YLSY7.js +17 -0
  9. package/dist/antigravity-CX2YLSY7.js.map +1 -0
  10. package/dist/antigravity-STHZWMP3.js +171 -0
  11. package/dist/antigravity-STHZWMP3.js.map +1 -0
  12. package/dist/antigravity-cli-P6HADOAO.js +121 -0
  13. package/dist/antigravity-cli-P6HADOAO.js.map +1 -0
  14. package/dist/antigravity-cli-YQDFVV4U.js +86 -0
  15. package/dist/antigravity-cli-YQDFVV4U.js.map +1 -0
  16. package/dist/chunk-54EMKTTX.js +191 -0
  17. package/dist/chunk-54EMKTTX.js.map +1 -0
  18. package/dist/chunk-7L6ITC4T.js +54 -0
  19. package/dist/chunk-7L6ITC4T.js.map +1 -0
  20. package/dist/chunk-7MSDGHJW.js +316 -0
  21. package/dist/chunk-7MSDGHJW.js.map +1 -0
  22. package/dist/chunk-BCHWFTV4.js +196 -0
  23. package/dist/chunk-BCHWFTV4.js.map +1 -0
  24. package/dist/chunk-DBQMX75U.js +36 -0
  25. package/dist/chunk-DBQMX75U.js.map +1 -0
  26. package/dist/chunk-EXLS7BSI.js +29 -0
  27. package/dist/chunk-EXLS7BSI.js.map +1 -0
  28. package/dist/chunk-JNM3TPLX.js +593 -0
  29. package/dist/chunk-JNM3TPLX.js.map +1 -0
  30. package/dist/chunk-JWNT5KW7.js +197 -0
  31. package/dist/chunk-JWNT5KW7.js.map +1 -0
  32. package/dist/chunk-KHO5WNTP.js +30 -0
  33. package/dist/chunk-KHO5WNTP.js.map +1 -0
  34. package/dist/chunk-LTT56GI3.js +155 -0
  35. package/dist/chunk-LTT56GI3.js.map +1 -0
  36. package/dist/chunk-MEH7GC7R.js +111 -0
  37. package/dist/chunk-MEH7GC7R.js.map +1 -0
  38. package/dist/chunk-MQPNU2CY.js +64 -0
  39. package/dist/chunk-MQPNU2CY.js.map +1 -0
  40. package/dist/chunk-OPXAP3AC.js +12 -0
  41. package/dist/chunk-OPXAP3AC.js.map +1 -0
  42. package/dist/chunk-RK6VBLXP.js +50 -0
  43. package/dist/chunk-RK6VBLXP.js.map +1 -0
  44. package/dist/chunk-TIIP3RG2.js +420 -0
  45. package/dist/chunk-TIIP3RG2.js.map +1 -0
  46. package/dist/chunk-TRKWUNO4.js +702 -0
  47. package/dist/chunk-TRKWUNO4.js.map +1 -0
  48. package/dist/chunk-TRQKHP7D.js +93 -0
  49. package/dist/chunk-TRQKHP7D.js.map +1 -0
  50. package/dist/chunk-WCETQWWK.js +59 -0
  51. package/dist/chunk-WCETQWWK.js.map +1 -0
  52. package/dist/chunk-WV63X7IK.js +357 -0
  53. package/dist/chunk-WV63X7IK.js.map +1 -0
  54. package/dist/chunk-XD7MY6HB.js +343 -0
  55. package/dist/chunk-XD7MY6HB.js.map +1 -0
  56. package/dist/chunk-XNAM7F35.js +276 -0
  57. package/dist/chunk-XNAM7F35.js.map +1 -0
  58. package/dist/chunk-XUCWLJY5.js +238 -0
  59. package/dist/chunk-XUCWLJY5.js.map +1 -0
  60. package/dist/chunk-YNZU6PAV.js +800 -0
  61. package/dist/chunk-YNZU6PAV.js.map +1 -0
  62. package/dist/chunk-YT43MUSJ.js +146 -0
  63. package/dist/chunk-YT43MUSJ.js.map +1 -0
  64. package/dist/claude-code-HKDV7T32.js +637 -0
  65. package/dist/claude-code-HKDV7T32.js.map +1 -0
  66. package/dist/claude-code-W74MNTAC.js +652 -0
  67. package/dist/claude-code-W74MNTAC.js.map +1 -0
  68. package/dist/cli/sdk.d.ts +54 -0
  69. package/dist/cli/sdk.js +82 -0
  70. package/dist/cli/sdk.js.map +1 -0
  71. package/dist/cli.d.ts +2 -0
  72. package/dist/cli.js +15 -0
  73. package/dist/cli.js.map +1 -0
  74. package/dist/codebuff-3PMZJJHP.js +307 -0
  75. package/dist/codebuff-3PMZJJHP.js.map +1 -0
  76. package/dist/codebuff-QX57FJDN.js +220 -0
  77. package/dist/codebuff-QX57FJDN.js.map +1 -0
  78. package/dist/codex-JFQTS6LU.js +593 -0
  79. package/dist/codex-JFQTS6LU.js.map +1 -0
  80. package/dist/codex-Q3ATRRX3.js +364 -0
  81. package/dist/codex-Q3ATRRX3.js.map +1 -0
  82. package/dist/copilot-cli-MTCGHZ2T.js +622 -0
  83. package/dist/copilot-cli-MTCGHZ2T.js.map +1 -0
  84. package/dist/copilot-cli-SJGIXVSD.js +369 -0
  85. package/dist/copilot-cli-SJGIXVSD.js.map +1 -0
  86. package/dist/crush-I7PK3FGI.js +360 -0
  87. package/dist/crush-I7PK3FGI.js.map +1 -0
  88. package/dist/crush-LN5QFFR2.js +183 -0
  89. package/dist/crush-LN5QFFR2.js.map +1 -0
  90. package/dist/cursor-4TMXKJOZ.js +603 -0
  91. package/dist/cursor-4TMXKJOZ.js.map +1 -0
  92. package/dist/cursor-QZ6MTO74.js +194 -0
  93. package/dist/cursor-QZ6MTO74.js.map +1 -0
  94. package/dist/detect-WIAGVYS4.js +68 -0
  95. package/dist/detect-WIAGVYS4.js.map +1 -0
  96. package/dist/doctor-EZW2K4NI.js +372 -0
  97. package/dist/doctor-EZW2K4NI.js.map +1 -0
  98. package/dist/droid-KN6VRMMT.js +424 -0
  99. package/dist/droid-KN6VRMMT.js.map +1 -0
  100. package/dist/droid-W5WF5XEX.js +224 -0
  101. package/dist/droid-W5WF5XEX.js.map +1 -0
  102. package/dist/gemini-cli-CIRW37TU.js +369 -0
  103. package/dist/gemini-cli-CIRW37TU.js.map +1 -0
  104. package/dist/gemini-cli-Y35FFK4M.js +705 -0
  105. package/dist/gemini-cli-Y35FFK4M.js.map +1 -0
  106. package/dist/goose-A3M5GODH.js +212 -0
  107. package/dist/goose-A3M5GODH.js.map +1 -0
  108. package/dist/goose-ZTGTSUFJ.js +480 -0
  109. package/dist/goose-ZTGTSUFJ.js.map +1 -0
  110. package/dist/hermes-H2KV44GK.js +470 -0
  111. package/dist/hermes-H2KV44GK.js.map +1 -0
  112. package/dist/hermes-ZYLMOFLZ.js +196 -0
  113. package/dist/hermes-ZYLMOFLZ.js.map +1 -0
  114. package/dist/hook-YVDILAMZ.js +75 -0
  115. package/dist/hook-YVDILAMZ.js.map +1 -0
  116. package/dist/index.d.ts +22 -0
  117. package/dist/index.js +10 -0
  118. package/dist/index.js.map +1 -0
  119. package/dist/install-HQRYZOQ2.js +60 -0
  120. package/dist/install-HQRYZOQ2.js.map +1 -0
  121. package/dist/jetbrains-copilot-HWA3DMH7.js +633 -0
  122. package/dist/jetbrains-copilot-HWA3DMH7.js.map +1 -0
  123. package/dist/kilo-NSWAVP6P.js +235 -0
  124. package/dist/kilo-NSWAVP6P.js.map +1 -0
  125. package/dist/kilo-QXJRCSLT.js +384 -0
  126. package/dist/kilo-QXJRCSLT.js.map +1 -0
  127. package/dist/kilo-cli-EAQTHXUW.js +587 -0
  128. package/dist/kilo-cli-EAQTHXUW.js.map +1 -0
  129. package/dist/kilo-cli-EVBKUODA.js +160 -0
  130. package/dist/kilo-cli-EVBKUODA.js.map +1 -0
  131. package/dist/kimi-EI3UM3ZV.js +155 -0
  132. package/dist/kimi-EI3UM3ZV.js.map +1 -0
  133. package/dist/kimi-GQ7VXNYT.js +423 -0
  134. package/dist/kimi-GQ7VXNYT.js.map +1 -0
  135. package/dist/kiro-UCLSLBW2.js +217 -0
  136. package/dist/kiro-UCLSLBW2.js.map +1 -0
  137. package/dist/kiro-VQTT6LO2.js +451 -0
  138. package/dist/kiro-VQTT6LO2.js.map +1 -0
  139. package/dist/leaderboard-K6ON3SWW.js +137 -0
  140. package/dist/leaderboard-K6ON3SWW.js.map +1 -0
  141. package/dist/mux-T2TV4CIQ.js +211 -0
  142. package/dist/mux-T2TV4CIQ.js.map +1 -0
  143. package/dist/mux-ZMLVAXOO.js +96 -0
  144. package/dist/mux-ZMLVAXOO.js.map +1 -0
  145. package/dist/omp-PB4VDKS6.js +586 -0
  146. package/dist/omp-PB4VDKS6.js.map +1 -0
  147. package/dist/openclaw-ETN2M63O.js +751 -0
  148. package/dist/openclaw-ETN2M63O.js.map +1 -0
  149. package/dist/openclaw-IYA7ASL6.js +150 -0
  150. package/dist/openclaw-IYA7ASL6.js.map +1 -0
  151. package/dist/opencode-FZ33JKUZ.js +734 -0
  152. package/dist/opencode-FZ33JKUZ.js.map +1 -0
  153. package/dist/opencode-HWT3RSMN.js +216 -0
  154. package/dist/opencode-HWT3RSMN.js.map +1 -0
  155. package/dist/package-DLOVE2E4.js +1132 -0
  156. package/dist/package-DLOVE2E4.js.map +1 -0
  157. package/dist/pi-CIU2QHT4.js +208 -0
  158. package/dist/pi-CIU2QHT4.js.map +1 -0
  159. package/dist/pi-UFX2OYFV.js +139 -0
  160. package/dist/pi-UFX2OYFV.js.map +1 -0
  161. package/dist/qwen-code-5POCNU6P.js +573 -0
  162. package/dist/qwen-code-5POCNU6P.js.map +1 -0
  163. package/dist/qwen-code-W7NUCDEN.js +134 -0
  164. package/dist/qwen-code-W7NUCDEN.js.map +1 -0
  165. package/dist/roo-code-IOIUXRDE.js +242 -0
  166. package/dist/roo-code-IOIUXRDE.js.map +1 -0
  167. package/dist/roo-code-ZLKH4A7N.js +229 -0
  168. package/dist/roo-code-ZLKH4A7N.js.map +1 -0
  169. package/dist/runtime/index.d.ts +157 -0
  170. package/dist/runtime/index.js +20 -0
  171. package/dist/runtime/index.js.map +1 -0
  172. package/dist/serve-HVWWY4B6.js +65 -0
  173. package/dist/serve-HVWWY4B6.js.map +1 -0
  174. package/dist/status-FE7TECZD.js +128 -0
  175. package/dist/status-FE7TECZD.js.map +1 -0
  176. package/dist/synthetic-UKR6SMGS.js +178 -0
  177. package/dist/synthetic-UKR6SMGS.js.map +1 -0
  178. package/dist/telemetry-36GESKQQ.js +349 -0
  179. package/dist/telemetry-36GESKQQ.js.map +1 -0
  180. package/dist/trae-JSNDZFKL.js +204 -0
  181. package/dist/trae-JSNDZFKL.js.map +1 -0
  182. package/dist/trae-PA26DPBW.js +157 -0
  183. package/dist/trae-PA26DPBW.js.map +1 -0
  184. package/dist/types-CYUB1OTr.d.ts +427 -0
  185. package/dist/uninstall-IGCKNOSF.js +72 -0
  186. package/dist/uninstall-IGCKNOSF.js.map +1 -0
  187. package/dist/upgrade-JV2VK242.js +104 -0
  188. package/dist/upgrade-JV2VK242.js.map +1 -0
  189. package/dist/usage-6ER6EMEY.js +324 -0
  190. package/dist/usage-6ER6EMEY.js.map +1 -0
  191. package/dist/usage-event-JKBI6XCF.js +48 -0
  192. package/dist/usage-event-JKBI6XCF.js.map +1 -0
  193. package/dist/vscode-copilot-CK3NO54M.js +715 -0
  194. package/dist/vscode-copilot-CK3NO54M.js.map +1 -0
  195. package/dist/warp-JNQA7PBU.js +126 -0
  196. package/dist/warp-JNQA7PBU.js.map +1 -0
  197. package/dist/warp-QNVDXOG4.js +199 -0
  198. package/dist/warp-QNVDXOG4.js.map +1 -0
  199. package/dist/zed-NNNX5MNT.js +272 -0
  200. package/dist/zed-NNNX5MNT.js.map +1 -0
  201. package/dist/zed-VRJKWYUR.js +209 -0
  202. package/dist/zed-VRJKWYUR.js.map +1 -0
  203. package/package.json +79 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/telemetry/measure.ts","../src/runtime/hook-entrypoint.ts","../src/runtime/serve.ts","../src/telemetry/calibration.ts","../src/telemetry/proxy.ts","../src/runtime/usage-event.ts"],"sourcesContent":["/**\n * telemetry/measure — pure measurement helpers over a single MCP tool call.\n *\n * The framework tokenizes its OWN bytes: the tool-call arguments going in, the\n * tool result coming out, and the fixed tool-definition schemas. These helpers\n * turn those into {@link TokenCount}s using the default {@link Tokenizer}.\n *\n * Honesty rules:\n * • Binary modalities (image/audio/resource blobs) are NOT tokenized — base64\n * would massively over-count. Each gets a flat per-modality estimate, and\n * because that estimate is itself an approximation the combined confidence\n * is pulled down to at least \"tokenizer-approx\".\n * • When combining several counts, the reported confidence is the WORST\n * (least-confident) of the inputs — never report \"exact\" for a mixed bag.\n *\n * Everything here is pure: no IO, no mutation of inputs.\n */\n\nimport { getTokenizer } from \"./tokenizer.js\";\nimport { worstConfidence } from \"./types.js\";\nimport type {\n ConfidenceSource,\n ModelFamily,\n TokenCount,\n Tokenizer,\n} from \"./types.js\";\n\n/** Per-call measurement: tokens in, tokens out, and combined confidence. */\nexport interface ToolCallMeasurement {\n inputTokens: number;\n outputTokens: number;\n source: ConfidenceSource;\n}\n\n/**\n * Flat token estimates for non-text content blocks. These mirror common host\n * accounting (an image tile is roughly ~85 tokens at low detail); they are\n * deliberately coarse — we never tokenize the underlying base64 payload.\n */\nconst MODALITY_ESTIMATE: Record<string, number> = {\n image: 85,\n audio: 85,\n resource: 85,\n};\n/** Fallback estimate for an unknown non-text block type. */\nconst UNKNOWN_BLOCK_ESTIMATE = 85;\n\n// Confidence ordering + the worst-of comparison live in ./types (the single\n// source of truth, imported as `worstConfidence` above). Re-exported here so\n// callers that already import `worstConfidence` from this module keep working\n// as a new ConfidenceSource value (e.g. tokenizer-calibrated) slots into the\n// shared ordering.\nexport { worstConfidence };\n\n/** Reduce a list of sources to the single worst (least-confident) one. */\nfunction combineSources(sources: readonly ConfidenceSource[]): ConfidenceSource {\n // Default to the most-confident floor so an empty list combines to the only\n // other source it is paired with; in practice callers always pass ≥1 source.\n let worst: ConfidenceSource = \"host-native\";\n for (const s of sources) worst = worstConfidence(worst, s);\n return worst;\n}\n\n// ── Structural shapes we read from a tool result (kept local + narrow) ───────\n\n/** A text content block: `{ type: \"text\", text: \"...\" }`. */\ninterface TextBlock {\n type: \"text\";\n text?: unknown;\n}\n/** Any content block; only text blocks expose a `text` field we tokenize. */\ninterface ContentBlock {\n type?: unknown;\n text?: unknown;\n}\n/** The portion of an MCP tool result we measure. */\ninterface ToolResultLike {\n content?: unknown;\n structuredContent?: unknown;\n}\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null;\n}\n\nfunction isTextBlock(block: ContentBlock): block is TextBlock {\n return block.type === \"text\";\n}\n\n/**\n * Measure one tool call.\n *\n * Input = canonical JSON of `args`.\n * Output = tokens over the TEXTUAL parts of `result`:\n * • If `result.content` is an array of blocks, text blocks are tokenized via\n * their `text` field and non-text blocks add a flat per-modality estimate\n * (no base64 tokenization).\n * • `result.structuredContent`, when present, is tokenized as canonical JSON.\n * • Anything else (string / arbitrary object) is tokenized as canonical JSON.\n *\n * The reported `source` is the worst of the input and output sources.\n */\nexport function measureToolCall(\n args: unknown,\n result: unknown,\n family: ModelFamily,\n tok: Tokenizer = getTokenizer(),\n): ToolCallMeasurement {\n const input = tok.countValue(args, family);\n const output = measureResult(result, family, tok);\n return {\n inputTokens: input.tokens,\n outputTokens: output.tokens,\n source: worstConfidence(input.source, output.source),\n };\n}\n\n/** Tokenize the textual + structured parts of a tool result. */\nfunction measureResult(\n result: unknown,\n family: ModelFamily,\n tok: Tokenizer,\n): TokenCount {\n if (!isObject(result)) {\n // Plain string or scalar result — count its canonical form directly.\n return tok.countValue(result, family);\n }\n\n const res = result as ToolResultLike;\n const sources: ConfidenceSource[] = [];\n let tokens = 0;\n\n if (Array.isArray(res.content)) {\n for (const raw of res.content) {\n if (!isObject(raw)) continue;\n const block = raw as ContentBlock;\n if (isTextBlock(block)) {\n const text = typeof block.text === \"string\" ? block.text : \"\";\n const c = tok.count(text, family);\n tokens += c.tokens;\n sources.push(c.source);\n } else {\n // image / audio / resource / unknown → flat estimate, no base64 BPE.\n const key = typeof block.type === \"string\" ? block.type : \"\";\n tokens += MODALITY_ESTIMATE[key] ?? UNKNOWN_BLOCK_ESTIMATE;\n // A flat estimate is an approximation, never \"exact\".\n sources.push(\"tokenizer-approx\");\n }\n }\n } else if (res.content !== undefined) {\n // content present but not an array (e.g. a bare string) → count it whole.\n const c = tok.countValue(res.content, family);\n tokens += c.tokens;\n sources.push(c.source);\n }\n\n if (res.structuredContent !== undefined) {\n const c = tok.countValue(res.structuredContent, family);\n tokens += c.tokens;\n sources.push(c.source);\n }\n\n // Nothing measurable found → count the whole object as a fallback so we never\n // silently report zero for a non-empty result.\n if (sources.length === 0) {\n return tok.countValue(result, family);\n }\n\n return { tokens, source: combineSources(sources) };\n}\n\n/**\n * Measure the fixed tool-definition overhead: tokenize the JSON of the entire\n * `tools/list` array once. `tools` is the raw array of tool descriptors as the\n * server advertises them (shape is host/SDK-specific, so it is treated as\n * opaque JSON here).\n */\nexport function measureToolDefs(\n tools: readonly unknown[],\n family: ModelFamily,\n tok: Tokenizer = getTokenizer(),\n): TokenCount {\n return tok.countValue(tools, family);\n}\n\n/**\n * Measure one RUNTIME hook dispatch (the new `hook` developer-axis surface).\n *\n * Input = canonical JSON of the inbound normalized event payload the handler\n * reads (the host-provided fields: toolInput / prompt / raw / etc.).\n * Output = canonical JSON of what the handler RETURNS that becomes context or a\n * decision the host consumes (additionalContext / updatedInput / reason\n * and the rest of the normalized {@link HookResponse}).\n *\n * Uses the SAME tokenizer + worst-of confidence combination as the proxy. Pure:\n * no IO, no mutation. The two values are tokenized whole (a hook payload has no\n * binary content blocks to special-case, unlike a tool result).\n */\nexport function measureHook(\n eventPayload: unknown,\n handlerReturn: unknown,\n family: ModelFamily,\n tok: Tokenizer = getTokenizer(),\n): ToolCallMeasurement {\n const input = tok.countValue(eventPayload, family);\n const output = tok.countValue(handlerReturn, family);\n return {\n inputTokens: input.tokens,\n outputTokens: output.tokens,\n source: worstConfidence(input.source, output.source),\n };\n}\n","/**\n * runtime/hook-entrypoint — the universal json-stdio hook dispatcher.\n *\n * Every json-stdio host points its hook config at the single stable home binary\n * (`<homeBin> hook <platformId> <event> --connector <id>`, built by\n * core/spawn.buildHomeBinHookCommand). The CLI reads stdin and calls\n * {@link runHook} with the parsed flags + the raw stdin string. This module:\n *\n * 1. Loads the registered connector (live handlers) and the host adapter.\n * 2. Parses the host's stdin payload into a normalized event via the adapter.\n * 3. Finds the connector's handler for the event, honoring the tool matcher.\n * 4. Runs the handler, normalizes its return, and formats the adapter's native\n * reply.\n *\n * Fail-open is the safety contract: ANY error degrades to exit 0 (\"allow\") so a\n * framework or handler bug can never wedge a host's tool call — EXCEPT when the\n * event is PreToolUse and the handler explicitly denied, in which case the deny\n * (a deliberate security decision) is preserved rather than swallowed.\n */\n\nimport type {\n HookEventName,\n HookResponse,\n PlatformId,\n ResolvedConnector,\n} from \"../core/types.js\";\nimport { log } from \"../core/logger.js\";\nimport { loadRegisteredConnector } from \"../core/load-connector.js\";\nimport { loadAdapter, REGISTERED_PLATFORM_IDS } from \"../adapters/registry.js\";\nimport type { NormalizedEvent } from \"../adapters/spi.js\";\nimport { projectIdentity } from \"../core/paths.js\";\nimport { measureHook } from \"../telemetry/measure.js\";\nimport { openStore, newRecordId } from \"../telemetry/store.js\";\nimport { getTokenizer, inferModelFamily } from \"../telemetry/tokenizer.js\";\n\n/** Flags + stdin the CLI hands to {@link runHook}. */\nexport interface RunHookOptions {\n /** Host platform id from the hook command (`hook <platformId> ...`). */\n platformId: string;\n /** Canonical lifecycle event name from the hook command. */\n event: HookEventName;\n /** Connector id from `--connector <id>`. */\n connectorId: string;\n /** Raw stdin payload (host-native JSON). Empty string is tolerated → `{}`. */\n stdin: string;\n}\n\n/** Process-level result the CLI translates into exit code + stdout/stderr. */\nexport interface RunHookResult {\n exitCode: number;\n stdout?: string;\n stderr?: string;\n}\n\n/** A pass-through \"allow\" reply with exit 0 and no payload. */\nconst ALLOW: RunHookResult = { exitCode: 0 };\n\n/** Does a normalized event carry a tool name (only tool events do)? */\nfunction eventToolName(evt: NormalizedEvent): string | undefined {\n const name = (evt as { toolName?: unknown }).toolName;\n return typeof name === \"string\" ? name : undefined;\n}\n\n/**\n * Tolerantly parse the host's stdin payload. Empty / whitespace-only input is a\n * legitimate \"no payload\" signal from some hosts and resolves to `{}`. Malformed\n * JSON also degrades to `{}` rather than throwing — fail-open is the contract.\n */\nfunction parseStdin(stdin: string): unknown {\n const trimmed = stdin.trim();\n if (trimmed === \"\") return {};\n try {\n return JSON.parse(trimmed);\n } catch {\n return {};\n }\n}\n\n/**\n * Compile the connector's matcher (a regex string) for a tool event. A missing\n * or empty matcher matches everything (returns null → no filtering). An invalid\n * regex degrades to \"match everything\" so a typo never blocks tool calls.\n */\nfunction compileMatcher(matcher: string | undefined): RegExp | null {\n if (!matcher || matcher === \"\") return null;\n try {\n return new RegExp(matcher);\n } catch {\n return null;\n }\n}\n\n/** Normalize a handler return (void → allow) into a concrete HookResponse. */\nfunction normalizeResponse(value: HookResponse | void): HookResponse {\n if (value == null || typeof value !== \"object\") return { decision: \"allow\" };\n return value;\n}\n\n/**\n * Resolve the host platform to stamp on a hook telemetry row. Mirrors the serve\n * `--host` plumbing: the install-target platform id is baked into the hook\n * command (`hook <platformId> <event> …`) so `opts.platformId` is authoritative,\n * but an explicit env override (AGENT_CONNECTOR_HOST) wins when it names a known\n * platform. Falls back to the event's adapter-stamped hostPlatform, then\n * \"unknown\" — never throws.\n */\nfunction resolveHookHostPlatform(\n platformId: string,\n evt: NormalizedEvent,\n): PlatformId {\n const override = process.env.AGENT_CONNECTOR_HOST;\n if (\n override !== undefined &&\n REGISTERED_PLATFORM_IDS.has(override as PlatformId)\n ) {\n return override as PlatformId;\n }\n if (REGISTERED_PLATFORM_IDS.has(platformId as PlatformId)) {\n return platformId as PlatformId;\n }\n const fromEvent = (evt as { hostPlatform?: unknown }).hostPlatform;\n if (\n typeof fromEvent === \"string\" &&\n REGISTERED_PLATFORM_IDS.has(fromEvent as PlatformId)\n ) {\n return fromEvent as PlatformId;\n }\n return \"unknown\";\n}\n\n/**\n * Record one RUNTIME hook dispatch as a `hook` developer-axis telemetry row.\n *\n * input = the inbound normalized event payload the handler reads;\n * output = the normalized {@link HookResponse} the handler returned (the part\n * that becomes host context/decision: additionalContext/updatedInput/\n * reason/…). Tokenized with the SAME tokenizer the proxy uses.\n *\n * MUST be fail-open (the hook runtime is fail-open by contract): any error here\n * is swallowed so a measurement bug can NEVER break a host's hook. Honors the\n * AGENT_CONNECTOR_TELEMETRY=0 kill switch (skips entirely; the store's append is\n * already a no-op under it, but we also skip the tokenize work).\n */\nfunction recordHookTelemetry(\n opts: RunHookOptions,\n connector: ResolvedConnector,\n evt: NormalizedEvent,\n response: HookResponse,\n): void {\n if (process.env.AGENT_CONNECTOR_TELEMETRY === \"0\") return;\n try {\n const family = inferModelFamily(\"\", connector.telemetry.modelFamilyHint);\n const measurement = measureHook(evt, response, family, getTokenizer());\n\n const sessionId =\n typeof (evt as { sessionId?: unknown }).sessionId === \"string\"\n ? ((evt as { sessionId: string }).sessionId)\n : \"\";\n const evtProjectDir = (evt as { projectDir?: unknown }).projectDir;\n const projectDir =\n typeof evtProjectDir === \"string\" && evtProjectDir !== \"\"\n ? evtProjectDir\n : process.cwd();\n const id = projectIdentity(projectDir);\n\n const store = openStore({});\n try {\n store.append({\n id: newRecordId(0),\n ts: Date.now(),\n connectorId: opts.connectorId,\n toolName: opts.event, // for a hook row the per-item name IS the event\n scope: \"hook\",\n surfaceKind: \"hook\",\n hostPlatform: resolveHookHostPlatform(opts.platformId, evt),\n sessionId,\n projectKey: id.key,\n projectDir: id.dir,\n inputTokens: measurement.inputTokens,\n outputTokens: measurement.outputTokens,\n confidenceSource: measurement.source,\n isError: false,\n });\n } finally {\n store.close();\n }\n } catch {\n // Fail-open: a telemetry error must NEVER break the hook runtime.\n }\n}\n\n/**\n * Dispatch one host hook invocation. Always resolves (never rejects): every\n * failure path returns a concrete {@link RunHookResult} so the CLI can exit\n * cleanly. See the module header for the fail-open contract.\n */\nexport async function runHook(opts: RunHookOptions): Promise<RunHookResult> {\n const { platformId, event, connectorId, stdin } = opts;\n\n try {\n const connector = await loadRegisteredConnector(connectorId);\n const adapter = await loadAdapter(platformId);\n\n // mcp-only hosts (and any adapter without runtime dispatch) cannot parse a\n // hook payload — nothing to do, allow.\n if (!adapter || !adapter.parseEvent || !adapter.formatReply) {\n return ALLOW;\n }\n\n const raw = parseStdin(stdin);\n const evt = adapter.parseEvent(event, raw);\n // The hook command carries the authoritative connector id; stamp it on the\n // event so handlers see the connector they were dispatched for.\n evt.connectorId = connectorId;\n\n const definition = connector.hooks[event];\n if (!definition || typeof definition.handler !== \"function\") {\n // The connector declares no handler for this event — allow.\n return ALLOW;\n }\n\n // Tool-event matcher: if set and the event's tool name does not match, allow\n // (the hook is simply not interested in this tool).\n const toolName = eventToolName(evt);\n if (toolName !== undefined) {\n const re = compileMatcher(definition.matcher);\n if (re && !re.test(toolName)) return ALLOW;\n }\n\n // Run the handler. Its return is normalized (void → allow) and handed to the\n // adapter to render the host-native reply.\n const handlerResult = await definition.handler(\n // The adapter parsed `evt` as exactly this event's payload type; the\n // HooksConfig handler for the same event expects that payload.\n evt as never,\n );\n const response = normalizeResponse(handlerResult);\n\n // Developer-axis telemetry for the RUNTIME `hook` surface. Fail-open: never\n // lets a measurement error break the hook (handled inside the helper).\n recordHookTelemetry(opts, connector, evt, response);\n\n const reply = adapter.formatReply(event, response);\n return {\n exitCode: reply.exitCode,\n ...(reply.stdout !== undefined ? { stdout: reply.stdout } : {}),\n ...(reply.stderr !== undefined ? { stderr: reply.stderr } : {}),\n };\n } catch (err) {\n // Fail-open: a framework/handler error must not wedge the host's tool call.\n // The ONE exception is a PreToolUse deny — a deliberate block we honor even\n // if a later step threw. We re-derive that decision defensively from the\n // adapter so a throw AFTER the deny still surfaces it.\n const message = err instanceof Error ? err.message : String(err);\n log.error(`hook ${platformId}/${event} (${connectorId}) failed:`, message);\n return failOpenOrPreserveDeny(opts, message);\n }\n}\n\n/**\n * Error path. Returns fail-open allow, UNLESS this is a PreToolUse event whose\n * handler explicitly denied — in which case the deny is reconstructed and\n * preserved (a security decision is never silently downgraded to allow).\n *\n * Best-effort: if anything in the deny reconstruction itself throws, we fall\n * back to allow (we never escalate an error into a spurious block).\n */\nasync function failOpenOrPreserveDeny(\n opts: RunHookOptions,\n errorMessage: string,\n): Promise<RunHookResult> {\n if (opts.event !== \"PreToolUse\") return ALLOW;\n try {\n const connector = await loadRegisteredConnector(opts.connectorId);\n const adapter = await loadAdapter(opts.platformId);\n if (!adapter?.parseEvent || !adapter.formatReply) return ALLOW;\n\n const definition = connector.hooks.PreToolUse;\n if (!definition || typeof definition.handler !== \"function\") return ALLOW;\n\n const raw = parseStdin(opts.stdin);\n const evt = adapter.parseEvent(\"PreToolUse\", raw);\n evt.connectorId = opts.connectorId;\n\n const toolName = eventToolName(evt);\n if (toolName !== undefined) {\n const re = compileMatcher(definition.matcher);\n if (re && !re.test(toolName)) return ALLOW;\n }\n\n const response = normalizeResponse(await definition.handler(evt as never));\n if (response.decision !== \"deny\") return ALLOW;\n\n const reply = adapter.formatReply(\"PreToolUse\", response);\n return {\n exitCode: reply.exitCode,\n ...(reply.stdout !== undefined ? { stdout: reply.stdout } : {}),\n ...(reply.stderr !== undefined\n ? { stderr: reply.stderr }\n : { stderr: errorMessage }),\n };\n } catch {\n // Reconstruction failed — never escalate an internal error into a block.\n return ALLOW;\n }\n}\n","/**\n * runtime/serve — the `agent-connector serve` telemetry-wrapping entrypoint.\n *\n * When a stdio MCP server opts into transparent telemetry, its host config is\n * rewritten (by the adapter, via core/spawn.buildServeWrapperCommand) to launch\n * <homeBin> serve --connector <id> -- <realCommand> <realArgs...>\n * instead of the server directly. The CLI parses those flags and calls\n * {@link runServe}, which stands up the per-session telemetry context (store,\n * tokenizer, project identity, host detection) and hands off to the proxy.\n *\n * The proxy (telemetry/proxy.runServeProxy) forwards bytes VERBATIM in both\n * directions and measures aggregate per-tool token counts out of band, so this\n * wrapper is transparent to both the host and the real server. It resolves with\n * the child server's exit code, which the CLI uses as its own.\n */\n\nimport { randomUUID } from \"node:crypto\";\n\nimport { detectRuntimeHost } from \"../adapters/detect.js\";\nimport { REGISTERED_PLATFORM_IDS } from \"../adapters/registry.js\";\nimport { loadRegisteredConnector } from \"../core/load-connector.js\";\nimport { projectIdentity } from \"../core/paths.js\";\nimport { detectLaunchMethod } from \"../core/spawn.js\";\nimport type { PlatformId } from \"../core/types.js\";\nimport { runServeProxy } from \"../telemetry/proxy.js\";\nimport { openStore } from \"../telemetry/store.js\";\nimport { getTokenizer } from \"../telemetry/tokenizer.js\";\nimport type { TelemetryInstallScope } from \"../telemetry/types.js\";\n\n/** Flags the CLI hands to {@link runServe}. */\nexport interface RunServeOptions {\n /** Connector id from `--connector <id>`; selects telemetry config + stamps records. */\n connectorId: string;\n /** The real MCP server executable to spawn (everything after `--`). */\n serverCommand: string;\n /** Arguments passed to that executable. */\n serverArgs: string[];\n /**\n * Install scope from `--scope <user|project>`. OPTIONAL: absent for configs\n * written before scope plumbing existed — left unstamped so older rows read\n * as \"unknown\". Stamped verbatim onto every telemetry record when present.\n */\n installScope?: TelemetryInstallScope;\n /**\n * Install TARGET platform id from `--host <platformId>` (baked into the\n * wrapper at install time). OPTIONAL: when a recognized platform id, it\n * OVERRIDES runtime env detection so headless spawns stamp hostPlatform\n * correctly (detectRuntimeHost only knows env markers for a few hosts and\n * otherwise mis-attributes). Absent/unrecognized → fall back to detection.\n */\n hostPlatformOverride?: PlatformId;\n}\n\n/**\n * Launch the developer's real MCP server under the telemetry-wrapping proxy.\n *\n * Resolves with the child server's exit code (propagated as this process's exit\n * code by the CLI). The session id comes from AGENT_CONNECTOR_SESSION when the\n * host sets it (empty otherwise); the host platform is detected from runtime env\n * markers; the project identity partitions telemetry by the stable project key.\n */\n/**\n * Resolve a session id for telemetry attribution. Prefers a host-provided\n * session/thread marker (so records from the same host session group together);\n * falls back to a per-process UUID — each `serve` invocation is one server\n * session, a sensible default granularity — so `--by session` rollups are never\n * collapsed into a single empty-keyed group.\n */\nfunction resolveSessionId(env: NodeJS.ProcessEnv = process.env): string {\n return (\n env.AGENT_CONNECTOR_SESSION ||\n env.CLAUDE_SESSION_ID ||\n env.CODEX_THREAD_ID ||\n env.CURSOR_TRACE_ID ||\n env.MCP_SESSION_ID ||\n `proc-${randomUUID()}`\n );\n}\n\nexport async function runServe(opts: RunServeOptions): Promise<number> {\n const { connectorId, serverCommand, serverArgs, installScope, hostPlatformOverride } =\n opts;\n\n const connector = await loadRegisteredConnector(connectorId);\n\n const id = projectIdentity(process.cwd());\n // Prefer the install TARGET platform baked into the wrapper (--host), but only\n // when it is a KNOWN registered platform id — a bad/unknown value falls back to\n // runtime env detection so a config typo can never poison hostPlatform.\n const hostPlatform: PlatformId =\n hostPlatformOverride !== undefined &&\n REGISTERED_PLATFORM_IDS.has(hostPlatformOverride)\n ? hostPlatformOverride\n : detectRuntimeHost().platform;\n const sessionId = resolveSessionId();\n\n // `serve` only ever wraps a locally-spawned stdio server (a remote/http server\n // is never launched through the proxy), so isRemote is always false here.\n const launchMethod = detectLaunchMethod(serverCommand, serverArgs);\n\n const store = openStore({});\n const tok = getTokenizer();\n\n return runServeProxy({\n connectorId,\n command: serverCommand,\n args: serverArgs,\n store,\n tokenizer: tok,\n modelFamilyHint: connector.telemetry.modelFamilyHint,\n hostPlatform,\n sessionId,\n projectKey: id.key,\n projectDir: id.dir,\n measureToolDefs: connector.telemetry.measureToolDefs,\n installScope,\n launchMethod,\n });\n}\n","/**\n * telemetry/calibration — OPT-IN Anthropic count_tokens calibration.\n *\n * The default tokenizer counts every family with the OpenAI o200k_base BPE, so\n * an Anthropic session's counts are an honest-but-approximate stand-in\n * (\"tokenizer-approx\"). This module lets a developer OPT IN to calibrating that\n * approximation against Anthropic's real `count_tokens` endpoint: we sample a\n * tiny fraction of tool calls off-box, learn a per-family correction factor\n * (rolling mean of exact/approx), and apply it to the locally-tokenized counts\n * so they land much closer to the host's real numbers — labeled honestly as\n * \"tokenizer-calibrated\".\n *\n * PRIVACY + SAFETY — load-bearing invariants:\n * • OPT-IN only. Nothing here runs unless BOTH AGENT_CONNECTOR_CALIBRATE\n * contains \"anthropic\" AND ANTHROPIC_API_KEY is set (see isCalibrationEnabled).\n * • Sampling only — shouldSample() rate-limits hard so we never hammer the API.\n * • Content leaves the box ONLY on a sampled call, ONLY when opted in. We store\n * a single scalar factor + sample count — NEVER the sampled text itself.\n * • Fail-open everywhere: a network/parse/IO error returns null / passes the\n * approximation through unchanged and NEVER throws into a tool call or hook.\n *\n * No new dependencies: uses Node's global fetch (Node >= 18) and node:fs.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { dataRoot, ensureDir } from \"../core/paths.js\";\nimport type { ConfidenceSource, ModelFamily } from \"./types.js\";\n\n// ── Env switches ──────────────────────────────────────────────────────────\n\n/**\n * Is opt-in Anthropic calibration enabled for this process?\n *\n * Requires BOTH:\n * • AGENT_CONNECTOR_CALIBRATE — a comma-separated allowlist that INCLUDES\n * `anthropic` (so a future `AGENT_CONNECTOR_CALIBRATE=openai,anthropic` can\n * opt other families in without touching this gate), and\n * • ANTHROPIC_API_KEY — a non-empty key to authenticate the off-box call.\n *\n * Either missing → disabled (the privacy-safe default).\n */\nexport function isCalibrationEnabled(): boolean {\n const families = (process.env.AGENT_CONNECTOR_CALIBRATE || \"\")\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s !== \"\");\n const key = (process.env.ANTHROPIC_API_KEY || \"\").trim();\n return families.includes(\"anthropic\") && key !== \"\";\n}\n\n// ── Factor store (dataRoot/calibration.json) ────────────────────────────────\n\n/** One learned correction factor for a model family: factor + sample count. */\nexport interface CalibrationFactor {\n /** Multiply an approx count by this to estimate the real count. */\n factor: number;\n /** How many samples have folded into the rolling mean. */\n samples: number;\n}\n\n/** The on-disk factor map, keyed by model family. */\nexport type CalibrationFactors = Partial<Record<ModelFamily, CalibrationFactor>>;\n\n/** Path to the learned-factor store: dataRoot()/calibration.json. */\nexport function calibrationPath(): string {\n return join(dataRoot(), \"calibration.json\");\n}\n\n/**\n * Clamp a measured exact/approx ratio into a sane range. A pathological sample\n * (e.g. an empty-string approx of 0 → Infinity, or a parse glitch) must never\n * poison the rolling mean, so ratios are pinned to [0.2, 5].\n */\nconst RATIO_MIN = 0.2;\nconst RATIO_MAX = 5;\n\nfunction clampRatio(ratio: number): number | null {\n if (!Number.isFinite(ratio) || ratio <= 0) return null;\n if (ratio < RATIO_MIN) return RATIO_MIN;\n if (ratio > RATIO_MAX) return RATIO_MAX;\n return ratio;\n}\n\n/**\n * Load the learned factors from disk. Fail-open: a missing/unreadable/malformed\n * file returns an empty map rather than throwing.\n */\nexport function loadFactors(): CalibrationFactors {\n const path = calibrationPath();\n if (!existsSync(path)) return {};\n try {\n const parsed = JSON.parse(readFileSync(path, \"utf8\")) as unknown;\n if (parsed === null || typeof parsed !== \"object\") return {};\n const out: CalibrationFactors = {};\n for (const [family, value] of Object.entries(parsed as Record<string, unknown>)) {\n if (value === null || typeof value !== \"object\") continue;\n const rec = value as Record<string, unknown>;\n const factor = rec[\"factor\"];\n const samples = rec[\"samples\"];\n if (\n typeof factor === \"number\" &&\n Number.isFinite(factor) &&\n factor > 0 &&\n typeof samples === \"number\" &&\n Number.isFinite(samples) &&\n samples >= 0\n ) {\n (out as Record<string, CalibrationFactor>)[family] = {\n factor,\n samples,\n };\n }\n }\n return out;\n } catch {\n return {};\n }\n}\n\n/**\n * Fold one observed exact/approx `ratio` into the rolling mean for `family` and\n * persist it. A running average converges to the true mean while staying cheap\n * and stateless across processes (each writer reads the prior count, blends in\n * the new sample, writes back). Fail-open: any read/write/clamp problem leaves\n * the store untouched and never throws.\n */\nexport function recordSample(family: ModelFamily, ratio: number): void {\n const clamped = clampRatio(ratio);\n if (clamped === null) return;\n try {\n const factors = loadFactors();\n const prior = factors[family];\n let next: CalibrationFactor;\n if (prior === undefined || prior.samples <= 0) {\n next = { factor: clamped, samples: 1 };\n } else {\n const samples = prior.samples + 1;\n // Running average: new mean = old mean + (sample - old mean) / n.\n const factor = prior.factor + (clamped - prior.factor) / samples;\n next = { factor, samples };\n }\n const updated: CalibrationFactors = { ...factors, [family]: next };\n const path = calibrationPath();\n ensureDir(dataRoot());\n writeFileSync(path, `${JSON.stringify(updated, null, 2)}\\n`, \"utf8\");\n } catch {\n /* fail-open: a calibration write must never break a tool call */\n }\n}\n\n// ── Anthropic count_tokens (off-box, sampled, fail-open) ─────────────────────\n\n/** Default model used for count_tokens when no family→model map applies. */\nconst DEFAULT_ANTHROPIC_MODEL = \"claude-3-5-sonnet-latest\";\n\n/** Anthropic count_tokens endpoint. */\nconst COUNT_TOKENS_URL = \"https://api.anthropic.com/v1/messages/count_tokens\";\n\n/** The single field we read out of a successful response. */\ninterface CountTokensResponse {\n input_tokens?: unknown;\n}\n\n/**\n * Ask Anthropic's `count_tokens` endpoint for the exact token count of `text`\n * under `model`. Returns the integer count, or `null` on ANY failure (no key,\n * non-200, network error, unparseable body) — fail-open by contract.\n *\n * Only ever called on a SAMPLED tool call when calibration is opted in, so the\n * sampled text leaves the box only under explicit operator consent.\n */\nexport async function countTokensAnthropic(\n text: string,\n model: string = DEFAULT_ANTHROPIC_MODEL,\n): Promise<number | null> {\n const apiKey = (process.env.ANTHROPIC_API_KEY || \"\").trim();\n if (apiKey === \"\") return null;\n try {\n const res = await fetch(COUNT_TOKENS_URL, {\n method: \"POST\",\n headers: {\n \"x-api-key\": apiKey,\n \"anthropic-version\": \"2023-06-01\",\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n model,\n messages: [{ role: \"user\", content: text }],\n }),\n });\n if (!res.ok) return null;\n const body = (await res.json()) as CountTokensResponse;\n const n = body.input_tokens;\n if (typeof n === \"number\" && Number.isFinite(n) && n >= 0) {\n return n;\n }\n return null;\n } catch {\n return null;\n }\n}\n\n// ── Sampling (rate-limit so we never hammer the API) ─────────────────────────\n\n/**\n * Sample roughly 1 in {@link SAMPLE_EVERY} calls, with a hard per-minute cap so\n * a burst of tool calls can never fan out into a burst of API calls. Both\n * counters are in-memory (per process) — calibration is a best-effort,\n * low-volume background signal, not a per-call requirement.\n */\nconst SAMPLE_EVERY = 20;\nconst MAX_SAMPLES_PER_MINUTE = 10;\n\nlet callCounter = 0;\nlet windowStartMs = 0;\nlet samplesThisWindow = 0;\n\n/**\n * Should THIS call fire an off-box count_tokens sample? Combines a 1-in-N\n * counter with a rolling per-minute cap. Pure in-memory bookkeeping; never\n * throws, never blocks.\n */\nexport function shouldSample(now: number = Date.now()): boolean {\n // Roll the per-minute window.\n if (now - windowStartMs >= 60_000) {\n windowStartMs = now;\n samplesThisWindow = 0;\n }\n callCounter += 1;\n if (callCounter % SAMPLE_EVERY !== 0) return false;\n if (samplesThisWindow >= MAX_SAMPLES_PER_MINUTE) return false;\n samplesThisWindow += 1;\n return true;\n}\n\n/** Reset the in-memory sampling counters. Test-only seam; cheap + side-effect-free. */\nexport function _resetSamplingForTest(): void {\n callCounter = 0;\n windowStartMs = 0;\n samplesThisWindow = 0;\n}\n\n// ── Apply a learned factor to a local approximation ──────────────────────────\n\n/** Result of {@link applyCalibration}: the adjusted count + its honest source. */\nexport interface CalibratedCount {\n tokens: number;\n source: Extract<ConfidenceSource, \"tokenizer-approx\" | \"tokenizer-calibrated\">;\n}\n\n/**\n * Adjust a locally-tokenized `approxTokens` count by the learned factor for\n * `family`. When a stored factor exists for the anthropic family, return the\n * scaled count labeled \"tokenizer-calibrated\"; otherwise pass the approximation\n * through unchanged as \"tokenizer-approx\". Pure: reads the factor store but\n * mutates nothing.\n */\nexport function applyCalibration(\n approxTokens: number,\n family: ModelFamily,\n factors: CalibrationFactors = loadFactors(),\n): CalibratedCount {\n if (family === \"anthropic\") {\n const f = factors[family];\n if (f !== undefined && f.samples > 0 && Number.isFinite(f.factor) && f.factor > 0) {\n return {\n tokens: Math.max(0, Math.round(approxTokens * f.factor)),\n source: \"tokenizer-calibrated\",\n };\n }\n }\n return { tokens: approxTokens, source: \"tokenizer-approx\" };\n}\n\n/** The model used for a family's count_tokens sample (anthropic → default model). */\nexport function modelForFamily(_family: ModelFamily): string {\n return DEFAULT_ANTHROPIC_MODEL;\n}\n","/**\n * telemetry/proxy — the telemetry-wrapping MCP stdio proxy.\n *\n * `agent-connector serve <command> <args…>` spawns the developer's REAL MCP\n * server as a child and sits transparently between the host and that server,\n * speaking the MCP stdio wire format: NEWLINE-DELIMITED JSON-RPC (one single-line\n * JSON object per message, terminated by `\\n`; stdio has NO Content-Length\n * framing). Bytes are forwarded VERBATIM in both directions so the proxy can\n * never corrupt the stream; a side line-buffer tees a COPY of each direction,\n * parses complete messages, and measures per-tool token usage out of band.\n *\n * Honesty / safety rules baked in here:\n * • Forwarding always happens FIRST. Measurement runs after the bytes are out\n * the door and is wrapped so a measurement bug can never break a tool call.\n * • Telemetry stores AGGREGATE COUNTS ONLY — the parsed `tools/call` arguments\n * and results are tokenized and discarded; raw content is never persisted.\n * • AGENT_CONNECTOR_TELEMETRY=0 → still proxy transparently, skip all measure.\n *\n * The proxy resolves with the child's exit code and propagates SIGINT/SIGTERM.\n */\n\nimport type { PlatformId } from \"../core/types.js\";\nimport { spawnChild } from \"../core/spawn-child.js\";\nimport { type JsonRpcMessage, LineBuffer, idKey, isObject } from \"./jsonrpc.js\";\nimport {\n applyCalibration,\n countTokensAnthropic,\n isCalibrationEnabled,\n modelForFamily,\n recordSample,\n shouldSample,\n} from \"./calibration.js\";\nimport { measureToolCall, measureToolDefs } from \"./measure.js\";\nimport { newRecordId } from \"./store.js\";\nimport { inferModelFamily } from \"./tokenizer.js\";\nimport type {\n ConfidenceSource,\n LaunchMethod,\n ModelFamily,\n TelemetryInstallScope,\n TelemetryStore,\n Tokenizer,\n ToolEventRecord,\n} from \"./types.js\";\n\n/** Options for {@link runServeProxy}. */\nexport interface RunServeProxyOptions {\n /** Connector id this server belongs to (stamped on every record). */\n connectorId: string;\n /** The real MCP server executable to spawn. */\n command: string;\n /** Arguments passed to that executable. */\n args: string[];\n /** Where measured records are appended. */\n store: TelemetryStore;\n /** Tokenizer used for measurement (defaults baked into measure helpers). */\n tokenizer: Tokenizer;\n /**\n * Telemetry model-family hint. \"auto\" infers the family from the MCP client's\n * `initialize` clientInfo.name; any explicit family wins outright.\n */\n modelFamilyHint: \"auto\" | ModelFamily;\n /** Host platform executing this proxy (stamped on every record). */\n hostPlatform: PlatformId;\n /** Host session id (stamped on every record). */\n sessionId: string;\n /** Hashed stable project identity (stamped on every record). */\n projectKey: string;\n /** Human-readable project directory (stamped on every record). */\n projectDir: string;\n /** When true, tokenize the `tools/list` schema once → tool-defs overhead. */\n measureToolDefs: boolean;\n /**\n * Install scope (global user vs project-local) stamped on every record.\n * OPTIONAL: omitted for configs written before scope plumbing existed, leaving\n * the field off the row so it reads as \"unknown\".\n */\n installScope?: TelemetryInstallScope;\n /**\n * How the wrapped server was launched (npx/bunx/uvx/node/binary/http), stamped\n * on every record. OPTIONAL for the same backward-compat reason as above.\n */\n launchMethod?: LaunchMethod;\n}\n\n// ── JSON-RPC shapes we read (kept local + narrow; everything else opaque) ─────\n\n/** A client→server `tools/call` we remember until its result comes back. */\ninterface PendingCall {\n toolName: string;\n args: unknown;\n}\n\n/**\n * Canonical string form of a tool call's arguments for an off-box count_tokens\n * sample — mirrors the tokenizer's own serialization so the sampled text equals\n * the bytes we approximated locally. A string passes through; anything else is\n * JSON-stringified; a value that stringifies to undefined becomes \"\".\n */\nfunction canonicalArgs(value: unknown): string {\n if (typeof value === \"string\") return value;\n try {\n return JSON.stringify(value) ?? \"\";\n } catch {\n return \"\";\n }\n}\n\n/**\n * Run the telemetry-wrapping MCP stdio proxy.\n *\n * Spawns `command args` with piped stdin/stdout (stderr inherited), forwards\n * both directions byte-for-byte, and measures `tools/call` round-trips and the\n * one-time `tools/list` tool-defs overhead into `store`. Resolves with the\n * child's exit code (or a signal-derived code) once the child closes.\n */\nexport async function runServeProxy(\n opts: RunServeProxyOptions,\n): Promise<number> {\n const {\n connectorId,\n command,\n args,\n store,\n tokenizer,\n modelFamilyHint,\n hostPlatform,\n sessionId,\n projectKey,\n projectDir,\n measureToolDefs: shouldMeasureToolDefs,\n installScope,\n launchMethod,\n } = opts;\n\n // Global kill switch: still proxy transparently, but skip ALL measurement.\n const measuringEnabled = process.env.AGENT_CONNECTOR_TELEMETRY !== \"0\";\n // OPT-IN Anthropic count_tokens calibration. Resolved once per session — the\n // gate (AGENT_CONNECTOR_CALIBRATE + ANTHROPIC_API_KEY) is process-level and\n // does not change mid-session. Off by default; privacy-safe.\n const calibrationEnabled = isCalibrationEnabled();\n\n // spawnChild fixes native-Windows package-runner launches: a bare npx/uvx\n // resolves to a .cmd shim that raw CreateProcess can't find/launch, so it is\n // run via a quoted single command line with a shell. No-op on macOS/Linux.\n const child = spawnChild(command, args, {\n stdio: [\"pipe\", \"pipe\", \"inherit\"],\n env: process.env,\n });\n\n // ── Per-session measurement state ───────────────────────────────────────\n // Family resolved from the client's `initialize` (or the hint) and cached.\n let family: ModelFamily = inferModelFamily(\"\", modelFamilyHint);\n // Outstanding tools/call requests, keyed by JSON-RPC id.\n const pending = new Map<string, PendingCall>();\n // Monotonic sequence so two records in the same ms still get distinct ids.\n let seq = 0;\n // tools/list overhead is measured exactly once per session.\n let toolDefsMeasured = false;\n\n /**\n * Build a base record stamped with the per-session identity fields plus the\n * scope dimensions. `installScope` / `launchMethod` are spread in ONLY when\n * defined, so a session without them leaves those fields off the row entirely\n * (read as \"unknown\") rather than writing an explicit `undefined`.\n */\n function baseRecord(): Omit<\n ToolEventRecord,\n \"toolName\" | \"scope\" | \"inputTokens\" | \"outputTokens\" | \"confidenceSource\" | \"isError\"\n > {\n return {\n id: newRecordId(seq++),\n ts: Date.now(),\n connectorId,\n hostPlatform,\n sessionId,\n projectKey,\n projectDir,\n ...(installScope !== undefined ? { installScope } : {}),\n ...(launchMethod !== undefined ? { launchMethod } : {}),\n };\n }\n\n /**\n * Inspect one parsed CLIENT→SERVER message. Caches the model family on\n * `initialize` and remembers `tools/call` requests so their results can be\n * measured when they come back. Never throws into the data path.\n */\n function onClientMessage(msg: JsonRpcMessage): void {\n const method = msg.method;\n if (method === \"initialize\") {\n const params = isObject(msg.params) ? msg.params : undefined;\n const clientInfo =\n params && isObject(params[\"clientInfo\"])\n ? (params[\"clientInfo\"] as Record<string, unknown>)\n : undefined;\n const clientName =\n clientInfo && typeof clientInfo[\"name\"] === \"string\"\n ? (clientInfo[\"name\"] as string)\n : \"\";\n family = inferModelFamily(clientName, modelFamilyHint);\n return;\n }\n\n if (method === \"tools/call\") {\n const key = idKey(msg.id);\n if (key === null) return; // a call with no id has no result to match\n const params = isObject(msg.params) ? msg.params : undefined;\n const toolName =\n params && typeof params[\"name\"] === \"string\"\n ? (params[\"name\"] as string)\n : \"unknown\";\n const callArgs = params ? params[\"arguments\"] : undefined;\n pending.set(key, { toolName, args: callArgs });\n }\n }\n\n /**\n * Inspect one parsed SERVER→CLIENT message. Matches `tools/call` results to\n * remembered requests and measures them; measures `tools/list` results once.\n * Never throws into the data path.\n */\n function onServerMessage(msg: JsonRpcMessage): void {\n const key = idKey(msg.id);\n if (key === null) return; // notifications carry no id we can correlate\n\n const pendingCall = pending.get(key);\n if (pendingCall !== undefined) {\n pending.delete(key);\n recordToolCall(pendingCall, msg);\n return;\n }\n\n // Not a tracked tools/call — it may be the tools/list result we measure\n // once for the fixed tool-definition overhead.\n if (shouldMeasureToolDefs && !toolDefsMeasured) {\n const result = isObject(msg.result) ? msg.result : undefined;\n const tools = result ? result[\"tools\"] : undefined;\n if (Array.isArray(tools)) {\n recordToolDefs(tools);\n }\n }\n }\n\n /** Measure a matched tools/call round-trip and append the record. */\n function recordToolCall(call: PendingCall, response: JsonRpcMessage): void {\n const hasError = response.error !== undefined;\n const result = response.result;\n // A JSON-RPC error has no `result`; measure against an empty object so the\n // input (args) tokens are still recorded honestly.\n const resultForMeasure = hasError ? {} : result;\n const measurement = measureToolCall(\n call.args,\n resultForMeasure,\n family,\n tokenizer,\n );\n\n // OPT-IN calibration: for an anthropic session, nudge the locally-tokenized\n // approx counts toward Anthropic's real numbers via the learned factor, and\n // fire a sampled off-box count_tokens to keep that factor fresh. Both steps\n // are best-effort and wrapped so they can never break the record path.\n let inputTokens = measurement.inputTokens;\n let outputTokens = measurement.outputTokens;\n let confidenceSource: ConfidenceSource = measurement.source;\n if (calibrationEnabled && family === \"anthropic\") {\n try {\n ({ inputTokens, outputTokens, confidenceSource } = calibrateCounts(\n measurement.inputTokens,\n measurement.outputTokens,\n measurement.source,\n ));\n maybeSampleCalibration(call.args, measurement.inputTokens);\n } catch {\n // Calibration is a non-essential enrichment — fall back to the raw\n // measurement values already captured above.\n }\n }\n\n // MCP signals a tool-level failure via result.isError===true; a JSON-RPC\n // protocol error (response.error) is also a failure.\n const resultIsError =\n isObject(result) && result[\"isError\"] === true;\n store.append({\n ...baseRecord(),\n toolName: call.toolName,\n scope: \"call\",\n inputTokens,\n outputTokens,\n confidenceSource,\n isError: hasError || resultIsError,\n });\n }\n\n /**\n * Apply the learned anthropic factor to the approx input/output counts. Only\n * a `tokenizer-approx` measurement is calibratable (a heuristic fallback or\n * host-native count is left exactly as-is); the combined source becomes\n * `tokenizer-calibrated` only when at least one side was actually scaled.\n */\n function calibrateCounts(\n rawIn: number,\n rawOut: number,\n rawSource: ConfidenceSource,\n ): { inputTokens: number; outputTokens: number; confidenceSource: ConfidenceSource } {\n if (rawSource !== \"tokenizer-approx\") {\n return { inputTokens: rawIn, outputTokens: rawOut, confidenceSource: rawSource };\n }\n const cin = applyCalibration(rawIn, family);\n const cout = applyCalibration(rawOut, family);\n const calibrated =\n cin.source === \"tokenizer-calibrated\" || cout.source === \"tokenizer-calibrated\";\n return {\n inputTokens: cin.tokens,\n outputTokens: cout.tokens,\n confidenceSource: calibrated ? \"tokenizer-calibrated\" : \"tokenizer-approx\",\n };\n }\n\n /**\n * On a SAMPLED call, fire-and-forget an off-box count_tokens for the call's\n * input args and fold the resulting exact/approx ratio into the learned\n * factor. Returns immediately — the network round-trip never blocks\n * forwarding or measurement. Fail-open: any error is swallowed.\n */\n function maybeSampleCalibration(args: unknown, approxInputTokens: number): void {\n if (approxInputTokens <= 0) return; // nothing to ratio against\n if (!shouldSample()) return;\n const text = canonicalArgs(args);\n if (text === \"\") return;\n // Detached promise — intentionally NOT awaited so the proxy never blocks on\n // the network. Errors are handled inside countTokensAnthropic (returns null)\n // and the .catch is a belt-and-braces guard against an unhandled rejection.\n void countTokensAnthropic(text, modelForFamily(family))\n .then((exact) => {\n if (exact !== null && exact > 0) {\n recordSample(family, exact / approxInputTokens);\n }\n })\n .catch(() => {\n /* fail-open: a calibration sample must never surface an error */\n });\n }\n\n /** Measure the one-time tools/list overhead and append the record. */\n function recordToolDefs(tools: readonly unknown[]): void {\n toolDefsMeasured = true;\n const count = measureToolDefs(tools, family, tokenizer);\n store.append({\n ...baseRecord(),\n toolName: \"*\",\n scope: \"tool_defs\",\n inputTokens: count.tokens,\n outputTokens: 0,\n confidenceSource: count.source,\n isError: false,\n });\n }\n\n /** Parse one NDJSON line and route it, swallowing any measurement error. */\n function handleLine(line: string, direction: \"client\" | \"server\"): void {\n if (!measuringEnabled) return;\n let msg: JsonRpcMessage;\n try {\n const parsed = JSON.parse(line) as unknown;\n if (!isObject(parsed)) return;\n msg = parsed as JsonRpcMessage;\n } catch {\n return; // not a complete/valid JSON message — ignore for telemetry\n }\n try {\n if (direction === \"client\") onClientMessage(msg);\n else onServerMessage(msg);\n } catch {\n // Measurement must NEVER break the proxy. Drop the record silently.\n }\n }\n\n const clientLines = new LineBuffer((line) => handleLine(line, \"client\"));\n const serverLines = new LineBuffer((line) => handleLine(line, \"server\"));\n\n // ── Transparent byte forwarding (host stdin → child stdin) ───────────────\n // Forward VERBATIM first, then tee a copy into the line buffer to measure.\n // Honor backpressure: if the child's stdin buffer is full, pause the host\n // stdin and resume on drain so a slow server can't make us buffer unboundedly.\n process.stdin.on(\"data\", (chunk: Buffer) => {\n if (child.stdin && child.stdin.writable) {\n const ok = child.stdin.write(chunk);\n if (!ok) {\n process.stdin.pause();\n child.stdin.once(\"drain\", () => process.stdin.resume());\n }\n }\n if (measuringEnabled) {\n try {\n clientLines.push(chunk);\n } catch {\n /* tee side-channel must never affect forwarding */\n }\n }\n });\n process.stdin.on(\"end\", () => {\n if (child.stdin && !child.stdin.destroyed) child.stdin.end();\n });\n\n // ── Transparent byte forwarding (child stdout → host stdout) ─────────────\n if (child.stdout) {\n const childStdout = child.stdout;\n childStdout.on(\"data\", (chunk: Buffer) => {\n const ok = process.stdout.write(chunk);\n if (!ok) {\n childStdout.pause();\n process.stdout.once(\"drain\", () => childStdout.resume());\n }\n if (measuringEnabled) {\n try {\n serverLines.push(chunk);\n } catch {\n /* tee side-channel must never affect forwarding */\n }\n }\n });\n }\n\n // ── Signal propagation: forward SIGINT/SIGTERM to the child ──────────────\n const forwardSignal = (signal: NodeJS.Signals): void => {\n try {\n if (!child.killed) child.kill(signal);\n } catch {\n /* child may already be gone */\n }\n };\n const onSigint = (): void => forwardSignal(\"SIGINT\");\n const onSigterm = (): void => forwardSignal(\"SIGTERM\");\n process.on(\"SIGINT\", onSigint);\n process.on(\"SIGTERM\", onSigterm);\n\n // ── Resolve with the child's exit code (or signal-derived code) ──────────\n return await new Promise<number>((resolve) => {\n const finish = (code: number): void => {\n process.removeListener(\"SIGINT\", onSigint);\n process.removeListener(\"SIGTERM\", onSigterm);\n try {\n store.close();\n } catch {\n /* best-effort flush */\n }\n resolve(code);\n };\n\n child.on(\"error\", () => {\n // The server could not be spawned/launched. Surface a conventional\n // \"command not executable\" style failure code.\n finish(126);\n });\n\n child.on(\"close\", (code, signal) => {\n if (typeof code === \"number\") {\n finish(code);\n return;\n }\n // Killed by a signal → conventional 128 + signal number where known.\n if (signal) {\n const num = signalToNumber(signal);\n finish(num === undefined ? 1 : 128 + num);\n return;\n }\n finish(1);\n });\n });\n}\n\n/** Map the common termination signals to their numbers for exit-code math. */\nfunction signalToNumber(signal: NodeJS.Signals): number | undefined {\n const table: Partial<Record<NodeJS.Signals, number>> = {\n SIGINT: 2,\n SIGQUIT: 3,\n SIGKILL: 9,\n SIGTERM: 15,\n };\n return table[signal];\n}\n\nexport default runServeProxy;\n","/**\n * runtime/usage-event — the OPT-IN host-native turn-usage enricher (enricher 4a).\n *\n * Gemini CLI / Antigravity fire an `AfterModel` (Antigravity CLI: `PostInvocation`)\n * hook AFTER each model turn, whose stdin payload carries a `usageMetadata` block\n * with the host's OWN exact token accounting for that whole conversation turn:\n * { promptTokenCount, candidatesTokenCount, cachedContentTokenCount,\n * thoughtsTokenCount, totalTokenCount }\n * This is the single point in the whole matrix where a host reports REAL per-turn\n * usage to a command we control — so we record it as `confidenceSource:\"host-native\"`\n * (the top of CONFIDENCE_RANK), upgrading those rows from the serve-proxy estimate.\n *\n * DISTINCT, NEVER-SUMMED ORIGIN. Host-native turn usage is WHOLE-CONVERSATION, not\n * per-MCP. To avoid double-counting against (a) the per-MCP serve-proxy `call`\n * rows and (b) the usage-reader host-scan numbers, every record written here uses\n * the DISTINCT scope `\"model_turn\"`. The MCP leaderboard excludes that scope (just\n * as it special-cases `tool_defs`); the unified leaderboard surfaces it as its own\n * clearly-labeled section that is explicitly never added to the other two origins.\n *\n * PRIVACY + FAIL-OPEN. This enricher is OPT-IN at install time (see the adapters);\n * it stores AGGREGATE COUNTS ONLY (no raw content — the payload's prompt/response\n * text is never read). ANY parse / store / IO error degrades to exit 0 and records\n * NOTHING: a host-native usage hook must never break a model turn. This function\n * never throws.\n */\n\nimport { projectIdentity } from \"../core/paths.js\";\nimport { newRecordId, openStore } from \"../telemetry/store.js\";\nimport type { PlatformId } from \"../core/types.js\";\nimport type { ToolEventRecord } from \"../telemetry/types.js\";\n\n/** Flags + stdin the CLI hands to {@link runUsageEvent}. */\nexport interface RunUsageEventOptions {\n /** Host platform id from the command (`usage-event <platformId> …`). */\n platformId: string;\n /** Connector id from `--connector <id>` (stamped on the record). */\n connectorId: string;\n /** Raw stdin payload (host-native JSON). Empty string is tolerated → no record. */\n stdin: string;\n}\n\n/** Process-level result the CLI translates into an exit code. */\nexport interface RunUsageEventResult {\n /** Always 0 — a host-native usage hook must never block a model turn. */\n exitCode: number;\n /** True when a `model_turn` record was appended (false on any fail-open path). */\n recorded: boolean;\n}\n\n/** The never-records, never-throws result. */\nconst NOOP: RunUsageEventResult = { exitCode: 0, recorded: false };\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/** Coerce a value to a non-negative safe integer (NaN/negatives/floats → 0). */\nfunction toNonNegInt(v: unknown): number {\n const n = typeof v === \"number\" ? v : typeof v === \"string\" ? Number(v) : NaN;\n if (!Number.isFinite(n) || n < 0) return 0;\n return Math.floor(n);\n}\n\n/** First non-empty string among the given keys of an object. */\nfunction firstStr(obj: Record<string, unknown>, keys: readonly string[]): string | undefined {\n for (const k of keys) {\n const v = obj[k];\n if (typeof v === \"string\" && v.trim() !== \"\") return v;\n }\n return undefined;\n}\n\n/** Read a token field tolerant of both camelCase and snake_case spellings. */\nfunction tokenField(\n meta: Record<string, unknown>,\n keys: readonly string[],\n): number {\n for (const k of keys) {\n if (k in meta) return toNonNegInt(meta[k]);\n }\n return 0;\n}\n\n/** Locate the `usageMetadata` block under either spelling, top-level or nested. */\nfunction findUsageMetadata(root: Record<string, unknown>): Record<string, unknown> | undefined {\n for (const k of [\"usageMetadata\", \"usage_metadata\"]) {\n if (isObject(root[k])) return root[k] as Record<string, unknown>;\n }\n // Some hosts nest the model response (with its usage) under a `response` /\n // `modelResponse` envelope — probe one level down, best-effort.\n for (const k of [\"response\", \"modelResponse\", \"model_response\"]) {\n const nested = root[k];\n if (isObject(nested)) {\n for (const mk of [\"usageMetadata\", \"usage_metadata\"]) {\n if (isObject(nested[mk])) return nested[mk] as Record<string, unknown>;\n }\n }\n }\n return undefined;\n}\n\n/** A registered PlatformId, or \"unknown\" when the id is not one we know. */\nconst KNOWN_PLATFORMS: ReadonlySet<string> = new Set<PlatformId>([\n \"claude-code\", \"codex\", \"cursor\", \"vscode-copilot\", \"jetbrains-copilot\",\n \"copilot-cli\", \"gemini-cli\", \"opencode\", \"kilo\", \"kilo-cli\", \"warp\", \"hermes\",\n \"openclaw\", \"zed\", \"antigravity\", \"antigravity-cli\", \"kiro\", \"qwen-code\",\n \"kimi\", \"pi\", \"omp\", \"droid\", \"roo-code\", \"trae\", \"amp\", \"codebuff\", \"mux\",\n \"crush\", \"goose\", \"synthetic\", \"unknown\",\n]);\n\nfunction asPlatformId(id: string): PlatformId {\n return (KNOWN_PLATFORMS.has(id) ? id : \"unknown\") as PlatformId;\n}\n\n/**\n * Record one host-native model turn. Parses the host's `usageMetadata`, maps it to\n * a DISTINCT `model_turn` `ToolEventRecord` (confidence `host-native`, toolName\n * `\"*\"`), and appends it to the shared telemetry store. NEVER throws and never\n * blocks the turn: every failure path resolves to {@link NOOP} (exit 0, nothing\n * recorded).\n */\nexport async function runUsageEvent(\n opts: RunUsageEventOptions,\n): Promise<RunUsageEventResult> {\n try {\n // Global telemetry kill switch is honored by the store's append (no-op when\n // AGENT_CONNECTOR_TELEMETRY=0); we still parse cheaply and let append drop it.\n const trimmed = opts.stdin.trim();\n if (trimmed === \"\") return NOOP;\n\n let raw: unknown;\n try {\n raw = JSON.parse(trimmed);\n } catch {\n return NOOP; // malformed payload → fail-open, record nothing\n }\n if (!isObject(raw)) return NOOP;\n\n const meta = findUsageMetadata(raw);\n if (meta === undefined) return NOOP;\n\n const promptTokens = tokenField(meta, [\"promptTokenCount\", \"prompt_token_count\"]);\n const candidates = tokenField(meta, [\"candidatesTokenCount\", \"candidates_token_count\"]);\n const cached = tokenField(meta, [\"cachedContentTokenCount\", \"cached_content_token_count\"]);\n const thoughts = tokenField(meta, [\"thoughtsTokenCount\", \"thoughts_token_count\"]);\n\n // promptTokenCount is cache-INCLUSIVE (Gemini-family semantics, mirrored by\n // the antigravity-shared usage reader): net fresh input = prompt - cached.\n const inputTokens = Math.max(0, promptTokens - Math.min(cached, promptTokens));\n // Output = generated candidates + reasoning (\"thoughts\") tokens.\n const outputTokens = candidates + thoughts;\n\n // A turn with no measurable tokens is not worth a row.\n if (inputTokens === 0 && outputTokens === 0) return NOOP;\n\n // Identity: prefer payload session/cwd; fall back to process.cwd() for the\n // project key so a turn always lands in a stable project partition.\n const sessionId =\n firstStr(raw, [\"session_id\", \"sessionId\", \"conversationId\", \"conversation_id\"]) ?? \"\";\n const cwd = firstStr(raw, [\"cwd\", \"workspace\", \"projectDir\", \"project_dir\"]) ?? process.cwd();\n const id = projectIdentity(cwd);\n\n const record: ToolEventRecord = {\n id: newRecordId(0),\n ts: Date.now(),\n connectorId: opts.connectorId,\n toolName: \"*\",\n scope: \"model_turn\",\n hostPlatform: asPlatformId(opts.platformId),\n sessionId,\n projectKey: id.key,\n projectDir: id.dir,\n inputTokens,\n outputTokens,\n confidenceSource: \"host-native\",\n isError: false,\n };\n\n const store = openStore({});\n try {\n store.append(record);\n } finally {\n try {\n store.close();\n } catch {\n /* best-effort flush */\n }\n }\n return { exitCode: 0, recorded: true };\n } catch {\n // Fail-open: a host-native usage enricher must never surface an error.\n return NOOP;\n }\n}\n\nexport default runUsageEvent;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,IAAM,oBAA4C;AAAA,EAChD,OAAO;AAAA,EACP,OAAO;AAAA,EACP,UAAU;AACZ;AAEA,IAAM,yBAAyB;AAU/B,SAAS,eAAe,SAAwD;AAG9E,MAAI,QAA0B;AAC9B,aAAW,KAAK,QAAS,SAAQ,gBAAgB,OAAO,CAAC;AACzD,SAAO;AACT;AAoBA,SAASA,UAAS,GAA0C;AAC1D,SAAO,OAAO,MAAM,YAAY,MAAM;AACxC;AAEA,SAAS,YAAY,OAAyC;AAC5D,SAAO,MAAM,SAAS;AACxB;AAeO,SAAS,gBACd,MACA,QACA,QACA,MAAiB,aAAa,GACT;AACrB,QAAM,QAAQ,IAAI,WAAW,MAAM,MAAM;AACzC,QAAM,SAAS,cAAc,QAAQ,QAAQ,GAAG;AAChD,SAAO;AAAA,IACL,aAAa,MAAM;AAAA,IACnB,cAAc,OAAO;AAAA,IACrB,QAAQ,gBAAgB,MAAM,QAAQ,OAAO,MA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,MAClB,SAAS;AAAA,IACX;AAEA,UAAM,QAAQ,UAAU,CAAC,CAAC;AAC1B,QAAI;AACF,YAAM,OAAO,MAAM;AAAA,IACrB,UAAE;AACA,UAAI;AACF,cAAM,MAAM;AAAA,MACd,QAAQ;AAAA,MAER;AAAA,IACF;AACA,WAAO,EAAE,UAAU,GAAG,UAAU,KAAK;AAAA,EACvC,QAAQ;AAEN,WAAO;AAAA,EACT;AACF;","names":["isObject","args","isObject"]}
@@ -0,0 +1,146 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/usage/sqlite.ts
4
+ import { copyFileSync, existsSync, mkdtempSync, readFileSync, rmSync } from "fs";
5
+ import { createRequire } from "module";
6
+ import { tmpdir } from "os";
7
+ import { basename, dirname, join } from "path";
8
+ var require2 = createRequire(import.meta.url);
9
+ var sqlPromise;
10
+ function locateWasm(file) {
11
+ try {
12
+ const entry = require2.resolve("sql.js");
13
+ return join(dirname(entry), file);
14
+ } catch {
15
+ return file;
16
+ }
17
+ }
18
+ function loadSqlJs() {
19
+ if (sqlPromise === void 0) {
20
+ sqlPromise = (async () => {
21
+ try {
22
+ const mod = require2("sql.js");
23
+ const init = typeof mod === "function" ? mod : mod.default;
24
+ return await init({ locateFile: locateWasm });
25
+ } catch {
26
+ return null;
27
+ }
28
+ })();
29
+ }
30
+ return sqlPromise;
31
+ }
32
+ var SIDECAR_SUFFIXES = ["-wal", "-shm"];
33
+ async function openSqlite(path) {
34
+ if (!existsSync(path)) return null;
35
+ const SQL = await loadSqlJs();
36
+ if (SQL === null) return null;
37
+ const hasSidecar = SIDECAR_SUFFIXES.some((s) => existsSync(path + s));
38
+ let openPath = path;
39
+ let tempDir;
40
+ if (hasSidecar) {
41
+ try {
42
+ tempDir = mkdtempSync(join(tmpdir(), "agent-connector-usage-"));
43
+ const dst = join(tempDir, basename(path));
44
+ copyFileSync(path, dst);
45
+ for (const suffix of SIDECAR_SUFFIXES) {
46
+ const side = path + suffix;
47
+ if (existsSync(side)) copyFileSync(side, dst + suffix);
48
+ }
49
+ openPath = dst;
50
+ } catch {
51
+ openPath = path;
52
+ if (tempDir) {
53
+ cleanupTemp(tempDir);
54
+ tempDir = void 0;
55
+ }
56
+ }
57
+ }
58
+ let bytes;
59
+ try {
60
+ bytes = readFileSync(openPath);
61
+ } catch {
62
+ if (tempDir) cleanupTemp(tempDir);
63
+ return null;
64
+ }
65
+ if (!hasSqliteMagic(bytes)) {
66
+ if (tempDir) cleanupTemp(tempDir);
67
+ return null;
68
+ }
69
+ let db;
70
+ try {
71
+ db = new SQL.Database(bytes);
72
+ } catch {
73
+ if (tempDir) cleanupTemp(tempDir);
74
+ return null;
75
+ }
76
+ let closed = false;
77
+ return {
78
+ all(sql) {
79
+ if (closed) return [];
80
+ let result;
81
+ try {
82
+ result = db.exec(sql);
83
+ } catch {
84
+ return [];
85
+ }
86
+ const out = [];
87
+ for (const block of result) {
88
+ const { columns, values } = block;
89
+ for (const row of values) {
90
+ const obj = {};
91
+ for (let i = 0; i < columns.length; i++) {
92
+ const col = columns[i];
93
+ if (col !== void 0) obj[col] = row[i];
94
+ }
95
+ out.push(obj);
96
+ }
97
+ }
98
+ return out;
99
+ },
100
+ close() {
101
+ if (closed) return;
102
+ closed = true;
103
+ try {
104
+ db.close();
105
+ } catch {
106
+ }
107
+ if (tempDir) cleanupTemp(tempDir);
108
+ }
109
+ };
110
+ }
111
+ var SQLITE_MAGIC = Uint8Array.from([
112
+ 83,
113
+ 81,
114
+ 76,
115
+ 105,
116
+ 116,
117
+ 101,
118
+ 32,
119
+ 102,
120
+ 111,
121
+ 114,
122
+ 109,
123
+ 97,
124
+ 116,
125
+ 32,
126
+ 51,
127
+ 0
128
+ ]);
129
+ function hasSqliteMagic(bytes) {
130
+ if (bytes.length < SQLITE_MAGIC.length) return false;
131
+ for (let i = 0; i < SQLITE_MAGIC.length; i++) {
132
+ if (bytes[i] !== SQLITE_MAGIC[i]) return false;
133
+ }
134
+ return true;
135
+ }
136
+ function cleanupTemp(dir) {
137
+ try {
138
+ rmSync(dir, { recursive: true, force: true });
139
+ } catch {
140
+ }
141
+ }
142
+
143
+ export {
144
+ openSqlite
145
+ };
146
+ //# sourceMappingURL=chunk-YT43MUSJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/usage/sqlite.ts"],"sourcesContent":["/**\n * usage/sqlite — a lazy, read-only sql.js (WASM) loader for SQLite readers.\n *\n * Why sql.js: pure WASM, zero native build / node-gyp / prebuilt-binary matrix,\n * so it installs identically on Linux/macOS/Windows and in CI (the decisive\n * constraint — see docs/research/usage-design.md §2). We never write the host DB:\n * we load its bytes and run SELECTs, then discard.\n *\n * Read-only by construction:\n * • open by reading the file into a Uint8Array → new SQL.Database(bytes);\n * • if a -wal/-shm sidecar exists, the on-disk file may be a half-flushed\n * snapshot, so we copy the db (+ sidecars) into an os.tmpdir temp path,\n * open the copy, and clean it up afterward. This avoids reading a torn page\n * of a live DB (Crush/OpenCode can be running).\n *\n * Fail-open: ANY failure (missing wasm, unreadable file, corrupt db, bad SQL)\n * returns null / [] — a SQLite reader degrades to zero rows, never throws.\n *\n * The WASM module is initialized once (lazy singleton) so report runs that touch\n * no SQLite reader pay nothing.\n */\n\nimport { copyFileSync, existsSync, mkdtempSync, readFileSync, rmSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { basename, dirname, join } from \"node:path\";\n\n/** Minimal handle a SQLite reader needs: run a SELECT, then close. */\nexport interface SqliteDb {\n /** Run a SQL statement and return all rows as plain objects (column → value). */\n all(sql: string): Array<Record<string, unknown>>;\n /** Release the in-memory database. Idempotent. */\n close(): void;\n}\n\n/** The sql.js factory signature we depend on (a tiny structural subset). */\ninterface SqlJsStatic {\n Database: new (data: Uint8Array) => SqlJsDatabase;\n}\ninterface SqlJsDatabase {\n exec(sql: string): Array<{ columns: string[]; values: unknown[][] }>;\n close(): void;\n}\ntype InitSqlJs = (config?: { locateFile?: (file: string) => string }) => Promise<SqlJsStatic>;\n\nconst require = createRequire(import.meta.url);\n\n/** Lazy singleton: the initialized sql.js module (or null if it failed to load). */\nlet sqlPromise: Promise<SqlJsStatic | null> | undefined;\n\n/** Resolve the sql-wasm.wasm next to the resolved sql.js package entry. */\nfunction locateWasm(file: string): string {\n try {\n const entry = require.resolve(\"sql.js\"); // → node_modules/sql.js/dist/sql-wasm.js\n return join(dirname(entry), file);\n } catch {\n return file;\n }\n}\n\n/** Initialize sql.js once. Returns null (cached) when the module cannot load. */\nfunction loadSqlJs(): Promise<SqlJsStatic | null> {\n if (sqlPromise === undefined) {\n sqlPromise = (async () => {\n try {\n // sql.js's default export is the initializer (a CommonJS module).\n const mod = require(\"sql.js\") as InitSqlJs | { default: InitSqlJs };\n const init: InitSqlJs = typeof mod === \"function\" ? mod : mod.default;\n return await init({ locateFile: locateWasm });\n } catch {\n return null;\n }\n })();\n }\n return sqlPromise;\n}\n\n/** SQLite WAL/SHM sidecar suffixes that signal a possibly-live database file. */\nconst SIDECAR_SUFFIXES = [\"-wal\", \"-shm\"] as const;\n\n/**\n * Open a SQLite file read-only via sql.js. Returns a small {@link SqliteDb} or\n * null on any failure. When a -wal/-shm sidecar is present the db is copied to a\n * temp dir first (and the copy is removed when the handle is closed) to avoid\n * reading a torn snapshot of a live database.\n */\nexport async function openSqlite(path: string): Promise<SqliteDb | null> {\n if (!existsSync(path)) return null;\n\n const SQL = await loadSqlJs();\n if (SQL === null) return null;\n\n const hasSidecar = SIDECAR_SUFFIXES.some((s) => existsSync(path + s));\n let openPath = path;\n let tempDir: string | undefined;\n\n if (hasSidecar) {\n try {\n tempDir = mkdtempSync(join(tmpdir(), \"agent-connector-usage-\"));\n const dst = join(tempDir, basename(path));\n copyFileSync(path, dst);\n for (const suffix of SIDECAR_SUFFIXES) {\n const side = path + suffix;\n if (existsSync(side)) copyFileSync(side, dst + suffix);\n }\n openPath = dst;\n } catch {\n // If the copy fails, fall back to opening the original bytes directly.\n openPath = path;\n if (tempDir) {\n cleanupTemp(tempDir);\n tempDir = undefined;\n }\n }\n }\n\n let bytes: Uint8Array;\n try {\n bytes = readFileSync(openPath);\n } catch {\n if (tempDir) cleanupTemp(tempDir);\n return null;\n }\n\n // Reject anything that is not a SQLite file up front (the 16-byte header magic\n // \"SQLite format 3\\0\"). sql.js would otherwise accept arbitrary bytes and only\n // fail at query time; this keeps the documented \"null on non-db\" contract.\n if (!hasSqliteMagic(bytes)) {\n if (tempDir) cleanupTemp(tempDir);\n return null;\n }\n\n let db: SqlJsDatabase;\n try {\n db = new SQL.Database(bytes);\n } catch {\n if (tempDir) cleanupTemp(tempDir);\n return null;\n }\n\n let closed = false;\n return {\n all(sql: string): Array<Record<string, unknown>> {\n if (closed) return [];\n let result: Array<{ columns: string[]; values: unknown[][] }>;\n try {\n result = db.exec(sql);\n } catch {\n return []; // bad SQL / schema mismatch → no rows\n }\n const out: Array<Record<string, unknown>> = [];\n for (const block of result) {\n const { columns, values } = block;\n for (const row of values) {\n const obj: Record<string, unknown> = {};\n for (let i = 0; i < columns.length; i++) {\n const col = columns[i];\n if (col !== undefined) obj[col] = row[i];\n }\n out.push(obj);\n }\n }\n return out;\n },\n close(): void {\n if (closed) return;\n closed = true;\n try {\n db.close();\n } catch {\n /* ignore */\n }\n if (tempDir) cleanupTemp(tempDir);\n },\n };\n}\n\n/** The 16-byte SQLite file header: \"SQLite format 3\\0\". */\nconst SQLITE_MAGIC = Uint8Array.from([\n 0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33, 0x00,\n]);\n\n/** Does `bytes` begin with the SQLite file-header magic? */\nfunction hasSqliteMagic(bytes: Uint8Array): boolean {\n if (bytes.length < SQLITE_MAGIC.length) return false;\n for (let i = 0; i < SQLITE_MAGIC.length; i++) {\n if (bytes[i] !== SQLITE_MAGIC[i]) return false;\n }\n return true;\n}\n\nfunction cleanupTemp(dir: string): void {\n try {\n rmSync(dir, { recursive: true, force: true });\n } catch {\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