github-router 0.3.369 → 0.3.371

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/dist/ado-tools-512UGB6R.js +1 -0
  2. package/dist/{aic-ledger-_mvGW2Ev.js → aic-ledger-Cp7Yk9-Q.js} +2 -2
  3. package/dist/{aic-ledger-_mvGW2Ev.js.map → aic-ledger-Cp7Yk9-Q.js.map} +1 -1
  4. package/dist/{attribution-settings-zoBxw08y.js → attribution-settings-Beer9wsJ.js} +6 -6
  5. package/dist/{attribution-settings-zoBxw08y.js.map → attribution-settings-Beer9wsJ.js.map} +1 -1
  6. package/dist/{auth-B3UvYB2r.js → auth-B1egtvt4.js} +3 -3
  7. package/dist/{auth-B3UvYB2r.js.map → auth-B1egtvt4.js.map} +1 -1
  8. package/dist/{bluebird-client-C29-JOkG.js → bluebird-client-ByCRusGQ.js} +3 -3
  9. package/dist/bluebird-client-ByCRusGQ.js.map +1 -0
  10. package/dist/bluebird-client-CY6NBHQu.js +1 -0
  11. package/dist/browser-ext/manifest.json +1 -1
  12. package/dist/{check-usage-45vyaLfl.js → check-usage-T_z84Pgc.js} +3 -3
  13. package/dist/{check-usage-45vyaLfl.js.map → check-usage-T_z84Pgc.js.map} +1 -1
  14. package/dist/{claude-BbIfnWbm.js → claude-CAYTTiyt.js} +18 -15
  15. package/dist/claude-CAYTTiyt.js.map +1 -0
  16. package/dist/{claude-md-injection-BtBG1RBZ.js → claude-md-injection-D1aMjvb_.js} +3 -3
  17. package/dist/{claude-md-injection-BtBG1RBZ.js.map → claude-md-injection-D1aMjvb_.js.map} +1 -1
  18. package/dist/{codex-CZVlP2tB.js → codex-CALX-qG4.js} +8 -8
  19. package/dist/{codex-CZVlP2tB.js.map → codex-CALX-qG4.js.map} +1 -1
  20. package/dist/{copilot-discount-BuDbQOHq.js → copilot-discount-T-cfWmc4.js} +2 -2
  21. package/dist/{copilot-discount-BuDbQOHq.js.map → copilot-discount-T-cfWmc4.js.map} +1 -1
  22. package/dist/engine-CSAEqj2p.js +1 -0
  23. package/dist/{gate-discovery-BYyYeUnn.js → gate-discovery-CITKjhsD.js} +2 -2
  24. package/dist/{gate-discovery-BYyYeUnn.js.map → gate-discovery-CITKjhsD.js.map} +1 -1
  25. package/dist/{get-copilot-usage-BbGmK03C.js → get-copilot-usage-BSXeQEx8.js} +3 -3
  26. package/dist/{get-copilot-usage-BbGmK03C.js.map → get-copilot-usage-BSXeQEx8.js.map} +1 -1
  27. package/dist/hooks.mjs +2 -0
  28. package/dist/hooks.sha256 +1 -1
  29. package/dist/{internal-aic-status-BAVomi5A.js → internal-aic-status-CY0QxSa7.js} +3 -3
  30. package/dist/{internal-aic-status-BAVomi5A.js.map → internal-aic-status-CY0QxSa7.js.map} +1 -1
  31. package/dist/{internal-max-dispatch-guard-BodVFHRC.js → internal-max-dispatch-guard-4rh6KSd8.js} +2 -2
  32. package/dist/{internal-max-dispatch-guard-BodVFHRC.js.map → internal-max-dispatch-guard-4rh6KSd8.js.map} +1 -1
  33. package/dist/{internal-max-dispatch-guard-BB0vwiPx.js → internal-max-dispatch-guard-CKnzgJje.js} +1 -1
  34. package/dist/{internal-stop-hook-BbyobGUU.js → internal-stop-hook-DT27bzH7.js} +2 -2
  35. package/dist/{internal-stop-hook-BbyobGUU.js.map → internal-stop-hook-DT27bzH7.js.map} +1 -1
  36. package/dist/main.js +12 -11
  37. package/dist/main.js.map +1 -1
  38. package/dist/{max-profile-contract-Cx5_Z1Y7.js → max-profile-contract-CRj7N211.js} +2 -2
  39. package/dist/{max-profile-contract-Cx5_Z1Y7.js.map → max-profile-contract-CRj7N211.js.map} +1 -1
  40. package/dist/{models-BR6i348u.js → models-Ca-HQTYi.js} +2 -2
  41. package/dist/{models-BR6i348u.js.map → models-Ca-HQTYi.js.map} +1 -1
  42. package/dist/{peer-mcp-personas-DNtWI2C1.js → peer-mcp-personas-D7vaM-V5.js} +813 -59
  43. package/dist/peer-mcp-personas-D7vaM-V5.js.map +1 -0
  44. package/dist/{pi-Bc-MVgAo.js → pi-D4LrdubN.js} +16 -13
  45. package/dist/{pi-Bc-MVgAo.js.map → pi-D4LrdubN.js.map} +1 -1
  46. package/dist/{provision-DUWdcY_a.js → provision-DonGTIfK.js} +3 -2
  47. package/dist/provision-DonGTIfK.js.map +1 -0
  48. package/dist/{serve-CmWOTR7m.js → serve-jzmQ8KEE.js} +18 -10
  49. package/dist/serve-jzmQ8KEE.js.map +1 -0
  50. package/dist/{server-setup-CIzmDJzT.js → server-setup-wWidNq5m.js} +73 -28
  51. package/dist/server-setup-wWidNq5m.js.map +1 -0
  52. package/dist/{start-rlpaeAtx.js → start-CTluQxu5.js} +3 -3
  53. package/dist/{start-rlpaeAtx.js.map → start-CTluQxu5.js.map} +1 -1
  54. package/dist/{state-CiwCLVDZ.js → state-DzsaGHr9.js} +3 -1
  55. package/dist/{state-CiwCLVDZ.js.map → state-DzsaGHr9.js.map} +1 -1
  56. package/dist/token-CVG0yI_j.js +480 -0
  57. package/dist/token-CVG0yI_j.js.map +1 -0
  58. package/dist/{token-OTb61rOC.js → token-Dqjs5ixP.js} +3 -3
  59. package/dist/{token-OTb61rOC.js.map → token-Dqjs5ixP.js.map} +1 -1
  60. package/dist/workiq-qnJR5_n2.js +144 -0
  61. package/dist/workiq-qnJR5_n2.js.map +1 -0
  62. package/dist/workiq-tools-CDLIrILp.js +1 -0
  63. package/package.json +1 -1
  64. package/dist/ado-tools-C0sY_rX1.js +0 -1
  65. package/dist/bluebird-client-C29-JOkG.js.map +0 -1
  66. package/dist/bluebird-client-DGE3WZqh.js +0 -1
  67. package/dist/claude-BbIfnWbm.js.map +0 -1
  68. package/dist/engine-DeIo-VIR.js +0 -1
  69. package/dist/peer-mcp-personas-DNtWI2C1.js.map +0 -1
  70. package/dist/provision-DUWdcY_a.js.map +0 -1
  71. package/dist/serve-CmWOTR7m.js.map +0 -1
  72. package/dist/server-setup-CIzmDJzT.js.map +0 -1
@@ -1,6 +1,6 @@
1
1
  import { P as warmTreeSitterPool } from "./service-backend-B6D_DY1Z.js";
2
- import { Z as runSelfUpdate, a as setupAndServe, i as parseSharedArgs, n as getCodexEnvVars, o as sharedServerArgs, t as getClaudeCodeEnvVars, v as startKeepAwake } from "./server-setup-CIzmDJzT.js";
3
- import { Mn as provisionAndIndexColbert, Tn as provisionBrowserAssets, Tt as browserToolsEnabled, jn as colbertDegradedWarning } from "./peer-mcp-personas-DNtWI2C1.js";
2
+ import { Z as runSelfUpdate, a as setupAndServe, i as parseSharedArgs, n as getCodexEnvVars, o as sharedServerArgs, t as getClaudeCodeEnvVars, v as startKeepAwake } from "./server-setup-wWidNq5m.js";
3
+ import { Bn as colbertDegradedWarning, Nt as browserToolsEnabled, Pn as provisionBrowserAssets, Vn as provisionAndIndexColbert } from "./peer-mcp-personas-D7vaM-V5.js";
4
4
  import { defineCommand } from "citty";
5
5
  import consola from "consola";
6
6
  import process$1 from "node:process";
