@ken-jo/agent-connector 0.4.75 → 0.4.91
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.
- package/README.md +3 -3
- package/dist/{action-TCKBTTZX.js → action-L44DXFHT.js} +14 -14
- package/dist/{amazon-q-CB4XFX7T.js → amazon-q-B52EY2SV.js} +5 -5
- package/dist/{amp-6Q5OYHNW.js → amp-UXABVUKC.js} +5 -5
- package/dist/{antigravity-WIK3XBN5.js → antigravity-RZHN53VB.js} +6 -6
- package/dist/antigravity-cli-JO6GUTV7.js +436 -0
- package/dist/antigravity-cli-JO6GUTV7.js.map +1 -0
- package/dist/{chunk-Q5LECKZL.js → chunk-25CPWJA7.js} +116 -36
- package/dist/chunk-25CPWJA7.js.map +1 -0
- package/dist/{chunk-D6ZJS4ND.js → chunk-4FWETID5.js} +2 -2
- package/dist/{chunk-Q42SEI7W.js → chunk-4HVQ7IUM.js} +3 -3
- package/dist/{chunk-IU42THN7.js → chunk-4NSU3KWX.js} +2 -2
- package/dist/{chunk-7CZKXXBD.js → chunk-56R2ER7K.js} +2 -2
- package/dist/{chunk-HKM3HUOK.js → chunk-7HUUINPB.js} +18 -18
- package/dist/{chunk-TZ5KGCE2.js → chunk-AY3RGRTT.js} +2 -2
- package/dist/{chunk-MHDQWZ4A.js → chunk-BLTVZACS.js} +23 -13
- package/dist/chunk-BLTVZACS.js.map +1 -0
- package/dist/{chunk-7ITLLYWB.js → chunk-G4CEELKO.js} +5 -5
- package/dist/{chunk-TO57WYBB.js → chunk-HORHRHNG.js} +9 -3
- package/dist/chunk-HORHRHNG.js.map +1 -0
- package/dist/{chunk-2HCJV6UO.js → chunk-IXOQDZWC.js} +9 -2
- package/dist/chunk-IXOQDZWC.js.map +1 -0
- package/dist/{chunk-2L6LTQ6L.js → chunk-KIRCPLM4.js} +21 -10
- package/dist/chunk-KIRCPLM4.js.map +1 -0
- package/dist/{chunk-24K6JOKV.js → chunk-LAIITCMW.js} +8 -8
- package/dist/{chunk-OEQJGBBW.js → chunk-LF76VPGQ.js} +9 -9
- package/dist/{chunk-7QRUZAUG.js → chunk-LN76OGNR.js} +2 -2
- package/dist/{chunk-DI6OWKH2.js → chunk-NBUEL74R.js} +3 -3
- package/dist/{chunk-IRUYJD23.js → chunk-NLE2J5P4.js} +1 -1
- package/dist/{chunk-5LAFKXFM.js → chunk-NWLRJNXM.js} +3 -3
- package/dist/{chunk-ECSRTK4M.js → chunk-QARPXSIV.js} +4 -4
- package/dist/{chunk-AXAHW2KU.js → chunk-QKLJU4JX.js} +2 -2
- package/dist/{chunk-MDZG5QHB.js → chunk-R6LML2YS.js} +2 -2
- package/dist/{chunk-FUXUEXDP.js → chunk-UBB7T54N.js} +3 -3
- package/dist/{chunk-NUGMVVV2.js → chunk-VVFDU4IX.js} +4 -4
- package/dist/{chunk-ALVXORZM.js → chunk-YYNXIUR2.js} +2 -2
- package/dist/{chunk-TW4DVR4V.js → chunk-ZMLVR4J7.js} +7 -2
- package/dist/chunk-ZMLVR4J7.js.map +1 -0
- package/dist/{claude-code-HFBAAVWS.js → claude-code-WS4NAGZT.js} +9 -9
- package/dist/cli/sdk.js +7 -7
- package/dist/cli.js +1 -1
- package/dist/{cline-26W4FEZ6.js → cline-NNMVCECA.js} +5 -5
- package/dist/codebuddy-RBEZGXBG.js +643 -0
- package/dist/codebuddy-RBEZGXBG.js.map +1 -0
- package/dist/{codebuff-J5KEEBIL.js → codebuff-RJIDSEU3.js} +5 -5
- package/dist/{codex-JKQ6TLRI.js → codex-ZZ434GYR.js} +8 -8
- package/dist/{continue-KQSJUSWX.js → continue-MNM7YVJY.js} +6 -6
- package/dist/{copilot-cli-YBNKLYUB.js → copilot-cli-SMTX5F65.js} +5 -5
- package/dist/{crush-JTWTZIPB.js → crush-NYDBHIJE.js} +5 -5
- package/dist/{cursor-2NIZSDZ4.js → cursor-AOELDNZU.js} +6 -6
- package/dist/{detect-CWEIQCRC.js → detect-3S46RUMK.js} +4 -4
- package/dist/devin-PRJY2TTD.js +510 -0
- package/dist/devin-PRJY2TTD.js.map +1 -0
- package/dist/{doctor-AC437ZAW.js → doctor-3CUBPQKU.js} +22 -22
- package/dist/{droid-HF2AIFB2.js → droid-PTCH2K7Y.js} +5 -5
- package/dist/{gemini-cli-2EOK26S2.js → gemini-cli-QGLN2UMS.js} +5 -5
- package/dist/{goose-55JOTXS5.js → goose-DQ6GSZ5O.js} +6 -6
- package/dist/grok-cli-5QD235UB.js +482 -0
- package/dist/grok-cli-5QD235UB.js.map +1 -0
- package/dist/{hermes-QVZOZU4B.js → hermes-E47IG63A.js} +6 -6
- package/dist/{hook-VYD3OCLM.js → hook-P6EKDINW.js} +14 -14
- package/dist/index.d.ts +2 -2
- package/dist/index.js +5 -5
- package/dist/{install-S6BYIJ62.js → install-7DMK53SB.js} +18 -18
- package/dist/{introspect-5o5ick0_.d.ts → introspect-DYOIX8Ov.d.ts} +1 -1
- package/dist/{jetbrains-copilot-DZ2ATXFN.js → jetbrains-copilot-T2EPKROP.js} +13 -7
- package/dist/jetbrains-copilot-T2EPKROP.js.map +1 -0
- package/dist/junie-SQ4SDLGK.js +227 -0
- package/dist/junie-SQ4SDLGK.js.map +1 -0
- package/dist/{kilo-GJNSBWVV.js → kilo-OU2ZLZKB.js} +8 -8
- package/dist/{kilo-cli-2CCB3DBI.js → kilo-cli-NMWGYF4F.js} +8 -8
- package/dist/{kimi-YRPCSB6N.js → kimi-Z7L2LEEI.js} +5 -5
- package/dist/{kiro-BUOQFASX.js → kiro-4IN5IH46.js} +81 -6
- package/dist/kiro-4IN5IH46.js.map +1 -0
- package/dist/{leaderboard-SUSUDKHR.js → leaderboard-LF5SP6X2.js} +7 -7
- package/dist/{mimo-code-V4FP5PUJ.js → mimo-code-G2CBZ4M6.js} +5 -5
- package/dist/mistral-vibe-TRQDHAWV.js +300 -0
- package/dist/mistral-vibe-TRQDHAWV.js.map +1 -0
- package/dist/{mux-CMJSM42O.js → mux-JNM3F2NW.js} +5 -5
- package/dist/{nemoclaw-VP56PGKC.js → nemoclaw-SHA4IUML.js} +6 -6
- package/dist/{omp-OOFGD3GG.js → omp-OOVUNXME.js} +5 -5
- package/dist/open-interpreter-4PKL56AA.js +264 -0
- package/dist/open-interpreter-4PKL56AA.js.map +1 -0
- package/dist/openclaw-BD56E5MV.js +17 -0
- package/dist/{opencode-MKLHSQRD.js → opencode-W2RK4M7G.js} +5 -5
- package/dist/openhands-5LNH3BKB.js +384 -0
- package/dist/openhands-5LNH3BKB.js.map +1 -0
- package/dist/{package-KOAAVKHH.js → package-2EAIYSJ4.js} +13 -13
- package/dist/{pi-NMVL7OFL.js → pi-BUADR5MJ.js} +143 -6
- package/dist/pi-BUADR5MJ.js.map +1 -0
- package/dist/{qwen-code-2XE2T6F4.js → qwen-code-TUJNHKNI.js} +9 -9
- package/dist/{roo-code-YJOIKCCS.js → roo-code-L5F7S6QH.js} +5 -5
- package/dist/runtime/index.d.ts +12 -1
- package/dist/runtime/index.js +12 -12
- package/dist/sdk/index.d.ts +3 -3
- package/dist/sdk/index.js +6 -6
- package/dist/sdk/test.d.ts +2 -2
- package/dist/sdk/test.js +10 -10
- package/dist/{serve-BU23QUSJ.js → serve-K62FW3V7.js} +24 -17
- package/dist/serve-K62FW3V7.js.map +1 -0
- package/dist/{status-N5LCQQ3R.js → status-E5MCFZM6.js} +11 -11
- package/dist/{statusline-442XOF7R.js → statusline-LIPF2KVP.js} +13 -13
- package/dist/{telemetry-V4YQL2NU.js → telemetry-4OC56NTM.js} +10 -10
- package/dist/{trae-QSV2JZFT.js → trae-Z7CQ2A2Q.js} +5 -5
- package/dist/{types-D6RWGXm1.d.ts → types-C4qMgbJn.d.ts} +10 -9
- package/dist/{uninstall-WGEKTCDZ.js → uninstall-2YYKN5DX.js} +18 -18
- package/dist/{upgrade-IH7CKPTO.js → upgrade-55AFPJEF.js} +18 -18
- package/dist/{usage-DI7XRCKM.js → usage-3PB3WZSL.js} +3 -3
- package/dist/{usage-event-2FCU55AN.js → usage-event-KD5FW6W4.js} +13 -13
- package/dist/{vscode-copilot-R23RTVST.js → vscode-copilot-LU5NC4ZS.js} +5 -5
- package/dist/{warp-B72XSQ5G.js → warp-4PPG5LOM.js} +5 -5
- package/dist/{windsurf-642VBMQ2.js → windsurf-3T3RVXKM.js} +5 -5
- package/dist/{zed-6UJS7JKB.js → zed-ZF2OQ75O.js} +123 -7
- package/dist/zed-ZF2OQ75O.js.map +1 -0
- package/package.json +1 -1
- package/dist/antigravity-cli-L3RZMF6V.js +0 -87
- package/dist/antigravity-cli-L3RZMF6V.js.map +0 -1
- package/dist/chunk-2HCJV6UO.js.map +0 -1
- package/dist/chunk-2L6LTQ6L.js.map +0 -1
- package/dist/chunk-MHDQWZ4A.js.map +0 -1
- package/dist/chunk-Q5LECKZL.js.map +0 -1
- package/dist/chunk-TO57WYBB.js.map +0 -1
- package/dist/chunk-TW4DVR4V.js.map +0 -1
- package/dist/jetbrains-copilot-DZ2ATXFN.js.map +0 -1
- package/dist/kiro-BUOQFASX.js.map +0 -1
- package/dist/openclaw-V73XHPXP.js +0 -17
- package/dist/pi-NMVL7OFL.js.map +0 -1
- package/dist/serve-BU23QUSJ.js.map +0 -1
- package/dist/zed-6UJS7JKB.js.map +0 -1
- /package/dist/{action-TCKBTTZX.js.map → action-L44DXFHT.js.map} +0 -0
- /package/dist/{amazon-q-CB4XFX7T.js.map → amazon-q-B52EY2SV.js.map} +0 -0
- /package/dist/{amp-6Q5OYHNW.js.map → amp-UXABVUKC.js.map} +0 -0
- /package/dist/{antigravity-WIK3XBN5.js.map → antigravity-RZHN53VB.js.map} +0 -0
- /package/dist/{chunk-D6ZJS4ND.js.map → chunk-4FWETID5.js.map} +0 -0
- /package/dist/{chunk-Q42SEI7W.js.map → chunk-4HVQ7IUM.js.map} +0 -0
- /package/dist/{chunk-IU42THN7.js.map → chunk-4NSU3KWX.js.map} +0 -0
- /package/dist/{chunk-7CZKXXBD.js.map → chunk-56R2ER7K.js.map} +0 -0
- /package/dist/{chunk-HKM3HUOK.js.map → chunk-7HUUINPB.js.map} +0 -0
- /package/dist/{chunk-TZ5KGCE2.js.map → chunk-AY3RGRTT.js.map} +0 -0
- /package/dist/{chunk-7ITLLYWB.js.map → chunk-G4CEELKO.js.map} +0 -0
- /package/dist/{chunk-24K6JOKV.js.map → chunk-LAIITCMW.js.map} +0 -0
- /package/dist/{chunk-OEQJGBBW.js.map → chunk-LF76VPGQ.js.map} +0 -0
- /package/dist/{chunk-7QRUZAUG.js.map → chunk-LN76OGNR.js.map} +0 -0
- /package/dist/{chunk-DI6OWKH2.js.map → chunk-NBUEL74R.js.map} +0 -0
- /package/dist/{chunk-IRUYJD23.js.map → chunk-NLE2J5P4.js.map} +0 -0
- /package/dist/{chunk-5LAFKXFM.js.map → chunk-NWLRJNXM.js.map} +0 -0
- /package/dist/{chunk-ECSRTK4M.js.map → chunk-QARPXSIV.js.map} +0 -0
- /package/dist/{chunk-AXAHW2KU.js.map → chunk-QKLJU4JX.js.map} +0 -0
- /package/dist/{chunk-MDZG5QHB.js.map → chunk-R6LML2YS.js.map} +0 -0
- /package/dist/{chunk-FUXUEXDP.js.map → chunk-UBB7T54N.js.map} +0 -0
- /package/dist/{chunk-NUGMVVV2.js.map → chunk-VVFDU4IX.js.map} +0 -0
- /package/dist/{chunk-ALVXORZM.js.map → chunk-YYNXIUR2.js.map} +0 -0
- /package/dist/{claude-code-HFBAAVWS.js.map → claude-code-WS4NAGZT.js.map} +0 -0
- /package/dist/{cline-26W4FEZ6.js.map → cline-NNMVCECA.js.map} +0 -0
- /package/dist/{codebuff-J5KEEBIL.js.map → codebuff-RJIDSEU3.js.map} +0 -0
- /package/dist/{codex-JKQ6TLRI.js.map → codex-ZZ434GYR.js.map} +0 -0
- /package/dist/{continue-KQSJUSWX.js.map → continue-MNM7YVJY.js.map} +0 -0
- /package/dist/{copilot-cli-YBNKLYUB.js.map → copilot-cli-SMTX5F65.js.map} +0 -0
- /package/dist/{crush-JTWTZIPB.js.map → crush-NYDBHIJE.js.map} +0 -0
- /package/dist/{cursor-2NIZSDZ4.js.map → cursor-AOELDNZU.js.map} +0 -0
- /package/dist/{detect-CWEIQCRC.js.map → detect-3S46RUMK.js.map} +0 -0
- /package/dist/{doctor-AC437ZAW.js.map → doctor-3CUBPQKU.js.map} +0 -0
- /package/dist/{droid-HF2AIFB2.js.map → droid-PTCH2K7Y.js.map} +0 -0
- /package/dist/{gemini-cli-2EOK26S2.js.map → gemini-cli-QGLN2UMS.js.map} +0 -0
- /package/dist/{goose-55JOTXS5.js.map → goose-DQ6GSZ5O.js.map} +0 -0
- /package/dist/{hermes-QVZOZU4B.js.map → hermes-E47IG63A.js.map} +0 -0
- /package/dist/{hook-VYD3OCLM.js.map → hook-P6EKDINW.js.map} +0 -0
- /package/dist/{install-S6BYIJ62.js.map → install-7DMK53SB.js.map} +0 -0
- /package/dist/{kilo-GJNSBWVV.js.map → kilo-OU2ZLZKB.js.map} +0 -0
- /package/dist/{kilo-cli-2CCB3DBI.js.map → kilo-cli-NMWGYF4F.js.map} +0 -0
- /package/dist/{kimi-YRPCSB6N.js.map → kimi-Z7L2LEEI.js.map} +0 -0
- /package/dist/{leaderboard-SUSUDKHR.js.map → leaderboard-LF5SP6X2.js.map} +0 -0
- /package/dist/{mimo-code-V4FP5PUJ.js.map → mimo-code-G2CBZ4M6.js.map} +0 -0
- /package/dist/{mux-CMJSM42O.js.map → mux-JNM3F2NW.js.map} +0 -0
- /package/dist/{nemoclaw-VP56PGKC.js.map → nemoclaw-SHA4IUML.js.map} +0 -0
- /package/dist/{omp-OOFGD3GG.js.map → omp-OOVUNXME.js.map} +0 -0
- /package/dist/{openclaw-V73XHPXP.js.map → openclaw-BD56E5MV.js.map} +0 -0
- /package/dist/{opencode-MKLHSQRD.js.map → opencode-W2RK4M7G.js.map} +0 -0
- /package/dist/{package-KOAAVKHH.js.map → package-2EAIYSJ4.js.map} +0 -0
- /package/dist/{qwen-code-2XE2T6F4.js.map → qwen-code-TUJNHKNI.js.map} +0 -0
- /package/dist/{roo-code-YJOIKCCS.js.map → roo-code-L5F7S6QH.js.map} +0 -0
- /package/dist/{status-N5LCQQ3R.js.map → status-E5MCFZM6.js.map} +0 -0
- /package/dist/{statusline-442XOF7R.js.map → statusline-LIPF2KVP.js.map} +0 -0
- /package/dist/{telemetry-V4YQL2NU.js.map → telemetry-4OC56NTM.js.map} +0 -0
- /package/dist/{trae-QSV2JZFT.js.map → trae-Z7CQ2A2Q.js.map} +0 -0
- /package/dist/{uninstall-WGEKTCDZ.js.map → uninstall-2YYKN5DX.js.map} +0 -0
- /package/dist/{upgrade-IH7CKPTO.js.map → upgrade-55AFPJEF.js.map} +0 -0
- /package/dist/{usage-DI7XRCKM.js.map → usage-3PB3WZSL.js.map} +0 -0
- /package/dist/{usage-event-2FCU55AN.js.map → usage-event-KD5FW6W4.js.map} +0 -0
- /package/dist/{vscode-copilot-R23RTVST.js.map → vscode-copilot-LU5NC4ZS.js.map} +0 -0
- /package/dist/{warp-B72XSQ5G.js.map → warp-4PPG5LOM.js.map} +0 -0
- /package/dist/{windsurf-642VBMQ2.js.map → windsurf-3T3RVXKM.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 * Framework data-root from `--data-dir <path>` (baked into the wrapper at\n * install time, only for a NON-DEFAULT root). OPTIONAL: when present, it pins\n * the data-root the WHOLE child resolves — connector record lookup AND the\n * telemetry store — by populating AGENT_CONNECTOR_DATA_DIR before anything\n * reads it. This is the env-independent path for hosts (codex) that strip the\n * MCP child's environment and would otherwise drop the override, leaving the\n * child to resolve the default `~/.agent-connector` and fail \"not registered\".\n * Absent → resolve the data-root the usual way (env or default).\n */\n dataDir?: string;\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 {\n connectorId,\n serverCommand,\n serverArgs,\n installScope,\n hostPlatformOverride,\n dataDir,\n } = opts;\n\n // Pin the data-root BEFORE anything resolves it (the connector record lookup\n // below and openStore later both read dataRoot()). The wrapper passes\n // --data-dir only for a non-default root on a host that may strip the child\n // env (codex) — populating AGENT_CONNECTOR_DATA_DIR here makes the whole child\n // resolve that root regardless of whether the host propagated the env var.\n if (dataDir !== undefined && dataDir.trim() !== \"\") {\n process.env.AGENT_CONNECTOR_DATA_DIR = dataDir;\n }\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 {\n attachLazyTelemetryUsage,\n buildTelemetryAccessor,\n} 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 // Keep `ctx.usage` synchronous for render functions, but compute it only if\n // the render actually reads the property. Status lines refresh frequently,\n // and the NDJSON backend has to scan the store for an all-time summary.\n attachLazyTelemetryUsage(ctx, 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}`,\n };\n }\n}\n\nexport default runAction;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,SAAS,kBAAkB;;;ACQ3B,SAAS,YAAY,cAAc,qBAAqB;AACxD,SAAS,YAAY;AAkBd,SAAS,uBAAgC;A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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"]}
|
|
@@ -1,22 +1,22 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
3
|
REGISTERED_PLATFORM_IDS
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-25CPWJA7.js";
|
|
5
5
|
import {
|
|
6
6
|
CONFIG_PATCH_SEGMENT_RE,
|
|
7
7
|
configPatchNamespaceViolation,
|
|
8
8
|
isJsonValue,
|
|
9
9
|
isValidConfigPatchKey
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-56R2ER7K.js";
|
|
11
11
|
import {
|
|
12
12
|
MANAGED_BLOCK_BEGIN_TOKEN,
|
|
13
13
|
MANAGED_BLOCK_END_TOKEN,
|
|
14
14
|
MEMORY_CONTENT_HARD_CAP_BYTES
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-YYNXIUR2.js";
|
|
16
16
|
import {
|
|
17
17
|
CONNECTOR_ID_RE,
|
|
18
18
|
isValidConnectorId
|
|
19
|
-
} from "./chunk-
|
|
19
|
+
} from "./chunk-IXOQDZWC.js";
|
|
20
20
|
|
|
21
21
|
// src/core/define-connector.ts
|
|
22
22
|
import { isAbsolute, normalize } from "path";
|
|
@@ -498,4 +498,4 @@ export {
|
|
|
498
498
|
defineConfigPatch,
|
|
499
499
|
defineNativeHook
|
|
500
500
|
};
|
|
501
|
-
//# sourceMappingURL=chunk-
|
|
501
|
+
//# sourceMappingURL=chunk-G4CEELKO.js.map
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
isNonDefaultDataRoot
|
|
4
|
+
} from "./chunk-IXOQDZWC.js";
|
|
2
5
|
|
|
3
6
|
// src/core/spawn.ts
|
|
4
7
|
import { existsSync } from "fs";
|
|
@@ -70,10 +73,11 @@ function isHostNativeUsageEnabled(telemetry, env = process.env) {
|
|
|
70
73
|
function shouldWrapForTelemetry(server, telemetry) {
|
|
71
74
|
return server.wrapForTelemetry !== false && telemetry.enabled === true && server.transport === "stdio" && typeof server.command === "string" && server.command !== "";
|
|
72
75
|
}
|
|
73
|
-
function buildServeWrapperCommand(homeBinPath, connectorId, realCommand, realArgs, scope, platformId) {
|
|
76
|
+
function buildServeWrapperCommand(homeBinPath, connectorId, realCommand, realArgs, scope, platformId, dataDir) {
|
|
74
77
|
const flags = ["serve", "--connector", connectorId];
|
|
75
78
|
if (scope !== void 0) flags.push("--scope", narrowInstallScope(scope));
|
|
76
79
|
if (platformId !== void 0) flags.push("--host", platformId);
|
|
80
|
+
if (dataDir !== void 0 && dataDir !== "") flags.push("--data-dir", dataDir);
|
|
77
81
|
return {
|
|
78
82
|
command: homeBinPath,
|
|
79
83
|
args: [...flags, "--", realCommand, ...realArgs]
|
|
@@ -83,13 +87,15 @@ function buildWrappedStdio(ctx, server, platformId, command, args) {
|
|
|
83
87
|
if (!shouldWrapForTelemetry(server, ctx.connector.telemetry)) {
|
|
84
88
|
return { command, args };
|
|
85
89
|
}
|
|
90
|
+
const dataDir = isNonDefaultDataRoot(ctx.dataRoot) ? ctx.dataRoot : void 0;
|
|
86
91
|
return buildServeWrapperCommand(
|
|
87
92
|
ctx.homeBinPath,
|
|
88
93
|
ctx.connector.id,
|
|
89
94
|
command,
|
|
90
95
|
args,
|
|
91
96
|
ctx.scope,
|
|
92
|
-
platformId
|
|
97
|
+
platformId,
|
|
98
|
+
dataDir
|
|
93
99
|
);
|
|
94
100
|
}
|
|
95
101
|
function resolveSpawnCommand(command, deps = {}) {
|
|
@@ -152,4 +158,4 @@ export {
|
|
|
152
158
|
resolveSpawnCommand,
|
|
153
159
|
detectLaunchMethod
|
|
154
160
|
};
|
|
155
|
-
//# sourceMappingURL=chunk-
|
|
161
|
+
//# sourceMappingURL=chunk-HORHRHNG.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 { isNonDefaultDataRoot } from \"./paths.js\";\nimport type { InstallScope, PlatformId, ServerDef } from \"./types.js\";\nimport type { InstallContext } from \"../adapters/spi.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 *\n * `dataDir` pins the framework data-root the spawned `serve` child must use to\n * resolve the connector record (and write telemetry). Emitted as `--data-dir\n * <path>` in the FLAG section. It exists because some hosts (codex strips the\n * MCP child's environment) do NOT propagate `AGENT_CONNECTOR_DATA_DIR` to the\n * spawned server — so a child that relied on inheriting it would resolve the\n * DEFAULT `~/.agent-connector` and die with \"Connector not registered\" when the\n * install wrote the record under an OVERRIDDEN root. Passing it explicitly makes\n * the wrap env-independent for any env-stripping host. OPTIONAL + backward-\n * compatible: callers pass it only for a non-default root (a default-root install\n * stays flag-free and relies on the correct fallback), and when omitted the\n * `--data-dir` flag is not emitted and the runtime resolves the data-root the\n * usual way.\n */\nexport function buildServeWrapperCommand(\n homeBinPath: string,\n connectorId: string,\n realCommand: string,\n realArgs: string[],\n scope?: InstallScope,\n platformId?: PlatformId,\n dataDir?: string,\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 if (dataDir !== undefined && dataDir !== \"\") flags.push(\"--data-dir\", dataDir);\n return {\n command: homeBinPath,\n args: [...flags, \"--\", realCommand, ...realArgs],\n };\n}\n\n/**\n * Telemetry serve-wrap for a stdio command: when the connector opts in, route\n * `command`/`args` through `<homeBin> serve --connector <id> -- …`; otherwise\n * return them unchanged. Consolidates the per-host wrap snippet — the caller\n * keeps its own command/args seeding + downstream env-resolution + entry shaping.\n *\n * When the install's framework data-root is NON-DEFAULT (overridden via\n * AGENT_CONNECTOR_DATA_DIR), the wrap also carries an explicit `--data-dir\n * <root>` so the spawned `serve` child resolves the connector record from that\n * root even on hosts that strip the child's environment (codex). A default-root\n * install emits no flag and relies on the correct runtime fallback.\n */\nexport function buildWrappedStdio(\n ctx: Pick<InstallContext, \"homeBinPath\" | \"connector\" | \"scope\" | \"dataRoot\">,\n server: ServerDef,\n platformId: PlatformId,\n command: string,\n args: string[],\n): { command: string; args: string[] } {\n if (!shouldWrapForTelemetry(server, ctx.connector.telemetry)) {\n return { command, args };\n }\n const dataDir = isNonDefaultDataRoot(ctx.dataRoot) ? ctx.dataRoot : undefined;\n return buildServeWrapperCommand(\n ctx.homeBinPath,\n ctx.connector.id,\n command,\n args,\n ctx.scope,\n platformId,\n dataDir,\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;AAed,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,YAAY,QAAQ,OAAO,GAAG,CAAC,EAAG,QAAO;AAC3D,QAAM,QAAQ,eAAe,WAAW;AACxC,MAAI,OAAO;AACX,aAAS;AACP,UAAM,MAAM,IAAI,QAAQ,OAAO,IAAI;AACnC,QAAI,MAAM,EAAG,QAAO;AACpB,UAAM,QAAQ,IAAI,OAAO,MAAM,MAAM,MAAM;AAC3C,QAAI,UAAU,MAAM,UAAU,OAAO,KAAK,KAAK,KAAK,EAAG,QAAO;AAC9D,WAAO,MAAM,MAAM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AAI,aAAa,IAAI,IAAI,EAAG,QAAO;AACnC,SAAO;AACT;","names":[]}
|
|
@@ -24,10 +24,16 @@ import {
|
|
|
24
24
|
} from "fs";
|
|
25
25
|
import { homedir } from "os";
|
|
26
26
|
import { basename, isAbsolute, join, parse, relative, resolve, sep } from "path";
|
|
27
|
+
function defaultDataRoot() {
|
|
28
|
+
return join(homedir(), ".agent-connector");
|
|
29
|
+
}
|
|
27
30
|
function dataRoot() {
|
|
28
31
|
const override = process.env.AGENT_CONNECTOR_DATA_DIR;
|
|
29
32
|
if (override && override.trim() !== "") return resolve(override);
|
|
30
|
-
return
|
|
33
|
+
return defaultDataRoot();
|
|
34
|
+
}
|
|
35
|
+
function isNonDefaultDataRoot(root) {
|
|
36
|
+
return resolve(root) !== resolve(defaultDataRoot());
|
|
31
37
|
}
|
|
32
38
|
function connectorsDir() {
|
|
33
39
|
return join(dataRoot(), "connectors");
|
|
@@ -130,6 +136,7 @@ export {
|
|
|
130
136
|
isValidConnectorId,
|
|
131
137
|
assertConnectorId,
|
|
132
138
|
dataRoot,
|
|
139
|
+
isNonDefaultDataRoot,
|
|
133
140
|
connectorsDir,
|
|
134
141
|
connectorDir,
|
|
135
142
|
backupsDir,
|
|
@@ -141,4 +148,4 @@ export {
|
|
|
141
148
|
ensureHomeBin,
|
|
142
149
|
projectIdentity
|
|
143
150
|
};
|
|
144
|
-
//# sourceMappingURL=chunk-
|
|
151
|
+
//# sourceMappingURL=chunk-IXOQDZWC.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/ids.ts","../src/core/paths.ts"],"sourcesContent":["/** Shared connector-id grammar for author-time configs and runtime ids. */\nexport const CONNECTOR_ID_RE = /^[a-z0-9][a-z0-9-]*$/;\n\nexport function isValidConnectorId(id: unknown): id is string {\n return typeof id === \"string\" && CONNECTOR_ID_RE.test(id);\n}\n\nexport function assertConnectorId(id: unknown, label = \"connector id\"): string {\n if (isValidConnectorId(id)) return id;\n throw new Error(\n `${label} must be kebab-case matching ${CONNECTOR_ID_RE} (got ${JSON.stringify(id)})`,\n );\n}\n","/**\n * core/paths — home data-root, stable home binary, and project identity.\n *\n * Operating model (docs/ARCHITECTURE.md §3):\n * • One home data-root holds the single binary + shared telemetry + state.\n * Override with AGENT_CONNECTOR_DATA_DIR (the cross-agent shared-DB key).\n * This relocates FRAMEWORK state only — never platform-native config files.\n * • The home binary lives at a STABLE path so every host's pointer config\n * keeps working across updates (no versioned cache dir → no cache-heal bug).\n * • Per-project data is keyed by a stable project identity (git remote ||\n * normalized absolute path), hashed — not by code location.\n */\n\nimport { createHash } from \"node:crypto\";\nimport {\n chmodSync,\n existsSync,\n lstatSync,\n mkdirSync,\n readFileSync,\n writeFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { basename, isAbsolute, join, parse, relative, resolve, sep } from \"node:path\";\n\nimport { assertConnectorId } from \"./ids.js\";\n\n/** The built-in default framework data-root (`~/.agent-connector`), ignoring\n * any AGENT_CONNECTOR_DATA_DIR override. */\nexport function defaultDataRoot(): string {\n return join(homedir(), \".agent-connector\");\n}\n\n/** Framework data-root: AGENT_CONNECTOR_DATA_DIR || ~/.agent-connector. */\nexport function dataRoot(): string {\n const override = process.env.AGENT_CONNECTOR_DATA_DIR;\n if (override && override.trim() !== \"\") return resolve(override);\n return defaultDataRoot();\n}\n\n/**\n * True when `root` is a NON-DEFAULT data root — i.e. it differs from the\n * built-in `~/.agent-connector`. Compared after `resolve()` so two spellings of\n * the same dir read as equal. Used at install time to decide whether the\n * telemetry serve-wrap must carry an explicit `--data-dir` flag: a default-root\n * install relies on the (correct) fallback and stays flag-free, but an overridden\n * root must be passed explicitly because some hosts (codex) strip the child env,\n * so the spawned `serve` would otherwise resolve the default root and fail to\n * find the connector record written under the overridden one.\n */\nexport function isNonDefaultDataRoot(root: string): boolean {\n return resolve(root) !== resolve(defaultDataRoot());\n}\n\nexport function connectorsDir(): string {\n return join(dataRoot(), \"connectors\");\n}\nexport function connectorDir(id: string): string {\n const root = resolve(connectorsDir());\n const safeId = assertConnectorId(id);\n const dir = resolve(root, safeId);\n const rel = relative(root, dir);\n if (rel === \"\" || rel.startsWith(\"..\") || isAbsolute(rel)) {\n throw new Error(`connector record path escapes ${root}: ${id}`);\n }\n return dir;\n}\nexport function backupsDir(): string {\n return join(dataRoot(), \"backups\");\n}\nexport function logsDir(): string {\n return join(dataRoot(), \"logs\");\n}\n\n/** Telemetry store path for the selected backend. */\nexport function telemetryPath(store: \"ndjson\" | \"sqlite\" = \"ndjson\"): string {\n return join(dataRoot(), store === \"sqlite\" ? \"telemetry.db\" : \"telemetry.ndjson\");\n}\n\n/** Stable, OS-correct path to the single home binary pointer. */\nexport function homeBinPath(): string {\n const name = process.platform === \"win32\" ? \"agent-connector.cmd\" : \"agent-connector\";\n return join(dataRoot(), \"bin\", name);\n}\n\nexport function ensureDir(dir: string): void {\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n}\n\n/**\n * Return the first existing symbolic-link component in `path`, or null when the\n * existing prefix is symlink-free. Stops at the first missing component so new\n * directories/files can still be created normally.\n */\nexport function firstSymlinkInPath(path: string): string | null {\n const abs = resolve(path);\n const root = parse(abs).root;\n const rest = relative(root, abs);\n if (rest === \"\") return null;\n\n let cur = root;\n for (const part of rest.split(sep)) {\n if (part === \"\") continue;\n cur = join(cur, part);\n try {\n if (lstatSync(cur).isSymbolicLink()) return cur;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") return null;\n throw err;\n }\n }\n return null;\n}\n\nexport function assertNoSymlinkInPath(path: string): void {\n const symlink = firstSymlinkInPath(path);\n if (symlink !== null) {\n throw new Error(`${basename(path)} skipped: symbolic link in path (${symlink})`);\n }\n}\n\n/**\n * Write a stable launcher at homeBinPath() that execs the real CLI entry.\n * Avoids symlinks (Windows constraint) and versioned paths. Idempotent.\n *\n * @param cliEntry absolute path to the installed cli.js\n * @param nodePath node runtime to exec with (defaults to current process.execPath)\n * @returns the stable launcher path\n */\nexport function ensureHomeBin(cliEntry: string, nodePath: string = process.execPath): string {\n const binPath = homeBinPath();\n assertNoSymlinkInPath(binPath);\n ensureDir(join(dataRoot(), \"bin\"));\n const node = nodePath.replace(/\\\\/g, \"/\");\n const cli = cliEntry.replace(/\\\\/g, \"/\");\n if (process.platform === \"win32\") {\n writeFileSync(binPath, `@echo off\\r\\n\"${node}\" \"${cli}\" %*\\r\\n`, \"utf8\");\n } else {\n writeFileSync(binPath, `#!/bin/sh\\nexec \"${node}\" \"${cli}\" \"$@\"\\n`, \"utf8\");\n chmodSync(binPath, 0o755);\n }\n return binPath;\n}\n\n/** Read remote.origin.url from a project's .git/config without spawning git. */\nfunction gitRemoteUrl(projectDir: string): string | null {\n const cfg = join(projectDir, \".git\", \"config\");\n if (!existsSync(cfg)) return null;\n try {\n const text = readFileSync(cfg, \"utf8\");\n // Find [remote \"origin\"] ... url = X\n const lines = text.split(/\\r?\\n/);\n let inOrigin = false;\n for (const line of lines) {\n const s = line.trim();\n if (s.startsWith(\"[\")) inOrigin = /^\\[remote\\s+\"origin\"\\]$/.test(s);\n else if (inOrigin) {\n const m = s.match(/^url\\s*=\\s*(.+)$/);\n if (m && m[1]) return m[1].trim();\n }\n }\n } catch {\n /* ignore */\n }\n return null;\n}\n\nexport interface ProjectIdentity {\n /** Hashed stable key used to partition telemetry/state. */\n key: string;\n /** Human-readable label (git remote or directory name). */\n label: string;\n /** Absolute project directory. */\n dir: string;\n}\n\n/**\n * Derive a stable project identity. Prefers the git origin URL (stable across\n * clones/locations); falls back to the normalized absolute path.\n */\nexport function projectIdentity(projectDir: string): ProjectIdentity {\n const dir = resolve(projectDir);\n const remote = gitRemoteUrl(dir);\n const basis = remote ?? dir;\n const key = createHash(\"sha256\").update(basis).digest(\"hex\").slice(0, 16);\n return { key, label: remote ?? basename(dir), dir };\n}\n"],"mappings":";;;AACO,IAAM,kBAAkB;AAExB,SAAS,mBAAmB,IAA2B;AAC5D,SAAO,OAAO,O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,QAAoB,IAAI,MAAM,GAAG;AAAA,GAAY,MAAM;AAC1E,cAAU,SAAS,GAAK;AAAA,EAC1B;AACA,SAAO;AACT;AAGA,SAAS,aAAa,YAAmC;AACvD,QAAM,MAAM,KAAK,YAAY,QAAQ,QAAQ;AAC7C,MAAI,CAAC,WAAW,GAAG,EAAG,QAAO;AAC7B,MAAI;AACF,UAAM,OAAO,aAAa,KAAK,MAAM;AAErC,UAAM,QAAQ,KAAK,MAAM,OAAO;AAChC,QAAI,WAAW;AACf,eAAW,QAAQ,OAAO;AACxB,YAAM,IAAI,KAAK,KAAK;AACpB,UAAI,EAAE,WAAW,GAAG,EAAG,YAAW,0BAA0B,KAAK,CAAC;AAAA,eACzD,UAAU;AACjB,cAAM,IAAI,EAAE,MAAM,kBAAkB;AACpC,YAAI,KAAK,EAAE,CAAC,EAAG,QAAO,EAAE,CAAC,EAAE,KAAK;AAAA,MAClC;AAAA,IACF;AAAA,EACF,QAAQ;AAAA,EAER;AACA,SAAO;AACT;AAeO,SAAS,gBAAgB,YAAqC;AACnE,QAAM,MAAM,QAAQ,UAAU;AAC9B,QAAM,SAAS,aAAa,GAAG;AAC/B,QAAM,QAAQ,UAAU;AACxB,QAAM,MAAM,WAAW,QAAQ,EAAE,OAAO,KAAK,EAAE,OAAO,KAAK,EAAE,MAAM,GAAG,EAAE;AACxE,SAAO,EAAE,KAAK,OAAO,UAAU,SAAS,GAAG,GAAG,IAAI;AACpD;","names":[]}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import {
|
|
3
3
|
installInstructions,
|
|
4
4
|
packageConnector
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-LF76VPGQ.js";
|
|
6
6
|
import {
|
|
7
7
|
MARKETPLACE_NAME,
|
|
8
8
|
agyPluginInstalled,
|
|
@@ -38,13 +38,13 @@ import {
|
|
|
38
38
|
readMarketplaceInstalls,
|
|
39
39
|
readNpmConfig,
|
|
40
40
|
writeMarketplaceInstalls
|
|
41
|
-
} from "./chunk-
|
|
41
|
+
} from "./chunk-QKLJU4JX.js";
|
|
42
42
|
import {
|
|
43
43
|
spawnChild
|
|
44
|
-
} from "./chunk-
|
|
44
|
+
} from "./chunk-LN76OGNR.js";
|
|
45
45
|
import {
|
|
46
46
|
detectInstalledPlatforms
|
|
47
|
-
} from "./chunk-
|
|
47
|
+
} from "./chunk-ZMLVR4J7.js";
|
|
48
48
|
import {
|
|
49
49
|
log
|
|
50
50
|
} from "./chunk-KHO5WNTP.js";
|
|
@@ -52,20 +52,20 @@ import {
|
|
|
52
52
|
deregisterConnector,
|
|
53
53
|
loadRegisteredConnector,
|
|
54
54
|
registerConnector
|
|
55
|
-
} from "./chunk-
|
|
55
|
+
} from "./chunk-NWLRJNXM.js";
|
|
56
56
|
import {
|
|
57
57
|
REGISTERED_PLATFORM_IDS,
|
|
58
58
|
loadAdapter
|
|
59
|
-
} from "./chunk-
|
|
59
|
+
} from "./chunk-25CPWJA7.js";
|
|
60
60
|
import {
|
|
61
61
|
configPatchManualEdit
|
|
62
|
-
} from "./chunk-
|
|
62
|
+
} from "./chunk-56R2ER7K.js";
|
|
63
63
|
import {
|
|
64
64
|
findUnsetEnvRefs
|
|
65
65
|
} from "./chunk-BEFVJ2OE.js";
|
|
66
66
|
import {
|
|
67
67
|
hasMemoryLedger
|
|
68
|
-
} from "./chunk-
|
|
68
|
+
} from "./chunk-YYNXIUR2.js";
|
|
69
69
|
import {
|
|
70
70
|
connectorDir,
|
|
71
71
|
connectorsDir,
|
|
@@ -74,7 +74,7 @@ import {
|
|
|
74
74
|
ensureHomeBin,
|
|
75
75
|
firstSymlinkInPath,
|
|
76
76
|
homeBinPath
|
|
77
|
-
} from "./chunk-
|
|
77
|
+
} from "./chunk-IXOQDZWC.js";
|
|
78
78
|
|
|
79
79
|
// src/core/installer.ts
|
|
80
80
|
import { existsSync, readdirSync, rmSync } from "fs";
|
|
@@ -144,6 +144,17 @@ async function installConnector(opts) {
|
|
|
144
144
|
}
|
|
145
145
|
}
|
|
146
146
|
}
|
|
147
|
+
{
|
|
148
|
+
const wroteEntry = serverChanges.some(
|
|
149
|
+
(c) => c.action === "create" || c.action === "update"
|
|
150
|
+
);
|
|
151
|
+
const server = effectiveServerFor(connector, id);
|
|
152
|
+
if (wroteEntry && server && server.transport !== "stdio" && connector.telemetry.enabled === true) {
|
|
153
|
+
const detail = `telemetry not captured for ${connector.id} on ${id} \u2014 remote (${server.transport}) transport; per-tool telemetry is stdio-only`;
|
|
154
|
+
result.changes.push({ platform: id, action: "warn", detail });
|
|
155
|
+
result.warnings.push(detail);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
147
158
|
});
|
|
148
159
|
runStep(id, "installHooks", result, () => {
|
|
149
160
|
pushAll(result.changes, adapter.installHooks(ctx));
|
|
@@ -3073,4 +3084,4 @@ export {
|
|
|
3073
3084
|
upgradeViaMarketplace,
|
|
3074
3085
|
marketplaceDoctorChecks
|
|
3075
3086
|
};
|
|
3076
|
-
//# sourceMappingURL=chunk-
|
|
3087
|
+
//# sourceMappingURL=chunk-KIRCPLM4.js.map
|