@ken-jo/agent-connector 0.3.0 → 0.4.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 (166) hide show
  1. package/README.md +188 -20
  2. package/dist/action-PLZW5BGX.js +54 -0
  3. package/dist/action-PLZW5BGX.js.map +1 -0
  4. package/dist/{amp-YGV66GJT.js → amp-B524U6LO.js} +81 -5
  5. package/dist/amp-B524U6LO.js.map +1 -0
  6. package/dist/{antigravity-7IBYFO6P.js → antigravity-ANDKF3K7.js} +4 -4
  7. package/dist/{antigravity-cli-JEOUP2VN.js → antigravity-cli-LLRPDDOT.js} +4 -4
  8. package/dist/chunk-22Y24V7O.js +21 -0
  9. package/dist/chunk-22Y24V7O.js.map +1 -0
  10. package/dist/chunk-3PFFTFCU.js +190 -0
  11. package/dist/chunk-3PFFTFCU.js.map +1 -0
  12. package/dist/{chunk-SCVBYSF7.js → chunk-6XHB6BE3.js} +1 -1
  13. package/dist/chunk-76FUSVIA.js +43 -0
  14. package/dist/chunk-76FUSVIA.js.map +1 -0
  15. package/dist/{chunk-GSGDG2BV.js → chunk-ADTHT2FN.js} +109 -16
  16. package/dist/chunk-ADTHT2FN.js.map +1 -0
  17. package/dist/{chunk-ZAM4M7LI.js → chunk-BHUCB6LY.js} +135 -296
  18. package/dist/chunk-BHUCB6LY.js.map +1 -0
  19. package/dist/{chunk-MEH7GC7R.js → chunk-BXGFUENQ.js} +20 -3
  20. package/dist/chunk-BXGFUENQ.js.map +1 -0
  21. package/dist/chunk-CIRDOY2V.js +351 -0
  22. package/dist/chunk-CIRDOY2V.js.map +1 -0
  23. package/dist/{chunk-QADSG2JY.js → chunk-G3ER4SY5.js} +1152 -106
  24. package/dist/chunk-G3ER4SY5.js.map +1 -0
  25. package/dist/{chunk-44HUXXC6.js → chunk-G5CQHVQG.js} +232 -5
  26. package/dist/chunk-G5CQHVQG.js.map +1 -0
  27. package/dist/{chunk-PD4VFEBY.js → chunk-IW77FFNX.js} +39 -1
  28. package/dist/chunk-IW77FFNX.js.map +1 -0
  29. package/dist/chunk-J3D5W5T2.js +83 -0
  30. package/dist/chunk-J3D5W5T2.js.map +1 -0
  31. package/dist/{openclaw-UZ5BMCGQ.js → chunk-KGGBNKI4.js} +125 -33
  32. package/dist/chunk-KGGBNKI4.js.map +1 -0
  33. package/dist/{chunk-3JCRUROU.js → chunk-KGJWE6A2.js} +13 -4
  34. package/dist/chunk-KGJWE6A2.js.map +1 -0
  35. package/dist/{chunk-DS3LUFVN.js → chunk-KGXDYGNJ.js} +26 -16
  36. package/dist/chunk-KGXDYGNJ.js.map +1 -0
  37. package/dist/{chunk-KVAAFYRR.js → chunk-KHO5WNTP.js} +2 -18
  38. package/dist/chunk-KHO5WNTP.js.map +1 -0
  39. package/dist/{chunk-KQSNDFBN.js → chunk-LL4OBGRU.js} +3 -3
  40. package/dist/{chunk-WNREHWKL.js → chunk-MAH6QQTO.js} +3 -3
  41. package/dist/{claude-code-4275HQU4.js → claude-code-MLWS7CW6.js} +180 -28
  42. package/dist/claude-code-MLWS7CW6.js.map +1 -0
  43. package/dist/cli/sdk.js +4 -3
  44. package/dist/cli/sdk.js.map +1 -1
  45. package/dist/cli.js +1 -1
  46. package/dist/{codebuff-LE3KBZGM.js → codebuff-SH2S3QAN.js} +102 -5
  47. package/dist/codebuff-SH2S3QAN.js.map +1 -0
  48. package/dist/{codex-4BY2ZJIW.js → codex-BXA4FIF4.js} +3 -3
  49. package/dist/{copilot-cli-IPISKO3V.js → copilot-cli-ROIBTTDT.js} +3 -3
  50. package/dist/{crush-X3E25EQG.js → crush-QLEFLHUC.js} +3 -3
  51. package/dist/{cursor-UH3W622V.js → cursor-ASJPWZ4R.js} +6 -3
  52. package/dist/cursor-ASJPWZ4R.js.map +1 -0
  53. package/dist/{detect-MNDHGLSV.js → detect-ZIIS55LD.js} +4 -3
  54. package/dist/{detect-MNDHGLSV.js.map → detect-ZIIS55LD.js.map} +1 -1
  55. package/dist/{doctor-N5KZDD55.js → doctor-TJUGSQ5C.js} +17 -13
  56. package/dist/doctor-TJUGSQ5C.js.map +1 -0
  57. package/dist/{droid-T5VBRXZF.js → droid-NCSS3B5Y.js} +170 -4
  58. package/dist/droid-NCSS3B5Y.js.map +1 -0
  59. package/dist/{gemini-cli-ZSUK55UA.js → gemini-cli-SLVWLXJW.js} +3 -3
  60. package/dist/{goose-M3RR3CZG.js → goose-PBA7KTE5.js} +100 -5
  61. package/dist/goose-PBA7KTE5.js.map +1 -0
  62. package/dist/{hermes-CUNKIAR5.js → hermes-ONDCECP2.js} +3 -3
  63. package/dist/{hook-7LUOKIXH.js → hook-OU522ABV.js} +12 -9
  64. package/dist/{hook-7LUOKIXH.js.map → hook-OU522ABV.js.map} +1 -1
  65. package/dist/index.d.ts +71 -3
  66. package/dist/index.js +22 -3
  67. package/dist/{install-TQTT4F3I.js → install-UDCBL7HP.js} +12 -10
  68. package/dist/{install-TQTT4F3I.js.map → install-UDCBL7HP.js.map} +1 -1
  69. package/dist/introspect-DuZSPSHB.d.ts +53 -0
  70. package/dist/{jetbrains-copilot-C3HDGGML.js → jetbrains-copilot-YABZ3HFA.js} +3 -3
  71. package/dist/{kilo-PKAJCWPX.js → kilo-F3ZDZKCT.js} +3 -3
  72. package/dist/{kilo-cli-QWUVXG2O.js → kilo-cli-3HWPWBY4.js} +3 -3
  73. package/dist/{kimi-EVD7YKXS.js → kimi-NV72FVAO.js} +3 -3
  74. package/dist/{kiro-UQRY6EIO.js → kiro-C5W6AGDR.js} +3 -3
  75. package/dist/{leaderboard-MUJ7DURM.js → leaderboard-TIBVONVT.js} +3 -3
  76. package/dist/mimo-code-IMM5YM3M.js +754 -0
  77. package/dist/mimo-code-IMM5YM3M.js.map +1 -0
  78. package/dist/{mux-5CI5FP2W.js → mux-DSSH4AFS.js} +3 -3
  79. package/dist/nemoclaw-3EVNKD3I.js +58 -0
  80. package/dist/nemoclaw-3EVNKD3I.js.map +1 -0
  81. package/dist/{omp-AXA7XY22.js → omp-Z6FRNDPN.js} +3 -3
  82. package/dist/openclaw-7G437NT7.js +18 -0
  83. package/dist/openclaw-7G437NT7.js.map +1 -0
  84. package/dist/{opencode-NZBRLJN3.js → opencode-Q6KBSAKW.js} +3 -3
  85. package/dist/{package-SYPA5POO.js → package-RMPN57YZ.js} +7 -6
  86. package/dist/{package-SYPA5POO.js.map → package-RMPN57YZ.js.map} +1 -1
  87. package/dist/{pi-WMTUX6ES.js → pi-LZT6WWAZ.js} +2 -2
  88. package/dist/{qwen-code-MRRIUQ3P.js → qwen-code-WQBKRPWJ.js} +3 -3
  89. package/dist/{roo-code-NI5UU6JB.js → roo-code-GWSNU3OW.js} +137 -4
  90. package/dist/roo-code-GWSNU3OW.js.map +1 -0
  91. package/dist/runtime/index.d.ts +96 -2
  92. package/dist/runtime/index.js +18 -10
  93. package/dist/sdk/index.d.ts +52 -0
  94. package/dist/sdk/index.js +81 -0
  95. package/dist/sdk/index.js.map +1 -0
  96. package/dist/sdk/test.d.ts +74 -0
  97. package/dist/sdk/test.js +291 -0
  98. package/dist/sdk/test.js.map +1 -0
  99. package/dist/{serve-XJOSA7BY.js → serve-D3GO36UT.js} +12 -9
  100. package/dist/{serve-XJOSA7BY.js.map → serve-D3GO36UT.js.map} +1 -1
  101. package/dist/{status-DYSS6BOR.js → status-KOSKCETC.js} +10 -8
  102. package/dist/{status-DYSS6BOR.js.map → status-KOSKCETC.js.map} +1 -1
  103. package/dist/statusline-ZNTCL5YC.js +59 -0
  104. package/dist/statusline-ZNTCL5YC.js.map +1 -0
  105. package/dist/{telemetry-IJ4GP2Q3.js → telemetry-XIKUUGTQ.js} +5 -4
  106. package/dist/{telemetry-IJ4GP2Q3.js.map → telemetry-XIKUUGTQ.js.map} +1 -1
  107. package/dist/{trae-CQC72RHH.js → trae-NWT3TMSZ.js} +99 -5
  108. package/dist/trae-NWT3TMSZ.js.map +1 -0
  109. package/dist/{types-CNigfEuR.d.ts → types-BEKsAium.d.ts} +268 -6
  110. package/dist/{uninstall-3DXIBRCV.js → uninstall-2LBLQVFA.js} +12 -10
  111. package/dist/{uninstall-3DXIBRCV.js.map → uninstall-2LBLQVFA.js.map} +1 -1
  112. package/dist/{upgrade-GJEB3ITY.js → upgrade-ZC2S7VRN.js} +12 -10
  113. package/dist/{upgrade-GJEB3ITY.js.map → upgrade-ZC2S7VRN.js.map} +1 -1
  114. package/dist/{usage-2BJLM3GJ.js → usage-E2A4O2CY.js} +3 -3
  115. package/dist/{usage-event-472X3DOY.js → usage-event-JKMC4QC4.js} +11 -8
  116. package/dist/{usage-event-472X3DOY.js.map → usage-event-JKMC4QC4.js.map} +1 -1
  117. package/dist/{vscode-copilot-4RVRTCKV.js → vscode-copilot-ALV45XF6.js} +3 -3
  118. package/dist/{warp-X6MB67NT.js → warp-H6IX4U3J.js} +3 -3
  119. package/dist/{zed-NTCYW4V2.js → zed-RH34TNSW.js} +3 -3
  120. package/package.json +9 -1
  121. package/dist/amp-YGV66GJT.js.map +0 -1
  122. package/dist/chunk-3JCRUROU.js.map +0 -1
  123. package/dist/chunk-44HUXXC6.js.map +0 -1
  124. package/dist/chunk-DS3LUFVN.js.map +0 -1
  125. package/dist/chunk-GSGDG2BV.js.map +0 -1
  126. package/dist/chunk-KVAAFYRR.js.map +0 -1
  127. package/dist/chunk-MEH7GC7R.js.map +0 -1
  128. package/dist/chunk-NJU275US.js +0 -238
  129. package/dist/chunk-NJU275US.js.map +0 -1
  130. package/dist/chunk-PD4VFEBY.js.map +0 -1
  131. package/dist/chunk-QADSG2JY.js.map +0 -1
  132. package/dist/chunk-ZAM4M7LI.js.map +0 -1
  133. package/dist/claude-code-4275HQU4.js.map +0 -1
  134. package/dist/codebuff-LE3KBZGM.js.map +0 -1
  135. package/dist/cursor-UH3W622V.js.map +0 -1
  136. package/dist/doctor-N5KZDD55.js.map +0 -1
  137. package/dist/droid-T5VBRXZF.js.map +0 -1
  138. package/dist/goose-M3RR3CZG.js.map +0 -1
  139. package/dist/openclaw-UZ5BMCGQ.js.map +0 -1
  140. package/dist/roo-code-NI5UU6JB.js.map +0 -1
  141. package/dist/trae-CQC72RHH.js.map +0 -1
  142. /package/dist/{antigravity-7IBYFO6P.js.map → antigravity-ANDKF3K7.js.map} +0 -0
  143. /package/dist/{antigravity-cli-JEOUP2VN.js.map → antigravity-cli-LLRPDDOT.js.map} +0 -0
  144. /package/dist/{chunk-SCVBYSF7.js.map → chunk-6XHB6BE3.js.map} +0 -0
  145. /package/dist/{chunk-KQSNDFBN.js.map → chunk-LL4OBGRU.js.map} +0 -0
  146. /package/dist/{chunk-WNREHWKL.js.map → chunk-MAH6QQTO.js.map} +0 -0
  147. /package/dist/{codex-4BY2ZJIW.js.map → codex-BXA4FIF4.js.map} +0 -0
  148. /package/dist/{copilot-cli-IPISKO3V.js.map → copilot-cli-ROIBTTDT.js.map} +0 -0
  149. /package/dist/{crush-X3E25EQG.js.map → crush-QLEFLHUC.js.map} +0 -0
  150. /package/dist/{gemini-cli-ZSUK55UA.js.map → gemini-cli-SLVWLXJW.js.map} +0 -0
  151. /package/dist/{hermes-CUNKIAR5.js.map → hermes-ONDCECP2.js.map} +0 -0
  152. /package/dist/{jetbrains-copilot-C3HDGGML.js.map → jetbrains-copilot-YABZ3HFA.js.map} +0 -0
  153. /package/dist/{kilo-PKAJCWPX.js.map → kilo-F3ZDZKCT.js.map} +0 -0
  154. /package/dist/{kilo-cli-QWUVXG2O.js.map → kilo-cli-3HWPWBY4.js.map} +0 -0
  155. /package/dist/{kimi-EVD7YKXS.js.map → kimi-NV72FVAO.js.map} +0 -0
  156. /package/dist/{kiro-UQRY6EIO.js.map → kiro-C5W6AGDR.js.map} +0 -0
  157. /package/dist/{leaderboard-MUJ7DURM.js.map → leaderboard-TIBVONVT.js.map} +0 -0
  158. /package/dist/{mux-5CI5FP2W.js.map → mux-DSSH4AFS.js.map} +0 -0
  159. /package/dist/{omp-AXA7XY22.js.map → omp-Z6FRNDPN.js.map} +0 -0
  160. /package/dist/{opencode-NZBRLJN3.js.map → opencode-Q6KBSAKW.js.map} +0 -0
  161. /package/dist/{pi-WMTUX6ES.js.map → pi-LZT6WWAZ.js.map} +0 -0
  162. /package/dist/{qwen-code-MRRIUQ3P.js.map → qwen-code-WQBKRPWJ.js.map} +0 -0
  163. /package/dist/{usage-2BJLM3GJ.js.map → usage-E2A4O2CY.js.map} +0 -0
  164. /package/dist/{vscode-copilot-4RVRTCKV.js.map → vscode-copilot-ALV45XF6.js.map} +0 -0
  165. /package/dist/{warp-X6MB67NT.js.map → warp-H6IX4U3J.js.map} +0 -0
  166. /package/dist/{zed-NTCYW4V2.js.map → zed-RH34TNSW.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/runtime/serve.ts","../src/telemetry/calibration.ts","../src/telemetry/proxy.ts","../src/runtime/usage-event.ts","../src/runtime/statusline-entrypoint.ts","../src/runtime/action-entrypoint.ts"],"sourcesContent":["/**\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","/**\n * runtime/statusline-entrypoint — the universal statusline (HUD) renderer.\n *\n * A statusline-supporting host points its status line config at the single stable\n * home binary (`<homeBin> statusline <platformId> --connector <id>`, built by\n * core/spawn.buildHomeBinStatuslineCommand). The CLI reads stdin and calls\n * {@link runStatusline} with the parsed flags + the raw stdin string. This module:\n *\n * 1. Loads the registered connector (live render handler) and the host adapter.\n * 2. Parses the host's raw status payload into a normalized StatuslineContext.\n * 3. Calls the connector's render(ctx) and coerces the result to a string.\n * 4. Formats the line into the host's native status reply (exit code + stdout).\n *\n * FAIL-SAFE is the contract (NOT fail-open with carve-outs like hooks): a status\n * line is decorative — it must NEVER wedge the host or spew an error/stack trace\n * into the status bar. So ANY error path — bad payload, missing connector,\n * throwing render, adapter without statusline support — returns exit 0 with NO\n * stdout (an empty status line), never a non-zero exit and never partial output.\n *\n * NOTE (follow-up): no telemetry is recorded for statusline renders in v1 (out of\n * scope). When added, it MUST stay inside the same fail-safe envelope.\n */\n\nimport type { PlatformId } from \"../core/types.js\";\nimport { log } from \"../core/logger.js\";\nimport {\n loadRegisteredConnector,\n readRegisteredMeta,\n} from \"../core/load-connector.js\";\nimport { loadAdapter } from \"../adapters/registry.js\";\nimport { buildTelemetryAccessor } from \"./telemetry-accessor.js\";\n\n/** Flags + stdin the CLI hands to {@link runStatusline}. */\nexport interface RunStatuslineOptions {\n /** Host platform id from the command (`statusline <platformId> …`). */\n platformId: string;\n /** Connector id from `--connector <id>`. */\n connectorId: string;\n /** Raw stdin payload (host-native status JSON). Empty string is tolerated → `{}`. */\n stdin: string;\n}\n\n/** Process-level result the CLI translates into exit code + stdout/stderr. */\nexport interface RunStatuslineResult {\n exitCode: number;\n stdout?: string;\n stderr?: string;\n}\n\n/** The fail-safe result: exit 0, no output (an empty status line). */\nconst EMPTY: RunStatuslineResult = { exitCode: 0 };\n\n/**\n * Tolerantly parse the host's stdin payload. Empty / whitespace-only input is a\n * legitimate \"no payload\" signal and resolves to `{}`. Malformed JSON also\n * degrades to `{}` rather than throwing — fail-safe 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 * Render one host status-line invocation. Always resolves (never rejects): every\n * failure path returns the empty {@link EMPTY} result so the CLI exits cleanly\n * with an empty status line. See the module header for the fail-safe contract.\n */\nexport async function runStatusline(\n opts: RunStatuslineOptions,\n): Promise<RunStatuslineResult> {\n const { platformId, connectorId, stdin } = opts;\n\n try {\n const connector = await loadRegisteredConnector(connectorId);\n const adapter = await loadAdapter(platformId);\n\n // Nothing to render: no statusline declared, or the host adapter has no\n // statusline runtime support (parse/format pair). Empty line, exit 0.\n if (\n !connector.statusline ||\n typeof connector.statusline.render !== \"function\" ||\n !adapter ||\n !adapter.parseStatusInput ||\n !adapter.formatStatusOutput\n ) {\n return EMPTY;\n }\n\n const raw = parseStdin(stdin);\n const ctx = adapter.parseStatusInput(raw);\n // The command carries the authoritative connector id; stamp it so render()\n // sees the connector it was dispatched for.\n ctx.connectorId = connectorId;\n // capabilities is REQUIRED on StatuslineContext. claude-code's parseStatusInput\n // sets it, but a future/third-party adapter could omit it — backfill so the\n // runtime guarantee matches the type (mirrors the simulate harness). Never\n // let render() see undefined capabilities while the type claims it is present.\n if (ctx.capabilities == null) ctx.capabilities = adapter.capabilities;\n // Recover the install scope from the registered metadata (sync) and stamp it\n // onto the ctx — scope is an install-time property the entrypoint has no\n // other access to. Undefined when the meta carries none. Also expose the\n // per-connector telemetry usage accessor (lazy, fail-safe to zeros).\n ctx.scope = readRegisteredMeta(connectorId)?.scope;\n ctx.telemetry = buildTelemetryAccessor(connectorId);\n\n // Per-host render override: when rendering for host X, `hosts[X].render`\n // wins over the top-level render; a host not listed (or a per-host entry\n // that is somehow not a function) falls back to the top-level render.\n // Selection NEVER throws — fail-safe is preserved.\n const perHost = connector.statusline.hosts?.[platformId as PlatformId]?.render;\n const render =\n typeof perHost === \"function\" ? perHost : connector.statusline.render;\n\n const rendered = await render(ctx);\n // Coerce: a non-string return (number, accidental object) is stringified so\n // a misbehaving render never crashes the format step. null/undefined → \"\".\n const line = rendered == null ? \"\" : String(rendered);\n\n const reply = adapter.formatStatusOutput(line);\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-SAFE: a status line must never wedge the host or surface an error.\n // Log for diagnostics (stderr of the home binary — not the status bar) and\n // return the empty line.\n const message = err instanceof Error ? err.message : String(err);\n log.error(`statusline ${platformId} (${connectorId}) failed:`, message);\n return EMPTY;\n }\n}\n\nexport default runStatusline;\n","/**\n * runtime/action-entrypoint — the universal user-invokable action dispatcher.\n *\n * A future host affordance (slash command / keybinding) points at the single\n * stable home binary (`<homeBin> action <platformId> <actionId> --connector\n * <id>`, built by core/spawn.buildHomeBinActionCommand). The CLI parses the\n * flags and calls {@link runAction}. This module:\n *\n * 1. Loads the registered connector (live run handler) and the host adapter.\n * 2. Builds the shared {@link HostCtx} (host + the adapter's capabilities; NO\n * stdin — an action takes no host payload, unlike a hook or status line).\n * 3. Finds the action by id, resolves the per-host run override, runs it, and\n * prints the optional result.message.\n *\n * USER-TRIGGERED ERROR SEMANTICS (the key difference from hooks/statusline):\n * actions are invoked DELIBERATELY by a user, so errors are SURFACED, never\n * failed silently. An unknown action id or a throwing run → exit 1 + a stderr\n * message. (Hooks fail-open to exit 0; the statusline fail-safes to an empty\n * line — both are passive surfaces a host fires automatically. An action is not:\n * swallowing its failure would leave the user staring at nothing, unable to\n * tell the action ran.)\n *\n * NOTE (follow-up): no telemetry is recorded for action runs in v1 (out of\n * scope), and no adapter EMITS the affordance yet — v1 ships the dispatch\n * backbone only.\n */\n\nimport type {\n HostCtx,\n PlatformCapabilities,\n PlatformId,\n} from \"../core/types.js\";\nimport {\n loadRegisteredConnector,\n readRegisteredMeta,\n} from \"../core/load-connector.js\";\nimport { loadAdapter, REGISTERED_PLATFORM_IDS } from \"../adapters/registry.js\";\nimport { buildTelemetryAccessor } from \"./telemetry-accessor.js\";\n\n/** Flags the CLI hands to {@link runAction} (no stdin — actions take no payload). */\nexport interface RunActionOptions {\n /** Host platform id from the command (`action <platformId> <actionId> …`). */\n platformId: string;\n /** Connector id from `--connector <id>`. */\n connectorId: string;\n /** The action id positional (`action <platformId> <actionId> …`). */\n actionId: string;\n}\n\n/** Process-level result the CLI translates into exit code + stdout/stderr. */\nexport interface RunActionResult {\n exitCode: number;\n stdout?: string;\n stderr?: string;\n}\n\n/**\n * Minimal all-false capabilities for the fallback ctx when the host adapter is\n * unknown/unregistered. The action still runs (it takes no host payload), but\n * branching on `ctx.capabilities` reads every flag as off — no affordance is\n * advertised for a host we cannot describe.\n */\nconst EMPTY_CAPABILITIES: PlatformCapabilities = {\n preToolUse: false,\n postToolUse: false,\n preCompact: false,\n sessionStart: false,\n sessionEnd: false,\n userPromptSubmit: false,\n stop: false,\n notification: false,\n canModifyArgs: false,\n canModifyOutput: false,\n canInjectSessionContext: false,\n transports: [],\n};\n\n/**\n * Dispatch one user-invokable action. Always resolves (never rejects): every\n * path returns a concrete {@link RunActionResult} so the CLI can exit cleanly,\n * but UNLIKE the hook/statusline runtimes an error resolves to exit 1 + a stderr\n * message (actions are user-triggered — surface the failure). See the module\n * header for the user-triggered error contract.\n */\nexport async function runAction(\n opts: RunActionOptions,\n): Promise<RunActionResult> {\n const { platformId, connectorId, actionId } = opts;\n\n let connector;\n try {\n connector = await loadRegisteredConnector(connectorId);\n } catch (err) {\n // A user asked to run an action on a connector we cannot load — surface it\n // (do NOT fail-open: the user would otherwise see nothing and assume it ran).\n const message = err instanceof Error ? err.message : String(err);\n return { exitCode: 1, stderr: message };\n }\n\n const action = connector.actions.find((a) => a.id === actionId);\n if (!action) {\n return {\n exitCode: 1,\n stderr: `no action \"${actionId}\" on connector ${connectorId}`,\n };\n }\n\n // Build the shared HostCtx. capabilities come from the adapter; an unknown\n // adapter still runs with the minimal ctx (an action takes no host payload).\n const adapter = await loadAdapter(platformId).catch(() => undefined);\n const host: PlatformId = REGISTERED_PLATFORM_IDS.has(platformId as PlatformId)\n ? (platformId as PlatformId)\n : \"unknown\";\n const ctx: HostCtx = {\n host,\n capabilities: adapter?.capabilities ?? EMPTY_CAPABILITIES,\n // Recover the install scope from the registered metadata (sync) — scope is\n // an install-time property the entrypoint otherwise has no access to —\n // and expose the per-connector telemetry usage accessor (lazy, fail-safe).\n scope: readRegisteredMeta(connectorId)?.scope,\n telemetry: buildTelemetryAccessor(connectorId),\n };\n\n // Per-host run override: when running for host X, `hosts[X].run` wins over the\n // top-level run; a host not listed (or a per-host entry that is somehow not a\n // function) falls back to the top-level run.\n const perHost = action.hosts?.[platformId as PlatformId]?.run;\n const run = typeof perHost === \"function\" ? perHost : action.run;\n\n try {\n const result = await run(ctx);\n const message = result?.message;\n if (typeof message === \"string\" && message !== \"\") {\n return { exitCode: 0, stdout: message };\n }\n // void / no message → success with no output.\n return { exitCode: 0 };\n } catch (err) {\n // USER-TRIGGERED: a throwing action surfaces its failure (exit 1 + stderr),\n // never a silent fail-open. This is the documented difference from\n // hooks/statusline.\n const message = err instanceof Error ? err.message : String(err);\n return {\n exitCode: 1,\n stderr: `action \"${actionId}\" failed: ${message}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IACxC;AAEA,WAAO,EAAE,UAAU,EAAE;AAAA,EACvB,SAAS,KAAK;AAIZ,UAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC/D,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ,WAAW,QAAQ,aAAa,OAAO;AAAA,IACjD;AAAA,EACF;AACF;","names":["args","isObject"]}
