github-router 0.3.373 → 0.3.375

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 (152) hide show
  1. package/dist/ado-tools-BOW1k1KW.js +1 -0
  2. package/dist/{aic-ledger-Cp7Yk9-Q.js → aic-ledger-CeSXqTEE.js} +5 -7
  3. package/dist/{aic-ledger-Cp7Yk9-Q.js.map → aic-ledger-CeSXqTEE.js.map} +1 -1
  4. package/dist/{aic-statusline-settings-B5EMMSFC.js → aic-statusline-settings-BKveu679.js} +3 -4
  5. package/dist/{aic-statusline-settings-B5EMMSFC.js.map → aic-statusline-settings-BKveu679.js.map} +1 -1
  6. package/dist/{attribution-settings-DZ8fEfvP.js → attribution-settings-Cs6CsXK3.js} +33 -53
  7. package/dist/{attribution-settings-DZ8fEfvP.js.map → attribution-settings-Cs6CsXK3.js.map} +1 -1
  8. package/dist/{auth-B1egtvt4.js → auth-BZHpTtfF.js} +5 -6
  9. package/dist/{auth-B1egtvt4.js.map → auth-BZHpTtfF.js.map} +1 -1
  10. package/dist/{balanced-profile-contract-Dm_usmw7.js → balanced-profile-contract-B6pSoWjm.js} +2 -3
  11. package/dist/{balanced-profile-contract-Dm_usmw7.js.map → balanced-profile-contract-B6pSoWjm.js.map} +1 -1
  12. package/dist/{bluebird-client-ByCRusGQ.js → bluebird-client-BasIdv5J.js} +8 -12
  13. package/dist/{bluebird-client-ByCRusGQ.js.map → bluebird-client-BasIdv5J.js.map} +1 -1
  14. package/dist/{bluebird-client-CY6NBHQu.js → bluebird-client-BvoMTmEv.js} +1 -1
  15. package/dist/browser-bridge/index.js +84 -55
  16. package/dist/browser-ext/manifest.json +1 -1
  17. package/dist/{check-usage-T_z84Pgc.js → check-usage-BlIWDuV2.js} +5 -6
  18. package/dist/{check-usage-T_z84Pgc.js.map → check-usage-BlIWDuV2.js.map} +1 -1
  19. package/dist/{claude-8ksmV0dC.js → claude-Q1yfHGGE.js} +37 -43
  20. package/dist/{claude-8ksmV0dC.js.map → claude-Q1yfHGGE.js.map} +1 -1
  21. package/dist/{claude-md-injection-BnzVv_aB.js → claude-md-injection-DU5KYXNc.js} +6 -7
  22. package/dist/{claude-md-injection-BnzVv_aB.js.map → claude-md-injection-DU5KYXNc.js.map} +1 -1
  23. package/dist/{client-CQMfroGV.js → client-Bjp3XAMK.js} +3 -5
  24. package/dist/{client-CQMfroGV.js.map → client-Bjp3XAMK.js.map} +1 -1
  25. package/dist/{codex-C89FoaaG.js → codex-BuOUR6lB.js} +10 -11
  26. package/dist/{codex-C89FoaaG.js.map → codex-BuOUR6lB.js.map} +1 -1
  27. package/dist/{copilot-discount-T-cfWmc4.js → copilot-discount-CHNQLYDJ.js} +3 -4
  28. package/dist/{copilot-discount-T-cfWmc4.js.map → copilot-discount-CHNQLYDJ.js.map} +1 -1
  29. package/dist/{debug-DL2JsRqY.js → debug-1HUHCWFl.js} +3 -4
  30. package/dist/{debug-DL2JsRqY.js.map → debug-1HUHCWFl.js.map} +1 -1
  31. package/dist/engine-BC4TF4pt.js +1 -0
  32. package/dist/{exec-Bf8g_bIR.js → exec-BC0MAnoA.js} +2 -3
  33. package/dist/{exec-Bf8g_bIR.js.map → exec-BC0MAnoA.js.map} +1 -1
  34. package/dist/{fast-profile-contract-JOnZBgFB.js → fast-profile-contract-BLnKg0Ay.js} +2 -3
  35. package/dist/{fast-profile-contract-JOnZBgFB.js.map → fast-profile-contract-BLnKg0Ay.js.map} +1 -1
  36. package/dist/{gate-discovery-Bc9FdRwg.js → gate-discovery-DiXu_olc.js} +8 -10
  37. package/dist/{gate-discovery-Bc9FdRwg.js.map → gate-discovery-DiXu_olc.js.map} +1 -1
  38. package/dist/{get-copilot-usage-BSXeQEx8.js → get-copilot-usage-CKg42gSH.js} +5 -6
  39. package/dist/{get-copilot-usage-BSXeQEx8.js.map → get-copilot-usage-CKg42gSH.js.map} +1 -1
  40. package/dist/{hook-mcp-client-DERIkeR7.js → hook-mcp-client-CYx10nlU.js} +2 -3
  41. package/dist/hook-mcp-client-CYx10nlU.js.map +1 -0
  42. package/dist/hooks.mjs +1766 -1548
  43. package/dist/hooks.sha256 +1 -1
  44. package/dist/{index-cmd-DOhwt92u.js → index-cmd-BPXhTfGQ.js} +8 -9
  45. package/dist/index-cmd-BPXhTfGQ.js.map +1 -0
  46. package/dist/{internal-aic-status-CY0QxSa7.js → internal-aic-status-FQB1DQzX.js} +6 -8
  47. package/dist/{internal-aic-status-CY0QxSa7.js.map → internal-aic-status-FQB1DQzX.js.map} +1 -1
  48. package/dist/{internal-artifact-open-NAGn9Mgt.js → internal-artifact-open-DbHjipxU.js} +5 -7
  49. package/dist/{internal-artifact-open-NAGn9Mgt.js.map → internal-artifact-open-DbHjipxU.js.map} +1 -1
  50. package/dist/{internal-fast-dispatch-guard-De_DJOyZ.js → internal-fast-dispatch-guard-DMzqs-r8.js} +1 -1
  51. package/dist/{internal-fast-dispatch-guard-_n-A8hgo.js → internal-fast-dispatch-guard-PDdlkPU3.js} +6 -8
  52. package/dist/{internal-fast-dispatch-guard-_n-A8hgo.js.map → internal-fast-dispatch-guard-PDdlkPU3.js.map} +1 -1
  53. package/dist/{internal-first-mate-guard-GufCUMl3.js → internal-first-mate-guard-4Yro9xNM.js} +5 -7
  54. package/dist/{internal-first-mate-guard-GufCUMl3.js.map → internal-first-mate-guard-4Yro9xNM.js.map} +1 -1
  55. package/dist/{internal-first-mate-guard-C8GwLbaX.js → internal-first-mate-guard-BxPDUsV3.js} +1 -1
  56. package/dist/{internal-max-dispatch-guard-4rh6KSd8.js → internal-max-dispatch-guard-D3L00YXj.js} +5 -7
  57. package/dist/{internal-max-dispatch-guard-4rh6KSd8.js.map → internal-max-dispatch-guard-D3L00YXj.js.map} +1 -1
  58. package/dist/{internal-max-dispatch-guard-CKnzgJje.js → internal-max-dispatch-guard-fhBX_w49.js} +1 -1
  59. package/dist/{internal-plan-review-ChFx8wTX.js → internal-plan-review-BfHLeszV.js} +6 -7
  60. package/dist/{internal-plan-review-ChFx8wTX.js.map → internal-plan-review-BfHLeszV.js.map} +1 -1
  61. package/dist/{internal-prompt-submit-BW5g3MjD.js → internal-prompt-submit-BbnaMF2R.js} +7 -8
  62. package/dist/{internal-prompt-submit-BW5g3MjD.js.map → internal-prompt-submit-BbnaMF2R.js.map} +1 -1
  63. package/dist/{internal-prompt-submit-C4uDwr7G.js → internal-prompt-submit-DKzCckz-.js} +2 -2
  64. package/dist/{internal-rebrief-DvBS8myn.js → internal-rebrief-aEvxp7jw.js} +7 -9
  65. package/dist/{internal-rebrief-DvBS8myn.js.map → internal-rebrief-aEvxp7jw.js.map} +1 -1
  66. package/dist/{internal-session-bind-dsUOcKxU.js → internal-session-bind-pN1V11Mn.js} +3 -4
  67. package/dist/{internal-session-bind-dsUOcKxU.js.map → internal-session-bind-pN1V11Mn.js.map} +1 -1
  68. package/dist/{internal-stop-hook-nS91Jkda.js → internal-stop-hook-VQuOYpUC.js} +9 -10
  69. package/dist/{internal-stop-hook-nS91Jkda.js.map → internal-stop-hook-VQuOYpUC.js.map} +1 -1
  70. package/dist/{internal-stop-review-D_KEV_04.js → internal-stop-review-BWp-4XWW.js} +4 -5
  71. package/dist/{internal-stop-review-D_KEV_04.js.map → internal-stop-review-BWp-4XWW.js.map} +1 -1
  72. package/dist/{internal-worker-guard-DB6shBIn.js → internal-worker-guard-C9OZPgzu.js} +3 -4
  73. package/dist/{internal-worker-guard-DB6shBIn.js.map → internal-worker-guard-C9OZPgzu.js.map} +1 -1
  74. package/dist/{internal-workspace-header-DBg5Y7oN.js → internal-workspace-header-B4TXFBLU.js} +3 -4
  75. package/dist/{internal-workspace-header-DBg5Y7oN.js.map → internal-workspace-header-B4TXFBLU.js.map} +1 -1
  76. package/dist/lib/tree-sitter-pool/{lifecycle-Dx0SnP7Z.js → lifecycle-BPpOigPZ.js} +1 -2
  77. package/dist/lib/tree-sitter-pool/{lifecycle-C7W8D2lx.js → lifecycle-C3vsqXjS.js} +1 -3
  78. package/dist/lib/tree-sitter-pool/worker.js +29 -35
  79. package/dist/lifecycle-BENRuuX6.js +1 -0
  80. package/dist/{lifecycle-K9oVtGde.mjs → lifecycle-DBKu1T5r.mjs} +0 -1
  81. package/dist/{lifecycle-Gge2Dadd.js → lifecycle-Dh9y8OF1.js} +3 -4
  82. package/dist/{lifecycle-Gge2Dadd.js.map → lifecycle-Dh9y8OF1.js.map} +1 -1
  83. package/dist/lifecycle-Dli9vGI2.js +1 -0
  84. package/dist/{lifecycle-9nX09dBl.js → lifecycle-vjHAFCaY.js} +4 -6
  85. package/dist/{lifecycle-9nX09dBl.js.map → lifecycle-vjHAFCaY.js.map} +1 -1
  86. package/dist/main.js +26 -27
  87. package/dist/{max-profile-contract-CRj7N211.js → max-profile-contract-DLLTsSs2.js} +5 -8
  88. package/dist/{max-profile-contract-CRj7N211.js.map → max-profile-contract-DLLTsSs2.js.map} +1 -1
  89. package/dist/{mcp-workspace-header-Xw9B1W6T.js → mcp-workspace-header-C5-dOWNa.js} +3 -4
  90. package/dist/{mcp-workspace-header-Xw9B1W6T.js.map → mcp-workspace-header-C5-dOWNa.js.map} +1 -1
  91. package/dist/{models-Ca-HQTYi.js → models-B6nH1sS6.js} +4 -5
  92. package/dist/{models-Ca-HQTYi.js.map → models-B6nH1sS6.js.map} +1 -1
  93. package/dist/{orchestration-D3-2ulhX.js → orchestration-B93jxrWI.js} +4 -5
  94. package/dist/{orchestration-D3-2ulhX.js.map → orchestration-B93jxrWI.js.map} +1 -1
  95. package/dist/{package-root-B-osctCk.js → package-root-BXgdIM3q.js} +2 -3
  96. package/dist/{package-root-B-osctCk.js.map → package-root-BXgdIM3q.js.map} +1 -1
  97. package/dist/paths-Be9_ujQ3.js +1 -0
  98. package/dist/{paths-C5477RGC.js → paths-CVEO8jEH.js} +5 -7
  99. package/dist/{paths-C5477RGC.js.map → paths-CVEO8jEH.js.map} +1 -1
  100. package/dist/{peer-mcp-personas-BSxDj9sJ.js → peer-mcp-personas-Cv21q_YR.js} +244 -372
  101. package/dist/peer-mcp-personas-Cv21q_YR.js.map +1 -0
  102. package/dist/{pi-BglhJ6n_.js → pi-B5qq1G6b.js} +84 -36
  103. package/dist/pi-B5qq1G6b.js.map +1 -0
  104. package/dist/{pi-memory-bridge-DEU1SUDz.js → pi-memory-bridge-Dvj1T3e3.js} +2 -3
  105. package/dist/{pi-memory-bridge-DEU1SUDz.js.map → pi-memory-bridge-Dvj1T3e3.js.map} +1 -1
  106. package/dist/{plan-review-hook-C9K-em4D.js → plan-review-hook-MhjK92wq.js} +5 -6
  107. package/dist/{plan-review-hook-C9K-em4D.js.map → plan-review-hook-MhjK92wq.js.map} +1 -1
  108. package/dist/{provision-B0GNohdl.js → provision-CRmtV6ew.js} +10 -14
  109. package/dist/{provision-B0GNohdl.js.map → provision-CRmtV6ew.js.map} +1 -1
  110. package/dist/rolldown-runtime-D3PmRqjj.js +4 -0
  111. package/dist/{self-invocation-BtcGj-lY.js → self-invocation-DMUnXVGT.js} +5 -7
  112. package/dist/{self-invocation-BtcGj-lY.js.map → self-invocation-DMUnXVGT.js.map} +1 -1
  113. package/dist/{serve-BxZq9vNl.js → serve-wl5FKum-.js} +24 -30
  114. package/dist/{serve-BxZq9vNl.js.map → serve-wl5FKum-.js.map} +1 -1
  115. package/dist/{server-setup-BLdWCcby.js → server-setup-Ck_FRAEt.js} +67 -117
  116. package/dist/{server-setup-BLdWCcby.js.map → server-setup-Ck_FRAEt.js.map} +1 -1
  117. package/dist/{service-backend-BV2hHjuB.js → service-backend-Ce6b2XEe.js} +112 -130
  118. package/dist/service-backend-Ce6b2XEe.js.map +1 -0
  119. package/dist/{start-C3Zb8XMT.js → start-CsMY6_qY.js} +6 -8
  120. package/dist/{start-C3Zb8XMT.js.map → start-CsMY6_qY.js.map} +1 -1
  121. package/dist/{state-DzsaGHr9.js → state-CCGDJ43X.js} +2 -3
  122. package/dist/{state-DzsaGHr9.js.map → state-CCGDJ43X.js.map} +1 -1
  123. package/dist/{static-context-pack-CsOAC87F.js → static-context-pack-DwC69_VA.js} +14 -24
  124. package/dist/{static-context-pack-CsOAC87F.js.map → static-context-pack-DwC69_VA.js.map} +1 -1
  125. package/dist/{stop-gate-hook-DnLC09Lg.js → stop-gate-hook-CBVLD8iB.js} +9 -14
  126. package/dist/{stop-gate-hook-DnLC09Lg.js.map → stop-gate-hook-CBVLD8iB.js.map} +1 -1
  127. package/dist/{stop-gate-policy-Dx9c98_d.js → stop-gate-policy-BehNiNix.js} +4 -5
  128. package/dist/{stop-gate-policy-Dx9c98_d.js.map → stop-gate-policy-BehNiNix.js.map} +1 -1
  129. package/dist/{token-Dqjs5ixP.js → token-CPzYxU4Y.js} +16 -28
  130. package/dist/{token-Dqjs5ixP.js.map → token-CPzYxU4Y.js.map} +1 -1
  131. package/dist/{token-CVG0yI_j.js → token-DHEkiO4g.js} +3 -4
  132. package/dist/{token-CVG0yI_j.js.map → token-DHEkiO4g.js.map} +1 -1
  133. package/dist/{upstream-retry-i1k1Xai2.js → upstream-retry-VNR-bCuT.js} +2 -3
  134. package/dist/{upstream-retry-i1k1Xai2.js.map → upstream-retry-VNR-bCuT.js.map} +1 -1
  135. package/dist/{version-C8x2hQrZ.js → version-CTqwKr26.js} +3 -4
  136. package/dist/{version-C8x2hQrZ.js.map → version-CTqwKr26.js.map} +1 -1
  137. package/dist/{worker-dispatch-B1w2qfjX.js → worker-dispatch-C7RtNOXv.js} +3 -4
  138. package/dist/{worker-dispatch-B1w2qfjX.js.map → worker-dispatch-C7RtNOXv.js.map} +1 -1
  139. package/dist/{workiq-qnJR5_n2.js → workiq-CQauEAMc.js} +3 -4
  140. package/dist/{workiq-qnJR5_n2.js.map → workiq-CQauEAMc.js.map} +1 -1
  141. package/dist/{workiq-tools-C6LAF_vA.js → workiq-tools-7n2xXMrQ.js} +1 -1
  142. package/package.json +18 -15
  143. package/dist/ado-tools-WDyisN8w.js +0 -1
  144. package/dist/engine-C207cikp.js +0 -1
  145. package/dist/hook-mcp-client-DERIkeR7.js.map +0 -1
  146. package/dist/index-cmd-DOhwt92u.js.map +0 -1
  147. package/dist/lifecycle-C_CT13c9.js +0 -1
  148. package/dist/lifecycle-DibiH857.js +0 -1
  149. package/dist/paths-CEswtFj5.js +0 -1
  150. package/dist/peer-mcp-personas-BSxDj9sJ.js.map +0 -1
  151. package/dist/pi-BglhJ6n_.js.map +0 -1
  152. package/dist/service-backend-BV2hHjuB.js.map +0 -1
@@ -1,5 +1,5 @@
1
- import { t as PATHS } from "./paths-C5477RGC.js";
2
- import { a as writeTokenFileAtomic, g as credentialFingerprint } from "./token-Dqjs5ixP.js";
1
+ import { a as writeTokenFileAtomic, g as credentialFingerprint } from "./token-CPzYxU4Y.js";
2
+ import { t as PATHS } from "./paths-CVEO8jEH.js";
3
3
  import consola from "consola";
4
4
  import path from "node:path";
5
5
  import { createHash, randomBytes } from "node:crypto";
@@ -474,7 +474,6 @@ async function runLoopbackAuth(opts = {}) {
474
474
  consola.success(`Work IQ: signed in${file.account ? ` as ${file.account}` : ""} (token fingerprint ${credentialFingerprint(file.accessToken)}).`);
475
475
  return file;
476
476
  }
477
- //#endregion
478
477
  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
478
 