@@ -130,4 +130,4 @@ const start = defineCommand({
130
130
  //#endregion
131
131
  export { start };
132
132
 
133
- //# sourceMappingURL=start-rlpaeAtx.js.map
133
+ //# sourceMappingURL=start-CTluQxu5.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"start-rlpaeAtx.js","names":["process"],"sources":["../src/lib/shell.ts","../src/start.ts"],"sourcesContent":["import process from \"node:process\"\n\ntype ShellName = \"bash\" | \"zsh\" | \"fish\" | \"powershell\" | \"cmd\" | \"sh\"\ntype EnvVars = Record<string, string | undefined>\n\nfunction getShell(): ShellName {\n const { platform, env } = process\n\n if (platform === \"win32\") {\n // Git Bash / MSYS2 / Cygwin set SHELL even on Windows\n if (env.SHELL) {\n if (env.SHELL.endsWith(\"zsh\")) return \"zsh\"\n if (env.SHELL.endsWith(\"fish\")) return \"fish\"\n if (env.SHELL.endsWith(\"bash\")) return \"bash\"\n return \"sh\"\n }\n\n // Windows PowerShell 5.x sets this\n if (env.POWERSHELL_DISTRIBUTION_CHANNEL) return \"powershell\"\n\n // PowerShell (both 5.x and 7+/pwsh) adds user-scoped module paths\n // at runtime. The system-level PSModulePath in CMD lacks these paths.\n if (env.PSModulePath) {\n const lower = env.PSModulePath.toLowerCase()\n if (\n lower.includes(\"documents\\\\powershell\")\n || lower.includes(\"documents\\\\windowspowershell\")\n ) {\n return \"powershell\"\n }\n }\n\n return \"cmd\"\n }\n\n const shellPath = env.SHELL\n if (shellPath) {\n if (shellPath.endsWith(\"zsh\")) return \"zsh\"\n if (shellPath.endsWith(\"fish\")) return \"fish\"\n if (shellPath.endsWith(\"bash\")) return \"bash\"\n }\n\n return \"sh\"\n}\n\nfunction quotePosixValue(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`\n}\n\nfunction quotePowerShellValue(value: string): string {\n return `'${value.replace(/'/g, \"''\")}'`\n}\n\n/**\n * Generates a copy-pasteable script to set multiple environment variables\n * and run a subsequent command.\n * @param {EnvVars} envVars - An object of environment variables to set.\n * @param {string} commandToRun - The command to run after setting the variables.\n * @returns {string} The formatted script string.\n */\nexport function generateEnvScript(\n envVars: EnvVars,\n commandToRun: string = \"\",\n): string {\n const shell = getShell()\n const filteredEnvVars = Object.entries(envVars).filter(\n ([, value]) => value !== undefined,\n ) as Array<[string, string]>\n\n let commandBlock: string\n\n switch (shell) {\n case \"powershell\": {\n commandBlock = filteredEnvVars\n .map(([key, value]) => `$env:${key} = ${quotePowerShellValue(value)}`)\n .join(\"; \")\n break\n }\n case \"cmd\": {\n commandBlock = filteredEnvVars\n .map(([key, value]) => `set \"${key}=${value}\"`)\n .join(\" & \")\n break\n }\n case \"fish\": {\n commandBlock = filteredEnvVars\n .map(([key, value]) => `set -gx ${key} ${quotePosixValue(value)}`)\n .join(\"; \")\n break\n }\n default: {\n // bash, zsh, sh\n const assignments = filteredEnvVars\n .map(([key, value]) => `${key}=${quotePosixValue(value)}`)\n .join(\" \")\n commandBlock = filteredEnvVars.length > 0 ? `export ${assignments}` : \"\"\n break\n }\n }\n\n if (commandBlock && commandToRun) {\n const separator =\n shell === \"cmd\" ? \" & \" : shell === \"powershell\" ? \"; \" : \" && \"\n return `${commandBlock}${separator}${commandToRun}`\n }\n\n return commandBlock || commandToRun\n}\n","#!/usr/bin/env node\n\nimport { defineCommand } from \"citty\"\nimport clipboard from \"clipboardy\"\nimport consola from \"consola\"\n\nimport { generateEnvScript } from \"./lib/shell\"\nimport { DEFAULT_CODEX_MODEL, DEFAULT_PORT } from \"./lib/port\"\nimport { provisionBrowserAssets } from \"./lib/browser-mcp/provision\"\nimport { browserToolsEnabled } from \"./lib/mcp-capabilities\"\nimport { colbertDegradedWarning, provisionAndIndexColbert } from \"./lib/colbert\"\nimport { startKeepAwake } from \"./lib/keep-awake\"\nimport { warmTreeSitterPool } from \"./lib/tree-sitter-pool/pool\"\nimport {\n getClaudeCodeEnvVars,\n getCodexEnvVars,\n parseSharedArgs,\n setupAndServe,\n sharedServerArgs,\n} from \"./lib/server-setup\"\nimport { runSelfUpdate } from \"./lib/self-update\"\n\nfunction printAndCopyCommand(command: string, label: string): void {\n consola.box(`${label}\\n\\n${command}`)\n try {\n clipboard.writeSync(command)\n consola.success(`Copied ${label} command to clipboard!`)\n } catch {\n consola.warn(\"Failed to copy to clipboard. Copy the command above manually.\")\n }\n}\n\nfunction generateClaudeCodeCommand(serverUrl: string, model?: string) {\n const envVars = getClaudeCodeEnvVars(serverUrl, model)\n const command = generateEnvScript(envVars, \"claude --dangerously-skip-permissions\")\n printAndCopyCommand(command, \"Claude Code\")\n}\n\nfunction generateCodexCommand(serverUrl: string, model?: string) {\n const codexModel = model ?? DEFAULT_CODEX_MODEL\n const envVars = getCodexEnvVars(serverUrl)\n const command = generateEnvScript(envVars, `codex -m ${codexModel}`)\n printAndCopyCommand(command, \"Codex CLI\")\n}\n\nexport const start = defineCommand({\n meta: {\n name: \"start\",\n description: \"Start the github-router server\",\n },\n args: {\n ...sharedServerArgs,\n cc: {\n type: \"boolean\",\n default: false,\n description:\n \"Generate a command to launch Claude Code with Copilot API config\",\n },\n cx: {\n type: \"boolean\",\n default: false,\n description:\n \"Generate a command to launch Codex CLI with Copilot API config\",\n },\n model: {\n alias: \"m\",\n type: \"string\",\n description: \"Override the default model (used with --cc or --cx)\",\n },\n },\n async run({ args }) {\n const parsed = parseSharedArgs(args as unknown as Record<string, unknown>)\n\n const { serverUrl } = await setupAndServe({\n ...parsed,\n port: parsed.port ?? DEFAULT_PORT,\n silent: false,\n })\n\n // Best-effort self-update (detached, applies next launch). Runs\n // after the server is listening so the bounded probe can't delay it.\n void runSelfUpdate({ selfUpdate: args[\"self-update\"] !== false })\n\n // Best-effort ColBERT semantic-search provision + background index of\n // the launch cwd (if a git repo). Opt-IN via --search (no-op otherwise);\n // never blocks launch, never throws.\n void provisionAndIndexColbert()\n\n // Surface a terminally-failed semantic index to the HUMAN (see the note\n // in claude.ts). Fire-and-forget; lexical search still works.\n void colbertDegradedWarning()\n .then((warning) => {\n if (warning) process.stderr.write(`${warning}\\n`)\n })\n .catch(() => {})\n\n // Ready one tree-sitter worker in the background so the first code search\n // avoids WASM/grammar initialization. One worker keeps launch CPU bounded;\n // demand grows the pool lazily. Opt out with GH_ROUTER_DISABLE_TS_POOL_WARMUP=1.\n void warmTreeSitterPool()\n\n // Best-effort: keep the machine awake while the proxy serves (win32\n // default-on; opt out with GH_ROUTER_DISABLE_KEEP_AWAKE=1). Holds a\n // SetThreadExecutionState assertion via a persistent PowerShell\n // helper. Self-registers its own SIGINT/SIGTERM/exit reaper — load-\n // bearing here, because `start` has no launchChild/onShutdown.\n startKeepAwake()\n\n // Best-effort: materialize the browser extension + bridge into the\n // stable app-dir and stamp the running version, so a one-time \"Load\n // unpacked\" survives npx/bunx upgrades. Gated on --browse; never\n // blocks launch, never throws.\n if (browserToolsEnabled()) {\n void provisionBrowserAssets().catch((err) =>\n consola.debug(\"Browser extension provisioning failed:\", err),\n )\n }\n\n if (args.cc) generateClaudeCodeCommand(serverUrl, args.model)\n if (args.cx) generateCodexCommand(serverUrl, args.model)\n\n consola.box(\n `🌐 Usage Viewer: https://animeshkundu.github.io/github-router/dashboard.html?endpoint=${serverUrl}/usage`,\n )\n },\n})\n"],"mappings":"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"}
1
+ {"version":3,"file":"start-CTluQxu5.js","names":["process"],"sources":["../src/lib/shell.ts","../src/start.ts"],"sourcesContent":["import process from \"node:process\"\n\ntype ShellName = \"bash\" | \"zsh\" | \"fish\" | \"powershell\" | \"cmd\" | \"sh\"\ntype EnvVars = Record<string, string | undefined>\n\nfunction getShell(): ShellName {\n const { platform, env } = process\n\n if (platform === \"win32\") {\n // Git Bash / MSYS2 / Cygwin set SHELL even on Windows\n if (env.SHELL) {\n if (env.SHELL.endsWith(\"zsh\")) return \"zsh\"\n if (env.SHELL.endsWith(\"fish\")) return \"fish\"\n if (env.SHELL.endsWith(\"bash\")) return \"bash\"\n return \"sh\"\n }\n\n // Windows PowerShell 5.x sets this\n if (env.POWERSHELL_DISTRIBUTION_CHANNEL) return \"powershell\"\n\n // PowerShell (both 5.x and 7+/pwsh) adds user-scoped module paths\n // at runtime. The system-level PSModulePath in CMD lacks these paths.\n if (env.PSModulePath) {\n const lower = env.PSModulePath.toLowerCase()\n if (\n lower.includes(\"documents\\\\powershell\")\n || lower.includes(\"documents\\\\windowspowershell\")\n ) {\n return \"powershell\"\n }\n }\n\n return \"cmd\"\n }\n\n const shellPath = env.SHELL\n if (shellPath) {\n if (shellPath.endsWith(\"zsh\")) return \"zsh\"\n if (shellPath.endsWith(\"fish\")) return \"fish\"\n if (shellPath.endsWith(\"bash\")) return \"bash\"\n }\n\n return \"sh\"\n}\n\nfunction quotePosixValue(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`\n}\n\nfunction quotePowerShellValue(value: string): string {\n return `'${value.replace(/'/g, \"''\")}'`\n}\n\n/**\n * Generates a copy-pasteable script to set multiple environment variables\n * and run a subsequent command.\n * @param {EnvVars} envVars - An object of environment variables to set.\n * @param {string} commandToRun - The command to run after setting the variables.\n * @returns {string} The formatted script string.\n */\nexport function generateEnvScript(\n envVars: EnvVars,\n commandToRun: string = \"\",\n): string {\n const shell = getShell()\n const filteredEnvVars = Object.entries(envVars).filter(\n ([, value]) => value !== undefined,\n ) as Array<[string, string]>\n\n let commandBlock: string\n\n switch (shell) {\n case \"powershell\": {\n commandBlock = filteredEnvVars\n .map(([key, value]) => `$env:${key} = ${quotePowerShellValue(value)}`)\n .join(\"; \")\n break\n }\n case \"cmd\": {\n commandBlock = filteredEnvVars\n .map(([key, value]) => `set \"${key}=${value}\"`)\n .join(\" & \")\n break\n }\n case \"fish\": {\n commandBlock = filteredEnvVars\n .map(([key, value]) => `set -gx ${key} ${quotePosixValue(value)}`)\n .join(\"; \")\n break\n }\n default: {\n // bash, zsh, sh\n const assignments = filteredEnvVars\n .map(([key, value]) => `${key}=${quotePosixValue(value)}`)\n .join(\" \")\n commandBlock = filteredEnvVars.length > 0 ? `export ${assignments}` : \"\"\n break\n }\n }\n\n if (commandBlock && commandToRun) {\n const separator =\n shell === \"cmd\" ? \" & \" : shell === \"powershell\" ? \"; \" : \" && \"\n return `${commandBlock}${separator}${commandToRun}`\n }\n\n return commandBlock || commandToRun\n}\n","#!/usr/bin/env node\n\nimport { defineCommand } from \"citty\"\nimport clipboard from \"clipboardy\"\nimport consola from \"consola\"\n\nimport { generateEnvScript } from \"./lib/shell\"\nimport { DEFAULT_CODEX_MODEL, DEFAULT_PORT } from \"./lib/port\"\nimport { provisionBrowserAssets } from \"./lib/browser-mcp/provision\"\nimport { browserToolsEnabled } from \"./lib/mcp-capabilities\"\nimport { colbertDegradedWarning, provisionAndIndexColbert } from \"./lib/colbert\"\nimport { startKeepAwake } from \"./lib/keep-awake\"\nimport { warmTreeSitterPool } from \"./lib/tree-sitter-pool/pool\"\nimport {\n getClaudeCodeEnvVars,\n getCodexEnvVars,\n parseSharedArgs,\n setupAndServe,\n sharedServerArgs,\n} from \"./lib/server-setup\"\nimport { runSelfUpdate } from \"./lib/self-update\"\n\nfunction printAndCopyCommand(command: string, label: string): void {\n consola.box(`${label}\\n\\n${command}`)\n try {\n clipboard.writeSync(command)\n consola.success(`Copied ${label} command to clipboard!`)\n } catch {\n consola.warn(\"Failed to copy to clipboard. Copy the command above manually.\")\n }\n}\n\nfunction generateClaudeCodeCommand(serverUrl: string, model?: string) {\n const envVars = getClaudeCodeEnvVars(serverUrl, model)\n const command = generateEnvScript(envVars, \"claude --dangerously-skip-permissions\")\n printAndCopyCommand(command, \"Claude Code\")\n}\n\nfunction generateCodexCommand(serverUrl: string, model?: string) {\n const codexModel = model ?? DEFAULT_CODEX_MODEL\n const envVars = getCodexEnvVars(serverUrl)\n const command = generateEnvScript(envVars, `codex -m ${codexModel}`)\n printAndCopyCommand(command, \"Codex CLI\")\n}\n\nexport const start = defineCommand({\n meta: {\n name: \"start\",\n description: \"Start the github-router server\",\n },\n args: {\n ...sharedServerArgs,\n cc: {\n type: \"boolean\",\n default: false,\n description:\n \"Generate a command to launch Claude Code with Copilot API config\",\n },\n cx: {\n type: \"boolean\",\n default: false,\n description:\n \"Generate a command to launch Codex CLI with Copilot API config\",\n },\n model: {\n alias: \"m\",\n type: \"string\",\n description: \"Override the default model (used with --cc or --cx)\",\n },\n },\n async run({ args }) {\n const parsed = parseSharedArgs(args as unknown as Record<string, unknown>)\n\n const { serverUrl } = await setupAndServe({\n ...parsed,\n port: parsed.port ?? DEFAULT_PORT,\n silent: false,\n })\n\n // Best-effort self-update (detached, applies next launch). Runs\n // after the server is listening so the bounded probe can't delay it.\n void runSelfUpdate({ selfUpdate: args[\"self-update\"] !== false })\n\n // Best-effort ColBERT semantic-search provision + background index of\n // the launch cwd (if a git repo). Opt-IN via --search (no-op otherwise);\n // never blocks launch, never throws.\n void provisionAndIndexColbert()\n\n // Surface a terminally-failed semantic index to the HUMAN (see the note\n // in claude.ts). Fire-and-forget; lexical search still works.\n void colbertDegradedWarning()\n .then((warning) => {\n if (warning) process.stderr.write(`${warning}\\n`)\n })\n .catch(() => {})\n\n // Ready one tree-sitter worker in the background so the first code search\n // avoids WASM/grammar initialization. One worker keeps launch CPU bounded;\n // demand grows the pool lazily. Opt out with GH_ROUTER_DISABLE_TS_POOL_WARMUP=1.\n void warmTreeSitterPool()\n\n // Best-effort: keep the machine awake while the proxy serves (win32\n // default-on; opt out with GH_ROUTER_DISABLE_KEEP_AWAKE=1). Holds a\n // SetThreadExecutionState assertion via a persistent PowerShell\n // helper. Self-registers its own SIGINT/SIGTERM/exit reaper — load-\n // bearing here, because `start` has no launchChild/onShutdown.\n startKeepAwake()\n\n // Best-effort: materialize the browser extension + bridge into the\n // stable app-dir and stamp the running version, so a one-time \"Load\n // unpacked\" survives npx/bunx upgrades. Gated on --browse; never\n // blocks launch, never throws.\n if (browserToolsEnabled()) {\n void provisionBrowserAssets().catch((err) =>\n consola.debug(\"Browser extension provisioning failed:\", err),\n )\n }\n\n if (args.cc) generateClaudeCodeCommand(serverUrl, args.model)\n if (args.cx) generateCodexCommand(serverUrl, args.model)\n\n consola.box(\n `🌐 Usage Viewer: https://animeshkundu.github.io/github-router/dashboard.html?endpoint=${serverUrl}/usage`,\n )\n },\n})\n"],"mappings":"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"}
@@ -33,6 +33,8 @@ const state = {
33
33
  kustoDatabase: null,
34
34
  cloudAgentEnabled: false,
35
35
  cloudAgentEnvironment: "prod",
36
+ workiqEnabled: false,
37
+ workiqWriteEnabled: false,
36
38
  humanlikeForce: "auto",
37
39
  sessionId: randomUUID(),
38
40
  machineId: randomBytes(32).toString("hex"),
@@ -64,4 +66,4 @@ Object.defineProperty(state, "peerMcpNonce", {
64
66
  //#endregion
65
67
  export { state as t };
66
68
 
67
- //# sourceMappingURL=state-CiwCLVDZ.js.map
69
+ //# sourceMappingURL=state-DzsaGHr9.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"state-CiwCLVDZ.js","names":[],"sources":["../src/lib/state.ts"],"sourcesContent":["import { randomBytes, randomUUID } from \"node:crypto\"\n\nimport type { ModelsResponse } from \"~/services/copilot/get-models\"\nimport type { BluebirdMcpClient } from \"./bluebird-client\"\nimport type { LaunchProfileId } from \"./launch-profile\"\n\n/**\n * One authenticated `github-router claude` (or `serve`) launch's identity\n * and capability scope, keyed by `launchId` in `state.launchRegistry`.\n *\n * Replaces the earlier scalar `state.peerMcpNonce` assumption — a single\n * process-global nonce cannot express \"which profile is this caller\", so\n * a concurrent fast + standard launch (or a reconnect) had no way to keep\n * their identities from being interchangeable. Each entry carries BOTH\n * credentials a launch presents on the wire:\n *\n * - `nonce` — the `/mcp` bearer (Streamable HTTP `Authorization` header).\n * - `secret` — the `/v1/messages` identity-preflight bearer, deliberately\n * a SEPARATE credential from `nonce` so leaking one surface's token\n * (say, via a client log) does not also authenticate the other.\n *\n * `allowedGroups` / `allowedPersonas` are the narrowing declaration for\n * scoped MCP surfaces: `undefined` means UNRESTRICTED (the standard/BYO\n * launch shape today), and a concrete `ReadonlySet` is a restricted profile's\n * hard allow-list. This module only stores and looks up the declaration;\n * enforcing it against `tools/list` / `tools/call` is the MCP route\n * handler's job.\n */\nexport interface LaunchRegistryEntry {\n /** Opaque per-launch id. Primary key into `state.launchRegistry`. */\n launchId: string\n /** `/mcp` Streamable HTTP bearer for this launch. */\n nonce: string\n /**\n * Optional lead-only `/mcp` bearer for fast profile.\n * Grants access to lead-only tools such as `astra`.\n */\n leadPeersNonce?: string\n /** `/v1/messages` identity-preflight bearer for this launch. */\n secret: string\n /** Which launch profile authenticated this entry. */\n profileId: LaunchProfileId\n /** Scoped MCP group allow-list. `undefined` = unrestricted. */\n allowedGroups?: ReadonlySet<string>\n /** Persona (peers-group) tool-name allow-list. `undefined` = unrestricted. */\n allowedPersonas?: ReadonlySet<string>\n /**\n * The client's own conversation id, learned from `x-claude-code-session-id`\n * on this launch's `/v1/messages` traffic.\n *\n * `/mcp` has no conversation header of its own, so a local consult issued\n * from an MCP tool call has nothing to key prompt-cache routing on. The\n * lead's `/v1/messages` requests are the one channel that carries the id,\n * and the launch registry is the shared place the messages route and the MCP\n * route both hold. Latest value wins: `/clear` starts a new conversation and\n * the stale id would otherwise follow the session forever.\n */\n sessionId?: string\n createdAt: number\n}\n\n/**\n * Registry key backing the `state.peerMcpNonce` back-compat accessor\n * below. Not a real launch id (no `registerLaunch` caller ever produces\n * this string), so it can never collide with a genuine per-launch UUID.\n */\nconst DEFAULT_LAUNCH_ID = \"__default__\"\n\nexport interface State {\n githubToken?: string\n copilotToken?: string\n /**\n * GitHub login of `githubToken`, resolved once at setup for the\n * launch summary. Display-only; auth decisions never read it.\n */\n githubUserLogin?: string\n\n /**\n * Where `githubToken` came from, which decides whether the proxy may\n * re-read it from disk.\n *\n * `\"file\"` — read from `PATHS.GITHUB_TOKEN_PATH`. A re-read is allowed, so\n * an out-of-band `github-router auth` heals a running proxy without a\n * restart.\n *\n * `\"explicit\"` — supplied by the operator via `--github-token` / `GH_TOKEN`.\n * The file is NEVER read on this path: silently replacing a\n * caller-supplied credential with whatever happens to be on disk would\n * override an explicit instruction. It also means \"run `github-router\n * auth`\" is false advice for this source — the remediation is to replace\n * the supplied value.\n */\n githubTokenSource?: \"file\" | \"explicit\"\n\n /**\n * Monotonic counter bumped on every SUCCESSFUL Copilot token exchange.\n *\n * This is the retry criterion for `tryRefreshAndRetry`, and it is\n * deliberately not \"did the token string change\": two consecutive\n * successful exchanges were observed returning an identical token, so a\n * string comparison would silently suppress legitimate retries. Nor is it\n * the refresh's own verdict — with requests A and B both holding a stale\n * token, A can refresh while B's later 401 is cooled down to a no-op, and\n * a verdict of \"nothing happened\" would fail B even though a good token is\n * already in `copilotToken`. Comparing generations answers the question\n * each request actually has: \"is what is in state now different from what\n * I already tried?\"\n */\n copilotTokenGeneration: number\n\n /**\n * Wall-clock ms after which `copilotToken` should be refreshed — already\n * skew-adjusted, so the per-request check is a plain `Date.now() >=` compare.\n *\n * Derived from the exchange's `refresh_in` (a DURATION) and never from its\n * absolute `expires_at`. A local clock running ahead of GitHub's would make\n * an absolute timestamp look already-past on a brand-new token and drive a\n * refresh storm; a duration is immune, because it is anchored to the same\n * clock that later reads it.\n */\n copilotTokenRefreshAt?: number\n\n /**\n * Second, WRITE-capable GitHub token for the first-mate\n * agent-orchestration surface (`--agents`). Minted by a separate\n * device-flow login against the GitHub CLI's OAuth client\n * (`GITHUB_AGENT_CLIENT_ID`, scopes `repo workflow read:org`) and\n * stored at `PATHS.GITHUB_AGENT_TOKEN_PATH`, apart from `githubToken`\n * (the Copilot App token, read:user). The first-mate GitHub service\n * layer uses this for ALL its calls (reads included, so it also works\n * on private repos). Undefined until the agent login has run.\n */\n githubAgentToken?: string\n\n accountType: string\n copilotApiUrl?: string\n models?: ModelsResponse\n vsCodeVersion?: string\n copilotVersion?: string\n\n manualApprove: boolean\n rateLimitWait: boolean\n showToken: boolean\n extendedBetas: boolean\n\n /**\n * Opt-in flag for the browser-control MCP tools (`browser_*`). Set by\n * `setupAndServe` from the `--browse` CLI flag or\n * `GH_ROUTER_ENABLE_BROWSE=1` env var. When false, all `browser_*`\n * tools are dropped from `tools/list` AND `tools/call` returns\n * -32601 — same defense-in-depth pattern as `workerToolsEnabled()` /\n * `standInToolEnabled()`. See `browserToolsEnabled()` in\n * `src/routes/mcp/handler.ts`.\n */\n browseEnabled: boolean\n\n /**\n * Opt-in flag for the fleet session-control MCP tools (`mcp__fleet__*`).\n * Set by `setupAndServe` from the `--fleet` CLI flag or\n * `GH_ROUTER_ENABLE_FLEET=1` env var. When false, all fleet tools are\n * dropped from `tools/list` AND `tools/call` returns -32601 — same\n * defense-in-depth pattern as `workerToolsEnabled()` /\n * `standInToolEnabled()`. See `fleetToolsEnabled()` in\n * `src/lib/mcp-capabilities.ts`.\n */\n fleetEnabled: boolean\n\n /**\n * Opt-in flag for the first-mate agent-orchestration MCP tools\n * (`mcp__first-mate__*`) and the in-process GitHub cloud-agent driving\n * layer. Set by `setupAndServe` from the `--agents` CLI flag or\n * `GH_ROUTER_ENABLE_AGENTS=1`. When false, the first-mate tools are\n * dropped from `tools/list` AND `tools/call` returns -32601 — same\n * defense-in-depth pattern as `fleetToolsEnabled()`. Additionally\n * requires `state.githubAgentToken` present (the write login), so the\n * surface is invisible rather than 401-ing when unauthenticated. See\n * `agentToolsEnabled()` in `src/lib/mcp-capabilities.ts`.\n */\n agentsEnabled: boolean\n\n /**\n * When true, --power-browse was passed (or GH_ROUTER_ENABLE_POWER_BROWSE=1\n * is set). Exposes the FULL browser MCP surface (~18 tools) on /mcp,\n * including the L0/L1 primitives that hand DOM details (refs,\n * bboxes, role/name dumps) to the lead model. Default --browse mode\n * exposes only the 6 lead-model tools (act, observe, extract,\n * navigate, screenshot, open_tab). Always implies browseEnabled.\n */\n powerBrowseEnabled: boolean\n\n /**\n * Opt-in flag for ColBERT/colgrep semantic code search. Set by\n * `setupAndServe` from the `--search` CLI flag or\n * `GH_ROUTER_ENABLE_SEMANTIC_SEARCH=1` env var. When false, no colgrep\n * binary/model is provisioned, no workspace is indexed, and the `code`\n * MCP tool serves lexical results (with `lexical-fallback` source when\n * semantic mode was requested). See `semanticSearchOptedIn()` in\n * `src/lib/colbert/index.ts`; `GH_ROUTER_DISABLE_SEMANTIC_SEARCH=1`\n * hard-disables regardless of this flag.\n */\n searchEnabled: boolean\n\n /**\n * Opt-in flag for Bluebird Azure DevOps code search. Set by\n * `setupAndServe` from the `--bluebird` CLI flag or\n * `GH_ROUTER_ENABLE_BLUEBIRD=1` env var. When true, the `code` MCP\n * tool routes `semantic`/`lexical` modes through the Bluebird MCP\n * server. This flag is independent from `searchEnabled`, which controls\n * local ColBERT provisioning; `exact`/`regex`/`ast` stay local.\n * See `src/lib/bluebird-client.ts`.\n */\n bluebirdEnabled: boolean\n\n /** Last connected Bluebird client, retained only for compatibility and\n * diagnostics. Client selection is owned by the Bluebird runtime manager. */\n bluebirdClient: BluebirdMcpClient | null\n\n /** Resolved Bluebird scope (org/project/repos/branch), for logging and\n * the `x-mcp-ec-*` headers baked into the client. */\n bluebirdOrganization: string | null\n bluebirdProject: string | null\n bluebirdRepositories: Array<string>\n bluebirdBranch: string | null\n\n /**\n * Azure DevOps remote MCP group (`mcp__ado__*`). Enabled by `--ado`, by\n * `GH_ROUTER_ENABLE_ADO=1`, or automatically when the workspace's git\n * remotes resolve to an Azure DevOps repository. See\n * `src/lib/azure-mcp-flags.ts` for the precedence and the trust argument.\n */\n adoEnabled: boolean\n /** Organization whose `https://mcp.dev.azure.com/{org}` endpoint is used. */\n adoOrganization: string | null\n /**\n * `X-MCP-Toolsets` selection. The single entry `\"all\"` means \"send no\n * header\". Empty only while the group is off.\n */\n adoToolsets: Array<string>\n /**\n * Send `X-MCP-Readonly: true`. True unless `--ado-write` was passed. Never\n * cleared by discovery — a git remote can turn this group on but can never\n * widen it to writes.\n */\n adoReadOnly: boolean\n\n /**\n * Kusto (Azure Data Explorer) MCP group (`mcp__kusto__*`). Turned on by the\n * operator's `--kusto` flag, by a named cluster, or automatically when the\n * workspace's git remotes resolve to an Azure DevOps repository. Discovery\n * turns the GROUP on and never supplies a cluster: the model names one per\n * call, and the operator's own cluster access bounds the reach.\n */\n kustoEnabled: boolean\n /**\n * Default cluster for calls that do not name one, or null. Null no longer\n * turns the group off: every kusto tool takes its own `cluster`, so a launch\n * with no default still works, it just requires the argument.\n */\n kustoCluster: string | null\n kustoDatabase: string | null\n\n /**\n * Cloud Agent Job API v2 MCP group (`mcp__cloudagent__*`): hand work to a cloud\n * coding agent running against an Azure DevOps repository.\n *\n * Enabled by `--cloudagent`, by `GH_ROUTER_ENABLE_CLOUDAGENT=1`, or automatically\n * when the workspace's git remotes resolve to an Azure DevOps repository.\n * Discovery enables the whole group, write tools included, matching the ADO,\n * Kusto and Bluebird groups; `--no-cloudagent` remains the operator's veto.\n */\n cloudAgentEnabled: boolean\n /** `prod` or `ppe`, normalized by `resolveCloudAgentFlags()` at launch. */\n cloudAgentEnvironment: string\n\n /**\n * Humanlike pacing override:\n * \"on\" - --humanlike CLI flag or GH_ROUTER_HUMANLIKE=1 env;\n * inject Beta-distributed inter-action delays, Bezier\n * mouse paths, per-keystroke jitter, scroll chunking\n * into every browser_* action dispatch.\n * \"off\" - GH_ROUTER_BROWSER_NO_HUMANLIKE=1; HARD disable, wins\n * over \"on\" so tests are reproducible.\n * \"auto\" - default; pacing engages only when bot-challenge\n * detection fires (Phase 4-future).\n *\n * Lead model never sees this state — it's an internal concern.\n */\n humanlikeForce: \"on\" | \"off\" | \"auto\"\n\n // Rate limiting configuration\n rateLimitSeconds?: number\n lastRequestTimestamp?: number\n\n // Persistent session identifiers to match VS Code fingerprint\n sessionId: string\n machineId: string\n\n /**\n * Keyed per-launch registry for the loopback `/mcp` endpoint AND the\n * `/v1/messages` identity preflight. Set by the `claude` subcommand\n * (via `registerLaunch` in `./launch-registry`) after `setupAndServe`\n * and before spawning Claude Code; removed by the launch's own\n * cleanup. When empty, `/mcp` rejects all requests — closes the\n * loopback-no-auth gap (DNS rebinding, malicious browser-ext native\n * messaging, sibling-process probe) exactly as the old scalar nonce\n * did when unset.\n *\n * Multiple entries coexist for concurrent fast/standard launches (or a\n * launch plus a reconnect); each is looked up by its OWN nonce/secret,\n * so two launches' authenticated identities never cross.\n */\n launchRegistry: Map<string, LaunchRegistryEntry>\n\n /**\n * @deprecated Back-compat accessor over the registry's DEFAULT_LAUNCH_ID\n * entry (profileId \"standard\", unrestricted `allowedGroups`/\n * `allowedPersonas`) — defined below via `Object.defineProperty`, not a\n * real stored field. Reading returns that entry's nonce; writing creates\n * or updates it (or deletes it on `undefined`). Exists so single-launch\n * call sites and tests that already do `state.peerMcpNonce = NONCE`\n * keep working unmodified while `checkAuth` and the identity preflight\n * consult the real keyed registry underneath. New code should call\n * `registerLaunch` / `findLaunchByNonce` / `findLaunchBySecret` from\n * `./launch-registry` directly instead of reading/writing this field.\n */\n peerMcpNonce?: string\n\n /**\n * Set by `github-router serve` (a single machine-wide control plane serving\n * many repos). When true, repo-scoped worker tools require an explicit/So-derived\n * `workspace` and must NOT silently default to the proxy launch cwd.\n */\n serveMode?: boolean\n}\n\nexport const state: State = {\n accountType: \"enterprise\",\n copilotTokenGeneration: 0,\n manualApprove: false,\n rateLimitWait: false,\n showToken: false,\n extendedBetas: false,\n browseEnabled: false,\n fleetEnabled: false,\n agentsEnabled: false,\n powerBrowseEnabled: false,\n searchEnabled: false,\n bluebirdEnabled: false,\n bluebirdClient: null,\n bluebirdOrganization: null,\n bluebirdProject: null,\n bluebirdRepositories: [],\n bluebirdBranch: null,\n adoEnabled: false,\n adoOrganization: null,\n adoToolsets: [],\n adoReadOnly: true,\n kustoEnabled: false,\n kustoCluster: null,\n kustoDatabase: null,\n cloudAgentEnabled: false,\n cloudAgentEnvironment: \"prod\",\n humanlikeForce: \"auto\",\n sessionId: randomUUID(),\n machineId: randomBytes(32).toString(\"hex\"),\n launchRegistry: new Map(),\n}\n\n// `peerMcpNonce` is not a plain data field — it's a live view onto\n// `state.launchRegistry.get(DEFAULT_LAUNCH_ID)`. Defined via\n// `Object.defineProperty` (rather than a class) so `state` stays the\n// plain object literal every existing importer already destructures /\n// mutates directly.\nObject.defineProperty(state, \"peerMcpNonce\", {\n enumerable: true,\n configurable: true,\n get(): string | undefined {\n return state.launchRegistry.get(DEFAULT_LAUNCH_ID)?.nonce\n },\n set(value: string | undefined) {\n if (value === undefined) {\n state.launchRegistry.delete(DEFAULT_LAUNCH_ID)\n return\n }\n const existing = state.launchRegistry.get(DEFAULT_LAUNCH_ID)\n state.launchRegistry.set(DEFAULT_LAUNCH_ID, {\n launchId: DEFAULT_LAUNCH_ID,\n nonce: value,\n // A caller that only ever touches `peerMcpNonce` exposes MCP only and has\n // no Messages identity secret.\n // Never reuse the MCP bearer across surfaces: an empty secret cannot match\n // any non-empty custom header, while registered Claude launches always use\n // `registerLaunch` with independently generated credentials.\n secret: existing?.secret ?? \"\",\n profileId: existing?.profileId ?? \"standard\",\n allowedGroups: existing?.allowedGroups,\n allowedPersonas: existing?.allowedPersonas,\n createdAt: existing?.createdAt ?? Date.now(),\n })\n },\n})\n"],"mappings":";;;;;;;AAkEA,MAAM,oBAAoB;AA6Q1B,MAAa,QAAe;CAC1B,aAAa;CACb,wBAAwB;CACxB,eAAe;CACf,eAAe;CACf,WAAW;CACX,eAAe;CACf,eAAe;CACf,cAAc;CACd,eAAe;CACf,oBAAoB;CACpB,eAAe;CACf,iBAAiB;CACjB,gBAAgB;CAChB,sBAAsB;CACtB,iBAAiB;CACjB,sBAAsB,CAAC;CACvB,gBAAgB;CAChB,YAAY;CACZ,iBAAiB;CACjB,aAAa,CAAC;CACd,aAAa;CACb,cAAc;CACd,cAAc;CACd,eAAe;CACf,mBAAmB;CACnB,uBAAuB;CACvB,gBAAgB;CAChB,WAAW,WAAW;CACtB,WAAW,YAAY,EAAE,CAAC,CAAC,SAAS,KAAK;CACzC,gCAAgB,IAAI,IAAI;AAC1B;AAOA,OAAO,eAAe,OAAO,gBAAgB;CAC3C,YAAY;CACZ,cAAc;CACd,MAA0B;EACxB,OAAO,MAAM,eAAe,IAAI,iBAAiB,CAAC,EAAE;CACtD;CACA,IAAI,OAA2B;EAC7B,IAAI,UAAU,KAAA,GAAW;GACvB,MAAM,eAAe,OAAO,iBAAiB;GAC7C;EACF;EACA,MAAM,WAAW,MAAM,eAAe,IAAI,iBAAiB;EAC3D,MAAM,eAAe,IAAI,mBAAmB;GAC1C,UAAU;GACV,OAAO;GAMP,QAAQ,UAAU,UAAU;GAC5B,WAAW,UAAU,aAAa;GAClC,eAAe,UAAU;GACzB,iBAAiB,UAAU;GAC3B,WAAW,UAAU,aAAa,KAAK,IAAI;EAC7C,CAAC;CACH;AACF,CAAC"}
1
+ {"version":3,"file":"state-DzsaGHr9.js","names":[],"sources":["../src/lib/state.ts"],"sourcesContent":["import { randomBytes, randomUUID } from \"node:crypto\"\n\nimport type { ModelsResponse } from \"~/services/copilot/get-models\"\nimport type { BluebirdMcpClient } from \"./bluebird-client\"\nimport type { LaunchProfileId } from \"./launch-profile\"\n\n/**\n * One authenticated `github-router claude` (or `serve`) launch's identity\n * and capability scope, keyed by `launchId` in `state.launchRegistry`.\n *\n * Replaces the earlier scalar `state.peerMcpNonce` assumption — a single\n * process-global nonce cannot express \"which profile is this caller\", so\n * a concurrent fast + standard launch (or a reconnect) had no way to keep\n * their identities from being interchangeable. Each entry carries BOTH\n * credentials a launch presents on the wire:\n *\n * - `nonce` — the `/mcp` bearer (Streamable HTTP `Authorization` header).\n * - `secret` — the `/v1/messages` identity-preflight bearer, deliberately\n * a SEPARATE credential from `nonce` so leaking one surface's token\n * (say, via a client log) does not also authenticate the other.\n *\n * `allowedGroups` / `allowedPersonas` are the narrowing declaration for\n * scoped MCP surfaces: `undefined` means UNRESTRICTED (the standard/BYO\n * launch shape today), and a concrete `ReadonlySet` is a restricted profile's\n * hard allow-list. This module only stores and looks up the declaration;\n * enforcing it against `tools/list` / `tools/call` is the MCP route\n * handler's job.\n */\nexport interface LaunchRegistryEntry {\n /** Opaque per-launch id. Primary key into `state.launchRegistry`. */\n launchId: string\n /** `/mcp` Streamable HTTP bearer for this launch. */\n nonce: string\n /**\n * Optional lead-only `/mcp` bearer for fast profile.\n * Grants access to lead-only tools such as `astra`.\n */\n leadPeersNonce?: string\n /** `/v1/messages` identity-preflight bearer for this launch. */\n secret: string\n /** Which launch profile authenticated this entry. */\n profileId: LaunchProfileId\n /** Scoped MCP group allow-list. `undefined` = unrestricted. */\n allowedGroups?: ReadonlySet<string>\n /** Persona (peers-group) tool-name allow-list. `undefined` = unrestricted. */\n allowedPersonas?: ReadonlySet<string>\n /**\n * The client's own conversation id, learned from `x-claude-code-session-id`\n * on this launch's `/v1/messages` traffic.\n *\n * `/mcp` has no conversation header of its own, so a local consult issued\n * from an MCP tool call has nothing to key prompt-cache routing on. The\n * lead's `/v1/messages` requests are the one channel that carries the id,\n * and the launch registry is the shared place the messages route and the MCP\n * route both hold. Latest value wins: `/clear` starts a new conversation and\n * the stale id would otherwise follow the session forever.\n */\n sessionId?: string\n createdAt: number\n}\n\n/**\n * Registry key backing the `state.peerMcpNonce` back-compat accessor\n * below. Not a real launch id (no `registerLaunch` caller ever produces\n * this string), so it can never collide with a genuine per-launch UUID.\n */\nconst DEFAULT_LAUNCH_ID = \"__default__\"\n\nexport interface State {\n githubToken?: string\n copilotToken?: string\n /**\n * GitHub login of `githubToken`, resolved once at setup for the\n * launch summary. Display-only; auth decisions never read it.\n */\n githubUserLogin?: string\n\n /**\n * Where `githubToken` came from, which decides whether the proxy may\n * re-read it from disk.\n *\n * `\"file\"` — read from `PATHS.GITHUB_TOKEN_PATH`. A re-read is allowed, so\n * an out-of-band `github-router auth` heals a running proxy without a\n * restart.\n *\n * `\"explicit\"` — supplied by the operator via `--github-token` / `GH_TOKEN`.\n * The file is NEVER read on this path: silently replacing a\n * caller-supplied credential with whatever happens to be on disk would\n * override an explicit instruction. It also means \"run `github-router\n * auth`\" is false advice for this source — the remediation is to replace\n * the supplied value.\n */\n githubTokenSource?: \"file\" | \"explicit\"\n\n /**\n * Monotonic counter bumped on every SUCCESSFUL Copilot token exchange.\n *\n * This is the retry criterion for `tryRefreshAndRetry`, and it is\n * deliberately not \"did the token string change\": two consecutive\n * successful exchanges were observed returning an identical token, so a\n * string comparison would silently suppress legitimate retries. Nor is it\n * the refresh's own verdict — with requests A and B both holding a stale\n * token, A can refresh while B's later 401 is cooled down to a no-op, and\n * a verdict of \"nothing happened\" would fail B even though a good token is\n * already in `copilotToken`. Comparing generations answers the question\n * each request actually has: \"is what is in state now different from what\n * I already tried?\"\n */\n copilotTokenGeneration: number\n\n /**\n * Wall-clock ms after which `copilotToken` should be refreshed — already\n * skew-adjusted, so the per-request check is a plain `Date.now() >=` compare.\n *\n * Derived from the exchange's `refresh_in` (a DURATION) and never from its\n * absolute `expires_at`. A local clock running ahead of GitHub's would make\n * an absolute timestamp look already-past on a brand-new token and drive a\n * refresh storm; a duration is immune, because it is anchored to the same\n * clock that later reads it.\n */\n copilotTokenRefreshAt?: number\n\n /**\n * Second, WRITE-capable GitHub token for the first-mate\n * agent-orchestration surface (`--agents`). Minted by a separate\n * device-flow login against the GitHub CLI's OAuth client\n * (`GITHUB_AGENT_CLIENT_ID`, scopes `repo workflow read:org`) and\n * stored at `PATHS.GITHUB_AGENT_TOKEN_PATH`, apart from `githubToken`\n * (the Copilot App token, read:user). The first-mate GitHub service\n * layer uses this for ALL its calls (reads included, so it also works\n * on private repos). Undefined until the agent login has run.\n */\n githubAgentToken?: string\n\n accountType: string\n copilotApiUrl?: string\n models?: ModelsResponse\n vsCodeVersion?: string\n copilotVersion?: string\n\n manualApprove: boolean\n rateLimitWait: boolean\n showToken: boolean\n extendedBetas: boolean\n\n /**\n * Opt-in flag for the browser-control MCP tools (`browser_*`). Set by\n * `setupAndServe` from the `--browse` CLI flag or\n * `GH_ROUTER_ENABLE_BROWSE=1` env var. When false, all `browser_*`\n * tools are dropped from `tools/list` AND `tools/call` returns\n * -32601 — same defense-in-depth pattern as `workerToolsEnabled()` /\n * `standInToolEnabled()`. See `browserToolsEnabled()` in\n * `src/routes/mcp/handler.ts`.\n */\n browseEnabled: boolean\n\n /**\n * Opt-in flag for the fleet session-control MCP tools (`mcp__fleet__*`).\n * Set by `setupAndServe` from the `--fleet` CLI flag or\n * `GH_ROUTER_ENABLE_FLEET=1` env var. When false, all fleet tools are\n * dropped from `tools/list` AND `tools/call` returns -32601 — same\n * defense-in-depth pattern as `workerToolsEnabled()` /\n * `standInToolEnabled()`. See `fleetToolsEnabled()` in\n * `src/lib/mcp-capabilities.ts`.\n */\n fleetEnabled: boolean\n\n /**\n * Opt-in flag for the first-mate agent-orchestration MCP tools\n * (`mcp__first-mate__*`) and the in-process GitHub cloud-agent driving\n * layer. Set by `setupAndServe` from the `--agents` CLI flag or\n * `GH_ROUTER_ENABLE_AGENTS=1`. When false, the first-mate tools are\n * dropped from `tools/list` AND `tools/call` returns -32601 — same\n * defense-in-depth pattern as `fleetToolsEnabled()`. Additionally\n * requires `state.githubAgentToken` present (the write login), so the\n * surface is invisible rather than 401-ing when unauthenticated. See\n * `agentToolsEnabled()` in `src/lib/mcp-capabilities.ts`.\n */\n agentsEnabled: boolean\n\n /**\n * When true, --power-browse was passed (or GH_ROUTER_ENABLE_POWER_BROWSE=1\n * is set). Exposes the FULL browser MCP surface (~18 tools) on /mcp,\n * including the L0/L1 primitives that hand DOM details (refs,\n * bboxes, role/name dumps) to the lead model. Default --browse mode\n * exposes only the 6 lead-model tools (act, observe, extract,\n * navigate, screenshot, open_tab). Always implies browseEnabled.\n */\n powerBrowseEnabled: boolean\n\n /**\n * Opt-in flag for ColBERT/colgrep semantic code search. Set by\n * `setupAndServe` from the `--search` CLI flag or\n * `GH_ROUTER_ENABLE_SEMANTIC_SEARCH=1` env var. When false, no colgrep\n * binary/model is provisioned, no workspace is indexed, and the `code`\n * MCP tool serves lexical results (with `lexical-fallback` source when\n * semantic mode was requested). See `semanticSearchOptedIn()` in\n * `src/lib/colbert/index.ts`; `GH_ROUTER_DISABLE_SEMANTIC_SEARCH=1`\n * hard-disables regardless of this flag.\n */\n searchEnabled: boolean\n\n /**\n * Opt-in flag for Bluebird Azure DevOps code search. Set by\n * `setupAndServe` from the `--bluebird` CLI flag or\n * `GH_ROUTER_ENABLE_BLUEBIRD=1` env var. When true, the `code` MCP\n * tool routes `semantic`/`lexical` modes through the Bluebird MCP\n * server. This flag is independent from `searchEnabled`, which controls\n * local ColBERT provisioning; `exact`/`regex`/`ast` stay local.\n * See `src/lib/bluebird-client.ts`.\n */\n bluebirdEnabled: boolean\n\n /** Last connected Bluebird client, retained only for compatibility and\n * diagnostics. Client selection is owned by the Bluebird runtime manager. */\n bluebirdClient: BluebirdMcpClient | null\n\n /** Resolved Bluebird scope (org/project/repos/branch), for logging and\n * the `x-mcp-ec-*` headers baked into the client. */\n bluebirdOrganization: string | null\n bluebirdProject: string | null\n bluebirdRepositories: Array<string>\n bluebirdBranch: string | null\n\n /**\n * Azure DevOps remote MCP group (`mcp__ado__*`). Enabled by `--ado`, by\n * `GH_ROUTER_ENABLE_ADO=1`, or automatically when the workspace's git\n * remotes resolve to an Azure DevOps repository. See\n * `src/lib/azure-mcp-flags.ts` for the precedence and the trust argument.\n */\n adoEnabled: boolean\n /** Organization whose `https://mcp.dev.azure.com/{org}` endpoint is used. */\n adoOrganization: string | null\n /**\n * `X-MCP-Toolsets` selection. The single entry `\"all\"` means \"send no\n * header\". Empty only while the group is off.\n */\n adoToolsets: Array<string>\n /**\n * Send `X-MCP-Readonly: true`. True unless `--ado-write` was passed. Never\n * cleared by discovery — a git remote can turn this group on but can never\n * widen it to writes.\n */\n adoReadOnly: boolean\n\n /**\n * Kusto (Azure Data Explorer) MCP group (`mcp__kusto__*`). Turned on by the\n * operator's `--kusto` flag, by a named cluster, or automatically when the\n * workspace's git remotes resolve to an Azure DevOps repository. Discovery\n * turns the GROUP on and never supplies a cluster: the model names one per\n * call, and the operator's own cluster access bounds the reach.\n */\n kustoEnabled: boolean\n /**\n * Default cluster for calls that do not name one, or null. Null no longer\n * turns the group off: every kusto tool takes its own `cluster`, so a launch\n * with no default still works, it just requires the argument.\n */\n kustoCluster: string | null\n kustoDatabase: string | null\n\n /**\n * Cloud Agent Job API v2 MCP group (`mcp__cloudagent__*`): hand work to a cloud\n * coding agent running against an Azure DevOps repository.\n *\n * Enabled by `--cloudagent`, by `GH_ROUTER_ENABLE_CLOUDAGENT=1`, or automatically\n * when the workspace's git remotes resolve to an Azure DevOps repository.\n * Discovery enables the whole group, write tools included, matching the ADO,\n * Kusto and Bluebird groups; `--no-cloudagent` remains the operator's veto.\n */\n cloudAgentEnabled: boolean\n /** `prod` or `ppe`, normalized by `resolveCloudAgentFlags()` at launch. */\n cloudAgentEnvironment: string\n\n /**\n * Work IQ MCP group (`mcp__workiq__*`): Microsoft 365 research through the\n * hosted Work IQ service.\n *\n * Off by default and never auto-enabled: the group needs a signed-in Work IQ\n * account, and turning it on without one would advertise an empty server.\n * Enabled by `--workiq` or `GH_ROUTER_ENABLE_WORKIQ=1`.\n *\n * `setupAndServe` clears it back to false when the launch-time provisioning\n * pass cannot reach the service or has no usable token, so the group is\n * advertised only when the snapshot behind it is real.\n */\n workiqEnabled: boolean\n /**\n * Exposes the four mutating Work IQ tools (`create_entity`, `update_entity`,\n * `delete_entity`, `do_action`). The default surface is the eight read-only\n * tools; `--workiq-write` widens the snapshot to whatever the live server\n * actually advertises.\n */\n workiqWriteEnabled: boolean\n\n /**\n * Humanlike pacing override:\n * \"on\" - --humanlike CLI flag or GH_ROUTER_HUMANLIKE=1 env;\n * inject Beta-distributed inter-action delays, Bezier\n * mouse paths, per-keystroke jitter, scroll chunking\n * into every browser_* action dispatch.\n * \"off\" - GH_ROUTER_BROWSER_NO_HUMANLIKE=1; HARD disable, wins\n * over \"on\" so tests are reproducible.\n * \"auto\" - default; pacing engages only when bot-challenge\n * detection fires (Phase 4-future).\n *\n * Lead model never sees this state — it's an internal concern.\n */\n humanlikeForce: \"on\" | \"off\" | \"auto\"\n\n // Rate limiting configuration\n rateLimitSeconds?: number\n lastRequestTimestamp?: number\n\n // Persistent session identifiers to match VS Code fingerprint\n sessionId: string\n machineId: string\n\n /**\n * Keyed per-launch registry for the loopback `/mcp` endpoint AND the\n * `/v1/messages` identity preflight. Set by the `claude` subcommand\n * (via `registerLaunch` in `./launch-registry`) after `setupAndServe`\n * and before spawning Claude Code; removed by the launch's own\n * cleanup. When empty, `/mcp` rejects all requests — closes the\n * loopback-no-auth gap (DNS rebinding, malicious browser-ext native\n * messaging, sibling-process probe) exactly as the old scalar nonce\n * did when unset.\n *\n * Multiple entries coexist for concurrent fast/standard launches (or a\n * launch plus a reconnect); each is looked up by its OWN nonce/secret,\n * so two launches' authenticated identities never cross.\n */\n launchRegistry: Map<string, LaunchRegistryEntry>\n\n /**\n * @deprecated Back-compat accessor over the registry's DEFAULT_LAUNCH_ID\n * entry (profileId \"standard\", unrestricted `allowedGroups`/\n * `allowedPersonas`) — defined below via `Object.defineProperty`, not a\n * real stored field. Reading returns that entry's nonce; writing creates\n * or updates it (or deletes it on `undefined`). Exists so single-launch\n * call sites and tests that already do `state.peerMcpNonce = NONCE`\n * keep working unmodified while `checkAuth` and the identity preflight\n * consult the real keyed registry underneath. New code should call\n * `registerLaunch` / `findLaunchByNonce` / `findLaunchBySecret` from\n * `./launch-registry` directly instead of reading/writing this field.\n */\n peerMcpNonce?: string\n\n /**\n * Set by `github-router serve` (a single machine-wide control plane serving\n * many repos). When true, repo-scoped worker tools require an explicit/So-derived\n * `workspace` and must NOT silently default to the proxy launch cwd.\n */\n serveMode?: boolean\n}\n\nexport const state: State = {\n accountType: \"enterprise\",\n copilotTokenGeneration: 0,\n manualApprove: false,\n rateLimitWait: false,\n showToken: false,\n extendedBetas: false,\n browseEnabled: false,\n fleetEnabled: false,\n agentsEnabled: false,\n powerBrowseEnabled: false,\n searchEnabled: false,\n bluebirdEnabled: false,\n bluebirdClient: null,\n bluebirdOrganization: null,\n bluebirdProject: null,\n bluebirdRepositories: [],\n bluebirdBranch: null,\n adoEnabled: false,\n adoOrganization: null,\n adoToolsets: [],\n adoReadOnly: true,\n kustoEnabled: false,\n kustoCluster: null,\n kustoDatabase: null,\n cloudAgentEnabled: false,\n cloudAgentEnvironment: \"prod\",\n workiqEnabled: false,\n workiqWriteEnabled: false,\n humanlikeForce: \"auto\",\n sessionId: randomUUID(),\n machineId: randomBytes(32).toString(\"hex\"),\n launchRegistry: new Map(),\n}\n\n// `peerMcpNonce` is not a plain data field — it's a live view onto\n// `state.launchRegistry.get(DEFAULT_LAUNCH_ID)`. Defined via\n// `Object.defineProperty` (rather than a class) so `state` stays the\n// plain object literal every existing importer already destructures /\n// mutates directly.\nObject.defineProperty(state, \"peerMcpNonce\", {\n enumerable: true,\n configurable: true,\n get(): string | undefined {\n return state.launchRegistry.get(DEFAULT_LAUNCH_ID)?.nonce\n },\n set(value: string | undefined) {\n if (value === undefined) {\n state.launchRegistry.delete(DEFAULT_LAUNCH_ID)\n return\n }\n const existing = state.launchRegistry.get(DEFAULT_LAUNCH_ID)\n state.launchRegistry.set(DEFAULT_LAUNCH_ID, {\n launchId: DEFAULT_LAUNCH_ID,\n nonce: value,\n // A caller that only ever touches `peerMcpNonce` exposes MCP only and has\n // no Messages identity secret.\n // Never reuse the MCP bearer across surfaces: an empty secret cannot match\n // any non-empty custom header, while registered Claude launches always use\n // `registerLaunch` with independently generated credentials.\n secret: existing?.secret ?? \"\",\n profileId: existing?.profileId ?? \"standard\",\n allowedGroups: existing?.allowedGroups,\n allowedPersonas: existing?.allowedPersonas,\n createdAt: existing?.createdAt ?? Date.now(),\n })\n },\n})\n"],"mappings":";;;;;;;AAkEA,MAAM,oBAAoB;AAkS1B,MAAa,QAAe;CAC1B,aAAa;CACb,wBAAwB;CACxB,eAAe;CACf,eAAe;CACf,WAAW;CACX,eAAe;CACf,eAAe;CACf,cAAc;CACd,eAAe;CACf,oBAAoB;CACpB,eAAe;CACf,iBAAiB;CACjB,gBAAgB;CAChB,sBAAsB;CACtB,iBAAiB;CACjB,sBAAsB,CAAC;CACvB,gBAAgB;CAChB,YAAY;CACZ,iBAAiB;CACjB,aAAa,CAAC;CACd,aAAa;CACb,cAAc;CACd,cAAc;CACd,eAAe;CACf,mBAAmB;CACnB,uBAAuB;CACvB,eAAe;CACf,oBAAoB;CACpB,gBAAgB;CAChB,WAAW,WAAW;CACtB,WAAW,YAAY,EAAE,CAAC,CAAC,SAAS,KAAK;CACzC,gCAAgB,IAAI,IAAI;AAC1B;AAOA,OAAO,eAAe,OAAO,gBAAgB;CAC3C,YAAY;CACZ,cAAc;CACd,MAA0B;EACxB,OAAO,MAAM,eAAe,IAAI,iBAAiB,CAAC,EAAE;CACtD;CACA,IAAI,OAA2B;EAC7B,IAAI,UAAU,KAAA,GAAW;GACvB,MAAM,eAAe,OAAO,iBAAiB;GAC7C;EACF;EACA,MAAM,WAAW,MAAM,eAAe,IAAI,iBAAiB;EAC3D,MAAM,eAAe,IAAI,mBAAmB;GAC1C,UAAU;GACV,OAAO;GAMP,QAAQ,UAAU,UAAU;GAC5B,WAAW,UAAU,aAAa;GAClC,eAAe,UAAU;GACzB,iBAAiB,UAAU;GAC3B,WAAW,UAAU,aAAa,KAAK,IAAI;EAC7C,CAAC;CACH;AACF,CAAC"}
@@ -0,0 +1,480 @@
1
+ import { t as PATHS } from "./paths-C5477RGC.js";
2
+ import { a as writeTokenFileAtomic, g as credentialFingerprint } from "./token-Dqjs5ixP.js";
3
+ import consola from "consola";
4
+ import path from "node:path";
5
+ import { createHash, randomBytes } from "node:crypto";
6
+ import fs from "node:fs/promises";
7
+ import process from "node:process";
8
+ import { spawn } from "node:child_process";
9
+ import http from "node:http";
10
+ const WORKIQ_MCP_URL = `https://workiq.svc.cloud.microsoft/mcp`;
11
+ /**
12
+ * Scopes requested in one string. `.default` is what yields the delegated
13
+ * `WorkIQ.Act WorkIQ.Read WorkIQAgent.Ask` set on the access token; `openid
14
+ * profile` give us the `id_token` we read the account name from; and
15
+ * `offline_access` is what makes Entra issue the refresh token the durable
16
+ * login depends on.
17
+ */
18
+ const WORKIQ_SCOPE = `api://workiq.svc.cloud.microsoft/.default openid profile offline_access`;
19
+ /** Public native client id (no secret). See the module comment. */
20
+ const WORKIQ_PUBLIC_CLIENT_ID = "ba081686-5d24-4bc6-a0d6-d034ecffed87";
21
+ /**
22
+ * MCP protocol version. The live server answers `2025-06-18`, the same
23
+ * version the Azure groups use.
24
+ */
25
+ const WORKIQ_PROTOCOL_VERSION = "2025-06-18";
26
+ /**
27
+ * Raw bearer override for tests and manual runs. It skips both the token file
28
+ * and the refresh path entirely.
29
+ */
30
+ const WORKIQ_TOKEN_ENV = "WORKIQ_MCP_TOKEN";
31
+ /**
32
+ * The eight tools that only read M365 data, keyed by the exact names the live
33
+ * server advertises (`tools/list` on 2026-11-02 listed exactly twelve).
34
+ *
35
+ * `call_function` is here because the server's own description defines it as a
36
+ * read-only Work IQ function call (Graph functions use GET). The four mutating
37
+ * tools are in `WORKIQ_WRITE_TOOLS`.
38
+ */
39
+ const WORKIQ_READ_TOOLS = /* @__PURE__ */ new Set([
40
+ "ask",
41
+ "retrieve",
42
+ "fetch",
43
+ "fetch_blob",
44
+ "list_agents",
45
+ "get_schema",
46
+ "search_paths",
47
+ "call_function"
48
+ ]);
49
+ /** The four tools that change M365 state. Exposed only with `--workiq-write`. */
50
+ const WORKIQ_WRITE_TOOLS = /* @__PURE__ */ new Set([
51
+ "create_entity",
52
+ "update_entity",
53
+ "delete_entity",
54
+ "do_action"
55
+ ]);
56
+ /**
57
+ * Structured-content key carrying the authoritative `retrieve` payload. The
58
+ * same shape is documented for the hosted service; `markdown` is the rendered
59
+ * answer and `retrievalHits` the citation set.
60
+ */
61
+ const WORKIQ_RETRIEVAL_CONTENT_TYPE = "application/vnd.ms-workiq.retrieval";
62
+ /** `expires_in` fallback when Entra omits it (it normally does not). */
63
+ const DEFAULT_EXPIRES_IN_S = 3600;
64
+ /** How long `workiq auth` waits for the browser before giving up. */
65
+ const DEFAULT_AUTH_TIMEOUT_MS = 3e5;
66
+ const LOGIN_BASE = "https://login.microsoftonline.com";
67
+ /**
68
+ * A failed sign-in or refresh.
69
+ *
70
+ * `remedy` is the actionable one-liner the CLI and the launch provisioning
71
+ * path print. It always names the command that fixes the state, because every
72
+ * terminal error here has exactly one fix.
73
+ */
74
+ var WorkiqAuthError = class extends Error {
75
+ remedy;
76
+ /** Entra's error code (`invalid_grant`, `interaction_required`, …). */
77
+ errorCode;
78
+ constructor(message, opts = {}) {
79
+ super(message);
80
+ this.name = "WorkiqAuthError";
81
+ this.errorCode = opts.errorCode;
82
+ this.remedy = opts.remedy ?? "Run `github-router workiq auth`.";
83
+ }
84
+ };
85
+ const AUTH_REMEDY = "Run `github-router workiq auth`.";
86
+ /** Resolved tenant segment: `GH_ROUTER_WORKIQ_TENANT` over the default. */
87
+ function workiqTenant() {
88
+ return process.env["GH_ROUTER_WORKIQ_TENANT"]?.trim() || "organizations";
89
+ }
90
+ /** Resolved token file path: `GH_ROUTER_WORKIQ_TOKEN_PATH` over APP_DIR. */
91
+ function workiqTokenPath() {
92
+ return process.env["GH_ROUTER_WORKIQ_TOKEN_PATH"]?.trim() || path.join(PATHS.APP_DIR, "workiq-token.json");
93
+ }
94
+ function isRecord(value) {
95
+ return typeof value === "object" && value !== null && !Array.isArray(value);
96
+ }
97
+ function isFiniteNumber(value) {
98
+ return typeof value === "number" && Number.isFinite(value);
99
+ }
100
+ /**
101
+ * Parse the token file leniently about extra fields and strictly about the
102
+ * ones the refresh grant needs. A file that fails this is treated as absent,
103
+ * which routes the caller to the `workiq auth` remedy rather than to a
104
+ * confusing `invalid_request` from Entra.
105
+ */
106
+ function parseTokenFile(raw) {
107
+ let parsed;
108
+ try {
109
+ parsed = JSON.parse(raw);
110
+ } catch {
111
+ return null;
112
+ }
113
+ if (!isRecord(parsed)) return null;
114
+ if (typeof parsed.accessToken !== "string" || !parsed.accessToken) return null;
115
+ if (typeof parsed.refreshToken !== "string" || !parsed.refreshToken) return null;
116
+ if (!isFiniteNumber(parsed.expiresAtMs)) return null;
117
+ return {
118
+ version: 1,
119
+ clientId: typeof parsed.clientId === "string" ? parsed.clientId : WORKIQ_PUBLIC_CLIENT_ID,
120
+ tenant: typeof parsed.tenant === "string" ? parsed.tenant : workiqTenant(),
121
+ scope: typeof parsed.scope === "string" ? parsed.scope : WORKIQ_SCOPE,
122
+ accessToken: parsed.accessToken,
123
+ refreshToken: parsed.refreshToken,
124
+ expiresAtMs: parsed.expiresAtMs,
125
+ ...typeof parsed.account === "string" ? { account: parsed.account } : {}
126
+ };
127
+ }
128
+ /** Read the token file, or null when it is absent or unreadable. */
129
+ async function readWorkiqTokenFile(filePath = workiqTokenPath()) {
130
+ let raw;
131
+ try {
132
+ raw = await fs.readFile(filePath, "utf8");
133
+ } catch {
134
+ return null;
135
+ }
136
+ return parseTokenFile(raw);
137
+ }
138
+ /** Persist the token file atomically (0600, temp + rename). */
139
+ async function writeWorkiqTokenFile(file, filePath = workiqTokenPath()) {
140
+ await fs.mkdir(path.dirname(filePath), { recursive: true }).catch(() => {});
141
+ await writeTokenFileAtomic(filePath, `${JSON.stringify(file, null, 2)}\n`);
142
+ }
143
+ /** Delete the durable login. `workiq logout`. */
144
+ async function deleteWorkiqTokenFile(filePath = workiqTokenPath()) {
145
+ try {
146
+ await fs.unlink(filePath);
147
+ return true;
148
+ } catch (err) {
149
+ if (err.code === "ENOENT") return false;
150
+ throw err;
151
+ }
152
+ }
153
+ /** A fresh PKCE S256 verifier/challenge pair. */
154
+ function createWorkiqPkce() {
155
+ const verifier = randomBytes(32).toString("base64url");
156
+ return {
157
+ verifier,
158
+ challenge: createHash("sha256").update(verifier).digest("base64url")
159
+ };
160
+ }
161
+ /** The authorize URL. Pure, so the shape is pinned by a unit test. */
162
+ function buildWorkiqAuthorizeUrl(opts) {
163
+ const url = new URL(`${LOGIN_BASE}/${encodeURIComponent(opts.tenant)}/oauth2/v2.0/authorize`);
164
+ url.searchParams.set("client_id", opts.clientId ?? "ba081686-5d24-4bc6-a0d6-d034ecffed87");
165
+ url.searchParams.set("response_type", "code");
166
+ url.searchParams.set("response_mode", "query");
167
+ url.searchParams.set("redirect_uri", opts.redirectUri);
168
+ url.searchParams.set("scope", WORKIQ_SCOPE);
169
+ url.searchParams.set("code_challenge", opts.codeChallenge);
170
+ url.searchParams.set("code_challenge_method", "S256");
171
+ url.searchParams.set("state", opts.state);
172
+ if (opts.loginHint) url.searchParams.set("login_hint", opts.loginHint);
173
+ return url.toString();
174
+ }
175
+ /** Decode a JWT payload without verifying it. Display-only. */
176
+ function decodeIdTokenPayload(idToken) {
177
+ if (!idToken) return null;
178
+ const parts = idToken.split(".");
179
+ if (parts.length < 2) return null;
180
+ try {
181
+ const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
182
+ return isRecord(payload) ? payload : null;
183
+ } catch {
184
+ return null;
185
+ }
186
+ }
187
+ function accountFromIdToken(idToken) {
188
+ const payload = decodeIdTokenPayload(idToken);
189
+ if (!payload) return void 0;
190
+ for (const key of [
191
+ "preferred_username",
192
+ "upn",
193
+ "unique_name",
194
+ "email",
195
+ "name"
196
+ ]) {
197
+ const value = payload[key];
198
+ if (typeof value === "string" && value.trim()) return value.trim();
199
+ }
200
+ }
201
+ function describeEndpointFailure(status, body) {
202
+ const code = typeof body?.error === "string" ? body.error : void 0;
203
+ const description = typeof body?.error_description === "string" && body.error_description.trim() ? body.error_description.trim() : void 0;
204
+ const head = code ? `Work IQ sign-in failed (${code})` : `Work IQ sign-in failed (HTTP ${status})`;
205
+ return new WorkiqAuthError(description ? `${head}: ${description}` : head, { errorCode: code });
206
+ }
207
+ async function postTokenEndpoint(tenant, form, signal) {
208
+ const res = await fetch(`${LOGIN_BASE}/${encodeURIComponent(tenant)}/oauth2/v2.0/token`, {
209
+ method: "POST",
210
+ headers: {
211
+ "Content-Type": "application/x-www-form-urlencoded",
212
+ Accept: "application/json"
213
+ },
214
+ body: new URLSearchParams(form).toString(),
215
+ ...signal ? { signal } : {}
216
+ });
217
+ let body;
218
+ try {
219
+ const parsed = await res.json();
220
+ body = isRecord(parsed) ? parsed : null;
221
+ } catch {
222
+ body = null;
223
+ }
224
+ if (!res.ok) throw describeEndpointFailure(res.status, body);
225
+ if (!body) throw new WorkiqAuthError("Work IQ sign-in failed: the token endpoint returned no JSON.");
226
+ return body;
227
+ }
228
+ /**
229
+ * Turn a token endpoint response into the durable file shape.
230
+ *
231
+ * `expires_in` is treated as a DURATION from now; a missing or malformed value
232
+ * falls back to an hour, which only makes the next refresh later than it could
233
+ * have been, never earlier than the token's real expiry in the common case.
234
+ */
235
+ function tokenFileFromResponse(body, context) {
236
+ const accessToken = typeof body.access_token === "string" ? body.access_token : "";
237
+ if (!accessToken) throw new WorkiqAuthError("Work IQ sign-in failed: the token endpoint returned no access token.");
238
+ const refreshToken = typeof body.refresh_token === "string" && body.refresh_token ? body.refresh_token : context.previous?.refreshToken ?? "";
239
+ if (!refreshToken) throw new WorkiqAuthError("Work IQ sign-in failed: the token endpoint returned no refresh token, so the login would not survive this process.", { remedy: AUTH_REMEDY });
240
+ const expiresInRaw = typeof body.expires_in === "string" ? Number(body.expires_in) : body.expires_in;
241
+ const expiresIn = isFiniteNumber(expiresInRaw) && expiresInRaw > 0 ? expiresInRaw : DEFAULT_EXPIRES_IN_S;
242
+ const account = accountFromIdToken(typeof body.id_token === "string" ? body.id_token : void 0) ?? context.previous?.account;
243
+ return {
244
+ version: 1,
245
+ clientId: WORKIQ_PUBLIC_CLIENT_ID,
246
+ tenant: context.tenant,
247
+ scope: WORKIQ_SCOPE,
248
+ accessToken,
249
+ refreshToken,
250
+ expiresAtMs: Date.now() + expiresIn * 1e3,
251
+ ...account ? { account } : {}
252
+ };
253
+ }
254
+ /**
255
+ * Exchange a refresh token. Rotates and persists the new refresh token before
256
+ * returning, so a crash after a successful grant cannot lose the only valid
257
+ * token (the old one is already consumed upstream).
258
+ */
259
+ async function exchangeRefreshToken(file, refreshToken, signal) {
260
+ const next = tokenFileFromResponse(await postTokenEndpoint(file.tenant, {
261
+ client_id: file.clientId || "ba081686-5d24-4bc6-a0d6-d034ecffed87",
262
+ grant_type: "refresh_token",
263
+ scope: file.scope || "api://workiq.svc.cloud.microsoft/.default openid profile offline_access",
264
+ refresh_token: refreshToken
265
+ }, signal), {
266
+ tenant: file.tenant,
267
+ previous: file
268
+ });
269
+ await writeWorkiqTokenFile(next);
270
+ cached = next;
271
+ consola.debug(`Work IQ: refreshed the access token (fingerprint ${credentialFingerprint(next.accessToken)}).`);
272
+ return next;
273
+ }
274
+ /**
275
+ * Refresh an access token through the refresh grant, retrying once on
276
+ * `invalid_grant` after re-reading the file. Exported for the CLI's `status`
277
+ * path and for tests.
278
+ */
279
+ async function refreshWorkiqAccessToken(file, signal) {
280
+ try {
281
+ return await exchangeRefreshToken(file, file.refreshToken, signal);
282
+ } catch (err) {
283
+ if (!(err instanceof WorkiqAuthError) || err.errorCode !== "invalid_grant") throw err;
284
+ const disk = await readWorkiqTokenFile();
285
+ if (disk && disk.refreshToken !== file.refreshToken) {
286
+ consola.info("Work IQ: the token file was rotated by another process; retrying with the newest refresh token.");
287
+ return await exchangeRefreshToken(disk, disk.refreshToken, signal);
288
+ }
289
+ throw err;
290
+ }
291
+ }
292
+ let cached = null;
293
+ let inflight = null;
294
+ function throwIfAborted(signal) {
295
+ if (signal?.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("aborted");
296
+ }
297
+ async function refreshPath(opts) {
298
+ throwIfAborted(opts.signal);
299
+ const file = cached ?? await readWorkiqTokenFile();
300
+ if (!file) throw new WorkiqAuthError(`No Work IQ login found at ${workiqTokenPath()}.`, { remedy: AUTH_REMEDY });
301
+ cached = file;
302
+ if (!opts.forceRefresh && file.expiresAtMs - 3e5 > Date.now()) return file.accessToken;
303
+ const next = await refreshWorkiqAccessToken(file, opts.signal);
304
+ throwIfAborted(opts.signal);
305
+ return next.accessToken;
306
+ }
307
+ /**
308
+ * The bearer the MCP client sends. Reads, in order:
309
+ *
310
+ * 1. `WORKIQ_MCP_TOKEN` (tests / manual runs) — nothing else runs.
311
+ * 2. The in-memory token, if it is still comfortably unexpired.
312
+ * 3. The durable file, refreshing first when it is inside the skew window or
313
+ * `forceRefresh` is set (the 401 path).
314
+ *
315
+ * Concurrent callers share ONE refresh. The guard and its assignment are
316
+ * deliberately adjacent (no `await` between them): anything awaited in between
317
+ * would yield the event loop and let a second caller past the guard.
318
+ */
319
+ function ensureWorkiqToken(opts = {}) {
320
+ const env = process.env[WORKIQ_TOKEN_ENV]?.trim();
321
+ if (env) return Promise.resolve(env);
322
+ if (!opts.forceRefresh && cached && cached.expiresAtMs - 3e5 > Date.now()) return Promise.resolve(cached.accessToken);
323
+ if (inflight) return attachSignal(inflight, opts.signal);
324
+ const promise = refreshPath(opts);
325
+ inflight = promise;
326
+ promise.finally(() => {
327
+ if (inflight === promise) inflight = null;
328
+ }).catch(() => {});
329
+ return promise;
330
+ }
331
+ /**
332
+ * Wait for a shared refresh but let the CALLER's signal abandon the wait.
333
+ *
334
+ * The shared promise itself must keep running: another caller may still need
335
+ * it, and the refresh rotates the refresh token, so abandoning it midway would
336
+ * waste the one grant. `race` only stops this caller from waiting.
337
+ */
338
+ function attachSignal(promise, signal) {
339
+ if (!signal) return promise;
340
+ if (signal.aborted) return Promise.reject(signal.reason ?? /* @__PURE__ */ new Error("aborted"));
341
+ return new Promise((resolve, reject) => {
342
+ const onAbort = () => reject(signal.reason ?? /* @__PURE__ */ new Error("aborted"));
343
+ signal.addEventListener("abort", onAbort, { once: true });
344
+ promise.then((value) => {
345
+ signal.removeEventListener("abort", onAbort);
346
+ resolve(value);
347
+ }, (err) => {
348
+ signal.removeEventListener("abort", onAbort);
349
+ reject(err);
350
+ });
351
+ });
352
+ }
353
+ /**
354
+ * Open the default browser. Best effort by contract: the caller always prints
355
+ * the URL too, so a headless or locked-down machine is a paste, not a failure.
356
+ */
357
+ function openWorkiqBrowser(url) {
358
+ try {
359
+ if (process.platform === "win32") {
360
+ spawn("rundll32.exe", ["url.dll,FileProtocolHandler", url], {
361
+ stdio: "ignore",
362
+ detached: true
363
+ }).unref();
364
+ return;
365
+ }
366
+ const command = process.platform === "darwin" ? "open" : "xdg-open";
367
+ spawn(command, [url], {
368
+ stdio: "ignore",
369
+ detached: true
370
+ }).unref();
371
+ } catch {}
372
+ }
373
+ /** The page shown after the browser round-trips. Plain, self-contained HTML. */
374
+ function resultPage(title, detail) {
375
+ const escape = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
376
+ return `<!doctype html><html><head><meta charset="utf-8"><title>${escape(title)}</title><style>body{font:16px/1.5 system-ui,sans-serif;margin:4rem auto;max-width:32rem;padding:0 1.5rem}</style></head><body><h1>${escape(title)}</h1><p>${escape(detail)}</p></body></html>`;
377
+ }
378
+ /**
379
+ * Run the interactive sign-in and persist the result.
380
+ *
381
+ * The listener binds with `listen(0)` and no host, which is dual-stack: a
382
+ * browser that resolves `localhost` to `::1` must reach it, and binding
383
+ * `127.0.0.1` would silently leave that connection refused. Entra accepts any
384
+ * port on a `http://localhost` loopback redirect.
385
+ */
386
+ async function runLoopbackAuth(opts = {}) {
387
+ const tenant = opts.tenant ?? workiqTenant();
388
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_AUTH_TIMEOUT_MS;
389
+ const { verifier, challenge } = createWorkiqPkce();
390
+ const expectedState = randomBytes(24).toString("base64url");
391
+ let settle = null;
392
+ const codePromise = new Promise((resolve, reject) => {
393
+ settle = {
394
+ resolve,
395
+ reject
396
+ };
397
+ });
398
+ const server = http.createServer((req, res) => {
399
+ const params = new URL(req.url ?? "/", "http://localhost").searchParams;
400
+ const respond = (status, title, detail) => {
401
+ res.statusCode = status;
402
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
403
+ res.end(resultPage(title, detail));
404
+ };
405
+ if (params.get("state") !== expectedState) {
406
+ respond(400, "Unexpected sign-in response", "The state value did not match this sign-in attempt.");
407
+ return;
408
+ }
409
+ const error = params.get("error");
410
+ if (error) {
411
+ const description = params.get("error_description") ?? "";
412
+ respond(400, "Work IQ sign-in failed", description || error);
413
+ settle?.reject(new WorkiqAuthError(description ? `Work IQ sign-in failed (${error}): ${description}` : `Work IQ sign-in failed (${error}).`, { errorCode: error }));
414
+ settle = null;
415
+ return;
416
+ }
417
+ const code = params.get("code");
418
+ if (!code) {
419
+ respond(400, "Work IQ sign-in failed", "The redirect carried no authorization code.");
420
+ return;
421
+ }
422
+ respond(200, "Work IQ sign-in complete", "You can close this window and return to the terminal.");
423
+ settle?.resolve(code);
424
+ settle = null;
425
+ });
426
+ const redirectUri = `http://localhost:${await new Promise((resolve, reject) => {
427
+ server.once("error", reject);
428
+ server.listen(0, () => {
429
+ const address = server.address();
430
+ if (address && typeof address === "object") resolve(address.port);
431
+ else reject(new WorkiqAuthError("Could not determine the sign-in listener port."));
432
+ });
433
+ })}/`;
434
+ const authorizeUrl = buildWorkiqAuthorizeUrl({
435
+ tenant,
436
+ redirectUri,
437
+ codeChallenge: challenge,
438
+ state: expectedState,
439
+ ...opts.loginHint ? { loginHint: opts.loginHint } : {}
440
+ });
441
+ consola.info("Opening the browser to sign in to Work IQ. If it does not open, visit:");
442
+ consola.info(authorizeUrl);
443
+ opts.onAuthorizeUrl?.(authorizeUrl);
444
+ (opts.openBrowser ?? openWorkiqBrowser)(authorizeUrl);
445
+ const timeout = setTimeout(() => {
446
+ settle?.reject(new WorkiqAuthError(`Work IQ sign-in did not complete within ${Math.round(timeoutMs / 6e4)} minutes.`));
447
+ settle = null;
448
+ }, timeoutMs);
449
+ timeout.unref?.();
450
+ const onAbort = () => {
451
+ settle?.reject(opts.signal?.reason ?? /* @__PURE__ */ new Error("aborted"));
452
+ settle = null;
453
+ };
454
+ opts.signal?.addEventListener("abort", onAbort, { once: true });
455
+ let code;
456
+ try {
457
+ code = await codePromise;
458
+ } finally {
459
+ clearTimeout(timeout);
460
+ opts.signal?.removeEventListener("abort", onAbort);
461
+ server.close();
462
+ server.closeAllConnections?.();
463
+ }
464
+ const file = tokenFileFromResponse(await postTokenEndpoint(tenant, {
465
+ client_id: WORKIQ_PUBLIC_CLIENT_ID,
466
+ grant_type: "authorization_code",
467
+ code,
468
+ redirect_uri: redirectUri,
469
+ code_verifier: verifier,
470
+ scope: WORKIQ_SCOPE
471
+ }, opts.signal), { tenant });
472
+ await writeWorkiqTokenFile(file);
473
+ cached = file;
474
+ consola.success(`Work IQ: signed in${file.account ? ` as ${file.account}` : ""} (token fingerprint ${credentialFingerprint(file.accessToken)}).`);
475
+ return file;
476
+ }
477
+ //#endregion
478
+ export { readWorkiqTokenFile as a, workiqTokenPath as c, WORKIQ_READ_TOOLS as d, WORKIQ_RETRIEVAL_CONTENT_TYPE as f, ensureWorkiqToken as i, WORKIQ_MCP_URL as l, WORKIQ_WRITE_TOOLS as m, WorkiqAuthError as n, runLoopbackAuth as o, WORKIQ_TOKEN_ENV as p, deleteWorkiqTokenFile as r, workiqTenant as s, AUTH_REMEDY as t, WORKIQ_PROTOCOL_VERSION as u };
479
+
480
+ //# sourceMappingURL=token-CVG0yI_j.js.map