@@ -9,6 +9,9 @@ function narrowInstallScope(scope) {
9
9
  function quoteArg(arg) {
10
10
  return `"${arg.replace(/\\/g, "/")}"`;
11
11
  }
12
+ function hasVerbSlot(hay, homeBinNorm, verb) {
13
+ return hay.includes(`"${homeBinNorm}" ${verb} `);
14
+ }
12
15
  function buildHomeBinHookCommand(homeBinPath, platformId, event, connectorId) {
13
16
  return `${quoteArg(homeBinPath)} hook ${platformId} ${event} --connector ${connectorId}`;
14
17
  }
@@ -32,8 +35,20 @@ function buildUsageEventCommand(homeBinPath, platformId, connectorId) {
32
35
  function isUsageEventCommand(command, homeBinPath, connectorId) {
33
36
  if (!command) return false;
34
37
  const hay = command.replace(/\\/g, "/");
35
- if (!hay.includes(homeBinPath.replace(/\\/g, "/"))) return false;
36
- if (!hay.includes(" usage-event ")) return false;
38
+ const homeBinNorm = homeBinPath.replace(/\\/g, "/");
39
+ if (!hay.includes(homeBinNorm)) return false;
40
+ if (!hasVerbSlot(hay, homeBinNorm, "usage-event")) return false;
41
+ return isHomeBinHookCommand(command, homeBinPath, connectorId);
42
+ }
43
+ function buildHomeBinStatuslineCommand(homeBinPath, platformId, connectorId) {
44
+ return `${quoteArg(homeBinPath)} statusline ${platformId} --connector ${connectorId}`;
45
+ }
46
+ function isHomeBinStatuslineCommand(command, homeBinPath, connectorId) {
47
+ if (!command) return false;
48
+ const hay = command.replace(/\\/g, "/");
49
+ const homeBinNorm = homeBinPath.replace(/\\/g, "/");
50
+ if (!hay.includes(homeBinNorm)) return false;
51
+ if (!hasVerbSlot(hay, homeBinNorm, "statusline")) return false;
37
52
  return isHomeBinHookCommand(command, homeBinPath, connectorId);
38
53
  }
39
54
  function isHostNativeUsageEnabled(telemetry, env = process.env) {
@@ -102,10 +117,12 @@ export {
102
117
  isHomeBinHookCommand,
103
118
  buildUsageEventCommand,
104
119
  isUsageEventCommand,
120
+ buildHomeBinStatuslineCommand,
121
+ isHomeBinStatuslineCommand,
105
122
  isHostNativeUsageEnabled,
106
123
  shouldWrapForTelemetry,
107
124
  buildServeWrapperCommand,
108
125
  resolveSpawnCommand,
109
126
  detectLaunchMethod
110
127
  };
111
- //# sourceMappingURL=chunk-MEH7GC7R.js.map
128
+ //# sourceMappingURL=chunk-BXGFUENQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/spawn.ts"],"sourcesContent":["/**\n * core/spawn — cross-platform command construction.\n *\n * Borrowed from context-mode (issues #369/#372/#548/#738): bare `node` is\n * unreliable on Windows Git Bash (MSYS) and MSYS rewrites absolute paths on\n * non-C: drives. Always use the resolved runtime path, forward slashes, and\n * double-quoting. No-ops on macOS/Linux.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport type { InstallScope, PlatformId, ServerDef } from \"./types.js\";\nimport type {\n LaunchMethod,\n TelemetryInstallScope,\n} from \"../telemetry/types.js\";\n\n/**\n * Narrow the framework's 5-value {@link InstallScope} down to the two telemetry\n * slicing buckets: only a `project`-local install is `project`; everything else\n * (system/user/profile/managed) is global and reads as `user`.\n */\nexport function narrowInstallScope(scope: InstallScope): TelemetryInstallScope {\n return scope === \"project\" ? \"project\" : \"user\";\n}\n\n/** Build `\"<nodePath>\" \"<scriptPath>\"`. */\nexport function buildNodeCommand(\n scriptPath: string,\n opts?: { nodePath?: string },\n): string {\n const nodePath = (opts?.nodePath ?? process.execPath).replace(/\\\\/g, \"/\");\n const safe = scriptPath.replace(/\\\\/g, \"/\");\n return `\"${nodePath}\" \"${safe}\"`;\n}\n\n/**\n * Strict inverse of buildNodeCommand. Returns the two quoted tokens, or null if\n * `cmd` was not produced by buildNodeCommand (no fragile last-whitespace tail\n * grabbing — that was the #548 doubled-path bug when paths contained spaces).\n */\nexport function parseNodeCommand(\n cmd: string,\n): { nodePath: string; scriptPath: string } | null {\n if (typeof cmd !== \"string\" || cmd.length === 0) return null;\n const m = cmd.match(/^\"([^\"]+)\"\\s+\"([^\"]+)\"\\s*$/);\n if (!m || !m[1] || !m[2]) return null;\n return { nodePath: m[1], scriptPath: m[2] };\n}\n\n/** Quote a single argument for inclusion in a host hook command string. */\nexport function quoteArg(arg: string): string {\n return `\"${arg.replace(/\\\\/g, \"/\")}\"`;\n}\n\n/**\n * True when `hay` (slash-normalized) has the quoted home-bin path IMMEDIATELY\n * followed by `verb` — i.e. the verb sits in its command SLOT (right after the\n * home binary), not merely somewhere in the argument list. This distinguishes\n * `\"<bin>\" statusline …` from `\"<bin>\" action … statusline …`: the action verb\n * takes a free-form `actionId` positional that can legitimately equal another\n * verb's name (`statusline` / `usage-event` / `hook`), and only the SLOT\n * position identifies the real verb. `homeBinNorm` is the slash-normalized\n * home-bin path the caller already derived.\n */\nfunction hasVerbSlot(hay: string, homeBinNorm: string, verb: string): boolean {\n return hay.includes(`\"${homeBinNorm}\" ${verb} `);\n}\n\n/**\n * Build the universal hook command a host config points at:\n * \"<homeBin>\" hook <platformId> <event> --connector <id>\n * Pointing every host at the one stable home binary is how a single update\n * propagates everywhere (docs/ARCHITECTURE.md §3 R1).\n */\nexport function buildHomeBinHookCommand(\n homeBinPath: string,\n platformId: string,\n event: string,\n connectorId: string,\n): string {\n return `${quoteArg(homeBinPath)} hook ${platformId} ${event} --connector ${connectorId}`;\n}\n\n/**\n * True when `command` is a home-bin hook command for exactly `connectorId`.\n *\n * Critical: the connector id is the LAST token of the hook command\n * (`... --connector <id>`), so a naive `command.includes(\"--connector \" + id)`\n * collides on shared-prefix ids — `--connector acme-db` contains\n * `--connector acme`, which would let uninstalling `acme` strip `acme-db`'s\n * hooks. We anchor the id token: the character after it must be end-of-string,\n * whitespace, or a closing double-quote (the JSON-embedded case). Connector ids\n * are kebab-case (ID_RE) so they never contain whitespace or quotes themselves.\n */\nexport function isHomeBinHookCommand(\n command: string | undefined,\n homeBinPath: string,\n connectorId: string,\n): boolean {\n if (!command) return false;\n // The stored command was forward-slashed by quoteArg(); homeBinPath() yields\n // NATIVE (back)slashes on Windows (node:path join). Normalize BOTH sides so the\n // ownership substring test holds on win32 (without this, detection always\n // returns false there → duplicate hooks on re-install + orphans on uninstall).\n // No-op on POSIX.\n const hay = command.replace(/\\\\/g, \"/\");\n if (!hay.includes(homeBinPath.replace(/\\\\/g, \"/\"))) return false;\n const token = `--connector ${connectorId}`;\n let from = 0;\n for (;;) {\n const idx = hay.indexOf(token, from);\n if (idx < 0) return false;\n const after = hay.charAt(idx + token.length);\n if (after === \"\" || after === '\"' || /\\s/.test(after)) return true;\n from = idx + token.length;\n }\n}\n\n/**\n * Build the OPT-IN host-native usage-event command an AfterModel / PostInvocation\n * hook points at:\n * \"<homeBin>\" usage-event <platformId> --connector <id>\n * Mirrors {@link buildHomeBinHookCommand} (same anchoring rules apply) but routes\n * to the hidden `usage-event` entrypoint, which records a DISTINCT `model_turn`\n * row instead of dispatching a connector handler.\n */\nexport function buildUsageEventCommand(\n homeBinPath: string,\n platformId: string,\n connectorId: string,\n): string {\n return `${quoteArg(homeBinPath)} usage-event ${platformId} --connector ${connectorId}`;\n}\n\n/**\n * True when `command` is OUR host-native usage-event command for exactly\n * `connectorId`. Same end-of-token anchoring as {@link isHomeBinHookCommand} so a\n * shared-prefix id can't collide; additionally requires the ` usage-event ` verb\n * so it is never confused with a plain `hook` command during uninstall.\n */\nexport function isUsageEventCommand(\n command: string | undefined,\n homeBinPath: string,\n connectorId: string,\n): boolean {\n if (!command) return false;\n // Normalize separators like isHomeBinHookCommand (win32 ownership detection).\n const hay = command.replace(/\\\\/g, \"/\");\n const homeBinNorm = homeBinPath.replace(/\\\\/g, \"/\");\n if (!hay.includes(homeBinNorm)) return false;\n if (!hasVerbSlot(hay, homeBinNorm, \"usage-event\")) return false;\n return isHomeBinHookCommand(command, homeBinPath, connectorId);\n}\n\n/**\n * Build the home-bin statusline command a host's status line config points at:\n * \"<homeBin>\" statusline <platformId> --connector <id>\n * Mirrors {@link buildHomeBinHookCommand} / {@link buildUsageEventCommand} (the\n * same single-home-binary indirection) but routes to the `statusline`\n * entrypoint, which renders the connector's HUD line for the host.\n */\nexport function buildHomeBinStatuslineCommand(\n homeBinPath: string,\n platformId: string,\n connectorId: string,\n): string {\n return `${quoteArg(homeBinPath)} statusline ${platformId} --connector ${connectorId}`;\n}\n\n/**\n * True when `command` is OUR home-bin statusline command for exactly\n * `connectorId`. Same end-of-token anchoring as {@link isHomeBinHookCommand} so a\n * shared-prefix id can't collide; additionally requires the ` statusline ` verb\n * so it is never confused with a plain `hook` / `usage-event` command.\n */\nexport function isHomeBinStatuslineCommand(\n command: string | undefined,\n homeBinPath: string,\n connectorId: string,\n): boolean {\n if (!command) return false;\n // Normalize separators like isHomeBinHookCommand (win32 ownership detection).\n const hay = command.replace(/\\\\/g, \"/\");\n const homeBinNorm = homeBinPath.replace(/\\\\/g, \"/\");\n if (!hay.includes(homeBinNorm)) return false;\n if (!hasVerbSlot(hay, homeBinNorm, \"statusline\")) return false;\n return isHomeBinHookCommand(command, homeBinPath, connectorId);\n}\n\n/**\n * Build the home-bin action command a future host affordance (slash command /\n * keybinding) points at:\n * \"<homeBin>\" action <platformId> <actionId> --connector <id>\n * Mirrors {@link buildHomeBinStatuslineCommand} (the same single-home-binary\n * indirection) but routes to the `action` entrypoint, which re-imports the\n * connector and runs the named action's run(ctx). v1 ships only this command\n * builder + the runtime verb; no adapter EMITS the affordance yet.\n */\nexport function buildHomeBinActionCommand(\n homeBinPath: string,\n platformId: string,\n actionId: string,\n connectorId: string,\n): string {\n return `${quoteArg(homeBinPath)} action ${platformId} ${actionId} --connector ${connectorId}`;\n}\n\n/**\n * True when `command` is OUR home-bin action command for exactly `connectorId`.\n * Same end-of-token anchoring as {@link isHomeBinHookCommand} so a shared-prefix\n * id can't collide; additionally requires the ` action ` verb so it is never\n * confused with a plain `hook` / `usage-event` / `statusline` command.\n */\nexport function isHomeBinActionCommand(\n command: string | undefined,\n homeBinPath: string,\n connectorId: string,\n): boolean {\n if (!command) return false;\n // Normalize separators like isHomeBinHookCommand (win32 ownership detection).\n const hay = command.replace(/\\\\/g, \"/\");\n const homeBinNorm = homeBinPath.replace(/\\\\/g, \"/\");\n if (!hay.includes(homeBinNorm)) return false;\n if (!hasVerbSlot(hay, homeBinNorm, \"action\")) return false;\n return isHomeBinHookCommand(command, homeBinPath, connectorId);\n}\n\n/**\n * Single source of truth for \"is OPT-IN host-native turn-usage capture enabled\n * for this connector?\" — read by the Gemini / Antigravity adapters at install\n * time to decide whether to ALSO write the AfterModel / PostInvocation usage hook.\n * Enabled when the connector opts in via telemetry.hostNativeUsage OR when the\n * install-time env switch AGENT_CONNECTOR_HOST_NATIVE=1 forces it on. Off by\n * default (privacy: host-native capture is never installed silently).\n */\nexport function isHostNativeUsageEnabled(\n telemetry: { enabled: boolean; hostNativeUsage?: boolean },\n env: NodeJS.ProcessEnv = process.env,\n): boolean {\n if (telemetry.enabled !== true) return false;\n if (env.AGENT_CONNECTOR_HOST_NATIVE === \"1\") return true;\n return telemetry.hostNativeUsage === true;\n}\n\n/**\n * Single source of truth for \"should this server be wrapped by `serve` for\n * telemetry?\" — so every adapter behaves identically even for a server that\n * skipped normalizeServer (e.g. a per-platform override). On by default for an\n * stdio server with a command, unless explicitly disabled or telemetry is off.\n */\nexport function shouldWrapForTelemetry(\n server: ServerDef,\n telemetry: { enabled: boolean },\n): boolean {\n return (\n server.wrapForTelemetry !== false &&\n telemetry.enabled === true &&\n server.transport === \"stdio\" &&\n typeof server.command === \"string\" &&\n server.command !== \"\"\n );\n}\n\n/**\n * Build the telemetry-wrapping server command:\n * \"<homeBin>\" serve --connector <id> --scope <scope> --host <platformId> -- <realCommand> <realArgs...>\n * Used when a stdio server opts into transparent telemetry capture.\n *\n * `scope` records the install dimension (global user vs project-local) on every\n * telemetry row so usage can be sliced by it later. It is OPTIONAL for backward\n * compatibility: when omitted, the `--scope` flag is not emitted and the runtime\n * treats the scope as \"unknown\".\n *\n * `platformId` bakes the install TARGET platform into the wrapper so the proxy\n * stamps `hostPlatform` correctly even under a headless spawn where runtime env\n * markers are absent (detectRuntimeHost only knows claude-code/cursor/codex and\n * otherwise mis-attributes). Emitted as `--host <platformId>` in the FLAG\n * section (before `--`). It is OPTIONAL + backward-compatible: when omitted the\n * `--host` flag is not emitted and the runtime falls back to env detection.\n */\nexport function buildServeWrapperCommand(\n homeBinPath: string,\n connectorId: string,\n realCommand: string,\n realArgs: string[],\n scope?: InstallScope,\n platformId?: PlatformId,\n): { command: string; args: string[] } {\n const flags = [\"serve\", \"--connector\", connectorId];\n if (scope !== undefined) flags.push(\"--scope\", narrowInstallScope(scope));\n if (platformId !== undefined) flags.push(\"--host\", platformId);\n return {\n command: homeBinPath,\n args: [...flags, \"--\", realCommand, ...realArgs],\n };\n}\n\n/** Injectable deps for {@link resolveSpawnCommand} (so the win32 branch is unit-testable on POSIX). */\nexport interface SpawnResolveDeps {\n platform?: NodeJS.Platform;\n /** PATH value (`;`-separated on Windows). */\n pathEnv?: string;\n /** PATHEXT value (`;`-separated). */\n pathExt?: string;\n /** File-existence probe (defaults to fs.existsSync). */\n exists?: (p: string) => boolean;\n}\n\n/** How a child command should be handed to spawn() on this platform. */\nexport interface SpawnResolution {\n /** The command to pass to spawn() (an absolute path on win32 when resolved). */\n file: string;\n /**\n * Whether spawn() MUST use `shell: true`. On native Windows a `.cmd`/`.bat`\n * shim (npx.cmd, pnpm.cmd, the agent-connector.cmd launcher) cannot be run by\n * raw CreateProcess — Node throws EINVAL since the 2024 security fix unless a\n * shell is used. `.exe` resolves directly with no shell.\n */\n needsShell: boolean;\n}\n\n/**\n * Resolve a child command for spawn() across platforms. NO-OP on macOS/Linux\n * (returns the command unchanged, no shell). On native Windows it fixes the two\n * spawn failure modes for bare package runners:\n * 1. raw CreateProcess ignores PATHEXT, so spawn(\"npx\") → ENOENT even though\n * `npx.cmd` is on PATH. We search PATH × PATHEXT and return the resolved\n * absolute path.\n * 2. a resolved `.cmd`/`.bat` still cannot be launched without a shell, so we\n * flag `needsShell` for those (and `.exe`/`.com` run directly).\n * A bare name that PATH search misses falls back to `{ file: command,\n * needsShell: true }` so cmd.exe's own PATHEXT lookup still finds it.\n */\nexport function resolveSpawnCommand(\n command: string,\n deps: SpawnResolveDeps = {},\n): SpawnResolution {\n const platform = deps.platform ?? process.platform;\n if (platform !== \"win32\") return { file: command, needsShell: false };\n\n const isBatch = (s: string): boolean => /\\.(cmd|bat)$/i.test(s);\n\n // Already a path or already has an extension → don't search; only decide shell.\n if (/[\\\\/]/.test(command) || /\\.[a-z0-9]+$/i.test(command)) {\n return { file: command, needsShell: isBatch(command) };\n }\n\n const exists = deps.exists ?? existsSync;\n const pathEnv = deps.pathEnv ?? process.env.PATH ?? process.env.Path ?? \"\";\n const pathExt = deps.pathExt ?? process.env.PATHEXT ?? \".COM;.EXE;.BAT;.CMD\";\n const dirs = pathEnv.split(\";\").filter((d) => d !== \"\");\n const exts = pathExt.split(\";\").filter((e) => e !== \"\");\n for (const dir of dirs) {\n for (const ext of exts) {\n const candidate = join(dir, command + ext);\n if (exists(candidate)) return { file: candidate, needsShell: isBatch(ext) };\n }\n }\n // Not found on PATH — let cmd.exe resolve it (handles shim dirs we may miss).\n return { file: command, needsShell: true };\n}\n\n/** Basenames (case-insensitive, sans common extensions) of the ephemeral package runners. */\nconst PACKAGE_RUNNERS: Record<string, Extract<LaunchMethod, \"npx\" | \"bunx\" | \"uvx\">> = {\n npx: \"npx\",\n bunx: \"bunx\",\n uvx: \"uvx\",\n};\n\n/** Basenames of language interpreters that launch a local script. */\nconst INTERPRETERS: ReadonlySet<string> = new Set([\"node\", \"bun\", \"deno\"]);\n\n/**\n * Strip a directory prefix and a trailing executable extension to get the bare\n * program name. Tolerates both POSIX and Windows separators (the wrapped command\n * may be an absolute Windows path) and lowercases for case-insensitive matching.\n */\nfunction commandBasename(realCommand: string): string {\n const noDir = realCommand.replace(/\\\\/g, \"/\").split(\"/\").pop() ?? realCommand;\n return noDir.replace(/\\.(exe|cmd|bat|com)$/i, \"\").toLowerCase();\n}\n\n/**\n * Classify how the real MCP server is launched, for the \"launch-method\" slicing\n * dimension. Package runners (npx/bunx/uvx) and interpreters (node/bun/deno) are\n * detected by the command basename. A remote (http) server is not launched\n * locally, so the caller — which alone knows the transport — passes\n * `isRemote: true` to force \"http\". Anything else resolves to \"binary\".\n */\nexport function detectLaunchMethod(\n realCommand: string,\n realArgs: string[],\n opts?: { isRemote?: boolean },\n): LaunchMethod {\n void realArgs; // reserved: args may later refine node-vs-script heuristics\n if (opts?.isRemote === true) return \"http\";\n if (typeof realCommand !== \"string\" || realCommand.trim() === \"\") {\n return \"unknown\";\n }\n const base = commandBasename(realCommand);\n if (base === \"\") return \"unknown\";\n const runner = PACKAGE_RUNNERS[base];\n if (runner !== undefined) return runner;\n if (INTERPRETERS.has(base)) return \"node\";\n return \"binary\";\n}\n"],"mappings":";;;AASA,SAAS,kBAAkB;AAC3B,SAAS,YAAY;AAad,SAAS,mBAAmB,OAA4C;AAC7E,SAAO,UAAU,YAAY,YAAY;AAC3C;AA2BO,SAAS,SAAS,KAAqB;AAC5C,SAAO,IAAI,IAAI,QAAQ,OAAO,GAAG,CAAC;AACpC;AAYA,SAAS,YAAY,KAAa,aAAqB,MAAuB;AAC5E,SAAO,IAAI,SAAS,IAAI,WAAW,KAAK,IAAI,GAAG;AACjD;AAQO,SAAS,wBACd,aACA,YACA,OACA,aACQ;AACR,SAAO,GAAG,SAAS,WAAW,CAAC,SAAS,UAAU,IAAI,KAAK,gBAAgB,WAAW;AACxF;AAaO,SAAS,qBACd,SACA,aACA,aACS;AACT,MAAI,CAAC,QAAS,QAAO;AAMrB,QAAM,MAAM,QAAQ,QAAQ,OAAO,GAAG;AACtC,MAAI,CAAC,IAAI,SAAS,YAA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,SAAS,EAAG,QAAO,EAAE,MAAM,WAAW,YAAY,QAAQ,GAAG,EAAE;AAAA,IAC5E;AAAA,EACF;AAEA,SAAO,EAAE,MAAM,SAAS,YAAY,KAAK;AAC3C;AAGA,IAAM,kBAAiF;AAAA,EACrF,KAAK;AAAA,EACL,MAAM;AAAA,EACN,KAAK;AACP;AAGA,IAAM,eAAoC,oBAAI,IAAI,CAAC,QAAQ,OAAO,MAAM,CAAC;AAOzE,SAAS,gBAAgB,aAA6B;AACpD,QAAM,QAAQ,YAAY,QAAQ,OAAO,GAAG,EAAE,MAAM,GAAG,EAAE,IAAI,KAAK;AAClE,SAAO,MAAM,QAAQ,yBAAyB,EAAE,EAAE,YAAY;AAChE;AASO,SAAS,mBACd,aACA,UACA,MACc;AACd,OAAK;AACL,MAAI,MAAM,aAAa,KAAM,QAAO;AACpC,MAAI,OAAO,gBAAgB,YAAY,YAAY,KAAK,MAAM,IAAI;AAChE,WAAO;AAAA,EACT;AACA,QAAM,OAAO,gBAAgB,WAAW;AACxC,MAAI,SAAS,GAAI,QAAO;AACxB,QAAM,SAAS,gBAAgB,IAAI;AACnC,MAAI,WAAW,OAAW,QAAO;AACjC,MAAI,aAAa,IAAI,IAAI,EAAG,QAAO;AACnC,SAAO;AACT;","names":[]}
@@ -0,0 +1,351 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ getTokenizer,
4
+ inferModelFamily,
5
+ newRecordId,
6
+ openStore,
7
+ worstConfidence
8
+ } from "./chunk-BCHWFTV4.js";
9
+ import {
10
+ log
11
+ } from "./chunk-KHO5WNTP.js";
12
+ import {
13
+ loadRegisteredConnector,
14
+ readRegisteredMeta
15
+ } from "./chunk-KGJWE6A2.js";
16
+ import {
17
+ REGISTERED_PLATFORM_IDS,
18
+ loadAdapter
19
+ } from "./chunk-3PFFTFCU.js";
20
+ import {
21
+ projectIdentity
22
+ } from "./chunk-TRQKHP7D.js";
23
+
24
+ // src/runtime/telemetry-accessor.ts
25
+ var ZERO = {
26
+ inputTokens: 0,
27
+ outputTokens: 0,
28
+ totalTokens: 0,
29
+ calls: 0
30
+ };
31
+ function buildTelemetryAccessor(connectorId) {
32
+ return async () => {
33
+ if (process.env.AGENT_CONNECTOR_TELEMETRY === "0") return { ...ZERO };
34
+ try {
35
+ const store = openStore({});
36
+ try {
37
+ let inputTokens = 0;
38
+ let outputTokens = 0;
39
+ let calls = 0;
40
+ for (const row of store.query({ connectorId })) {
41
+ inputTokens += Number.isFinite(row.inputTokens) ? row.inputTokens : 0;
42
+ outputTokens += Number.isFinite(row.outputTokens) ? row.outputTokens : 0;
43
+ calls += 1;
44
+ }
45
+ return {
46
+ inputTokens,
47
+ outputTokens,
48
+ totalTokens: inputTokens + outputTokens,
49
+ calls
50
+ };
51
+ } finally {
52
+ store.close();
53
+ }
54
+ } catch {
55
+ return { ...ZERO };
56
+ }
57
+ };
58
+ }
59
+
60
+ // src/telemetry/measure.ts
61
+ var MODALITY_ESTIMATE = {
62
+ image: 85,
63
+ audio: 85,
64
+ resource: 85
65
+ };
66
+ var UNKNOWN_BLOCK_ESTIMATE = 85;
67
+ function combineSources(sources) {
68
+ let worst = "host-native";
69
+ for (const s of sources) worst = worstConfidence(worst, s);
70
+ return worst;
71
+ }
72
+ function isObject(v) {
73
+ return typeof v === "object" && v !== null;
74
+ }
75
+ function isTextBlock(block) {
76
+ return block.type === "text";
77
+ }
78
+ function measureToolCall(args, result, family, tok = getTokenizer()) {
79
+ const input = tok.countValue(args, family);
80
+ const output = measureResult(result, family, tok);
81
+ return {
82
+ inputTokens: input.tokens,
83
+ outputTokens: output.tokens,
84
+ source: worstConfidence(input.source, output.source)
85
+ };
86
+ }
87
+ function measureResult(result, family, tok) {
88
+ if (!isObject(result)) {
89
+ return tok.countValue(result, family);
90
+ }
91
+ const res = result;
92
+ const sources = [];
93
+ let tokens = 0;
94
+ if (Array.isArray(res.content)) {
95
+ for (const raw of res.content) {
96
+ if (!isObject(raw)) continue;
97
+ const block = raw;
98
+ if (isTextBlock(block)) {
99
+ const text = typeof block.text === "string" ? block.text : "";
100
+ const c = tok.count(text, family);
101
+ tokens += c.tokens;
102
+ sources.push(c.source);
103
+ } else {
104
+ const key = typeof block.type === "string" ? block.type : "";
105
+ tokens += MODALITY_ESTIMATE[key] ?? UNKNOWN_BLOCK_ESTIMATE;
106
+ sources.push("tokenizer-approx");
107
+ }
108
+ }
109
+ } else if (res.content !== void 0) {
110
+ const c = tok.countValue(res.content, family);
111
+ tokens += c.tokens;
112
+ sources.push(c.source);
113
+ }
114
+ if (res.structuredContent !== void 0) {
115
+ const c = tok.countValue(res.structuredContent, family);
116
+ tokens += c.tokens;
117
+ sources.push(c.source);
118
+ }
119
+ if (sources.length === 0) {
120
+ return tok.countValue(result, family);
121
+ }
122
+ return { tokens, source: combineSources(sources) };
123
+ }
124
+ function measureToolDefs(tools, family, tok = getTokenizer()) {
125
+ return tok.countValue(tools, family);
126
+ }
127
+ function measureHook(eventPayload, handlerReturn, family, tok = getTokenizer()) {
128
+ const input = tok.countValue(eventPayload, family);
129
+ const output = tok.countValue(handlerReturn, family);
130
+ return {
131
+ inputTokens: input.tokens,
132
+ outputTokens: output.tokens,
133
+ source: worstConfidence(input.source, output.source)
134
+ };
135
+ }
136
+
137
+ // src/runtime/hook-entrypoint.ts
138
+ var ALLOW = { exitCode: 0 };
139
+ function eventMatcherSubject(evt) {
140
+ const name = evt.toolName;
141
+ if (typeof name === "string") return name;
142
+ const agentType = evt.agentType;
143
+ if (typeof agentType === "string") return agentType;
144
+ return void 0;
145
+ }
146
+ function parseStdin(stdin) {
147
+ const trimmed = stdin.trim();
148
+ if (trimmed === "") return {};
149
+ try {
150
+ return JSON.parse(trimmed);
151
+ } catch {
152
+ return {};
153
+ }
154
+ }
155
+ function compileMatcher(matcher) {
156
+ if (!matcher || matcher === "") return null;
157
+ try {
158
+ return new RegExp(matcher);
159
+ } catch {
160
+ return null;
161
+ }
162
+ }
163
+ function normalizeResponse(value) {
164
+ if (value == null || typeof value !== "object") return {};
165
+ return value;
166
+ }
167
+ function resolveHookHostPlatform(platformId, evt) {
168
+ const override = process.env.AGENT_CONNECTOR_HOST;
169
+ if (override !== void 0 && REGISTERED_PLATFORM_IDS.has(override)) {
170
+ return override;
171
+ }
172
+ if (REGISTERED_PLATFORM_IDS.has(platformId)) {
173
+ return platformId;
174
+ }
175
+ const fromEvent = evt.hostPlatform;
176
+ if (typeof fromEvent === "string" && REGISTERED_PLATFORM_IDS.has(fromEvent)) {
177
+ return fromEvent;
178
+ }
179
+ return "unknown";
180
+ }
181
+ function recordHookTelemetry(opts, connector, evt, response) {
182
+ if (process.env.AGENT_CONNECTOR_TELEMETRY === "0") return;
183
+ try {
184
+ const family = inferModelFamily("", connector.telemetry.modelFamilyHint);
185
+ const measurement = measureHook(evt, response, family, getTokenizer());
186
+ const sessionId = typeof evt.sessionId === "string" ? evt.sessionId : "";
187
+ const evtProjectDir = evt.projectDir;
188
+ const projectDir = typeof evtProjectDir === "string" && evtProjectDir !== "" ? evtProjectDir : process.cwd();
189
+ const id = projectIdentity(projectDir);
190
+ const store = openStore({});
191
+ try {
192
+ store.append({
193
+ id: newRecordId(0),
194
+ ts: Date.now(),
195
+ connectorId: opts.connectorId,
196
+ toolName: opts.event,
197
+ // for a hook row the per-item name IS the event
198
+ scope: "hook",
199
+ surfaceKind: "hook",
200
+ hostPlatform: resolveHookHostPlatform(opts.platformId, evt),
201
+ sessionId,
202
+ projectKey: id.key,
203
+ projectDir: id.dir,
204
+ inputTokens: measurement.inputTokens,
205
+ outputTokens: measurement.outputTokens,
206
+ confidenceSource: measurement.source,
207
+ isError: false
208
+ });
209
+ } finally {
210
+ store.close();
211
+ }
212
+ } catch {
213
+ }
214
+ }
215
+ async function runHook(opts) {
216
+ const { platformId, event, connectorId, stdin } = opts;
217
+ try {
218
+ const connector = await loadRegisteredConnector(connectorId);
219
+ const adapter = await loadAdapter(platformId);
220
+ if (!adapter || !adapter.parseEvent || !adapter.formatReply) {
221
+ return ALLOW;
222
+ }
223
+ const raw = parseStdin(stdin);
224
+ const evt = adapter.parseEvent(event, raw);
225
+ evt.connectorId = connectorId;
226
+ evt.capabilities = adapter.capabilities;
227
+ evt.scope = readRegisteredMeta(connectorId)?.scope;
228
+ evt.telemetry = buildTelemetryAccessor(connectorId);
229
+ const definition = connector.hooks[event];
230
+ if (!definition || typeof definition.handler !== "function") {
231
+ return ALLOW;
232
+ }
233
+ const perHost = definition.hosts?.[platformId]?.handler;
234
+ const handler = typeof perHost === "function" ? perHost : definition.handler;
235
+ const subject = eventMatcherSubject(evt);
236
+ if (subject !== void 0) {
237
+ const re = compileMatcher(definition.matcher);
238
+ if (re && !re.test(subject)) return ALLOW;
239
+ }
240
+ const handlerResult = await handler(
241
+ // The adapter parsed `evt` as exactly this event's payload type; the
242
+ // HooksConfig handler for the same event expects that payload.
243
+ evt
244
+ );
245
+ const response = normalizeResponse(handlerResult);
246
+ recordHookTelemetry(opts, connector, evt, response);
247
+ const reply = adapter.formatReply(event, response);
248
+ return {
249
+ exitCode: reply.exitCode,
250
+ ...reply.stdout !== void 0 ? { stdout: reply.stdout } : {},
251
+ ...reply.stderr !== void 0 ? { stderr: reply.stderr } : {}
252
+ };
253
+ } catch (err) {
254
+ const message = err instanceof Error ? err.message : String(err);
255
+ log.error(`hook ${platformId}/${event} (${connectorId}) failed:`, message);
256
+ return failOpenOrPreserveDeny(opts, message);
257
+ }
258
+ }
259
+ var DENY_PRESERVE_EVENTS = /* @__PURE__ */ new Set([
260
+ "PreToolUse",
261
+ "PermissionRequest"
262
+ ]);
263
+ async function failOpenOrPreserveDeny(opts, errorMessage) {
264
+ if (!DENY_PRESERVE_EVENTS.has(opts.event)) return ALLOW;
265
+ try {
266
+ const connector = await loadRegisteredConnector(opts.connectorId);
267
+ const adapter = await loadAdapter(opts.platformId);
268
+ if (!adapter?.parseEvent || !adapter.formatReply) return ALLOW;
269
+ const definition = connector.hooks[opts.event];
270
+ if (!definition || typeof definition.handler !== "function") return ALLOW;
271
+ const perHost = definition.hosts?.[opts.platformId]?.handler;
272
+ const handler = typeof perHost === "function" ? perHost : definition.handler;
273
+ const raw = parseStdin(opts.stdin);
274
+ const evt = adapter.parseEvent(opts.event, raw);
275
+ evt.connectorId = opts.connectorId;
276
+ evt.capabilities = adapter.capabilities;
277
+ evt.scope = readRegisteredMeta(opts.connectorId)?.scope;
278
+ evt.telemetry = buildTelemetryAccessor(opts.connectorId);
279
+ const subject = eventMatcherSubject(evt);
280
+ if (subject !== void 0) {
281
+ const re = compileMatcher(definition.matcher);
282
+ if (re && !re.test(subject)) return ALLOW;
283
+ }
284
+ const response = normalizeResponse(await handler(evt));
285
+ if (response.decision !== "deny") return ALLOW;
286
+ const reply = adapter.formatReply(opts.event, response);
287
+ return {
288
+ exitCode: reply.exitCode,
289
+ ...reply.stdout !== void 0 ? { stdout: reply.stdout } : {},
290
+ ...reply.stderr !== void 0 ? { stderr: reply.stderr } : { stderr: errorMessage }
291
+ };
292
+ } catch {
293
+ return ALLOW;
294
+ }
295
+ }
296
+ function nativeHookDef(connector, platformId, event) {
297
+ return connector.platforms[platformId]?.nativeHooks?.[event];
298
+ }
299
+ async function isNativeHookDeclared(platformId, event, connectorId) {
300
+ try {
301
+ const connector = await loadRegisteredConnector(connectorId);
302
+ return typeof nativeHookDef(connector, platformId, event)?.handler === "function";
303
+ } catch {
304
+ return false;
305
+ }
306
+ }
307
+ async function runNativeHook(opts) {
308
+ const { platformId, event, connectorId, stdin } = opts;
309
+ try {
310
+ const connector = await loadRegisteredConnector(connectorId);
311
+ const def = nativeHookDef(connector, platformId, event);
312
+ if (!def || typeof def.handler !== "function") {
313
+ return ALLOW;
314
+ }
315
+ const raw = parseStdin(stdin);
316
+ const sessionId = typeof raw?.session_id === "string" ? raw.session_id : "";
317
+ const cwd = raw?.cwd;
318
+ const evt = {
319
+ event,
320
+ hostPlatform: REGISTERED_PLATFORM_IDS.has(platformId) ? platformId : "unknown",
321
+ sessionId,
322
+ ...typeof cwd === "string" && cwd !== "" ? { projectDir: cwd } : {},
323
+ raw
324
+ };
325
+ const result = await def.handler(evt);
326
+ recordHookTelemetry(opts, connector, evt, result === void 0 ? {} : result);
327
+ if (result === void 0) return ALLOW;
328
+ const json = JSON.stringify(result);
329
+ if (json === void 0) return ALLOW;
330
+ return { exitCode: 0, stdout: json };
331
+ } catch (err) {
332
+ const message = err instanceof Error ? err.message : String(err);
333
+ log.error(
334
+ `native hook ${platformId}/${event} (${connectorId}) failed:`,
335
+ message
336
+ );
337
+ return ALLOW;
338
+ }
339
+ }
340
+
341
+ export {
342
+ buildTelemetryAccessor,
343
+ measureToolCall,
344
+ measureToolDefs,
345
+ eventMatcherSubject,
346
+ compileMatcher,
347
+ runHook,
348
+ isNativeHookDeclared,
349
+ runNativeHook
350
+ };
351
+ //# sourceMappingURL=chunk-CIRDOY2V.js.map