480
- //# sourceMappingURL=token-CVG0yI_j.js.map
479
+ //# sourceMappingURL=token-DHEkiO4g.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"token-CVG0yI_j.js","names":[],"sources":["../src/lib/workiq/constants.ts","../src/lib/workiq/token.ts"],"sourcesContent":["/**\n * Constants for the Work IQ (Microsoft 365) MCP group.\n *\n * Work IQ is a hosted Streamable HTTP MCP server at\n * `https://workiq.svc.cloud.microsoft/mcp`. It is protected by Entra ID, and\n * its protected-resource metadata advertises a single scope,\n * `api://workiq.svc.cloud.microsoft/.default`, whose audience is\n * `fdcc1f02-fc51-4226-8753-f668596af7f7`. That metadata publishes no\n * authorization-server information, so dynamic client registration is not\n * available and the public client id has to be known in advance. The value\n * below is the same public client the official Work IQ Claude plugin ships and\n * the CLI prints; it is a PUBLIC native client, so it carries no secret and\n * its presence here is not a credential.\n *\n * Auth is therefore a loopback authorization-code flow with PKCE, driven\n * entirely from this process. Nothing here shells out to the `workiq` CLI: the\n * CLI bundles its own MSAL cache (`~/.work-iq-cli/msal_token_cache.dat`, DPAPI\n * encrypted and opaque outside .NET), and the MCP endpoint is reachable\n * without it.\n */\n\n/** Hosted MCP endpoint. Streamable HTTP, stateless: no `Mcp-Session-Id`. */\nexport const WORKIQ_MCP_HOST = \"https://workiq.svc.cloud.microsoft\"\nexport const WORKIQ_MCP_URL = `${WORKIQ_MCP_HOST}/mcp`\n\n/** Entra application (resource) id the access token is minted for. */\nexport const WORKIQ_RESOURCE_APP_ID = \"fdcc1f02-fc51-4226-8753-f668596af7f7\"\n\n/** Resource URI form, as accepted by the `.default` scope. */\nexport const WORKIQ_RESOURCE = \"api://workiq.svc.cloud.microsoft\"\n\n/**\n * Scopes requested in one string. `.default` is what yields the delegated\n * `WorkIQ.Act WorkIQ.Read WorkIQAgent.Ask` set on the access token; `openid\n * profile` give us the `id_token` we read the account name from; and\n * `offline_access` is what makes Entra issue the refresh token the durable\n * login depends on.\n */\nexport const WORKIQ_SCOPE = `${WORKIQ_RESOURCE}/.default openid profile offline_access`\n\n/** Public native client id (no secret). See the module comment. */\nexport const WORKIQ_PUBLIC_CLIENT_ID = \"ba081686-5d24-4bc6-a0d6-d034ecffed87\"\n\n/**\n * MCP protocol version. The live server answers `2025-06-18`, the same\n * version the Azure groups use.\n */\nexport const WORKIQ_PROTOCOL_VERSION = \"2025-06-18\"\n\n/**\n * Multi-tenant authority segment. `organizations` accepts any work or school\n * account, which is what the CLI's MSAL config uses (its tenant is empty).\n * Override with `GH_ROUTER_WORKIQ_TENANT` for a single-tenant deployment.\n */\nexport const WORKIQ_DEFAULT_TENANT = \"organizations\"\n\nexport const WORKIQ_TENANT_ENV = \"GH_ROUTER_WORKIQ_TENANT\"\n\n/**\n * Raw bearer override for tests and manual runs. It skips both the token file\n * and the refresh path entirely.\n */\nexport const WORKIQ_TOKEN_ENV = \"WORKIQ_MCP_TOKEN\"\n\n/** Overrides the durable token file path (tests, shared installs). */\nexport const WORKIQ_TOKEN_PATH_ENV = \"GH_ROUTER_WORKIQ_TOKEN_PATH\"\n\n/**\n * The eight tools that only read M365 data, keyed by the exact names the live\n * server advertises (`tools/list` on 2026-11-02 listed exactly twelve).\n *\n * `call_function` is here because the server's own description defines it as a\n * read-only Work IQ function call (Graph functions use GET). The four mutating\n * tools are in `WORKIQ_WRITE_TOOLS`.\n */\nexport const WORKIQ_READ_TOOLS: ReadonlySet<string> = new Set([\n \"ask\",\n \"retrieve\",\n \"fetch\",\n \"fetch_blob\",\n \"list_agents\",\n \"get_schema\",\n \"search_paths\",\n \"call_function\",\n])\n\n/** The four tools that change M365 state. Exposed only with `--workiq-write`. */\nexport const WORKIQ_WRITE_TOOLS: ReadonlySet<string> = new Set([\n \"create_entity\",\n \"update_entity\",\n \"delete_entity\",\n \"do_action\",\n])\n\n/**\n * Structured-content key carrying the authoritative `retrieve` payload. The\n * same shape is documented for the hosted service; `markdown` is the rendered\n * answer and `retrievalHits` the citation set.\n */\nexport const WORKIQ_RETRIEVAL_CONTENT_TYPE = \"application/vnd.ms-workiq.retrieval\"\n","/**\n * Work IQ authentication: one browser sign-in, then a durable rotating refresh\n * token shared by every `github-router` process on the machine.\n *\n * The flow is a loopback authorization-code request with PKCE against\n * `login.microsoftonline.com/<tenant>`, using the public native client the Work\n * IQ plugin ships. It was verified end to end against the live service before\n * this module existed: the authorize URL returns a code for an account with a\n * live Entra session without further interaction, the code exchange returns an\n * access token with `scp=WorkIQ.Act WorkIQ.Read WorkIQAgent.Ask`, the refresh\n * grant rotates the refresh token, and the refreshed access token is accepted\n * by the MCP endpoint.\n *\n * Three properties are load-bearing:\n *\n * 1. The refresh deadline is derived from `expires_in` (a DURATION) anchored\n * to this process's clock, never from an absolute timestamp, so a clock\n * running ahead of Entra's cannot mark a fresh token expired and drive a\n * refresh storm. Same rule as the Copilot token in `~/lib/token`.\n * 2. The refresh is single-flight. Several `tools/call`s can arrive at once\n * and a refresh ROTATES the refresh token, so two concurrent grants would\n * make one of them present an already-consumed token.\n * 3. On `invalid_grant` the token file is re-read from disk and the grant is\n * retried once with whatever refresh token is newest. That is what lets\n * two proxy processes share one login file across a rotation, mirroring\n * the disk-re-read rule the GitHub credential already follows.\n *\n * Tokens are never logged. Successful exchanges log a SHA-256 fingerprint\n * prefix, which distinguishes \"this process holds a stale token\" from \"the\n * token on disk is dead\" without putting the credential in a log line.\n */\n\nimport { spawn } from \"node:child_process\"\nimport { createHash, randomBytes } from \"node:crypto\"\nimport fs from \"node:fs/promises\"\nimport http from \"node:http\"\nimport path from \"node:path\"\nimport process from \"node:process\"\n\nimport consola from \"consola\"\n\nimport { credentialFingerprint } from \"~/services/github/get-copilot-token\"\n\nimport { PATHS } from \"../paths\"\nimport { writeTokenFileAtomic } from \"../token\"\nimport {\n WORKIQ_DEFAULT_TENANT,\n WORKIQ_PUBLIC_CLIENT_ID,\n WORKIQ_SCOPE,\n WORKIQ_TENANT_ENV,\n WORKIQ_TOKEN_ENV,\n WORKIQ_TOKEN_PATH_ENV,\n} from \"./constants\"\n\n/** Refresh this long before the access token actually expires. */\nexport const WORKIQ_REFRESH_SKEW_MS = 5 * 60 * 1000\n\n/** `expires_in` fallback when Entra omits it (it normally does not). */\nconst DEFAULT_EXPIRES_IN_S = 3600\n\n/** How long `workiq auth` waits for the browser before giving up. */\nconst DEFAULT_AUTH_TIMEOUT_MS = 5 * 60 * 1000\n\nconst LOGIN_BASE = \"https://login.microsoftonline.com\"\n\n/** The durable token file. Shape is versioned so a future change can migrate. */\nexport interface WorkiqTokenFile {\n version: 1\n clientId: string\n tenant: string\n scope: string\n accessToken: string\n refreshToken: string\n /** Wall-clock ms derived from `expires_in`, anchored to THIS clock. */\n expiresAtMs: number\n /**\n * Display-only account name from the id token (`preferred_username`). Never\n * used for an authorization decision.\n */\n account?: string\n}\n\n/**\n * A failed sign-in or refresh.\n *\n * `remedy` is the actionable one-liner the CLI and the launch provisioning\n * path print. It always names the command that fixes the state, because every\n * terminal error here has exactly one fix.\n */\nexport class WorkiqAuthError extends Error {\n readonly remedy: string\n /** Entra's error code (`invalid_grant`, `interaction_required`, …). */\n readonly errorCode?: string\n\n constructor(message: string, opts: { errorCode?: string; remedy?: string } = {}) {\n super(message)\n this.name = \"WorkiqAuthError\"\n this.errorCode = opts.errorCode\n this.remedy = opts.remedy ?? AUTH_REMEDY\n }\n}\n\nexport const AUTH_REMEDY = \"Run `github-router workiq auth`.\"\n\n/** Resolved tenant segment: `GH_ROUTER_WORKIQ_TENANT` over the default. */\nexport function workiqTenant(): string {\n const env = process.env[WORKIQ_TENANT_ENV]?.trim()\n return env || WORKIQ_DEFAULT_TENANT\n}\n\n/** Resolved token file path: `GH_ROUTER_WORKIQ_TOKEN_PATH` over APP_DIR. */\nexport function workiqTokenPath(): string {\n const env = process.env[WORKIQ_TOKEN_PATH_ENV]?.trim()\n return env || path.join(PATHS.APP_DIR, \"workiq-token.json\")\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n\nfunction isFiniteNumber(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value)\n}\n\n/**\n * Parse the token file leniently about extra fields and strictly about the\n * ones the refresh grant needs. A file that fails this is treated as absent,\n * which routes the caller to the `workiq auth` remedy rather than to a\n * confusing `invalid_request` from Entra.\n */\nfunction parseTokenFile(raw: string): WorkiqTokenFile | null {\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n return null\n }\n if (!isRecord(parsed)) return null\n if (typeof parsed.accessToken !== \"string\" || !parsed.accessToken) return null\n if (typeof parsed.refreshToken !== \"string\" || !parsed.refreshToken) return null\n if (!isFiniteNumber(parsed.expiresAtMs)) return null\n return {\n version: 1,\n clientId: typeof parsed.clientId === \"string\" ? parsed.clientId : WORKIQ_PUBLIC_CLIENT_ID,\n tenant: typeof parsed.tenant === \"string\" ? parsed.tenant : workiqTenant(),\n scope: typeof parsed.scope === \"string\" ? parsed.scope : WORKIQ_SCOPE,\n accessToken: parsed.accessToken,\n refreshToken: parsed.refreshToken,\n expiresAtMs: parsed.expiresAtMs,\n ...(typeof parsed.account === \"string\" ? { account: parsed.account } : {}),\n }\n}\n\n/** Read the token file, or null when it is absent or unreadable. */\nexport async function readWorkiqTokenFile(\n filePath: string = workiqTokenPath(),\n): Promise<WorkiqTokenFile | null> {\n let raw: string\n try {\n raw = await fs.readFile(filePath, \"utf8\")\n } catch {\n return null\n }\n return parseTokenFile(raw)\n}\n\n/** Persist the token file atomically (0600, temp + rename). */\nexport async function writeWorkiqTokenFile(\n file: WorkiqTokenFile,\n filePath: string = workiqTokenPath(),\n): Promise<void> {\n await fs.mkdir(path.dirname(filePath), { recursive: true }).catch(() => {})\n await writeTokenFileAtomic(filePath, `${JSON.stringify(file, null, 2)}\\n`)\n}\n\n/** Delete the durable login. `workiq logout`. */\nexport async function deleteWorkiqTokenFile(\n filePath: string = workiqTokenPath(),\n): Promise<boolean> {\n try {\n await fs.unlink(filePath)\n return true\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return false\n throw err\n }\n}\n\n// ---------------------------------------------------------------------------\n// PKCE and authorize URL\n// ---------------------------------------------------------------------------\n\n/** A fresh PKCE S256 verifier/challenge pair. */\nexport function createWorkiqPkce(): { verifier: string; challenge: string } {\n const verifier = randomBytes(32).toString(\"base64url\")\n const challenge = createHash(\"sha256\").update(verifier).digest(\"base64url\")\n return { verifier, challenge }\n}\n\nexport interface AuthorizeUrlOptions {\n tenant: string\n redirectUri: string\n codeChallenge: string\n state: string\n clientId?: string\n loginHint?: string\n}\n\n/** The authorize URL. Pure, so the shape is pinned by a unit test. */\nexport function buildWorkiqAuthorizeUrl(opts: AuthorizeUrlOptions): string {\n const url = new URL(`${LOGIN_BASE}/${encodeURIComponent(opts.tenant)}/oauth2/v2.0/authorize`)\n url.searchParams.set(\"client_id\", opts.clientId ?? WORKIQ_PUBLIC_CLIENT_ID)\n url.searchParams.set(\"response_type\", \"code\")\n url.searchParams.set(\"response_mode\", \"query\")\n url.searchParams.set(\"redirect_uri\", opts.redirectUri)\n url.searchParams.set(\"scope\", WORKIQ_SCOPE)\n url.searchParams.set(\"code_challenge\", opts.codeChallenge)\n url.searchParams.set(\"code_challenge_method\", \"S256\")\n url.searchParams.set(\"state\", opts.state)\n if (opts.loginHint) url.searchParams.set(\"login_hint\", opts.loginHint)\n return url.toString()\n}\n\n/** Decode a JWT payload without verifying it. Display-only. */\nfunction decodeIdTokenPayload(idToken: string | undefined): Record<string, unknown> | null {\n if (!idToken) return null\n const parts = idToken.split(\".\")\n if (parts.length < 2) return null\n try {\n const payload = JSON.parse(Buffer.from(parts[1]!, \"base64url\").toString(\"utf8\"))\n return isRecord(payload) ? payload : null\n } catch {\n return null\n }\n}\n\nfunction accountFromIdToken(idToken: string | undefined): string | undefined {\n const payload = decodeIdTokenPayload(idToken)\n if (!payload) return undefined\n for (const key of [\"preferred_username\", \"upn\", \"unique_name\", \"email\", \"name\"]) {\n const value = payload[key]\n if (typeof value === \"string\" && value.trim()) return value.trim()\n }\n return undefined\n}\n\n// ---------------------------------------------------------------------------\n// Token endpoint\n// ---------------------------------------------------------------------------\n\ninterface TokenEndpointResponse {\n access_token?: unknown\n refresh_token?: unknown\n expires_in?: unknown\n id_token?: unknown\n error?: unknown\n error_description?: unknown\n}\n\nfunction describeEndpointFailure(\n status: number,\n body: TokenEndpointResponse | null,\n): WorkiqAuthError {\n const code = typeof body?.error === \"string\" ? body.error : undefined\n const description =\n typeof body?.error_description === \"string\" && body.error_description.trim()\n ? body.error_description.trim()\n : undefined\n const head = code ? `Work IQ sign-in failed (${code})` : `Work IQ sign-in failed (HTTP ${status})`\n const message = description ? `${head}: ${description}` : head\n return new WorkiqAuthError(message, { errorCode: code })\n}\n\nasync function postTokenEndpoint(\n tenant: string,\n form: Record<string, string>,\n signal?: AbortSignal,\n): Promise<TokenEndpointResponse> {\n const res = await fetch(`${LOGIN_BASE}/${encodeURIComponent(tenant)}/oauth2/v2.0/token`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n },\n body: new URLSearchParams(form).toString(),\n ...(signal ? { signal } : {}),\n })\n let body: TokenEndpointResponse | null\n try {\n const parsed: unknown = await res.json()\n body = isRecord(parsed) ? (parsed as TokenEndpointResponse) : null\n } catch {\n body = null\n }\n if (!res.ok) throw describeEndpointFailure(res.status, body)\n if (!body) throw new WorkiqAuthError(\"Work IQ sign-in failed: the token endpoint returned no JSON.\")\n return body\n}\n\n/**\n * Turn a token endpoint response into the durable file shape.\n *\n * `expires_in` is treated as a DURATION from now; a missing or malformed value\n * falls back to an hour, which only makes the next refresh later than it could\n * have been, never earlier than the token's real expiry in the common case.\n */\nfunction tokenFileFromResponse(\n body: TokenEndpointResponse,\n context: { tenant: string; previous?: WorkiqTokenFile },\n): WorkiqTokenFile {\n const accessToken = typeof body.access_token === \"string\" ? body.access_token : \"\"\n if (!accessToken) {\n throw new WorkiqAuthError(\"Work IQ sign-in failed: the token endpoint returned no access token.\")\n }\n const refreshToken =\n typeof body.refresh_token === \"string\" && body.refresh_token\n ? body.refresh_token\n // Entra omits the refresh token when the grant did not request\n // `offline_access`; keeping the previous one is the only sane recovery.\n : (context.previous?.refreshToken ?? \"\")\n if (!refreshToken) {\n throw new WorkiqAuthError(\n \"Work IQ sign-in failed: the token endpoint returned no refresh token, so the login would not survive this process.\",\n { remedy: AUTH_REMEDY },\n )\n }\n const expiresInRaw = typeof body.expires_in === \"string\" ? Number(body.expires_in) : body.expires_in\n const expiresIn = isFiniteNumber(expiresInRaw) && expiresInRaw > 0 ? expiresInRaw : DEFAULT_EXPIRES_IN_S\n const account =\n accountFromIdToken(typeof body.id_token === \"string\" ? body.id_token : undefined)\n ?? context.previous?.account\n return {\n version: 1,\n clientId: WORKIQ_PUBLIC_CLIENT_ID,\n tenant: context.tenant,\n scope: WORKIQ_SCOPE,\n accessToken,\n refreshToken,\n expiresAtMs: Date.now() + expiresIn * 1000,\n ...(account ? { account } : {}),\n }\n}\n\n/**\n * Exchange a refresh token. Rotates and persists the new refresh token before\n * returning, so a crash after a successful grant cannot lose the only valid\n * token (the old one is already consumed upstream).\n */\nasync function exchangeRefreshToken(\n file: WorkiqTokenFile,\n refreshToken: string,\n signal?: AbortSignal,\n): Promise<WorkiqTokenFile> {\n const body = await postTokenEndpoint(\n file.tenant,\n {\n client_id: file.clientId || WORKIQ_PUBLIC_CLIENT_ID,\n grant_type: \"refresh_token\",\n scope: file.scope || WORKIQ_SCOPE,\n refresh_token: refreshToken,\n },\n signal,\n )\n const next = tokenFileFromResponse(body, { tenant: file.tenant, previous: file })\n await writeWorkiqTokenFile(next)\n cached = next\n consola.debug(\n `Work IQ: refreshed the access token (fingerprint ${credentialFingerprint(next.accessToken)}).`,\n )\n return next\n}\n\n/**\n * Refresh an access token through the refresh grant, retrying once on\n * `invalid_grant` after re-reading the file. Exported for the CLI's `status`\n * path and for tests.\n */\nexport async function refreshWorkiqAccessToken(\n file: WorkiqTokenFile,\n signal?: AbortSignal,\n): Promise<WorkiqTokenFile> {\n try {\n return await exchangeRefreshToken(file, file.refreshToken, signal)\n } catch (err) {\n if (!(err instanceof WorkiqAuthError) || err.errorCode !== \"invalid_grant\") throw err\n const disk = await readWorkiqTokenFile()\n if (disk && disk.refreshToken !== file.refreshToken) {\n consola.info(\n \"Work IQ: the token file was rotated by another process; retrying with the newest refresh token.\",\n )\n return await exchangeRefreshToken(disk, disk.refreshToken, signal)\n }\n throw err\n }\n}\n\n// ---------------------------------------------------------------------------\n// Single-flight accessor\n// ---------------------------------------------------------------------------\n\nlet cached: WorkiqTokenFile | null = null\nlet inflight: Promise<string> | null = null\n\n/** Test seam: forget the in-memory cache and any in-flight refresh. */\nexport function resetWorkiqTokenStateForTesting(): void {\n cached = null\n inflight = null\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) throw signal.reason ?? new Error(\"aborted\")\n}\n\nasync function refreshPath(opts: { signal?: AbortSignal; forceRefresh?: boolean }): Promise<string> {\n throwIfAborted(opts.signal)\n const file = cached ?? (await readWorkiqTokenFile())\n if (!file) {\n throw new WorkiqAuthError(\n `No Work IQ login found at ${workiqTokenPath()}.`,\n { remedy: AUTH_REMEDY },\n )\n }\n cached = file\n if (!opts.forceRefresh && file.expiresAtMs - WORKIQ_REFRESH_SKEW_MS > Date.now()) {\n return file.accessToken\n }\n const next = await refreshWorkiqAccessToken(file, opts.signal)\n throwIfAborted(opts.signal)\n return next.accessToken\n}\n\n/**\n * The bearer the MCP client sends. Reads, in order:\n *\n * 1. `WORKIQ_MCP_TOKEN` (tests / manual runs) — nothing else runs.\n * 2. The in-memory token, if it is still comfortably unexpired.\n * 3. The durable file, refreshing first when it is inside the skew window or\n * `forceRefresh` is set (the 401 path).\n *\n * Concurrent callers share ONE refresh. The guard and its assignment are\n * deliberately adjacent (no `await` between them): anything awaited in between\n * would yield the event loop and let a second caller past the guard.\n */\nexport function ensureWorkiqToken(\n opts: { signal?: AbortSignal; forceRefresh?: boolean } = {},\n): Promise<string> {\n const env = process.env[WORKIQ_TOKEN_ENV]?.trim()\n if (env) return Promise.resolve(env)\n if (!opts.forceRefresh && cached && cached.expiresAtMs - WORKIQ_REFRESH_SKEW_MS > Date.now()) {\n return Promise.resolve(cached.accessToken)\n }\n if (inflight) return attachSignal(inflight, opts.signal)\n const promise = refreshPath(opts)\n inflight = promise\n void promise.finally(() => {\n if (inflight === promise) inflight = null\n }).catch(() => {})\n return promise\n}\n\n/**\n * Wait for a shared refresh but let the CALLER's signal abandon the wait.\n *\n * The shared promise itself must keep running: another caller may still need\n * it, and the refresh rotates the refresh token, so abandoning it midway would\n * waste the one grant. `race` only stops this caller from waiting.\n */\nfunction attachSignal(promise: Promise<string>, signal?: AbortSignal): Promise<string> {\n if (!signal) return promise\n if (signal.aborted) return Promise.reject(signal.reason ?? new Error(\"aborted\"))\n return new Promise<string>((resolve, reject) => {\n const onAbort = (): void => reject(signal.reason ?? new Error(\"aborted\"))\n signal.addEventListener(\"abort\", onAbort, { once: true })\n promise.then(\n (value) => {\n signal.removeEventListener(\"abort\", onAbort)\n resolve(value)\n },\n (err) => {\n signal.removeEventListener(\"abort\", onAbort)\n reject(err)\n },\n )\n })\n}\n\n// ---------------------------------------------------------------------------\n// Loopback authorization-code flow\n// ---------------------------------------------------------------------------\n\n/**\n * Open the default browser. Best effort by contract: the caller always prints\n * the URL too, so a headless or locked-down machine is a paste, not a failure.\n */\nexport function openWorkiqBrowser(url: string): void {\n try {\n if (process.platform === \"win32\") {\n spawn(\"rundll32.exe\", [\"url.dll,FileProtocolHandler\", url], {\n stdio: \"ignore\",\n detached: true,\n }).unref()\n return\n }\n const command = process.platform === \"darwin\" ? \"open\" : \"xdg-open\"\n spawn(command, [url], { stdio: \"ignore\", detached: true }).unref()\n } catch {\n // Ignored on purpose; the URL has already been printed.\n }\n}\n\nexport interface LoopbackAuthOptions {\n tenant?: string\n loginHint?: string\n timeoutMs?: number\n signal?: AbortSignal\n /** Test seam: receives the authorize URL instead of/in addition to opening it. */\n onAuthorizeUrl?: (url: string) => void\n /** Test seam: replace the browser launch entirely. */\n openBrowser?: (url: string) => void\n}\n\n/** The page shown after the browser round-trips. Plain, self-contained HTML. */\nfunction resultPage(title: string, detail: string): string {\n const escape = (value: string): string =>\n value.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\")\n return `<!doctype html><html><head><meta charset=\"utf-8\"><title>${escape(title)}</title>`\n + `<style>body{font:16px/1.5 system-ui,sans-serif;margin:4rem auto;max-width:32rem;padding:0 1.5rem}</style>`\n + `</head><body><h1>${escape(title)}</h1><p>${escape(detail)}</p></body></html>`\n}\n\n/**\n * Run the interactive sign-in and persist the result.\n *\n * The listener binds with `listen(0)` and no host, which is dual-stack: a\n * browser that resolves `localhost` to `::1` must reach it, and binding\n * `127.0.0.1` would silently leave that connection refused. Entra accepts any\n * port on a `http://localhost` loopback redirect.\n */\nexport async function runLoopbackAuth(\n opts: LoopbackAuthOptions = {},\n): Promise<WorkiqTokenFile> {\n const tenant = opts.tenant ?? workiqTenant()\n const timeoutMs = opts.timeoutMs ?? DEFAULT_AUTH_TIMEOUT_MS\n const { verifier, challenge } = createWorkiqPkce()\n const expectedState = randomBytes(24).toString(\"base64url\")\n\n let settle: { resolve: (code: string) => void; reject: (err: unknown) => void } | null = null\n const codePromise = new Promise<string>((resolve, reject) => {\n settle = { resolve, reject }\n })\n\n const server = http.createServer((req, res) => {\n const url = new URL(req.url ?? \"/\", \"http://localhost\")\n const params = url.searchParams\n const respond = (status: number, title: string, detail: string): void => {\n res.statusCode = status\n res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\")\n res.end(resultPage(title, detail))\n }\n\n // A mismatched state is not the flow's answer and never settles it: it is\n // some other request hitting the ephemeral port. Answer 400 and keep\n // waiting for the real redirect.\n if (params.get(\"state\") !== expectedState) {\n respond(400, \"Unexpected sign-in response\", \"The state value did not match this sign-in attempt.\")\n return\n }\n const error = params.get(\"error\")\n if (error) {\n const description = params.get(\"error_description\") ?? \"\"\n respond(400, \"Work IQ sign-in failed\", description || error)\n settle?.reject(\n new WorkiqAuthError(\n description ? `Work IQ sign-in failed (${error}): ${description}` : `Work IQ sign-in failed (${error}).`,\n { errorCode: error },\n ),\n )\n settle = null\n return\n }\n const code = params.get(\"code\")\n if (!code) {\n respond(400, \"Work IQ sign-in failed\", \"The redirect carried no authorization code.\")\n return\n }\n respond(200, \"Work IQ sign-in complete\", \"You can close this window and return to the terminal.\")\n settle?.resolve(code)\n settle = null\n })\n\n const port = await new Promise<number>((resolve, reject) => {\n server.once(\"error\", reject)\n server.listen(0, () => {\n const address = server.address()\n if (address && typeof address === \"object\") resolve(address.port)\n else reject(new WorkiqAuthError(\"Could not determine the sign-in listener port.\"))\n })\n })\n const redirectUri = `http://localhost:${port}/`\n\n const authorizeUrl = buildWorkiqAuthorizeUrl({\n tenant,\n redirectUri,\n codeChallenge: challenge,\n state: expectedState,\n ...(opts.loginHint ? { loginHint: opts.loginHint } : {}),\n })\n\n consola.info(\"Opening the browser to sign in to Work IQ. If it does not open, visit:\")\n consola.info(authorizeUrl)\n opts.onAuthorizeUrl?.(authorizeUrl)\n ;(opts.openBrowser ?? openWorkiqBrowser)(authorizeUrl)\n\n const timeout = setTimeout(() => {\n settle?.reject(\n new WorkiqAuthError(\n `Work IQ sign-in did not complete within ${Math.round(timeoutMs / 60_000)} minutes.`,\n ),\n )\n settle = null\n }, timeoutMs)\n timeout.unref?.()\n\n const onAbort = (): void => {\n settle?.reject(opts.signal?.reason ?? new Error(\"aborted\"))\n settle = null\n }\n opts.signal?.addEventListener(\"abort\", onAbort, { once: true })\n\n let code: string\n try {\n code = await codePromise\n } finally {\n clearTimeout(timeout)\n opts.signal?.removeEventListener(\"abort\", onAbort)\n server.close()\n // `close` waits for keep-alive sockets; the browser may hold one open.\n server.closeAllConnections?.()\n }\n\n const body = await postTokenEndpoint(\n tenant,\n {\n client_id: WORKIQ_PUBLIC_CLIENT_ID,\n grant_type: \"authorization_code\",\n code,\n redirect_uri: redirectUri,\n code_verifier: verifier,\n scope: WORKIQ_SCOPE,\n },\n opts.signal,\n )\n const file = tokenFileFromResponse(body, { tenant })\n await writeWorkiqTokenFile(file)\n cached = file\n consola.success(\n `Work IQ: signed in${file.account ? ` as ${file.account}` : \"\"} `\n + `(token fingerprint ${credentialFingerprint(file.accessToken)}).`,\n )\n return file\n}\n"],"mappings":";;;;;;;;;AAuBA,MAAa,iBAAiB;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S,OAAO;EACjD,OAAO,MAAM;EAEb,OAAO,sBAAsB;CAC/B;CAcA,MAAM,OAAO,sBAAsB,MAZhB,kBACjB,QACA;EACE,WAAW;EACX,YAAY;EACZ;EACA,cAAc;EACd,eAAe;EACf,OAAO;CACT,GACA,KAAK,MACP,GACyC,EAAE,OAAO,CAAC;CACnD,MAAM,qBAAqB,IAAI;CAC/B,SAAS;CACT,QAAQ,QACN,qBAAqB,KAAK,UAAU,OAAO,KAAK,YAAY,GAAG,sBACrC,sBAAsB,KAAK,WAAW,EAAE,GACpE;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"token-DHEkiO4g.js","names":[],"sources":["../src/lib/workiq/constants.ts","../src/lib/workiq/token.ts"],"sourcesContent":["/**\n * Constants for the Work IQ (Microsoft 365) MCP group.\n *\n * Work IQ is a hosted Streamable HTTP MCP server at\n * `https://workiq.svc.cloud.microsoft/mcp`. It is protected by Entra ID, and\n * its protected-resource metadata advertises a single scope,\n * `api://workiq.svc.cloud.microsoft/.default`, whose audience is\n * `fdcc1f02-fc51-4226-8753-f668596af7f7`. That metadata publishes no\n * authorization-server information, so dynamic client registration is not\n * available and the public client id has to be known in advance. The value\n * below is the same public client the official Work IQ Claude plugin ships and\n * the CLI prints; it is a PUBLIC native client, so it carries no secret and\n * its presence here is not a credential.\n *\n * Auth is therefore a loopback authorization-code flow with PKCE, driven\n * entirely from this process. Nothing here shells out to the `workiq` CLI: the\n * CLI bundles its own MSAL cache (`~/.work-iq-cli/msal_token_cache.dat`, DPAPI\n * encrypted and opaque outside .NET), and the MCP endpoint is reachable\n * without it.\n */\n\n/** Hosted MCP endpoint. Streamable HTTP, stateless: no `Mcp-Session-Id`. */\nexport const WORKIQ_MCP_HOST = \"https://workiq.svc.cloud.microsoft\"\nexport const WORKIQ_MCP_URL = `${WORKIQ_MCP_HOST}/mcp`\n\n/** Entra application (resource) id the access token is minted for. */\nexport const WORKIQ_RESOURCE_APP_ID = \"fdcc1f02-fc51-4226-8753-f668596af7f7\"\n\n/** Resource URI form, as accepted by the `.default` scope. */\nexport const WORKIQ_RESOURCE = \"api://workiq.svc.cloud.microsoft\"\n\n/**\n * Scopes requested in one string. `.default` is what yields the delegated\n * `WorkIQ.Act WorkIQ.Read WorkIQAgent.Ask` set on the access token; `openid\n * profile` give us the `id_token` we read the account name from; and\n * `offline_access` is what makes Entra issue the refresh token the durable\n * login depends on.\n */\nexport const WORKIQ_SCOPE = `${WORKIQ_RESOURCE}/.default openid profile offline_access`\n\n/** Public native client id (no secret). See the module comment. */\nexport const WORKIQ_PUBLIC_CLIENT_ID = \"ba081686-5d24-4bc6-a0d6-d034ecffed87\"\n\n/**\n * MCP protocol version. The live server answers `2025-06-18`, the same\n * version the Azure groups use.\n */\nexport const WORKIQ_PROTOCOL_VERSION = \"2025-06-18\"\n\n/**\n * Multi-tenant authority segment. `organizations` accepts any work or school\n * account, which is what the CLI's MSAL config uses (its tenant is empty).\n * Override with `GH_ROUTER_WORKIQ_TENANT` for a single-tenant deployment.\n */\nexport const WORKIQ_DEFAULT_TENANT = \"organizations\"\n\nexport const WORKIQ_TENANT_ENV = \"GH_ROUTER_WORKIQ_TENANT\"\n\n/**\n * Raw bearer override for tests and manual runs. It skips both the token file\n * and the refresh path entirely.\n */\nexport const WORKIQ_TOKEN_ENV = \"WORKIQ_MCP_TOKEN\"\n\n/** Overrides the durable token file path (tests, shared installs). */\nexport const WORKIQ_TOKEN_PATH_ENV = \"GH_ROUTER_WORKIQ_TOKEN_PATH\"\n\n/**\n * The eight tools that only read M365 data, keyed by the exact names the live\n * server advertises (`tools/list` on 2026-11-02 listed exactly twelve).\n *\n * `call_function` is here because the server's own description defines it as a\n * read-only Work IQ function call (Graph functions use GET). The four mutating\n * tools are in `WORKIQ_WRITE_TOOLS`.\n */\nexport const WORKIQ_READ_TOOLS: ReadonlySet<string> = new Set([\n \"ask\",\n \"retrieve\",\n \"fetch\",\n \"fetch_blob\",\n \"list_agents\",\n \"get_schema\",\n \"search_paths\",\n \"call_function\",\n])\n\n/** The four tools that change M365 state. Exposed only with `--workiq-write`. */\nexport const WORKIQ_WRITE_TOOLS: ReadonlySet<string> = new Set([\n \"create_entity\",\n \"update_entity\",\n \"delete_entity\",\n \"do_action\",\n])\n\n/**\n * Structured-content key carrying the authoritative `retrieve` payload. The\n * same shape is documented for the hosted service; `markdown` is the rendered\n * answer and `retrievalHits` the citation set.\n */\nexport const WORKIQ_RETRIEVAL_CONTENT_TYPE = \"application/vnd.ms-workiq.retrieval\"\n","/**\n * Work IQ authentication: one browser sign-in, then a durable rotating refresh\n * token shared by every `github-router` process on the machine.\n *\n * The flow is a loopback authorization-code request with PKCE against\n * `login.microsoftonline.com/<tenant>`, using the public native client the Work\n * IQ plugin ships. It was verified end to end against the live service before\n * this module existed: the authorize URL returns a code for an account with a\n * live Entra session without further interaction, the code exchange returns an\n * access token with `scp=WorkIQ.Act WorkIQ.Read WorkIQAgent.Ask`, the refresh\n * grant rotates the refresh token, and the refreshed access token is accepted\n * by the MCP endpoint.\n *\n * Three properties are load-bearing:\n *\n * 1. The refresh deadline is derived from `expires_in` (a DURATION) anchored\n * to this process's clock, never from an absolute timestamp, so a clock\n * running ahead of Entra's cannot mark a fresh token expired and drive a\n * refresh storm. Same rule as the Copilot token in `~/lib/token`.\n * 2. The refresh is single-flight. Several `tools/call`s can arrive at once\n * and a refresh ROTATES the refresh token, so two concurrent grants would\n * make one of them present an already-consumed token.\n * 3. On `invalid_grant` the token file is re-read from disk and the grant is\n * retried once with whatever refresh token is newest. That is what lets\n * two proxy processes share one login file across a rotation, mirroring\n * the disk-re-read rule the GitHub credential already follows.\n *\n * Tokens are never logged. Successful exchanges log a SHA-256 fingerprint\n * prefix, which distinguishes \"this process holds a stale token\" from \"the\n * token on disk is dead\" without putting the credential in a log line.\n */\n\nimport { spawn } from \"node:child_process\"\nimport { createHash, randomBytes } from \"node:crypto\"\nimport fs from \"node:fs/promises\"\nimport http from \"node:http\"\nimport path from \"node:path\"\nimport process from \"node:process\"\n\nimport consola from \"consola\"\n\nimport { credentialFingerprint } from \"~/services/github/get-copilot-token\"\n\nimport { PATHS } from \"../paths\"\nimport { writeTokenFileAtomic } from \"../token\"\nimport {\n WORKIQ_DEFAULT_TENANT,\n WORKIQ_PUBLIC_CLIENT_ID,\n WORKIQ_SCOPE,\n WORKIQ_TENANT_ENV,\n WORKIQ_TOKEN_ENV,\n WORKIQ_TOKEN_PATH_ENV,\n} from \"./constants\"\n\n/** Refresh this long before the access token actually expires. */\nexport const WORKIQ_REFRESH_SKEW_MS = 5 * 60 * 1000\n\n/** `expires_in` fallback when Entra omits it (it normally does not). */\nconst DEFAULT_EXPIRES_IN_S = 3600\n\n/** How long `workiq auth` waits for the browser before giving up. */\nconst DEFAULT_AUTH_TIMEOUT_MS = 5 * 60 * 1000\n\nconst LOGIN_BASE = \"https://login.microsoftonline.com\"\n\n/** The durable token file. Shape is versioned so a future change can migrate. */\nexport interface WorkiqTokenFile {\n version: 1\n clientId: string\n tenant: string\n scope: string\n accessToken: string\n refreshToken: string\n /** Wall-clock ms derived from `expires_in`, anchored to THIS clock. */\n expiresAtMs: number\n /**\n * Display-only account name from the id token (`preferred_username`). Never\n * used for an authorization decision.\n */\n account?: string\n}\n\n/**\n * A failed sign-in or refresh.\n *\n * `remedy` is the actionable one-liner the CLI and the launch provisioning\n * path print. It always names the command that fixes the state, because every\n * terminal error here has exactly one fix.\n */\nexport class WorkiqAuthError extends Error {\n readonly remedy: string\n /** Entra's error code (`invalid_grant`, `interaction_required`, …). */\n readonly errorCode?: string\n\n constructor(message: string, opts: { errorCode?: string; remedy?: string } = {}) {\n super(message)\n this.name = \"WorkiqAuthError\"\n this.errorCode = opts.errorCode\n this.remedy = opts.remedy ?? AUTH_REMEDY\n }\n}\n\nexport const AUTH_REMEDY = \"Run `github-router workiq auth`.\"\n\n/** Resolved tenant segment: `GH_ROUTER_WORKIQ_TENANT` over the default. */\nexport function workiqTenant(): string {\n const env = process.env[WORKIQ_TENANT_ENV]?.trim()\n return env || WORKIQ_DEFAULT_TENANT\n}\n\n/** Resolved token file path: `GH_ROUTER_WORKIQ_TOKEN_PATH` over APP_DIR. */\nexport function workiqTokenPath(): string {\n const env = process.env[WORKIQ_TOKEN_PATH_ENV]?.trim()\n return env || path.join(PATHS.APP_DIR, \"workiq-token.json\")\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n\nfunction isFiniteNumber(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value)\n}\n\n/**\n * Parse the token file leniently about extra fields and strictly about the\n * ones the refresh grant needs. A file that fails this is treated as absent,\n * which routes the caller to the `workiq auth` remedy rather than to a\n * confusing `invalid_request` from Entra.\n */\nfunction parseTokenFile(raw: string): WorkiqTokenFile | null {\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n return null\n }\n if (!isRecord(parsed)) return null\n if (typeof parsed.accessToken !== \"string\" || !parsed.accessToken) return null\n if (typeof parsed.refreshToken !== \"string\" || !parsed.refreshToken) return null\n if (!isFiniteNumber(parsed.expiresAtMs)) return null\n return {\n version: 1,\n clientId: typeof parsed.clientId === \"string\" ? parsed.clientId : WORKIQ_PUBLIC_CLIENT_ID,\n tenant: typeof parsed.tenant === \"string\" ? parsed.tenant : workiqTenant(),\n scope: typeof parsed.scope === \"string\" ? parsed.scope : WORKIQ_SCOPE,\n accessToken: parsed.accessToken,\n refreshToken: parsed.refreshToken,\n expiresAtMs: parsed.expiresAtMs,\n ...(typeof parsed.account === \"string\" ? { account: parsed.account } : {}),\n }\n}\n\n/** Read the token file, or null when it is absent or unreadable. */\nexport async function readWorkiqTokenFile(\n filePath: string = workiqTokenPath(),\n): Promise<WorkiqTokenFile | null> {\n let raw: string\n try {\n raw = await fs.readFile(filePath, \"utf8\")\n } catch {\n return null\n }\n return parseTokenFile(raw)\n}\n\n/** Persist the token file atomically (0600, temp + rename). */\nexport async function writeWorkiqTokenFile(\n file: WorkiqTokenFile,\n filePath: string = workiqTokenPath(),\n): Promise<void> {\n await fs.mkdir(path.dirname(filePath), { recursive: true }).catch(() => {})\n await writeTokenFileAtomic(filePath, `${JSON.stringify(file, null, 2)}\\n`)\n}\n\n/** Delete the durable login. `workiq logout`. */\nexport async function deleteWorkiqTokenFile(\n filePath: string = workiqTokenPath(),\n): Promise<boolean> {\n try {\n await fs.unlink(filePath)\n return true\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return false\n throw err\n }\n}\n\n// ---------------------------------------------------------------------------\n// PKCE and authorize URL\n// ---------------------------------------------------------------------------\n\n/** A fresh PKCE S256 verifier/challenge pair. */\nexport function createWorkiqPkce(): { verifier: string; challenge: string } {\n const verifier = randomBytes(32).toString(\"base64url\")\n const challenge = createHash(\"sha256\").update(verifier).digest(\"base64url\")\n return { verifier, challenge }\n}\n\nexport interface AuthorizeUrlOptions {\n tenant: string\n redirectUri: string\n codeChallenge: string\n state: string\n clientId?: string\n loginHint?: string\n}\n\n/** The authorize URL. Pure, so the shape is pinned by a unit test. */\nexport function buildWorkiqAuthorizeUrl(opts: AuthorizeUrlOptions): string {\n const url = new URL(`${LOGIN_BASE}/${encodeURIComponent(opts.tenant)}/oauth2/v2.0/authorize`)\n url.searchParams.set(\"client_id\", opts.clientId ?? WORKIQ_PUBLIC_CLIENT_ID)\n url.searchParams.set(\"response_type\", \"code\")\n url.searchParams.set(\"response_mode\", \"query\")\n url.searchParams.set(\"redirect_uri\", opts.redirectUri)\n url.searchParams.set(\"scope\", WORKIQ_SCOPE)\n url.searchParams.set(\"code_challenge\", opts.codeChallenge)\n url.searchParams.set(\"code_challenge_method\", \"S256\")\n url.searchParams.set(\"state\", opts.state)\n if (opts.loginHint) url.searchParams.set(\"login_hint\", opts.loginHint)\n return url.toString()\n}\n\n/** Decode a JWT payload without verifying it. Display-only. */\nfunction decodeIdTokenPayload(idToken: string | undefined): Record<string, unknown> | null {\n if (!idToken) return null\n const parts = idToken.split(\".\")\n if (parts.length < 2) return null\n try {\n const payload = JSON.parse(Buffer.from(parts[1]!, \"base64url\").toString(\"utf8\"))\n return isRecord(payload) ? payload : null\n } catch {\n return null\n }\n}\n\nfunction accountFromIdToken(idToken: string | undefined): string | undefined {\n const payload = decodeIdTokenPayload(idToken)\n if (!payload) return undefined\n for (const key of [\"preferred_username\", \"upn\", \"unique_name\", \"email\", \"name\"]) {\n const value = payload[key]\n if (typeof value === \"string\" && value.trim()) return value.trim()\n }\n return undefined\n}\n\n// ---------------------------------------------------------------------------\n// Token endpoint\n// ---------------------------------------------------------------------------\n\ninterface TokenEndpointResponse {\n access_token?: unknown\n refresh_token?: unknown\n expires_in?: unknown\n id_token?: unknown\n error?: unknown\n error_description?: unknown\n}\n\nfunction describeEndpointFailure(\n status: number,\n body: TokenEndpointResponse | null,\n): WorkiqAuthError {\n const code = typeof body?.error === \"string\" ? body.error : undefined\n const description =\n typeof body?.error_description === \"string\" && body.error_description.trim()\n ? body.error_description.trim()\n : undefined\n const head = code ? `Work IQ sign-in failed (${code})` : `Work IQ sign-in failed (HTTP ${status})`\n const message = description ? `${head}: ${description}` : head\n return new WorkiqAuthError(message, { errorCode: code })\n}\n\nasync function postTokenEndpoint(\n tenant: string,\n form: Record<string, string>,\n signal?: AbortSignal,\n): Promise<TokenEndpointResponse> {\n const res = await fetch(`${LOGIN_BASE}/${encodeURIComponent(tenant)}/oauth2/v2.0/token`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n },\n body: new URLSearchParams(form).toString(),\n ...(signal ? { signal } : {}),\n })\n let body: TokenEndpointResponse | null\n try {\n const parsed: unknown = await res.json()\n body = isRecord(parsed) ? (parsed as TokenEndpointResponse) : null\n } catch {\n body = null\n }\n if (!res.ok) throw describeEndpointFailure(res.status, body)\n if (!body) throw new WorkiqAuthError(\"Work IQ sign-in failed: the token endpoint returned no JSON.\")\n return body\n}\n\n/**\n * Turn a token endpoint response into the durable file shape.\n *\n * `expires_in` is treated as a DURATION from now; a missing or malformed value\n * falls back to an hour, which only makes the next refresh later than it could\n * have been, never earlier than the token's real expiry in the common case.\n */\nfunction tokenFileFromResponse(\n body: TokenEndpointResponse,\n context: { tenant: string; previous?: WorkiqTokenFile },\n): WorkiqTokenFile {\n const accessToken = typeof body.access_token === \"string\" ? body.access_token : \"\"\n if (!accessToken) {\n throw new WorkiqAuthError(\"Work IQ sign-in failed: the token endpoint returned no access token.\")\n }\n const refreshToken =\n typeof body.refresh_token === \"string\" && body.refresh_token\n ? body.refresh_token\n // Entra omits the refresh token when the grant did not request\n // `offline_access`; keeping the previous one is the only sane recovery.\n : (context.previous?.refreshToken ?? \"\")\n if (!refreshToken) {\n throw new WorkiqAuthError(\n \"Work IQ sign-in failed: the token endpoint returned no refresh token, so the login would not survive this process.\",\n { remedy: AUTH_REMEDY },\n )\n }\n const expiresInRaw = typeof body.expires_in === \"string\" ? Number(body.expires_in) : body.expires_in\n const expiresIn = isFiniteNumber(expiresInRaw) && expiresInRaw > 0 ? expiresInRaw : DEFAULT_EXPIRES_IN_S\n const account =\n accountFromIdToken(typeof body.id_token === \"string\" ? body.id_token : undefined)\n ?? context.previous?.account\n return {\n version: 1,\n clientId: WORKIQ_PUBLIC_CLIENT_ID,\n tenant: context.tenant,\n scope: WORKIQ_SCOPE,\n accessToken,\n refreshToken,\n expiresAtMs: Date.now() + expiresIn * 1000,\n ...(account ? { account } : {}),\n }\n}\n\n/**\n * Exchange a refresh token. Rotates and persists the new refresh token before\n * returning, so a crash after a successful grant cannot lose the only valid\n * token (the old one is already consumed upstream).\n */\nasync function exchangeRefreshToken(\n file: WorkiqTokenFile,\n refreshToken: string,\n signal?: AbortSignal,\n): Promise<WorkiqTokenFile> {\n const body = await postTokenEndpoint(\n file.tenant,\n {\n client_id: file.clientId || WORKIQ_PUBLIC_CLIENT_ID,\n grant_type: \"refresh_token\",\n scope: file.scope || WORKIQ_SCOPE,\n refresh_token: refreshToken,\n },\n signal,\n )\n const next = tokenFileFromResponse(body, { tenant: file.tenant, previous: file })\n await writeWorkiqTokenFile(next)\n cached = next\n consola.debug(\n `Work IQ: refreshed the access token (fingerprint ${credentialFingerprint(next.accessToken)}).`,\n )\n return next\n}\n\n/**\n * Refresh an access token through the refresh grant, retrying once on\n * `invalid_grant` after re-reading the file. Exported for the CLI's `status`\n * path and for tests.\n */\nexport async function refreshWorkiqAccessToken(\n file: WorkiqTokenFile,\n signal?: AbortSignal,\n): Promise<WorkiqTokenFile> {\n try {\n return await exchangeRefreshToken(file, file.refreshToken, signal)\n } catch (err) {\n if (!(err instanceof WorkiqAuthError) || err.errorCode !== \"invalid_grant\") throw err\n const disk = await readWorkiqTokenFile()\n if (disk && disk.refreshToken !== file.refreshToken) {\n consola.info(\n \"Work IQ: the token file was rotated by another process; retrying with the newest refresh token.\",\n )\n return await exchangeRefreshToken(disk, disk.refreshToken, signal)\n }\n throw err\n }\n}\n\n// ---------------------------------------------------------------------------\n// Single-flight accessor\n// ---------------------------------------------------------------------------\n\nlet cached: WorkiqTokenFile | null = null\nlet inflight: Promise<string> | null = null\n\n/** Test seam: forget the in-memory cache and any in-flight refresh. */\nexport function resetWorkiqTokenStateForTesting(): void {\n cached = null\n inflight = null\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) throw signal.reason ?? new Error(\"aborted\")\n}\n\nasync function refreshPath(opts: { signal?: AbortSignal; forceRefresh?: boolean }): Promise<string> {\n throwIfAborted(opts.signal)\n const file = cached ?? (await readWorkiqTokenFile())\n if (!file) {\n throw new WorkiqAuthError(\n `No Work IQ login found at ${workiqTokenPath()}.`,\n { remedy: AUTH_REMEDY },\n )\n }\n cached = file\n if (!opts.forceRefresh && file.expiresAtMs - WORKIQ_REFRESH_SKEW_MS > Date.now()) {\n return file.accessToken\n }\n const next = await refreshWorkiqAccessToken(file, opts.signal)\n throwIfAborted(opts.signal)\n return next.accessToken\n}\n\n/**\n * The bearer the MCP client sends. Reads, in order:\n *\n * 1. `WORKIQ_MCP_TOKEN` (tests / manual runs) — nothing else runs.\n * 2. The in-memory token, if it is still comfortably unexpired.\n * 3. The durable file, refreshing first when it is inside the skew window or\n * `forceRefresh` is set (the 401 path).\n *\n * Concurrent callers share ONE refresh. The guard and its assignment are\n * deliberately adjacent (no `await` between them): anything awaited in between\n * would yield the event loop and let a second caller past the guard.\n */\nexport function ensureWorkiqToken(\n opts: { signal?: AbortSignal; forceRefresh?: boolean } = {},\n): Promise<string> {\n const env = process.env[WORKIQ_TOKEN_ENV]?.trim()\n if (env) return Promise.resolve(env)\n if (!opts.forceRefresh && cached && cached.expiresAtMs - WORKIQ_REFRESH_SKEW_MS > Date.now()) {\n return Promise.resolve(cached.accessToken)\n }\n if (inflight) return attachSignal(inflight, opts.signal)\n const promise = refreshPath(opts)\n inflight = promise\n void promise.finally(() => {\n if (inflight === promise) inflight = null\n }).catch(() => {})\n return promise\n}\n\n/**\n * Wait for a shared refresh but let the CALLER's signal abandon the wait.\n *\n * The shared promise itself must keep running: another caller may still need\n * it, and the refresh rotates the refresh token, so abandoning it midway would\n * waste the one grant. `race` only stops this caller from waiting.\n */\nfunction attachSignal(promise: Promise<string>, signal?: AbortSignal): Promise<string> {\n if (!signal) return promise\n if (signal.aborted) return Promise.reject(signal.reason ?? new Error(\"aborted\"))\n return new Promise<string>((resolve, reject) => {\n const onAbort = (): void => reject(signal.reason ?? new Error(\"aborted\"))\n signal.addEventListener(\"abort\", onAbort, { once: true })\n promise.then(\n (value) => {\n signal.removeEventListener(\"abort\", onAbort)\n resolve(value)\n },\n (err) => {\n signal.removeEventListener(\"abort\", onAbort)\n reject(err)\n },\n )\n })\n}\n\n// ---------------------------------------------------------------------------\n// Loopback authorization-code flow\n// ---------------------------------------------------------------------------\n\n/**\n * Open the default browser. Best effort by contract: the caller always prints\n * the URL too, so a headless or locked-down machine is a paste, not a failure.\n */\nexport function openWorkiqBrowser(url: string): void {\n try {\n if (process.platform === \"win32\") {\n spawn(\"rundll32.exe\", [\"url.dll,FileProtocolHandler\", url], {\n stdio: \"ignore\",\n detached: true,\n }).unref()\n return\n }\n const command = process.platform === \"darwin\" ? \"open\" : \"xdg-open\"\n spawn(command, [url], { stdio: \"ignore\", detached: true }).unref()\n } catch {\n // Ignored on purpose; the URL has already been printed.\n }\n}\n\nexport interface LoopbackAuthOptions {\n tenant?: string\n loginHint?: string\n timeoutMs?: number\n signal?: AbortSignal\n /** Test seam: receives the authorize URL instead of/in addition to opening it. */\n onAuthorizeUrl?: (url: string) => void\n /** Test seam: replace the browser launch entirely. */\n openBrowser?: (url: string) => void\n}\n\n/** The page shown after the browser round-trips. Plain, self-contained HTML. */\nfunction resultPage(title: string, detail: string): string {\n const escape = (value: string): string =>\n value.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\")\n return `<!doctype html><html><head><meta charset=\"utf-8\"><title>${escape(title)}</title>`\n + `<style>body{font:16px/1.5 system-ui,sans-serif;margin:4rem auto;max-width:32rem;padding:0 1.5rem}</style>`\n + `</head><body><h1>${escape(title)}</h1><p>${escape(detail)}</p></body></html>`\n}\n\n/**\n * Run the interactive sign-in and persist the result.\n *\n * The listener binds with `listen(0)` and no host, which is dual-stack: a\n * browser that resolves `localhost` to `::1` must reach it, and binding\n * `127.0.0.1` would silently leave that connection refused. Entra accepts any\n * port on a `http://localhost` loopback redirect.\n */\nexport async function runLoopbackAuth(\n opts: LoopbackAuthOptions = {},\n): Promise<WorkiqTokenFile> {\n const tenant = opts.tenant ?? workiqTenant()\n const timeoutMs = opts.timeoutMs ?? DEFAULT_AUTH_TIMEOUT_MS\n const { verifier, challenge } = createWorkiqPkce()\n const expectedState = randomBytes(24).toString(\"base64url\")\n\n let settle: { resolve: (code: string) => void; reject: (err: unknown) => void } | null = null\n const codePromise = new Promise<string>((resolve, reject) => {\n settle = { resolve, reject }\n })\n\n const server = http.createServer((req, res) => {\n const url = new URL(req.url ?? \"/\", \"http://localhost\")\n const params = url.searchParams\n const respond = (status: number, title: string, detail: string): void => {\n res.statusCode = status\n res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\")\n res.end(resultPage(title, detail))\n }\n\n // A mismatched state is not the flow's answer and never settles it: it is\n // some other request hitting the ephemeral port. Answer 400 and keep\n // waiting for the real redirect.\n if (params.get(\"state\") !== expectedState) {\n respond(400, \"Unexpected sign-in response\", \"The state value did not match this sign-in attempt.\")\n return\n }\n const error = params.get(\"error\")\n if (error) {\n const description = params.get(\"error_description\") ?? \"\"\n respond(400, \"Work IQ sign-in failed\", description || error)\n settle?.reject(\n new WorkiqAuthError(\n description ? `Work IQ sign-in failed (${error}): ${description}` : `Work IQ sign-in failed (${error}).`,\n { errorCode: error },\n ),\n )\n settle = null\n return\n }\n const code = params.get(\"code\")\n if (!code) {\n respond(400, \"Work IQ sign-in failed\", \"The redirect carried no authorization code.\")\n return\n }\n respond(200, \"Work IQ sign-in complete\", \"You can close this window and return to the terminal.\")\n settle?.resolve(code)\n settle = null\n })\n\n const port = await new Promise<number>((resolve, reject) => {\n server.once(\"error\", reject)\n server.listen(0, () => {\n const address = server.address()\n if (address && typeof address === \"object\") resolve(address.port)\n else reject(new WorkiqAuthError(\"Could not determine the sign-in listener port.\"))\n })\n })\n const redirectUri = `http://localhost:${port}/`\n\n const authorizeUrl = buildWorkiqAuthorizeUrl({\n tenant,\n redirectUri,\n codeChallenge: challenge,\n state: expectedState,\n ...(opts.loginHint ? { loginHint: opts.loginHint } : {}),\n })\n\n consola.info(\"Opening the browser to sign in to Work IQ. If it does not open, visit:\")\n consola.info(authorizeUrl)\n opts.onAuthorizeUrl?.(authorizeUrl)\n ;(opts.openBrowser ?? openWorkiqBrowser)(authorizeUrl)\n\n const timeout = setTimeout(() => {\n settle?.reject(\n new WorkiqAuthError(\n `Work IQ sign-in did not complete within ${Math.round(timeoutMs / 60_000)} minutes.`,\n ),\n )\n settle = null\n }, timeoutMs)\n timeout.unref?.()\n\n const onAbort = (): void => {\n settle?.reject(opts.signal?.reason ?? new Error(\"aborted\"))\n settle = null\n }\n opts.signal?.addEventListener(\"abort\", onAbort, { once: true })\n\n let code: string\n try {\n code = await codePromise\n } finally {\n clearTimeout(timeout)\n opts.signal?.removeEventListener(\"abort\", onAbort)\n server.close()\n // `close` waits for keep-alive sockets; the browser may hold one open.\n server.closeAllConnections?.()\n }\n\n const body = await postTokenEndpoint(\n tenant,\n {\n client_id: WORKIQ_PUBLIC_CLIENT_ID,\n grant_type: \"authorization_code\",\n code,\n redirect_uri: redirectUri,\n code_verifier: verifier,\n scope: WORKIQ_SCOPE,\n },\n opts.signal,\n )\n const file = tokenFileFromResponse(body, { tenant })\n await writeWorkiqTokenFile(file)\n cached = file\n consola.success(\n `Work IQ: signed in${file.account ? ` as ${file.account}` : \"\"} `\n + `(token fingerprint ${credentialFingerprint(file.accessToken)}).`,\n )\n return file\n}\n"],"mappings":";;;;;;;;;AAuBA,MAAa,iBAAiB;;;;;;;;AAe9B,MAAa,eAAe;;AAG5B,MAAa,0BAA0B;;;;;AAMvC,MAAa,0BAA0B;;;;;AAevC,MAAa,mBAAmB;;;;;;;;;AAahC,MAAa,oCAAyC,IAAI,IAAI;CAC5D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,MAAa,qCAA0C,IAAI,IAAI;CAC7D;CACA;CACA;CACA;AACF,CAAC;;;;;;AAOD,MAAa,gCAAgC;;ACzC7C,MAAM,uBAAuB;;AAG7B,MAAM,0BAA0B;AAEhC,MAAM,aAAa;;;;;;;;AA0BnB,IAAa,kBAAb,cAAqC,MAAM;CAChC;;CAEA;CAET,YAAY,SAAiB,OAAgD,CAAC,GAAG;EAC/E,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,YAAY,KAAK;EACtB,KAAK,SAAS,KAAK,UAAA;CACrB;AACF;AAEA,MAAa,cAAc;;AAG3B,SAAgB,eAAuB;CAErC,OADY,QAAQ,IAAA,0BAAsB,EAAE,KAAK,KAAA;AAEnD;;AAGA,SAAgB,kBAA0B;CAExC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D,CAAC;CAED,QAAQ,KAAK,wEAAwE;CACrF,QAAQ,KAAK,YAAY;CACzB,KAAK,iBAAiB,YAAY;CACjC,CAAC,KAAK,eAAe,kBAAA,CAAmB,YAAY;CAErD,MAAM,UAAU,iBAAiB;EAC/B,QAAQ,OACN,IAAI,gBACF,2CAA2C,KAAK,MAAM,YAAY,GAAM,EAAE,UAC5E,CACF;EACA,SAAS;CACX,GAAG,SAAS;CACZ,QAAQ,QAAQ;CAEhB,MAAM,gBAAsB;EAC1B,QAAQ,OAAO,KAAK,QAAQ,0BAAU,IAAI,MAAM,SAAS,CAAC;EAC1D,SAAS;CACX;CACA,KAAK,QAAQ,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;CAE9D,IAAI;CACJ,IAAI;EACF,OAAO,MAAM;CACf,UAAU;EACR,aAAa,OAAO;EACpB,KAAK,QAAQ,oBAAoB,SAAS,OAAO;EACjD,OAAO,MAAM;EAEb,OAAO,sBAAsB;CAC/B;CAcA,MAAM,OAAO,sBAAsB,MAZhB,kBACjB,QACA;EACE,WAAW;EACX,YAAY;EACZ;EACA,cAAc;EACd,eAAe;EACf,OAAO;CACT,GACA,KAAK,MACP,GACyC,EAAE,OAAO,CAAC;CACnD,MAAM,qBAAqB,IAAI;CAC/B,SAAS;CACT,QAAQ,QACN,qBAAqB,KAAK,UAAU,OAAO,KAAK,YAAY,GAAG,sBACrC,sBAAsB,KAAK,WAAW,EAAE,GACpE;CACA,OAAO;AACT"}
@@ -1,5 +1,5 @@
1
1
  import consola from "consola";
2
- //#region src/lib/upstream-retry.ts
2
+ // src/lib/upstream-retry.ts
3
3
  /**
4
4
  * Shared transient-failure retry for upstream calls (`src/lib/upstream-retry.ts`).
5
5
  *
@@ -377,7 +377,6 @@ async function withTransientRetry(fn, opts = {}) {
377
377
  }
378
378
  }
379
379
  }
380
- //#endregion
381
380
  export { withTransientRetry as a, sanitizeTransportText as i, classifyTransportError as n, fetchWithTransientRetry as r, TransportExhaustionError as t };
382
381
 
383
- //# sourceMappingURL=upstream-retry-i1k1Xai2.js.map
382
+ //# sourceMappingURL=upstream-retry-VNR-bCuT.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"upstream-retry-i1k1Xai2.js","names":[],"sources":["../src/lib/upstream-retry.ts"],"sourcesContent":["/**\n * Shared transient-failure retry for upstream calls (`src/lib/upstream-retry.ts`).\n *\n * Retries ONLY on transient conditions — never on success, never on a\n * deterministic 4xx (400/401/403/404…), so a malformed request or auth\n * failure fails fast instead of being hammered. 401 is intentionally NOT\n * retried here: it stays with the existing token-refresh path so the\n * 401→503 forwardError invariant is preserved.\n *\n * Retryable:\n * - HTTP 429 + 5xx (500/502/503/504) — the \"upstream is sick\" class.\n * - network errors (ECONNRESET / \"fetch failed\" / \"terminated\" / EPIPE …).\n * - upstream TIMEOUT aborts: an AbortError thrown while the CALLER'S\n * `signal` is NOT aborted (a user cancel aborts the caller's signal\n * and is rethrown immediately, never retried).\n *\n * Exponential backoff + FULL jitter, capped, honoring `Retry-After`. The\n * inter-attempt sleep is abortable so a user cancel during backoff\n * returns promptly. Bounded `attempts` keep a single call from holding an\n * inflight slot indefinitely (robust AND fast).\n *\n * Streaming note: the user-facing passthrough and the worker loop must\n * only retry in the PRE-FIRST-BYTE window — a retry after bytes have\n * streamed would duplicate output. Callers there pass a `doFetch` that\n * has not yet handed its body to the consumer.\n */\n\nimport consola from \"consola\"\n\nexport interface TransientRetryOpts {\n /** Total attempts including the first (default 3 → up to 2 retries). */\n attempts?: number\n /** Retryable HTTP statuses (default 429, 500, 502, 503, 504). */\n retryStatuses?: ReadonlyArray<number>\n /** Backoff base (default 250ms) and cap (default 4000ms). */\n baseDelayMs?: number\n maxDelayMs?: number\n /** Caller's abort signal — a user cancel fails fast (never retried). */\n signal?: AbortSignal\n /** Short label for debug logging (e.g. \"codex_critic\", \"advisor\"). */\n label?: string\n /** Upstream endpoint when it differs from the human-readable label. */\n endpoint?: string\n}\n\nconst DEFAULT_RETRY_STATUSES: ReadonlyArray<number> = [429, 500, 502, 503, 504]\nconst TRANSPORT_MESSAGE_MAX = 512\nconst TRANSIENT_CODES = new Set([\n \"ECONNRESET\",\n \"ETIMEDOUT\",\n \"EPIPE\",\n \"EAI_AGAIN\",\n \"UND_ERR_CONNECT_TIMEOUT\",\n \"UND_ERR_HEADERS_TIMEOUT\",\n \"UND_ERR_SOCKET\",\n // A dispatch that raced a pool teardown. Previously in NEITHER set, so it\n // fell through to \"non_transport\" and was rethrown raw at the retry loop —\n // an unclassified error escaping a classifier is a gap, not a policy.\n \"UND_ERR_CLOSED\",\n // HTTP/2 session death. These reached \"transient\" only incidentally, via the\n // outer TypeError(\"fetch failed\") message match, which means a future change\n // to that string would silently reclassify them. Name them.\n \"ERR_HTTP2_INVALID_SESSION\",\n \"ERR_HTTP2_GOAWAY_SESSION\",\n \"ERR_HTTP2_STREAM_CANCEL\",\n])\n\n/**\n * TLS faults that are genuinely permanent: a protocol/version/cipher mismatch,\n * or a certificate this client cannot validate. Retrying any of these buys\n * three times the latency before the identical failure.\n *\n * Deliberately NOT the blanket `\"ssl routines\"` match this replaces. Every\n * OpenSSL error carries that string, so the catch-all also swallowed alert 20\n * (`bad record mac`) — an integrity fault a fresh connection routinely clears.\n * See TRANSIENT_TLS_MESSAGES.\n *\n * Each entry must stay disjoint from TRANSIENT_TLS_MESSAGES. The bucket order\n * in `classifyTransportError` checks the narrower transient alert first, so an\n * overlap would resolve as transient; `tests/upstream-retry.test.ts` pins that\n * no error matches two buckets.\n */\nconst DETERMINISTIC_TLS_MESSAGES = [\n \"self signed certificate\",\n \"certificate has expired\",\n \"unable to verify the first certificate\",\n \"unable to get local issuer certificate\",\n \"hostname/ip does not match certificate\",\n \"certificate verify failed\",\n \"unknown ca\",\n \"wrong version number\",\n \"unsupported protocol\",\n \"no protocols available\",\n \"alert handshake failure\",\n \"alert protocol version\",\n \"alert insufficient security\",\n \"tls handshake\",\n]\n\n/**\n * TLS alert 20 (`bad_record_mac`) ONLY — a record failed AEAD authentication\n * somewhere on the path. The connection is unusable, but the next one is\n * typically fine, which is exactly what a bounded retry is for.\n *\n * This also matches OpenSSL's local-detection wording (\"decryption failed or\n * bad record mac\", reason 281) as well as the received-alert wording (\"ssl/tls\n * alert bad record mac\", reason 1020). Both are integrity faults and both\n * warrant the same one-bounded-replay policy.\n *\n * An earlier revision promoted four alert phrases; three were wrong and stay\n * deterministic on purpose. Alert 10 (`unexpected message`) is protocol state,\n * alert 21 (`decryption failed`) is legacy-server incompatibility, and alert 22\n * (`record overflow`) is a malformed or desynchronised stream. Promoting those\n * converts fail-fast configuration errors into 3x latency.\n */\nconst TRANSIENT_TLS_MESSAGES = [\"bad record mac\"]\nconst DETERMINISTIC_CODES = new Set([\n \"ENOTFOUND\",\n \"ECONNREFUSED\",\n \"DEPTH_ZERO_SELF_SIGNED_CERT\",\n \"SELF_SIGNED_CERT_IN_CHAIN\",\n \"UNABLE_TO_GET_ISSUER_CERT\",\n \"UNABLE_TO_GET_ISSUER_CERT_LOCALLY\",\n \"UNABLE_TO_VERIFY_LEAF_SIGNATURE\",\n \"CERT_HAS_EXPIRED\",\n \"CERT_NOT_YET_VALID\",\n \"ERR_TLS_CERT_ALTNAME_INVALID\",\n \"ERR_TLS_CERT_SIGNATURE_ALGORITHM_UNSUPPORTED\",\n \"ERR_SSL_WRONG_VERSION_NUMBER\",\n])\nconst CREDENTIAL_RE =\n /\\b(eyJ[A-Za-z0-9_-]{20,}(?:\\.[A-Za-z0-9_-]+){0,2}|gh[opsu]_[A-Za-z0-9_]{20,}|Bearer\\s+\\S{20,})\\b/gi\nconst SECRET_ASSIGNMENT_RE =\n /\\b(authorization|api[_-]?key|access[_-]?token|token|password)\\s*[:=]\\s*([^\\s,;]+)/gi\nconst REQUEST_BODY_RE =\n /\\b(request\\s+body|body)\\s*[:=]\\s*.*$/gi\n\nexport type TransportErrorClassification =\n | \"transient\"\n | \"deterministic\"\n | \"non_transport\"\n | \"cancelled\"\n\nexport interface TransportErrorDetails {\n classification: TransportErrorClassification\n name: string\n message: string\n code?: string\n causeCode?: string\n}\n\nexport interface TransportExhaustionMetadata {\n endpoint?: string\n label?: string\n attempts: number\n classification: \"transient\" | \"deterministic\"\n lastError: Omit<TransportErrorDetails, \"classification\">\n}\n\nexport class TransportExhaustionError extends Error {\n readonly endpoint?: string\n readonly label?: string\n readonly attempts: number\n readonly classification: \"transient\" | \"deterministic\"\n readonly lastError: Omit<TransportErrorDetails, \"classification\">\n\n constructor(metadata: TransportExhaustionMetadata, cause: unknown) {\n const target = metadata.endpoint ?? metadata.label ?? \"upstream\"\n const lastError = {\n name: sanitizeTransportText(metadata.lastError.name),\n message: sanitizeTransportText(metadata.lastError.message),\n code: metadata.lastError.code\n ? sanitizeTransportText(metadata.lastError.code)\n : undefined,\n causeCode: metadata.lastError.causeCode\n ? sanitizeTransportText(metadata.lastError.causeCode)\n : undefined,\n }\n const code = lastError.causeCode ?? lastError.code\n const suffix = code ? ` (${code})` : \"\"\n super(\n `Upstream transport ${metadata.classification === \"transient\" ? \"failed\" : \"is unreachable\"} at ${sanitizeTransportText(target)} after ${metadata.attempts} attempt${metadata.attempts === 1 ? \"\" : \"s\"}: ${lastError.name}: ${lastError.message}${suffix}`,\n { cause },\n )\n this.name = \"TransportExhaustionError\"\n this.endpoint = metadata.endpoint\n ? sanitizeTransportText(metadata.endpoint)\n : undefined\n this.label = metadata.label ? sanitizeTransportText(metadata.label) : undefined\n this.attempts = metadata.attempts\n this.classification = metadata.classification\n this.lastError = lastError\n }\n}\n\nfunction readStringProperty(value: unknown, key: string): string | undefined {\n if (\n (typeof value !== \"object\" && typeof value !== \"function\")\n || value === null\n ) {\n return undefined\n }\n try {\n const property = (value as Record<string, unknown>)[key]\n return typeof property === \"string\" ? property : undefined\n } catch {\n return undefined\n }\n}\n\nfunction readCause(value: unknown): unknown {\n if (\n (typeof value !== \"object\" && typeof value !== \"function\")\n || value === null\n ) {\n return undefined\n }\n try {\n return (value as { cause?: unknown }).cause\n } catch {\n return undefined\n }\n}\n\nfunction safeString(value: unknown): string {\n try {\n return String(value)\n } catch {\n return \"[unserializable error]\"\n }\n}\n\nexport function sanitizeTransportText(value: string): string {\n const sanitized = value\n .replace(/\\r\\n|\\r|\\n/g, \" \")\n .replace(CREDENTIAL_RE, \"[REDACTED]\")\n .replace(SECRET_ASSIGNMENT_RE, \"$1=[REDACTED]\")\n .replace(REQUEST_BODY_RE, \"$1=[REDACTED]\")\n return sanitized.length > TRANSPORT_MESSAGE_MAX\n ? `${sanitized.slice(0, TRANSPORT_MESSAGE_MAX)}…`\n : sanitized\n}\n\n/**\n * Classify errors thrown before the first response byte. Deterministic\n * connectivity/configuration signals win over generic runtime wording such as\n * TypeError(\"fetch failed\"), because the nested cause is more specific.\n *\n * Buckets are evaluated in a stated total order, narrowest first, and the first\n * match wins — so no error can land in two of them:\n *\n * 1. caller cancel\n * 2. TLS alert 20 (`bad record mac`) — integrity, retryable\n * 3. deterministic cert/config codes and messages, plus refused/DNS-miss\n * 4. transient codes (incl. HTTP/2 session death) and generic transport text\n * 5. everything else — `non_transport`, rethrown raw\n */\nexport function classifyTransportError(\n error: unknown,\n opts: { callerCancelled?: boolean } = {},\n): TransportErrorDetails {\n const name = readStringProperty(error, \"name\") ?? \"Error\"\n const rawMessage =\n readStringProperty(error, \"message\")\n ?? (typeof error === \"string\" ? error : safeString(error))\n const message = sanitizeTransportText(rawMessage)\n const code = readStringProperty(error, \"code\")\n\n const causes: unknown[] = []\n const seen = new Set<unknown>()\n let current = readCause(error)\n for (let depth = 0; current !== undefined && depth < 4; depth++) {\n if (\n (typeof current === \"object\" || typeof current === \"function\")\n && current !== null\n ) {\n if (seen.has(current)) break\n seen.add(current)\n }\n causes.push(current)\n current = readCause(current)\n }\n const causeCode = causes\n .map((cause) => readStringProperty(cause, \"code\"))\n .find((value): value is string => value !== undefined)\n const codes = [code, ...causes.map((cause) => readStringProperty(cause, \"code\"))]\n .filter((value): value is string => value !== undefined)\n .map((value) => value.toUpperCase())\n const messages = [\n rawMessage,\n ...causes.map((cause) => readStringProperty(cause, \"message\") ?? \"\"),\n ]\n .join(\" \")\n .toLowerCase()\n\n if (opts.callerCancelled) {\n return { classification: \"cancelled\", name, message, code, causeCode }\n }\n // Narrowest match first: TLS alert 20 is an integrity fault, not a\n // configuration fault, and it must not be swallowed by the broader cert /\n // protocol patterns below (which is exactly what the old blanket\n // `\"ssl routines\"` match did — it failed the alert after ONE attempt).\n if (TRANSIENT_TLS_MESSAGES.some((phrase) => messages.includes(phrase))) {\n return { classification: \"transient\", name, message, code, causeCode }\n }\n if (\n codes.some((value) => DETERMINISTIC_CODES.has(value))\n || DETERMINISTIC_TLS_MESSAGES.some((phrase) => messages.includes(phrase))\n // Catch-all for every OTHER OpenSSL failure. Safe here, and only here,\n // because the one retryable alert already returned above — so this keeps\n // fail-fast for the long tail (`tlsv13 alert certificate required`,\n // `sslv3 alert bad certificate`, `tlsv1 alert internal error`, …) without\n // re-swallowing alert 20.\n //\n // Without it those errors fall through to the generic transient branch via\n // the outer `TypeError: fetch failed`, turning a permanent configuration\n // failure into three attempts. Narrowing the deterministic list alone was\n // not sufficient; the residue has to land somewhere deliberate.\n || messages.includes(\"ssl routines\")\n // A refused connection or a DNS miss is a configuration signal, so it\n // fails fast rather than being hammered. Kept deliberately, not inherited:\n // transient DNS is already covered by EAI_AGAIN, and a genuinely\n // restarting upstream surfaces as ECONNRESET or a 5xx, both of which do\n // retry.\n || messages.includes(\"econnrefused\")\n || messages.includes(\"enotfound\")\n ) {\n return { classification: \"deterministic\", name, message, code, causeCode }\n }\n if (\n name === \"AbortError\"\n || name === \"TimeoutError\"\n || name === \"InactivityTimeout\"\n || codes.some((value) => TRANSIENT_CODES.has(value))\n || messages.includes(\"terminated\")\n || messages.includes(\"fetch failed\")\n || messages.includes(\"network error\")\n || messages.includes(\"socket hang up\")\n || messages.includes(\"socket closed\")\n || messages.includes(\"econnreset\")\n || messages.includes(\"etimedout\")\n || messages.includes(\"epipe\")\n || messages.includes(\"eai_again\")\n ) {\n return { classification: \"transient\", name, message, code, causeCode }\n }\n return { classification: \"non_transport\", name, message, code, causeCode }\n}\n\nfunction transportExhaustion(\n error: unknown,\n attempts: number,\n opts: TransientRetryOpts,\n details: TransportErrorDetails,\n): TransportExhaustionError {\n if (\n details.classification !== \"transient\"\n && details.classification !== \"deterministic\"\n ) {\n throw new TypeError(\"transportExhaustion requires a transport error\")\n }\n return new TransportExhaustionError(\n {\n endpoint: opts.endpoint ?? opts.label,\n label: opts.label,\n attempts,\n classification: details.classification,\n lastError: {\n name: details.name,\n message: details.message,\n code: details.code,\n causeCode: details.causeCode,\n },\n },\n error,\n )\n}\n\nfunction parseRetryAfter(headerValue: string | null): number | undefined {\n if (!headerValue) return undefined\n const secs = Number(headerValue)\n if (Number.isFinite(secs)) return Math.max(0, secs * 1000)\n const dateMs = Date.parse(headerValue)\n if (Number.isFinite(dateMs)) return Math.max(0, dateMs - Date.now())\n return undefined\n}\n\n/** Sleep that resolves early (does not reject) when `signal` aborts — the\n * retry loop re-checks `signal.aborted` at the top and throws there. */\nfunction abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (ms <= 0) return Promise.resolve()\n return new Promise<void>((resolve) => {\n let settled = false\n const done = (): void => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n signal?.removeEventListener(\"abort\", done)\n resolve()\n }\n const timer = setTimeout(done, ms)\n if (signal) {\n if (signal.aborted) {\n done()\n return\n }\n signal.addEventListener(\"abort\", done, { once: true })\n }\n })\n}\n\n/**\n * Run `doFetch` with bounded transient-failure retries. `doFetch` is a\n * thunk so each attempt issues a FRESH request (bodies can't be replayed\n * from a consumed stream). Returns the final `Response` — which may still\n * carry a retryable status if all attempts are exhausted (the caller\n * handles that as it would a single-shot failure).\n */\nexport async function fetchWithTransientRetry(\n doFetch: (attempt: number) => Promise<Response>,\n opts: TransientRetryOpts = {},\n): Promise<Response> {\n const attempts = Math.max(1, opts.attempts ?? 3)\n const retryStatuses = opts.retryStatuses ?? DEFAULT_RETRY_STATUSES\n const baseDelayMs = opts.baseDelayMs ?? 250\n const maxDelayMs = opts.maxDelayMs ?? 4000\n const { signal, label } = opts\n\n for (let attempt = 1; ; attempt++) {\n if (signal?.aborted) {\n throw new DOMException(\"This operation was aborted\", \"AbortError\")\n }\n\n let res: Response | undefined\n let caught: unknown\n try {\n res = await doFetch(attempt)\n } catch (err) {\n caught = err\n }\n\n // Success or a non-retryable status → done.\n if (res && !retryStatuses.includes(res.status)) return res\n\n // A thrown error: a user cancel fails fast; otherwise only retry the\n // transient network/timeout class.\n if (caught !== undefined) {\n if (signal?.aborted) throw caught\n const details = classifyTransportError(caught)\n if (details.classification === \"deterministic\") {\n throw transportExhaustion(caught, attempt, opts, details)\n }\n if (details.classification !== \"transient\") throw caught\n }\n\n // Out of attempts → return the last error response (or rethrow).\n if (attempt >= attempts) {\n if (res) return res\n const details = classifyTransportError(caught)\n throw transportExhaustion(caught, attempt, opts, details)\n }\n\n // Free the connection before retrying a retryable-status response.\n const retryAfterMs = res\n ? parseRetryAfter(res.headers.get(\"retry-after\"))\n : undefined\n if (res?.body) {\n try {\n await res.body.cancel()\n } catch {\n /* already torn down */\n }\n }\n\n // Full jitter (random within the exponential cap), Retry-After wins.\n const expCap = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1))\n const delay = Math.min(\n maxDelayMs,\n retryAfterMs ?? Math.round(Math.random() * expCap),\n )\n if (label) {\n const why = res\n ? `HTTP ${res.status}`\n : (caught as { name?: string } | undefined)?.name ?? \"error\"\n consola.debug(\n `[upstream-retry] ${label}: attempt ${attempt}/${attempts} failed (${why}); retrying in ${delay}ms`,\n )\n }\n await abortableSleep(delay, signal)\n }\n}\n\n/** Extract an HTTP status from a thrown error (HTTPError carries\n * `.response.status`; others may carry `.status`/`.statusCode`; last\n * resort parses `\"HTTP <code>\"` from the message). */\nfunction errorStatus(err: unknown): number | undefined {\n const e = err as\n | {\n status?: unknown\n statusCode?: unknown\n response?: { status?: unknown }\n message?: string\n }\n | undefined\n for (const v of [e?.status, e?.statusCode, e?.response?.status]) {\n if (typeof v === \"number\") return v\n }\n const m = /\\bHTTP (\\d{3})\\b/.exec(e?.message ?? \"\")\n return m ? Number(m[1]) : undefined\n}\n\n/**\n * Generic transient-retry for a non-`Response`-returning call (e.g. the\n * Copilot service clients, which throw `HTTPError` on non-OK and throw on\n * network errors). Retries `fn()` when it throws a transient error — an\n * `HTTPError`-like with a retryable status (429/5xx) OR a transient\n * network/timeout error — using the same backoff + abort semantics as\n * `fetchWithTransientRetry`. Never retries a deterministic 4xx (incl.\n * 401), a non-transient throw, or a user cancel.\n */\nexport async function withTransientRetry<T>(\n fn: (attempt: number) => Promise<T>,\n opts: TransientRetryOpts = {},\n): Promise<T> {\n const attempts = Math.max(1, opts.attempts ?? 3)\n const retryStatuses = opts.retryStatuses ?? DEFAULT_RETRY_STATUSES\n const baseDelayMs = opts.baseDelayMs ?? 250\n const maxDelayMs = opts.maxDelayMs ?? 4000\n const { signal, label } = opts\n\n for (let attempt = 1; ; attempt++) {\n if (signal?.aborted) {\n throw new DOMException(\"This operation was aborted\", \"AbortError\")\n }\n try {\n return await fn(attempt)\n } catch (err) {\n if (signal?.aborted) throw err\n const status = errorStatus(err)\n const details = classifyTransportError(err)\n if (status !== undefined) {\n if (!retryStatuses.includes(status) || attempt >= attempts) throw err\n } else {\n if (details.classification === \"deterministic\") {\n throw transportExhaustion(err, attempt, opts, details)\n }\n if (details.classification !== \"transient\") throw err\n if (attempt >= attempts) {\n throw transportExhaustion(err, attempt, opts, details)\n }\n }\n\n const retryAfterMs = parseRetryAfter(\n (err as { response?: { headers?: { get?: (k: string) => string | null } } })\n ?.response?.headers?.get?.(\"retry-after\") ?? null,\n )\n const expCap = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1))\n const delay = Math.min(\n maxDelayMs,\n retryAfterMs ?? Math.round(Math.random() * expCap),\n )\n if (label) {\n consola.debug(\n `[upstream-retry] ${label}: attempt ${attempt}/${attempts} threw (${\n status !== undefined ? `HTTP ${status}` : (err as { name?: string })?.name ?? \"error\"\n }); retrying in ${delay}ms`,\n )\n }\n await abortableSleep(delay, signal)\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,MAAM,yBAAgD;CAAC;CAAK;CAAK;CAAK;CAAK;AAAG;AAC9E,MAAM,wBAAwB;AAC9B,MAAM,kCAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CAIA;CAIA;CACA;CACA;AACF,CAAC;;;;;;;;;;;;;;;;AAiBD,MAAM,6BAA6B;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;;;;;;;AAkBA,MAAM,yBAAyB,CAAC,gBAAgB;AAChD,MAAM,sCAAsB,IAAI,IAAI;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,gBACJ;AACF,MAAM,uBACJ;AACF,MAAM,kBACJ;AAwBF,IAAa,2BAAb,cAA8C,MAAM;CAClD;CACA;CACA;CACA;CACA;CAEA,YAAY,UAAuC,OAAgB;EACjE,MAAM,SAAS,SAAS,YAAY,SAAS,SAAS;EACtD,MAAM,YAAY;GAChB,MAAM,sBAAsB,SAAS,UAAU,IAAI;GACnD,SAAS,sBAAsB,SAAS,UAAU,OAAO;GACzD,MAAM,SAAS,UAAU,OACrB,sBAAsB,SAAS,UAAU,IAAI,IAC7C,KAAA;GACJ,WAAW,SAAS,UAAU,YAC1B,sBAAsB,SAAS,UAAU,SAAS,IAClD,KAAA;EACN;EACA,MAAM,OAAO,UAAU,aAAa,UAAU;EAC9C,MAAM,SAAS,OAAO,KAAK,KAAK,KAAK;EACrC,MACE,sBAAsB,SAAS,mBAAmB,cAAc,WAAW,iBAAiB,MAAM,sBAAsB,MAAM,EAAE,SAAS,SAAS,SAAS,UAAU,SAAS,aAAa,IAAI,KAA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AAoB,KAAK,SAAS,MAAM,OAAO;IAEvD,IAAI,QAAQ,mBAAmB,aAAa,MAAM;IAClD,IAAI,WAAW,UACb,MAAM,oBAAoB,KAAK,SAAS,MAAM,OAAO;GAEzD;GAEA,MAAM,eAAe,gBAClB,KACG,UAAU,SAAS,MAAM,aAAa,KAAK,IACjD;GACA,MAAM,SAAS,KAAK,IAAI,YAAY,cAAc,MAAM,UAAU,EAAE;GACpE,MAAM,QAAQ,KAAK,IACjB,YACA,gBAAgB,KAAK,MAAM,KAAK,OAAO,IAAI,MAAM,CACnD;GACA,IAAI,OACF,QAAQ,MACN,oBAAoB,MAAM,YAAY,QAAQ,GAAG,SAAS,UACxD,WAAW,KAAA,IAAY,QAAQ,WAAY,KAA2B,QAAQ,QAC/E,iBAAiB,MAAM,GAC1B;GAEF,MAAM,eAAe,OAAO,MAAM;EACpC;CACF;AACF"}
1
+ {"version":3,"file":"upstream-retry-VNR-bCuT.js","names":[],"sources":["../src/lib/upstream-retry.ts"],"sourcesContent":["/**\n * Shared transient-failure retry for upstream calls (`src/lib/upstream-retry.ts`).\n *\n * Retries ONLY on transient conditions — never on success, never on a\n * deterministic 4xx (400/401/403/404…), so a malformed request or auth\n * failure fails fast instead of being hammered. 401 is intentionally NOT\n * retried here: it stays with the existing token-refresh path so the\n * 401→503 forwardError invariant is preserved.\n *\n * Retryable:\n * - HTTP 429 + 5xx (500/502/503/504) — the \"upstream is sick\" class.\n * - network errors (ECONNRESET / \"fetch failed\" / \"terminated\" / EPIPE …).\n * - upstream TIMEOUT aborts: an AbortError thrown while the CALLER'S\n * `signal` is NOT aborted (a user cancel aborts the caller's signal\n * and is rethrown immediately, never retried).\n *\n * Exponential backoff + FULL jitter, capped, honoring `Retry-After`. The\n * inter-attempt sleep is abortable so a user cancel during backoff\n * returns promptly. Bounded `attempts` keep a single call from holding an\n * inflight slot indefinitely (robust AND fast).\n *\n * Streaming note: the user-facing passthrough and the worker loop must\n * only retry in the PRE-FIRST-BYTE window — a retry after bytes have\n * streamed would duplicate output. Callers there pass a `doFetch` that\n * has not yet handed its body to the consumer.\n */\n\nimport consola from \"consola\"\n\nexport interface TransientRetryOpts {\n /** Total attempts including the first (default 3 → up to 2 retries). */\n attempts?: number\n /** Retryable HTTP statuses (default 429, 500, 502, 503, 504). */\n retryStatuses?: ReadonlyArray<number>\n /** Backoff base (default 250ms) and cap (default 4000ms). */\n baseDelayMs?: number\n maxDelayMs?: number\n /** Caller's abort signal — a user cancel fails fast (never retried). */\n signal?: AbortSignal\n /** Short label for debug logging (e.g. \"codex_critic\", \"advisor\"). */\n label?: string\n /** Upstream endpoint when it differs from the human-readable label. */\n endpoint?: string\n}\n\nconst DEFAULT_RETRY_STATUSES: ReadonlyArray<number> = [429, 500, 502, 503, 504]\nconst TRANSPORT_MESSAGE_MAX = 512\nconst TRANSIENT_CODES = new Set([\n \"ECONNRESET\",\n \"ETIMEDOUT\",\n \"EPIPE\",\n \"EAI_AGAIN\",\n \"UND_ERR_CONNECT_TIMEOUT\",\n \"UND_ERR_HEADERS_TIMEOUT\",\n \"UND_ERR_SOCKET\",\n // A dispatch that raced a pool teardown. Previously in NEITHER set, so it\n // fell through to \"non_transport\" and was rethrown raw at the retry loop —\n // an unclassified error escaping a classifier is a gap, not a policy.\n \"UND_ERR_CLOSED\",\n // HTTP/2 session death. These reached \"transient\" only incidentally, via the\n // outer TypeError(\"fetch failed\") message match, which means a future change\n // to that string would silently reclassify them. Name them.\n \"ERR_HTTP2_INVALID_SESSION\",\n \"ERR_HTTP2_GOAWAY_SESSION\",\n \"ERR_HTTP2_STREAM_CANCEL\",\n])\n\n/**\n * TLS faults that are genuinely permanent: a protocol/version/cipher mismatch,\n * or a certificate this client cannot validate. Retrying any of these buys\n * three times the latency before the identical failure.\n *\n * Deliberately NOT the blanket `\"ssl routines\"` match this replaces. Every\n * OpenSSL error carries that string, so the catch-all also swallowed alert 20\n * (`bad record mac`) — an integrity fault a fresh connection routinely clears.\n * See TRANSIENT_TLS_MESSAGES.\n *\n * Each entry must stay disjoint from TRANSIENT_TLS_MESSAGES. The bucket order\n * in `classifyTransportError` checks the narrower transient alert first, so an\n * overlap would resolve as transient; `tests/upstream-retry.test.ts` pins that\n * no error matches two buckets.\n */\nconst DETERMINISTIC_TLS_MESSAGES = [\n \"self signed certificate\",\n \"certificate has expired\",\n \"unable to verify the first certificate\",\n \"unable to get local issuer certificate\",\n \"hostname/ip does not match certificate\",\n \"certificate verify failed\",\n \"unknown ca\",\n \"wrong version number\",\n \"unsupported protocol\",\n \"no protocols available\",\n \"alert handshake failure\",\n \"alert protocol version\",\n \"alert insufficient security\",\n \"tls handshake\",\n]\n\n/**\n * TLS alert 20 (`bad_record_mac`) ONLY — a record failed AEAD authentication\n * somewhere on the path. The connection is unusable, but the next one is\n * typically fine, which is exactly what a bounded retry is for.\n *\n * This also matches OpenSSL's local-detection wording (\"decryption failed or\n * bad record mac\", reason 281) as well as the received-alert wording (\"ssl/tls\n * alert bad record mac\", reason 1020). Both are integrity faults and both\n * warrant the same one-bounded-replay policy.\n *\n * An earlier revision promoted four alert phrases; three were wrong and stay\n * deterministic on purpose. Alert 10 (`unexpected message`) is protocol state,\n * alert 21 (`decryption failed`) is legacy-server incompatibility, and alert 22\n * (`record overflow`) is a malformed or desynchronised stream. Promoting those\n * converts fail-fast configuration errors into 3x latency.\n */\nconst TRANSIENT_TLS_MESSAGES = [\"bad record mac\"]\nconst DETERMINISTIC_CODES = new Set([\n \"ENOTFOUND\",\n \"ECONNREFUSED\",\n \"DEPTH_ZERO_SELF_SIGNED_CERT\",\n \"SELF_SIGNED_CERT_IN_CHAIN\",\n \"UNABLE_TO_GET_ISSUER_CERT\",\n \"UNABLE_TO_GET_ISSUER_CERT_LOCALLY\",\n \"UNABLE_TO_VERIFY_LEAF_SIGNATURE\",\n \"CERT_HAS_EXPIRED\",\n \"CERT_NOT_YET_VALID\",\n \"ERR_TLS_CERT_ALTNAME_INVALID\",\n \"ERR_TLS_CERT_SIGNATURE_ALGORITHM_UNSUPPORTED\",\n \"ERR_SSL_WRONG_VERSION_NUMBER\",\n])\nconst CREDENTIAL_RE =\n /\\b(eyJ[A-Za-z0-9_-]{20,}(?:\\.[A-Za-z0-9_-]+){0,2}|gh[opsu]_[A-Za-z0-9_]{20,}|Bearer\\s+\\S{20,})\\b/gi\nconst SECRET_ASSIGNMENT_RE =\n /\\b(authorization|api[_-]?key|access[_-]?token|token|password)\\s*[:=]\\s*([^\\s,;]+)/gi\nconst REQUEST_BODY_RE =\n /\\b(request\\s+body|body)\\s*[:=]\\s*.*$/gi\n\nexport type TransportErrorClassification =\n | \"transient\"\n | \"deterministic\"\n | \"non_transport\"\n | \"cancelled\"\n\nexport interface TransportErrorDetails {\n classification: TransportErrorClassification\n name: string\n message: string\n code?: string\n causeCode?: string\n}\n\nexport interface TransportExhaustionMetadata {\n endpoint?: string\n label?: string\n attempts: number\n classification: \"transient\" | \"deterministic\"\n lastError: Omit<TransportErrorDetails, \"classification\">\n}\n\nexport class TransportExhaustionError extends Error {\n readonly endpoint?: string\n readonly label?: string\n readonly attempts: number\n readonly classification: \"transient\" | \"deterministic\"\n readonly lastError: Omit<TransportErrorDetails, \"classification\">\n\n constructor(metadata: TransportExhaustionMetadata, cause: unknown) {\n const target = metadata.endpoint ?? metadata.label ?? \"upstream\"\n const lastError = {\n name: sanitizeTransportText(metadata.lastError.name),\n message: sanitizeTransportText(metadata.lastError.message),\n code: metadata.lastError.code\n ? sanitizeTransportText(metadata.lastError.code)\n : undefined,\n causeCode: metadata.lastError.causeCode\n ? sanitizeTransportText(metadata.lastError.causeCode)\n : undefined,\n }\n const code = lastError.causeCode ?? lastError.code\n const suffix = code ? ` (${code})` : \"\"\n super(\n `Upstream transport ${metadata.classification === \"transient\" ? \"failed\" : \"is unreachable\"} at ${sanitizeTransportText(target)} after ${metadata.attempts} attempt${metadata.attempts === 1 ? \"\" : \"s\"}: ${lastError.name}: ${lastError.message}${suffix}`,\n { cause },\n )\n this.name = \"TransportExhaustionError\"\n this.endpoint = metadata.endpoint\n ? sanitizeTransportText(metadata.endpoint)\n : undefined\n this.label = metadata.label ? sanitizeTransportText(metadata.label) : undefined\n this.attempts = metadata.attempts\n this.classification = metadata.classification\n this.lastError = lastError\n }\n}\n\nfunction readStringProperty(value: unknown, key: string): string | undefined {\n if (\n (typeof value !== \"object\" && typeof value !== \"function\")\n || value === null\n ) {\n return undefined\n }\n try {\n const property = (value as Record<string, unknown>)[key]\n return typeof property === \"string\" ? property : undefined\n } catch {\n return undefined\n }\n}\n\nfunction readCause(value: unknown): unknown {\n if (\n (typeof value !== \"object\" && typeof value !== \"function\")\n || value === null\n ) {\n return undefined\n }\n try {\n return (value as { cause?: unknown }).cause\n } catch {\n return undefined\n }\n}\n\nfunction safeString(value: unknown): string {\n try {\n return String(value)\n } catch {\n return \"[unserializable error]\"\n }\n}\n\nexport function sanitizeTransportText(value: string): string {\n const sanitized = value\n .replace(/\\r\\n|\\r|\\n/g, \" \")\n .replace(CREDENTIAL_RE, \"[REDACTED]\")\n .replace(SECRET_ASSIGNMENT_RE, \"$1=[REDACTED]\")\n .replace(REQUEST_BODY_RE, \"$1=[REDACTED]\")\n return sanitized.length > TRANSPORT_MESSAGE_MAX\n ? `${sanitized.slice(0, TRANSPORT_MESSAGE_MAX)}…`\n : sanitized\n}\n\n/**\n * Classify errors thrown before the first response byte. Deterministic\n * connectivity/configuration signals win over generic runtime wording such as\n * TypeError(\"fetch failed\"), because the nested cause is more specific.\n *\n * Buckets are evaluated in a stated total order, narrowest first, and the first\n * match wins — so no error can land in two of them:\n *\n * 1. caller cancel\n * 2. TLS alert 20 (`bad record mac`) — integrity, retryable\n * 3. deterministic cert/config codes and messages, plus refused/DNS-miss\n * 4. transient codes (incl. HTTP/2 session death) and generic transport text\n * 5. everything else — `non_transport`, rethrown raw\n */\nexport function classifyTransportError(\n error: unknown,\n opts: { callerCancelled?: boolean } = {},\n): TransportErrorDetails {\n const name = readStringProperty(error, \"name\") ?? \"Error\"\n const rawMessage =\n readStringProperty(error, \"message\")\n ?? (typeof error === \"string\" ? error : safeString(error))\n const message = sanitizeTransportText(rawMessage)\n const code = readStringProperty(error, \"code\")\n\n const causes: unknown[] = []\n const seen = new Set<unknown>()\n let current = readCause(error)\n for (let depth = 0; current !== undefined && depth < 4; depth++) {\n if (\n (typeof current === \"object\" || typeof current === \"function\")\n && current !== null\n ) {\n if (seen.has(current)) break\n seen.add(current)\n }\n causes.push(current)\n current = readCause(current)\n }\n const causeCode = causes\n .map((cause) => readStringProperty(cause, \"code\"))\n .find((value): value is string => value !== undefined)\n const codes = [code, ...causes.map((cause) => readStringProperty(cause, \"code\"))]\n .filter((value): value is string => value !== undefined)\n .map((value) => value.toUpperCase())\n const messages = [\n rawMessage,\n ...causes.map((cause) => readStringProperty(cause, \"message\") ?? \"\"),\n ]\n .join(\" \")\n .toLowerCase()\n\n if (opts.callerCancelled) {\n return { classification: \"cancelled\", name, message, code, causeCode }\n }\n // Narrowest match first: TLS alert 20 is an integrity fault, not a\n // configuration fault, and it must not be swallowed by the broader cert /\n // protocol patterns below (which is exactly what the old blanket\n // `\"ssl routines\"` match did — it failed the alert after ONE attempt).\n if (TRANSIENT_TLS_MESSAGES.some((phrase) => messages.includes(phrase))) {\n return { classification: \"transient\", name, message, code, causeCode }\n }\n if (\n codes.some((value) => DETERMINISTIC_CODES.has(value))\n || DETERMINISTIC_TLS_MESSAGES.some((phrase) => messages.includes(phrase))\n // Catch-all for every OTHER OpenSSL failure. Safe here, and only here,\n // because the one retryable alert already returned above — so this keeps\n // fail-fast for the long tail (`tlsv13 alert certificate required`,\n // `sslv3 alert bad certificate`, `tlsv1 alert internal error`, …) without\n // re-swallowing alert 20.\n //\n // Without it those errors fall through to the generic transient branch via\n // the outer `TypeError: fetch failed`, turning a permanent configuration\n // failure into three attempts. Narrowing the deterministic list alone was\n // not sufficient; the residue has to land somewhere deliberate.\n || messages.includes(\"ssl routines\")\n // A refused connection or a DNS miss is a configuration signal, so it\n // fails fast rather than being hammered. Kept deliberately, not inherited:\n // transient DNS is already covered by EAI_AGAIN, and a genuinely\n // restarting upstream surfaces as ECONNRESET or a 5xx, both of which do\n // retry.\n || messages.includes(\"econnrefused\")\n || messages.includes(\"enotfound\")\n ) {\n return { classification: \"deterministic\", name, message, code, causeCode }\n }\n if (\n name === \"AbortError\"\n || name === \"TimeoutError\"\n || name === \"InactivityTimeout\"\n || codes.some((value) => TRANSIENT_CODES.has(value))\n || messages.includes(\"terminated\")\n || messages.includes(\"fetch failed\")\n || messages.includes(\"network error\")\n || messages.includes(\"socket hang up\")\n || messages.includes(\"socket closed\")\n || messages.includes(\"econnreset\")\n || messages.includes(\"etimedout\")\n || messages.includes(\"epipe\")\n || messages.includes(\"eai_again\")\n ) {\n return { classification: \"transient\", name, message, code, causeCode }\n }\n return { classification: \"non_transport\", name, message, code, causeCode }\n}\n\nfunction transportExhaustion(\n error: unknown,\n attempts: number,\n opts: TransientRetryOpts,\n details: TransportErrorDetails,\n): TransportExhaustionError {\n if (\n details.classification !== \"transient\"\n && details.classification !== \"deterministic\"\n ) {\n throw new TypeError(\"transportExhaustion requires a transport error\")\n }\n return new TransportExhaustionError(\n {\n endpoint: opts.endpoint ?? opts.label,\n label: opts.label,\n attempts,\n classification: details.classification,\n lastError: {\n name: details.name,\n message: details.message,\n code: details.code,\n causeCode: details.causeCode,\n },\n },\n error,\n )\n}\n\nfunction parseRetryAfter(headerValue: string | null): number | undefined {\n if (!headerValue) return undefined\n const secs = Number(headerValue)\n if (Number.isFinite(secs)) return Math.max(0, secs * 1000)\n const dateMs = Date.parse(headerValue)\n if (Number.isFinite(dateMs)) return Math.max(0, dateMs - Date.now())\n return undefined\n}\n\n/** Sleep that resolves early (does not reject) when `signal` aborts — the\n * retry loop re-checks `signal.aborted` at the top and throws there. */\nfunction abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (ms <= 0) return Promise.resolve()\n return new Promise<void>((resolve) => {\n let settled = false\n const done = (): void => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n signal?.removeEventListener(\"abort\", done)\n resolve()\n }\n const timer = setTimeout(done, ms)\n if (signal) {\n if (signal.aborted) {\n done()\n return\n }\n signal.addEventListener(\"abort\", done, { once: true })\n }\n })\n}\n\n/**\n * Run `doFetch` with bounded transient-failure retries. `doFetch` is a\n * thunk so each attempt issues a FRESH request (bodies can't be replayed\n * from a consumed stream). Returns the final `Response` — which may still\n * carry a retryable status if all attempts are exhausted (the caller\n * handles that as it would a single-shot failure).\n */\nexport async function fetchWithTransientRetry(\n doFetch: (attempt: number) => Promise<Response>,\n opts: TransientRetryOpts = {},\n): Promise<Response> {\n const attempts = Math.max(1, opts.attempts ?? 3)\n const retryStatuses = opts.retryStatuses ?? DEFAULT_RETRY_STATUSES\n const baseDelayMs = opts.baseDelayMs ?? 250\n const maxDelayMs = opts.maxDelayMs ?? 4000\n const { signal, label } = opts\n\n for (let attempt = 1; ; attempt++) {\n if (signal?.aborted) {\n throw new DOMException(\"This operation was aborted\", \"AbortError\")\n }\n\n let res: Response | undefined\n let caught: unknown\n try {\n res = await doFetch(attempt)\n } catch (err) {\n caught = err\n }\n\n // Success or a non-retryable status → done.\n if (res && !retryStatuses.includes(res.status)) return res\n\n // A thrown error: a user cancel fails fast; otherwise only retry the\n // transient network/timeout class.\n if (caught !== undefined) {\n if (signal?.aborted) throw caught\n const details = classifyTransportError(caught)\n if (details.classification === \"deterministic\") {\n throw transportExhaustion(caught, attempt, opts, details)\n }\n if (details.classification !== \"transient\") throw caught\n }\n\n // Out of attempts → return the last error response (or rethrow).\n if (attempt >= attempts) {\n if (res) return res\n const details = classifyTransportError(caught)\n throw transportExhaustion(caught, attempt, opts, details)\n }\n\n // Free the connection before retrying a retryable-status response.\n const retryAfterMs = res\n ? parseRetryAfter(res.headers.get(\"retry-after\"))\n : undefined\n if (res?.body) {\n try {\n await res.body.cancel()\n } catch {\n /* already torn down */\n }\n }\n\n // Full jitter (random within the exponential cap), Retry-After wins.\n const expCap = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1))\n const delay = Math.min(\n maxDelayMs,\n retryAfterMs ?? Math.round(Math.random() * expCap),\n )\n if (label) {\n const why = res\n ? `HTTP ${res.status}`\n : (caught as { name?: string } | undefined)?.name ?? \"error\"\n consola.debug(\n `[upstream-retry] ${label}: attempt ${attempt}/${attempts} failed (${why}); retrying in ${delay}ms`,\n )\n }\n await abortableSleep(delay, signal)\n }\n}\n\n/** Extract an HTTP status from a thrown error (HTTPError carries\n * `.response.status`; others may carry `.status`/`.statusCode`; last\n * resort parses `\"HTTP <code>\"` from the message). */\nfunction errorStatus(err: unknown): number | undefined {\n const e = err as\n | {\n status?: unknown\n statusCode?: unknown\n response?: { status?: unknown }\n message?: string\n }\n | undefined\n for (const v of [e?.status, e?.statusCode, e?.response?.status]) {\n if (typeof v === \"number\") return v\n }\n const m = /\\bHTTP (\\d{3})\\b/.exec(e?.message ?? \"\")\n return m ? Number(m[1]) : undefined\n}\n\n/**\n * Generic transient-retry for a non-`Response`-returning call (e.g. the\n * Copilot service clients, which throw `HTTPError` on non-OK and throw on\n * network errors). Retries `fn()` when it throws a transient error — an\n * `HTTPError`-like with a retryable status (429/5xx) OR a transient\n * network/timeout error — using the same backoff + abort semantics as\n * `fetchWithTransientRetry`. Never retries a deterministic 4xx (incl.\n * 401), a non-transient throw, or a user cancel.\n */\nexport async function withTransientRetry<T>(\n fn: (attempt: number) => Promise<T>,\n opts: TransientRetryOpts = {},\n): Promise<T> {\n const attempts = Math.max(1, opts.attempts ?? 3)\n const retryStatuses = opts.retryStatuses ?? DEFAULT_RETRY_STATUSES\n const baseDelayMs = opts.baseDelayMs ?? 250\n const maxDelayMs = opts.maxDelayMs ?? 4000\n const { signal, label } = opts\n\n for (let attempt = 1; ; attempt++) {\n if (signal?.aborted) {\n throw new DOMException(\"This operation was aborted\", \"AbortError\")\n }\n try {\n return await fn(attempt)\n } catch (err) {\n if (signal?.aborted) throw err\n const status = errorStatus(err)\n const details = classifyTransportError(err)\n if (status !== undefined) {\n if (!retryStatuses.includes(status) || attempt >= attempts) throw err\n } else {\n if (details.classification === \"deterministic\") {\n throw transportExhaustion(err, attempt, opts, details)\n }\n if (details.classification !== \"transient\") throw err\n if (attempt >= attempts) {\n throw transportExhaustion(err, attempt, opts, details)\n }\n }\n\n const retryAfterMs = parseRetryAfter(\n (err as { response?: { headers?: { get?: (k: string) => string | null } } })\n ?.response?.headers?.get?.(\"retry-after\") ?? null,\n )\n const expCap = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1))\n const delay = Math.min(\n maxDelayMs,\n retryAfterMs ?? Math.round(Math.random() * expCap),\n )\n if (label) {\n consola.debug(\n `[upstream-retry] ${label}: attempt ${attempt}/${attempts} threw (${\n status !== undefined ? `HTTP ${status}` : (err as { name?: string })?.name ?? \"error\"\n }); retrying in ${delay}ms`,\n )\n }\n await abortableSleep(delay, signal)\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,MAAM,yBAAgD;CAAC;CAAK;CAAK;CAAK;CAAK;AAAG;AAC9E,MAAM,wBAAwB;AAC9B,MAAM,kCAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CAIA;CAIA;CACA;CACA;AACF,CAAC;;;;;;;;;;;;;;;;AAiBD,MAAM,6BAA6B;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;;;;;;;AAkBA,MAAM,yBAAyB,CAAC,gBAAgB;AAChD,MAAM,sCAAsB,IAAI,IAAI;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,gBACJ;AACF,MAAM,uBACJ;AACF,MAAM,kBACJ;AAwBF,IAAa,2BAAb,cAA8C,MAAM;CACzC;CACA;CACA;CACA;CACA;CAET,YAAY,UAAuC,OAAgB;EACjE,MAAM,SAAS,SAAS,YAAY,SAAS,SAAS;E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M,aAAa,KAAK,cAAc;CACtC,MAAM,EAAE,QAAQ,UAAU;CAE1B,KAAK,IAAI,UAAU,IAAK,WAAW;EACjC,IAAI,QAAQ,SACV,MAAM,IAAI,aAAa,8BAA8B,YAAY;EAEnE,IAAI;GACF,OAAO,MAAM,GAAG,OAAO;EACzB,SAAS,KAAK;GACZ,IAAI,QAAQ,SAAS,MAAM;GAC3B,MAAM,SAAS,YAAY,GAAG;GAC9B,MAAM,UAAU,uBAAuB,GAAG;GAC1C,IAAI,WAAW,KAAA,GACT;QAAA,CAAC,cAAc,SAAS,MAAM,KAAK,WAAW,UAAU,MAAM;GAAA,OAC7D;IACL,IAAI,QAAQ,mBAAmB,iBAC7B,MAAM,oBAAoB,KAAK,SAAS,MAAM,OAAO;IAEvD,IAAI,QAAQ,mBAAmB,aAAa,MAAM;IAClD,IAAI,WAAW,UACb,MAAM,oBAAoB,KAAK,SAAS,MAAM,OAAO;GAEzD;GAEA,MAAM,eAAe,gBAClB,KACG,UAAU,SAAS,MAAM,aAAa,KAAK,IACjD;GACA,MAAM,SAAS,KAAK,IAAI,YAAY,cAAc,MAAM,UAAU,EAAE;GACpE,MAAM,QAAQ,KAAK,IACjB,YACA,gBAAgB,KAAK,MAAM,KAAK,OAAO,IAAI,MAAM,CACnD;GACA,IAAI,OACF,QAAQ,MACN,oBAAoB,MAAM,YAAY,QAAQ,GAAG,SAAS,UACxD,WAAW,KAAA,IAAY,QAAQ,WAAY,KAA2B,QAAQ,QAC/E,iBAAiB,MAAM,GAC1B;GAEF,MAAM,eAAe,OAAO,MAAM;EACpC;CACF;AACF"}
@@ -1,8 +1,8 @@
1
- import { n as explicitPackageRoot } from "./package-root-B-osctCk.js";
1
+ import { n as explicitPackageRoot } from "./package-root-BXgdIM3q.js";
2
2
  import { readFileSync } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
- //#region src/lib/version.ts
5
+ // src/lib/version.ts
6
6
  /**
7
7
  * Read this binary's published version from package.json at runtime.
8
8
  *
@@ -38,7 +38,6 @@ function getPackageVersion() {
38
38
  } catch {}
39
39
  return "unknown";
40
40
  }
41
- //#endregion
42
41
  export { getPackageVersion as t };
43
42
 
44
- //# sourceMappingURL=version-C8x2hQrZ.js.map
43
+ //# sourceMappingURL=version-CTqwKr26.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version-C8x2hQrZ.js","names":[],"sources":["../src/lib/version.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\"\nimport { dirname, join } from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\n\nimport { explicitPackageRoot } from \"./package-root\"\n\n/**\n * Read this binary's published version from package.json at runtime.\n *\n * Done at runtime (not baked at build time) because release.yml builds\n * BEFORE `npm version patch` bumps the version — a build-time inline\n * would always ship the pre-bump value. The npm tarball ships package.json\n * alongside `dist/`, so a sibling-up lookup from import.meta.url resolves\n * cleanly in both dev (`src/lib/`) and bundled (`dist/`) layouts.\n *\n * The sibling-up walk fails for the relocated hook launcher, which runs from\n * `<APP_DIR>/hooks/` with no package.json above it — hence the explicit root\n * tried first. Baking the version into that bundle instead would reintroduce\n * exactly the pre-bump staleness the runtime read exists to avoid, so the\n * launcher is handed a path to read rather than a value to trust.\n *\n * Returns `\"unknown\"` if package.json can't be located or parsed —\n * never throws, so the CLI never fails to start over version reporting.\n */\nexport function getPackageVersion(): string {\n try {\n const here = dirname(fileURLToPath(import.meta.url))\n const explicit = explicitPackageRoot()\n const candidates = [\n // Relocated hook launcher — the root was baked into its command line.\n ...(explicit ? [join(explicit, \"package.json\")] : []),\n // src/lib/version.ts → ../../package.json (dev)\n // dist/main.js → ../package.json (built npm tarball)\n // dist/<chunk>.js → ../package.json (split bundle)\n join(here, \"..\", \"..\", \"package.json\"),\n join(here, \"..\", \"package.json\"),\n ]\n for (const path of candidates) {\n try {\n const raw = readFileSync(path, \"utf8\")\n const parsed = JSON.parse(raw) as { version?: unknown; name?: unknown }\n if (\n typeof parsed.version === \"string\"\n && (parsed.name === \"github-router\"\n || parsed.name === \"@animeshkundu/github-router\")\n ) {\n return parsed.version\n }\n } catch {\n // Try next candidate.\n }\n }\n } catch {\n // Fall through to \"unknown\".\n }\n return \"unknown\"\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,oBAA4B;CAC1C,IAAI;EACF,MAAM,OAAO,QAAQ,cAAc,YAAY,GAAG,CAAC;EACnD,MAAM,WAAW,oBAAoB;EACrC,MAAM,aAAa;GAEjB,GAAI,WAAW,CAAC,KAAK,UAAU,cAAc,CAAC,IAAI,CAAC;GAInD,KAAK,MAAM,MAAM,MAAM,cAAc;GACrC,KAAK,MAAM,MAAM,cAAc;EACjC;EACA,KAAK,MAAM,QAAQ,YACjB,IAAI;GACF,MAAM,MAAM,aAAa,MAAM,MAAM;GACrC,MAAM,SAAS,KAAK,MAAM,GAAG;GAC7B,IACE,OAAO,OAAO,YAAY,aACtB,OAAO,SAAS,mBACf,OAAO,SAAS,gCAErB,OAAO,OAAO;EAElB,QAAQ,CAER;CAEJ,QAAQ,CAER;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"version-CTqwKr26.js","names":[],"sources":["../src/lib/version.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\"\nimport { dirname, join } from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\n\nimport { explicitPackageRoot } from \"./package-root\"\n\n/**\n * Read this binary's published version from package.json at runtime.\n *\n * Done at runtime (not baked at build time) because release.yml builds\n * BEFORE `npm version patch` bumps the version — a build-time inline\n * would always ship the pre-bump value. The npm tarball ships package.json\n * alongside `dist/`, so a sibling-up lookup from import.meta.url resolves\n * cleanly in both dev (`src/lib/`) and bundled (`dist/`) layouts.\n *\n * The sibling-up walk fails for the relocated hook launcher, which runs from\n * `<APP_DIR>/hooks/` with no package.json above it — hence the explicit root\n * tried first. Baking the version into that bundle instead would reintroduce\n * exactly the pre-bump staleness the runtime read exists to avoid, so the\n * launcher is handed a path to read rather than a value to trust.\n *\n * Returns `\"unknown\"` if package.json can't be located or parsed —\n * never throws, so the CLI never fails to start over version reporting.\n */\nexport function getPackageVersion(): string {\n try {\n const here = dirname(fileURLToPath(import.meta.url))\n const explicit = explicitPackageRoot()\n const candidates = [\n // Relocated hook launcher — the root was baked into its command line.\n ...(explicit ? [join(explicit, \"package.json\")] : []),\n // src/lib/version.ts → ../../package.json (dev)\n // dist/main.js → ../package.json (built npm tarball)\n // dist/<chunk>.js → ../package.json (split bundle)\n join(here, \"..\", \"..\", \"package.json\"),\n join(here, \"..\", \"package.json\"),\n ]\n for (const path of candidates) {\n try {\n const raw = readFileSync(path, \"utf8\")\n const parsed = JSON.parse(raw) as { version?: unknown; name?: unknown }\n if (\n typeof parsed.version === \"string\"\n && (parsed.name === \"github-router\"\n || parsed.name === \"@animeshkundu/github-router\")\n ) {\n return parsed.version\n }\n } catch {\n // Try next candidate.\n }\n }\n } catch {\n // Fall through to \"unknown\".\n }\n return \"unknown\"\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,oBAA4B;CAC1C,IAAI;EACF,MAAM,OAAO,QAAQ,cAAc,YAAY,GAAG,CAAC;EACnD,MAAM,WAAW,oBAAoB;EACrC,MAAM,aAAa;GAEjB,GAAI,WAAW,CAAC,KAAK,UAAU,cAAc,CAAC,IAAI,CAAC;GAInD,KAAK,MAAM,MAAM,MAAM,cAAc;GACrC,KAAK,MAAM,MAAM,cAAc;EACjC;EACA,KAAK,MAAM,QAAQ,YACjB,IAAI;GACF,MAAM,MAAM,aAAa,MAAM,MAAM;GACrC,MAAM,SAAS,KAAK,MAAM,GAAG;GAC7B,IACE,OAAO,OAAO,YAAY,aACtB,OAAO,SAAS,mBACf,OAAO,SAAS,gCAErB,OAAO,OAAO;EAElB,QAAQ,CAER;CAEJ,QAAQ,CAER;CACA,OAAO;AACT"}
@@ -1,5 +1,5 @@
1
- import { t as buildSelfCommand } from "./self-invocation-BtcGj-lY.js";
2
- //#region src/lib/worker-dispatch.ts
1
+ import { t as buildSelfCommand } from "./self-invocation-DMUnXVGT.js";
2
+ // src/lib/worker-dispatch.ts
3
3
  /**
4
4
  * Frozen contract for the NON-BLOCKING workers surface.
5
5
  *
@@ -246,7 +246,6 @@ Object.freeze({
246
246
  worktree: false
247
247
  })
248
248
  });
249
- //#endregion
250
249
  export { dispatcherAgentName as a, dispatcherTools as c, decideWorkerGuard as i, guardToolMatcher as l, activeDispatchModes as n, dispatcherDescription as o, buildWorkerGuardHookCommand as r, dispatcherPrompt as s, ALL_WORKER_DISPATCH_MODES as t, parseModesCsv as u };
251
250
 
252
- //# sourceMappingURL=worker-dispatch-B1w2qfjX.js.map
251
+ //# sourceMappingURL=worker-dispatch-C7RtNOXv.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"worker-dispatch-B1w2qfjX.js","names":[],"sources":["../src/lib/worker-dispatch.ts"],"sourcesContent":["/**\n * Frozen contract for the NON-BLOCKING workers surface.\n *\n * The `workers` MCP tools (`explore`/`implement`/`review`/`plan`/`test`, and\n * `browse` when the browse agent is enabled) BLOCK the caller for up to 6h\n * (`runWorkerAgent`). The MAIN Claude Code agent must never block on one, so a\n * per-mode `worker-*` DISPATCHER SUBAGENT — which Claude Code runs in the\n * background and reports on via a completion notification — is the only\n * sanctioned way to run a worker. This module is the single source of truth for\n * three things that must never drift:\n *\n * 1. the tool → dispatcher map (`mcp__<workersKey>__<mode>` ↔ `worker-<mode>`),\n * 2. the PreToolUse GUARD decision that denies a raw worker call from the main\n * agent (or any non-dispatcher subagent) and redirects it to the matching\n * `worker-*` agent, allowing it only from the dispatcher itself, and\n * 3. the dispatcher subagent bodies (description / system prompt / `tools:`\n * allowlist).\n *\n * Imported by `codex-mcp-config.ts` (dispatcher `.md` generation + the hook\n * command it bakes into settings.json) AND `internal-worker-guard.ts` (the\n * runtime PreToolUse hook). Keeping the map here means the settings matcher, the\n * redirect target, the dispatcher names, and the `tools:` allowlist are all\n * derived from one place.\n *\n * Discrimination mechanism: a Claude Code PreToolUse payload carries\n * `agent_type` (the invoking subagent's name) ONLY inside a subagent context —\n * absent for the top-level/main agent. So `agent_type === \"worker-<mode>\"` is\n * the reliable \"this call came from the dispatcher, allow it\" signal, and its\n * absence (or any other value) means \"main agent or an unrelated subagent →\n * deny\". This is the SAME field this repo's Stop / prompt-submit hooks already\n * key off (`isSubagentContext` in `orchestration/stop-gate-policy.ts`); the\n * guard here is the inverse (allow-only-dispatcher rather than skip-any-sub).\n */\n\nimport { buildSelfCommand, type SelfInvocation } from \"./hook-launcher/self-invocation\"\n\n/** The five always-available worker modes (gated by `workerToolsEnabled()`). */\nexport const CORE_WORKER_MODES = [\n \"explore\",\n \"implement\",\n \"review\",\n \"plan\",\n \"test\",\n] as const\n\n/** The browse worker mode, gated separately by `browseAgentEnabled()`. */\nexport const BROWSE_WORKER_MODE = \"browse\" as const\n\nexport type CoreWorkerMode = (typeof CORE_WORKER_MODES)[number]\nexport type WorkerDispatchMode = CoreWorkerMode | typeof BROWSE_WORKER_MODE\n\n/** Every mode the surface can expose — used to build the sweep-regex allowlist\n * and to validate `--modes`. Order is stable (core first, browse last). */\nexport const ALL_WORKER_DISPATCH_MODES: ReadonlyArray<WorkerDispatchMode> = [\n ...CORE_WORKER_MODES,\n BROWSE_WORKER_MODE,\n]\n\n/** The dispatcher subagent name for a mode, e.g. `implement` → `worker-implement`. */\nexport function dispatcherAgentName(mode: WorkerDispatchMode): string {\n return `worker-${mode}`\n}\n\n/** Every possible dispatcher subagent name (used by the stale-`.md` sweep). */\nexport const ALL_DISPATCHER_AGENT_NAMES: ReadonlyArray<string> =\n ALL_WORKER_DISPATCH_MODES.map(dispatcherAgentName)\n\n/** The MCP tool name the workers server exposes for a mode under the resolved key. */\nexport function workerToolName(workersKey: string, mode: WorkerDispatchMode): string {\n return `mcp__${workersKey}__${mode}`\n}\n\n/** The active dispatch modes for a launch: the five core modes plus `browse`\n * only when the browse agent is enabled. */\nexport function activeDispatchModes(opts: { browse: boolean }): Array<WorkerDispatchMode> {\n return opts.browse ? [...CORE_WORKER_MODES, BROWSE_WORKER_MODE] : [...CORE_WORKER_MODES]\n}\n\nfunction escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n}\n\n/**\n * The Claude Code PreToolUse `matcher` (a regex over the tool name) that scopes\n * the guard hook to exactly the active worker tools — nothing else invokes the\n * hook. Anchored + exact-alternation so an unrelated `mcp__<key>__status` (a\n * future non-blocking tool with no dispatcher) is never matched, hence never\n * denied.\n */\nexport function guardToolMatcher(workersKey: string, modes: ReadonlyArray<WorkerDispatchMode>): string {\n const alt = modes.map((m) => escapeRegex(m)).join(\"|\")\n return `^mcp__${escapeRegex(workersKey)}__(${alt})$`\n}\n\n/** Parse the worker mode out of a tool name for the resolved key, or null if it\n * isn't one of the recognized worker tools. */\nexport function parseWorkerToolCall(\n toolName: string,\n workersKey: string,\n modes: ReadonlyArray<WorkerDispatchMode>,\n): WorkerDispatchMode | null {\n const prefix = `mcp__${workersKey}__`\n if (!toolName.startsWith(prefix)) return null\n const rest = toolName.slice(prefix.length)\n return (modes as ReadonlyArray<string>).includes(rest) ? (rest as WorkerDispatchMode) : null\n}\n\n/** The `permissionDecisionReason` shown to the model on a deny, steering it to\n * the matching background dispatcher. `mode` is null when the payload was\n * unparseable (fail-closed generic message). */\nexport function guardDenyReason(mode: WorkerDispatchMode | null): string {\n const target = mode\n ? `Agent(subagent_type: \"${dispatcherAgentName(mode)}\", prompt: <your worker brief>)`\n : `the matching background \\`worker-*\\` agent via the Agent tool`\n return (\n \"Workers run as background subagents in this session so your turn never blocks. \"\n + `Re-issue this as ${target}. `\n + \"It returns immediately and delivers the worker's result as a completion notification — \"\n + \"do not call the raw `mcp__…__` worker tool from the main thread.\"\n )\n}\n\n/** The stdout JSON a PreToolUse hook prints to DENY a tool call. */\nexport function guardDenyOutput(mode: WorkerDispatchMode | null): string {\n return JSON.stringify({\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: guardDenyReason(mode),\n },\n })\n}\n\nexport interface WorkerGuardResult {\n /** JSON to print to stdout (a deny decision), or null to ALLOW (print nothing). */\n output: string | null\n /** Machine-readable verdict for tests/telemetry. */\n verdict: \"allow-dispatcher\" | \"allow-non-worker\" | \"deny-main\" | \"deny-malformed\"\n}\n\n/**\n * Pure PreToolUse guard decision. Given the raw stdin payload, the resolved\n * workers key, and the active modes, decide whether to DENY the tool call.\n *\n * Rules (fail toward protecting the \"main never blocks\" invariant):\n * - Payload unparseable / no string `tool_name`: the matcher only fires this\n * hook for worker tools, so a payload we can't read is still a worker call\n * → DENY (fail closed, generic redirect).\n * - `tool_name` is not a recognized worker tool for this key: ALLOW (not a\n * tool we guard — never deny a non-worker tool).\n * - `agent_type` equals one of the active dispatcher names: ALLOW (the call\n * came from the dispatcher subagent that is meant to run the worker).\n * - Otherwise (main agent: `agent_type` absent; or a non-dispatcher subagent):\n * DENY with a redirect to the matching `worker-<mode>` agent.\n */\nexport function decideWorkerGuard(input: {\n stdin: string\n workersKey: string\n modes: ReadonlyArray<WorkerDispatchMode>\n}): WorkerGuardResult {\n let payload: { tool_name?: unknown; agent_type?: unknown } | null = null\n try {\n const parsed: unknown = JSON.parse(input.stdin)\n if (parsed && typeof parsed === \"object\") {\n payload = parsed as { tool_name?: unknown; agent_type?: unknown }\n }\n } catch {\n payload = null\n }\n\n const toolName = typeof payload?.tool_name === \"string\" ? payload.tool_name : null\n if (!toolName) {\n // Fail CLOSED: the settings matcher only routes worker-tool calls here, so\n // an unreadable payload is still a worker call we must not let through.\n return { output: guardDenyOutput(null), verdict: \"deny-malformed\" }\n }\n\n const mode = parseWorkerToolCall(toolName, input.workersKey, input.modes)\n if (mode === null) {\n // Not one of the worker tools we guard (matcher over-fired, or a future\n // non-blocking tool under the same server) → allow the normal flow.\n return { output: null, verdict: \"allow-non-worker\" }\n }\n\n const agentType = payload?.agent_type\n if (typeof agentType === \"string\" && agentType === dispatcherAgentName(mode)) {\n // The call originated inside the `worker-<mode>` dispatcher subagent that is\n // meant to run THIS worker. Require an exact mode match (not just \"any\n // dispatcher\"), so a read-only `worker-explore` can't invoke the\n // write-capable `implement` worker if it misroutes or is prompt-injected.\n // If a matching dispatcher is still denied, the payload that reached this\n // hook did not carry this exact top-level `agent_type`, or a different\n // PreToolUse hook denied the call after this guard allowed it.\n return { output: null, verdict: \"allow-dispatcher\" }\n }\n\n // Main agent (agent_type absent), a non-dispatcher subagent, or a dispatcher\n // for a DIFFERENT mode → deny + redirect. Denying non-dispatcher subagents\n // too closes the transitive-blocking hole (a foreground subagent that blocked\n // on a worker would transitively block the main agent).\n return { output: guardDenyOutput(mode), verdict: \"deny-main\" }\n}\n\n// ─── Dispatcher subagent bodies ──────────────────────────────────────────────\n\n/** One-line human description shown to the lead when picking a subagent. Uses\n * the documented \"Use proactively\" auto-delegation idiom. */\nexport function dispatcherDescription(mode: WorkerDispatchMode): string {\n const blurb: Record<WorkerDispatchMode, string> = {\n explore:\n \"Non-blocking `explore` worker: dispatches a read-only autonomous worker (its own context) in the background and delivers its summary as a completion notification.\",\n implement:\n \"Non-blocking `implement` worker: dispatches an autonomous coding worker (read/write/bash) that ALWAYS runs in an isolated git worktree and returns the diff (for in-place edits use the `implementer` subagent), in the background, and delivers its result as a completion notification.\",\n review:\n \"Non-blocking `review` worker: the backgrounded counterpart of the `reviewer` subagent, running a cross-lab model. It has explore's read-and-search tools plus `bash`, so it can VERIFY rather than only read: reproduce a failure, or run the build or suite to check a claim. By default it works directly in the workspace, where it gets no edit/write tools but `bash` still runs real commands, so a build or test it invokes can touch the tree. Pass `worktree: true` to run it isolated in a replayed git worktree instead, which also lets it author a throwaway probe test. Returns severity-ranked findings with file:line and a go/no-go, as a completion notification. Use `explore` instead when you just need to find or understand something.\",\n plan:\n \"Non-blocking `plan` worker: dispatches a read-only planner that returns an ordered implementation plan, in the background, and delivers it as a completion notification.\",\n test:\n \"Non-blocking `test` worker: dispatches an independent test author (in an isolated git worktree) that writes tests trying to break the implementation, in the background, and delivers pass/fail as a completion notification.\",\n browse:\n \"Non-blocking `browse` worker: dispatches an autonomous browser agent in the background and delivers its result as a completion notification.\",\n }\n return (\n `${blurb[mode]} Use proactively for any ${mode}-mode worker task so a long run never blocks your turn: `\n + \"it returns immediately and notifies you when done.\"\n )\n}\n\n/** The dispatcher subagent's full system prompt: call the one worker tool once,\n * relay verbatim, do nothing else. */\nexport function dispatcherPrompt(mode: WorkerDispatchMode, workersKey: string): string {\n const tool = workerToolName(workersKey, mode)\n const briefField = mode === \"browse\" ? \"task\" : \"prompt\"\n const briefDescription = mode === \"browse\" ? \"the lead's browse task, copied verbatim\" : \"the lead's worker brief, copied verbatim\"\n const modeSpecificPassThrough = mode === \"browse\"\n ? \"\\n - `sessionId` (optional): pass through if the lead specified one\"\n : mode === \"review\"\n ? \"\\n - `worktree` (optional): pass `true` only if the lead asked for an isolated review\"\n : \"\"\n return [\n `# Subagent: ${dispatcherAgentName(mode)}`,\n \"\",\n `You are a thin DISPATCHER for the \\`${mode}\\` worker. You run in the background so the`,\n \"lead agent's turn is never blocked while the (up-to-6-hour) worker runs.\",\n \"\",\n \"## Your only job\",\n \"\",\n `Call the \\`${tool}\\` tool EXACTLY ONCE, passing through the fields from the lead's brief:`,\n ` - \\`${briefField}\\`: ${briefDescription}`,\n \" - `workspace`: ALWAYS pass this. Use the absolute path of the directory the\",\n \" lead named, or, when the lead named none, your own current working\",\n \" directory. The proxy runs as a separate long-lived process and cannot see\",\n \" where you are, so if you omit this it falls back to the session's directory,\",\n \" which may be a different checkout than the files the lead is asking about.\",\n \" - `model` / `thinking` (optional): only if the lead specified them\",\n \" - `maxWallClockMs` (optional): per-call wall-clock budget in ms, if the lead specified one\"\n + modeSpecificPassThrough,\n \"\",\n \"When the tool returns, output its result VERBATIM as your final message. That final\",\n \"message is what the lead receives in the completion notification — it IS the result.\",\n \"\",\n \"## Hard rules\",\n \"\",\n \"- Call the worker tool exactly once. Do not retry on a normal (non-error) return.\",\n \"- Do NOT attempt the task yourself, do NOT read/edit files, do NOT run other tools.\",\n \"- Do NOT spawn other agents (you have no Agent tool and must not try to gain one).\",\n \"- Do NOT summarize, paraphrase, or add commentary — relay the worker output verbatim.\",\n \"- If the worker returns an error, relay that error verbatim (do not mask it).\",\n ].join(\"\\n\")\n}\n\n/** The `tools:` frontmatter allowlist for a dispatcher: the workers MCP server\n * wildcard (`mcp__<workersKey>__*`). Claude Code's `tools:` field supports\n * MCP patterns only at SERVER granularity (`mcp__<server>__*`), not individual\n * tool names, so this grants exactly the workers tools and NOTHING else — no\n * Agent/Task (so it cannot spawn further agents → no recursion), no Read/Bash\n * (so it cannot do extra work). The dispatcher's prompt narrows it to the one\n * mode; the guard allows only the exact dispatcher for that worker mode. */\nexport function dispatcherTools(_mode: WorkerDispatchMode, workersKey: string): Array<string> {\n return [`mcp__${workersKey}__*`]\n}\n\n/**\n * Build the shell command Claude Code runs for the workers `PreToolUse` guard\n * hook — the running github-router via its node/bun binary so it works\n * regardless of PATH. Mirrors `buildPromptSubmitHookCommand`.\n *\n * The resolved `workersKey` and the active `modes` are baked into the command\n * ARGS (not env): `mergeStopHookIntoSettings` dedups hooks by the command\n * string only, so baking the key/modes makes a changed resolution produce a\n * DISTINCT command — no stale-matcher entry can survive from a prior launch.\n */\nexport function buildWorkerGuardHookCommand(\n invocation: SelfInvocation,\n workersKey: string,\n modes: ReadonlyArray<WorkerDispatchMode>,\n): string {\n const q = (s: string): string => `\"${s}\"`\n const args = `internal-worker-guard --workers-key ${q(workersKey)} --modes ${q(modes.join(\",\"))}`\n return buildSelfCommand(invocation, args)\n}\n\n/** Parse a `--modes` CSV back into validated modes (drops unknown tokens). */\nexport function parseModesCsv(csv: string | undefined): Array<WorkerDispatchMode> {\n if (!csv) return [...CORE_WORKER_MODES]\n const known = new Set<string>(ALL_WORKER_DISPATCH_MODES)\n const out = csv\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => known.has(s)) as Array<WorkerDispatchMode>\n return out.length > 0 ? out : [...CORE_WORKER_MODES]\n}\n\n// ─── Pipeline skill worker configs (additive, non-guard) ─────────────────────\n\n/**\n * Bounded worker configs for the `/gh-gather-context`, `/gh-plan`, and\n * `/gh-implement` pipeline skills. These reuse the existing\n * `worker-explore` / `worker-implement` / `worker-review` / `worker-plan`\n * dispatchers (so the PreToolUse guard above is untouched); the configs only\n * pin the 200K-default model alias, the wall-clock budget, and the worktree\n * policy each skill brief must use. All models are bare slugs (no `[1m]`).\n *\n * No output-token cap is listed: worker tools accept `{prompt, model,\n * thinking, workspace, maxWallClockMs, worktree}` and have no output-token\n * parameter, so such a cap would be unenforced. `timeoutMs` IS enforceable:\n * the skill bodies instruct the lead to pass it as the real `maxWallClockMs`\n * worker arg (honored by `worker-agent/budget.ts`, clamped to the per-call\n * ceiling in `peer-mcp-personas.ts`).\n */\nexport type SkillWorkerRole =\n | \"gather-context-explore\"\n | \"implement-task\"\n | \"review-pass1\"\n | \"review-pass2\"\n\nexport interface SkillWorkerConfig {\n /** Existing dispatcher to reuse (guard-compatible, no new modes). */\n dispatcher: WorkerDispatchMode\n /** Router-owned model alias (200K default, effort pinned). */\n modelAlias: string\n /**\n * Wall-clock budget per worker call, passed by the lead as the real\n * `maxWallClockMs` worker arg (well under the 6h per-call ceiling).\n */\n timeoutMs: number\n /** Whether the worker runs in an isolated git worktree. */\n worktree: boolean\n}\n\nexport const SKILL_WORKER_CONFIGS: Readonly<Record<SkillWorkerRole, SkillWorkerConfig>> = Object.freeze({\n \"gather-context-explore\": Object.freeze({\n dispatcher: \"explore\",\n modelAlias: \"gh-router-skill-gather-context-explore-high\",\n timeoutMs: 180_000,\n worktree: false,\n }),\n \"implement-task\": Object.freeze({\n dispatcher: \"implement\",\n modelAlias: \"gh-router-skill-implement-task-max\",\n timeoutMs: 600_000,\n worktree: true,\n }),\n \"review-pass1\": Object.freeze({\n dispatcher: \"review\",\n modelAlias: \"gh-router-skill-review-pass1-max\",\n timeoutMs: 300_000,\n worktree: false,\n }),\n \"review-pass2\": Object.freeze({\n dispatcher: \"review\",\n modelAlias: \"gh-router-skill-review-pass2-medium\",\n timeoutMs: 300_000,\n worktree: false,\n }),\n})\n\nexport function skillWorkerConfig(role: SkillWorkerRole): SkillWorkerConfig {\n return SKILL_WORKER_CONFIGS[role]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAa,qBAAqB;;;AAOlC,MAAa,4BAA+D,CAC1E,GAAG,mBACH,kBACF;;AAGA,SAAgB,oBAAoB,MAAkC;CACpE,OAAO,UAAU;AACnB;AAIE,0BAA0B,IAAI,mBAAmB;;AAGnD,SAAgB,eAAe,YAAoB,MAAkC;CACnF,OAAO,QAAQ,WAAW,IAAI;AAChC;;;AAIA,SAAgB,oBAAoB,MAAsD;CACxF,OAAO,KAAK,SAAS,CAAC,GAAG,mBAAmB,kBAAkB,IAAI,CAAC,GAAG,iBAAiB;AACzF;AAEA,SAAS,YAAY,GAAmB;CACtC,OAAO,EAAE,QAAQ,uBAAuB,MAAM;AAChD;;;;;;;;AASA,SAAgB,iBAAiB,YAAoB,OAAkD;CACrG,MAAM,MAAM,MAAM,KAAK,MAAM,YAAY,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG;CACrD,OAAO,SAAS,YAAY,UAAU,EAAE,KAAK,IAAI;AACnD;;;AAIA,SAAgB,oBACd,UACA,YACA,OAC2B;CAC3B,MAAM,SAAS,QAAQ,WAAW;CAClC,IAAI,CAAC,SAAS,WAAW,MAAM,GAAG,OAAO;CACzC,MAAM,OAAO,SAAS,MAAM,OAAO,MAAM;CACzC,OAAQ,MAAgC,SAAS,IAAI,IAAK,OAA8B;AAC1F;;;;AAKA,SAAgB,gBAAgB,MAAyC;CAIvE,OACE,mGAJa,OACX,yBAAyB,oBAAoB,IAAI,EAAE,mCACnD,gEAG2B;AAIjC;;AAGA,SAAgB,gBAAgB,MA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AAM;EAC1B;EACA;EACA;EACA;EACA;EACA;EACA,iGACI;EACJ;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC,CAAC,KAAK,IAAI;AACb;;;;;;;;AASA,SAAgB,gBAAgB,OAA2B,YAAmC;CAC5F,OAAO,CAAC,QAAQ,WAAW,IAAI;AACjC;;;;;;;;;;;AAYA,SAAgB,4BACd,YACA,YACA,OACQ;CACR,MAAM,KAAK,MAAsB,IAAI,EAAE;CACvC,MAAM,OAAO,uCAAuC,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,KAAK,GAAG,CAAC;CAC9F,OAAO,iBAAiB,YAAY,IAAI;AAC1C;;AAGA,SAAgB,cAAc,KAAoD;CAChF,IAAI,CAAC,KAAK,OAAO,CAAC,GAAG,iBAAiB;CACtC,MAAM,QAAQ,IAAI,IAAY,yBAAyB;CACvD,MAAM,MAAM,IACT,MAAM,GAAG,CAAC,CACV,KAAK,MAAM,EAAE,KAAK,CAAC,CAAC,CACpB,QAAQ,MAAM,MAAM,IAAI,CAAC,CAAC;CAC7B,OAAO,IAAI,SAAS,IAAI,MAAM,CAAC,GAAG,iBAAiB;AACrD;AAuC0F,OAAO,OAAO;CACtG,0BAA0B,OAAO,OAAO;EACtC,YAAY;EACZ,YAAY;EACZ,WAAW;EACX,UAAU;CACZ,CAAC;CACD,kBAAkB,OAAO,OAAO;EAC9B,YAAY;EACZ,YAAY;EACZ,WAAW;EACX,UAAU;CACZ,CAAC;CACD,gBAAgB,OAAO,OAAO;EAC5B,YAAY;EACZ,YAAY;EACZ,WAAW;EACX,UAAU;CACZ,CAAC;CACD,gBAAgB,OAAO,OAAO;EAC5B,YAAY;EACZ,YAAY;EACZ,WAAW;EACX,UAAU;CACZ,CAAC;AACH,CAAC"}
1
+ {"version":3,"file":"worker-dispatch-C7RtNOXv.js","names":[],"sources":["../src/lib/worker-dispatch.ts"],"sourcesContent":["/**\n * Frozen contract for the NON-BLOCKING workers surface.\n *\n * The `workers` MCP tools (`explore`/`implement`/`review`/`plan`/`test`, and\n * `browse` when the browse agent is enabled) BLOCK the caller for up to 6h\n * (`runWorkerAgent`). The MAIN Claude Code agent must never block on one, so a\n * per-mode `worker-*` DISPATCHER SUBAGENT — which Claude Code runs in the\n * background and reports on via a completion notification — is the only\n * sanctioned way to run a worker. This module is the single source of truth for\n * three things that must never drift:\n *\n * 1. the tool → dispatcher map (`mcp__<workersKey>__<mode>` ↔ `worker-<mode>`),\n * 2. the PreToolUse GUARD decision that denies a raw worker call from the main\n * agent (or any non-dispatcher subagent) and redirects it to the matching\n * `worker-*` agent, allowing it only from the dispatcher itself, and\n * 3. the dispatcher subagent bodies (description / system prompt / `tools:`\n * allowlist).\n *\n * Imported by `codex-mcp-config.ts` (dispatcher `.md` generation + the hook\n * command it bakes into settings.json) AND `internal-worker-guard.ts` (the\n * runtime PreToolUse hook). Keeping the map here means the settings matcher, the\n * redirect target, the dispatcher names, and the `tools:` allowlist are all\n * derived from one place.\n *\n * Discrimination mechanism: a Claude Code PreToolUse payload carries\n * `agent_type` (the invoking subagent's name) ONLY inside a subagent context —\n * absent for the top-level/main agent. So `agent_type === \"worker-<mode>\"` is\n * the reliable \"this call came from the dispatcher, allow it\" signal, and its\n * absence (or any other value) means \"main agent or an unrelated subagent →\n * deny\". This is the SAME field this repo's Stop / prompt-submit hooks already\n * key off (`isSubagentContext` in `orchestration/stop-gate-policy.ts`); the\n * guard here is the inverse (allow-only-dispatcher rather than skip-any-sub).\n */\n\nimport { buildSelfCommand, type SelfInvocation } from \"./hook-launcher/self-invocation\"\n\n/** The five always-available worker modes (gated by `workerToolsEnabled()`). */\nexport const CORE_WORKER_MODES = [\n \"explore\",\n \"implement\",\n \"review\",\n \"plan\",\n \"test\",\n] as const\n\n/** The browse worker mode, gated separately by `browseAgentEnabled()`. */\nexport const BROWSE_WORKER_MODE = \"browse\" as const\n\nexport type CoreWorkerMode = (typeof CORE_WORKER_MODES)[number]\nexport type WorkerDispatchMode = CoreWorkerMode | typeof BROWSE_WORKER_MODE\n\n/** Every mode the surface can expose — used to build the sweep-regex allowlist\n * and to validate `--modes`. Order is stable (core first, browse last). */\nexport const ALL_WORKER_DISPATCH_MODES: ReadonlyArray<WorkerDispatchMode> = [\n ...CORE_WORKER_MODES,\n BROWSE_WORKER_MODE,\n]\n\n/** The dispatcher subagent name for a mode, e.g. `implement` → `worker-implement`. */\nexport function dispatcherAgentName(mode: WorkerDispatchMode): string {\n return `worker-${mode}`\n}\n\n/** Every possible dispatcher subagent name (used by the stale-`.md` sweep). */\nexport const ALL_DISPATCHER_AGENT_NAMES: ReadonlyArray<string> =\n ALL_WORKER_DISPATCH_MODES.map(dispatcherAgentName)\n\n/** The MCP tool name the workers server exposes for a mode under the resolved key. */\nexport function workerToolName(workersKey: string, mode: WorkerDispatchMode): string {\n return `mcp__${workersKey}__${mode}`\n}\n\n/** The active dispatch modes for a launch: the five core modes plus `browse`\n * only when the browse agent is enabled. */\nexport function activeDispatchModes(opts: { browse: boolean }): Array<WorkerDispatchMode> {\n return opts.browse ? [...CORE_WORKER_MODES, BROWSE_WORKER_MODE] : [...CORE_WORKER_MODES]\n}\n\nfunction escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n}\n\n/**\n * The Claude Code PreToolUse `matcher` (a regex over the tool name) that scopes\n * the guard hook to exactly the active worker tools — nothing else invokes the\n * hook. Anchored + exact-alternation so an unrelated `mcp__<key>__status` (a\n * future non-blocking tool with no dispatcher) is never matched, hence never\n * denied.\n */\nexport function guardToolMatcher(workersKey: string, modes: ReadonlyArray<WorkerDispatchMode>): string {\n const alt = modes.map((m) => escapeRegex(m)).join(\"|\")\n return `^mcp__${escapeRegex(workersKey)}__(${alt})$`\n}\n\n/** Parse the worker mode out of a tool name for the resolved key, or null if it\n * isn't one of the recognized worker tools. */\nexport function parseWorkerToolCall(\n toolName: string,\n workersKey: string,\n modes: ReadonlyArray<WorkerDispatchMode>,\n): WorkerDispatchMode | null {\n const prefix = `mcp__${workersKey}__`\n if (!toolName.startsWith(prefix)) return null\n const rest = toolName.slice(prefix.length)\n return (modes as ReadonlyArray<string>).includes(rest) ? (rest as WorkerDispatchMode) : null\n}\n\n/** The `permissionDecisionReason` shown to the model on a deny, steering it to\n * the matching background dispatcher. `mode` is null when the payload was\n * unparseable (fail-closed generic message). */\nexport function guardDenyReason(mode: WorkerDispatchMode | null): string {\n const target = mode\n ? `Agent(subagent_type: \"${dispatcherAgentName(mode)}\", prompt: <your worker brief>)`\n : `the matching background \\`worker-*\\` agent via the Agent tool`\n return (\n \"Workers run as background subagents in this session so your turn never blocks. \"\n + `Re-issue this as ${target}. `\n + \"It returns immediately and delivers the worker's result as a completion notification — \"\n + \"do not call the raw `mcp__…__` worker tool from the main thread.\"\n )\n}\n\n/** The stdout JSON a PreToolUse hook prints to DENY a tool call. */\nexport function guardDenyOutput(mode: WorkerDispatchMode | null): string {\n return JSON.stringify({\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: guardDenyReason(mode),\n },\n })\n}\n\nexport interface WorkerGuardResult {\n /** JSON to print to stdout (a deny decision), or null to ALLOW (print nothing). */\n output: string | null\n /** Machine-readable verdict for tests/telemetry. */\n verdict: \"allow-dispatcher\" | \"allow-non-worker\" | \"deny-main\" | \"deny-malformed\"\n}\n\n/**\n * Pure PreToolUse guard decision. Given the raw stdin payload, the resolved\n * workers key, and the active modes, decide whether to DENY the tool call.\n *\n * Rules (fail toward protecting the \"main never blocks\" invariant):\n * - Payload unparseable / no string `tool_name`: the matcher only fires this\n * hook for worker tools, so a payload we can't read is still a worker call\n * → DENY (fail closed, generic redirect).\n * - `tool_name` is not a recognized worker tool for this key: ALLOW (not a\n * tool we guard — never deny a non-worker tool).\n * - `agent_type` equals one of the active dispatcher names: ALLOW (the call\n * came from the dispatcher subagent that is meant to run the worker).\n * - Otherwise (main agent: `agent_type` absent; or a non-dispatcher subagent):\n * DENY with a redirect to the matching `worker-<mode>` agent.\n */\nexport function decideWorkerGuard(input: {\n stdin: string\n workersKey: string\n modes: ReadonlyArray<WorkerDispatchMode>\n}): WorkerGuardResult {\n let payload: { tool_name?: unknown; agent_type?: unknown } | null = null\n try {\n const parsed: unknown = JSON.parse(input.stdin)\n if (parsed && typeof parsed === \"object\") {\n payload = parsed as { tool_name?: unknown; agent_type?: unknown }\n }\n } catch {\n payload = null\n }\n\n const toolName = typeof payload?.tool_name === \"string\" ? payload.tool_name : null\n if (!toolName) {\n // Fail CLOSED: the settings matcher only routes worker-tool calls here, so\n // an unreadable payload is still a worker call we must not let through.\n return { output: guardDenyOutput(null), verdict: \"deny-malformed\" }\n }\n\n const mode = parseWorkerToolCall(toolName, input.workersKey, input.modes)\n if (mode === null) {\n // Not one of the worker tools we guard (matcher over-fired, or a future\n // non-blocking tool under the same server) → allow the normal flow.\n return { output: null, verdict: \"allow-non-worker\" }\n }\n\n const agentType = payload?.agent_type\n if (typeof agentType === \"string\" && agentType === dispatcherAgentName(mode)) {\n // The call originated inside the `worker-<mode>` dispatcher subagent that is\n // meant to run THIS worker. Require an exact mode match (not just \"any\n // dispatcher\"), so a read-only `worker-explore` can't invoke the\n // write-capable `implement` worker if it misroutes or is prompt-injected.\n // If a matching dispatcher is still denied, the payload that reached this\n // hook did not carry this exact top-level `agent_type`, or a different\n // PreToolUse hook denied the call after this guard allowed it.\n return { output: null, verdict: \"allow-dispatcher\" }\n }\n\n // Main agent (agent_type absent), a non-dispatcher subagent, or a dispatcher\n // for a DIFFERENT mode → deny + redirect. Denying non-dispatcher subagents\n // too closes the transitive-blocking hole (a foreground subagent that blocked\n // on a worker would transitively block the main agent).\n return { output: guardDenyOutput(mode), verdict: \"deny-main\" }\n}\n\n// ─── Dispatcher subagent bodies ──────────────────────────────────────────────\n\n/** One-line human description shown to the lead when picking a subagent. Uses\n * the documented \"Use proactively\" auto-delegation idiom. */\nexport function dispatcherDescription(mode: WorkerDispatchMode): string {\n const blurb: Record<WorkerDispatchMode, string> = {\n explore:\n \"Non-blocking `explore` worker: dispatches a read-only autonomous worker (its own context) in the background and delivers its summary as a completion notification.\",\n implement:\n \"Non-blocking `implement` worker: dispatches an autonomous coding worker (read/write/bash) that ALWAYS runs in an isolated git worktree and returns the diff (for in-place edits use the `implementer` subagent), in the background, and delivers its result as a completion notification.\",\n review:\n \"Non-blocking `review` worker: the backgrounded counterpart of the `reviewer` subagent, running a cross-lab model. It has explore's read-and-search tools plus `bash`, so it can VERIFY rather than only read: reproduce a failure, or run the build or suite to check a claim. By default it works directly in the workspace, where it gets no edit/write tools but `bash` still runs real commands, so a build or test it invokes can touch the tree. Pass `worktree: true` to run it isolated in a replayed git worktree instead, which also lets it author a throwaway probe test. Returns severity-ranked findings with file:line and a go/no-go, as a completion notification. Use `explore` instead when you just need to find or understand something.\",\n plan:\n \"Non-blocking `plan` worker: dispatches a read-only planner that returns an ordered implementation plan, in the background, and delivers it as a completion notification.\",\n test:\n \"Non-blocking `test` worker: dispatches an independent test author (in an isolated git worktree) that writes tests trying to break the implementation, in the background, and delivers pass/fail as a completion notification.\",\n browse:\n \"Non-blocking `browse` worker: dispatches an autonomous browser agent in the background and delivers its result as a completion notification.\",\n }\n return (\n `${blurb[mode]} Use proactively for any ${mode}-mode worker task so a long run never blocks your turn: `\n + \"it returns immediately and notifies you when done.\"\n )\n}\n\n/** The dispatcher subagent's full system prompt: call the one worker tool once,\n * relay verbatim, do nothing else. */\nexport function dispatcherPrompt(mode: WorkerDispatchMode, workersKey: string): string {\n const tool = workerToolName(workersKey, mode)\n const briefField = mode === \"browse\" ? \"task\" : \"prompt\"\n const briefDescription = mode === \"browse\" ? \"the lead's browse task, copied verbatim\" : \"the lead's worker brief, copied verbatim\"\n const modeSpecificPassThrough = mode === \"browse\"\n ? \"\\n - `sessionId` (optional): pass through if the lead specified one\"\n : mode === \"review\"\n ? \"\\n - `worktree` (optional): pass `true` only if the lead asked for an isolated review\"\n : \"\"\n return [\n `# Subagent: ${dispatcherAgentName(mode)}`,\n \"\",\n `You are a thin DISPATCHER for the \\`${mode}\\` worker. You run in the background so the`,\n \"lead agent's turn is never blocked while the (up-to-6-hour) worker runs.\",\n \"\",\n \"## Your only job\",\n \"\",\n `Call the \\`${tool}\\` tool EXACTLY ONCE, passing through the fields from the lead's brief:`,\n ` - \\`${briefField}\\`: ${briefDescription}`,\n \" - `workspace`: ALWAYS pass this. Use the absolute path of the directory the\",\n \" lead named, or, when the lead named none, your own current working\",\n \" directory. The proxy runs as a separate long-lived process and cannot see\",\n \" where you are, so if you omit this it falls back to the session's directory,\",\n \" which may be a different checkout than the files the lead is asking about.\",\n \" - `model` / `thinking` (optional): only if the lead specified them\",\n \" - `maxWallClockMs` (optional): per-call wall-clock budget in ms, if the lead specified one\"\n + modeSpecificPassThrough,\n \"\",\n \"When the tool returns, output its result VERBATIM as your final message. That final\",\n \"message is what the lead receives in the completion notification — it IS the result.\",\n \"\",\n \"## Hard rules\",\n \"\",\n \"- Call the worker tool exactly once. Do not retry on a normal (non-error) return.\",\n \"- Do NOT attempt the task yourself, do NOT read/edit files, do NOT run other tools.\",\n \"- Do NOT spawn other agents (you have no Agent tool and must not try to gain one).\",\n \"- Do NOT summarize, paraphrase, or add commentary — relay the worker output verbatim.\",\n \"- If the worker returns an error, relay that error verbatim (do not mask it).\",\n ].join(\"\\n\")\n}\n\n/** The `tools:` frontmatter allowlist for a dispatcher: the workers MCP server\n * wildcard (`mcp__<workersKey>__*`). Claude Code's `tools:` field supports\n * MCP patterns only at SERVER granularity (`mcp__<server>__*`), not individual\n * tool names, so this grants exactly the workers tools and NOTHING else — no\n * Agent/Task (so it cannot spawn further agents → no recursion), no Read/Bash\n * (so it cannot do extra work). The dispatcher's prompt narrows it to the one\n * mode; the guard allows only the exact dispatcher for that worker mode. */\nexport function dispatcherTools(_mode: WorkerDispatchMode, workersKey: string): Array<string> {\n return [`mcp__${workersKey}__*`]\n}\n\n/**\n * Build the shell command Claude Code runs for the workers `PreToolUse` guard\n * hook — the running github-router via its node/bun binary so it works\n * regardless of PATH. Mirrors `buildPromptSubmitHookCommand`.\n *\n * The resolved `workersKey` and the active `modes` are baked into the command\n * ARGS (not env): `mergeStopHookIntoSettings` dedups hooks by the command\n * string only, so baking the key/modes makes a changed resolution produce a\n * DISTINCT command — no stale-matcher entry can survive from a prior launch.\n */\nexport function buildWorkerGuardHookCommand(\n invocation: SelfInvocation,\n workersKey: string,\n modes: ReadonlyArray<WorkerDispatchMode>,\n): string {\n const q = (s: string): string => `\"${s}\"`\n const args = `internal-worker-guard --workers-key ${q(workersKey)} --modes ${q(modes.join(\",\"))}`\n return buildSelfCommand(invocation, args)\n}\n\n/** Parse a `--modes` CSV back into validated modes (drops unknown tokens). */\nexport function parseModesCsv(csv: string | undefined): Array<WorkerDispatchMode> {\n if (!csv) return [...CORE_WORKER_MODES]\n const known = new Set<string>(ALL_WORKER_DISPATCH_MODES)\n const out = csv\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => known.has(s)) as Array<WorkerDispatchMode>\n return out.length > 0 ? out : [...CORE_WORKER_MODES]\n}\n\n// ─── Pipeline skill worker configs (additive, non-guard) ─────────────────────\n\n/**\n * Bounded worker configs for the `/gh-gather-context`, `/gh-plan`, and\n * `/gh-implement` pipeline skills. These reuse the existing\n * `worker-explore` / `worker-implement` / `worker-review` / `worker-plan`\n * dispatchers (so the PreToolUse guard above is untouched); the configs only\n * pin the 200K-default model alias, the wall-clock budget, and the worktree\n * policy each skill brief must use. All models are bare slugs (no `[1m]`).\n *\n * No output-token cap is listed: worker tools accept `{prompt, model,\n * thinking, workspace, maxWallClockMs, worktree}` and have no output-token\n * parameter, so such a cap would be unenforced. `timeoutMs` IS enforceable:\n * the skill bodies instruct the lead to pass it as the real `maxWallClockMs`\n * worker arg (honored by `worker-agent/budget.ts`, clamped to the per-call\n * ceiling in `peer-mcp-personas.ts`).\n */\nexport type SkillWorkerRole =\n | \"gather-context-explore\"\n | \"implement-task\"\n | \"review-pass1\"\n | \"review-pass2\"\n\nexport interface SkillWorkerConfig {\n /** Existing dispatcher to reuse (guard-compatible, no new modes). */\n dispatcher: WorkerDispatchMode\n /** Router-owned model alias (200K default, effort pinned). */\n modelAlias: string\n /**\n * Wall-clock budget per worker call, passed by the lead as the real\n * `maxWallClockMs` worker arg (well under the 6h per-call ceiling).\n */\n timeoutMs: number\n /** Whether the worker runs in an isolated git worktree. */\n worktree: boolean\n}\n\nexport const SKILL_WORKER_CONFIGS: Readonly<Record<SkillWorkerRole, SkillWorkerConfig>> = Object.freeze({\n \"gather-context-explore\": Object.freeze({\n dispatcher: \"explore\",\n modelAlias: \"gh-router-skill-gather-context-explore-high\",\n timeoutMs: 180_000,\n worktree: false,\n }),\n \"implement-task\": Object.freeze({\n dispatcher: \"implement\",\n modelAlias: \"gh-router-skill-implement-task-max\",\n timeoutMs: 600_000,\n worktree: true,\n }),\n \"review-pass1\": Object.freeze({\n dispatcher: \"review\",\n modelAlias: \"gh-router-skill-review-pass1-max\",\n timeoutMs: 300_000,\n worktree: false,\n }),\n \"review-pass2\": Object.freeze({\n dispatcher: \"review\",\n modelAlias: \"gh-router-skill-review-pass2-medium\",\n timeoutMs: 300_000,\n worktree: false,\n }),\n})\n\nexport function skillWorkerConfig(role: SkillWorkerRole): SkillWorkerConfig {\n return SKILL_WORKER_CONFIGS[role]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAa,qBAAqB;;;AAOlC,MAAa,4BAA+D,CAC1E,GAAG,mBACH,kBACF;;AAGA,SAAgB,oBAAoB,MAAkC;CACpE,OAAO,UAAU;AACnB;AAIE,0BAA0B,IAAI,mBAAmB;;AAGnD,SAAgB,eAAe,YAAoB,MAAkC;CACnF,OAAO,QAAQ,WAAW,IAAI;AAChC;;;AAIA,SAAgB,oBAAoB,MAAsD;CACxF,OAAO,KAAK,SAAS,CAAC,GAAG,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V,KAAK,MAAM,EAAE,KAAK,CAAC,CAAC,CACpB,QAAQ,MAAM,MAAM,IAAI,CAAC,CAAC;CAC7B,OAAO,IAAI,SAAS,IAAI,MAAM,CAAC,GAAG,iBAAiB;AACrD;AAuC0F,OAAO,OAAO;CACtG,0BAA0B,OAAO,OAAO;EACtC,YAAY;EACZ,YAAY;EACZ,WAAW;EACX,UAAU;CACZ,CAAC;CACD,kBAAkB,OAAO,OAAO;EAC9B,YAAY;EACZ,YAAY;EACZ,WAAW;EACX,UAAU;CACZ,CAAC;CACD,gBAAgB,OAAO,OAAO;EAC5B,YAAY;EACZ,YAAY;EACZ,WAAW;EACX,UAAU;CACZ,CAAC;CACD,gBAAgB,OAAO,OAAO;EAC5B,YAAY;EACZ,YAAY;EACZ,WAAW;EACX,UAAU;CACZ,CAAC;AACH,CAAC"}
@@ -1,7 +1,7 @@
1
- import { a as readWorkiqTokenFile, c as workiqTokenPath, n as WorkiqAuthError, o as runLoopbackAuth, p as WORKIQ_TOKEN_ENV, r as deleteWorkiqTokenFile, s as workiqTenant, t as AUTH_REMEDY } from "./token-CVG0yI_j.js";
1
+ import { a as readWorkiqTokenFile, c as workiqTokenPath, n as WorkiqAuthError, o as runLoopbackAuth, p as WORKIQ_TOKEN_ENV, r as deleteWorkiqTokenFile, s as workiqTenant, t as AUTH_REMEDY } from "./token-DHEkiO4g.js";
2
2
  import { defineCommand, showUsage } from "citty";
3
3
  import consola from "consola";
4
- //#region src/workiq.ts
4
+ // src/workiq.ts
5
5
  /**
6
6
  * `github-router workiq` — manage the durable Work IQ sign-in.
7
7
  *
@@ -138,7 +138,6 @@ const workiq = defineCommand({
138
138
  if (rawArgs.length === 0) return showUsage(workiq);
139
139
  }
140
140
  });
141
- //#endregion
142
141
  export { workiq };
143
142
 
144
- //# sourceMappingURL=workiq-qnJR5_n2.js.map
143
+ //# sourceMappingURL=workiq-CQauEAMc.js.map