@fased/fased 0.1.56 → 0.1.57

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 (359) hide show
  1. package/dist/acp/client.js +2 -2
  2. package/dist/acp/secret-file.js +2 -2
  3. package/dist/agents/agent-scope.js +2 -2
  4. package/dist/agents/apply-patch.js +8 -8
  5. package/dist/agents/auth-profiles/paths.js +2 -2
  6. package/dist/agents/auth-profiles/store.js +2 -2
  7. package/dist/agents/bash-tools.shared.js +2 -2
  8. package/dist/agents/cli-credentials.js +4 -4
  9. package/dist/agents/docs-path.js +3 -3
  10. package/dist/agents/embedded-pi-mcp.js +4 -4
  11. package/dist/agents/identity-avatar.js +3 -3
  12. package/dist/agents/identity-file.js +2 -2
  13. package/dist/agents/model-catalog-snapshot.js +124 -0
  14. package/dist/agents/openai-codex-app-server.js +35 -10
  15. package/dist/agents/openai-codex-runtime-component.js +39 -0
  16. package/dist/agents/pi-embedded-runner/compact.js +1 -1
  17. package/dist/agents/pi-embedded-runner/extra-params.js +28 -16
  18. package/dist/agents/pi-embedded-runner/run/attempt.js +1 -1
  19. package/dist/agents/pi-embedded-subscribe.raw-stream.js +3 -3
  20. package/dist/agents/pi-extensions/compaction-safeguard.js +3 -3
  21. package/dist/agents/pi-model-discovery.js +6 -6
  22. package/dist/agents/pi-project-settings.js +3 -3
  23. package/dist/agents/sandbox/fs-bridge.js +2 -2
  24. package/dist/agents/session-dirs.js +4 -4
  25. package/dist/agents/session-write-lock.js +13 -13
  26. package/dist/agents/shell-utils.js +5 -5
  27. package/dist/agents/skills/bundled-dir.js +4 -4
  28. package/dist/agents/skills/local-loader.js +6 -6
  29. package/dist/agents/skills/plugin-skills.js +2 -2
  30. package/dist/agents/skills/workspace.js +13 -13
  31. package/dist/agents/skills-install-download.js +7 -7
  32. package/dist/agents/skills-install-plan.js +2 -2
  33. package/dist/agents/skills-install.js +2 -2
  34. package/dist/agents/skills-status.js +2 -2
  35. package/dist/agents/subagent-depth.js +2 -2
  36. package/dist/agents/system-prompt-params.js +2 -2
  37. package/dist/agents/tools/session-status-tool.js +1 -1
  38. package/dist/agents/workspace.js +22 -22
  39. package/dist/auto-reply/reply/agent-runner-execution.js +2 -2
  40. package/dist/auto-reply/reply/agent-runner.js +2 -2
  41. package/dist/auto-reply/reply/commands-export-session.js +7 -7
  42. package/dist/auto-reply/reply/post-compaction-audit.js +3 -3
  43. package/dist/auto-reply/reply/post-compaction-context.js +3 -3
  44. package/dist/auto-reply/reply/session.js +3 -3
  45. package/dist/auto-reply/skill-commands.js +3 -3
  46. package/dist/auto-reply/status.js +6 -6
  47. package/dist/brand.js +1 -1
  48. package/dist/browser/chrome.executables.js +3 -3
  49. package/dist/browser/chrome.js +3 -3
  50. package/dist/browser/chrome.profile-decoration.js +6 -6
  51. package/dist/browser/profiles-service.js +2 -2
  52. package/dist/browser/server-context.js +2 -2
  53. package/dist/browser/trash.js +4 -4
  54. package/dist/build-info.json +3 -3
  55. package/dist/canvas-host/a2ui/.bundle.hash +1 -1
  56. package/dist/canvas-host/server.js +4 -4
  57. package/dist/capabilities/catalog.js +3 -3
  58. package/dist/capabilities/install.js +43 -0
  59. package/dist/channels/plugins/catalog.js +3 -3
  60. package/dist/cli/browser-cli-extension.js +6 -6
  61. package/dist/cli/command-format.js +2 -2
  62. package/dist/cli/components-cli.js +9 -31
  63. package/dist/cli/cron-cli/register.cron-simple.js +2 -2
  64. package/dist/cli/dns-cli.js +9 -9
  65. package/dist/cli/gateway-cli/dev.js +5 -5
  66. package/dist/cli/gateway-cli/run.js +2 -2
  67. package/dist/cli/hooks-cli.js +6 -6
  68. package/dist/cli/lightweight/gateway-runtime-probe.js +2 -2
  69. package/dist/cli/memory-cli.js +7 -7
  70. package/dist/cli/nodes-media-utils.js +2 -2
  71. package/dist/cli/plugins-cli.js +5 -5
  72. package/dist/cli/secrets-cli.js +3 -3
  73. package/dist/cli/update-cli/update-command.js +50 -12
  74. package/dist/cli/windows-argv.js +2 -2
  75. package/dist/commands/agent.js +1 -1
  76. package/dist/commands/auth-choice.apply.openai.js +9 -0
  77. package/dist/commands/auth-choice.apply.plugin-provider.js +1 -1
  78. package/dist/commands/dashboard-link.js +3 -3
  79. package/dist/commands/doctor-install.js +5 -5
  80. package/dist/commands/doctor-memory-search.js +2 -2
  81. package/dist/commands/doctor-platform-notes.js +2 -2
  82. package/dist/commands/doctor-sandbox.js +2 -2
  83. package/dist/commands/doctor-state-integrity.js +23 -23
  84. package/dist/commands/doctor-workspace.js +3 -3
  85. package/dist/commands/doctor.js +3 -3
  86. package/dist/commands/managed-up.js +2 -2
  87. package/dist/commands/onboard-auth.credentials.js +3 -3
  88. package/dist/commands/onboard-channels.js +1 -1
  89. package/dist/commands/onboarding/plugin-install.js +4 -4
  90. package/dist/commands/sessions-cleanup.js +2 -2
  91. package/dist/commands/signal-install.js +6 -6
  92. package/dist/commands/status-all/channels.js +2 -2
  93. package/dist/commands/wallet.js +47 -47
  94. package/dist/config/cache-utils.js +2 -2
  95. package/dist/config/includes.js +5 -5
  96. package/dist/config/io.js +2 -2
  97. package/dist/config/paths.js +3 -3
  98. package/dist/config/sat-runtime-ids.js +3 -3
  99. package/dist/config/sessions/disk-budget.js +6 -6
  100. package/dist/config/sessions/paths.js +2 -2
  101. package/dist/config/sessions/store.js +17 -17
  102. package/dist/config/sessions/transcript.js +4 -4
  103. package/dist/config/talk.js +2 -2
  104. package/dist/control-ui/assets/{app-D7TXyNRi.js → app-DltSyY4Y.js} +1689 -1689
  105. package/dist/control-ui/assets/{index-BmSBom-w.js → index-D5JlBp7f.js} +3 -3
  106. package/dist/control-ui/index.html +1 -1
  107. package/dist/control-ui/version.json +1 -1
  108. package/dist/cron/service/store.js +2 -2
  109. package/dist/cron/store.js +6 -6
  110. package/dist/daemon/systemd-system.js +5 -5
  111. package/dist/discord/monitor/thread-bindings.state.js +2 -2
  112. package/dist/extensions/sat-mining/src/sat-bond-layout.js +9 -9
  113. package/dist/gateway/control-ui-boot-check.js +6 -6
  114. package/dist/gateway/control-ui-login.js +7 -7
  115. package/dist/gateway/control-ui.js +9 -9
  116. package/dist/gateway/hooks-mapping.js +4 -4
  117. package/dist/gateway/protocol/schema/agents-models-skills.js +43 -1
  118. package/dist/gateway/server-discovery.js +2 -2
  119. package/dist/gateway/server-http.js +4 -4
  120. package/dist/gateway/server-methods/chat.js +3 -3
  121. package/dist/gateway/server-methods/hooks.js +1 -1
  122. package/dist/gateway/server-methods/models.js +12 -5
  123. package/dist/gateway/server-methods/plugins-marketplace.js +3 -3
  124. package/dist/gateway/server-methods/services.js +1 -1
  125. package/dist/gateway/server-methods/sessions.js +7 -7
  126. package/dist/gateway/server-methods/usage.js +2 -2
  127. package/dist/gateway/server.impl.js +3 -3
  128. package/dist/gateway/session-compaction-checkpoints.js +4 -4
  129. package/dist/gateway/session-utils.fs.js +24 -24
  130. package/dist/gateway/session-utils.js +6 -6
  131. package/dist/gateway/sessions-patch.js +1 -1
  132. package/dist/hooks/bundled-dir.js +4 -4
  133. package/dist/hooks/gmail-setup-utils.js +6 -6
  134. package/dist/hooks/import-url.js +2 -2
  135. package/dist/hooks/loader.js +4 -4
  136. package/dist/hooks/workspace.js +7 -7
  137. package/dist/infra/archive.js +17 -17
  138. package/dist/infra/boundary-file-read.js +2 -2
  139. package/dist/infra/boundary-path.js +15 -15
  140. package/dist/infra/brew.js +2 -2
  141. package/dist/infra/control-ui-assets.js +14 -14
  142. package/dist/infra/device-auth-store.js +8 -8
  143. package/dist/infra/device-identity.js +8 -8
  144. package/dist/infra/dotenv.js +2 -2
  145. package/dist/infra/exec-approvals.js +8 -8
  146. package/dist/infra/exec-command-resolution.js +4 -4
  147. package/dist/infra/exec-safe-bin-trust.js +2 -2
  148. package/dist/infra/fased-root.js +5 -5
  149. package/dist/infra/fs-safe.js +14 -14
  150. package/dist/infra/gateway-lock.js +11 -11
  151. package/dist/infra/git-commit.js +5 -5
  152. package/dist/infra/git-root.js +4 -4
  153. package/dist/infra/hosted-runtime-artifact.js +3 -3
  154. package/dist/infra/is-main.js +2 -2
  155. package/dist/infra/json-file.js +7 -7
  156. package/dist/infra/outbound/delivery-queue.js +16 -16
  157. package/dist/infra/path-env.js +3 -3
  158. package/dist/infra/ports-lsof.js +4 -4
  159. package/dist/infra/provider-usage.auth.js +3 -3
  160. package/dist/infra/safe-open-sync.js +2 -2
  161. package/dist/infra/session-cost-usage.js +9 -9
  162. package/dist/infra/shell-env.js +2 -2
  163. package/dist/infra/state-migrations.fs.js +6 -6
  164. package/dist/infra/state-migrations.js +23 -23
  165. package/dist/infra/tmp-fased-dir.js +6 -6
  166. package/dist/infra/widearea-dns.js +3 -3
  167. package/dist/infra/wsl.js +2 -2
  168. package/dist/light-update-status.js +11 -11
  169. package/dist/line/accounts.js +2 -2
  170. package/dist/line/download.js +2 -2
  171. package/dist/logging/config.js +3 -3
  172. package/dist/logging/logger.js +7 -7
  173. package/dist/managed/federation.js +3 -3
  174. package/dist/managed/tunnel.js +3 -3
  175. package/dist/media/store.js +13 -13
  176. package/dist/media-understanding/runner.js +3 -3
  177. package/dist/memory/embeddings.js +2 -2
  178. package/dist/memory/internal.js +10 -10
  179. package/dist/memory/manager-sync-ops.js +7 -7
  180. package/dist/memory/repair-executor.js +17 -17
  181. package/dist/node-host/invoke-system-run-plan.js +8 -8
  182. package/dist/node-host/invoke.js +2 -2
  183. package/dist/node-host/runner.js +3 -3
  184. package/dist/pairing/pairing-store.js +3 -3
  185. package/dist/plugin-sdk/{accounts-DzWlKv1U.js → accounts-CmMwe9Dt.js} +1 -1
  186. package/dist/plugin-sdk/{actions-BplQVLL6.js → actions-DYViFQiX.js} +2 -2
  187. package/dist/plugin-sdk/{active-listener-x4MLhYUw.js → active-listener-DVbpcisf.js} +1 -1
  188. package/dist/plugin-sdk/{agent-scope-BbgPlhtw.js → agent-scope-CCjfjKoO.js} +1 -1
  189. package/dist/plugin-sdk/{audio-preflight-G8h3Sn8_.js → audio-preflight-D-Mfay8i.js} +31 -31
  190. package/dist/plugin-sdk/{audit-CWknklvI.js → audit-JImYFOzJ.js} +1 -1
  191. package/dist/plugin-sdk/{channel-access-configure-CD4QDN5E.js → channel-access-configure-B_qYjml8.js} +1 -1
  192. package/dist/plugin-sdk/{channel-access-a9Dnfw7-.js → channel-access-cxCK2mci.js} +1 -1
  193. package/dist/plugin-sdk/channel-plugin-common.d.ts +2 -2
  194. package/dist/plugin-sdk/channel-plugin-common.js +5 -5
  195. package/dist/plugin-sdk/{chunk-B8EZkwiT.js → chunk-CF8nvZNj.js} +1 -1
  196. package/dist/plugin-sdk/{chunk-items-CEPklxGe.js → chunk-items-yLFoO571.js} +1 -1
  197. package/dist/plugin-sdk/command-status.js +31 -31
  198. package/dist/plugin-sdk/{commands-registry-BfEa4tFA.js → commands-registry-CK4KmMG0.js} +2 -2
  199. package/dist/plugin-sdk/{common-CbfckC19.js → common-Cky4hpqr.js} +1 -1
  200. package/dist/plugin-sdk/{config-Bt5GhnA-.js → config-Dbxj_jUP.js} +1125 -3
  201. package/dist/plugin-sdk/{config-schema-B9DKr6J5.js → config-schema-aKPMn6ML.js} +1749 -1387
  202. package/dist/plugin-sdk/device-pair.d.ts +1 -1
  203. package/dist/plugin-sdk/discord.d.ts +4 -4
  204. package/dist/plugin-sdk/discord.js +22 -22
  205. package/dist/plugin-sdk/{filesystem-manager-BGGGrkiN.js → filesystem-manager-ZoHU8oA7.js} +2 -2
  206. package/dist/plugin-sdk/{fs-safe-xBqok6yR.js → fs-safe-g4g7GT02.js} +2 -2
  207. package/dist/plugin-sdk/{handle-action-DbzZFYnG.js → handle-action-BSNDD2Vc.js} +17 -17
  208. package/dist/plugin-sdk/{helpers-CluGKuIV.js → helpers-CDo2XBSr.js} +1 -1
  209. package/dist/plugin-sdk/{image-ops-CUaLtIFj.js → image-ops-DbeBxbn4.js} +1 -1
  210. package/dist/plugin-sdk/index.d.ts +15 -15
  211. package/dist/plugin-sdk/index.js +33 -33
  212. package/dist/plugin-sdk/json-store.js +6 -6
  213. package/dist/plugin-sdk/{login-DJuHYDiK.js → login-CWXvFTd8.js} +3 -3
  214. package/dist/plugin-sdk/{login-qr-CbHL5ayf.js → login-qr-CJB2zjmM.js} +4 -4
  215. package/dist/plugin-sdk/{manager-oHAvZCT3.js → manager-CbiFFLKS.js} +4 -4
  216. package/dist/plugin-sdk/{markdown-tables-Mkx7k92Y.js → markdown-tables-Bskt9r8i.js} +1 -1
  217. package/dist/plugin-sdk/{media-CA8sTmVE.js → media-B3aAg5rh.js} +4 -4
  218. package/dist/plugin-sdk/{memory-search-VFll-AIb.js → memory-search-DTjIMw8J.js} +1 -1
  219. package/dist/plugin-sdk/{monitor-CZrN9pev.js → monitor-BJs6z7AT.js} +35 -35
  220. package/dist/plugin-sdk/{monitor-CmwGqNyV.js → monitor-BYGbTI5V.js} +36 -36
  221. package/dist/plugin-sdk/{openresponses-http-CWOd4war.js → openresponses-http-BGCl2dS2.js} +31 -31
  222. package/dist/plugin-sdk/{optional-runtime-dependency-DKmk9PZa.js → optional-runtime-dependency-BlTVkcAg.js} +1 -1
  223. package/dist/plugin-sdk/{outbound-0oN9IfNw.js → outbound-CIemga5_.js} +6 -6
  224. package/dist/plugin-sdk/{outbound-attachment-DdVkqUzE.js → outbound-attachment-2RckWqrk.js} +2 -2
  225. package/dist/plugin-sdk/{pairing-message-BMkkS038.d.ts → pairing-message-C403mq4K.d.ts} +1 -1
  226. package/dist/plugin-sdk/{pairing-message-ClqhfCUk.js → pairing-message-r-VQfhFB.js} +1 -1
  227. package/dist/plugin-sdk/{pairing-store-B01mCSct.js → pairing-store-uPnLfGgB.js} +2 -2
  228. package/dist/plugin-sdk/{path-alias-guards-BJZD5JMJ.js → path-alias-guards-DjgDArrp.js} +1 -1
  229. package/dist/plugin-sdk/{pi-model-discovery-Buz0JC1Y.js → pi-model-discovery-BpEilAym.js} +1 -1
  230. package/dist/plugin-sdk/{pi-model-discovery-runtime-DuwuoteY.js → pi-model-discovery-runtime-DwNdFaz-.js} +3 -3
  231. package/dist/plugin-sdk/{probe--7xtfzMm.js → probe-CJb5uR8B.js} +1 -1
  232. package/dist/plugin-sdk/provider-web-search-config-contract.d.ts +1 -1
  233. package/dist/plugin-sdk/{pw-ai-B0domrii.js → pw-ai-H7UgunQQ.js} +6 -6
  234. package/dist/plugin-sdk/{qmd-manager-CFFeM4Fl.js → qmd-manager-DSyx77KY.js} +1 -1
  235. package/dist/plugin-sdk/{replies-1macZ1mZ.js → replies-CKMwkH4G.js} +2 -2
  236. package/dist/plugin-sdk/{reply-prefix-ClpxvL_w.js → reply-prefix-CeVw7Mn2.js} +1 -1
  237. package/dist/plugin-sdk/{probe-xY3Ky0Tx.js → resolve-channels-_-nV-EK2.js} +3 -2
  238. package/dist/plugin-sdk/{resolve-outbound-target-BdH6LUoW.js → resolve-outbound-target-B68fSoGi.js} +1 -1
  239. package/dist/plugin-sdk/{resolve-route-CkNIKKEW.js → resolve-route-B8fOfihG.js} +2 -2
  240. package/dist/plugin-sdk/{retry-policy-9ybIh4Fq.js → retry-policy-B6GQldxB.js} +1 -1
  241. package/dist/plugin-sdk/{runtime-dependency-CIw9t7-k.js → runtime-dependency-DlqVSsSs.js} +4 -4
  242. package/dist/plugin-sdk/{runtime-Dy420wBu.js → runtime-nVJl3PlS.js} +4 -4
  243. package/dist/plugin-sdk/{sandbox-paths-w64tYl0v.js → sandbox-paths-Dx2lUqCu.js} +2 -2
  244. package/dist/plugin-sdk/sat-runtime.d.ts +2 -2
  245. package/dist/plugin-sdk/sat-runtime.js +31 -31
  246. package/dist/plugin-sdk/{send-BQUtCJFW.js → send-BCJ4hi3t.js} +8 -8
  247. package/dist/plugin-sdk/{send-DPJIIYAs.js → send-BHokB4TR.js} +6 -6
  248. package/dist/plugin-sdk/{send-2VcOMTN5.js → send-CPK_HlYW.js} +5 -5
  249. package/dist/plugin-sdk/{send-J4JWKP62.js → send-D3DQOg2a.js} +6 -6
  250. package/dist/plugin-sdk/{send-Dqes9tdU.js → send-hSu1HWms.js} +7 -7
  251. package/dist/plugin-sdk/{session-C_n2S5ub.js → session-DQ4Dr-mf.js} +2 -2
  252. package/dist/plugin-sdk/{skill-commands-B7wx9ax8.js → skill-commands-CmdoKLh_.js} +4 -4
  253. package/dist/plugin-sdk/{slack-BouRQG-W.js → slack-B70NHpMF.js} +47 -47
  254. package/dist/plugin-sdk/{slack-actions-CasHVtiq.js → slack-actions-fSmP981b.js} +14 -14
  255. package/dist/plugin-sdk/slack.d.ts +4 -4
  256. package/dist/plugin-sdk/slack.js +12 -12
  257. package/dist/plugin-sdk/{sticker-cache-BvGEUas3.js → sticker-cache-B4dG2sKU.js} +3 -3
  258. package/dist/plugin-sdk/{tables-CjlQJV4r.js → tables-EX4Hy-a-.js} +1 -1
  259. package/dist/plugin-sdk/{targets-QfP164Dh.js → targets-BeGUCGWK.js} +1 -1
  260. package/dist/plugin-sdk/{telegram-actions-CwYjV6Db.js → telegram-actions-CM8SJgc9.js} +34 -34
  261. package/dist/plugin-sdk/telegram.d.ts +4 -4
  262. package/dist/plugin-sdk/telegram.js +9 -9
  263. package/dist/plugin-sdk/{thread-bindings.lifecycle-DU4iX_Jr.js → thread-bindings.lifecycle-tHK_1mvp.js} +3 -3
  264. package/dist/plugin-sdk/{thread-bindings.state-BgYWFjNF.js → thread-bindings.state-D7xG1GHu.js} +2 -2
  265. package/dist/plugin-sdk/{tmp-fased-dir-BdFQvrvw.d.ts → tmp-fased-dir-Ouj58axY.d.ts} +1 -1
  266. package/dist/plugin-sdk/{types-BYDL6dQj.d.ts → types-B4hj6HgR.d.ts} +1 -1
  267. package/dist/plugin-sdk/{types-CLIvQaVg.d.ts → types-dWZFX1fk.d.ts} +2 -2
  268. package/dist/plugin-sdk/{web-D0yENDve.js → web-BFolfZ3i.js} +36 -36
  269. package/dist/plugin-sdk/{whatsapp-actions-BT2nPLyo.js → whatsapp-actions-CYmleHCz.js} +16 -16
  270. package/dist/plugin-sdk/{whatsapp-heartbeat-CiABSZ6G.js → whatsapp-heartbeat-BEwm4GK3.js} +2 -2
  271. package/dist/plugin-sdk/whatsapp.d.ts +9 -9
  272. package/dist/plugin-sdk/whatsapp.js +13 -13
  273. package/dist/plugin-sdk/{wsl-B_ojyEtC.js → wsl-BtMDzMv5.js} +3 -3
  274. package/dist/plugin-sdk/{zod-schema.providers-core-CIzCjXH9.d.ts → zod-schema.providers-core-FaYR6KdD.d.ts} +61 -61
  275. package/dist/plugins/bundled-dir.js +3 -3
  276. package/dist/plugins/discovery.js +11 -11
  277. package/dist/plugins/lifecycle.js +1 -1
  278. package/dist/plugins/loader.js +13 -13
  279. package/dist/plugins/manifest-registry.js +28 -2
  280. package/dist/plugins/manifest.js +6 -4
  281. package/dist/plugins/marketplace.js +1 -1
  282. package/dist/plugins/path-safety.js +3 -3
  283. package/dist/plugins/status-cache.js +9 -9
  284. package/dist/plugins/update.js +4 -4
  285. package/dist/plugins/web-search-install-catalog.js +3 -3
  286. package/dist/providers/openai-codex-model-discovery.js +11 -1
  287. package/dist/providers/runtime-model-catalog.js +2 -2
  288. package/dist/secrets/apply.js +16 -16
  289. package/dist/secrets/audit.js +11 -11
  290. package/dist/secrets/shared.js +9 -9
  291. package/dist/security/scan-paths.js +2 -2
  292. package/dist/shared/config-eval.js +2 -2
  293. package/dist/shared/pid-alive.js +2 -2
  294. package/dist/tasks/standing-orders.js +5 -5
  295. package/dist/tasks/task-flow-registry.js +5 -5
  296. package/dist/tasks/task-registry.js +5 -5
  297. package/dist/tasks/workflow-definitions.js +6 -6
  298. package/dist/telegram/token.js +5 -5
  299. package/dist/utils.js +5 -5
  300. package/dist/wallet/local-socket-signer-broker.js +16 -16
  301. package/dist/wallet/providers/embedded-keystore-adapter.js +5 -5
  302. package/dist/wallet/providers/local-socket-signer-adapter.js +2 -2
  303. package/dist/wallet/wallet-approval-auth.js +5 -5
  304. package/dist/wallet/wallet-audit-log.js +5 -5
  305. package/dist/wallet/wallet-custody.js +21 -21
  306. package/dist/wallet/wallet-inbound-events.js +5 -5
  307. package/dist/wallet/wallet-observability.js +5 -5
  308. package/dist/wallet/wallet-policy.js +9 -9
  309. package/dist/wallet/wallet-provider-registry.js +7 -7
  310. package/dist/wallet/wallet-runtime-config.js +3 -3
  311. package/dist/wallet/wallet-secrets-store.js +22 -22
  312. package/dist/wallet/wallet-send-approvals.js +5 -5
  313. package/dist/wallet/wallet-settlement-links.js +5 -5
  314. package/dist/web/accounts.js +3 -3
  315. package/dist/web/auth-store.js +18 -18
  316. package/dist/web/session.js +4 -4
  317. package/dist/wizard/host-security-capability.js +2 -2
  318. package/dist/wizard/onboarding.finalize.js +1 -1
  319. package/dist/wizard/onboarding.host-security.js +7 -7
  320. package/dist/wizard/onboarding.js +7 -7
  321. package/dist/wizard/onboarding.wallet.js +44 -44
  322. package/extensions/acpx/package.json +1 -1
  323. package/extensions/bluebubbles/package.json +1 -1
  324. package/extensions/copilot-proxy/package.json +1 -1
  325. package/extensions/diagnostics-otel/package.json +1 -1
  326. package/extensions/fased-federation/package.json +1 -1
  327. package/extensions/google-gemini-cli-auth/package.json +1 -1
  328. package/extensions/imessage/package.json +1 -1
  329. package/extensions/irc/package.json +1 -1
  330. package/extensions/line/package.json +1 -1
  331. package/extensions/llm-task/package.json +1 -1
  332. package/extensions/lobster/package.json +1 -1
  333. package/extensions/matrix/CHANGELOG.md +6 -0
  334. package/extensions/matrix/package.json +1 -1
  335. package/extensions/mattermost/package.json +1 -1
  336. package/extensions/memory-core/package.json +2 -2
  337. package/extensions/memory-lancedb/package.json +1 -1
  338. package/extensions/minimax-portal-auth/package.json +1 -1
  339. package/extensions/msteams/CHANGELOG.md +6 -0
  340. package/extensions/msteams/package.json +1 -1
  341. package/extensions/nextcloud-talk/package.json +1 -1
  342. package/extensions/nostr/CHANGELOG.md +6 -0
  343. package/extensions/nostr/package.json +1 -1
  344. package/extensions/open-prose/package.json +1 -1
  345. package/extensions/sat-mining/package.json +1 -1
  346. package/extensions/signal/package.json +1 -1
  347. package/extensions/synology-chat/package.json +1 -1
  348. package/extensions/tlon/package.json +1 -1
  349. package/extensions/twitch/CHANGELOG.md +6 -0
  350. package/extensions/twitch/package.json +1 -1
  351. package/extensions/voice-call/CHANGELOG.md +6 -0
  352. package/extensions/voice-call/package.json +1 -1
  353. package/extensions/zalo/CHANGELOG.md +6 -0
  354. package/extensions/zalo/package.json +1 -1
  355. package/extensions/zalouser/CHANGELOG.md +6 -0
  356. package/extensions/zalouser/package.json +1 -1
  357. package/package.json +1 -1
  358. package/dist/plugin-sdk/resolve-channels-CwB2_019.js +0 -4
  359. /package/dist/plugin-sdk/{resolve-users-Cxb5wpAQ.js → resolve-users-DN9VQBwv.js} +0 -0
@@ -1,11 +1,11 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-Cbj13DAv.js";
2
- import { $ as mergeSessionEntry, A as deliveryContextKey, An as GATEWAY_CLIENT_IDS, B as INPUT_PROVENANCE_KIND_VALUES, Bn as CLI_DEFAULT_OPERATOR_SCOPES, C as recordSessionMetaFromInbound, Cn as isGatewayMessageChannel, D as isCacheEnabled, Dn as normalizeMessageChannel, Dt as getChannelDock, E as updateSessionStoreEntry, En as listDeliverableMessageChannels, F as archiveSessionTranscripts, Fn as normalizeAnyChannelId, Ft as trimMessagingTarget, G as resolveSessionLockMaxHoldFromTimeout, Gn as getPluginCommandSpecs, H as hasInterSessionUserProvenance, Hn as resolveLeastPrivilegeOperatorScopesForMethod, I as capArrayByJsonBytes, In as normalizeChannelId$2, It as isWhatsAppGroupJid, J as resolveChannelResetConfig, Jn as createInternalHookEvent, K as resolveSessionKey$1, Kn as listPluginCommands, L as countToolResults, Ln as logMutatingAdminRpcAudit, Lt as normalizeWhatsAppTarget, M as normalizeDeliveryContext, Mn as GATEWAY_CLIENT_NAMES, N as normalizeSessionDeliveryFields, Nn as getChatChannelMeta, O as resolveCacheTtlMs$1, On as resolveGatewayMessageChannel, Ot as listChannelDocks, P as normalizeAccountId$1, Pn as listChatChannels, Pt as looksLikeHandleOrPhoneTarget, Q as DEFAULT_RESET_TRIGGERS, R as extractToolCallNames, Rn as consumeMutatingAdminRpcBudget, S as readSessionUpdatedAt, Sn as isDeliverableMessageChannel, T as updateSessionStore, Tn as isMarkdownCapableMessageChannel, U as normalizeInputProvenance, Un as clearPluginCommands, V as applyInputProvenanceToUserMessage, Vn as authorizeOperatorScopesForMethod, W as acquireSessionWriteLock, Wn as executePluginCommand, X as resolveSessionResetType, Xn as normalizePluginHttpPath, Y as resolveSessionResetPolicy, Yn as triggerInternalHook, Z as resolveThreadFlag, _ as appendAssistantMessageToSessionTranscript, _n as resolveChannelGroupRequireMention, a as createPluginRegistry, an as resolveTelegramToken, at as resolveMainSessionKey, b as resolveAndPersistSessionFile, bn as resolveGroupSessionKey, bt as parseSlackTarget, c as listAgentsForGateway, ct as listChannelPlugins, d as lookupContextTokens, dn as resolveDefaultSignalAccountId, en as createTelegramActionGate, et as resolveFreshSessionTotalTokens, f as resolveContextTokensForModel, fn as resolveSignalAccount, g as parseSessionThreadInfo, gn as resolveChannelGroupPolicy, h as extractDeliveryInfo, hn as resolveIMessageAccount, i as setActivePluginRegistry, in as resolveTelegramAccount, it as resolveExplicitAgentSessionKey, j as mergeDeliveryContext, jn as GATEWAY_CLIENT_MODES, k as deliveryContextFromSession, kn as resolveMessageChannel, l as loadCombinedSessionStoreForGateway, ln as listEnabledSignalAccounts, lt as normalizeChannelId$1, mn as resolveDefaultIMessageAccountId, n as getActivePluginRegistryKey, nn as listTelegramAccountIds, nt as canonicalizeMainSessionAlias, o as createRuntimeHelpers, on as buildChannelAccountBindings, ot as deriveSessionMetaPatch, p as ensureFasedAgentModelsJson, pn as listIMessageAccountIds, q as evaluateSessionFreshness, qn as matchPluginCommand, r as requireActivePluginRegistry, rt as resolveAgentMainSessionKey, s as classifySessionKey, st as getChannelPlugin, t as getActivePluginRegistry, tn as listEnabledTelegramAccounts, tt as setSessionRuntimeModel, u as resolveSessionModelRef, un as listSignalAccountIds, v as resolveMirroredTranscriptText, vn as resolveChannelGroupToolsPolicy, w as updateLastRoute, wn as isInternalMessageChannel, x as loadSessionStore, xn as INTERNAL_MESSAGE_CHANNEL, y as resolveSessionTranscriptFile, z as parseInlineDirectives$1, zn as ADMIN_SCOPE, zt as normalizeSignalMessagingTarget } from "./runtime-Dy420wBu.js";
2
+ import { $ as mergeSessionEntry, A as deliveryContextKey, An as GATEWAY_CLIENT_IDS, B as INPUT_PROVENANCE_KIND_VALUES, Bn as CLI_DEFAULT_OPERATOR_SCOPES, C as recordSessionMetaFromInbound, Cn as isGatewayMessageChannel, D as isCacheEnabled, Dn as normalizeMessageChannel, Dt as getChannelDock, E as updateSessionStoreEntry, En as listDeliverableMessageChannels, F as archiveSessionTranscripts, Fn as normalizeAnyChannelId, Ft as trimMessagingTarget, G as resolveSessionLockMaxHoldFromTimeout, Gn as getPluginCommandSpecs, H as hasInterSessionUserProvenance, Hn as resolveLeastPrivilegeOperatorScopesForMethod, I as capArrayByJsonBytes, In as normalizeChannelId$2, It as isWhatsAppGroupJid, J as resolveChannelResetConfig, Jn as createInternalHookEvent, K as resolveSessionKey$1, Kn as listPluginCommands, L as countToolResults, Ln as logMutatingAdminRpcAudit, Lt as normalizeWhatsAppTarget, M as normalizeDeliveryContext, Mn as GATEWAY_CLIENT_NAMES, N as normalizeSessionDeliveryFields, Nn as getChatChannelMeta, O as resolveCacheTtlMs$1, On as resolveGatewayMessageChannel, Ot as listChannelDocks, P as normalizeAccountId$1, Pn as listChatChannels, Pt as looksLikeHandleOrPhoneTarget, Q as DEFAULT_RESET_TRIGGERS, R as extractToolCallNames, Rn as consumeMutatingAdminRpcBudget, S as readSessionUpdatedAt, Sn as isDeliverableMessageChannel, T as updateSessionStore, Tn as isMarkdownCapableMessageChannel, U as normalizeInputProvenance, Un as clearPluginCommands, V as applyInputProvenanceToUserMessage, Vn as authorizeOperatorScopesForMethod, W as acquireSessionWriteLock, Wn as executePluginCommand, X as resolveSessionResetType, Xn as normalizePluginHttpPath, Y as resolveSessionResetPolicy, Yn as triggerInternalHook, Z as resolveThreadFlag, _ as appendAssistantMessageToSessionTranscript, _n as resolveChannelGroupRequireMention, a as createPluginRegistry, an as resolveTelegramToken, at as resolveMainSessionKey, b as resolveAndPersistSessionFile, bn as resolveGroupSessionKey, bt as parseSlackTarget, c as listAgentsForGateway, ct as listChannelPlugins, d as lookupContextTokens, dn as resolveDefaultSignalAccountId, en as createTelegramActionGate, et as resolveFreshSessionTotalTokens, f as resolveContextTokensForModel, fn as resolveSignalAccount, g as parseSessionThreadInfo, gn as resolveChannelGroupPolicy, h as extractDeliveryInfo, hn as resolveIMessageAccount, i as setActivePluginRegistry, in as resolveTelegramAccount, it as resolveExplicitAgentSessionKey, j as mergeDeliveryContext, jn as GATEWAY_CLIENT_MODES, k as deliveryContextFromSession, kn as resolveMessageChannel, l as loadCombinedSessionStoreForGateway, ln as listEnabledSignalAccounts, lt as normalizeChannelId$1, mn as resolveDefaultIMessageAccountId, n as getActivePluginRegistryKey, nn as listTelegramAccountIds, nt as canonicalizeMainSessionAlias, o as createRuntimeHelpers, on as buildChannelAccountBindings, ot as deriveSessionMetaPatch, p as ensureFasedAgentModelsJson, pn as listIMessageAccountIds, q as evaluateSessionFreshness, qn as matchPluginCommand, r as requireActivePluginRegistry, rt as resolveAgentMainSessionKey, s as classifySessionKey, st as getChannelPlugin, t as getActivePluginRegistry, tn as listEnabledTelegramAccounts, tt as setSessionRuntimeModel, u as resolveSessionModelRef, un as listSignalAccountIds, v as resolveMirroredTranscriptText, vn as resolveChannelGroupToolsPolicy, w as updateLastRoute, wn as isInternalMessageChannel, x as loadSessionStore, xn as INTERNAL_MESSAGE_CHANNEL, y as resolveSessionTranscriptFile, z as parseInlineDirectives$1, zn as ADMIN_SCOPE, zt as normalizeSignalMessagingTarget } from "./runtime-nVJl3PlS.js";
3
3
  import { a as clearActiveProgressLine, c as CHANNEL_IDS, f as normalizeChatChannelId, i as defaultRuntime, l as CHAT_CHANNEL_ORDER, o as registerActiveProgressLine, r as createNonExitingRuntime, s as unregisterActiveProgressLine, t as createSubsystemLogger } from "./subsystem-DBPNbQDQ.js";
4
4
  import { S as normalizeLogLevel, d as isRich, f as theme, i as logVerbose, l as warn, o as setVerbose, p as getChildLogger, s as shouldLogVerbose, t as danger, u as colorize, w as resolvePreferredFasedAgentTmpDir } from "./globals-B_jjtAje.js";
5
5
  import { c as expandHomePrefix, i as resolveGatewayPort, n as resolveConfigPath, s as resolveStateDir, t as STATE_DIR, u as resolveRequiredHomeDir } from "./paths-BEmvSyOV.js";
6
- import { C as isPlainObject, S as truncateUtf16Safe, _ as shortenHomeInString, a as ensureDir$3, b as sliceUtf16Safe, c as isRecord$4, d as normalizeE164, h as resolveUserPath, o as escapeRegExp, r as clampInt, t as CONFIG_DIR, v as shortenHomePath, y as sleep } from "./utils-CYk9EKoq.js";
7
- import { $ as resetConfigOverrides, $i as DEFAULT_MODEL, $n as ANTHROPIC_ROUTE_ID, $r as QWEN_CODING_PLAN_MODEL_IDS, $t as resolveSubagentSpawnModelSelection, Ai as lookupProviderManifestModelCapability, An as markAuthProfileGood, Ar as MINIMAX_PROVIDER_BRAND_ID, At as isSafeExecutableValue, B as MODEL_APIS, Bi as HUGGINGFACE_MODEL_IDS, Bn as normalizeProviderId$2, Br as OPENAI_API_ROUTE_ID, Bt as buildModelAliasIndex, C as resolveIMessageAttachmentRoots, Ca as normalizePluginsConfig, Ci as ZAI_MODEL_IDS, Cn as markAuthProfileFailure, Cr as LITELLM_ROUTE_ID, Ct as unwrapKnownDispatchWrapperInvocation, Di as isOpenAISignInRuntimeModelSupported, Dn as dedupeProfileIds, Dr as MINIMAX_CN_ROUTE_ID, Dt as normalizeSafeBinProfileFixtures, Ei as getProviderBrandManifestForRoute, En as resolveApiKeyForProfile, Er as MINIMAX_API_ROUTE_ID, Et as SAFE_BIN_PROFILES, Fi as VERCEL_AI_GATEWAY_MODEL_IDS, Fr as MOONSHOT_PROVIDER_BRAND_ID, G as isAvatarDataUrl, Gi as formatThinkingLevels, Gn as resolveAuthProfileDisplayLabel, Gr as OPENROUTER_MODEL_IDS, Gt as normalizeModelRef$1, H as parseDurationMs, Hi as CLOUDFLARE_AI_GATEWAY_PROVIDER_BRAND_ID, Hn as discoverFasedAgentPlugins, Hr as OPENAI_PROVIDER_BRAND_ID, Ii as VENICE_MODEL_IDS, In as withFileLock, Ir as MOONSHOT_ROUTE_ID, It as DEFAULT_SUBAGENT_MAX_SPAWN_DEPTH, J as isSupportedLocalAvatarExtension, Ji as normalizeThinkLevel, Jn as assertSecretInputResolved, Jr as QIANFAN_MODEL_IDS, Jt as resolveConfiguredModelRef, K as isAvatarHttpUrl, Ki as formatXHighModelHint, Kn as isPrivateNetworkBaseUrl, Kr as OPENROUTER_PROVIDER_BRAND_ID, Kt as normalizeProviderId$1, Li as TOGETHER_MODEL_IDS, Lr as OLLAMA_PROVIDER_BRAND_ID, Mi as resolveProviderRouteModelCapability, Mn as resolveAuthStorePathForDisplay, Mr as MISTRAL_PROVIDER_BRAND_ID, Ni as LITELLM_BASE_URL, Nn as resolveFasedAgentAgentDir, Nr as MISTRAL_ROUTE_ID, Oi as isStandardProviderCatalogEntry, On as listProfilesForProvider, Or as MINIMAX_MODEL_IDS, Ot as resolveSafeBinProfiles, Pi as XIAOMI_MODEL_IDS, Pr as MOONSHOT_MODEL_IDS, Q as getConfigOverrides, Qi as DEFAULT_CONTEXT_TOKENS, Qn as ANTHROPIC_PROVIDER_BRAND_ID, Qr as QWEN_API_ROUTE_ID, Qt as resolveReasoningDefault, Ri as SYNTHETIC_MODEL_IDS, Rr as OLLAMA_ROUTE_ID, Rt as buildAllowedModelSet, S as mergeInboundPathRoots, Si as XIAOMI_ROUTE_ID, Sn as isProfileInCooldown, Sr as LITELLM_PROVIDER_BRAND_ID, St as isShellWrapperExecutable, T as normalizeScpRemoteHost, Ta as resolveMemorySlotDecision, Ti as ZAI_ROUTE_ID, Tn as resolveProfilesUnavailableReason, Tr as LMSTUDIO_ROUTE_ID, Tt as splitShellArgs, Ui as CLOUDFLARE_AI_GATEWAY_ROUTE_ID, Un as isPathInside, Ur as OPENCODE_ZEN_PROVIDER_BRAND_ID, Ut as isCliProvider, V as getBlockedNetworkModeReason, Vi as CLOUDFLARE_AI_GATEWAY_MODEL_IDS, Vn as loadPluginManifestRegistry, Vr as OPENAI_CODEX_ROUTE_ID, Vt as findNormalizedProviderValue, W as AVATAR_MAX_BYTES, Wi as BASE_THINKING_LEVELS, Wn as safeStatSync, Wr as OPENCODE_ZEN_ROUTE_ID, Wt as modelKey, Xi as supportsThinkingLevel, Xn as splitTrailingAuthProfile, Xr as QIANFAN_ROUTE_ID, Yi as resolveModelThinkingCapability, Yn as coerceSecretRef, Yr as QIANFAN_PROVIDER_BRAND_ID, Yt as resolveDefaultModelForAgent, Z as validateJsonSchemaValue, Zi as supportsXHighThinking, Zn as ANTHROPIC_MODEL_IDS, Zr as QWEN_API_MODEL_IDS, Zt as resolveModelRefFromString, _a as formatCliCommand, _i as VOLCENGINE_ROUTE_ID, _n as normalizeModelCatalogProviderId, _r as GOOGLE_PROVIDER_BRAND_ID, _t as matchAllowlist, a as readConfigFileSnapshotForWrite, aa as extractErrorCode, ai as TOGETHER_ROUTE_ID, an as getApiKeyForModel, ar as BYTEPLUS_ROUTE_ID, at as unsetConfigValueAtPath, b as DEFAULT_IMESSAGE_ATTACHMENT_ROOTS, ba as parseBooleanValue$1, bi as XAI_ROUTE_ID, bn as resolveAuthProfileOrder, br as KIMI_CODING_MODEL_IDS, bt as extractShellWrapperInlineCommand, c as validateConfigObjectWithPlugins, ci as VERCEL_AI_GATEWAY_PROVIDER_BRAND_ID, cn as resolveApiKeyForProvider, cr as CHUTES_ROUTE_ID, ct as isTrustedSafeBinPath, da as resolveShellEnvFallbackTimeoutMs, di as VLLM_ROUTE_ID, dn as CURRENT_MODEL_PROVIDER_CATALOG, dr as COPILOT_PROXY_ROUTE_ID, dt as validateSafeBinArgv, ea as DEFAULT_PROVIDER, ei as QWEN_CODING_PLAN_ROUTE_ID, en as resolveThinkingDefault, er as BYTEPLUS_CODING_MODEL_IDS, et as setConfigOverride, fa as isDangerousHostEnvOverrideVarName, fi as VOLCENGINE_CODING_MODEL_IDS, fn as cloneCurrentModelProvider, fr as CUSTOM_PROVIDER_BRAND_ID, ft as analyzeShellCommand, ga as resolveOwnerDisplaySetting, gi as VOLCENGINE_PROVIDER_BRAND_ID, gn as normalizeModelCatalogModelId, gr as GOOGLE_GEMINI_MODEL_IDS, gt as DEFAULT_SAFE_BINS, ha as sanitizeHostExecEnv, hi as VOLCENGINE_PLAN_ROUTE_ID, hn as mergeModelCatalogRowsByAuthority, hr as GOOGLE_GEMINI_CLI_ROUTE_ID, ht as splitCommandChain, i as readConfigFileSnapshot, ii as TOGETHER_PROVIDER_BRAND_ID, ir as BYTEPLUS_PROVIDER_BRAND_ID, it as setConfigValueAtPath, ji as providerModelRecommendationRank, jn as ensureAuthProfileStore, jr as MISTRAL_MODEL_IDS, ki as listProviderBrandManifests, kn as listProvidersWithStoredCredentials, kr as MINIMAX_PORTAL_ROUTE_ID, kt as applyMergePatch, la as extractArchive, li as VERCEL_AI_GATEWAY_ROUTE_ID, ln as resolveEnvApiKey, lr as COPILOT_PROVIDER_BRAND_ID, lt as listWritableExplicitTrustedSafeBinDirs, ma as isDangerousHostInheritedEnvVarName, mi as VOLCENGINE_MODEL_IDS, mn as buildModelCatalogMergeKey, mr as GOOGLE_API_ROUTE_ID, mt as isWindowsPlatform, n as loadConfig, na as resolvePluginInstallDir, ni as SYNTHETIC_PROVIDER_BRAND_ID, nr as BYTEPLUS_MODEL_IDS, nt as getConfigValueAtPath, o as resolveConfigSnapshotHash, oa as formatErrorMessage, oi as VENICE_PROVIDER_BRAND_ID, on as getCustomProviderApiKey, or as CHUTES_MODEL_IDS, ot as ensurePluginAllowlisted, pi as VOLCENGINE_CODING_ROUTE_ID, pn as listCurrentModelCatalogRows, pr as CUSTOM_PROVIDER_ROUTE_ID, pt as buildEnforcedShellCommand, q as isPathWithinRoot, qn as normalizeSecretInput, qr as OPENROUTER_ROUTE_ID, r as parseConfigJson5, ra as getPackageManifestMetadata, ri as SYNTHETIC_ROUTE_ID, rr as BYTEPLUS_PLAN_ROUTE_ID, rt as parseConfigPath, s as writeConfigFile, si as VENICE_ROUTE_ID, sn as requireApiKey, sr as CHUTES_PROVIDER_BRAND_ID, st as getTrustedSafeBinDirs, t as createConfigIO, ta as VERSION, ti as QWEN_PROVIDER_BRAND_ID, tn as normalizeGoogleModelId, tr as BYTEPLUS_CODING_ROUTE_ID, tt as unsetConfigOverride, ua as getShellPathFromLoginShell, ui as VLLM_PROVIDER_BRAND_ID, un as resolveModelAuthMode, ur as COPILOT_PROXY_MODEL_IDS, ut as normalizeTrustedSafeBinDirs, va as resolveCliName, vi as XAI_MODEL_IDS, vn as normalizeProviderCatalogRows, vr as HUGGINGFACE_PROVIDER_BRAND_ID, vt as resolveAllowlistCandidatePath, w as resolveIMessageRemoteAttachmentRoots, wa as resolveEffectiveEnableState, wi as ZAI_PROVIDER_BRAND_ID, wn as markAuthProfileUsed, wr as LMSTUDIO_PROVIDER_BRAND_ID, wt as unwrapKnownShellMultiplexerInvocation, x as isInboundPathAllowed, xa as applyTestPluginDefaults, xi as XIAOMI_PROVIDER_BRAND_ID, xn as getSoonestCooldownExpiry, xr as KIMI_CODING_ROUTE_ID, xt as isDispatchWrapperExecutable, ya as isTruthyEnvValue, yi as XAI_PROVIDER_BRAND_ID, yr as HUGGINGFACE_ROUTE_ID, yt as resolveCommandResolutionFromArgv, zi as OPENCODE_ZEN_MODEL_IDS, zn as findNormalizedProviderValue$1, zr as OPENAI_API_MODEL_IDS, zt as buildConfiguredAllowlistKeys } from "./config-Bt5GhnA-.js";
8
- import { A as openBoundaryFileSync, C as ensureAgentWorkspace, D as resolveFasedAgentPackageRootSync, E as resolveFasedAgentPackageRoot, G as normalizeHyphenSlug, H as resolveAgentModelPrimaryValue, K as normalizeStringEntries, P as resolvePathViaExistingAncestorSync, S as DEFAULT_USER_FILENAME, T as loadWorkspaceBootstrapFiles, U as toAgentModelListLike, V as resolveAgentModelFallbackValues, W as normalizeAtHashSlug, _ as DEFAULT_BOOTSTRAP_FILENAME, a as resolveAgentDir, b as DEFAULT_SOUL_FILENAME, c as resolveAgentSkillsFilter, d as resolveEffectiveModelFallbacks, f as resolveRunModelFallbacksOverride, g as DEFAULT_AGENT_WORKSPACE_DIR, h as DEFAULT_AGENTS_FILENAME, i as resolveAgentConfig, k as openBoundaryFile, l as resolveAgentWorkspaceDir, m as resolveSessionAgentIds, n as listAgentEntries, p as resolveSessionAgentId, q as normalizeStringEntriesLower, r as listAgentIds, s as resolveAgentModelFallbacksOverride, t as hasConfiguredModelFallbacks, u as resolveDefaultAgentId, v as DEFAULT_HEARTBEAT_FILENAME, w as filterBootstrapFilesForSession, x as DEFAULT_TOOLS_FILENAME, y as DEFAULT_IDENTITY_FILENAME } from "./agent-scope-BbgPlhtw.js";
6
+ import { C as isPlainObject, S as truncateUtf16Safe, _ as shortenHomeInString, a as ensureDir$3, b as sliceUtf16Safe, c as isRecord$5, d as normalizeE164, h as resolveUserPath, o as escapeRegExp, r as clampInt, t as CONFIG_DIR, v as shortenHomePath, y as sleep } from "./utils-CYk9EKoq.js";
7
+ import { $ as resetConfigOverrides, $i as DEFAULT_CONTEXT_TOKENS, $n as ANTHROPIC_PROVIDER_BRAND_ID, $r as QWEN_API_ROUTE_ID, $t as resolveSubagentSpawnModelSelection, Ai as listProviderBrandManifests, An as markAuthProfileGood, Ar as MINIMAX_PORTAL_ROUTE_ID, At as isSafeExecutableValue, B as MODEL_APIS, Bi as OPENCODE_ZEN_MODEL_IDS, Bn as normalizeProviderId$2, Br as OPENAI_API_MODEL_IDS, Bt as buildModelAliasIndex, C as resolveIMessageAttachmentRoots, Ca as applyTestPluginDefaults, Ci as XIAOMI_ROUTE_ID, Cn as markAuthProfileFailure, Cr as LITELLM_PROVIDER_BRAND_ID, Ct as unwrapKnownDispatchWrapperInvocation, Da as resolveMemorySlotDecision, Di as getProviderBrandManifestForRoute, Dn as dedupeProfileIds, Dr as MINIMAX_API_ROUTE_ID, Dt as normalizeSafeBinProfileFixtures, Ea as resolveEffectiveEnableState, Ei as ZAI_ROUTE_ID, En as resolveApiKeyForProfile, Er as LMSTUDIO_ROUTE_ID, Et as SAFE_BIN_PROFILES, Fi as XIAOMI_MODEL_IDS, Fr as MOONSHOT_MODEL_IDS, G as isAvatarDataUrl, Gi as BASE_THINKING_LEVELS, Gn as safeStatSync, Gr as OPENCODE_ZEN_ROUTE_ID, Gt as normalizeModelRef$1, H as parseDurationMs, Hi as CLOUDFLARE_AI_GATEWAY_MODEL_IDS, Hn as loadPluginManifestRegistry, Hr as OPENAI_CODEX_ROUTE_ID, Ii as VERCEL_AI_GATEWAY_MODEL_IDS, In as withFileLock, Ir as MOONSHOT_PROVIDER_BRAND_ID, It as DEFAULT_SUBAGENT_MAX_SPAWN_DEPTH, J as isSupportedLocalAvatarExtension, Jn as normalizeSecretInput, Jr as OPENROUTER_ROUTE_ID, Jt as resolveConfiguredModelRef, K as isAvatarHttpUrl, Ki as formatThinkingLevels, Kn as resolveAuthProfileDisplayLabel, Kr as OPENROUTER_MODEL_IDS, Kt as normalizeProviderId$1, Li as VENICE_MODEL_IDS, Lr as MOONSHOT_ROUTE_ID, Mi as providerModelRecommendationRank, Mn as resolveAuthStorePathForDisplay, Mr as MISTRAL_MODEL_IDS, Ni as resolveProviderRouteModelCapability, Nn as resolveFasedAgentAgentDir, Nr as MISTRAL_PROVIDER_BRAND_ID, Oi as isOpenAISignInRuntimeModelSupported, On as listProfilesForProvider, Or as MINIMAX_CN_ROUTE_ID, Ot as resolveSafeBinProfiles, Pi as LITELLM_BASE_URL, Pr as MISTRAL_ROUTE_ID, Q as getConfigOverrides, Qi as supportsXHighThinking, Qn as ANTHROPIC_MODEL_IDS, Qr as QWEN_API_MODEL_IDS, Qt as resolveReasoningDefault, Ri as TOGETHER_MODEL_IDS, Rr as OLLAMA_PROVIDER_BRAND_ID, Rt as buildAllowedModelSet, S as mergeInboundPathRoots, Sa as parseBooleanValue$1, Si as XIAOMI_PROVIDER_BRAND_ID, Sn as isProfileInCooldown, Sr as KIMI_CODING_ROUTE_ID, St as isShellWrapperExecutable, T as normalizeScpRemoteHost, Ta as normalizePluginsConfig, Ti as ZAI_PROVIDER_BRAND_ID, Tn as resolveProfilesUnavailableReason, Tr as LMSTUDIO_PROVIDER_BRAND_ID, Tt as splitShellArgs, Ui as CLOUDFLARE_AI_GATEWAY_PROVIDER_BRAND_ID, Un as discoverFasedAgentPlugins, Ur as OPENAI_PROVIDER_BRAND_ID, Ut as isCliProvider, V as getBlockedNetworkModeReason, Vi as HUGGINGFACE_MODEL_IDS, Vn as clearPluginManifestRegistryCache, Vr as OPENAI_API_ROUTE_ID, Vt as findNormalizedProviderValue, W as AVATAR_MAX_BYTES, Wi as CLOUDFLARE_AI_GATEWAY_ROUTE_ID, Wn as isPathInside, Wr as OPENCODE_ZEN_PROVIDER_BRAND_ID, Wt as modelKey, Xi as resolveModelThinkingCapability, Xn as coerceSecretRef, Xr as QIANFAN_PROVIDER_BRAND_ID, Yi as normalizeThinkLevel, Yn as assertSecretInputResolved, Yr as QIANFAN_MODEL_IDS, Yt as resolveDefaultModelForAgent, Z as validateJsonSchemaValue, Zi as supportsThinkingLevel, Zn as splitTrailingAuthProfile, Zr as QIANFAN_ROUTE_ID, Zt as resolveModelRefFromString, _a as sanitizeHostExecEnv, _i as VOLCENGINE_PROVIDER_BRAND_ID, _n as normalizeModelCatalogProviderId, _r as GOOGLE_GEMINI_MODEL_IDS, _t as matchAllowlist, a as readConfigFileSnapshotForWrite, aa as getPackageManifestMetadata, ai as TOGETHER_PROVIDER_BRAND_ID, an as getApiKeyForModel, ar as BYTEPLUS_PROVIDER_BRAND_ID, at as unsetConfigValueAtPath, b as DEFAULT_IMESSAGE_ATTACHMENT_ROOTS, ba as resolveCliName, bi as XAI_PROVIDER_BRAND_ID, bn as resolveAuthProfileOrder, br as HUGGINGFACE_ROUTE_ID, bt as extractShellWrapperInlineCommand, c as validateConfigObjectWithPlugins, ca as formatErrorMessage, ci as VENICE_ROUTE_ID, cn as resolveApiKeyForProvider, cr as CHUTES_PROVIDER_BRAND_ID, ct as isTrustedSafeBinPath, da as extractArchive, di as VLLM_PROVIDER_BRAND_ID, dn as CURRENT_MODEL_PROVIDER_CATALOG, dr as COPILOT_PROXY_MODEL_IDS, dt as validateSafeBinArgv, ea as DEFAULT_MODEL, ei as QWEN_CODING_PLAN_MODEL_IDS, en as resolveThinkingDefault, er as ANTHROPIC_ROUTE_ID, et as setConfigOverride, fa as getShellPathFromLoginShell, fi as VLLM_ROUTE_ID, fn as cloneCurrentModelProvider, fr as COPILOT_PROXY_ROUTE_ID, ft as analyzeShellCommand, ga as isDangerousHostInheritedEnvVarName, gi as VOLCENGINE_PLAN_ROUTE_ID, gn as normalizeModelCatalogModelId, gr as GOOGLE_GEMINI_CLI_ROUTE_ID, gt as DEFAULT_SAFE_BINS, hi as VOLCENGINE_MODEL_IDS, hn as mergeModelCatalogRowsByAuthority, hr as GOOGLE_API_ROUTE_ID, ht as splitCommandChain, i as readConfigFileSnapshot, ia as resolvePluginInstallDir, ii as SYNTHETIC_ROUTE_ID, ir as BYTEPLUS_PLAN_ROUTE_ID, it as setConfigValueAtPath, ji as lookupProviderManifestModelCapability, jn as ensureAuthProfileStore, jr as MINIMAX_PROVIDER_BRAND_ID, ka as applyExclusiveSlotSelection, ki as isStandardProviderCatalogEntry, kn as listProvidersWithStoredCredentials, kr as MINIMAX_MODEL_IDS, kt as applyMergePatch, li as VERCEL_AI_GATEWAY_PROVIDER_BRAND_ID, ln as resolveEnvApiKey, lr as CHUTES_ROUTE_ID, lt as listWritableExplicitTrustedSafeBinDirs, ma as isDangerousHostEnvOverrideVarName, mi as VOLCENGINE_CODING_ROUTE_ID, mn as buildModelCatalogMergeKey, mr as CUSTOM_PROVIDER_ROUTE_ID, mt as isWindowsPlatform, n as loadConfig, na as VERSION, ni as QWEN_PROVIDER_BRAND_ID, nr as BYTEPLUS_CODING_ROUTE_ID, nt as getConfigValueAtPath, o as resolveConfigSnapshotHash, oi as TOGETHER_ROUTE_ID, on as getCustomProviderApiKey, or as BYTEPLUS_ROUTE_ID, ot as ensurePluginAllowlisted, pa as resolveShellEnvFallbackTimeoutMs, pi as VOLCENGINE_CODING_MODEL_IDS, pn as listCurrentModelCatalogRows, pr as CUSTOM_PROVIDER_BRAND_ID, pt as buildEnforcedShellCommand, q as isPathWithinRoot, qi as formatXHighModelHint, qn as isPrivateNetworkBaseUrl, qr as OPENROUTER_PROVIDER_BRAND_ID, r as parseConfigJson5, ra as installPluginFromNpmSpec, ri as SYNTHETIC_PROVIDER_BRAND_ID, rr as BYTEPLUS_MODEL_IDS, rt as parseConfigPath, s as writeConfigFile, sa as extractErrorCode, si as VENICE_PROVIDER_BRAND_ID, sn as requireApiKey, sr as CHUTES_MODEL_IDS, st as getTrustedSafeBinDirs, t as createConfigIO, ta as DEFAULT_PROVIDER, ti as QWEN_CODING_PLAN_ROUTE_ID, tn as normalizeGoogleModelId, tr as BYTEPLUS_CODING_MODEL_IDS, tt as unsetConfigOverride, ui as VERCEL_AI_GATEWAY_ROUTE_ID, un as resolveModelAuthMode, ur as COPILOT_PROVIDER_BRAND_ID, ut as normalizeTrustedSafeBinDirs, va as resolveOwnerDisplaySetting, vi as VOLCENGINE_ROUTE_ID, vn as normalizeProviderCatalogRows, vr as GOOGLE_PROVIDER_BRAND_ID, vt as resolveAllowlistCandidatePath, w as resolveIMessageRemoteAttachmentRoots, wi as ZAI_MODEL_IDS, wn as markAuthProfileUsed, wr as LITELLM_ROUTE_ID, wt as unwrapKnownShellMultiplexerInvocation, x as isInboundPathAllowed, xa as isTruthyEnvValue, xi as XAI_ROUTE_ID, xn as getSoonestCooldownExpiry, xr as KIMI_CODING_MODEL_IDS, xt as isDispatchWrapperExecutable, ya as formatCliCommand, yi as XAI_MODEL_IDS, yr as HUGGINGFACE_PROVIDER_BRAND_ID, yt as resolveCommandResolutionFromArgv, zi as SYNTHETIC_MODEL_IDS, zn as findNormalizedProviderValue$1, zr as OLLAMA_ROUTE_ID, zt as buildConfiguredAllowlistKeys } from "./config-Dbxj_jUP.js";
8
+ import { A as openBoundaryFile, C as ensureAgentWorkspace, D as resolveFasedAgentPackageRoot, E as resolveDefaultAgentWorkspaceDir, F as resolvePathViaExistingAncestorSync, G as normalizeAtHashSlug, H as resolveAgentModelFallbackValues, J as normalizeStringEntriesLower, K as normalizeHyphenSlug, O as resolveFasedAgentPackageRootSync, S as DEFAULT_USER_FILENAME, T as loadWorkspaceBootstrapFiles, U as resolveAgentModelPrimaryValue, W as toAgentModelListLike, _ as DEFAULT_BOOTSTRAP_FILENAME, a as resolveAgentDir, b as DEFAULT_SOUL_FILENAME, c as resolveAgentSkillsFilter, d as resolveEffectiveModelFallbacks, f as resolveRunModelFallbacksOverride, g as DEFAULT_AGENT_WORKSPACE_DIR, h as DEFAULT_AGENTS_FILENAME, i as resolveAgentConfig, j as openBoundaryFileSync, l as resolveAgentWorkspaceDir, m as resolveSessionAgentIds, n as listAgentEntries, p as resolveSessionAgentId, q as normalizeStringEntries, r as listAgentIds, s as resolveAgentModelFallbacksOverride, t as hasConfiguredModelFallbacks, u as resolveDefaultAgentId, v as DEFAULT_HEARTBEAT_FILENAME, w as filterBootstrapFilesForSession, x as DEFAULT_TOOLS_FILENAME, y as DEFAULT_IDENTITY_FILENAME } from "./agent-scope-CCjfjKoO.js";
9
9
  import { t as normalizeChatType } from "./chat-type-C0osVllE.js";
10
10
  import { n as resolveAccountEntry } from "./account-helpers-Bdfws46K.js";
11
11
  import { C as resolveThreadParentSessionKey, S as parseAgentSessionKey, _ as getSubagentDepth, b as isCronSessionKey, c as normalizeMainKey, d as sanitizeAgentId, f as DEFAULT_ACCOUNT_ID, g as deriveSessionChatType, h as isBlockedObjectKey, l as resolveAgentIdFromSessionKey, m as normalizeOptionalAccountId, o as classifySessionKeyShape, p as normalizeAccountId$2, r as buildAgentMainSessionKey, s as normalizeAgentId, t as DEFAULT_AGENT_ID, u as resolveThreadSessionKeys, v as isAcpSessionKey, x as isSubagentSessionKey } from "./session-key-HSJ2KQTc.js";
@@ -13,7 +13,7 @@ import { a as resolveDiscordAccount, r as listEnabledDiscordAccounts, t as creat
13
13
  import { i as resolveSlackAccount } from "./accounts-CuqIKU8X.js";
14
14
  import { i as logWarn, n as logError, r as logInfo, t as logDebug } from "./logger-BbFvCoKk.js";
15
15
  import { n as runExec, r as spawnWithFallback, t as runCommandWithTimeout } from "./exec-DQ8j4Fm3.js";
16
- import { _ as webAuthExists, c as logWebSelfId, i as resolveWhatsAppAccount, l as logoutWeb, p as readWebSelfId, s as getWebAuthAgeMs, t as hasAnyWhatsAppAuth } from "./accounts-DzWlKv1U.js";
16
+ import { _ as webAuthExists, c as logWebSelfId, i as resolveWhatsAppAccount, l as logoutWeb, p as readWebSelfId, s as getWebAuthAgeMs, t as hasAnyWhatsAppAuth } from "./accounts-CmMwe9Dt.js";
17
17
  import { S as resolveChannelEntryMatchWithFallback, b as normalizeChannelSlug, y as buildChannelKeyCandidates } from "./allow-list-DyAxs4yw.js";
18
18
  import { n as redactSensitiveText, r as redactToolDetail, t as getDefaultRedactPatterns } from "./redact-Bm8vu_ju.js";
19
19
  import { a as saveJsonFile, i as loadJsonFile, r as resolveCopilotApiToken } from "./github-copilot-token-CUK__1s1.js";
@@ -21,19 +21,19 @@ import { t as runTasksWithConcurrency } from "./run-with-concurrency-BsDJWzgM.js
21
21
  import { n as retryAsync } from "./retry-DstNBhDW.js";
22
22
  import { a as resolveSessionTranscriptPath, c as resolveSessionTranscriptsDirForAgent, i as resolveSessionFilePathOptions, l as resolveStorePath, n as resolveDefaultSessionStorePath, r as resolveSessionFilePath } from "./paths-CTZ2RS_E.js";
23
23
  import { t as emitSessionTranscriptUpdate } from "./transcript-events-BJQWUdmU.js";
24
- import { l as resolveChannelDefaultAccountId } from "./pairing-message-ClqhfCUk.js";
24
+ import { l as resolveChannelDefaultAccountId } from "./pairing-message-r-VQfhFB.js";
25
25
  import { n as fetchWithTimeout, t as bindAbortRelay } from "./fetch-timeout-l_6RdoMw.js";
26
26
  import { t as normalizeRequestInitHeadersForFetch } from "./fetch-headers-my7hgV2G.js";
27
27
  import { a as isBlockedHostnameOrIp, t as SsrFBlockedError } from "./ssrf-fG4UHKBw.js";
28
28
  import { t as fetchWithSsrFGuard } from "./fetch-guard-CeG6u6ld.js";
29
29
  import { n as redactSensitiveUrlLikeString, t as redactSensitiveUrl } from "./redact-sensitive-url-g-ukZjwA.js";
30
- import { a as formatIMessageChatTarget, c as normalizeIMessageHandle, i as DEFAULT_IMESSAGE_PROBE_TIMEOUT_MS, l as parseIMessageTarget, o as formatIMessageTargetForLog, r as createIMessageRpcClient, s as isAllowedIMessageSender, t as sendMessageIMessage } from "./send-DPJIIYAs.js";
31
- import { A as resolveDefaultGroupPolicy, D as formatDocsLink, M as warnMissingProviderGroupPolicyFallbackOnce, b as setOnboardingChannelEnabled, c as parseOnboardingEntriesAllowingWildcard, f as promptParsedAllowFromForScopedChannel, h as resolveAccountIdForConfigure, j as resolveOpenProviderRuntimeGroupPolicy, k as resolveAllowlistProviderRuntimeGroupPolicy, l as patchChannelConfigForAccount, v as setChannelDmPolicyWithAllowFrom } from "./helpers-CluGKuIV.js";
32
- import { A as formatLocationText, F as isSenderIdAllowed, I as mergeDmAllowFromSources, L as resolveGroupAllowFromSources, N as isVoiceCompatibleAudio, P as firstDefined$1, a as resolveCronStorePath, d as buildTelegramGroupPeerId, i as loadCronStore, j as toLocationContext, o as saveCronStore } from "./wsl-B_ojyEtC.js";
33
- import { a as upsertChannelPairingRequest, c as getPairingAdapter, i as removeChannelAllowFromStoreEntry, l as listPairingChannels, n as readChannelAllowFromStore, o as readJsonFileWithFallback, s as writeJsonFileAtomically, t as addChannelAllowFromStoreEntry } from "./pairing-store-B01mCSct.js";
34
- import { a as chunkText, c as resolveChunkMode, d as isSafeFenceBreak, f as parseFenceSpans, i as chunkMarkdownTextWithMode, l as resolveTextChunkLimit, n as chunkByParagraph, o as chunkTextWithMode, p as chunkTextByBreakResolver, r as chunkMarkdownText, t as chunkByNewline, u as findFenceSpanAt } from "./chunk-B8EZkwiT.js";
30
+ import { a as formatIMessageChatTarget, c as normalizeIMessageHandle, i as DEFAULT_IMESSAGE_PROBE_TIMEOUT_MS, l as parseIMessageTarget, o as formatIMessageTargetForLog, r as createIMessageRpcClient, s as isAllowedIMessageSender, t as sendMessageIMessage } from "./send-BHokB4TR.js";
31
+ import { A as resolveDefaultGroupPolicy, D as formatDocsLink, M as warnMissingProviderGroupPolicyFallbackOnce, b as setOnboardingChannelEnabled, c as parseOnboardingEntriesAllowingWildcard, f as promptParsedAllowFromForScopedChannel, h as resolveAccountIdForConfigure, j as resolveOpenProviderRuntimeGroupPolicy, k as resolveAllowlistProviderRuntimeGroupPolicy, l as patchChannelConfigForAccount, v as setChannelDmPolicyWithAllowFrom } from "./helpers-CDo2XBSr.js";
32
+ import { A as formatLocationText, F as isSenderIdAllowed, I as mergeDmAllowFromSources, L as resolveGroupAllowFromSources, N as isVoiceCompatibleAudio, P as firstDefined$1, a as resolveCronStorePath, d as buildTelegramGroupPeerId, i as loadCronStore, j as toLocationContext, o as saveCronStore } from "./wsl-BtMDzMv5.js";
33
+ import { a as upsertChannelPairingRequest, c as getPairingAdapter, i as removeChannelAllowFromStoreEntry, l as listPairingChannels, n as readChannelAllowFromStore, o as readJsonFileWithFallback, s as writeJsonFileAtomically, t as addChannelAllowFromStoreEntry } from "./pairing-store-uPnLfGgB.js";
34
+ import { a as chunkText, c as resolveChunkMode, d as isSafeFenceBreak, f as parseFenceSpans, i as chunkMarkdownTextWithMode, l as resolveTextChunkLimit, n as chunkByParagraph, o as chunkTextWithMode, p as chunkTextByBreakResolver, r as chunkMarkdownText, t as chunkByNewline, u as findFenceSpanAt } from "./chunk-CF8nvZNj.js";
35
35
  import { c as normalizeDeviceAuthScopes, i as clearDevicePairing, s as normalizeDeviceAuthRole } from "./tailscale-status-DwpNdO3Z.js";
36
- import { c as resolveHumanDelayConfig, i as resolveResponsePrefixTemplate, n as createReplyPrefixOptions, o as resolveAgentIdentity, s as resolveEffectiveMessagesConfig } from "./reply-prefix-ClpxvL_w.js";
36
+ import { c as resolveHumanDelayConfig, i as resolveResponsePrefixTemplate, n as createReplyPrefixOptions, o as resolveAgentIdentity, s as resolveEffectiveMessagesConfig } from "./reply-prefix-CeVw7Mn2.js";
37
37
  import { i as isSilentReplyText, n as SILENT_REPLY_TOKEN, r as isSilentReplyPrefixText, t as HEARTBEAT_TOKEN } from "./tokens-BbnqfVuu.js";
38
38
  import { n as safeEqualSecret, o as createAsyncLock, s as readJsonFile$1 } from "./pairing-token-Cs3BRKc0.js";
39
39
  import { n as generateSecureUuid, t as generateSecureToken } from "./secure-random-BIkG-k4s.js";
@@ -41,37 +41,37 @@ import { a as logMessageProcessed, i as logLaneEnqueue, m as isDiagnosticsEnable
41
41
  import { r as getDiagnosticSessionState } from "./diagnostic-session-state-DqgfGYqZ.js";
42
42
  import { t as redactIdentifier } from "./redact-identifier-Lt7t3l7S.js";
43
43
  import { i as resolveTelegramTargetChatType, r as parseTelegramTarget } from "./targets-CoMJ1ry1.js";
44
- import { t as importOptionalRuntimeDependency } from "./optional-runtime-dependency-DKmk9PZa.js";
45
- import { c as detectMime, d as imageMimeFromFormat, f as isAudioFileName, g as MAX_IMAGE_BYTES, i as getImageMetadata, l as extensionForMime, m as kindFromMime, n as buildImageResizeSideGrid, s as resizeToJpeg, t as IMAGE_REDUCE_QUALITY_STEPS, u as getFileExtension, v as mediaKindFromMime } from "./image-ops-CUaLtIFj.js";
46
- import { t as resolveMemorySearchConfig } from "./memory-search-VFll-AIb.js";
47
- import { i as executeWithApiKeyRotation, n as parseGeminiAuth, r as collectProviderApiKeysForExecution } from "./manager-oHAvZCT3.js";
44
+ import { t as importOptionalRuntimeDependency } from "./optional-runtime-dependency-BlTVkcAg.js";
45
+ import { c as detectMime, d as imageMimeFromFormat, f as isAudioFileName, g as MAX_IMAGE_BYTES, i as getImageMetadata, l as extensionForMime, m as kindFromMime, n as buildImageResizeSideGrid, s as resizeToJpeg, t as IMAGE_REDUCE_QUALITY_STEPS, u as getFileExtension, v as mediaKindFromMime } from "./image-ops-DbeBxbn4.js";
46
+ import { t as resolveMemorySearchConfig } from "./memory-search-DTjIMw8J.js";
47
+ import { i as executeWithApiKeyRotation, n as parseGeminiAuth, r as collectProviderApiKeysForExecution } from "./manager-CbiFFLKS.js";
48
48
  import { c as normalizeExtraMemoryPaths, s as listMemoryFiles } from "./internal-CG_nHo-2.js";
49
49
  import { i as resolveQmdScopeDenial } from "./qmd-scope-CdX34VCV.js";
50
- import { _ as estimateBase64DecodedBytes, a as jsonResult, d as readStringParam, f as sanitizeContentBlocksImages, g as canonicalizeBase64, h as resolveImageSanitizationLimits, i as imageResultFromFile, l as readStringArrayParam, m as sanitizeToolResultImages, n as createActionGate, p as sanitizeImageBlocks, r as imageResult, s as readNumberParam, u as readStringOrNumberParam } from "./common-CbfckC19.js";
51
- import { S as isCommandFlagEnabled, _ as normalizeElevatedLevel, a as listChatCommands, b as normalizeVerboseLevel, g as shouldHandleTextCommands, i as isCommandEnabled, l as maybeResolveTextAlias, m as resolveNativeCommandName, o as listChatCommandsForConfig, u as normalizeCommandBody, v as normalizeReasoningLevel, w as isRestartEnabled, x as resolveResponseUsageMode, y as normalizeUsageDisplay } from "./commands-registry-BfEa4tFA.js";
52
- import { A as fetchJson$1, B as DEFAULT_BROWSER_EVALUATE_ENABLED, C as normalizeCdpWsUrl, D as assertBrowserNavigationResultAllowed, E as assertBrowserNavigationAllowed, F as stopChromeExtensionRelayServer, G as isLoopbackHost, H as DEFAULT_FASED_BROWSER_ENABLED, I as DEFAULT_AI_SNAPSHOT_EFFICIENT_DEPTH, J as resolveClientIp, K as isSecureWebSocketUrl, L as DEFAULT_AI_SNAPSHOT_EFFICIENT_MAX_CHARS, O as withBrowserNavigationPolicy, P as ensureChromeExtensionRelayServer, R as DEFAULT_AI_SNAPSHOT_MAX_CHARS, T as InvalidBrowserNavigationUrlError, U as DEFAULT_FASED_BROWSER_PROFILE_NAME, V as DEFAULT_FASED_BROWSER_COLOR, W as isLoopbackAddress, X as rawDataToString, Y as resolveForwardedClientIp, _ as stopFasedAgentChrome, a as DEFAULT_TRACE_DIR, b as captureScreenshot, d as normalizeBrowserFormField, g as resolveFasedAgentUserDataDir, h as launchFasedAgentChrome, i as DEFAULT_DOWNLOAD_DIR, j as fetchOk, k as appendCdpPath, l as resolveWritablePathWithinRoot, m as isChromeReachable, o as DEFAULT_UPLOAD_DIR, p as isChromeCdpReady, q as isTrustedProxyAddress, r as loadReadability, s as resolveExistingPathsWithinRoot, t as loadLinkedom, v as resolveBrowserExecutableForPlatform, w as snapshotAria, x as createTargetViaCdp, y as resolveLsofCommandSync, z as DEFAULT_BROWSER_DEFAULT_PROFILE_NAME } from "./runtime-dependency-CIw9t7-k.js";
53
- import { t as PATH_ALIAS_POLICIES } from "./path-alias-guards-BJZD5JMJ.js";
54
- import { a as writeFileWithinRoot, n as openFileWithinRoot, r as readFileWithinRoot, t as SafeOpenError } from "./fs-safe-xBqok6yR.js";
55
- import { n as resolveMarkdownTableMode } from "./markdown-tables-Mkx7k92Y.js";
56
- import { a as fetchRemoteMedia, d as getDefaultMediaLocalRoots, i as MediaFetchError, n as loadWebMedia, o as readResponseWithLimit, t as getDefaultLocalRoots, u as getAgentScopedMediaLocalRoots } from "./media-CA8sTmVE.js";
57
- import { a as resolveSignalRpcContext, c as streamSignalEvents, l as markdownToSignalTextChunks, n as sendReadReceiptSignal, o as signalCheck, r as sendTypingSignal, s as signalRpcRequest, t as sendMessageSignal } from "./send-J4JWKP62.js";
58
- import { a as saveMediaBuffer, i as getMediaDir, n as ensureMediaDir } from "./outbound-attachment-DdVkqUzE.js";
50
+ import { _ as estimateBase64DecodedBytes, a as jsonResult, d as readStringParam, f as sanitizeContentBlocksImages, g as canonicalizeBase64, h as resolveImageSanitizationLimits, i as imageResultFromFile, l as readStringArrayParam, m as sanitizeToolResultImages, n as createActionGate, p as sanitizeImageBlocks, r as imageResult, s as readNumberParam, u as readStringOrNumberParam } from "./common-Cky4hpqr.js";
51
+ import { S as isCommandFlagEnabled, _ as normalizeElevatedLevel, a as listChatCommands, b as normalizeVerboseLevel, g as shouldHandleTextCommands, i as isCommandEnabled, l as maybeResolveTextAlias, m as resolveNativeCommandName, o as listChatCommandsForConfig, u as normalizeCommandBody, v as normalizeReasoningLevel, w as isRestartEnabled, x as resolveResponseUsageMode, y as normalizeUsageDisplay } from "./commands-registry-CK4KmMG0.js";
52
+ import { A as fetchJson$1, B as DEFAULT_BROWSER_EVALUATE_ENABLED, C as normalizeCdpWsUrl, D as assertBrowserNavigationResultAllowed, E as assertBrowserNavigationAllowed, F as stopChromeExtensionRelayServer, G as isLoopbackHost, H as DEFAULT_FASED_BROWSER_ENABLED, I as DEFAULT_AI_SNAPSHOT_EFFICIENT_DEPTH, J as resolveClientIp, K as isSecureWebSocketUrl, L as DEFAULT_AI_SNAPSHOT_EFFICIENT_MAX_CHARS, O as withBrowserNavigationPolicy, P as ensureChromeExtensionRelayServer, R as DEFAULT_AI_SNAPSHOT_MAX_CHARS, T as InvalidBrowserNavigationUrlError, U as DEFAULT_FASED_BROWSER_PROFILE_NAME, V as DEFAULT_FASED_BROWSER_COLOR, W as isLoopbackAddress, X as rawDataToString, Y as resolveForwardedClientIp, _ as stopFasedAgentChrome, a as DEFAULT_TRACE_DIR, b as captureScreenshot, d as normalizeBrowserFormField, g as resolveFasedAgentUserDataDir, h as launchFasedAgentChrome, i as DEFAULT_DOWNLOAD_DIR, j as fetchOk, k as appendCdpPath, l as resolveWritablePathWithinRoot, m as isChromeReachable, o as DEFAULT_UPLOAD_DIR, p as isChromeCdpReady, q as isTrustedProxyAddress, r as loadReadability, s as resolveExistingPathsWithinRoot, t as loadLinkedom, v as resolveBrowserExecutableForPlatform, w as snapshotAria, x as createTargetViaCdp, y as resolveLsofCommandSync, z as DEFAULT_BROWSER_DEFAULT_PROFILE_NAME } from "./runtime-dependency-DlqVSsSs.js";
53
+ import { t as PATH_ALIAS_POLICIES } from "./path-alias-guards-DjgDArrp.js";
54
+ import { a as writeFileWithinRoot, n as openFileWithinRoot, r as readFileWithinRoot, t as SafeOpenError } from "./fs-safe-g4g7GT02.js";
55
+ import { n as resolveMarkdownTableMode } from "./markdown-tables-Bskt9r8i.js";
56
+ import { a as fetchRemoteMedia, d as getDefaultMediaLocalRoots, i as MediaFetchError, n as loadWebMedia, o as readResponseWithLimit, t as getDefaultLocalRoots, u as getAgentScopedMediaLocalRoots } from "./media-B3aAg5rh.js";
57
+ import { a as resolveSignalRpcContext, c as streamSignalEvents, l as markdownToSignalTextChunks, n as sendReadReceiptSignal, o as signalCheck, r as sendTypingSignal, s as signalRpcRequest, t as sendMessageSignal } from "./send-D3DQOg2a.js";
58
+ import { a as saveMediaBuffer, i as getMediaDir, n as ensureMediaDir } from "./outbound-attachment-2RckWqrk.js";
59
59
  import { t as resolveFetch } from "./fetch-BtmoPIlf.js";
60
- import { B as isSessionBindingError, C as resolveThreadBindingMaxAgeMs$1, F as resolveThreadBindingIntroText, G as resolveSessionStorePathForAcp, I as resolveThreadBindingThreadName, K as upsertAcpSessionMeta, L as SYSTEM_MARK, N as formatThreadBindingDurationLabel, R as prefixSystemMessage, S as resolveThreadBindingMaxAgeExpiresAt, U as listAcpSessionEntries, W as readAcpSessionEntry, b as resolveThreadBindingIdleTimeoutMs$1, c as getThreadBindingManager, x as resolveThreadBindingInactivityExpiresAt, z as getSessionBindingService } from "./thread-bindings.state-BgYWFjNF.js";
61
- import { c as getSkillsSnapshotVersion, d as resolveSkillsPromptForRun, f as syncSkillsToWorkspace, h as sanitizeEnvVars, i as resolveSkillCommandInvocation, l as buildWorkspaceSkillSnapshot, m as applySkillEnvOverridesFromSnapshot, n as listSkillCommandsForAgents, o as getRemoteSkillEligibility, p as applySkillEnvOverrides, r as listSkillCommandsForWorkspace, s as ensureSkillsWatcher, t as listReservedChatSlashCommandNames, u as loadWorkspaceSkillEntries } from "./skill-commands-B7wx9ax8.js";
62
- import { a as resolveSandboxedMediaSource, i as resolveSandboxPath, n as assertSandboxPath, r as resolveSandboxInputPath, t as assertMediaNotDataUrl } from "./sandbox-paths-w64tYl0v.js";
60
+ import { B as isSessionBindingError, C as resolveThreadBindingMaxAgeMs$1, F as resolveThreadBindingIntroText, G as resolveSessionStorePathForAcp, I as resolveThreadBindingThreadName, K as upsertAcpSessionMeta, L as SYSTEM_MARK, N as formatThreadBindingDurationLabel, R as prefixSystemMessage, S as resolveThreadBindingMaxAgeExpiresAt, U as listAcpSessionEntries, W as readAcpSessionEntry, b as resolveThreadBindingIdleTimeoutMs$1, c as getThreadBindingManager, x as resolveThreadBindingInactivityExpiresAt, z as getSessionBindingService } from "./thread-bindings.state-D7xG1GHu.js";
61
+ import { c as getSkillsSnapshotVersion, d as resolveSkillsPromptForRun, f as syncSkillsToWorkspace, h as sanitizeEnvVars, i as resolveSkillCommandInvocation, l as buildWorkspaceSkillSnapshot, m as applySkillEnvOverridesFromSnapshot, n as listSkillCommandsForAgents, o as getRemoteSkillEligibility, p as applySkillEnvOverrides, r as listSkillCommandsForWorkspace, s as ensureSkillsWatcher, t as listReservedChatSlashCommandNames, u as loadWorkspaceSkillEntries } from "./skill-commands-CmdoKLh_.js";
62
+ import { a as resolveSandboxedMediaSource, i as resolveSandboxPath, n as assertSandboxPath, r as resolveSandboxInputPath, t as assertMediaNotDataUrl } from "./sandbox-paths-Dx2lUqCu.js";
63
63
  import { n as resolveUserTimeFormat, r as resolveUserTimezone, t as formatUserTime } from "./date-time-uUevHscU.js";
64
- import { t as parseDiscordTarget } from "./targets-QfP164Dh.js";
64
+ import { t as parseDiscordTarget } from "./targets-BeGUCGWK.js";
65
65
  import { n as missingTargetError, r as unknownTargetError, t as ambiguousTargetError } from "./target-errors-Ckufe179.js";
66
- import { i as discoverModels, r as discoverAuthStorage } from "./pi-model-discovery-Buz0JC1Y.js";
66
+ import { i as discoverModels, r as discoverAuthStorage } from "./pi-model-discovery-BpEilAym.js";
67
67
  import { n as normalizePollInput } from "./polls-DKQXVfJp.js";
68
- import { n as resolveAgentRoute, t as buildAgentSessionKey } from "./resolve-route-CkNIKKEW.js";
68
+ import { n as resolveAgentRoute, t as buildAgentSessionKey } from "./resolve-route-B8fOfihG.js";
69
69
  import { r as normalizeInboundTextNewlines, t as finalizeInboundContext } from "./inbound-context-DrAcXE0y.js";
70
70
  import { n as recordCommandPoll, r as resetCommandPollCount } from "./command-poll-backoff-yJU83wEq.js";
71
- import { t as convertMarkdownTables } from "./tables-CjlQJV4r.js";
71
+ import { t as convertMarkdownTables } from "./tables-EX4Hy-a-.js";
72
72
  import { n as recordChannelActivity, t as getChannelActivity } from "./channel-activity-DBDMQ3yI.js";
73
73
  import { t as withTimeout$3 } from "./with-timeout-ckWB8rTo.js";
74
- import { t as getActiveWebListener } from "./active-listener-x4MLhYUw.js";
74
+ import { t as getActiveWebListener } from "./active-listener-DVbpcisf.js";
75
75
  import { n as asString$4, r as collectIssuesForEnabledAccounts } from "./shared-CBgp_GBw.js";
76
76
  import { createRequire } from "node:module";
77
77
  import * as path$1 from "node:path";
@@ -1810,7 +1810,7 @@ function createHookRunner(registry, options = {}) {
1810
1810
  * Singleton hook runner that's initialized when plugins are loaded
1811
1811
  * and can be called from anywhere in the codebase.
1812
1812
  */
1813
- const log$21 = createSubsystemLogger("plugins");
1813
+ const log$22 = createSubsystemLogger("plugins");
1814
1814
  let globalHookRunner = null;
1815
1815
  let globalRegistry = null;
1816
1816
  /**
@@ -1821,14 +1821,14 @@ function initializeGlobalHookRunner(registry) {
1821
1821
  globalRegistry = registry;
1822
1822
  globalHookRunner = createHookRunner(registry, {
1823
1823
  logger: {
1824
- debug: (msg) => log$21.debug(msg),
1825
- warn: (msg) => log$21.warn(msg),
1826
- error: (msg) => log$21.error(msg)
1824
+ debug: (msg) => log$22.debug(msg),
1825
+ warn: (msg) => log$22.warn(msg),
1826
+ error: (msg) => log$22.error(msg)
1827
1827
  },
1828
1828
  catchErrors: true
1829
1829
  });
1830
1830
  const hookCount = registry.hooks.length;
1831
- if (hookCount > 0) log$21.info(`hook runner initialized with ${hookCount} registered hooks`);
1831
+ if (hookCount > 0) log$22.info(`hook runner initialized with ${hookCount} registered hooks`);
1832
1832
  }
1833
1833
  /**
1834
1834
  * Get the global hook runner.
@@ -7414,7 +7414,7 @@ async function discoverGitHubCopilotModels(params) {
7414
7414
  //#region src/agents/openai-codex-app-server.ts
7415
7415
  const OPENAI_CODEX_APP_SERVER_VERSION = "0.144.1";
7416
7416
  const DEFAULT_REQUEST_TIMEOUT_MS = 12e4;
7417
- function isRecord$3(value) {
7417
+ function isRecord$4(value) {
7418
7418
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
7419
7419
  }
7420
7420
  function decodeJwtPayload$1(token) {
@@ -7422,14 +7422,14 @@ function decodeJwtPayload$1(token) {
7422
7422
  if (!encoded) return null;
7423
7423
  try {
7424
7424
  const parsed = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
7425
- return isRecord$3(parsed) ? parsed : null;
7425
+ return isRecord$4(parsed) ? parsed : null;
7426
7426
  } catch {
7427
7427
  return null;
7428
7428
  }
7429
7429
  }
7430
7430
  function extractOpenAICodexAccountId(token) {
7431
7431
  const auth = decodeJwtPayload$1(token)?.["https://api.openai.com/auth"];
7432
- if (!isRecord$3(auth)) return null;
7432
+ if (!isRecord$4(auth)) return null;
7433
7433
  const accountId = auth.chatgpt_account_id;
7434
7434
  return typeof accountId === "string" && accountId.trim() ? accountId.trim() : null;
7435
7435
  }
@@ -7442,21 +7442,39 @@ function executableName() {
7442
7442
  function codexExecutableCandidates() {
7443
7443
  const configured = process.env.FASED_CODEX_BIN?.trim();
7444
7444
  const componentRoot = resolvePluginInstallDir("openai-runtime");
7445
+ const packageRoot = resolveFasedAgentPackageRootSync({
7446
+ moduleUrl: import.meta.url,
7447
+ argv1: process.argv[1],
7448
+ cwd: process.cwd()
7449
+ });
7445
7450
  const candidates = [
7446
7451
  configured,
7447
7452
  path.join(componentRoot, "node_modules", ".bin", executableName()),
7448
7453
  path.join(componentRoot, "node_modules", "@openai", "codex", "bin", executableName()),
7449
- "codex"
7454
+ packageRoot ? path.join(packageRoot, "extensions", "runtime-openai", "node_modules", ".bin", executableName()) : void 0
7450
7455
  ].filter((value) => Boolean(value));
7451
7456
  return [...new Set(candidates)];
7452
7457
  }
7453
7458
  function resolveOpenAICodexExecutable() {
7454
- for (const candidate of codexExecutableCandidates()) {
7455
- if (candidate === "codex") return candidate;
7456
- try {
7457
- if (fs.statSync(candidate).isFile()) return candidate;
7458
- } catch {}
7459
- }
7459
+ const explicitlyConfigured = process.env.FASED_CODEX_BIN?.trim();
7460
+ for (const candidate of codexExecutableCandidates()) try {
7461
+ if (!fs.statSync(candidate).isFile()) continue;
7462
+ if (explicitlyConfigured && candidate === explicitlyConfigured) return candidate;
7463
+ const resolved = fs.realpathSync(candidate);
7464
+ let current = path.dirname(resolved);
7465
+ for (let depth = 0; depth < 6; depth += 1) {
7466
+ try {
7467
+ const parsed = JSON.parse(fs.readFileSync(path.join(current, "package.json"), "utf8"));
7468
+ if (parsed.name === "@openai/codex") {
7469
+ if (parsed.version === OPENAI_CODEX_APP_SERVER_VERSION) return candidate;
7470
+ break;
7471
+ }
7472
+ } catch {}
7473
+ const parent = path.dirname(current);
7474
+ if (parent === current) break;
7475
+ current = parent;
7476
+ }
7477
+ } catch {}
7460
7478
  return null;
7461
7479
  }
7462
7480
  function managedCodexHome() {
@@ -7588,10 +7606,10 @@ async function initializeClient(client, token) {
7588
7606
  });
7589
7607
  }
7590
7608
  function parseAppServerModels$1(value) {
7591
- if (!isRecord$3(value) || !Array.isArray(value.data)) return [];
7609
+ if (!isRecord$4(value) || !Array.isArray(value.data)) return [];
7592
7610
  return value.data.flatMap((entry) => {
7593
- if (!isRecord$3(entry) || typeof entry.id !== "string" || !entry.id.trim()) return [];
7594
- const efforts = Array.isArray(entry.supportedReasoningEfforts) ? entry.supportedReasoningEfforts.flatMap((item) => isRecord$3(item) && typeof item.reasoningEffort === "string" ? [item.reasoningEffort] : []) : [];
7611
+ if (!isRecord$4(entry) || typeof entry.id !== "string" || !entry.id.trim()) return [];
7612
+ const efforts = Array.isArray(entry.supportedReasoningEfforts) ? entry.supportedReasoningEfforts.flatMap((item) => isRecord$4(item) && typeof item.reasoningEffort === "string" ? [item.reasoningEffort] : []) : [];
7595
7613
  const modalities = Array.isArray(entry.inputModalities) ? entry.inputModalities.filter((item) => item === "text" || item === "image") : [];
7596
7614
  return [{
7597
7615
  id: entry.id.trim(),
@@ -7605,7 +7623,7 @@ function parseAppServerModels$1(value) {
7605
7623
  });
7606
7624
  }
7607
7625
  async function listOpenAICodexAppServerModels(params) {
7608
- const executable = params.executable ?? resolveOpenAICodexExecutable();
7626
+ const executable = params.executable ?? (params.resolveExecutable ? await params.resolveExecutable() : resolveOpenAICodexExecutable());
7609
7627
  if (!executable) throw new Error("OpenAI sign-in runtime is not installed. Run `fased components install openai-runtime`.");
7610
7628
  const client = new CodexAppServerClient(executable);
7611
7629
  try {
@@ -7618,7 +7636,7 @@ async function listOpenAICodexAppServerModels(params) {
7618
7636
  function contentText(content) {
7619
7637
  if (typeof content === "string") return content;
7620
7638
  if (!Array.isArray(content)) return "";
7621
- return content.flatMap((part) => isRecord$3(part) && part.type === "text" && typeof part.text === "string" ? [part.text] : []).join("\n");
7639
+ return content.flatMap((part) => isRecord$4(part) && part.type === "text" && typeof part.text === "string" ? [part.text] : []).join("\n");
7622
7640
  }
7623
7641
  function renderConversationContext(context) {
7624
7642
  const messages = context.messages;
@@ -7657,8 +7675,8 @@ function readUsageNumber(value) {
7657
7675
  return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
7658
7676
  }
7659
7677
  function parseThreadTokenUsage(value) {
7660
- if (!isRecord$3(value)) return null;
7661
- const last = isRecord$3(value.last) ? value.last : null;
7678
+ if (!isRecord$4(value)) return null;
7679
+ const last = isRecord$4(value.last) ? value.last : null;
7662
7680
  if (!last) return null;
7663
7681
  const input = readUsageNumber(last.inputTokens);
7664
7682
  const output = readUsageNumber(last.outputTokens);
@@ -7696,7 +7714,7 @@ function createOpenAICodexAppServerStreamFn(params) {
7696
7714
  try {
7697
7715
  const token = options?.apiKey?.trim() || (await params?.resolveToken?.())?.trim();
7698
7716
  if (!token) throw new Error("OpenAI ChatGPT sign-in is required");
7699
- const executable = resolveOpenAICodexExecutable();
7717
+ const executable = params?.resolveExecutable ? await params.resolveExecutable() : resolveOpenAICodexExecutable();
7700
7718
  if (!executable) throw new Error("OpenAI sign-in runtime is not installed. Run `fased components install openai-runtime`.");
7701
7719
  client = new CodexAppServerClient(executable);
7702
7720
  await initializeClient(client, token);
@@ -7713,7 +7731,7 @@ function createOpenAICodexAppServerStreamFn(params) {
7713
7731
  features: { shell_tool: false }
7714
7732
  }
7715
7733
  });
7716
- const thread = isRecord$3(started.thread) ? started.thread : null;
7734
+ const thread = isRecord$4(started.thread) ? started.thread : null;
7717
7735
  const threadId = typeof thread?.id === "string" ? thread.id : "";
7718
7736
  if (!threadId) throw new Error("OpenAI sign-in runtime did not create a thread");
7719
7737
  let text = "";
@@ -7772,11 +7790,11 @@ function createOpenAICodexAppServerStreamFn(params) {
7772
7790
  return;
7773
7791
  }
7774
7792
  if (message.method !== "turn/completed" || settled) return;
7775
- const turn = isRecord$3(message.params?.turn) ? message.params.turn : null;
7793
+ const turn = isRecord$4(message.params?.turn) ? message.params.turn : null;
7776
7794
  settled = true;
7777
7795
  if (turn?.status === "completed") settle();
7778
7796
  else {
7779
- const error = isRecord$3(turn?.error) ? turn.error : null;
7797
+ const error = isRecord$4(turn?.error) ? turn.error : null;
7780
7798
  const status = typeof turn?.status === "string" ? turn.status : "unknown";
7781
7799
  reject(new Error(typeof error?.message === "string" ? error.message : `OpenAI sign-in turn ended with status ${status}`));
7782
7800
  }
@@ -7833,466 +7851,92 @@ function createOpenAICodexAppServerStreamFn(params) {
7833
7851
  }
7834
7852
 
7835
7853
  //#endregion
7836
- //#region src/providers/openai-codex-model-discovery.ts
7837
- const OPENAI_CODEX_MODELS_URL = "https://chatgpt.com/backend-api/codex/models";
7838
- const OPENAI_CODEX_ROUTE = "openai-codex";
7839
- const OPENAI_CODEX_CATALOG_CLIENT_VERSION = "0.144.0";
7840
- const DISCOVERY_TIMEOUT_MS = 8e3;
7841
- function decodeJwtPayload(token) {
7842
- const encoded = token.split(".")[1];
7843
- if (!encoded) return null;
7844
- try {
7845
- return JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
7846
- } catch {
7847
- return null;
7848
- }
7849
- }
7850
- function extractChatGptAccountId(token) {
7851
- const auth = decodeJwtPayload(token)?.["https://api.openai.com/auth"];
7852
- if (!auth || typeof auth !== "object" || Array.isArray(auth)) return null;
7853
- const accountId = auth.chatgpt_account_id;
7854
- return typeof accountId === "string" && accountId.trim() ? accountId.trim() : null;
7855
- }
7856
- function positiveInteger(value) {
7857
- return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : void 0;
7858
- }
7859
- function inputModalities(value) {
7860
- if (!Array.isArray(value)) return ["text"];
7861
- const values = value.filter((entry) => entry === "text" || entry === "image");
7862
- return values.length > 0 ? values : ["text"];
7863
- }
7864
- function modelCapabilities(model) {
7865
- const thinkingLevels = (Array.isArray(model.supported_reasoning_levels) ? model.supported_reasoning_levels : []).flatMap((entry) => {
7866
- if (!entry || typeof entry !== "object" || Array.isArray(entry)) return [];
7867
- const effort = entry.effort;
7868
- const normalized = typeof effort === "string" ? normalizeThinkLevel(effort) : void 0;
7869
- return normalized ? [normalized] : [];
7870
- });
7871
- const defaultThinkingLevel = typeof model.default_reasoning_level === "string" ? normalizeThinkLevel(model.default_reasoning_level) : void 0;
7854
+ //#region src/plugins/installs.ts
7855
+ function buildNpmResolutionInstallFields(resolution) {
7872
7856
  return {
7873
- tools: true,
7874
- json: true,
7875
- streaming: true,
7876
- ...thinkingLevels.length > 0 ? { thinkingLevels } : {},
7877
- ...defaultThinkingLevel ? { defaultThinkingLevel } : {},
7878
- thinkingMode: "openai-reasoning-effort",
7879
- reasoningBudgetSupported: thinkingLevels.length > 0
7857
+ resolvedName: resolution?.name,
7858
+ resolvedVersion: resolution?.version,
7859
+ resolvedSpec: resolution?.resolvedSpec,
7860
+ integrity: resolution?.integrity,
7861
+ shasum: resolution?.shasum,
7862
+ resolvedAt: resolution?.resolvedAt
7880
7863
  };
7881
7864
  }
7882
- function parseModels(value) {
7883
- if (!value || typeof value !== "object" || Array.isArray(value)) return [];
7884
- const models = value.models;
7885
- if (!Array.isArray(models)) return [];
7886
- return models.flatMap((entry) => {
7887
- if (!entry || typeof entry !== "object" || Array.isArray(entry)) return [];
7888
- const model = entry;
7889
- const id = typeof model.slug === "string" ? model.slug.trim() : "";
7890
- if (!id || model.visibility !== "list") return [];
7891
- const capabilities = modelCapabilities(model);
7892
- return [{
7893
- id,
7894
- name: typeof model.display_name === "string" && model.display_name.trim() ? model.display_name.trim().replace(/-(Sol|Terra|Luna|Mini)$/i, " $1") : id,
7895
- input: inputModalities(model.input_modalities),
7896
- reasoning: true,
7897
- tools: capabilities.tools,
7898
- json: capabilities.json,
7899
- thinkingLevels: capabilities.thinkingLevels,
7900
- defaultThinkingLevel: capabilities.defaultThinkingLevel,
7901
- thinkingMode: capabilities.thinkingMode,
7902
- reasoningBudgetSupported: capabilities.reasoningBudgetSupported,
7903
- contextWindow: positiveInteger(model.context_window),
7904
- responsesLite: model.use_responses_lite === true,
7905
- source: "openai-codex-account"
7906
- }];
7907
- });
7908
- }
7909
- function parseAppServerModels(models) {
7910
- return models.map((model) => {
7911
- const thinkingLevels = model.supportedReasoningEfforts.flatMap((effort) => {
7912
- const normalized = normalizeThinkLevel(effort);
7913
- return normalized ? [normalized] : [];
7914
- });
7915
- const defaultThinkingLevel = normalizeThinkLevel(model.defaultReasoningEffort);
7916
- const responsesLite = /^gpt-5\.6-(?:sol|terra|luna)$/i.test(model.id);
7917
- return {
7918
- id: model.id,
7919
- name: model.displayName.replace(/-(Sol|Terra|Luna|Mini)$/i, " $1"),
7920
- input: model.inputModalities,
7921
- reasoning: thinkingLevels.length > 0,
7922
- tools: !responsesLite,
7923
- json: !responsesLite,
7924
- thinkingLevels,
7925
- ...defaultThinkingLevel ? { defaultThinkingLevel } : {},
7926
- thinkingMode: "openai-reasoning-effort",
7927
- reasoningBudgetSupported: false,
7928
- responsesLite,
7929
- source: "openai-codex-app-server"
7930
- };
7931
- });
7932
- }
7933
- async function discoverOpenAICodexModels(params) {
7934
- const profileId = listProfilesForProvider(params.store, OPENAI_CODEX_ROUTE)[0];
7935
- if (!profileId) return [];
7936
- const resolved = await resolveApiKeyForProfile({
7937
- cfg: params.cfg,
7938
- store: params.store,
7939
- profileId,
7940
- agentDir: params.agentDir
7941
- });
7942
- if (!resolved?.apiKey) return [];
7943
- const accountId = extractChatGptAccountId(resolved.apiKey);
7944
- if (!accountId) throw new Error("OpenAI sign-in token does not contain a ChatGPT account ID");
7945
- if (!params.fetchImpl) return parseAppServerModels(await (params.listAppServerModels ?? listOpenAICodexAppServerModels)({ token: resolved.apiKey }));
7946
- const url = new URL(OPENAI_CODEX_MODELS_URL);
7947
- url.searchParams.set("client_version", OPENAI_CODEX_CATALOG_CLIENT_VERSION);
7948
- const response = await (params.fetchImpl ?? fetch)(url, {
7949
- headers: {
7950
- authorization: `Bearer ${resolved.apiKey}`,
7951
- "chatgpt-account-id": accountId,
7952
- originator: "fased",
7953
- accept: "application/json"
7954
- },
7955
- signal: AbortSignal.timeout(DISCOVERY_TIMEOUT_MS)
7956
- });
7957
- if (!response.ok) throw new Error(`OpenAI account model discovery failed (${response.status})`);
7958
- return parseModels(await response.json());
7959
- }
7960
-
7961
- //#endregion
7962
- //#region src/providers/runtime-model-catalog.ts
7963
- const DISCOVERY_TTL_MS = 5 * 6e4;
7964
- let cache$1 = null;
7965
- const SPECIALIZED_DISCOVERY_ROUTES = new Set(["openai-codex", "github-copilot"]);
7966
- function authModeForProfileType(type) {
7967
- return type === "api_key" ? "api-key" : type;
7968
- }
7969
- function methodMatchesAuthMode(method, authMode) {
7970
- return (method.kind === "api-key" || method.kind === "manual" ? "api-key" : method.kind === "token" ? "token" : "oauth") === authMode;
7971
- }
7972
- function methodRouteIds(method) {
7973
- return [
7974
- method.route,
7975
- method.statusRoute,
7976
- method.configProviderId
7977
- ].map((value) => value?.trim().toLowerCase()).filter((value) => Boolean(value));
7978
- }
7979
- function credentialRoutesForProvider(store, route) {
7980
- const normalizedRoute = route.trim().toLowerCase();
7981
- const manifest = getProviderBrandManifestForRoute(normalizedRoute);
7982
- const routes = [];
7983
- const seen = /* @__PURE__ */ new Set();
7984
- for (const profile of Object.values(store.profiles ?? {})) {
7985
- const profileProvider = profile.provider.trim().toLowerCase();
7986
- if (!profileProvider) continue;
7987
- const profileManifest = getProviderBrandManifestForRoute(profileProvider);
7988
- if (profileProvider !== normalizedRoute && profileManifest?.id !== manifest?.id) continue;
7989
- const authMode = authModeForProfileType(profile.type);
7990
- const method = manifest?.methods.find((candidate) => methodMatchesAuthMode(candidate, authMode) && (methodRouteIds(candidate).includes(profileProvider) || methodRouteIds(candidate).includes(normalizedRoute)));
7991
- const id = method?.id ?? `${normalizedRoute}:${authMode}`;
7992
- const key = `${id}:${authMode}`;
7993
- if (seen.has(key)) continue;
7994
- seen.add(key);
7995
- routes.push({
7996
- id,
7997
- label: method?.label ?? manifest?.label ?? normalizedRoute,
7998
- authMode
7999
- });
8000
- }
8001
- return routes;
8002
- }
8003
- function discoveryKey(params) {
8004
- const endpoints = [...params.routes].map((route) => route.trim().toLowerCase()).toSorted().map((route) => {
8005
- const provider = params.cfg.models?.providers?.[route];
8006
- return [
8007
- route,
8008
- provider?.baseUrl ?? "",
8009
- provider?.api ?? ""
8010
- ];
8011
- });
8012
- const credentialIdentity = createHash("sha256").update(JSON.stringify(params.store.profiles ?? {})).digest("hex");
8013
- return JSON.stringify({
8014
- endpoints,
8015
- credentialIdentity
8016
- });
8017
- }
8018
- async function loadSnapshot(params) {
8019
- const key = discoveryKey(params);
8020
- const now = Date.now();
8021
- if (cache$1?.key === key && cache$1.expiresAt > now) return await cache$1.value;
8022
- const value = fetchProviderRefreshSnapshotForRoutes({
8023
- routes: params.routes,
8024
- env: buildProviderRefreshEnvFromCredentials({
8025
- env: process.env,
8026
- authStores: [params.store],
8027
- modelProviders: params.cfg.models?.providers
8028
- })
8029
- });
8030
- cache$1 = {
8031
- key,
8032
- expiresAt: now + DISCOVERY_TTL_MS,
8033
- value
7865
+ function recordPluginInstall(cfg, update) {
7866
+ const { pluginId, ...record } = update;
7867
+ const installs = {
7868
+ ...cfg.plugins?.installs,
7869
+ [pluginId]: {
7870
+ ...cfg.plugins?.installs?.[pluginId],
7871
+ ...record,
7872
+ installedAt: record.installedAt ?? (/* @__PURE__ */ new Date()).toISOString()
7873
+ }
8034
7874
  };
8035
- try {
8036
- return await value;
8037
- } catch (error) {
8038
- if (cache$1?.value === value) cache$1 = null;
8039
- throw error;
8040
- }
8041
- }
8042
- async function discoverInteractiveRoutes(params) {
8043
- const discovered = /* @__PURE__ */ new Map();
8044
- if (params.routes.has("openai-codex")) discovered.set("openai-codex", await discoverOpenAICodexModels({
8045
- cfg: params.cfg,
8046
- store: params.store,
8047
- agentDir: params.agentDir
8048
- }));
8049
- if (params.routes.has("github-copilot")) discovered.set("github-copilot", await discoverGitHubCopilotModels({
8050
- cfg: params.cfg,
8051
- store: params.store,
8052
- agentDir: params.agentDir
8053
- }));
8054
- return discovered;
8055
- }
8056
- function snapshotCapabilities(model) {
8057
7875
  return {
8058
- ...model.tools !== void 0 ? { tools: model.tools } : {},
8059
- ...model.json !== void 0 ? { json: model.json } : {},
8060
- ...model.audio !== void 0 ? { audio: model.audio } : {},
8061
- ...model.video !== void 0 ? { video: model.video } : {},
8062
- ...model.speech !== void 0 ? { speech: model.speech } : {},
8063
- ...model.thinkingLevels?.length ? { thinkingLevels: model.thinkingLevels } : {},
8064
- ...model.defaultThinkingLevel ? { defaultThinkingLevel: model.defaultThinkingLevel } : {},
8065
- ...model.thinkingMode ? { thinkingMode: model.thinkingMode } : {},
8066
- ...model.reasoningBudgetSupported !== void 0 ? { reasoningBudgetSupported: model.reasoningBudgetSupported } : {}
8067
- };
8068
- }
8069
- function snapshotHasCapabilityMetadata(model) {
8070
- return model.input !== void 0 || model.reasoning !== void 0 || model.tools !== void 0 || model.json !== void 0 || model.audio !== void 0 || model.video !== void 0 || model.speech !== void 0 || model.thinkingLevels !== void 0 || model.defaultThinkingLevel !== void 0 || model.thinkingMode !== void 0 || model.reasoningBudgetSupported !== void 0 || model.contextWindow !== void 0 || model.maxTokens !== void 0;
8071
- }
8072
- function snapshotRoutes(snapshot) {
8073
- const routes = /* @__PURE__ */ new Map();
8074
- for (const provider of Object.values(snapshot.providers ?? {})) for (const [route, values] of Object.entries(provider.routes ?? {})) routes.set(route.trim().toLowerCase(), values.flatMap((value) => typeof value === "string" ? [{ id: value }] : value?.id?.trim() ? [value] : []));
8075
- return routes;
8076
- }
8077
- function mergeDiscoveredRoute(params) {
8078
- const baseByKey = new Map(params.catalog.map((model) => [buildModelCatalogMergeKey(model.provider, model.id), model]));
8079
- const providerConfig = params.cfg.models?.providers?.[params.route];
8080
- const credentialRoutes = credentialRoutesForProvider(params.store, params.route);
8081
- return params.discovered.map((model) => {
8082
- const base = baseByKey.get(buildModelCatalogMergeKey(params.route, model.id));
8083
- const capabilities = snapshotCapabilities(model);
8084
- const entry = {
8085
- id: model.id,
8086
- name: model.name ?? base?.name ?? model.id,
8087
- provider: params.route,
8088
- ...model.contextWindow ?? base?.contextWindow ? { contextWindow: model.contextWindow ?? base?.contextWindow } : {},
8089
- ...model.maxTokens ?? base?.maxTokens ? { maxTokens: model.maxTokens ?? base?.maxTokens } : {},
8090
- ...model.reasoning ?? base?.reasoning ? { reasoning: model.reasoning ?? base?.reasoning } : {},
8091
- input: model.input ?? base?.input ?? ["text"],
8092
- ...base?.baseUrl ?? providerConfig?.baseUrl ? { baseUrl: base?.baseUrl ?? providerConfig?.baseUrl } : {},
8093
- ...base?.api ?? providerConfig?.api ? { api: base?.api ?? providerConfig?.api } : {},
8094
- ...model.price ?? base?.cost ? { cost: model.price ?? base?.cost } : {},
8095
- ...Object.keys(capabilities).length > 0 ? { capabilities } : {},
8096
- ...model.responsesLite !== void 0 ? { compat: {
8097
- ...base?.compat,
8098
- responsesLite: model.responsesLite
8099
- } } : base?.compat ? { compat: base.compat } : {},
8100
- catalogSource: "provider-api"
8101
- };
8102
- return {
8103
- ...entry,
8104
- metadata: {
8105
- ...base?.metadata,
8106
- ...deriveModelMetadata({
8107
- model: entry,
8108
- cfg: params.cfg,
8109
- providerConfig,
8110
- ...credentialRoutes.length > 0 ? { credentialRoutes } : {},
8111
- ...snapshotHasCapabilityMetadata(model) ? {
8112
- capabilitySource: "provider-api",
8113
- capabilityRetrievedAt: params.retrievedAt
8114
- } : {}
8115
- }),
8116
- retrievedAt: params.retrievedAt
7876
+ ...cfg,
7877
+ plugins: {
7878
+ ...cfg.plugins,
7879
+ installs: {
7880
+ ...installs,
7881
+ [pluginId]: installs[pluginId]
8117
7882
  }
8118
- };
8119
- });
8120
- }
8121
- async function applyRuntimeProviderModelDiscovery(params) {
8122
- const requestedRoutes = new Set([...params.routes].map((route) => route.trim().toLowerCase()).filter(Boolean));
8123
- if (requestedRoutes.size === 0) return [];
8124
- const specializedRoutes = new Set([...requestedRoutes].filter((route) => SPECIALIZED_DISCOVERY_ROUTES.has(route)));
8125
- const providerApiRoutes = [...requestedRoutes].filter((route) => !specializedRoutes.has(route));
8126
- const interactiveRoutes = await discoverInteractiveRoutes({
8127
- routes: requestedRoutes,
8128
- cfg: params.cfg,
8129
- store: params.store,
8130
- agentDir: params.agentDir
8131
- }).catch(() => /* @__PURE__ */ new Map());
8132
- let discoveredRoutes = new Map(interactiveRoutes);
8133
- if (providerApiRoutes.length > 0) try {
8134
- const snapshot = await loadSnapshot({
8135
- ...params,
8136
- routes: providerApiRoutes
8137
- });
8138
- discoveredRoutes = new Map([...discoveredRoutes, ...snapshotRoutes(snapshot)]);
8139
- } catch {}
8140
- const retrievedAt = (/* @__PURE__ */ new Date()).toISOString();
8141
- const authoritativeRoutes = new Set([...discoveredRoutes.keys()].filter((route) => requestedRoutes.has(route)));
8142
- const replacedRoutes = new Set(providerApiRoutes);
8143
- for (const route of specializedRoutes) replacedRoutes.add(route);
8144
- const retained = params.catalog.filter((model) => !replacedRoutes.has(model.provider.trim().toLowerCase()));
8145
- const discovered = [...authoritativeRoutes].flatMap((route) => mergeDiscoveredRoute({
8146
- route,
8147
- discovered: discoveredRoutes.get(route) ?? [],
8148
- catalog: params.catalog,
8149
- cfg: params.cfg,
8150
- store: params.store,
8151
- retrievedAt
8152
- }));
8153
- return [...retained, ...discovered].toSorted((left, right) => left.provider.localeCompare(right.provider) || (left.metadata?.recommendationRank ?? Number.MAX_SAFE_INTEGER) - (right.metadata?.recommendationRank ?? Number.MAX_SAFE_INTEGER) || left.name.localeCompare(right.name));
8154
- }
8155
- function filterCatalogToAuthoritativeAvailability(catalog, store) {
8156
- const specializedProviders = store ? new Set(Object.values(store.profiles ?? {}).map((profile) => profile.provider.trim().toLowerCase()).filter((provider) => SPECIALIZED_DISCOVERY_ROUTES.has(provider))) : /* @__PURE__ */ new Set();
8157
- const byProvider = /* @__PURE__ */ new Map();
8158
- for (const model of catalog) {
8159
- const provider = model.provider.trim().toLowerCase();
8160
- byProvider.set(provider, [...byProvider.get(provider) ?? [], model]);
8161
- }
8162
- return [...byProvider.entries()].flatMap(([provider, models]) => {
8163
- if (models.some((model) => model.catalogSource === "provider-api")) return models.filter((model) => model.catalogSource === "provider-api");
8164
- if (specializedProviders.has(provider)) return models.filter((model) => model.catalogSource === "runtime" || model.catalogSource === "provider-api");
8165
- return models;
8166
- });
7883
+ }
7884
+ };
8167
7885
  }
8168
7886
 
8169
7887
  //#endregion
8170
- //#region src/agents/model-catalog-access.ts
8171
- function providerHasConfiguredCredential(cfg, provider) {
8172
- return Boolean(resolveEnvApiKey(provider)?.apiKey || getCustomProviderApiKey(cfg, provider));
8173
- }
8174
- function normalizeProviderSet(providers) {
8175
- return new Set([...providers ?? []].map((provider) => normalizeProviderId$1(provider)).filter(Boolean));
8176
- }
8177
- function buildUsableModelProviderSet(params) {
8178
- const usable = normalizeProviderSet(params.storedProviders ?? (params.store ? listProvidersWithStoredCredentials(params.store) : []));
8179
- for (const entry of params.catalog) {
8180
- const provider = normalizeProviderId$1(entry.provider);
8181
- if (!provider || usable.has(provider)) continue;
8182
- if (providerHasConfiguredCredential(params.cfg, provider)) usable.add(provider);
8183
- }
8184
- return usable;
8185
- }
8186
- function filterModelCatalogByProviders(catalog, providers) {
8187
- const normalizedProviders = normalizeProviderSet(providers);
8188
- if (normalizedProviders.size === 0) return [];
8189
- return catalog.filter((entry) => normalizedProviders.has(normalizeProviderId$1(entry.provider)));
8190
- }
8191
- function buildCredentialScopedAllowedModelSet(params) {
8192
- const usableProviders = buildUsableModelProviderSet({
8193
- cfg: params.cfg,
8194
- catalog: params.catalog,
8195
- storedProviders: params.storedProviders,
8196
- store: params.store
8197
- });
8198
- const usableCatalog = filterModelCatalogByProviders(params.catalog, usableProviders);
8199
- const allowed = buildAllowedModelSet({
8200
- cfg: params.cfg,
8201
- catalog: usableCatalog,
8202
- defaultProvider: params.defaultProvider,
8203
- defaultModel: params.defaultModel,
8204
- additionalAllowedProviders: usableProviders
8205
- });
8206
- const allowedCatalog = filterModelCatalogByProviders(allowed.allowedCatalog, usableProviders);
7888
+ //#region src/plugins/toggle-config.ts
7889
+ function setPluginEnabledInConfig(config, pluginId, enabled) {
7890
+ const builtInChannelId = normalizeChatChannelId(pluginId);
7891
+ const resolvedId = builtInChannelId ?? pluginId;
7892
+ const next = {
7893
+ ...config,
7894
+ plugins: {
7895
+ ...config.plugins,
7896
+ entries: {
7897
+ ...config.plugins?.entries,
7898
+ [resolvedId]: {
7899
+ ...config.plugins?.entries?.[resolvedId],
7900
+ enabled
7901
+ }
7902
+ }
7903
+ }
7904
+ };
7905
+ if (!builtInChannelId) return next;
7906
+ const existing = config.channels?.[builtInChannelId];
7907
+ const existingRecord = existing && typeof existing === "object" && !Array.isArray(existing) ? existing : {};
8207
7908
  return {
8208
- usableProviders,
8209
- usableCatalog,
8210
- allowedCatalog,
8211
- allowedKeys: new Set(allowedCatalog.map((entry) => modelKey(entry.provider, entry.id))),
8212
- allowAny: allowed.allowAny
7909
+ ...next,
7910
+ channels: {
7911
+ ...config.channels,
7912
+ [builtInChannelId]: {
7913
+ ...existingRecord,
7914
+ enabled
7915
+ }
7916
+ }
8213
7917
  };
8214
7918
  }
8215
7919
 
8216
7920
  //#endregion
8217
- //#region src/agents/authenticated-model-catalog.ts
8218
- async function resolveAuthenticatedModelCatalog(params) {
8219
- const initialScope = buildCredentialScopedAllowedModelSet({
8220
- cfg: params.cfg,
8221
- catalog: params.catalog,
8222
- defaultProvider: params.defaultProvider,
8223
- store: params.store
8224
- });
8225
- const discoveredCatalog = filterCatalogToAuthoritativeAvailability(await applyRuntimeProviderModelDiscovery({
8226
- cfg: params.cfg,
8227
- store: params.store,
8228
- routes: initialScope.usableProviders,
8229
- catalog: initialScope.usableCatalog,
8230
- agentDir: params.agentDir
8231
- }), params.store);
8232
- return buildCredentialScopedAllowedModelSet({
8233
- cfg: params.cfg,
8234
- catalog: discoveredCatalog,
8235
- defaultProvider: params.defaultProvider,
8236
- storedProviders: initialScope.usableProviders
8237
- });
8238
- }
8239
-
8240
- //#endregion
8241
- //#region src/agents/model-alias-lines.ts
8242
- function buildModelAliasLines(cfg) {
8243
- const models = cfg?.agents?.defaults?.models ?? {};
8244
- const entries = [];
8245
- for (const [keyRaw, entryRaw] of Object.entries(models)) {
8246
- const model = String(keyRaw ?? "").trim();
8247
- if (!model) continue;
8248
- const alias = String(entryRaw?.alias ?? "").trim();
8249
- if (!alias) continue;
8250
- entries.push({
8251
- alias,
8252
- model
8253
- });
8254
- }
8255
- return entries.toSorted((a, b) => a.alias.localeCompare(b.alias)).map((entry) => `- ${entry.alias}: ${entry.model}`);
8256
- }
8257
-
8258
- //#endregion
8259
- //#region src/plugins/provider-discovery.ts
8260
- function isUnsafeProviderKey(value) {
8261
- return value === "__proto__" || value === "prototype" || value === "constructor";
8262
- }
8263
- function normalizeProviderResultKey(value) {
8264
- if (!value) return;
8265
- const normalized = normalizeProviderId$2(value);
8266
- if (!normalized || isUnsafeProviderKey(normalized)) return;
8267
- return normalized;
8268
- }
8269
- function normalizeSingleProviderResultKey(provider) {
8270
- return [provider.id, ...provider.aliases ?? []].map((candidate) => normalizeProviderResultKey(candidate)).find((candidate) => Boolean(candidate));
8271
- }
8272
- function normalizePluginDiscoveryResult(params) {
8273
- const result = params.result;
8274
- if (!result) return {};
8275
- if ("provider" in result) {
8276
- const key = normalizeSingleProviderResultKey(params.provider);
8277
- return key ? { [key]: result.provider } : {};
8278
- }
8279
- const normalized = {};
8280
- for (const [key, value] of Object.entries(result.providers)) {
8281
- const normalizedKey = normalizeProviderResultKey(key);
8282
- if (!normalizedKey || !value) continue;
8283
- normalized[normalizedKey] = value;
8284
- }
8285
- return normalized;
8286
- }
8287
- function runProviderStaticCatalog(params) {
8288
- return params.provider.staticCatalog?.run({
8289
- config: params.config,
8290
- agentDir: params.agentDir,
8291
- workspaceDir: params.workspaceDir,
8292
- env: params.env,
8293
- resolveProviderApiKey: params.resolveProviderApiKey,
8294
- resolveProviderAuth: params.resolveProviderAuth
8295
- });
7921
+ //#region src/plugins/enable.ts
7922
+ function enablePluginInConfig(cfg, pluginId) {
7923
+ const resolvedId = normalizeChatChannelId(pluginId) ?? pluginId;
7924
+ if (cfg.plugins?.enabled === false) return {
7925
+ config: cfg,
7926
+ enabled: false,
7927
+ reason: "plugins disabled"
7928
+ };
7929
+ if (cfg.plugins?.deny?.includes(pluginId) || cfg.plugins?.deny?.includes(resolvedId)) return {
7930
+ config: cfg,
7931
+ enabled: false,
7932
+ reason: "blocked by denylist"
7933
+ };
7934
+ let next = setPluginEnabledInConfig(cfg, resolvedId, true);
7935
+ next = ensurePluginAllowlisted(next, resolvedId);
7936
+ return {
7937
+ config: next,
7938
+ enabled: true
7939
+ };
8296
7940
  }
8297
7941
 
8298
7942
  //#endregion
@@ -8494,7 +8138,7 @@ function resolveMemoryBackendConfig(params) {
8494
8138
 
8495
8139
  //#endregion
8496
8140
  //#region src/memory/search-manager.ts
8497
- const log$20 = createSubsystemLogger("memory");
8141
+ const log$21 = createSubsystemLogger("memory");
8498
8142
  const QMD_MANAGER_CACHE = /* @__PURE__ */ new Map();
8499
8143
  async function getMemorySearchManager(params) {
8500
8144
  const resolved = resolveMemoryBackendConfig(params);
@@ -8506,7 +8150,7 @@ async function getMemorySearchManager(params) {
8506
8150
  if (cached) return { manager: cached };
8507
8151
  }
8508
8152
  try {
8509
- const { QmdMemoryManager } = await import("./qmd-manager-CFFeM4Fl.js");
8153
+ const { QmdMemoryManager } = await import("./qmd-manager-DSyx77KY.js");
8510
8154
  const primary = await QmdMemoryManager.create({
8511
8155
  cfg: params.cfg,
8512
8156
  agentId: params.agentId,
@@ -8518,7 +8162,7 @@ async function getMemorySearchManager(params) {
8518
8162
  const wrapper = new FallbackMemoryManager({
8519
8163
  primary,
8520
8164
  fallbackFactory: async () => {
8521
- const { MemoryIndexManager } = await import("./manager-oHAvZCT3.js").then((n) => n.t);
8165
+ const { MemoryIndexManager } = await import("./manager-CbiFFLKS.js").then((n) => n.t);
8522
8166
  return await MemoryIndexManager.get(params);
8523
8167
  }
8524
8168
  }, () => QMD_MANAGER_CACHE.delete(cacheKey));
@@ -8527,23 +8171,23 @@ async function getMemorySearchManager(params) {
8527
8171
  }
8528
8172
  } catch (err) {
8529
8173
  const message = err instanceof Error ? err.message : String(err);
8530
- log$20.warn(`qmd memory unavailable; falling back to builtin: ${message}`);
8174
+ log$21.warn(`qmd memory unavailable; falling back to builtin: ${message}`);
8531
8175
  }
8532
8176
  }
8533
8177
  try {
8534
- const { MemoryIndexManager } = await import("./manager-oHAvZCT3.js").then((n) => n.t);
8178
+ const { MemoryIndexManager } = await import("./manager-CbiFFLKS.js").then((n) => n.t);
8535
8179
  return { manager: await MemoryIndexManager.get(params) };
8536
8180
  } catch (err) {
8537
8181
  const message = err instanceof Error ? err.message : String(err);
8538
8182
  if (isNodeSqliteUnavailable(message)) {
8539
- const { FilesystemMemorySearchManager } = await import("./filesystem-manager-BGGGrkiN.js");
8183
+ const { FilesystemMemorySearchManager } = await import("./filesystem-manager-ZoHU8oA7.js");
8540
8184
  const manager = await FilesystemMemorySearchManager.create({
8541
8185
  cfg: params.cfg,
8542
8186
  agentId: params.agentId,
8543
8187
  unavailableReason: message
8544
8188
  });
8545
8189
  if (manager) {
8546
- log$20.warn(`builtin sqlite memory unavailable; using filesystem fallback: ${message}`);
8190
+ log$21.warn(`builtin sqlite memory unavailable; using filesystem fallback: ${message}`);
8547
8191
  return { manager };
8548
8192
  }
8549
8193
  }
@@ -8570,7 +8214,7 @@ var FallbackMemoryManager = class {
8570
8214
  } catch (err) {
8571
8215
  this.primaryFailed = true;
8572
8216
  this.lastError = err instanceof Error ? err.message : String(err);
8573
- log$20.warn(`qmd memory failed; switching to builtin index: ${this.lastError}`);
8217
+ log$21.warn(`qmd memory failed; switching to builtin index: ${this.lastError}`);
8574
8218
  await this.deps.primary.close?.().catch(() => {});
8575
8219
  this.evictCacheEntry();
8576
8220
  }
@@ -8650,12 +8294,12 @@ var FallbackMemoryManager = class {
8650
8294
  try {
8651
8295
  fallback = await this.deps.fallbackFactory();
8652
8296
  if (!fallback) {
8653
- log$20.warn("memory fallback requested but builtin index is unavailable");
8297
+ log$21.warn("memory fallback requested but builtin index is unavailable");
8654
8298
  return null;
8655
8299
  }
8656
8300
  } catch (err) {
8657
8301
  const message = err instanceof Error ? err.message : String(err);
8658
- log$20.warn(`memory fallback unavailable: ${message}`);
8302
+ log$21.warn(`memory fallback unavailable: ${message}`);
8659
8303
  return null;
8660
8304
  }
8661
8305
  this.fallback = fallback;
@@ -10054,6 +9698,18 @@ const ModelChoiceSchema = Type.Object({
10054
9698
  Type.Literal("provider-index"),
10055
9699
  Type.Literal("manifest")
10056
9700
  ])),
9701
+ available: Type.Optional(Type.Boolean()),
9702
+ runnable: Type.Optional(Type.Boolean()),
9703
+ recommended: Type.Optional(Type.Boolean()),
9704
+ assignedRoles: Type.Optional(Type.Array(Type.Union([
9705
+ Type.Literal("primary"),
9706
+ Type.Literal("fallback"),
9707
+ Type.Literal("cheapCheck"),
9708
+ Type.Literal("strong"),
9709
+ Type.Literal("escalation"),
9710
+ Type.Literal("coding"),
9711
+ Type.Literal("summarizer")
9712
+ ]))),
10057
9713
  metadata: Type.Optional(Type.Object({
10058
9714
  ref: NonEmptyString,
10059
9715
  provider: NonEmptyString,
@@ -10285,7 +9941,37 @@ const ModelsListParamsSchema = Type.Object({
10285
9941
  sessionKey: Type.Optional(NonEmptyString),
10286
9942
  includeMetadata: Type.Optional(Type.Boolean())
10287
9943
  }, { additionalProperties: false });
10288
- const ModelsListResultSchema = Type.Object({ models: Type.Array(ModelChoiceSchema) }, { additionalProperties: false });
9944
+ const ModelsListResultSchema = Type.Object({
9945
+ models: Type.Array(ModelChoiceSchema),
9946
+ generatedAt: Type.Optional(NonEmptyString),
9947
+ agentId: Type.Optional(NonEmptyString),
9948
+ providers: Type.Optional(Type.Array(Type.Object({
9949
+ id: NonEmptyString,
9950
+ label: NonEmptyString,
9951
+ routes: Type.Array(NonEmptyString),
9952
+ credentialRoutes: Type.Array(Type.Object({
9953
+ id: NonEmptyString,
9954
+ label: NonEmptyString,
9955
+ authMode: NonEmptyString
9956
+ }, { additionalProperties: false })),
9957
+ available: Type.Integer({ minimum: 0 }),
9958
+ recommended: Type.Integer({ minimum: 0 }),
9959
+ assigned: Type.Integer({ minimum: 0 })
9960
+ }, { additionalProperties: false }))),
9961
+ assignments: Type.Optional(Type.Array(Type.Object({
9962
+ role: Type.Union([
9963
+ Type.Literal("primary"),
9964
+ Type.Literal("fallback"),
9965
+ Type.Literal("cheapCheck"),
9966
+ Type.Literal("strong"),
9967
+ Type.Literal("escalation"),
9968
+ Type.Literal("coding"),
9969
+ Type.Literal("summarizer")
9970
+ ]),
9971
+ ref: NonEmptyString,
9972
+ available: Type.Boolean()
9973
+ }, { additionalProperties: false })))
9974
+ }, { additionalProperties: false });
10289
9975
  const ModelsCatalogStatusParamsSchema = Type.Object({}, { additionalProperties: false });
10290
9976
  const ModelsCatalogStatusProviderSchema = Type.Object({
10291
9977
  provider: NonEmptyString,
@@ -25598,7 +25284,7 @@ function formatOutboundPayloadLog(payload) {
25598
25284
  //#endregion
25599
25285
  //#region src/infra/outbound/deliver.ts
25600
25286
  var deliver_exports = /* @__PURE__ */ __exportAll({ deliverOutboundPayloads: () => deliverOutboundPayloads });
25601
- const log$19 = createSubsystemLogger("outbound/deliver");
25287
+ const log$20 = createSubsystemLogger("outbound/deliver");
25602
25288
  async function createChannelHandler(params) {
25603
25289
  const outbound = await loadChannelOutboundAdapter(params.channel);
25604
25290
  const handler = createPluginHandler({
@@ -25814,7 +25500,7 @@ async function deliverOutboundPayloadsCore(params) {
25814
25500
  });
25815
25501
  const hookRunner = getGlobalHookRunner();
25816
25502
  const sessionKeyForInternalHooks = params.mirror?.sessionKey ?? params.session?.key;
25817
- if (hookRunner?.hasHooks("message_sent") && params.session?.agentId && !sessionKeyForInternalHooks) log$19.warn("deliverOutboundPayloads: session.agentId present without session key; internal message:sent hook will be skipped", {
25503
+ if (hookRunner?.hasHooks("message_sent") && params.session?.agentId && !sessionKeyForInternalHooks) log$20.warn("deliverOutboundPayloads: session.agentId present without session key; internal message:sent hook will be skipped", {
25818
25504
  channel,
25819
25505
  to,
25820
25506
  agentId: params.session.agentId
@@ -26341,27 +26027,27 @@ function createOutboundSendDepsFromCliSource(deps) {
26341
26027
  function createDefaultDeps() {
26342
26028
  return {
26343
26029
  sendMessageWhatsApp: async (...args) => {
26344
- const { sendMessageWhatsApp } = await import("./web-D0yENDve.js");
26030
+ const { sendMessageWhatsApp } = await import("./web-BFolfZ3i.js");
26345
26031
  return await sendMessageWhatsApp(...args);
26346
26032
  },
26347
26033
  sendMessageTelegram: async (...args) => {
26348
- const { sendMessageTelegram } = await import("./send-Dqes9tdU.js").then((n) => n.c);
26034
+ const { sendMessageTelegram } = await import("./send-hSu1HWms.js").then((n) => n.c);
26349
26035
  return await sendMessageTelegram(...args);
26350
26036
  },
26351
26037
  sendMessageDiscord: async (...args) => {
26352
- const { sendMessageDiscord } = await import("./send-BQUtCJFW.js").then((n) => n.t);
26038
+ const { sendMessageDiscord } = await import("./send-BCJ4hi3t.js").then((n) => n.t);
26353
26039
  return await sendMessageDiscord(...args);
26354
26040
  },
26355
26041
  sendMessageSlack: async (...args) => {
26356
- const { sendMessageSlack } = await import("./send-2VcOMTN5.js").then((n) => n.n);
26042
+ const { sendMessageSlack } = await import("./send-CPK_HlYW.js").then((n) => n.n);
26357
26043
  return await sendMessageSlack(...args);
26358
26044
  },
26359
26045
  sendMessageSignal: async (...args) => {
26360
- const { sendMessageSignal } = await import("./send-J4JWKP62.js").then((n) => n.i);
26046
+ const { sendMessageSignal } = await import("./send-D3DQOg2a.js").then((n) => n.i);
26361
26047
  return await sendMessageSignal(...args);
26362
26048
  },
26363
26049
  sendMessageIMessage: async (...args) => {
26364
- const { sendMessageIMessage } = await import("./send-DPJIIYAs.js").then((n) => n.n);
26050
+ const { sendMessageIMessage } = await import("./send-BHokB4TR.js").then((n) => n.n);
26365
26051
  return await sendMessageIMessage(...args);
26366
26052
  }
26367
26053
  };
@@ -28113,305 +27799,867 @@ async function resolveSessionAuthProfileOverride(params) {
28113
27799
  }
28114
27800
 
28115
27801
  //#endregion
28116
- //#region src/agents/failover-error.ts
28117
- const TIMEOUT_HINT_RE = /timeout|timed out|deadline exceeded|context deadline exceeded|stop reason:\s*abort|reason:\s*abort|unhandled stop reason:\s*abort/i;
28118
- const ABORT_TIMEOUT_RE = /request was aborted|request aborted/i;
28119
- var FailoverError = class extends Error {
28120
- constructor(message, params) {
28121
- super(message, { cause: params.cause });
28122
- this.name = "FailoverError";
28123
- this.reason = params.reason;
28124
- this.provider = params.provider;
28125
- this.model = params.model;
28126
- this.profileId = params.profileId;
28127
- this.status = params.status;
28128
- this.code = params.code;
28129
- }
28130
- };
28131
- function isFailoverError(err) {
28132
- return err instanceof FailoverError;
27802
+ //#region src/agents/model-catalog-access.ts
27803
+ function providerHasConfiguredCredential(cfg, provider) {
27804
+ return Boolean(resolveEnvApiKey(provider)?.apiKey || getCustomProviderApiKey(cfg, provider));
28133
27805
  }
28134
- function resolveFailoverStatus(reason) {
28135
- switch (reason) {
28136
- case "billing": return 402;
28137
- case "rate_limit": return 429;
28138
- case "auth": return 401;
28139
- case "auth_permanent": return 403;
28140
- case "timeout": return 408;
28141
- case "format": return 400;
28142
- case "model_not_found": return 404;
28143
- default: return;
28144
- }
27806
+ function normalizeProviderSet(providers) {
27807
+ return new Set([...providers ?? []].map((provider) => normalizeProviderId$1(provider)).filter(Boolean));
28145
27808
  }
28146
- function getStatusCode(err) {
28147
- if (!err || typeof err !== "object") return;
28148
- const candidate = err.status ?? err.statusCode;
28149
- if (typeof candidate === "number") return candidate;
28150
- if (typeof candidate === "string" && /^\d+$/.test(candidate)) return Number(candidate);
27809
+ function buildUsableModelProviderSet(params) {
27810
+ const usable = normalizeProviderSet(params.storedProviders ?? (params.store ? listProvidersWithStoredCredentials(params.store) : []));
27811
+ for (const entry of params.catalog) {
27812
+ const provider = normalizeProviderId$1(entry.provider);
27813
+ if (!provider || usable.has(provider)) continue;
27814
+ if (providerHasConfiguredCredential(params.cfg, provider)) usable.add(provider);
27815
+ }
27816
+ return usable;
28151
27817
  }
28152
- function getErrorName(err) {
28153
- if (!err || typeof err !== "object") return "";
28154
- return "name" in err ? String(err.name) : "";
27818
+ function filterModelCatalogByProviders(catalog, providers) {
27819
+ const normalizedProviders = normalizeProviderSet(providers);
27820
+ if (normalizedProviders.size === 0) return [];
27821
+ return catalog.filter((entry) => normalizedProviders.has(normalizeProviderId$1(entry.provider)));
28155
27822
  }
28156
- function getErrorCode(err) {
28157
- if (!err || typeof err !== "object") return;
28158
- const candidate = err.code;
28159
- if (typeof candidate !== "string") return;
28160
- const trimmed = candidate.trim();
28161
- return trimmed ? trimmed : void 0;
27823
+ function buildCredentialScopedAllowedModelSet(params) {
27824
+ const usableProviders = buildUsableModelProviderSet({
27825
+ cfg: params.cfg,
27826
+ catalog: params.catalog,
27827
+ storedProviders: params.storedProviders,
27828
+ store: params.store
27829
+ });
27830
+ const usableCatalog = filterModelCatalogByProviders(params.catalog, usableProviders);
27831
+ const allowed = buildAllowedModelSet({
27832
+ cfg: params.cfg,
27833
+ catalog: usableCatalog,
27834
+ defaultProvider: params.defaultProvider,
27835
+ defaultModel: params.defaultModel,
27836
+ additionalAllowedProviders: usableProviders
27837
+ });
27838
+ const allowedCatalog = filterModelCatalogByProviders(allowed.allowedCatalog, usableProviders);
27839
+ return {
27840
+ usableProviders,
27841
+ usableCatalog,
27842
+ allowedCatalog,
27843
+ allowedKeys: new Set(allowedCatalog.map((entry) => modelKey(entry.provider, entry.id))),
27844
+ allowAny: allowed.allowAny
27845
+ };
28162
27846
  }
28163
- function getErrorMessage(err) {
28164
- if (err instanceof Error) return err.message;
28165
- if (typeof err === "string") return err;
28166
- if (typeof err === "number" || typeof err === "boolean" || typeof err === "bigint") return String(err);
28167
- if (typeof err === "symbol") return err.description ?? "";
28168
- if (err && typeof err === "object") {
28169
- const message = err.message;
28170
- if (typeof message === "string") return message;
28171
- }
28172
- return "";
27847
+
27848
+ //#endregion
27849
+ //#region src/plugins/provider-discovery.ts
27850
+ function isUnsafeProviderKey(value) {
27851
+ return value === "__proto__" || value === "prototype" || value === "constructor";
28173
27852
  }
28174
- function hasTimeoutHint(err) {
28175
- if (!err) return false;
28176
- if (getErrorName(err) === "TimeoutError") return true;
28177
- const message = getErrorMessage(err);
28178
- return Boolean(message && TIMEOUT_HINT_RE.test(message));
27853
+ function normalizeProviderResultKey(value) {
27854
+ if (!value) return;
27855
+ const normalized = normalizeProviderId$2(value);
27856
+ if (!normalized || isUnsafeProviderKey(normalized)) return;
27857
+ return normalized;
28179
27858
  }
28180
- function isTimeoutError(err) {
28181
- if (hasTimeoutHint(err)) return true;
28182
- if (!err || typeof err !== "object") return false;
28183
- if (getErrorName(err) !== "AbortError") return false;
28184
- const message = getErrorMessage(err);
28185
- if (message && ABORT_TIMEOUT_RE.test(message)) return true;
28186
- const cause = "cause" in err ? err.cause : void 0;
28187
- const reason = "reason" in err ? err.reason : void 0;
28188
- return hasTimeoutHint(cause) || hasTimeoutHint(reason);
27859
+ function normalizeSingleProviderResultKey(provider) {
27860
+ return [provider.id, ...provider.aliases ?? []].map((candidate) => normalizeProviderResultKey(candidate)).find((candidate) => Boolean(candidate));
28189
27861
  }
28190
- function resolveFailoverReasonFromError(err) {
28191
- if (isFailoverError(err)) return err.reason;
28192
- const status = getStatusCode(err);
28193
- if (status === 402) return "billing";
28194
- if (status === 429) return "rate_limit";
28195
- if (status === 401 || status === 403) {
28196
- const msg = getErrorMessage(err);
28197
- if (msg && isAuthPermanentErrorMessage(msg)) return "auth_permanent";
28198
- return "auth";
27862
+ function normalizePluginDiscoveryResult(params) {
27863
+ const result = params.result;
27864
+ if (!result) return {};
27865
+ if ("provider" in result) {
27866
+ const key = normalizeSingleProviderResultKey(params.provider);
27867
+ return key ? { [key]: result.provider } : {};
28199
27868
  }
28200
- if (status === 408) return "timeout";
28201
- if (status === 502 || status === 503 || status === 504) return "timeout";
28202
- if (status === 400) return "format";
28203
- const code = (getErrorCode(err) ?? "").toUpperCase();
28204
- if ([
28205
- "ETIMEDOUT",
28206
- "ESOCKETTIMEDOUT",
28207
- "ECONNRESET",
28208
- "ECONNABORTED"
28209
- ].includes(code)) return "timeout";
28210
- if (isTimeoutError(err)) return "timeout";
28211
- const message = getErrorMessage(err);
28212
- if (!message) return null;
28213
- return classifyFailoverReason(message);
27869
+ const normalized = {};
27870
+ for (const [key, value] of Object.entries(result.providers)) {
27871
+ const normalizedKey = normalizeProviderResultKey(key);
27872
+ if (!normalizedKey || !value) continue;
27873
+ normalized[normalizedKey] = value;
27874
+ }
27875
+ return normalized;
28214
27876
  }
28215
- function describeFailoverError(err) {
28216
- if (isFailoverError(err)) return {
28217
- message: err.message,
28218
- reason: err.reason,
28219
- status: err.status,
28220
- code: err.code
28221
- };
27877
+ function runProviderStaticCatalog(params) {
27878
+ return params.provider.staticCatalog?.run({
27879
+ config: params.config,
27880
+ agentDir: params.agentDir,
27881
+ workspaceDir: params.workspaceDir,
27882
+ env: params.env,
27883
+ resolveProviderApiKey: params.resolveProviderApiKey,
27884
+ resolveProviderAuth: params.resolveProviderAuth
27885
+ });
27886
+ }
27887
+
27888
+ //#endregion
27889
+ //#region src/plugins/logger.ts
27890
+ function createPluginLoaderLogger(logger) {
28222
27891
  return {
28223
- message: getErrorMessage(err) || String(err),
28224
- reason: resolveFailoverReasonFromError(err) ?? void 0,
28225
- status: getStatusCode(err),
28226
- code: getErrorCode(err)
27892
+ info: (msg) => logger.info(msg),
27893
+ warn: (msg) => logger.warn(msg),
27894
+ error: (msg) => logger.error(msg),
27895
+ debug: (msg) => logger.debug?.(msg)
28227
27896
  };
28228
27897
  }
28229
- function coerceToFailoverError(err, context) {
28230
- if (isFailoverError(err)) return err;
28231
- const reason = resolveFailoverReasonFromError(err);
28232
- if (!reason) return null;
28233
- const message = getErrorMessage(err) || String(err);
28234
- const status = getStatusCode(err) ?? resolveFailoverStatus(reason);
28235
- const code = getErrorCode(err);
28236
- return new FailoverError(message, {
28237
- reason,
28238
- provider: context?.provider,
28239
- model: context?.model,
28240
- profileId: context?.profileId,
28241
- status,
28242
- code,
28243
- cause: err instanceof Error ? err : void 0
28244
- });
28245
- }
28246
27898
 
28247
27899
  //#endregion
28248
- //#region src/agents/model-fallback.ts
28249
- /**
28250
- * Fallback abort check. Only treats explicit AbortError names as user aborts.
28251
- * Message-based checks (e.g., "aborted") can mask timeouts and skip fallback.
28252
- */
28253
- function isFallbackAbortError(err) {
28254
- if (!err || typeof err !== "object") return false;
28255
- if (isFailoverError(err)) return false;
28256
- return ("name" in err ? String(err.name) : "") === "AbortError";
27900
+ //#region src/plugins/providers.ts
27901
+ const log$19 = createSubsystemLogger("plugins");
27902
+ function resolvePluginProviders(params) {
27903
+ return loadFasedAgentPlugins({
27904
+ config: params.config,
27905
+ workspaceDir: params.workspaceDir,
27906
+ logger: createPluginLoaderLogger(log$19)
27907
+ }).providers.map((entry) => entry.provider);
28257
27908
  }
28258
- function shouldRethrowAbort(err) {
28259
- return isFallbackAbortError(err) && !isTimeoutError(err);
27909
+
27910
+ //#endregion
27911
+ //#region src/plugins/provider-runtime.runtime.ts
27912
+ const log$18 = createSubsystemLogger("provider-runtime");
27913
+ function mergeProviders(target, providers) {
27914
+ for (const [providerId, providerConfig] of Object.entries(providers)) target[providerId] = providerConfig;
28260
27915
  }
28261
- function createModelCandidateCollector(allowlist) {
28262
- const seen = /* @__PURE__ */ new Set();
28263
- const candidates = [];
28264
- const addCandidate = (candidate, enforceAllowlist) => {
28265
- if (!candidate.provider || !candidate.model) return;
28266
- const key = modelKey(candidate.provider, candidate.model);
28267
- if (seen.has(key)) return;
28268
- if (enforceAllowlist && allowlist && !allowlist.has(key)) return;
28269
- seen.add(key);
28270
- candidates.push(candidate);
28271
- };
28272
- const addExplicitCandidate = (candidate) => {
28273
- addCandidate(candidate, false);
28274
- };
28275
- const addAllowlistedCandidate = (candidate) => {
28276
- addCandidate(candidate, true);
28277
- };
27916
+ function staticAuthContext() {
28278
27917
  return {
28279
- candidates,
28280
- addExplicitCandidate,
28281
- addAllowlistedCandidate
27918
+ resolveProviderApiKey: () => ({ apiKey: void 0 }),
27919
+ resolveProviderAuth: () => ({
27920
+ apiKey: void 0,
27921
+ discoveryApiKey: void 0,
27922
+ mode: "none",
27923
+ source: "none"
27924
+ })
28282
27925
  };
28283
27926
  }
28284
- function sameModelCandidate(a, b) {
28285
- return a.provider === b.provider && a.model === b.model;
28286
- }
28287
- function throwFallbackFailureSummary(params) {
28288
- if (params.attempts.length <= 1 && params.lastError) throw params.lastError;
28289
- const summary = params.attempts.length > 0 ? params.attempts.map(params.formatAttempt).join(" | ") : "unknown";
28290
- throw new Error(`All ${params.label} failed (${params.attempts.length || params.candidates.length}): ${summary}`, { cause: params.lastError instanceof Error ? params.lastError : void 0 });
27927
+ async function resolveProviderStaticCatalog(params) {
27928
+ if (!params.provider.staticCatalog) return {};
27929
+ const result = await runProviderStaticCatalog({
27930
+ provider: params.provider,
27931
+ config: params.config,
27932
+ agentDir: params.agentDir,
27933
+ workspaceDir: params.workspaceDir,
27934
+ env: params.env,
27935
+ ...staticAuthContext()
27936
+ });
27937
+ return normalizePluginDiscoveryResult({
27938
+ provider: params.provider,
27939
+ result
27940
+ });
28291
27941
  }
28292
- function resolveImageFallbackCandidates(params) {
28293
- const aliasIndex = buildModelAliasIndex({
28294
- cfg: params.cfg ?? {},
28295
- defaultProvider: params.defaultProvider
27942
+ async function augmentModelCatalogWithProviderPlugins(params) {
27943
+ const env = params.env ?? process.env;
27944
+ const providers = resolvePluginProviders({
27945
+ config: params.config,
27946
+ workspaceDir: params.workspaceDir
28296
27947
  });
28297
- const { candidates, addExplicitCandidate, addAllowlistedCandidate } = createModelCandidateCollector(buildConfiguredAllowlistKeys({
28298
- cfg: params.cfg,
28299
- defaultProvider: params.defaultProvider
28300
- }));
28301
- const addRaw = (raw, opts) => {
28302
- const resolved = resolveModelRefFromString({
28303
- raw: String(raw ?? ""),
28304
- defaultProvider: params.defaultProvider,
28305
- aliasIndex
28306
- });
28307
- if (!resolved) return;
28308
- if (opts?.allowlist) {
28309
- addAllowlistedCandidate(resolved.ref);
28310
- return;
28311
- }
28312
- addExplicitCandidate(resolved.ref);
28313
- };
28314
- if (params.modelOverride?.trim()) addRaw(params.modelOverride);
28315
- else {
28316
- const primary = resolveAgentModelPrimaryValue(params.cfg?.agents?.defaults?.imageModel);
28317
- if (primary?.trim()) addRaw(primary);
27948
+ const catalogProviders = {};
27949
+ for (const provider of providers) try {
27950
+ if (provider.models) mergeProviders(catalogProviders, normalizePluginDiscoveryResult({
27951
+ provider,
27952
+ result: { provider: provider.models }
27953
+ }));
27954
+ mergeProviders(catalogProviders, await resolveProviderStaticCatalog({
27955
+ provider,
27956
+ config: params.config,
27957
+ agentDir: params.agentDir,
27958
+ workspaceDir: params.workspaceDir,
27959
+ env
27960
+ }));
27961
+ } catch (error) {
27962
+ log$18.warn(`Failed to read provider catalog for ${provider.id}: ${String(error)}`);
28318
27963
  }
28319
- const imageFallbacks = resolveAgentModelFallbackValues(params.cfg?.agents?.defaults?.imageModel);
28320
- for (const raw of imageFallbacks) addRaw(raw);
28321
- return candidates;
27964
+ return catalogProviders;
28322
27965
  }
28323
- function resolveFallbackCandidates(params) {
28324
- const primary = params.cfg ? resolveConfiguredModelRef({
28325
- cfg: params.cfg,
28326
- defaultProvider: DEFAULT_PROVIDER,
28327
- defaultModel: DEFAULT_MODEL
28328
- }) : null;
28329
- const defaultProvider = primary?.provider ?? DEFAULT_PROVIDER;
28330
- const defaultModel = primary?.model ?? DEFAULT_MODEL;
28331
- const normalizedPrimary = normalizeModelRef$1(String(params.provider ?? "").trim() || defaultProvider, String(params.model ?? "").trim() || defaultModel);
28332
- const configuredPrimary = normalizeModelRef$1(defaultProvider, defaultModel);
28333
- const aliasIndex = buildModelAliasIndex({
28334
- cfg: params.cfg ?? {},
28335
- defaultProvider
28336
- });
28337
- const { candidates, addExplicitCandidate } = createModelCandidateCollector(buildConfiguredAllowlistKeys({
28338
- cfg: params.cfg,
28339
- defaultProvider
27966
+
27967
+ //#endregion
27968
+ //#region src/agents/model-catalog-source.ts
27969
+ function normalizePositiveNumber(value) {
27970
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : void 0;
27971
+ }
27972
+ function normalizeBoolean$1(value) {
27973
+ return typeof value === "boolean" ? value : void 0;
27974
+ }
27975
+ function normalizeString$1(value) {
27976
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
27977
+ }
27978
+ function normalizeInput(value) {
27979
+ if (!Array.isArray(value)) return ["text"];
27980
+ const out = value.filter((item) => item === "text" || item === "image");
27981
+ return out.length > 0 ? out : ["text"];
27982
+ }
27983
+ function normalizeApi(value) {
27984
+ return MODEL_APIS.includes(value) ? value : void 0;
27985
+ }
27986
+ function isSupportedRuntimeCatalogModel(provider, id) {
27987
+ if (provider !== "openai-codex") return true;
27988
+ return isOpenAISignInRuntimeModelSupported(id);
27989
+ }
27990
+ function configuredProviderCatalogRows(cfg) {
27991
+ return Object.entries(cfg.models?.providers ?? {}).flatMap(([provider, providerConfig]) => normalizeProviderCatalogRows({
27992
+ provider,
27993
+ providerConfig,
27994
+ source: "configured",
27995
+ status: "stable"
28340
27996
  }));
28341
- addExplicitCandidate(normalizedPrimary);
28342
- const modelFallbacks = (() => {
28343
- if (params.fallbacksOverride !== void 0) return params.fallbacksOverride;
28344
- const configuredFallbacks = resolveAgentModelFallbackValues(params.cfg?.agents?.defaults?.model);
28345
- if (normalizedPrimary.provider !== configuredPrimary.provider) return configuredFallbacks.some((raw) => {
28346
- const resolved = resolveModelRefFromString({
28347
- raw: String(raw ?? ""),
28348
- defaultProvider,
28349
- aliasIndex
28350
- });
28351
- return resolved ? sameModelCandidate(resolved.ref, normalizedPrimary) : false;
28352
- }) ? configuredFallbacks : [];
28353
- return configuredFallbacks;
28354
- })();
28355
- for (const raw of modelFallbacks) {
28356
- const resolved = resolveModelRefFromString({
28357
- raw: String(raw ?? ""),
28358
- defaultProvider,
28359
- aliasIndex
28360
- });
28361
- if (!resolved) continue;
28362
- addExplicitCandidate(resolved.ref);
28363
- }
28364
- if (params.fallbacksOverride === void 0 && primary?.provider && primary.model) addExplicitCandidate({
28365
- provider: primary.provider,
28366
- model: primary.model
28367
- });
28368
- return candidates;
28369
27997
  }
28370
- const lastProbeAttempt = /* @__PURE__ */ new Map();
28371
- const MIN_PROBE_INTERVAL_MS = 3e4;
28372
- const PROBE_MARGIN_MS = 120 * 1e3;
28373
- const PROBE_STATE_TTL_MS = 600 * 1e3;
28374
- const MAX_PROBE_KEYS = 256;
28375
- const PROBE_SCOPE_DELIMITER = "::";
28376
- function resolveProbeThrottleKey(provider, agentDir) {
28377
- const scope = String(agentDir ?? "").trim();
28378
- return scope ? `${scope}${PROBE_SCOPE_DELIMITER}${provider}` : provider;
27998
+ function providerPluginCatalogRows(providers) {
27999
+ return Object.entries(providers ?? {}).flatMap(([provider, providerConfig]) => normalizeProviderCatalogRows({
28000
+ provider,
28001
+ providerConfig,
28002
+ source: "provider-index",
28003
+ status: "stable"
28004
+ }));
28379
28005
  }
28380
- function pruneProbeThrottleState(now) {
28381
- for (const [key, timestamp] of lastProbeAttempt) if (now - timestamp > PROBE_STATE_TTL_MS) lastProbeAttempt.delete(key);
28382
- while (lastProbeAttempt.size > MAX_PROBE_KEYS) {
28383
- let oldestKey;
28384
- let oldest = Number.POSITIVE_INFINITY;
28385
- for (const [key, timestamp] of lastProbeAttempt) if (timestamp < oldest) {
28386
- oldest = timestamp;
28387
- oldestKey = key;
28388
- }
28389
- if (!oldestKey) return;
28390
- lastProbeAttempt.delete(oldestKey);
28006
+ function runtimeCatalogRows(params) {
28007
+ const rows = [];
28008
+ for (const model of params.models) try {
28009
+ const idRaw = normalizeString$1(model.id);
28010
+ const providerRaw = normalizeString$1(model.provider);
28011
+ if (!idRaw || !providerRaw) continue;
28012
+ const id = normalizeModelCatalogModelId(idRaw);
28013
+ const provider = normalizeModelCatalogProviderId(providerRaw);
28014
+ if (!id || !provider) continue;
28015
+ if (!isSupportedRuntimeCatalogModel(provider, id)) continue;
28016
+ if (id.toLowerCase() === "gpt-5.3-codex-spark" && (provider === "openai" || provider === "azure-openai-responses")) continue;
28017
+ rows.push({
28018
+ id,
28019
+ name: normalizeString$1(model.name) ?? id,
28020
+ provider,
28021
+ mergeKey: buildModelCatalogMergeKey(provider, id),
28022
+ source: "runtime",
28023
+ status: "stable",
28024
+ input: normalizeInput(model.input),
28025
+ contextWindow: normalizePositiveNumber(model.contextWindow),
28026
+ maxTokens: normalizePositiveNumber(model.maxTokens),
28027
+ reasoning: normalizeBoolean$1(model.reasoning),
28028
+ baseUrl: normalizeString$1(model.baseUrl),
28029
+ api: normalizeApi(model.api)
28030
+ });
28031
+ } catch (error) {
28032
+ params.onEntryError?.(error);
28391
28033
  }
28034
+ return rows;
28392
28035
  }
28393
- function isProbeThrottleOpen(now, throttleKey) {
28394
- pruneProbeThrottleState(now);
28395
- return now - (lastProbeAttempt.get(throttleKey) ?? 0) < MIN_PROBE_INTERVAL_MS;
28036
+ function manifestCatalogRows() {
28037
+ return listProviderBrandManifests().flatMap((manifest) => manifest.models.recommended.flatMap((ref) => {
28038
+ const slash = ref.indexOf("/");
28039
+ if (slash <= 0 || slash === ref.length - 1) return [];
28040
+ const provider = normalizeModelCatalogProviderId(ref.slice(0, slash));
28041
+ const id = normalizeModelCatalogModelId(ref.slice(slash + 1));
28042
+ if (!provider || !id) return [];
28043
+ return [{
28044
+ id,
28045
+ name: id,
28046
+ provider,
28047
+ mergeKey: buildModelCatalogMergeKey(provider, id),
28048
+ source: "manifest",
28049
+ status: "stable",
28050
+ input: ["text"]
28051
+ }];
28052
+ }));
28396
28053
  }
28397
- function markProbeAttempt(now, throttleKey) {
28398
- pruneProbeThrottleState(now);
28399
- lastProbeAttempt.set(throttleKey, now);
28400
- pruneProbeThrottleState(now);
28054
+ function providerConfigForRow(cfg, row) {
28055
+ return cfg.models?.providers?.[row.provider] ?? CURRENT_MODEL_PROVIDER_CATALOG[row.provider];
28401
28056
  }
28402
- function shouldProbePrimaryDuringCooldown(params) {
28403
- if (!params.isPrimary || !params.hasFallbackCandidates) return false;
28404
- if (isProbeThrottleOpen(params.now, params.throttleKey)) return false;
28405
- const soonest = getSoonestCooldownExpiry(params.authStore, params.profileIds);
28406
- if (soonest === null || !Number.isFinite(soonest)) return true;
28407
- return params.now >= soonest - PROBE_MARGIN_MS;
28057
+ function buildFasedModelCatalogRows(params) {
28058
+ const discoveredRows = mergeModelCatalogRowsByAuthority([
28059
+ ...[...listCurrentModelCatalogRows(), ...providerPluginCatalogRows(params.providerPluginProviders)].filter((row) => isSupportedRuntimeCatalogModel(row.provider, row.id)),
28060
+ ...runtimeCatalogRows({
28061
+ models: params.runtimeModels ?? [],
28062
+ onEntryError: params.onRuntimeEntryError
28063
+ }),
28064
+ ...configuredProviderCatalogRows(params.config)
28065
+ ]);
28066
+ const discoveredKeys = new Set(discoveredRows.map((row) => row.mergeKey));
28067
+ const missingManifestRows = manifestCatalogRows().filter((row) => !discoveredKeys.has(row.mergeKey));
28068
+ return mergeModelCatalogRowsByAuthority([...discoveredRows, ...missingManifestRows]);
28408
28069
  }
28409
- function resolveCooldownDecision(params) {
28410
- const shouldProbe = shouldProbePrimaryDuringCooldown({
28411
- isPrimary: params.isPrimary,
28412
- hasFallbackCandidates: params.hasFallbackCandidates,
28413
- now: params.now,
28414
- throttleKey: params.probeThrottleKey,
28070
+ function buildFasedModelCatalogEntries(params) {
28071
+ return buildFasedModelCatalogRows({
28072
+ config: params.config,
28073
+ runtimeModels: params.runtimeModels,
28074
+ providerPluginProviders: params.providerPluginProviders,
28075
+ onRuntimeEntryError: params.onRuntimeEntryError
28076
+ }).map((row) => {
28077
+ const providerConfig = providerConfigForRow(params.config, row);
28078
+ const model = {
28079
+ id: row.id,
28080
+ name: row.name,
28081
+ provider: row.provider,
28082
+ contextWindow: row.contextWindow,
28083
+ maxTokens: row.maxTokens,
28084
+ reasoning: row.reasoning,
28085
+ input: row.input,
28086
+ baseUrl: row.baseUrl,
28087
+ api: row.api,
28088
+ catalogSource: row.source
28089
+ };
28090
+ return {
28091
+ ...model,
28092
+ ...params.includeMetadata ? { metadata: deriveModelMetadata({
28093
+ model,
28094
+ cfg: params.config,
28095
+ providerConfig,
28096
+ recommended: isStandardProviderCatalogEntry(row)
28097
+ }) } : {}
28098
+ };
28099
+ });
28100
+ }
28101
+
28102
+ //#endregion
28103
+ //#region src/agents/provider-extension-catalog-index.ts
28104
+ const UNSAFE_PROVIDER_KEYS = new Set([
28105
+ "__proto__",
28106
+ "prototype",
28107
+ "constructor"
28108
+ ]);
28109
+ const DEFAULT_PROVIDER_EXTENSION_CATALOG_ENTRIES = [];
28110
+ let providerExtensionCatalogEntriesForTest;
28111
+ function listBundledProviderExtensionCatalogEntries() {
28112
+ return providerExtensionCatalogEntriesForTest ?? DEFAULT_PROVIDER_EXTENSION_CATALOG_ENTRIES;
28113
+ }
28114
+ function normalizeProviderIds(providerIds) {
28115
+ return [...new Set(providerIds.map((providerId) => normalizeModelCatalogProviderId(providerId)).filter((providerId) => providerId.length > 0 && !UNSAFE_PROVIDER_KEYS.has(providerId)))].toSorted((left, right) => left.localeCompare(right));
28116
+ }
28117
+ function normalizeEntryTrust(entry) {
28118
+ return entry.trusted === true || entry.source === "bundled";
28119
+ }
28120
+ function collectProviderConfigs(entry, module) {
28121
+ const providers = {};
28122
+ const explicitProviderIds = normalizeProviderIds(entry.providerIds);
28123
+ const moduleProviders = module.providers ?? module.default?.providers;
28124
+ if (moduleProviders) for (const [providerIdRaw, providerConfig] of Object.entries(moduleProviders)) {
28125
+ const providerId = normalizeProviderIds([providerIdRaw])[0];
28126
+ if (!providerId || !providerConfig) continue;
28127
+ providers[providerId] = providerConfig;
28128
+ }
28129
+ const singleProvider = module.provider ?? module.default?.provider;
28130
+ if (singleProvider && explicitProviderIds[0]) providers[explicitProviderIds[0]] = singleProvider;
28131
+ return providers;
28132
+ }
28133
+ function countModels(providers) {
28134
+ return Object.values(providers).reduce((total, provider) => total + (Array.isArray(provider.models) ? provider.models.length : 0), 0);
28135
+ }
28136
+ function formatCatalogError(error) {
28137
+ return error instanceof Error ? error.message : String(error);
28138
+ }
28139
+ async function loadProviderExtensionCatalogIndex(params) {
28140
+ const entries = params?.entries ?? listBundledProviderExtensionCatalogEntries();
28141
+ const includeUntrusted = params?.includeUntrusted === true;
28142
+ const providers = {};
28143
+ const statuses = [];
28144
+ for (const entry of entries) {
28145
+ const providerIds = normalizeProviderIds(entry.providerIds);
28146
+ const trusted = normalizeEntryTrust(entry);
28147
+ if (!trusted && !includeUntrusted) {
28148
+ statuses.push({
28149
+ id: entry.id,
28150
+ source: entry.source,
28151
+ trusted,
28152
+ providerIds,
28153
+ loadedProviderIds: [],
28154
+ modelCount: 0,
28155
+ status: "skipped-untrusted"
28156
+ });
28157
+ continue;
28158
+ }
28159
+ try {
28160
+ const loadedProviders = collectProviderConfigs(entry, await entry.load());
28161
+ const loadedProviderIds = Object.keys(loadedProviders).toSorted((left, right) => left.localeCompare(right));
28162
+ for (const providerId of loadedProviderIds) providers[providerId] = loadedProviders[providerId];
28163
+ const modelCount = countModels(loadedProviders);
28164
+ statuses.push({
28165
+ id: entry.id,
28166
+ source: entry.source,
28167
+ trusted,
28168
+ providerIds,
28169
+ loadedProviderIds,
28170
+ modelCount,
28171
+ status: loadedProviderIds.length > 0 ? "loaded" : "empty"
28172
+ });
28173
+ } catch (error) {
28174
+ statuses.push({
28175
+ id: entry.id,
28176
+ source: entry.source,
28177
+ trusted,
28178
+ providerIds,
28179
+ loadedProviderIds: [],
28180
+ modelCount: 0,
28181
+ status: "error",
28182
+ error: formatCatalogError(error)
28183
+ });
28184
+ }
28185
+ }
28186
+ return {
28187
+ providers,
28188
+ entries: statuses
28189
+ };
28190
+ }
28191
+
28192
+ //#endregion
28193
+ //#region src/agents/model-catalog.ts
28194
+ const log$17 = createSubsystemLogger("model-catalog");
28195
+ let modelCatalogPromise = null;
28196
+ let hasLoggedModelCatalogError = false;
28197
+ let hasLoggedProviderCatalogError = false;
28198
+ const defaultImportPiSdk = () => import("./pi-model-discovery-BpEilAym.js").then((n) => n.a);
28199
+ let importPiSdk = defaultImportPiSdk;
28200
+ const CODEX_PROVIDER = "openai-codex";
28201
+ const OPENAI_PROVIDER = "openai";
28202
+ const OPENAI_GPT55_MODEL_ID = "gpt-5.5";
28203
+ const OPENAI_GPT54_MODEL_ID = "gpt-5.4";
28204
+ const OPENAI_GPT54_MINI_MODEL_ID = "gpt-5.4-mini";
28205
+ const OPENAI_GPT54_NANO_MODEL_ID = "gpt-5.4-nano";
28206
+ const OPENAI_CODEX_GPT55_MODEL_ID = "gpt-5.5";
28207
+ const OPENAI_CODEX_GPT54_MODEL_ID = "gpt-5.4";
28208
+ const OPENAI_CODEX_GPT54_MINI_MODEL_ID = "gpt-5.4-mini";
28209
+ const OPENAI_CODEX_GPT53_SPARK_MODEL_ID = "gpt-5.3-codex-spark";
28210
+ const SYNTHETIC_CATALOG_FALLBACKS = [
28211
+ {
28212
+ provider: OPENAI_PROVIDER,
28213
+ id: OPENAI_GPT55_MODEL_ID,
28214
+ templateIds: [OPENAI_GPT54_MODEL_ID, "gpt-5.2"]
28215
+ },
28216
+ {
28217
+ provider: OPENAI_PROVIDER,
28218
+ id: OPENAI_GPT54_MODEL_ID,
28219
+ templateIds: ["gpt-5.2"]
28220
+ },
28221
+ {
28222
+ provider: OPENAI_PROVIDER,
28223
+ id: OPENAI_GPT54_MINI_MODEL_ID,
28224
+ templateIds: ["gpt-5-mini"]
28225
+ },
28226
+ {
28227
+ provider: OPENAI_PROVIDER,
28228
+ id: OPENAI_GPT54_NANO_MODEL_ID,
28229
+ templateIds: ["gpt-5-nano", "gpt-5-mini"]
28230
+ },
28231
+ {
28232
+ provider: CODEX_PROVIDER,
28233
+ id: OPENAI_CODEX_GPT55_MODEL_ID,
28234
+ templateIds: [OPENAI_CODEX_GPT54_MODEL_ID, OPENAI_CODEX_GPT53_SPARK_MODEL_ID]
28235
+ },
28236
+ {
28237
+ provider: CODEX_PROVIDER,
28238
+ id: OPENAI_CODEX_GPT54_MODEL_ID,
28239
+ templateIds: [OPENAI_CODEX_GPT53_SPARK_MODEL_ID]
28240
+ },
28241
+ {
28242
+ provider: CODEX_PROVIDER,
28243
+ id: OPENAI_CODEX_GPT54_MINI_MODEL_ID,
28244
+ templateIds: [OPENAI_CODEX_GPT54_MODEL_ID, OPENAI_CODEX_GPT53_SPARK_MODEL_ID]
28245
+ }
28246
+ ];
28247
+ function applySyntheticCatalogFallbacks(models) {
28248
+ const findCatalogEntry = (provider, id) => models.find((entry) => entry.provider.toLowerCase() === provider.toLowerCase() && entry.id.toLowerCase() === id.toLowerCase());
28249
+ for (const fallback of SYNTHETIC_CATALOG_FALLBACKS) {
28250
+ if (findCatalogEntry(fallback.provider, fallback.id)) continue;
28251
+ const template = fallback.templateIds.map((templateId) => findCatalogEntry(fallback.provider, templateId)).find((entry) => entry !== void 0);
28252
+ if (!template) continue;
28253
+ const { metadata: _ignoredMetadata, ...templateWithoutMetadata } = template;
28254
+ models.push({
28255
+ ...templateWithoutMetadata,
28256
+ id: fallback.id,
28257
+ name: fallback.id,
28258
+ ...template.metadata ? { metadata: deriveModelMetadata({ model: {
28259
+ ...templateWithoutMetadata,
28260
+ id: fallback.id,
28261
+ name: fallback.id
28262
+ } }) } : {}
28263
+ });
28264
+ }
28265
+ }
28266
+ async function loadProviderPluginCatalogProviders(params) {
28267
+ try {
28268
+ return await augmentModelCatalogWithProviderPlugins({
28269
+ config: params.config,
28270
+ agentDir: params.agentDir,
28271
+ env: process.env
28272
+ });
28273
+ } catch (error) {
28274
+ if (!hasLoggedProviderCatalogError) {
28275
+ hasLoggedProviderCatalogError = true;
28276
+ log$17.warn(`Failed to load provider plugin model catalog: ${String(error)}`);
28277
+ }
28278
+ return {};
28279
+ }
28280
+ }
28281
+ async function loadProviderExtensionCatalogProviders() {
28282
+ try {
28283
+ return (await loadProviderExtensionCatalogIndex()).providers;
28284
+ } catch (error) {
28285
+ if (!hasLoggedProviderCatalogError) {
28286
+ hasLoggedProviderCatalogError = true;
28287
+ log$17.warn(`Failed to load provider extension model catalog: ${String(error)}`);
28288
+ }
28289
+ return {};
28290
+ }
28291
+ }
28292
+ async function loadModelCatalog(params) {
28293
+ if (params?.useCache === false) modelCatalogPromise = null;
28294
+ if (modelCatalogPromise) return modelCatalogPromise;
28295
+ modelCatalogPromise = (async () => {
28296
+ const models = [];
28297
+ const sortModels = (entries) => entries.sort((a, b) => {
28298
+ const p = a.provider.localeCompare(b.provider);
28299
+ if (p !== 0) return p;
28300
+ return a.name.localeCompare(b.name);
28301
+ });
28302
+ try {
28303
+ const cfg = params?.config ?? loadConfig();
28304
+ await ensureFasedAgentModelsJson(cfg);
28305
+ const piSdk = await importPiSdk();
28306
+ const agentDir = resolveFasedAgentAgentDir();
28307
+ const { join } = await import("node:path");
28308
+ const authStorage = piSdk.discoverAuthStorage(agentDir);
28309
+ const registry = new piSdk.ModelRegistry(authStorage, join(agentDir, "models.json"));
28310
+ const entries = Array.isArray(registry) ? registry : registry.getAll();
28311
+ const runtimeModels = [];
28312
+ for (const entry of entries) runtimeModels.push(entry);
28313
+ const providerPluginProviders = await loadProviderPluginCatalogProviders({
28314
+ config: cfg,
28315
+ agentDir
28316
+ });
28317
+ const providerExtensionCatalogProviders = await loadProviderExtensionCatalogProviders();
28318
+ models.push(...buildFasedModelCatalogEntries({
28319
+ config: cfg,
28320
+ runtimeModels,
28321
+ providerPluginProviders: {
28322
+ ...providerExtensionCatalogProviders,
28323
+ ...providerPluginProviders
28324
+ },
28325
+ includeMetadata: params?.includeMetadata,
28326
+ onRuntimeEntryError: (error) => {
28327
+ if (!hasLoggedModelCatalogError) {
28328
+ hasLoggedModelCatalogError = true;
28329
+ log$17.warn(`Failed to read model catalog entry: ${String(error)}`);
28330
+ }
28331
+ }
28332
+ }));
28333
+ applySyntheticCatalogFallbacks(models);
28334
+ if (models.length === 0) modelCatalogPromise = null;
28335
+ return sortModels(models);
28336
+ } catch (error) {
28337
+ if (!hasLoggedModelCatalogError) {
28338
+ hasLoggedModelCatalogError = true;
28339
+ log$17.warn(`Failed to load model catalog: ${String(error)}`);
28340
+ }
28341
+ modelCatalogPromise = null;
28342
+ if (models.length > 0) return sortModels(models);
28343
+ return [];
28344
+ }
28345
+ })();
28346
+ return modelCatalogPromise;
28347
+ }
28348
+ /**
28349
+ * Check if a model supports image input based on its catalog entry.
28350
+ */
28351
+ function modelSupportsVision(entry) {
28352
+ return entry?.input?.includes("image") ?? false;
28353
+ }
28354
+ /**
28355
+ * Find a model in the catalog by provider and model ID.
28356
+ */
28357
+ function findModelInCatalog(catalog, provider, modelId) {
28358
+ const normalizedProvider = normalizeModelCatalogProviderId(provider);
28359
+ const normalizedModelId = modelId.toLowerCase().trim();
28360
+ return catalog.find((entry) => normalizeModelCatalogProviderId(entry.provider) === normalizedProvider && entry.id.toLowerCase() === normalizedModelId);
28361
+ }
28362
+
28363
+ //#endregion
28364
+ //#region src/agents/failover-error.ts
28365
+ const TIMEOUT_HINT_RE = /timeout|timed out|deadline exceeded|context deadline exceeded|stop reason:\s*abort|reason:\s*abort|unhandled stop reason:\s*abort/i;
28366
+ const ABORT_TIMEOUT_RE = /request was aborted|request aborted/i;
28367
+ var FailoverError = class extends Error {
28368
+ constructor(message, params) {
28369
+ super(message, { cause: params.cause });
28370
+ this.name = "FailoverError";
28371
+ this.reason = params.reason;
28372
+ this.provider = params.provider;
28373
+ this.model = params.model;
28374
+ this.profileId = params.profileId;
28375
+ this.status = params.status;
28376
+ this.code = params.code;
28377
+ }
28378
+ };
28379
+ function isFailoverError(err) {
28380
+ return err instanceof FailoverError;
28381
+ }
28382
+ function resolveFailoverStatus(reason) {
28383
+ switch (reason) {
28384
+ case "billing": return 402;
28385
+ case "rate_limit": return 429;
28386
+ case "auth": return 401;
28387
+ case "auth_permanent": return 403;
28388
+ case "timeout": return 408;
28389
+ case "format": return 400;
28390
+ case "model_not_found": return 404;
28391
+ default: return;
28392
+ }
28393
+ }
28394
+ function getStatusCode(err) {
28395
+ if (!err || typeof err !== "object") return;
28396
+ const candidate = err.status ?? err.statusCode;
28397
+ if (typeof candidate === "number") return candidate;
28398
+ if (typeof candidate === "string" && /^\d+$/.test(candidate)) return Number(candidate);
28399
+ }
28400
+ function getErrorName(err) {
28401
+ if (!err || typeof err !== "object") return "";
28402
+ return "name" in err ? String(err.name) : "";
28403
+ }
28404
+ function getErrorCode(err) {
28405
+ if (!err || typeof err !== "object") return;
28406
+ const candidate = err.code;
28407
+ if (typeof candidate !== "string") return;
28408
+ const trimmed = candidate.trim();
28409
+ return trimmed ? trimmed : void 0;
28410
+ }
28411
+ function getErrorMessage(err) {
28412
+ if (err instanceof Error) return err.message;
28413
+ if (typeof err === "string") return err;
28414
+ if (typeof err === "number" || typeof err === "boolean" || typeof err === "bigint") return String(err);
28415
+ if (typeof err === "symbol") return err.description ?? "";
28416
+ if (err && typeof err === "object") {
28417
+ const message = err.message;
28418
+ if (typeof message === "string") return message;
28419
+ }
28420
+ return "";
28421
+ }
28422
+ function hasTimeoutHint(err) {
28423
+ if (!err) return false;
28424
+ if (getErrorName(err) === "TimeoutError") return true;
28425
+ const message = getErrorMessage(err);
28426
+ return Boolean(message && TIMEOUT_HINT_RE.test(message));
28427
+ }
28428
+ function isTimeoutError(err) {
28429
+ if (hasTimeoutHint(err)) return true;
28430
+ if (!err || typeof err !== "object") return false;
28431
+ if (getErrorName(err) !== "AbortError") return false;
28432
+ const message = getErrorMessage(err);
28433
+ if (message && ABORT_TIMEOUT_RE.test(message)) return true;
28434
+ const cause = "cause" in err ? err.cause : void 0;
28435
+ const reason = "reason" in err ? err.reason : void 0;
28436
+ return hasTimeoutHint(cause) || hasTimeoutHint(reason);
28437
+ }
28438
+ function resolveFailoverReasonFromError(err) {
28439
+ if (isFailoverError(err)) return err.reason;
28440
+ const status = getStatusCode(err);
28441
+ if (status === 402) return "billing";
28442
+ if (status === 429) return "rate_limit";
28443
+ if (status === 401 || status === 403) {
28444
+ const msg = getErrorMessage(err);
28445
+ if (msg && isAuthPermanentErrorMessage(msg)) return "auth_permanent";
28446
+ return "auth";
28447
+ }
28448
+ if (status === 408) return "timeout";
28449
+ if (status === 502 || status === 503 || status === 504) return "timeout";
28450
+ if (status === 400) return "format";
28451
+ const code = (getErrorCode(err) ?? "").toUpperCase();
28452
+ if ([
28453
+ "ETIMEDOUT",
28454
+ "ESOCKETTIMEDOUT",
28455
+ "ECONNRESET",
28456
+ "ECONNABORTED"
28457
+ ].includes(code)) return "timeout";
28458
+ if (isTimeoutError(err)) return "timeout";
28459
+ const message = getErrorMessage(err);
28460
+ if (!message) return null;
28461
+ return classifyFailoverReason(message);
28462
+ }
28463
+ function describeFailoverError(err) {
28464
+ if (isFailoverError(err)) return {
28465
+ message: err.message,
28466
+ reason: err.reason,
28467
+ status: err.status,
28468
+ code: err.code
28469
+ };
28470
+ return {
28471
+ message: getErrorMessage(err) || String(err),
28472
+ reason: resolveFailoverReasonFromError(err) ?? void 0,
28473
+ status: getStatusCode(err),
28474
+ code: getErrorCode(err)
28475
+ };
28476
+ }
28477
+ function coerceToFailoverError(err, context) {
28478
+ if (isFailoverError(err)) return err;
28479
+ const reason = resolveFailoverReasonFromError(err);
28480
+ if (!reason) return null;
28481
+ const message = getErrorMessage(err) || String(err);
28482
+ const status = getStatusCode(err) ?? resolveFailoverStatus(reason);
28483
+ const code = getErrorCode(err);
28484
+ return new FailoverError(message, {
28485
+ reason,
28486
+ provider: context?.provider,
28487
+ model: context?.model,
28488
+ profileId: context?.profileId,
28489
+ status,
28490
+ code,
28491
+ cause: err instanceof Error ? err : void 0
28492
+ });
28493
+ }
28494
+
28495
+ //#endregion
28496
+ //#region src/agents/model-fallback.ts
28497
+ /**
28498
+ * Fallback abort check. Only treats explicit AbortError names as user aborts.
28499
+ * Message-based checks (e.g., "aborted") can mask timeouts and skip fallback.
28500
+ */
28501
+ function isFallbackAbortError(err) {
28502
+ if (!err || typeof err !== "object") return false;
28503
+ if (isFailoverError(err)) return false;
28504
+ return ("name" in err ? String(err.name) : "") === "AbortError";
28505
+ }
28506
+ function shouldRethrowAbort(err) {
28507
+ return isFallbackAbortError(err) && !isTimeoutError(err);
28508
+ }
28509
+ function createModelCandidateCollector(allowlist) {
28510
+ const seen = /* @__PURE__ */ new Set();
28511
+ const candidates = [];
28512
+ const addCandidate = (candidate, enforceAllowlist) => {
28513
+ if (!candidate.provider || !candidate.model) return;
28514
+ const key = modelKey(candidate.provider, candidate.model);
28515
+ if (seen.has(key)) return;
28516
+ if (enforceAllowlist && allowlist && !allowlist.has(key)) return;
28517
+ seen.add(key);
28518
+ candidates.push(candidate);
28519
+ };
28520
+ const addExplicitCandidate = (candidate) => {
28521
+ addCandidate(candidate, false);
28522
+ };
28523
+ const addAllowlistedCandidate = (candidate) => {
28524
+ addCandidate(candidate, true);
28525
+ };
28526
+ return {
28527
+ candidates,
28528
+ addExplicitCandidate,
28529
+ addAllowlistedCandidate
28530
+ };
28531
+ }
28532
+ function sameModelCandidate(a, b) {
28533
+ return a.provider === b.provider && a.model === b.model;
28534
+ }
28535
+ function throwFallbackFailureSummary(params) {
28536
+ if (params.attempts.length <= 1 && params.lastError) throw params.lastError;
28537
+ const summary = params.attempts.length > 0 ? params.attempts.map(params.formatAttempt).join(" | ") : "unknown";
28538
+ throw new Error(`All ${params.label} failed (${params.attempts.length || params.candidates.length}): ${summary}`, { cause: params.lastError instanceof Error ? params.lastError : void 0 });
28539
+ }
28540
+ function resolveImageFallbackCandidates(params) {
28541
+ const aliasIndex = buildModelAliasIndex({
28542
+ cfg: params.cfg ?? {},
28543
+ defaultProvider: params.defaultProvider
28544
+ });
28545
+ const { candidates, addExplicitCandidate, addAllowlistedCandidate } = createModelCandidateCollector(buildConfiguredAllowlistKeys({
28546
+ cfg: params.cfg,
28547
+ defaultProvider: params.defaultProvider
28548
+ }));
28549
+ const addRaw = (raw, opts) => {
28550
+ const resolved = resolveModelRefFromString({
28551
+ raw: String(raw ?? ""),
28552
+ defaultProvider: params.defaultProvider,
28553
+ aliasIndex
28554
+ });
28555
+ if (!resolved) return;
28556
+ if (opts?.allowlist) {
28557
+ addAllowlistedCandidate(resolved.ref);
28558
+ return;
28559
+ }
28560
+ addExplicitCandidate(resolved.ref);
28561
+ };
28562
+ if (params.modelOverride?.trim()) addRaw(params.modelOverride);
28563
+ else {
28564
+ const primary = resolveAgentModelPrimaryValue(params.cfg?.agents?.defaults?.imageModel);
28565
+ if (primary?.trim()) addRaw(primary);
28566
+ }
28567
+ const imageFallbacks = resolveAgentModelFallbackValues(params.cfg?.agents?.defaults?.imageModel);
28568
+ for (const raw of imageFallbacks) addRaw(raw);
28569
+ return candidates;
28570
+ }
28571
+ function resolveFallbackCandidates(params) {
28572
+ const primary = params.cfg ? resolveConfiguredModelRef({
28573
+ cfg: params.cfg,
28574
+ defaultProvider: DEFAULT_PROVIDER,
28575
+ defaultModel: DEFAULT_MODEL
28576
+ }) : null;
28577
+ const defaultProvider = primary?.provider ?? DEFAULT_PROVIDER;
28578
+ const defaultModel = primary?.model ?? DEFAULT_MODEL;
28579
+ const normalizedPrimary = normalizeModelRef$1(String(params.provider ?? "").trim() || defaultProvider, String(params.model ?? "").trim() || defaultModel);
28580
+ const configuredPrimary = normalizeModelRef$1(defaultProvider, defaultModel);
28581
+ const aliasIndex = buildModelAliasIndex({
28582
+ cfg: params.cfg ?? {},
28583
+ defaultProvider
28584
+ });
28585
+ const { candidates, addExplicitCandidate } = createModelCandidateCollector(buildConfiguredAllowlistKeys({
28586
+ cfg: params.cfg,
28587
+ defaultProvider
28588
+ }));
28589
+ addExplicitCandidate(normalizedPrimary);
28590
+ const modelFallbacks = (() => {
28591
+ if (params.fallbacksOverride !== void 0) return params.fallbacksOverride;
28592
+ const configuredFallbacks = resolveAgentModelFallbackValues(params.cfg?.agents?.defaults?.model);
28593
+ if (normalizedPrimary.provider !== configuredPrimary.provider) return configuredFallbacks.some((raw) => {
28594
+ const resolved = resolveModelRefFromString({
28595
+ raw: String(raw ?? ""),
28596
+ defaultProvider,
28597
+ aliasIndex
28598
+ });
28599
+ return resolved ? sameModelCandidate(resolved.ref, normalizedPrimary) : false;
28600
+ }) ? configuredFallbacks : [];
28601
+ return configuredFallbacks;
28602
+ })();
28603
+ for (const raw of modelFallbacks) {
28604
+ const resolved = resolveModelRefFromString({
28605
+ raw: String(raw ?? ""),
28606
+ defaultProvider,
28607
+ aliasIndex
28608
+ });
28609
+ if (!resolved) continue;
28610
+ addExplicitCandidate(resolved.ref);
28611
+ }
28612
+ if (params.fallbacksOverride === void 0 && primary?.provider && primary.model) addExplicitCandidate({
28613
+ provider: primary.provider,
28614
+ model: primary.model
28615
+ });
28616
+ return candidates;
28617
+ }
28618
+ const lastProbeAttempt = /* @__PURE__ */ new Map();
28619
+ const MIN_PROBE_INTERVAL_MS = 3e4;
28620
+ const PROBE_MARGIN_MS = 120 * 1e3;
28621
+ const PROBE_STATE_TTL_MS = 600 * 1e3;
28622
+ const MAX_PROBE_KEYS = 256;
28623
+ const PROBE_SCOPE_DELIMITER = "::";
28624
+ function resolveProbeThrottleKey(provider, agentDir) {
28625
+ const scope = String(agentDir ?? "").trim();
28626
+ return scope ? `${scope}${PROBE_SCOPE_DELIMITER}${provider}` : provider;
28627
+ }
28628
+ function pruneProbeThrottleState(now) {
28629
+ for (const [key, timestamp] of lastProbeAttempt) if (now - timestamp > PROBE_STATE_TTL_MS) lastProbeAttempt.delete(key);
28630
+ while (lastProbeAttempt.size > MAX_PROBE_KEYS) {
28631
+ let oldestKey;
28632
+ let oldest = Number.POSITIVE_INFINITY;
28633
+ for (const [key, timestamp] of lastProbeAttempt) if (timestamp < oldest) {
28634
+ oldest = timestamp;
28635
+ oldestKey = key;
28636
+ }
28637
+ if (!oldestKey) return;
28638
+ lastProbeAttempt.delete(oldestKey);
28639
+ }
28640
+ }
28641
+ function isProbeThrottleOpen(now, throttleKey) {
28642
+ pruneProbeThrottleState(now);
28643
+ return now - (lastProbeAttempt.get(throttleKey) ?? 0) < MIN_PROBE_INTERVAL_MS;
28644
+ }
28645
+ function markProbeAttempt(now, throttleKey) {
28646
+ pruneProbeThrottleState(now);
28647
+ lastProbeAttempt.set(throttleKey, now);
28648
+ pruneProbeThrottleState(now);
28649
+ }
28650
+ function shouldProbePrimaryDuringCooldown(params) {
28651
+ if (!params.isPrimary || !params.hasFallbackCandidates) return false;
28652
+ if (isProbeThrottleOpen(params.now, params.throttleKey)) return false;
28653
+ const soonest = getSoonestCooldownExpiry(params.authStore, params.profileIds);
28654
+ if (soonest === null || !Number.isFinite(soonest)) return true;
28655
+ return params.now >= soonest - PROBE_MARGIN_MS;
28656
+ }
28657
+ function resolveCooldownDecision(params) {
28658
+ const shouldProbe = shouldProbePrimaryDuringCooldown({
28659
+ isPrimary: params.isPrimary,
28660
+ hasFallbackCandidates: params.hasFallbackCandidates,
28661
+ now: params.now,
28662
+ throttleKey: params.probeThrottleKey,
28415
28663
  authStore: params.authStore,
28416
28664
  profileIds: params.profileIds
28417
28665
  });
@@ -29344,7 +29592,7 @@ function createRunRegistry(options) {
29344
29592
 
29345
29593
  //#endregion
29346
29594
  //#region src/process/supervisor/supervisor.ts
29347
- const log$18 = createSubsystemLogger("process/supervisor");
29595
+ const log$16 = createSubsystemLogger("process/supervisor");
29348
29596
  function clampTimeout(value) {
29349
29597
  if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return;
29350
29598
  return Math.max(1, Math.floor(value));
@@ -29530,7 +29778,7 @@ function createProcessSupervisor() {
29530
29778
  exitCode: null,
29531
29779
  exitSignal: null
29532
29780
  });
29533
- log$18.warn(`spawn failed: runId=${runId} reason=${String(err)}`);
29781
+ log$16.warn(`spawn failed: runId=${runId} reason=${String(err)}`);
29534
29782
  throw err;
29535
29783
  }
29536
29784
  };
@@ -29554,12 +29802,12 @@ function getProcessSupervisor() {
29554
29802
 
29555
29803
  //#endregion
29556
29804
  //#region src/agents/bootstrap-cache.ts
29557
- const cache = /* @__PURE__ */ new Map();
29805
+ const cache$1 = /* @__PURE__ */ new Map();
29558
29806
  async function getOrLoadBootstrapFiles(params) {
29559
- const existing = cache.get(params.sessionKey);
29807
+ const existing = cache$1.get(params.sessionKey);
29560
29808
  if (existing) return existing;
29561
29809
  const files = await loadWorkspaceBootstrapFiles(params.workspaceDir);
29562
- cache.set(params.sessionKey, files);
29810
+ cache$1.set(params.sessionKey, files);
29563
29811
  return files;
29564
29812
  }
29565
29813
 
@@ -29880,6 +30128,24 @@ function resolveCliBackendConfig(provider, cfg) {
29880
30128
  };
29881
30129
  }
29882
30130
 
30131
+ //#endregion
30132
+ //#region src/agents/model-alias-lines.ts
30133
+ function buildModelAliasLines(cfg) {
30134
+ const models = cfg?.agents?.defaults?.models ?? {};
30135
+ const entries = [];
30136
+ for (const [keyRaw, entryRaw] of Object.entries(models)) {
30137
+ const model = String(keyRaw ?? "").trim();
30138
+ if (!model) continue;
30139
+ const alias = String(entryRaw?.alias ?? "").trim();
30140
+ if (!alias) continue;
30141
+ entries.push({
30142
+ alias,
30143
+ model
30144
+ });
30145
+ }
30146
+ return entries.toSorted((a, b) => a.alias.localeCompare(b.alias)).map((entry) => `- ${entry.alias}: ${entry.model}`);
30147
+ }
30148
+
29883
30149
  //#endregion
29884
30150
  //#region src/agents/system-prompt-params.ts
29885
30151
  function buildSystemPromptParams(params) {
@@ -30572,11 +30838,11 @@ function collectText(value) {
30572
30838
  if (!value) return "";
30573
30839
  if (typeof value === "string") return value;
30574
30840
  if (Array.isArray(value)) return value.map((entry) => collectText(entry)).join("");
30575
- if (!isRecord$4(value)) return "";
30841
+ if (!isRecord$5(value)) return "";
30576
30842
  if (typeof value.text === "string") return value.text;
30577
30843
  if (typeof value.content === "string") return value.content;
30578
30844
  if (Array.isArray(value.content)) return value.content.map((entry) => collectText(entry)).join("");
30579
- if (isRecord$4(value.message)) return collectText(value.message);
30845
+ if (isRecord$5(value.message)) return collectText(value.message);
30580
30846
  return "";
30581
30847
  }
30582
30848
  function pickSessionId(parsed, backend) {
@@ -30600,9 +30866,9 @@ function parseCliJson(raw, backend) {
30600
30866
  } catch {
30601
30867
  return null;
30602
30868
  }
30603
- if (!isRecord$4(parsed)) return null;
30869
+ if (!isRecord$5(parsed)) return null;
30604
30870
  const sessionId = pickSessionId(parsed, backend);
30605
- const usage = isRecord$4(parsed.usage) ? toUsage(parsed.usage) : void 0;
30871
+ const usage = isRecord$5(parsed.usage) ? toUsage(parsed.usage) : void 0;
30606
30872
  return {
30607
30873
  text: (collectText(parsed.message) || collectText(parsed.content) || collectText(parsed.result) || collectText(parsed)).trim(),
30608
30874
  sessionId,
@@ -30622,11 +30888,11 @@ function parseCliJsonl(raw, backend) {
30622
30888
  } catch {
30623
30889
  continue;
30624
30890
  }
30625
- if (!isRecord$4(parsed)) continue;
30891
+ if (!isRecord$5(parsed)) continue;
30626
30892
  if (!sessionId) sessionId = pickSessionId(parsed, backend);
30627
30893
  if (!sessionId && typeof parsed.thread_id === "string") sessionId = parsed.thread_id.trim();
30628
- if (isRecord$4(parsed.usage)) usage = toUsage(parsed.usage) ?? usage;
30629
- const item = isRecord$4(parsed.item) ? parsed.item : null;
30894
+ if (isRecord$5(parsed.usage)) usage = toUsage(parsed.usage) ?? usage;
30895
+ const item = isRecord$5(parsed.item) ? parsed.item : null;
30630
30896
  if (item && typeof item.text === "string") {
30631
30897
  const type = typeof item.type === "string" ? item.type.toLowerCase() : "";
30632
30898
  if (!type || type.includes("message")) texts.push(item.text);
@@ -30809,7 +31075,7 @@ function resolveRunWorkspaceDir(params) {
30809
31075
 
30810
31076
  //#endregion
30811
31077
  //#region src/agents/cli-runner.ts
30812
- const log$17 = createSubsystemLogger("agent/claude-cli");
31078
+ const log$15 = createSubsystemLogger("agent/claude-cli");
30813
31079
  const CLI_ENV_AUTH_LOG_KEYS = [
30814
31080
  "AI_GATEWAY_API_KEY",
30815
31081
  "ANTHROPIC_API_KEY",
@@ -30859,7 +31125,7 @@ async function runCliAgent(params) {
30859
31125
  const redactedSessionId = redactRunIdentifier(params.sessionId);
30860
31126
  const redactedSessionKey = redactRunIdentifier(params.sessionKey);
30861
31127
  const redactedWorkspace = redactRunIdentifier(resolvedWorkspace);
30862
- if (workspaceResolution.usedFallback) log$17.warn(`[workspace-fallback] caller=runCliAgent reason=${workspaceResolution.fallbackReason} run=${params.runId} session=${redactedSessionId} sessionKey=${redactedSessionKey} agent=${workspaceResolution.agentId} workspace=${redactedWorkspace}`);
31128
+ if (workspaceResolution.usedFallback) log$15.warn(`[workspace-fallback] caller=runCliAgent reason=${workspaceResolution.fallbackReason} run=${params.runId} session=${redactedSessionId} sessionKey=${redactedSessionKey} agent=${workspaceResolution.agentId} workspace=${redactedWorkspace}`);
30863
31129
  const workspaceDir = resolvedWorkspace;
30864
31130
  const backendResolved = resolveCliBackendConfig(params.provider, params.config);
30865
31131
  if (!backendResolved) throw new Error(`Unknown CLI backend: ${params.provider}`);
@@ -30876,7 +31142,7 @@ async function runCliAgent(params) {
30876
31142
  sessionId: params.sessionId,
30877
31143
  warn: makeBootstrapWarn({
30878
31144
  sessionLabel,
30879
- warn: (message) => log$17.warn(message)
31145
+ warn: (message) => log$15.warn(message)
30880
31146
  })
30881
31147
  });
30882
31148
  const { defaultAgentId, sessionAgentId } = resolveSessionAgentIds({
@@ -30943,7 +31209,7 @@ async function runCliAgent(params) {
30943
31209
  const queueKey = backend.serialize ?? true ? backendResolved.id : `${backendResolved.id}:${params.runId}`;
30944
31210
  try {
30945
31211
  const output = await enqueueCliRun(queueKey, async () => {
30946
- log$17.info(`cli exec: provider=${params.provider} model=${normalizedModel} promptChars=${params.prompt.length}`);
31212
+ log$15.info(`cli exec: provider=${params.provider} model=${normalizedModel} promptChars=${params.prompt.length}`);
30947
31213
  const logOutputText = isTruthyEnvValue(process.env.FASED_CLAUDE_CLI_LOG_OUTPUT);
30948
31214
  const env = (() => {
30949
31215
  const next = sanitizeHostExecEnv({ baseEnv: process.env });
@@ -30982,8 +31248,8 @@ async function runCliAgent(params) {
30982
31248
  const promptIndex = logArgs.indexOf(argsPrompt);
30983
31249
  if (promptIndex >= 0) logArgs[promptIndex] = `<prompt:${argsPrompt.length} chars>`;
30984
31250
  }
30985
- log$17.info(`cli argv: ${backend.command} ${logArgs.join(" ")}`);
30986
- log$17.info(`cli env auth: ${buildCliEnvAuthLog(env)}`);
31251
+ log$15.info(`cli argv: ${backend.command} ${logArgs.join(" ")}`);
31252
+ log$15.info(`cli env auth: ${buildCliEnvAuthLog(env)}`);
30987
31253
  }
30988
31254
  const noOutputTimeoutMs = resolveCliNoOutputTimeoutMs({
30989
31255
  backend,
@@ -31013,17 +31279,17 @@ async function runCliAgent(params) {
31013
31279
  const stdout = result.stdout.trim();
31014
31280
  const stderr = result.stderr.trim();
31015
31281
  if (logOutputText) {
31016
- if (stdout) log$17.info(`cli stdout:\n${stdout}`);
31017
- if (stderr) log$17.info(`cli stderr:\n${stderr}`);
31282
+ if (stdout) log$15.info(`cli stdout:\n${stdout}`);
31283
+ if (stderr) log$15.info(`cli stderr:\n${stderr}`);
31018
31284
  }
31019
31285
  if (shouldLogVerbose()) {
31020
- if (stdout) log$17.debug(`cli stdout:\n${stdout}`);
31021
- if (stderr) log$17.debug(`cli stderr:\n${stderr}`);
31286
+ if (stdout) log$15.debug(`cli stdout:\n${stdout}`);
31287
+ if (stderr) log$15.debug(`cli stderr:\n${stderr}`);
31022
31288
  }
31023
31289
  if (result.exitCode !== 0 || result.reason !== "exit") {
31024
31290
  if (result.reason === "no-output-timeout" || result.noOutputTimedOut) {
31025
31291
  const timeoutReason = `CLI produced no output for ${Math.round(noOutputTimeoutMs / 1e3)}s and was terminated.`;
31026
- log$17.warn(`cli watchdog timeout: provider=${params.provider} model=${modelId} session=${cliSessionIdToSend ?? params.sessionId} noOutputTimeoutMs=${noOutputTimeoutMs} pid=${managedRun.pid ?? "unknown"}`);
31292
+ log$15.warn(`cli watchdog timeout: provider=${params.provider} model=${modelId} session=${cliSessionIdToSend ?? params.sessionId} noOutputTimeoutMs=${noOutputTimeoutMs} pid=${managedRun.pid ?? "unknown"}`);
31027
31293
  throw new FailoverError(timeoutReason, {
31028
31294
  reason: "timeout",
31029
31295
  provider: params.provider,
@@ -31207,11 +31473,11 @@ const DEFAULT_CATALOG_PATHS = [
31207
31473
  ];
31208
31474
  const ENV_CATALOG_PATHS = ["FASED_PLUGIN_CATALOG_PATHS", "FASED_MPM_CATALOG_PATHS"];
31209
31475
  function parseCatalogEntries(raw) {
31210
- if (Array.isArray(raw)) return raw.filter((entry) => isRecord$4(entry));
31211
- if (!isRecord$4(raw)) return [];
31476
+ if (Array.isArray(raw)) return raw.filter((entry) => isRecord$5(entry));
31477
+ if (!isRecord$5(raw)) return [];
31212
31478
  const list = raw.entries ?? raw.packages ?? raw.plugins;
31213
31479
  if (!Array.isArray(list)) return [];
31214
- return list.filter((entry) => isRecord$4(entry));
31480
+ return list.filter((entry) => isRecord$5(entry));
31215
31481
  }
31216
31482
  function splitEnvPaths(value) {
31217
31483
  const trimmed = value.trim();
@@ -31391,19 +31657,19 @@ function hasNonEmptyString(value) {
31391
31657
  return typeof value === "string" && value.trim().length > 0;
31392
31658
  }
31393
31659
  function recordHasKeys(value) {
31394
- return isRecord$4(value) && Object.keys(value).length > 0;
31660
+ return isRecord$5(value) && Object.keys(value).length > 0;
31395
31661
  }
31396
31662
  function accountsHaveKeys(value, keys) {
31397
- if (!isRecord$4(value)) return false;
31663
+ if (!isRecord$5(value)) return false;
31398
31664
  for (const account of Object.values(value)) {
31399
- if (!isRecord$4(account)) continue;
31665
+ if (!isRecord$5(account)) continue;
31400
31666
  for (const key of keys) if (hasNonEmptyString(account[key])) return true;
31401
31667
  }
31402
31668
  return false;
31403
31669
  }
31404
31670
  function resolveChannelConfig(cfg, channelId) {
31405
31671
  const entry = cfg.channels?.[channelId];
31406
- return isRecord$4(entry) ? entry : null;
31672
+ return isRecord$5(entry) ? entry : null;
31407
31673
  }
31408
31674
  const STRUCTURED_CHANNEL_CONFIG_SPECS = {
31409
31675
  telegram: {
@@ -31515,19 +31781,19 @@ function collectModelRefs(cfg) {
31515
31781
  if (!agent) return;
31516
31782
  const model = agent.model;
31517
31783
  if (typeof model === "string") pushModelRef(model);
31518
- else if (isRecord$4(model)) {
31784
+ else if (isRecord$5(model)) {
31519
31785
  pushModelRef(model.primary);
31520
31786
  const fallbacks = model.fallbacks;
31521
31787
  if (Array.isArray(fallbacks)) for (const entry of fallbacks) pushModelRef(entry);
31522
31788
  }
31523
31789
  const models = agent.models;
31524
- if (isRecord$4(models)) for (const key of Object.keys(models)) pushModelRef(key);
31790
+ if (isRecord$5(models)) for (const key of Object.keys(models)) pushModelRef(key);
31525
31791
  };
31526
31792
  const defaults = cfg.agents?.defaults;
31527
31793
  collectFromAgent(defaults);
31528
31794
  const list = cfg.agents?.list;
31529
31795
  if (Array.isArray(list)) {
31530
- for (const entry of list) if (isRecord$4(entry)) collectFromAgent(entry);
31796
+ for (const entry of list) if (isRecord$5(entry)) collectFromAgent(entry);
31531
31797
  }
31532
31798
  return refs;
31533
31799
  }
@@ -31541,7 +31807,7 @@ function isProviderConfigured(cfg, providerId) {
31541
31807
  const normalized = normalizeProviderId$1(providerId);
31542
31808
  const profiles = cfg.auth?.profiles;
31543
31809
  if (profiles && typeof profiles === "object") for (const profile of Object.values(profiles)) {
31544
- if (!isRecord$4(profile)) continue;
31810
+ if (!isRecord$5(profile)) continue;
31545
31811
  if (normalizeProviderId$1(String(profile.provider ?? "")) === normalized) return true;
31546
31812
  }
31547
31813
  const providerConfig = cfg.models?.providers;
@@ -33247,20 +33513,9 @@ async function handleGatewayPostJsonEndpoint(req, res, opts) {
33247
33513
  return { body };
33248
33514
  }
33249
33515
 
33250
- //#endregion
33251
- //#region src/plugins/logger.ts
33252
- function createPluginLoaderLogger(logger) {
33253
- return {
33254
- info: (msg) => logger.info(msg),
33255
- warn: (msg) => logger.warn(msg),
33256
- error: (msg) => logger.error(msg),
33257
- debug: (msg) => logger.debug?.(msg)
33258
- };
33259
- }
33260
-
33261
33516
  //#endregion
33262
33517
  //#region src/plugins/tools.ts
33263
- const log$16 = createSubsystemLogger("plugins");
33518
+ const log$14 = createSubsystemLogger("plugins");
33264
33519
  const pluginToolMeta = /* @__PURE__ */ new WeakMap();
33265
33520
  function getPluginToolMeta(tool) {
33266
33521
  return pluginToolMeta.get(tool);
@@ -33282,7 +33537,7 @@ function resolvePluginTools(params) {
33282
33537
  const registry = loadFasedAgentPlugins({
33283
33538
  config: effectiveConfig,
33284
33539
  workspaceDir: params.context.workspaceDir,
33285
- logger: createPluginLoaderLogger(log$16)
33540
+ logger: createPluginLoaderLogger(log$14)
33286
33541
  });
33287
33542
  const tools = [];
33288
33543
  const existing = params.existingToolNames ?? /* @__PURE__ */ new Set();
@@ -33295,7 +33550,7 @@ function resolvePluginTools(params) {
33295
33550
  if (existingNormalized.has(pluginIdKey)) {
33296
33551
  const message = `plugin id conflicts with core tool name (${entry.pluginId})`;
33297
33552
  if (!params.suppressNameConflicts) {
33298
- log$16.error(message);
33553
+ log$14.error(message);
33299
33554
  registry.diagnostics.push({
33300
33555
  level: "error",
33301
33556
  pluginId: entry.pluginId,
@@ -33310,7 +33565,7 @@ function resolvePluginTools(params) {
33310
33565
  try {
33311
33566
  resolved = entry.factory(params.context);
33312
33567
  } catch (err) {
33313
- log$16.error(`plugin tool failed (${entry.pluginId}): ${String(err)}`);
33568
+ log$14.error(`plugin tool failed (${entry.pluginId}): ${String(err)}`);
33314
33569
  continue;
33315
33570
  }
33316
33571
  if (!resolved) continue;
@@ -33326,7 +33581,7 @@ function resolvePluginTools(params) {
33326
33581
  if (nameSet.has(tool.name) || existing.has(tool.name)) {
33327
33582
  const message = `plugin tool name conflict (${entry.pluginId}): ${tool.name}`;
33328
33583
  if (!params.suppressNameConflicts) {
33329
- log$16.error(message);
33584
+ log$14.error(message);
33330
33585
  registry.diagnostics.push({
33331
33586
  level: "error",
33332
33587
  pluginId: entry.pluginId,
@@ -33708,7 +33963,7 @@ function isModuleNotFoundError(err) {
33708
33963
  }
33709
33964
  async function loadPwAiModule(mode) {
33710
33965
  try {
33711
- return await import("./pw-ai-B0domrii.js");
33966
+ return await import("./pw-ai-H7UgunQQ.js");
33712
33967
  } catch (err) {
33713
33968
  if (mode === "soft") return null;
33714
33969
  if (isModuleNotFoundError(err)) return null;
@@ -34102,11 +34357,11 @@ function createProfileContext(opts, profile) {
34102
34357
  const userDataDir = resolveFasedAgentUserDataDir(profile.name);
34103
34358
  const profileState = getProfileState();
34104
34359
  if (await isHttpReachable(300) && !profileState.running) try {
34105
- await (await import("./pw-ai-B0domrii.js")).closePlaywrightBrowserConnection();
34360
+ await (await import("./pw-ai-H7UgunQQ.js")).closePlaywrightBrowserConnection();
34106
34361
  } catch {}
34107
34362
  if (profileState.running) await stopRunningBrowser();
34108
34363
  try {
34109
- await (await import("./pw-ai-B0domrii.js")).closePlaywrightBrowserConnection();
34364
+ await (await import("./pw-ai-H7UgunQQ.js")).closePlaywrightBrowserConnection();
34110
34365
  } catch {}
34111
34366
  if (!fs.existsSync(userDataDir)) return {
34112
34367
  moved: false,
@@ -38372,7 +38627,7 @@ function coerceTrimmedString(raw) {
38372
38627
  }
38373
38628
  function coerceFailureAlert(raw) {
38374
38629
  if (raw === false) return false;
38375
- if (!isRecord$4(raw)) return;
38630
+ if (!isRecord$5(raw)) return;
38376
38631
  const next = {};
38377
38632
  const after = coercePositiveInteger(raw.after);
38378
38633
  if (after !== void 0) next.after = after;
@@ -38395,7 +38650,7 @@ function coerceStringList(raw) {
38395
38650
  }
38396
38651
  function coerceWorkflowSubsteps(raw) {
38397
38652
  if (!Array.isArray(raw)) return;
38398
- const substeps = raw.filter((entry) => isRecord$4(entry)).map((entry) => {
38653
+ const substeps = raw.filter((entry) => isRecord$5(entry)).map((entry) => {
38399
38654
  const id = coerceEnum(entry.id, [
38400
38655
  "plan-analysis",
38401
38656
  "execute-tool-or-model",
@@ -38419,11 +38674,11 @@ function coerceWorkflowSubsteps(raw) {
38419
38674
  return substeps.length > 0 ? substeps : void 0;
38420
38675
  }
38421
38676
  function coerceWorkflowGraph(raw) {
38422
- if (!isRecord$4(raw)) return;
38677
+ if (!isRecord$5(raw)) return;
38423
38678
  const entryNodeId = coerceTrimmedString(raw.entryNodeId);
38424
38679
  const terminalNodeIds = coerceStringList(raw.terminalNodeIds);
38425
38680
  if (!entryNodeId || !terminalNodeIds) return;
38426
- const nodes = Array.isArray(raw.nodes) ? raw.nodes.filter((entry) => isRecord$4(entry)).map((entry) => {
38681
+ const nodes = Array.isArray(raw.nodes) ? raw.nodes.filter((entry) => isRecord$5(entry)).map((entry) => {
38427
38682
  const id = coerceTrimmedString(entry.id);
38428
38683
  const label = coerceTrimmedString(entry.label);
38429
38684
  const kind = coerceEnum(entry.kind, [
@@ -38509,15 +38764,15 @@ function coerceExecutionPolicy(policy) {
38509
38764
  const allowedSkills = Array.from(new Set(policy.allowedSkills.filter((entry) => typeof entry === "string").map((entry) => entry.trim()).filter(Boolean)));
38510
38765
  if (allowedSkills.length > 0) next.allowedSkills = allowedSkills;
38511
38766
  }
38512
- if (isRecord$4(policy.skillAction)) {
38767
+ if (isRecord$5(policy.skillAction)) {
38513
38768
  const toolName = typeof policy.skillAction.toolName === "string" ? policy.skillAction.toolName.trim() : "";
38514
38769
  if (toolName) {
38515
38770
  const skillAction = { toolName };
38516
- if (isRecord$4(policy.skillAction.input)) skillAction.input = { ...policy.skillAction.input };
38771
+ if (isRecord$5(policy.skillAction.input)) skillAction.input = { ...policy.skillAction.input };
38517
38772
  next.skillAction = skillAction;
38518
38773
  }
38519
38774
  }
38520
- if (isRecord$4(policy.modelPolicy)) {
38775
+ if (isRecord$5(policy.modelPolicy)) {
38521
38776
  const modelPolicy = {};
38522
38777
  const mode = coerceEnum(policy.modelPolicy.mode, [
38523
38778
  "agent-default",
@@ -38544,7 +38799,7 @@ function coerceExecutionPolicy(policy) {
38544
38799
  }
38545
38800
  if (Object.keys(modelPolicy).length > 0) next.modelPolicy = modelPolicy;
38546
38801
  }
38547
- if (isRecord$4(policy.coordination)) {
38802
+ if (isRecord$5(policy.coordination)) {
38548
38803
  const coordination = {};
38549
38804
  const mode = coerceEnum(policy.coordination.mode, [
38550
38805
  "none",
@@ -38565,7 +38820,7 @@ function coerceExecutionPolicy(policy) {
38565
38820
  if (typeof policy.coordination.escalateWhenAdvisorsConflict === "boolean") coordination.escalateWhenAdvisorsConflict = policy.coordination.escalateWhenAdvisorsConflict;
38566
38821
  if (Object.keys(coordination).length > 0) next.coordination = coordination;
38567
38822
  }
38568
- if (isRecord$4(policy.budget)) {
38823
+ if (isRecord$5(policy.budget)) {
38569
38824
  const budget = {};
38570
38825
  for (const field of [
38571
38826
  "maxTokensPerRun",
@@ -38577,7 +38832,7 @@ function coerceExecutionPolicy(policy) {
38577
38832
  }
38578
38833
  if (Object.keys(budget).length > 0) next.budget = budget;
38579
38834
  }
38580
- if (isRecord$4(policy.stop)) {
38835
+ if (isRecord$5(policy.stop)) {
38581
38836
  const stop = {};
38582
38837
  if (typeof policy.stop.onSuccess === "boolean") stop.onSuccess = policy.stop.onSuccess;
38583
38838
  if (Array.isArray(policy.stop.outputIncludes)) {
@@ -38590,7 +38845,7 @@ function coerceExecutionPolicy(policy) {
38590
38845
  if (maxTotalRuns !== void 0) stop.maxTotalRuns = maxTotalRuns;
38591
38846
  if (Object.keys(stop).length > 0) next.stop = stop;
38592
38847
  }
38593
- if (isRecord$4(policy.evaluator)) {
38848
+ if (isRecord$5(policy.evaluator)) {
38594
38849
  const evaluator = {};
38595
38850
  if (typeof policy.evaluator.escalateOnSignal === "boolean") evaluator.escalateOnSignal = policy.evaluator.escalateOnSignal;
38596
38851
  if (Array.isArray(policy.evaluator.signalIncludes)) {
@@ -38601,7 +38856,7 @@ function coerceExecutionPolicy(policy) {
38601
38856
  if (maxEscalations !== void 0) evaluator.maxEscalations = maxEscalations;
38602
38857
  if (Object.keys(evaluator).length > 0) next.evaluator = evaluator;
38603
38858
  }
38604
- if (isRecord$4(policy.repairPolicy)) {
38859
+ if (isRecord$5(policy.repairPolicy)) {
38605
38860
  const repairPolicy = {};
38606
38861
  if (typeof policy.repairPolicy.autoRetryReplacement === "boolean") repairPolicy.autoRetryReplacement = policy.repairPolicy.autoRetryReplacement;
38607
38862
  if (typeof policy.repairPolicy.autoStopOptionalSources === "boolean") repairPolicy.autoStopOptionalSources = policy.repairPolicy.autoStopOptionalSources;
@@ -38610,7 +38865,7 @@ function coerceExecutionPolicy(policy) {
38610
38865
  if (typeof policy.repairPolicy.requireApprovalForPrimarySource === "boolean") repairPolicy.requireApprovalForPrimarySource = policy.repairPolicy.requireApprovalForPrimarySource;
38611
38866
  if (Object.keys(repairPolicy).length > 0) next.repairPolicy = repairPolicy;
38612
38867
  }
38613
- if (isRecord$4(policy.planner)) {
38868
+ if (isRecord$5(policy.planner)) {
38614
38869
  const strategy = coerceEnum(policy.planner.strategy, [
38615
38870
  "agent-default",
38616
38871
  "cheap-model",
@@ -38636,7 +38891,7 @@ function coerceExecutionPolicy(policy) {
38636
38891
  if (signals.length > 0) planner.signals = signals;
38637
38892
  }
38638
38893
  if (Array.isArray(policy.planner.steps)) {
38639
- const steps = policy.planner.steps.filter((entry) => isRecord$4(entry)).map((entry) => {
38894
+ const steps = policy.planner.steps.filter((entry) => isRecord$5(entry)).map((entry) => {
38640
38895
  const id = coerceEnum(entry.id, [
38641
38896
  "collect",
38642
38897
  "analyze",
@@ -38670,8 +38925,8 @@ function coerceExecutionPolicy(policy) {
38670
38925
  return Object.keys(next).length > 0 ? next : void 0;
38671
38926
  }
38672
38927
  function unwrapJob(raw) {
38673
- if (isRecord$4(raw.data)) return raw.data;
38674
- if (isRecord$4(raw.job)) return raw.job;
38928
+ if (isRecord$5(raw.data)) return raw.data;
38929
+ if (isRecord$5(raw.job)) return raw.job;
38675
38930
  return raw;
38676
38931
  }
38677
38932
  function normalizeSessionTarget(raw) {
@@ -38718,7 +38973,7 @@ function stripLegacyTopLevelFields(next) {
38718
38973
  delete next.provider;
38719
38974
  }
38720
38975
  function normalizeCronJobInput(raw, options = DEFAULT_OPTIONS$1) {
38721
- if (!isRecord$4(raw)) return null;
38976
+ if (!isRecord$5(raw)) return null;
38722
38977
  const base = unwrapJob(raw);
38723
38978
  const next = { ...base };
38724
38979
  if ("agentId" in base) {
@@ -38758,8 +39013,8 @@ function normalizeCronJobInput(raw, options = DEFAULT_OPTIONS$1) {
38758
39013
  if (normalized) next.wakeMode = normalized;
38759
39014
  else delete next.wakeMode;
38760
39015
  }
38761
- if (isRecord$4(base.schedule)) next.schedule = coerceSchedule(base.schedule);
38762
- if (!("payload" in next) || !isRecord$4(next.payload)) {
39016
+ if (isRecord$5(base.schedule)) next.schedule = coerceSchedule(base.schedule);
39017
+ if (!("payload" in next) || !isRecord$5(next.payload)) {
38763
39018
  const message = typeof next.message === "string" ? next.message.trim() : "";
38764
39019
  const text = typeof next.text === "string" ? next.text.trim() : "";
38765
39020
  if (message) next.payload = {
@@ -38771,21 +39026,21 @@ function normalizeCronJobInput(raw, options = DEFAULT_OPTIONS$1) {
38771
39026
  text
38772
39027
  };
38773
39028
  }
38774
- if (isRecord$4(base.payload)) next.payload = coercePayload(base.payload);
38775
- if (isRecord$4(base.delivery)) next.delivery = coerceDelivery(base.delivery);
39029
+ if (isRecord$5(base.payload)) next.payload = coercePayload(base.payload);
39030
+ if (isRecord$5(base.delivery)) next.delivery = coerceDelivery(base.delivery);
38776
39031
  if ("failureAlert" in base) {
38777
39032
  const failureAlert = coerceFailureAlert(base.failureAlert);
38778
39033
  if (failureAlert !== void 0) next.failureAlert = failureAlert;
38779
39034
  else delete next.failureAlert;
38780
39035
  }
38781
39036
  if ("executionPolicy" in base) if (base.executionPolicy === null) next.executionPolicy = null;
38782
- else if (isRecord$4(base.executionPolicy)) {
39037
+ else if (isRecord$5(base.executionPolicy)) {
38783
39038
  const executionPolicy = coerceExecutionPolicy(base.executionPolicy);
38784
39039
  if (executionPolicy) next.executionPolicy = executionPolicy;
38785
39040
  else delete next.executionPolicy;
38786
39041
  } else delete next.executionPolicy;
38787
39042
  if ("isolation" in next) delete next.isolation;
38788
- const payload = isRecord$4(next.payload) ? next.payload : null;
39043
+ const payload = isRecord$5(next.payload) ? next.payload : null;
38789
39044
  if (payload && payload.kind === "agentTurn") {
38790
39045
  copyTopLevelAgentTurnFields(next, payload);
38791
39046
  copyTopLevelLegacyDeliveryFields(next, payload);
@@ -38794,7 +39049,7 @@ function normalizeCronJobInput(raw, options = DEFAULT_OPTIONS$1) {
38794
39049
  if (options.applyDefaults) {
38795
39050
  if (!next.wakeMode) next.wakeMode = "now";
38796
39051
  if (typeof next.enabled !== "boolean") next.enabled = true;
38797
- if ((typeof next.name !== "string" || !next.name.trim()) && isRecord$4(next.schedule) && isRecord$4(next.payload)) next.name = inferLegacyName({
39052
+ if ((typeof next.name !== "string" || !next.name.trim()) && isRecord$5(next.schedule) && isRecord$5(next.payload)) next.name = inferLegacyName({
38798
39053
  schedule: next.schedule,
38799
39054
  payload: next.payload
38800
39055
  });
@@ -38802,13 +39057,13 @@ function normalizeCronJobInput(raw, options = DEFAULT_OPTIONS$1) {
38802
39057
  const trimmed = next.name.trim();
38803
39058
  if (trimmed) next.name = trimmed;
38804
39059
  }
38805
- if (!next.sessionTarget && isRecord$4(next.payload)) {
39060
+ if (!next.sessionTarget && isRecord$5(next.payload)) {
38806
39061
  const kind = typeof next.payload.kind === "string" ? next.payload.kind : "";
38807
39062
  if (kind === "systemEvent") next.sessionTarget = "main";
38808
39063
  if (kind === "agentTurn") next.sessionTarget = "isolated";
38809
39064
  }
38810
- if ("schedule" in next && isRecord$4(next.schedule) && next.schedule.kind === "at" && !("deleteAfterRun" in next)) next.deleteAfterRun = true;
38811
- if ("schedule" in next && isRecord$4(next.schedule) && next.schedule.kind === "cron") {
39065
+ if ("schedule" in next && isRecord$5(next.schedule) && next.schedule.kind === "at" && !("deleteAfterRun" in next)) next.deleteAfterRun = true;
39066
+ if ("schedule" in next && isRecord$5(next.schedule) && next.schedule.kind === "cron") {
38812
39067
  const schedule = next.schedule;
38813
39068
  const explicit = normalizeCronStaggerMs(schedule.staggerMs);
38814
39069
  if (explicit !== void 0) schedule.staggerMs = explicit;
@@ -38817,7 +39072,7 @@ function normalizeCronJobInput(raw, options = DEFAULT_OPTIONS$1) {
38817
39072
  if (defaultStaggerMs !== void 0) schedule.staggerMs = defaultStaggerMs;
38818
39073
  }
38819
39074
  }
38820
- const payload = isRecord$4(next.payload) ? next.payload : null;
39075
+ const payload = isRecord$5(next.payload) ? next.payload : null;
38821
39076
  const payloadKind = payload && typeof payload.kind === "string" ? payload.kind : "";
38822
39077
  const sessionTarget = typeof next.sessionTarget === "string" ? next.sessionTarget : "";
38823
39078
  const isIsolatedAgentTurn = sessionTarget === "isolated" || sessionTarget === "" && payloadKind === "agentTurn";
@@ -39096,7 +39351,7 @@ Use jobId as the canonical identifier; id is accepted for compatibility. Use con
39096
39351
  }
39097
39352
  if (opts?.agentSessionKey && job && typeof job === "object" && "payload" in job && job.payload?.kind === "agentTurn") {
39098
39353
  const deliveryValue = job.delivery;
39099
- const delivery = isRecord$4(deliveryValue) ? deliveryValue : void 0;
39354
+ const delivery = isRecord$5(deliveryValue) ? deliveryValue : void 0;
39100
39355
  const mode = (typeof delivery?.mode === "string" ? delivery.mode : "").trim().toLowerCase();
39101
39356
  if (mode === "webhook") {
39102
39357
  const webhookUrl = normalizeHttpWebhookUrl(delivery?.to);
@@ -39774,7 +40029,7 @@ function collectEnabledInsecureOrDangerousFlags(cfg) {
39774
40029
 
39775
40030
  //#endregion
39776
40031
  //#region src/agents/tools/gateway-tool.ts
39777
- const log$15 = createSubsystemLogger("gateway-tool");
40032
+ const log$13 = createSubsystemLogger("gateway-tool");
39778
40033
  const DEFAULT_UPDATE_TIMEOUT_MS = 20 * 6e4;
39779
40034
  function resolveBaseHashFromSnapshot(snapshot) {
39780
40035
  if (!snapshot || typeof snapshot !== "object") return;
@@ -39804,19 +40059,19 @@ const ALLOWED_GATEWAY_CONFIG_PATHS = [
39804
40059
  "channels.*.*.*.*.requireMention",
39805
40060
  "channels.*.*.*.*.*.requireMention"
39806
40061
  ];
39807
- function isRecord$2(value) {
40062
+ function isRecord$3(value) {
39808
40063
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
39809
40064
  }
39810
40065
  function getSnapshotConfig(snapshot) {
39811
- if (!isRecord$2(snapshot)) throw new Error("config.get response is not an object.");
40066
+ if (!isRecord$3(snapshot)) throw new Error("config.get response is not an object.");
39812
40067
  const config = snapshot.config;
39813
- if (!isRecord$2(config)) throw new Error("config.get response is missing a config object.");
40068
+ if (!isRecord$3(config)) throw new Error("config.get response is missing a config object.");
39814
40069
  return config;
39815
40070
  }
39816
40071
  function parseGatewayConfigMutationRaw(raw, action) {
39817
40072
  const parsed = parseConfigJson5(raw);
39818
40073
  if (!parsed.ok) throw new Error(parsed.error);
39819
- if (!isRecord$2(parsed.parsed)) throw new Error(`${action} raw must be an object.`);
40074
+ if (!isRecord$3(parsed.parsed)) throw new Error(`${action} raw must be an object.`);
39820
40075
  return parsed.parsed;
39821
40076
  }
39822
40077
  function normalizeGatewayConfigPath(path) {
@@ -39830,7 +40085,7 @@ function readKeyedArrayEntries(list) {
39830
40085
  let hasUnkeyedEntries = false;
39831
40086
  const entries = /* @__PURE__ */ new Map();
39832
40087
  for (const entry of list) {
39833
- if (!isRecord$2(entry) || typeof entry.id !== "string" || entry.id.length === 0) {
40088
+ if (!isRecord$3(entry) || typeof entry.id !== "string" || entry.id.length === 0) {
39834
40089
  hasUnkeyedEntries = true;
39835
40090
  continue;
39836
40091
  }
@@ -39861,7 +40116,7 @@ function collectConfigLeafPaths(value, basePath, out) {
39861
40116
  if (canonicalPath) out.add(canonicalPath);
39862
40117
  return;
39863
40118
  }
39864
- if (!isRecord$2(value)) {
40119
+ if (!isRecord$3(value)) {
39865
40120
  if (canonicalPath) out.add(canonicalPath);
39866
40121
  return;
39867
40122
  }
@@ -39894,7 +40149,7 @@ function collectChangedConfigPaths(currentValue, nextValue, basePath = "", out =
39894
40149
  for (const id of ids) collectChangedConfigPaths(currentEntries.entries.get(id), nextEntries.entries.get(id), `${basePath}[]`, out);
39895
40150
  return out;
39896
40151
  }
39897
- if (isRecord$2(currentValue) && isRecord$2(nextValue)) {
40152
+ if (isRecord$3(currentValue) && isRecord$3(nextValue)) {
39898
40153
  const keys = new Set([...Object.keys(currentValue), ...Object.keys(nextValue)]);
39899
40154
  for (const key of keys) collectChangedConfigPaths(currentValue[key], nextValue[key], basePath ? `${basePath}.${key}` : key, out);
39900
40155
  return out;
@@ -39981,7 +40236,7 @@ function createGatewayTool(opts) {
39981
40236
  try {
39982
40237
  await writeRestartSentinel(payload);
39983
40238
  } catch {}
39984
- log$15.info(`gateway tool: restart requested (delayMs=${delayMs ?? "default"}, reason=${reason ?? "none"})`);
40239
+ log$13.info(`gateway tool: restart requested (delayMs=${delayMs ?? "default"}, reason=${reason ?? "none"})`);
39985
40240
  return jsonResult(scheduleGatewaySigusr1Restart({
39986
40241
  delayMs,
39987
40242
  reason
@@ -40135,11 +40390,11 @@ async function minimaxUnderstandImage(params) {
40135
40390
  throw new Error(`MiniMax VLM request failed (${res.status} ${res.statusText}).${trace}${body ? ` Body: ${body.slice(0, 400)}` : ""}`);
40136
40391
  }
40137
40392
  const json = await res.json().catch(() => null);
40138
- if (!isRecord$4(json)) {
40393
+ if (!isRecord$5(json)) {
40139
40394
  const trace = traceId ? ` Trace-Id: ${traceId}` : "";
40140
40395
  throw new Error(`MiniMax VLM response was not JSON.${trace}`);
40141
40396
  }
40142
- const baseResp = isRecord$4(json.base_resp) ? json.base_resp : {};
40397
+ const baseResp = isRecord$5(json.base_resp) ? json.base_resp : {};
40143
40398
  const code = typeof baseResp.status_code === "number" ? baseResp.status_code : -1;
40144
40399
  if (code !== 0) {
40145
40400
  const msg = (baseResp.status_msg ?? "").trim();
@@ -49622,7 +49877,7 @@ function collectUsageCandidates(root) {
49622
49877
  const next = queue.shift();
49623
49878
  scanned += 1;
49624
49879
  const { value, depth } = next;
49625
- if (isRecord$4(value)) {
49880
+ if (isRecord$5(value)) {
49626
49881
  if (seen.has(value)) continue;
49627
49882
  seen.add(value);
49628
49883
  const score = scoreUsageRecord(value);
@@ -49632,7 +49887,7 @@ function collectUsageCandidates(root) {
49632
49887
  depth
49633
49888
  });
49634
49889
  if (depth < MAX_SCAN_DEPTH) {
49635
- for (const nested of Object.values(value)) if (isRecord$4(nested) || Array.isArray(nested)) queue.push({
49890
+ for (const nested of Object.values(value)) if (isRecord$5(nested) || Array.isArray(nested)) queue.push({
49636
49891
  value: nested,
49637
49892
  depth: depth + 1
49638
49893
  });
@@ -49640,7 +49895,7 @@ function collectUsageCandidates(root) {
49640
49895
  continue;
49641
49896
  }
49642
49897
  if (Array.isArray(value) && depth < MAX_SCAN_DEPTH) {
49643
- for (const nested of value) if (isRecord$4(nested) || Array.isArray(nested)) queue.push({
49898
+ for (const nested of value) if (isRecord$5(nested) || Array.isArray(nested)) queue.push({
49644
49899
  value: nested,
49645
49900
  depth: depth + 1
49646
49901
  });
@@ -49684,20 +49939,20 @@ async function fetchMinimaxUsage(apiKey, timeoutMs, fetchFn) {
49684
49939
  status: res.status
49685
49940
  });
49686
49941
  const data = await res.json().catch(() => null);
49687
- if (!isRecord$4(data)) return {
49942
+ if (!isRecord$5(data)) return {
49688
49943
  provider: "minimax",
49689
49944
  displayName: PROVIDER_LABELS.minimax,
49690
49945
  windows: [],
49691
49946
  error: "Invalid JSON"
49692
49947
  };
49693
- const baseResp = isRecord$4(data.base_resp) ? data.base_resp : void 0;
49948
+ const baseResp = isRecord$5(data.base_resp) ? data.base_resp : void 0;
49694
49949
  if (baseResp && typeof baseResp.status_code === "number" && baseResp.status_code !== 0) return {
49695
49950
  provider: "minimax",
49696
49951
  displayName: PROVIDER_LABELS.minimax,
49697
49952
  windows: [],
49698
49953
  error: baseResp.status_msg?.trim() || "API error"
49699
49954
  };
49700
- const payload = isRecord$4(data.data) ? data.data : data;
49955
+ const payload = isRecord$5(data.data) ? data.data : data;
49701
49956
  const candidates = collectUsageCandidates(payload);
49702
49957
  let usageRecord = payload;
49703
49958
  let usedPercent = null;
@@ -50762,7 +51017,7 @@ async function resolveAnnounceTarget(params) {
50762
51017
 
50763
51018
  //#endregion
50764
51019
  //#region src/agents/tools/sessions-send-tool.a2a.ts
50765
- const log$14 = createSubsystemLogger("agents/sessions-send");
51020
+ const log$12 = createSubsystemLogger("agents/sessions-send");
50766
51021
  const defaultDeps$1 = { callGateway };
50767
51022
  let deps$1 = defaultDeps$1;
50768
51023
  async function runSessionsSendA2AFlow(params) {
@@ -50856,7 +51111,7 @@ async function runSessionsSendA2AFlow(params) {
50856
51111
  timeoutMs: 1e4
50857
51112
  });
50858
51113
  } catch (err) {
50859
- log$14.warn("sessions_send announce delivery failed", {
51114
+ log$12.warn("sessions_send announce delivery failed", {
50860
51115
  runId: runContextId,
50861
51116
  channel: announceTarget.channel,
50862
51117
  to: announceTarget.to,
@@ -50864,7 +51119,7 @@ async function runSessionsSendA2AFlow(params) {
50864
51119
  });
50865
51120
  }
50866
51121
  } catch (err) {
50867
- log$14.warn("sessions_send announce flow failed", {
51122
+ log$12.warn("sessions_send announce flow failed", {
50868
51123
  runId: runContextId,
50869
51124
  error: formatErrorMessage(err)
50870
51125
  });
@@ -51293,7 +51548,7 @@ function normalizeChannelId(value) {
51293
51548
  function normalizeOptionalString$2(value) {
51294
51549
  return typeof value === "string" && value.trim() ? value.trim() : void 0;
51295
51550
  }
51296
- function normalizeBoolean$1(value) {
51551
+ function normalizeBoolean(value) {
51297
51552
  if (typeof value !== "boolean") return;
51298
51553
  return value;
51299
51554
  }
@@ -51329,13 +51584,13 @@ function resolveThreadBindingSpawnPolicy(params) {
51329
51584
  channel,
51330
51585
  accountId
51331
51586
  });
51332
- const enabled = normalizeBoolean$1(account?.enabled) ?? normalizeBoolean$1(root?.enabled) ?? normalizeBoolean$1(params.cfg.session?.threadBindings?.enabled) ?? true;
51587
+ const enabled = normalizeBoolean(account?.enabled) ?? normalizeBoolean(root?.enabled) ?? normalizeBoolean(params.cfg.session?.threadBindings?.enabled) ?? true;
51333
51588
  const spawnFlagKey = resolveSpawnFlagKey(params.kind);
51334
51589
  return {
51335
51590
  channel,
51336
51591
  accountId,
51337
51592
  enabled,
51338
- spawnEnabled: normalizeBoolean$1(account?.[spawnFlagKey]) ?? normalizeBoolean$1(root?.[spawnFlagKey]) ?? channel !== DISCORD_THREAD_BINDING_CHANNEL
51593
+ spawnEnabled: normalizeBoolean(account?.[spawnFlagKey]) ?? normalizeBoolean(root?.[spawnFlagKey]) ?? channel !== DISCORD_THREAD_BINDING_CHANNEL
51339
51594
  };
51340
51595
  }
51341
51596
  function stripKnownTargetPrefix(value) {
@@ -60231,14 +60486,14 @@ const FASED_CLI_ENV_VALUE = "1";
60231
60486
 
60232
60487
  //#endregion
60233
60488
  //#region src/agents/sandbox/registry.ts
60234
- function isRecord$1(value) {
60489
+ function isRecord$2(value) {
60235
60490
  return Boolean(value) && typeof value === "object";
60236
60491
  }
60237
60492
  function isRegistryEntry(value) {
60238
- return isRecord$1(value) && typeof value.containerName === "string";
60493
+ return isRecord$2(value) && typeof value.containerName === "string";
60239
60494
  }
60240
60495
  function isRegistryFile(value) {
60241
- if (!isRecord$1(value)) return false;
60496
+ if (!isRecord$2(value)) return false;
60242
60497
  const maybeEntries = value.entries;
60243
60498
  return Array.isArray(maybeEntries) && maybeEntries.every(isRegistryEntry);
60244
60499
  }
@@ -60669,7 +60924,7 @@ function execDockerRaw(args, opts) {
60669
60924
  else stdin.end();
60670
60925
  });
60671
60926
  }
60672
- const log$13 = createSubsystemLogger("docker");
60927
+ const log$11 = createSubsystemLogger("docker");
60673
60928
  const HOT_CONTAINER_WINDOW_MS = 300 * 1e3;
60674
60929
  async function execDocker(args, opts) {
60675
60930
  const result = await execDockerRaw(args, opts);
@@ -60797,8 +61052,8 @@ function buildSandboxCreateArgs(params) {
60797
61052
  if (params.cfg.network) args.push("--network", params.cfg.network);
60798
61053
  if (params.cfg.user) args.push("--user", params.cfg.user);
60799
61054
  const envSanitization = sanitizeEnvVars(params.cfg.env ?? {}, params.envSanitizationOptions);
60800
- if (envSanitization.blocked.length > 0) log$13.warn(`Blocked sensitive environment variables: ${envSanitization.blocked.join(", ")}`);
60801
- if (envSanitization.warnings.length > 0) log$13.warn(`Suspicious environment variables: ${envSanitization.warnings.join(", ")}`);
61055
+ if (envSanitization.blocked.length > 0) log$11.warn(`Blocked sensitive environment variables: ${envSanitization.blocked.join(", ")}`);
61056
+ if (envSanitization.warnings.length > 0) log$11.warn(`Suspicious environment variables: ${envSanitization.warnings.join(", ")}`);
60802
61057
  for (const [key, value] of Object.entries(envSanitization.allowed)) args.push("--env", `${key}=${value}`);
60803
61058
  if (!Object.hasOwn(envSanitization.allowed, "FASED_CLI")) args.push("--env", `FASED_CLI=${FASED_CLI_ENV_VALUE}`);
60804
61059
  for (const cap of params.cfg.capDrop) args.push("--cap-drop", cap);
@@ -61850,7 +62105,7 @@ function stableStringify$1(value) {
61850
62105
 
61851
62106
  //#endregion
61852
62107
  //#region src/agents/pi-embedded-helpers/errors.ts
61853
- const log$12 = createSubsystemLogger("errors");
62108
+ const log$10 = createSubsystemLogger("errors");
61854
62109
  function formatBillingErrorMessage(provider, model) {
61855
62110
  const providerName = provider?.trim();
61856
62111
  const modelName = model?.trim();
@@ -62145,7 +62400,7 @@ function formatAssistantErrorText(msg, opts) {
62145
62400
  if (isTimeoutErrorMessage(raw)) return "LLM request timed out.";
62146
62401
  if (isBillingErrorMessage(raw)) return formatBillingErrorMessage(opts?.provider, opts?.model ?? msg.model);
62147
62402
  if (isLikelyHttpErrorText(raw) || isRawApiErrorPayload(raw)) return formatRawAssistantErrorForUi(raw);
62148
- if (raw.length > 600) log$12.warn(`Long error truncated: ${raw.slice(0, 200)}`);
62403
+ if (raw.length > 600) log$10.warn(`Long error truncated: ${raw.slice(0, 200)}`);
62149
62404
  return raw.length > 600 ? `${raw.slice(0, 600)}…` : raw;
62150
62405
  }
62151
62406
  function sanitizeUserFacingText(text, opts) {
@@ -68910,19 +69165,19 @@ function toAcpRuntimeErrorText(params) {
68910
69165
 
68911
69166
  //#endregion
68912
69167
  //#region src/auto-reply/reply/commands-acp/context.ts
68913
- function normalizeString$1(value) {
69168
+ function normalizeString(value) {
68914
69169
  if (typeof value === "string") return value.trim();
68915
69170
  if (typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") return `${value}`.trim();
68916
69171
  return "";
68917
69172
  }
68918
69173
  function resolveAcpCommandChannel(params) {
68919
- return normalizeString$1(params.ctx.OriginatingChannel ?? params.command.channel ?? params.ctx.Surface ?? params.ctx.Provider).toLowerCase();
69174
+ return normalizeString(params.ctx.OriginatingChannel ?? params.command.channel ?? params.ctx.Surface ?? params.ctx.Provider).toLowerCase();
68920
69175
  }
68921
69176
  function resolveAcpCommandAccountId(params) {
68922
- return normalizeString$1(params.ctx.AccountId) || "default";
69177
+ return normalizeString(params.ctx.AccountId) || "default";
68923
69178
  }
68924
69179
  function resolveAcpCommandThreadId(params) {
68925
- return (params.ctx.MessageThreadId != null ? normalizeString$1(String(params.ctx.MessageThreadId)) : "") || void 0;
69180
+ return (params.ctx.MessageThreadId != null ? normalizeString(String(params.ctx.MessageThreadId)) : "") || void 0;
68926
69181
  }
68927
69182
  function resolveAcpCommandConversationId(params) {
68928
69183
  return resolveConversationIdFromTargets({
@@ -70567,7 +70822,7 @@ async function resolveSlackNames(params) {
70567
70822
  });
70568
70823
  const token = account.config.userToken?.trim() || account.botToken?.trim();
70569
70824
  if (!token) return /* @__PURE__ */ new Map();
70570
- const { resolveSlackUserAllowlist } = await import("./resolve-users-Cxb5wpAQ.js").then((n) => n.n);
70825
+ const { resolveSlackUserAllowlist } = await import("./resolve-users-DN9VQBwv.js").then((n) => n.n);
70571
70826
  return mapResolvedAllowlistNames(await resolveSlackUserAllowlist({
70572
70827
  token,
70573
70828
  entries: params.entries
@@ -80857,7 +81112,7 @@ function wrapToolWithAbortSignal(tool, abortSignal) {
80857
81112
 
80858
81113
  //#endregion
80859
81114
  //#region src/agents/pi-tools.before-tool-call.ts
80860
- const log$11 = createSubsystemLogger("agents/tools");
81115
+ const log$9 = createSubsystemLogger("agents/tools");
80861
81116
  const BEFORE_TOOL_CALL_WRAPPED = Symbol("beforeToolCallWrapped");
80862
81117
  const adjustedParamsByToolCallId = /* @__PURE__ */ new Map();
80863
81118
  const MAX_TRACKED_ADJUSTED_PARAMS = 1024;
@@ -80891,7 +81146,7 @@ async function recordLoopOutcome(args) {
80891
81146
  config: args.ctx.loopDetection
80892
81147
  });
80893
81148
  } catch (err) {
80894
- log$11.warn(`tool loop outcome tracking failed: tool=${args.toolName} error=${String(err)}`);
81149
+ log$9.warn(`tool loop outcome tracking failed: tool=${args.toolName} error=${String(err)}`);
80895
81150
  }
80896
81151
  }
80897
81152
  async function runBeforeToolCallHook(args) {
@@ -80908,7 +81163,7 @@ async function runBeforeToolCallHook(args) {
80908
81163
  const loopResult = detectToolCallLoop(sessionState, toolName, params, args.ctx.loopDetection);
80909
81164
  if (loopResult.stuck) {
80910
81165
  if (loopResult.level === "critical") {
80911
- log$11.error(`Blocking ${toolName} due to critical loop: ${loopResult.message}`);
81166
+ log$9.error(`Blocking ${toolName} due to critical loop: ${loopResult.message}`);
80912
81167
  logToolLoopAction({
80913
81168
  sessionKey: args.ctx.sessionKey,
80914
81169
  sessionId: args.ctx?.agentId,
@@ -80925,7 +81180,7 @@ async function runBeforeToolCallHook(args) {
80925
81180
  reason: loopResult.message
80926
81181
  };
80927
81182
  } else if (shouldEmitLoopWarning(sessionState, loopResult.warningKey ?? `${loopResult.detector}:${toolName}`, loopResult.count)) {
80928
- log$11.warn(`Loop warning for ${toolName}: ${loopResult.message}`);
81183
+ log$9.warn(`Loop warning for ${toolName}: ${loopResult.message}`);
80929
81184
  logToolLoopAction({
80930
81185
  sessionKey: args.ctx.sessionKey,
80931
81186
  sessionId: args.ctx?.agentId,
@@ -80975,7 +81230,7 @@ async function runBeforeToolCallHook(args) {
80975
81230
  }
80976
81231
  } catch (err) {
80977
81232
  const toolCallId = args.toolCallId ? ` toolCallId=${args.toolCallId}` : "";
80978
- log$11.warn(`before_tool_call hook failed: tool=${toolName}${toolCallId} error=${String(err)}`);
81233
+ log$9.warn(`before_tool_call hook failed: tool=${toolName}${toolCallId} error=${String(err)}`);
80979
81234
  }
80980
81235
  return {
80981
81236
  blocked: false,
@@ -84293,7 +84548,7 @@ const handleSessionCommand = async (params, allowTextCommands) => {
84293
84548
  reply: { text: resolveSessionCommandUsage() }
84294
84549
  };
84295
84550
  }
84296
- const { setThreadBindingIdleTimeoutBySessionKey, setThreadBindingMaxAgeBySessionKey } = await import("./thread-bindings.lifecycle-DU4iX_Jr.js").then((n) => n.i);
84551
+ const { setThreadBindingIdleTimeoutBySessionKey, setThreadBindingMaxAgeBySessionKey } = await import("./thread-bindings.lifecycle-tHK_1mvp.js").then((n) => n.i);
84297
84552
  const updatedBindings = action === SESSION_ACTION_IDLE ? setThreadBindingIdleTimeoutBySessionKey({
84298
84553
  targetSessionKey: binding.targetSessionKey,
84299
84554
  accountId,
@@ -85508,7 +85763,7 @@ async function createModelSelectionState(params) {
85508
85763
  }
85509
85764
  }
85510
85765
  if (sessionEntry && sessionStore && sessionKey && sessionEntry.authProfileOverride) {
85511
- const { ensureAuthProfileStore } = await import("./config-Bt5GhnA-.js").then((n) => n.yn);
85766
+ const { ensureAuthProfileStore } = await import("./config-Dbxj_jUP.js").then((n) => n.yn);
85512
85767
  const profile = ensureAuthProfileStore(void 0, { allowKeychainPrompt: false }).profiles[sessionEntry.authProfileOverride];
85513
85768
  const providerKey = normalizeProviderId$1(provider);
85514
85769
  if (!profile || normalizeProviderId$1(profile.provider) !== providerKey) await clearSessionAuthProfileOverride({
@@ -90759,7 +91014,7 @@ async function applyResetModelOverride(params) {
90759
91014
  //#endregion
90760
91015
  //#region src/infra/session-maintenance-warning.ts
90761
91016
  const warnedContexts = /* @__PURE__ */ new Map();
90762
- const log$10 = createSubsystemLogger("session-maintenance-warning");
91017
+ const log$8 = createSubsystemLogger("session-maintenance-warning");
90763
91018
  function shouldSendWarning() {
90764
91019
  return !process.env.VITEST && true;
90765
91020
  }
@@ -90830,14 +91085,14 @@ async function deliverSessionMaintenanceWarning(params) {
90830
91085
  session: outboundSession
90831
91086
  });
90832
91087
  } catch (err) {
90833
- log$10.warn(`Failed to deliver session maintenance warning: ${String(err)}`);
91088
+ log$8.warn(`Failed to deliver session maintenance warning: ${String(err)}`);
90834
91089
  enqueueSystemEvent(text, { sessionKey: params.sessionKey });
90835
91090
  }
90836
91091
  }
90837
91092
 
90838
91093
  //#endregion
90839
91094
  //#region src/auto-reply/reply/session.ts
90840
- const log$9 = createSubsystemLogger("session-init");
91095
+ const log$7 = createSubsystemLogger("session-init");
90841
91096
  function resolveActiveNamedSessionKey(params) {
90842
91097
  const baseSessionKey = params.baseSessionKey.trim().toLowerCase();
90843
91098
  if (!baseSessionKey) return params.baseSessionKey;
@@ -91115,10 +91370,10 @@ async function initSessionState(params) {
91115
91370
  if (parentSessionKey && parentSessionKey !== sessionKey && sessionStore[parentSessionKey] && !alreadyForked) {
91116
91371
  const parentTokens = sessionStore[parentSessionKey].totalTokens ?? 0;
91117
91372
  if (parentForkMaxTokens > 0 && parentTokens > parentForkMaxTokens) {
91118
- log$9.warn(`skipping parent fork (parent too large): parentKey=${parentSessionKey} → sessionKey=${sessionKey} parentTokens=${parentTokens} maxTokens=${parentForkMaxTokens}`);
91373
+ log$7.warn(`skipping parent fork (parent too large): parentKey=${parentSessionKey} → sessionKey=${sessionKey} parentTokens=${parentTokens} maxTokens=${parentForkMaxTokens}`);
91119
91374
  sessionEntry.forkedFromParent = true;
91120
91375
  } else {
91121
- log$9.warn(`forking from parent session: parentKey=${parentSessionKey} → sessionKey=${sessionKey} parentTokens=${parentTokens}`);
91376
+ log$7.warn(`forking from parent session: parentKey=${parentSessionKey} → sessionKey=${sessionKey} parentTokens=${parentTokens}`);
91122
91377
  const forked = forkSessionFromParent({
91123
91378
  parentEntry: sessionStore[parentSessionKey],
91124
91379
  agentId,
@@ -91129,7 +91384,7 @@ async function initSessionState(params) {
91129
91384
  sessionEntry.sessionId = forked.sessionId;
91130
91385
  sessionEntry.sessionFile = forked.sessionFile;
91131
91386
  sessionEntry.forkedFromParent = true;
91132
- log$9.warn(`forked session created: file=${forked.sessionFile}`);
91387
+ log$7.warn(`forked session created: file=${forked.sessionFile}`);
91133
91388
  }
91134
91389
  }
91135
91390
  }
@@ -93579,7 +93834,7 @@ const discordMessageActions = {
93579
93834
  return null;
93580
93835
  },
93581
93836
  handleAction: async ({ action, params, cfg, accountId, requesterSenderId, toolContext, mediaLocalRoots }) => {
93582
- const { handleDiscordMessageAction } = await import("./handle-action-DbzZFYnG.js");
93837
+ const { handleDiscordMessageAction } = await import("./handle-action-BSNDD2Vc.js");
93583
93838
  return await handleDiscordMessageAction({
93584
93839
  action,
93585
93840
  params,
@@ -93816,7 +94071,7 @@ const signalMessageActions = {
93816
94071
  //#region src/channels/plugins/actions/telegram.ts
93817
94072
  const providerId = "telegram";
93818
94073
  async function loadTelegramActionHandler() {
93819
- const { handleTelegramAction } = await import("./telegram-actions-CwYjV6Db.js");
94074
+ const { handleTelegramAction } = await import("./telegram-actions-CM8SJgc9.js");
93820
94075
  return handleTelegramAction;
93821
94076
  }
93822
94077
  function readTelegramSendParams(params) {
@@ -93986,7 +94241,7 @@ function createWhatsAppLoginTool() {
93986
94241
  force: Type.Optional(Type.Boolean())
93987
94242
  }),
93988
94243
  execute: async (_toolCallId, args) => {
93989
- const { startWebLoginWithQr, waitForWebLogin } = await import("./login-qr-CbHL5ayf.js");
94244
+ const { startWebLoginWithQr, waitForWebLogin } = await import("./login-qr-CJB2zjmM.js");
93990
94245
  if ((args?.action ?? "start") === "wait") {
93991
94246
  const result = await waitForWebLogin({ timeoutMs: typeof args.timeoutMs === "number" ? args.timeoutMs : void 0 });
93992
94247
  return {
@@ -96226,7 +96481,7 @@ function buildPairingReply(params) {
96226
96481
 
96227
96482
  //#endregion
96228
96483
  //#region src/brand.ts
96229
- const FASED_PRODUCT_VERSION = "0.1.56";
96484
+ const FASED_PRODUCT_VERSION = "0.1.57";
96230
96485
  const FASED_DISPLAY_VERSION = `v${FASED_PRODUCT_VERSION}`;
96231
96486
 
96232
96487
  //#endregion
@@ -96830,7 +97085,7 @@ function describeIMessageEchoDropLog(params) {
96830
97085
 
96831
97086
  //#endregion
96832
97087
  //#region src/imessage/monitor/parse-notification.ts
96833
- function isRecord(value) {
97088
+ function isRecord$1(value) {
96834
97089
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
96835
97090
  }
96836
97091
  function isOptionalString(value) {
@@ -96852,14 +97107,14 @@ function isOptionalAttachments(value) {
96852
97107
  if (value === void 0 || value === null) return true;
96853
97108
  if (!Array.isArray(value)) return false;
96854
97109
  return value.every((attachment) => {
96855
- if (!isRecord(attachment)) return false;
97110
+ if (!isRecord$1(attachment)) return false;
96856
97111
  return isOptionalString(attachment.original_path) && isOptionalString(attachment.mime_type) && isOptionalBoolean(attachment.missing);
96857
97112
  });
96858
97113
  }
96859
97114
  function parseIMessageNotification(raw) {
96860
- if (!isRecord(raw)) return null;
97115
+ if (!isRecord$1(raw)) return null;
96861
97116
  const maybeMessage = raw.message;
96862
- if (!isRecord(maybeMessage)) return null;
97117
+ if (!isRecord$1(maybeMessage)) return null;
96863
97118
  const message = maybeMessage;
96864
97119
  if (!isOptionalNumber(message.id) || !isOptionalNumber(message.chat_id) || !isOptionalString(message.sender) || !isOptionalBoolean(message.is_from_me) || !isOptionalString(message.text) || !isOptionalStringOrNumber(message.reply_to_id) || !isOptionalString(message.reply_to_text) || !isOptionalString(message.reply_to_sender) || !isOptionalString(message.created_at) || !isOptionalAttachments(message.attachments) || !isOptionalString(message.chat_identifier) || !isOptionalString(message.chat_guid) || !isOptionalString(message.chat_name) || !isOptionalStringArray(message.participants) || !isOptionalBoolean(message.is_group)) return null;
96865
97120
  return message;
@@ -100007,8 +100262,8 @@ async function auditTelegramGroupMembership(params) {
100007
100262
  for (const chatId of params.groupIds) try {
100008
100263
  const res = await fetchWithTimeout(`${base}/getChatMember?chat_id=${encodeURIComponent(chatId)}&user_id=${encodeURIComponent(String(params.botId))}`, {}, params.timeoutMs, fetcher);
100009
100264
  const json = await res.json();
100010
- if (!res.ok || !isRecord$4(json) || !json.ok) {
100011
- const desc = isRecord$4(json) && !json.ok && typeof json.description === "string" ? json.description : `getChatMember failed (${res.status})`;
100265
+ if (!res.ok || !isRecord$5(json) || !json.ok) {
100266
+ const desc = isRecord$5(json) && !json.ok && typeof json.description === "string" ? json.description : `getChatMember failed (${res.status})`;
100012
100267
  groups.push({
100013
100268
  chatId,
100014
100269
  ok: false,
@@ -100019,7 +100274,7 @@ async function auditTelegramGroupMembership(params) {
100019
100274
  });
100020
100275
  continue;
100021
100276
  }
100022
- const status = isRecord$4(json.result) ? json.result.status ?? null : null;
100277
+ const status = isRecord$5(json.result) ? json.result.status ?? null : null;
100023
100278
  const ok = status === "creator" || status === "administrator" || status === "member";
100024
100279
  groups.push({
100025
100280
  chatId,
@@ -100105,7 +100360,7 @@ const handleWhatsAppActionLazy = async (...args) => {
100105
100360
  return handleWhatsAppAction(...args);
100106
100361
  };
100107
100362
  const auditDiscordChannelPermissionsLazy = async (...args) => {
100108
- const { auditDiscordChannelPermissions } = await import("./audit-CWknklvI.js").then((n) => n.t);
100363
+ const { auditDiscordChannelPermissions } = await import("./audit-JImYFOzJ.js").then((n) => n.t);
100109
100364
  return auditDiscordChannelPermissions(...args);
100110
100365
  };
100111
100366
  const listDiscordDirectoryGroupsLiveLazy = async (...args) => {
@@ -100129,15 +100384,15 @@ const resolveDiscordUserAllowlistLazy = async (...args) => {
100129
100384
  return resolveDiscordUserAllowlist(...args);
100130
100385
  };
100131
100386
  const sendMessageDiscordLazy = async (...args) => {
100132
- const { sendMessageDiscord } = await import("./send-BQUtCJFW.js").then((n) => n.t);
100387
+ const { sendMessageDiscord } = await import("./send-BCJ4hi3t.js").then((n) => n.t);
100133
100388
  return sendMessageDiscord(...args);
100134
100389
  };
100135
100390
  const sendPollDiscordLazy = async (...args) => {
100136
- const { sendPollDiscord } = await import("./send-BQUtCJFW.js").then((n) => n.t);
100391
+ const { sendPollDiscord } = await import("./send-BCJ4hi3t.js").then((n) => n.t);
100137
100392
  return sendPollDiscord(...args);
100138
100393
  };
100139
100394
  const monitorDiscordProviderLazy = async (...args) => {
100140
- const { monitorDiscordProvider } = await import("./monitor-CmwGqNyV.js");
100395
+ const { monitorDiscordProvider } = await import("./monitor-BYGbTI5V.js");
100141
100396
  return monitorDiscordProvider(...args);
100142
100397
  };
100143
100398
  const listSlackDirectoryGroupsLiveLazy = async (...args) => {
@@ -100149,27 +100404,27 @@ const listSlackDirectoryPeersLiveLazy = async (...args) => {
100149
100404
  return listSlackDirectoryPeersLive(...args);
100150
100405
  };
100151
100406
  const probeSlackLazy = async (...args) => {
100152
- const { probeSlack } = await import("./probe-xY3Ky0Tx.js");
100407
+ const { probeSlack } = await import("./probe-CJb5uR8B.js");
100153
100408
  return probeSlack(...args);
100154
100409
  };
100155
100410
  const resolveSlackChannelAllowlistLazy = async (...args) => {
100156
- const { resolveSlackChannelAllowlist } = await import("./resolve-channels-CwB2_019.js");
100411
+ const { resolveSlackChannelAllowlist } = await import("./resolve-channels-_-nV-EK2.js").then((n) => n.n);
100157
100412
  return resolveSlackChannelAllowlist(...args);
100158
100413
  };
100159
100414
  const resolveSlackUserAllowlistLazy = async (...args) => {
100160
- const { resolveSlackUserAllowlist } = await import("./resolve-users-Cxb5wpAQ.js").then((n) => n.n);
100415
+ const { resolveSlackUserAllowlist } = await import("./resolve-users-DN9VQBwv.js").then((n) => n.n);
100161
100416
  return resolveSlackUserAllowlist(...args);
100162
100417
  };
100163
100418
  const sendMessageSlackLazy = async (...args) => {
100164
- const { sendMessageSlack } = await import("./send-2VcOMTN5.js").then((n) => n.n);
100419
+ const { sendMessageSlack } = await import("./send-CPK_HlYW.js").then((n) => n.n);
100165
100420
  return sendMessageSlack(...args);
100166
100421
  };
100167
100422
  const monitorSlackProviderLazy = async (...args) => {
100168
- const { monitorSlackProvider } = await import("./slack-BouRQG-W.js");
100423
+ const { monitorSlackProvider } = await import("./slack-B70NHpMF.js");
100169
100424
  return monitorSlackProvider(...args);
100170
100425
  };
100171
100426
  const handleSlackActionLazy = async (...args) => {
100172
- const { handleSlackAction } = await import("./slack-actions-CasHVtiq.js");
100427
+ const { handleSlackAction } = await import("./slack-actions-fSmP981b.js");
100173
100428
  return handleSlackAction(...args);
100174
100429
  };
100175
100430
  const probeTelegramLazy = async (...args) => {
@@ -100177,15 +100432,15 @@ const probeTelegramLazy = async (...args) => {
100177
100432
  return probeTelegram(...args);
100178
100433
  };
100179
100434
  const sendMessageTelegramLazy = async (...args) => {
100180
- const { sendMessageTelegram } = await import("./send-Dqes9tdU.js").then((n) => n.c);
100435
+ const { sendMessageTelegram } = await import("./send-hSu1HWms.js").then((n) => n.c);
100181
100436
  return sendMessageTelegram(...args);
100182
100437
  };
100183
100438
  const sendPollTelegramLazy = async (...args) => {
100184
- const { sendPollTelegram } = await import("./send-Dqes9tdU.js").then((n) => n.c);
100439
+ const { sendPollTelegram } = await import("./send-hSu1HWms.js").then((n) => n.c);
100185
100440
  return sendPollTelegram(...args);
100186
100441
  };
100187
100442
  const monitorTelegramProviderLazy = async (...args) => {
100188
- const { monitorTelegramProvider } = await import("./monitor-CZrN9pev.js");
100443
+ const { monitorTelegramProvider } = await import("./monitor-BJs6z7AT.js");
100189
100444
  return monitorTelegramProvider(...args);
100190
100445
  };
100191
100446
  let webOutboundPromise = null;
@@ -100194,23 +100449,23 @@ let webLoginQrPromise = null;
100194
100449
  let webChannelPromise = null;
100195
100450
  let whatsappActionsPromise = null;
100196
100451
  function loadWebOutbound() {
100197
- webOutboundPromise ??= import("./outbound-0oN9IfNw.js").then((n) => n.t);
100452
+ webOutboundPromise ??= import("./outbound-CIemga5_.js").then((n) => n.t);
100198
100453
  return webOutboundPromise;
100199
100454
  }
100200
100455
  function loadWebLogin() {
100201
- webLoginPromise ??= import("./login-DJuHYDiK.js").then((n) => n.n);
100456
+ webLoginPromise ??= import("./login-CWXvFTd8.js").then((n) => n.n);
100202
100457
  return webLoginPromise;
100203
100458
  }
100204
100459
  function loadWebLoginQr() {
100205
- webLoginQrPromise ??= import("./login-qr-CbHL5ayf.js");
100460
+ webLoginQrPromise ??= import("./login-qr-CJB2zjmM.js");
100206
100461
  return webLoginQrPromise;
100207
100462
  }
100208
100463
  function loadWebChannel() {
100209
- webChannelPromise ??= import("./web-D0yENDve.js");
100464
+ webChannelPromise ??= import("./web-BFolfZ3i.js");
100210
100465
  return webChannelPromise;
100211
100466
  }
100212
100467
  function loadWhatsAppActions() {
100213
- whatsappActionsPromise ??= import("./whatsapp-actions-BT2nPLyo.js");
100468
+ whatsappActionsPromise ??= import("./whatsapp-actions-CYmleHCz.js");
100214
100469
  return whatsappActionsPromise;
100215
100470
  }
100216
100471
  function createPluginRuntime(options = {}) {
@@ -101056,467 +101311,567 @@ function safeRealpathOrResolve(value) {
101056
101311
  }
101057
101312
 
101058
101313
  //#endregion
101059
- //#region src/plugins/providers.ts
101060
- const log$8 = createSubsystemLogger("plugins");
101061
- function resolvePluginProviders(params) {
101062
- return loadFasedAgentPlugins({
101063
- config: params.config,
101064
- workspaceDir: params.workspaceDir,
101065
- logger: createPluginLoaderLogger(log$8)
101066
- }).providers.map((entry) => entry.provider);
101314
+ //#region src/plugins/status.ts
101315
+ const log$6 = createSubsystemLogger("plugins");
101316
+ function buildPluginStatusReport(params) {
101317
+ const config = params?.config ?? loadConfig();
101318
+ const workspaceDir = params?.workspaceDir ? params.workspaceDir : resolveAgentWorkspaceDir(config, resolveDefaultAgentId(config)) ?? resolveDefaultAgentWorkspaceDir();
101319
+ return {
101320
+ workspaceDir,
101321
+ ...loadFasedAgentPlugins({
101322
+ config,
101323
+ workspaceDir,
101324
+ logger: createPluginLoaderLogger(log$6)
101325
+ })
101326
+ };
101067
101327
  }
101068
101328
 
101069
101329
  //#endregion
101070
- //#region src/plugins/provider-runtime.runtime.ts
101071
- const log$7 = createSubsystemLogger("provider-runtime");
101072
- function mergeProviders(target, providers) {
101073
- for (const [providerId, providerConfig] of Object.entries(providers)) target[providerId] = providerConfig;
101074
- }
101075
- function staticAuthContext() {
101330
+ //#region src/plugins/lifecycle.ts
101331
+ function applySlotSelectionForPlugin(config, pluginId) {
101332
+ const report = buildPluginStatusReport({ config });
101333
+ const plugin = (report.plugins ?? []).find((entry) => entry.id === pluginId);
101334
+ if (!plugin) return {
101335
+ config,
101336
+ warnings: []
101337
+ };
101338
+ const result = applyExclusiveSlotSelection({
101339
+ config,
101340
+ selectedId: plugin.id,
101341
+ selectedKind: plugin.kind,
101342
+ registry: report
101343
+ });
101076
101344
  return {
101077
- resolveProviderApiKey: () => ({ apiKey: void 0 }),
101078
- resolveProviderAuth: () => ({
101079
- apiKey: void 0,
101080
- discoveryApiKey: void 0,
101081
- mode: "none",
101082
- source: "none"
101083
- })
101345
+ config: result.config,
101346
+ warnings: result.warnings
101084
101347
  };
101085
101348
  }
101086
- async function resolveProviderStaticCatalog(params) {
101087
- if (!params.provider.staticCatalog) return {};
101088
- const result = await runProviderStaticCatalog({
101089
- provider: params.provider,
101090
- config: params.config,
101091
- agentDir: params.agentDir,
101092
- workspaceDir: params.workspaceDir,
101093
- env: params.env,
101094
- ...staticAuthContext()
101095
- });
101096
- return normalizePluginDiscoveryResult({
101097
- provider: params.provider,
101098
- result
101099
- });
101349
+ function addPluginLoadPath(cfg, pluginPath) {
101350
+ const existing = cfg.plugins?.load?.paths ?? [];
101351
+ const merged = Array.from(new Set([...existing, pluginPath]));
101352
+ return {
101353
+ ...cfg,
101354
+ plugins: {
101355
+ ...cfg.plugins,
101356
+ load: {
101357
+ ...cfg.plugins?.load,
101358
+ paths: merged
101359
+ }
101360
+ }
101361
+ };
101100
101362
  }
101101
- async function augmentModelCatalogWithProviderPlugins(params) {
101102
- const env = params.env ?? process.env;
101103
- const providers = resolvePluginProviders({
101104
- config: params.config,
101105
- workspaceDir: params.workspaceDir
101363
+ function finalizeInstalledPluginConfig(params) {
101364
+ if (params.refreshManifestRegistry) clearPluginManifestRegistryCache();
101365
+ let next = params.config;
101366
+ if (params.loadPath) next = addPluginLoadPath(next, params.loadPath);
101367
+ next = enablePluginInConfig(next, params.pluginId).config;
101368
+ if (params.installRecord) next = recordPluginInstall(next, {
101369
+ pluginId: params.pluginId,
101370
+ ...params.installRecord
101106
101371
  });
101107
- const catalogProviders = {};
101108
- for (const provider of providers) try {
101109
- if (provider.models) mergeProviders(catalogProviders, normalizePluginDiscoveryResult({
101110
- provider,
101111
- result: { provider: provider.models }
101112
- }));
101113
- mergeProviders(catalogProviders, await resolveProviderStaticCatalog({
101114
- provider,
101115
- config: params.config,
101116
- agentDir: params.agentDir,
101117
- workspaceDir: params.workspaceDir,
101118
- env
101119
- }));
101120
- } catch (error) {
101121
- log$7.warn(`Failed to read provider catalog for ${provider.id}: ${String(error)}`);
101122
- }
101123
- return catalogProviders;
101372
+ next = ensurePluginAllowlisted(next, params.pluginId, { createIfMissing: true });
101373
+ const slotResult = applySlotSelectionForPlugin(next, params.pluginId);
101374
+ return {
101375
+ config: slotResult.config,
101376
+ slotWarnings: slotResult.warnings
101377
+ };
101124
101378
  }
101125
101379
 
101126
101380
  //#endregion
101127
- //#region src/agents/model-catalog-source.ts
101128
- function normalizePositiveNumber(value) {
101129
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : void 0;
101381
+ //#region src/capabilities/catalog.ts
101382
+ const CATALOG_RELATIVE_PATH = path.join("config", "capability-catalog.json");
101383
+ const DELIVERY_VALUES = new Set([
101384
+ "core",
101385
+ "npm-addon",
101386
+ "external-runtime"
101387
+ ]);
101388
+ const CATEGORY_VALUES = new Set([
101389
+ "core",
101390
+ "crypto",
101391
+ "channel",
101392
+ "provider",
101393
+ "runtime"
101394
+ ]);
101395
+ function isRecord(value) {
101396
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
101130
101397
  }
101131
- function normalizeBoolean(value) {
101132
- return typeof value === "boolean" ? value : void 0;
101398
+ function requiredString(record, key, index) {
101399
+ const value = record[key];
101400
+ if (typeof value !== "string" || !value.trim()) throw new Error(`capability catalog entry ${index} requires ${key}`);
101401
+ return value.trim();
101133
101402
  }
101134
- function normalizeString(value) {
101403
+ function optionalString(record, key) {
101404
+ const value = record[key];
101135
101405
  return typeof value === "string" && value.trim() ? value.trim() : void 0;
101136
101406
  }
101137
- function normalizeInput(value) {
101138
- if (!Array.isArray(value)) return ["text"];
101139
- const out = value.filter((item) => item === "text" || item === "image");
101140
- return out.length > 0 ? out : ["text"];
101141
- }
101142
- function normalizeApi(value) {
101143
- return MODEL_APIS.includes(value) ? value : void 0;
101407
+ function parseCatalogEntry(value, index) {
101408
+ if (!isRecord(value)) throw new Error(`capability catalog entry ${index} must be an object`);
101409
+ const delivery = requiredString(value, "delivery", index);
101410
+ if (!DELIVERY_VALUES.has(delivery)) throw new Error(`capability catalog entry ${index} has invalid delivery ${delivery}`);
101411
+ const category = requiredString(value, "category", index);
101412
+ if (!CATEGORY_VALUES.has(category)) throw new Error(`capability catalog entry ${index} has invalid category ${category}`);
101413
+ const externalKind = optionalString(value, "externalKind");
101414
+ if (externalKind && externalKind !== "browser" && externalKind !== "model-server" && externalKind !== "local-embeddings") throw new Error(`capability catalog entry ${index} has invalid externalKind ${externalKind}`);
101415
+ return {
101416
+ id: requiredString(value, "id", index),
101417
+ label: requiredString(value, "label", index),
101418
+ category,
101419
+ delivery,
101420
+ description: requiredString(value, "description", index),
101421
+ docsPath: requiredString(value, "docsPath", index),
101422
+ surface: requiredString(value, "surface", index),
101423
+ ...optionalString(value, "packageName") ? { packageName: optionalString(value, "packageName") } : {},
101424
+ ...optionalString(value, "pluginId") ? { pluginId: optionalString(value, "pluginId") } : {},
101425
+ ...optionalString(value, "channelId") ? { channelId: optionalString(value, "channelId") } : {},
101426
+ ...optionalString(value, "providerId") ? { providerId: optionalString(value, "providerId") } : {},
101427
+ ...externalKind ? { externalKind } : {},
101428
+ ...value.restartRequired === true ? { restartRequired: true } : {}
101429
+ };
101430
+ }
101431
+ function resolveCatalogPath() {
101432
+ const roots = [
101433
+ resolveFasedAgentPackageRootSync({ moduleUrl: import.meta.url }),
101434
+ resolveFasedAgentPackageRootSync({ cwd: process.cwd() }),
101435
+ process.cwd()
101436
+ ].filter((entry, index, all) => Boolean(entry) && all.indexOf(entry) === index);
101437
+ for (const root of roots) {
101438
+ const candidate = path.join(root, CATALOG_RELATIVE_PATH);
101439
+ if (fs.existsSync(candidate)) return candidate;
101440
+ }
101441
+ throw new Error(`Fased capability catalog not found (${CATALOG_RELATIVE_PATH})`);
101144
101442
  }
101145
- function isSupportedRuntimeCatalogModel(provider, id) {
101146
- if (provider !== "openai-codex") return true;
101147
- return isOpenAISignInRuntimeModelSupported(id);
101443
+ function loadCapabilityCatalog() {
101444
+ const payload = JSON.parse(fs.readFileSync(resolveCatalogPath(), "utf8"));
101445
+ if (!isRecord(payload) || !Array.isArray(payload.entries)) throw new Error("capability catalog must contain an entries array");
101446
+ const entries = payload.entries.map(parseCatalogEntry);
101447
+ const ids = /* @__PURE__ */ new Set();
101448
+ for (const entry of entries) {
101449
+ if (ids.has(entry.id)) throw new Error(`duplicate capability catalog id: ${entry.id}`);
101450
+ ids.add(entry.id);
101451
+ }
101452
+ return entries;
101148
101453
  }
101149
- function configuredProviderCatalogRows(cfg) {
101150
- return Object.entries(cfg.models?.providers ?? {}).flatMap(([provider, providerConfig]) => normalizeProviderCatalogRows({
101151
- provider,
101152
- providerConfig,
101153
- source: "configured",
101154
- status: "stable"
101155
- }));
101454
+
101455
+ //#endregion
101456
+ //#region src/capabilities/install.ts
101457
+ async function installCapabilityComponent(params) {
101458
+ const entry = loadCapabilityCatalog().find((candidate) => candidate.id === params.id);
101459
+ if (!entry) throw new Error(`Unknown component: ${params.id}. Run \`fased components\` to list choices.`);
101460
+ if (entry.delivery !== "npm-addon" || !entry.packageName || !entry.pluginId) throw new Error(`${entry.label} is delivered as ${entry.delivery} and cannot be installed as an add-on. See ${entry.docsPath}.`);
101461
+ const packageSpec = params.packageSpec?.trim() || entry.packageName;
101462
+ const result = await installPluginFromNpmSpec({ spec: packageSpec });
101463
+ if (!result.ok) throw new Error(result.error);
101464
+ const finalized = finalizeInstalledPluginConfig({
101465
+ config: params.config,
101466
+ pluginId: result.pluginId,
101467
+ refreshManifestRegistry: true,
101468
+ installRecord: {
101469
+ source: "npm",
101470
+ spec: packageSpec,
101471
+ installPath: result.targetDir,
101472
+ version: result.version,
101473
+ ...buildNpmResolutionInstallFields(result.npmResolution)
101474
+ }
101475
+ });
101476
+ return {
101477
+ config: finalized.config,
101478
+ entry,
101479
+ pluginId: result.pluginId,
101480
+ targetDir: result.targetDir,
101481
+ ...result.version ? { version: result.version } : {},
101482
+ slotWarnings: finalized.slotWarnings
101483
+ };
101156
101484
  }
101157
- function providerPluginCatalogRows(providers) {
101158
- return Object.entries(providers ?? {}).flatMap(([provider, providerConfig]) => normalizeProviderCatalogRows({
101159
- provider,
101160
- providerConfig,
101161
- source: "provider-index",
101162
- status: "stable"
101163
- }));
101485
+
101486
+ //#endregion
101487
+ //#region src/agents/openai-codex-runtime-component.ts
101488
+ const OPENAI_RUNTIME_COMPONENT_ID = "openai-runtime";
101489
+ async function ensureOpenAICodexRuntimeComponent(params) {
101490
+ const resolveExecutable = params.resolveExecutable ?? resolveOpenAICodexExecutable;
101491
+ const existing = resolveExecutable();
101492
+ if (existing) return {
101493
+ config: params.config,
101494
+ executable: existing,
101495
+ installed: false,
101496
+ slotWarnings: []
101497
+ };
101498
+ const installed = await (params.installComponent ?? installCapabilityComponent)({
101499
+ id: OPENAI_RUNTIME_COMPONENT_ID,
101500
+ config: params.config,
101501
+ packageSpec: `@fased/openai-runtime@${params.version ?? VERSION}`
101502
+ });
101503
+ const executable = resolveExecutable();
101504
+ if (!executable) throw new Error("OpenAI sign-in runtime installation completed without an executable. Run `fased components install openai-runtime` and retry.");
101505
+ return {
101506
+ config: installed.config,
101507
+ executable,
101508
+ installed: true,
101509
+ slotWarnings: installed.slotWarnings
101510
+ };
101164
101511
  }
101165
- function runtimeCatalogRows(params) {
101166
- const rows = [];
101167
- for (const model of params.models) try {
101168
- const idRaw = normalizeString(model.id);
101169
- const providerRaw = normalizeString(model.provider);
101170
- if (!idRaw || !providerRaw) continue;
101171
- const id = normalizeModelCatalogModelId(idRaw);
101172
- const provider = normalizeModelCatalogProviderId(providerRaw);
101173
- if (!id || !provider) continue;
101174
- if (!isSupportedRuntimeCatalogModel(provider, id)) continue;
101175
- if (id.toLowerCase() === "gpt-5.3-codex-spark" && (provider === "openai" || provider === "azure-openai-responses")) continue;
101176
- rows.push({
101177
- id,
101178
- name: normalizeString(model.name) ?? id,
101179
- provider,
101180
- mergeKey: buildModelCatalogMergeKey(provider, id),
101181
- source: "runtime",
101182
- status: "stable",
101183
- input: normalizeInput(model.input),
101184
- contextWindow: normalizePositiveNumber(model.contextWindow),
101185
- maxTokens: normalizePositiveNumber(model.maxTokens),
101186
- reasoning: normalizeBoolean(model.reasoning),
101187
- baseUrl: normalizeString(model.baseUrl),
101188
- api: normalizeApi(model.api)
101189
- });
101190
- } catch (error) {
101191
- params.onEntryError?.(error);
101512
+
101513
+ //#endregion
101514
+ //#region src/providers/openai-codex-model-discovery.ts
101515
+ const OPENAI_CODEX_MODELS_URL = "https://chatgpt.com/backend-api/codex/models";
101516
+ const OPENAI_CODEX_ROUTE = "openai-codex";
101517
+ const OPENAI_CODEX_CATALOG_CLIENT_VERSION = "0.144.0";
101518
+ const DISCOVERY_TIMEOUT_MS = 8e3;
101519
+ function decodeJwtPayload(token) {
101520
+ const encoded = token.split(".")[1];
101521
+ if (!encoded) return null;
101522
+ try {
101523
+ return JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
101524
+ } catch {
101525
+ return null;
101192
101526
  }
101193
- return rows;
101194
101527
  }
101195
- function manifestCatalogRows() {
101196
- return listProviderBrandManifests().flatMap((manifest) => manifest.models.recommended.flatMap((ref) => {
101197
- const slash = ref.indexOf("/");
101198
- if (slash <= 0 || slash === ref.length - 1) return [];
101199
- const provider = normalizeModelCatalogProviderId(ref.slice(0, slash));
101200
- const id = normalizeModelCatalogModelId(ref.slice(slash + 1));
101201
- if (!provider || !id) return [];
101202
- return [{
101203
- id,
101204
- name: id,
101205
- provider,
101206
- mergeKey: buildModelCatalogMergeKey(provider, id),
101207
- source: "manifest",
101208
- status: "stable",
101209
- input: ["text"]
101210
- }];
101211
- }));
101528
+ function extractChatGptAccountId(token) {
101529
+ const auth = decodeJwtPayload(token)?.["https://api.openai.com/auth"];
101530
+ if (!auth || typeof auth !== "object" || Array.isArray(auth)) return null;
101531
+ const accountId = auth.chatgpt_account_id;
101532
+ return typeof accountId === "string" && accountId.trim() ? accountId.trim() : null;
101212
101533
  }
101213
- function providerConfigForRow(cfg, row) {
101214
- return cfg.models?.providers?.[row.provider] ?? CURRENT_MODEL_PROVIDER_CATALOG[row.provider];
101534
+ function positiveInteger(value) {
101535
+ return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : void 0;
101215
101536
  }
101216
- function buildFasedModelCatalogRows(params) {
101217
- const discoveredRows = mergeModelCatalogRowsByAuthority([
101218
- ...[...listCurrentModelCatalogRows(), ...providerPluginCatalogRows(params.providerPluginProviders)].filter((row) => isSupportedRuntimeCatalogModel(row.provider, row.id)),
101219
- ...runtimeCatalogRows({
101220
- models: params.runtimeModels ?? [],
101221
- onEntryError: params.onRuntimeEntryError
101222
- }),
101223
- ...configuredProviderCatalogRows(params.config)
101224
- ]);
101225
- const discoveredKeys = new Set(discoveredRows.map((row) => row.mergeKey));
101226
- const missingManifestRows = manifestCatalogRows().filter((row) => !discoveredKeys.has(row.mergeKey));
101227
- return mergeModelCatalogRowsByAuthority([...discoveredRows, ...missingManifestRows]);
101537
+ function inputModalities(value) {
101538
+ if (!Array.isArray(value)) return ["text"];
101539
+ const values = value.filter((entry) => entry === "text" || entry === "image");
101540
+ return values.length > 0 ? values : ["text"];
101228
101541
  }
101229
- function buildFasedModelCatalogEntries(params) {
101230
- return buildFasedModelCatalogRows({
101231
- config: params.config,
101232
- runtimeModels: params.runtimeModels,
101233
- providerPluginProviders: params.providerPluginProviders,
101234
- onRuntimeEntryError: params.onRuntimeEntryError
101235
- }).map((row) => {
101236
- const providerConfig = providerConfigForRow(params.config, row);
101237
- const model = {
101238
- id: row.id,
101239
- name: row.name,
101240
- provider: row.provider,
101241
- contextWindow: row.contextWindow,
101242
- maxTokens: row.maxTokens,
101243
- reasoning: row.reasoning,
101244
- input: row.input,
101245
- baseUrl: row.baseUrl,
101246
- api: row.api,
101247
- catalogSource: row.source
101248
- };
101542
+ function modelCapabilities(model) {
101543
+ const thinkingLevels = (Array.isArray(model.supported_reasoning_levels) ? model.supported_reasoning_levels : []).flatMap((entry) => {
101544
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) return [];
101545
+ const effort = entry.effort;
101546
+ const normalized = typeof effort === "string" ? normalizeThinkLevel(effort) : void 0;
101547
+ return normalized ? [normalized] : [];
101548
+ });
101549
+ const defaultThinkingLevel = typeof model.default_reasoning_level === "string" ? normalizeThinkLevel(model.default_reasoning_level) : void 0;
101550
+ return {
101551
+ tools: true,
101552
+ json: true,
101553
+ streaming: true,
101554
+ ...thinkingLevels.length > 0 ? { thinkingLevels } : {},
101555
+ ...defaultThinkingLevel ? { defaultThinkingLevel } : {},
101556
+ thinkingMode: "openai-reasoning-effort",
101557
+ reasoningBudgetSupported: thinkingLevels.length > 0
101558
+ };
101559
+ }
101560
+ function parseModels(value) {
101561
+ if (!value || typeof value !== "object" || Array.isArray(value)) return [];
101562
+ const models = value.models;
101563
+ if (!Array.isArray(models)) return [];
101564
+ return models.flatMap((entry) => {
101565
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) return [];
101566
+ const model = entry;
101567
+ const id = typeof model.slug === "string" ? model.slug.trim() : "";
101568
+ if (!id || model.visibility !== "list") return [];
101569
+ const capabilities = modelCapabilities(model);
101570
+ return [{
101571
+ id,
101572
+ name: typeof model.display_name === "string" && model.display_name.trim() ? model.display_name.trim().replace(/-(Sol|Terra|Luna|Mini)$/i, " $1") : id,
101573
+ input: inputModalities(model.input_modalities),
101574
+ reasoning: true,
101575
+ tools: capabilities.tools,
101576
+ json: capabilities.json,
101577
+ thinkingLevels: capabilities.thinkingLevels,
101578
+ defaultThinkingLevel: capabilities.defaultThinkingLevel,
101579
+ thinkingMode: capabilities.thinkingMode,
101580
+ reasoningBudgetSupported: capabilities.reasoningBudgetSupported,
101581
+ contextWindow: positiveInteger(model.context_window),
101582
+ responsesLite: model.use_responses_lite === true,
101583
+ source: "openai-codex-account"
101584
+ }];
101585
+ });
101586
+ }
101587
+ function parseAppServerModels(models) {
101588
+ return models.map((model) => {
101589
+ const thinkingLevels = model.supportedReasoningEfforts.flatMap((effort) => {
101590
+ const normalized = normalizeThinkLevel(effort);
101591
+ return normalized ? [normalized] : [];
101592
+ });
101593
+ const defaultThinkingLevel = normalizeThinkLevel(model.defaultReasoningEffort);
101594
+ const responsesLite = /^gpt-5\.6-(?:sol|terra|luna)$/i.test(model.id);
101249
101595
  return {
101250
- ...model,
101251
- ...params.includeMetadata ? { metadata: deriveModelMetadata({
101252
- model,
101253
- cfg: params.config,
101254
- providerConfig,
101255
- recommended: isStandardProviderCatalogEntry(row)
101256
- }) } : {}
101596
+ id: model.id,
101597
+ name: model.displayName.replace(/-(Sol|Terra|Luna|Mini)$/i, " $1"),
101598
+ input: model.inputModalities,
101599
+ reasoning: thinkingLevels.length > 0,
101600
+ tools: !responsesLite,
101601
+ json: !responsesLite,
101602
+ thinkingLevels,
101603
+ ...defaultThinkingLevel ? { defaultThinkingLevel } : {},
101604
+ thinkingMode: "openai-reasoning-effort",
101605
+ reasoningBudgetSupported: false,
101606
+ responsesLite,
101607
+ source: "openai-codex-app-server"
101257
101608
  };
101258
101609
  });
101259
101610
  }
101611
+ async function discoverOpenAICodexModels(params) {
101612
+ const profileId = listProfilesForProvider(params.store, OPENAI_CODEX_ROUTE)[0];
101613
+ if (!profileId) return [];
101614
+ const resolved = await resolveApiKeyForProfile({
101615
+ cfg: params.cfg,
101616
+ store: params.store,
101617
+ profileId,
101618
+ agentDir: params.agentDir
101619
+ });
101620
+ if (!resolved?.apiKey) return [];
101621
+ const accountId = extractChatGptAccountId(resolved.apiKey);
101622
+ if (!accountId) throw new Error("OpenAI sign-in token does not contain a ChatGPT account ID");
101623
+ if (!params.fetchImpl) {
101624
+ const runtime = await (params.ensureRuntime ?? ensureOpenAICodexRuntimeComponent)({ config: params.cfg });
101625
+ if (runtime.installed) await writeConfigFile(runtime.config);
101626
+ return parseAppServerModels(await (params.listAppServerModels ?? listOpenAICodexAppServerModels)({
101627
+ token: resolved.apiKey,
101628
+ executable: runtime.executable
101629
+ }));
101630
+ }
101631
+ const url = new URL(OPENAI_CODEX_MODELS_URL);
101632
+ url.searchParams.set("client_version", OPENAI_CODEX_CATALOG_CLIENT_VERSION);
101633
+ const response = await (params.fetchImpl ?? fetch)(url, {
101634
+ headers: {
101635
+ authorization: `Bearer ${resolved.apiKey}`,
101636
+ "chatgpt-account-id": accountId,
101637
+ originator: "fased",
101638
+ accept: "application/json"
101639
+ },
101640
+ signal: AbortSignal.timeout(DISCOVERY_TIMEOUT_MS)
101641
+ });
101642
+ if (!response.ok) throw new Error(`OpenAI account model discovery failed (${response.status})`);
101643
+ return parseModels(await response.json());
101644
+ }
101260
101645
 
101261
101646
  //#endregion
101262
- //#region src/agents/provider-extension-catalog-index.ts
101263
- const UNSAFE_PROVIDER_KEYS = new Set([
101264
- "__proto__",
101265
- "prototype",
101266
- "constructor"
101267
- ]);
101268
- const DEFAULT_PROVIDER_EXTENSION_CATALOG_ENTRIES = [];
101269
- let providerExtensionCatalogEntriesForTest;
101270
- function listBundledProviderExtensionCatalogEntries() {
101271
- return providerExtensionCatalogEntriesForTest ?? DEFAULT_PROVIDER_EXTENSION_CATALOG_ENTRIES;
101647
+ //#region src/providers/runtime-model-catalog.ts
101648
+ const DISCOVERY_TTL_MS = 5 * 6e4;
101649
+ let cache = null;
101650
+ const SPECIALIZED_DISCOVERY_ROUTES = new Set(["openai-codex", "github-copilot"]);
101651
+ function authModeForProfileType(type) {
101652
+ return type === "api_key" ? "api-key" : type;
101272
101653
  }
101273
- function normalizeProviderIds(providerIds) {
101274
- return [...new Set(providerIds.map((providerId) => normalizeModelCatalogProviderId(providerId)).filter((providerId) => providerId.length > 0 && !UNSAFE_PROVIDER_KEYS.has(providerId)))].toSorted((left, right) => left.localeCompare(right));
101654
+ function methodMatchesAuthMode(method, authMode) {
101655
+ return (method.kind === "api-key" || method.kind === "manual" ? "api-key" : method.kind === "token" ? "token" : "oauth") === authMode;
101275
101656
  }
101276
- function normalizeEntryTrust(entry) {
101277
- return entry.trusted === true || entry.source === "bundled";
101657
+ function methodRouteIds(method) {
101658
+ return [
101659
+ method.route,
101660
+ method.statusRoute,
101661
+ method.configProviderId
101662
+ ].map((value) => value?.trim().toLowerCase()).filter((value) => Boolean(value));
101278
101663
  }
101279
- function collectProviderConfigs(entry, module) {
101280
- const providers = {};
101281
- const explicitProviderIds = normalizeProviderIds(entry.providerIds);
101282
- const moduleProviders = module.providers ?? module.default?.providers;
101283
- if (moduleProviders) for (const [providerIdRaw, providerConfig] of Object.entries(moduleProviders)) {
101284
- const providerId = normalizeProviderIds([providerIdRaw])[0];
101285
- if (!providerId || !providerConfig) continue;
101286
- providers[providerId] = providerConfig;
101664
+ function credentialRoutesForProvider(store, route) {
101665
+ const normalizedRoute = route.trim().toLowerCase();
101666
+ const manifest = getProviderBrandManifestForRoute(normalizedRoute);
101667
+ const routes = [];
101668
+ const seen = /* @__PURE__ */ new Set();
101669
+ for (const profile of Object.values(store.profiles ?? {})) {
101670
+ const profileProvider = profile.provider.trim().toLowerCase();
101671
+ if (!profileProvider) continue;
101672
+ if (profileProvider !== normalizedRoute) continue;
101673
+ const authMode = authModeForProfileType(profile.type);
101674
+ const method = manifest?.methods.find((candidate) => methodMatchesAuthMode(candidate, authMode) && (methodRouteIds(candidate).includes(profileProvider) || methodRouteIds(candidate).includes(normalizedRoute)));
101675
+ const id = method?.id ?? `${normalizedRoute}:${authMode}`;
101676
+ const key = `${id}:${authMode}`;
101677
+ if (seen.has(key)) continue;
101678
+ seen.add(key);
101679
+ routes.push({
101680
+ id,
101681
+ label: method?.label ?? manifest?.label ?? normalizedRoute,
101682
+ authMode
101683
+ });
101287
101684
  }
101288
- const singleProvider = module.provider ?? module.default?.provider;
101289
- if (singleProvider && explicitProviderIds[0]) providers[explicitProviderIds[0]] = singleProvider;
101290
- return providers;
101291
- }
101292
- function countModels(providers) {
101293
- return Object.values(providers).reduce((total, provider) => total + (Array.isArray(provider.models) ? provider.models.length : 0), 0);
101685
+ return routes;
101294
101686
  }
101295
- function formatCatalogError(error) {
101296
- return error instanceof Error ? error.message : String(error);
101687
+ function discoveryKey(params) {
101688
+ const endpoints = [...params.routes].map((route) => route.trim().toLowerCase()).toSorted().map((route) => {
101689
+ const provider = params.cfg.models?.providers?.[route];
101690
+ return [
101691
+ route,
101692
+ provider?.baseUrl ?? "",
101693
+ provider?.api ?? ""
101694
+ ];
101695
+ });
101696
+ const credentialIdentity = createHash("sha256").update(JSON.stringify(params.store.profiles ?? {})).digest("hex");
101697
+ return JSON.stringify({
101698
+ endpoints,
101699
+ credentialIdentity
101700
+ });
101297
101701
  }
101298
- async function loadProviderExtensionCatalogIndex(params) {
101299
- const entries = params?.entries ?? listBundledProviderExtensionCatalogEntries();
101300
- const includeUntrusted = params?.includeUntrusted === true;
101301
- const providers = {};
101302
- const statuses = [];
101303
- for (const entry of entries) {
101304
- const providerIds = normalizeProviderIds(entry.providerIds);
101305
- const trusted = normalizeEntryTrust(entry);
101306
- if (!trusted && !includeUntrusted) {
101307
- statuses.push({
101308
- id: entry.id,
101309
- source: entry.source,
101310
- trusted,
101311
- providerIds,
101312
- loadedProviderIds: [],
101313
- modelCount: 0,
101314
- status: "skipped-untrusted"
101315
- });
101316
- continue;
101317
- }
101318
- try {
101319
- const loadedProviders = collectProviderConfigs(entry, await entry.load());
101320
- const loadedProviderIds = Object.keys(loadedProviders).toSorted((left, right) => left.localeCompare(right));
101321
- for (const providerId of loadedProviderIds) providers[providerId] = loadedProviders[providerId];
101322
- const modelCount = countModels(loadedProviders);
101323
- statuses.push({
101324
- id: entry.id,
101325
- source: entry.source,
101326
- trusted,
101327
- providerIds,
101328
- loadedProviderIds,
101329
- modelCount,
101330
- status: loadedProviderIds.length > 0 ? "loaded" : "empty"
101331
- });
101332
- } catch (error) {
101333
- statuses.push({
101334
- id: entry.id,
101335
- source: entry.source,
101336
- trusted,
101337
- providerIds,
101338
- loadedProviderIds: [],
101339
- modelCount: 0,
101340
- status: "error",
101341
- error: formatCatalogError(error)
101342
- });
101343
- }
101702
+ async function loadSnapshot(params) {
101703
+ const key = discoveryKey(params);
101704
+ const now = Date.now();
101705
+ if (cache?.key === key && cache.expiresAt > now) return await cache.value;
101706
+ const value = fetchProviderRefreshSnapshotForRoutes({
101707
+ routes: params.routes,
101708
+ env: buildProviderRefreshEnvFromCredentials({
101709
+ env: process.env,
101710
+ authStores: [params.store],
101711
+ modelProviders: params.cfg.models?.providers
101712
+ })
101713
+ });
101714
+ cache = {
101715
+ key,
101716
+ expiresAt: now + DISCOVERY_TTL_MS,
101717
+ value
101718
+ };
101719
+ try {
101720
+ return await value;
101721
+ } catch (error) {
101722
+ if (cache?.value === value) cache = null;
101723
+ throw error;
101344
101724
  }
101725
+ }
101726
+ async function discoverInteractiveRoutes(params) {
101727
+ const discovered = /* @__PURE__ */ new Map();
101728
+ if (params.routes.has("openai-codex")) discovered.set("openai-codex", await discoverOpenAICodexModels({
101729
+ cfg: params.cfg,
101730
+ store: params.store,
101731
+ agentDir: params.agentDir
101732
+ }));
101733
+ if (params.routes.has("github-copilot")) discovered.set("github-copilot", await discoverGitHubCopilotModels({
101734
+ cfg: params.cfg,
101735
+ store: params.store,
101736
+ agentDir: params.agentDir
101737
+ }));
101738
+ return discovered;
101739
+ }
101740
+ function snapshotCapabilities(model) {
101345
101741
  return {
101346
- providers,
101347
- entries: statuses
101742
+ ...model.tools !== void 0 ? { tools: model.tools } : {},
101743
+ ...model.json !== void 0 ? { json: model.json } : {},
101744
+ ...model.audio !== void 0 ? { audio: model.audio } : {},
101745
+ ...model.video !== void 0 ? { video: model.video } : {},
101746
+ ...model.speech !== void 0 ? { speech: model.speech } : {},
101747
+ ...model.thinkingLevels?.length ? { thinkingLevels: model.thinkingLevels } : {},
101748
+ ...model.defaultThinkingLevel ? { defaultThinkingLevel: model.defaultThinkingLevel } : {},
101749
+ ...model.thinkingMode ? { thinkingMode: model.thinkingMode } : {},
101750
+ ...model.reasoningBudgetSupported !== void 0 ? { reasoningBudgetSupported: model.reasoningBudgetSupported } : {}
101348
101751
  };
101349
101752
  }
101350
-
101351
- //#endregion
101352
- //#region src/agents/model-catalog.ts
101353
- const log$6 = createSubsystemLogger("model-catalog");
101354
- let modelCatalogPromise = null;
101355
- let hasLoggedModelCatalogError = false;
101356
- let hasLoggedProviderCatalogError = false;
101357
- const defaultImportPiSdk = () => import("./pi-model-discovery-Buz0JC1Y.js").then((n) => n.a);
101358
- let importPiSdk = defaultImportPiSdk;
101359
- const CODEX_PROVIDER = "openai-codex";
101360
- const OPENAI_PROVIDER = "openai";
101361
- const OPENAI_GPT55_MODEL_ID = "gpt-5.5";
101362
- const OPENAI_GPT54_MODEL_ID = "gpt-5.4";
101363
- const OPENAI_GPT54_MINI_MODEL_ID = "gpt-5.4-mini";
101364
- const OPENAI_GPT54_NANO_MODEL_ID = "gpt-5.4-nano";
101365
- const OPENAI_CODEX_GPT55_MODEL_ID = "gpt-5.5";
101366
- const OPENAI_CODEX_GPT54_MODEL_ID = "gpt-5.4";
101367
- const OPENAI_CODEX_GPT54_MINI_MODEL_ID = "gpt-5.4-mini";
101368
- const OPENAI_CODEX_GPT53_SPARK_MODEL_ID = "gpt-5.3-codex-spark";
101369
- const SYNTHETIC_CATALOG_FALLBACKS = [
101370
- {
101371
- provider: OPENAI_PROVIDER,
101372
- id: OPENAI_GPT55_MODEL_ID,
101373
- templateIds: [OPENAI_GPT54_MODEL_ID, "gpt-5.2"]
101374
- },
101375
- {
101376
- provider: OPENAI_PROVIDER,
101377
- id: OPENAI_GPT54_MODEL_ID,
101378
- templateIds: ["gpt-5.2"]
101379
- },
101380
- {
101381
- provider: OPENAI_PROVIDER,
101382
- id: OPENAI_GPT54_MINI_MODEL_ID,
101383
- templateIds: ["gpt-5-mini"]
101384
- },
101385
- {
101386
- provider: OPENAI_PROVIDER,
101387
- id: OPENAI_GPT54_NANO_MODEL_ID,
101388
- templateIds: ["gpt-5-nano", "gpt-5-mini"]
101389
- },
101390
- {
101391
- provider: CODEX_PROVIDER,
101392
- id: OPENAI_CODEX_GPT55_MODEL_ID,
101393
- templateIds: [OPENAI_CODEX_GPT54_MODEL_ID, OPENAI_CODEX_GPT53_SPARK_MODEL_ID]
101394
- },
101395
- {
101396
- provider: CODEX_PROVIDER,
101397
- id: OPENAI_CODEX_GPT54_MODEL_ID,
101398
- templateIds: [OPENAI_CODEX_GPT53_SPARK_MODEL_ID]
101399
- },
101400
- {
101401
- provider: CODEX_PROVIDER,
101402
- id: OPENAI_CODEX_GPT54_MINI_MODEL_ID,
101403
- templateIds: [OPENAI_CODEX_GPT54_MODEL_ID, OPENAI_CODEX_GPT53_SPARK_MODEL_ID]
101404
- }
101405
- ];
101406
- function applySyntheticCatalogFallbacks(models) {
101407
- const findCatalogEntry = (provider, id) => models.find((entry) => entry.provider.toLowerCase() === provider.toLowerCase() && entry.id.toLowerCase() === id.toLowerCase());
101408
- for (const fallback of SYNTHETIC_CATALOG_FALLBACKS) {
101409
- if (findCatalogEntry(fallback.provider, fallback.id)) continue;
101410
- const template = fallback.templateIds.map((templateId) => findCatalogEntry(fallback.provider, templateId)).find((entry) => entry !== void 0);
101411
- if (!template) continue;
101412
- const { metadata: _ignoredMetadata, ...templateWithoutMetadata } = template;
101413
- models.push({
101414
- ...templateWithoutMetadata,
101415
- id: fallback.id,
101416
- name: fallback.id,
101417
- ...template.metadata ? { metadata: deriveModelMetadata({ model: {
101418
- ...templateWithoutMetadata,
101419
- id: fallback.id,
101420
- name: fallback.id
101421
- } }) } : {}
101422
- });
101423
- }
101753
+ function snapshotHasCapabilityMetadata(model) {
101754
+ return model.input !== void 0 || model.reasoning !== void 0 || model.tools !== void 0 || model.json !== void 0 || model.audio !== void 0 || model.video !== void 0 || model.speech !== void 0 || model.thinkingLevels !== void 0 || model.defaultThinkingLevel !== void 0 || model.thinkingMode !== void 0 || model.reasoningBudgetSupported !== void 0 || model.contextWindow !== void 0 || model.maxTokens !== void 0;
101424
101755
  }
101425
- async function loadProviderPluginCatalogProviders(params) {
101426
- try {
101427
- return await augmentModelCatalogWithProviderPlugins({
101428
- config: params.config,
101429
- agentDir: params.agentDir,
101430
- env: process.env
101431
- });
101432
- } catch (error) {
101433
- if (!hasLoggedProviderCatalogError) {
101434
- hasLoggedProviderCatalogError = true;
101435
- log$6.warn(`Failed to load provider plugin model catalog: ${String(error)}`);
101436
- }
101437
- return {};
101438
- }
101756
+ function snapshotRoutes(snapshot) {
101757
+ const routes = /* @__PURE__ */ new Map();
101758
+ for (const provider of Object.values(snapshot.providers ?? {})) for (const [route, values] of Object.entries(provider.routes ?? {})) routes.set(route.trim().toLowerCase(), values.flatMap((value) => typeof value === "string" ? [{ id: value }] : value?.id?.trim() ? [value] : []));
101759
+ return routes;
101439
101760
  }
101440
- async function loadProviderExtensionCatalogProviders() {
101441
- try {
101442
- return (await loadProviderExtensionCatalogIndex()).providers;
101443
- } catch (error) {
101444
- if (!hasLoggedProviderCatalogError) {
101445
- hasLoggedProviderCatalogError = true;
101446
- log$6.warn(`Failed to load provider extension model catalog: ${String(error)}`);
101447
- }
101448
- return {};
101449
- }
101761
+ function mergeDiscoveredRoute(params) {
101762
+ const baseByKey = new Map(params.catalog.map((model) => [buildModelCatalogMergeKey(model.provider, model.id), model]));
101763
+ const providerConfig = params.cfg.models?.providers?.[params.route];
101764
+ const credentialRoutes = credentialRoutesForProvider(params.store, params.route);
101765
+ return params.discovered.map((model) => {
101766
+ const base = baseByKey.get(buildModelCatalogMergeKey(params.route, model.id));
101767
+ const capabilities = snapshotCapabilities(model);
101768
+ const entry = {
101769
+ id: model.id,
101770
+ name: model.name ?? base?.name ?? model.id,
101771
+ provider: params.route,
101772
+ ...model.contextWindow ?? base?.contextWindow ? { contextWindow: model.contextWindow ?? base?.contextWindow } : {},
101773
+ ...model.maxTokens ?? base?.maxTokens ? { maxTokens: model.maxTokens ?? base?.maxTokens } : {},
101774
+ ...model.reasoning ?? base?.reasoning ? { reasoning: model.reasoning ?? base?.reasoning } : {},
101775
+ input: model.input ?? base?.input ?? ["text"],
101776
+ ...base?.baseUrl ?? providerConfig?.baseUrl ? { baseUrl: base?.baseUrl ?? providerConfig?.baseUrl } : {},
101777
+ ...base?.api ?? providerConfig?.api ? { api: base?.api ?? providerConfig?.api } : {},
101778
+ ...model.price ?? base?.cost ? { cost: model.price ?? base?.cost } : {},
101779
+ ...Object.keys(capabilities).length > 0 ? { capabilities } : {},
101780
+ ...model.responsesLite !== void 0 ? { compat: {
101781
+ ...base?.compat,
101782
+ responsesLite: model.responsesLite
101783
+ } } : base?.compat ? { compat: base.compat } : {},
101784
+ catalogSource: "provider-api"
101785
+ };
101786
+ return {
101787
+ ...entry,
101788
+ metadata: {
101789
+ ...base?.metadata,
101790
+ ...deriveModelMetadata({
101791
+ model: entry,
101792
+ cfg: params.cfg,
101793
+ providerConfig,
101794
+ ...credentialRoutes.length > 0 ? { credentialRoutes } : {},
101795
+ ...snapshotHasCapabilityMetadata(model) ? {
101796
+ capabilitySource: "provider-api",
101797
+ capabilityRetrievedAt: params.retrievedAt
101798
+ } : {}
101799
+ }),
101800
+ retrievedAt: params.retrievedAt
101801
+ }
101802
+ };
101803
+ });
101450
101804
  }
101451
- async function loadModelCatalog(params) {
101452
- if (params?.useCache === false) modelCatalogPromise = null;
101453
- if (modelCatalogPromise) return modelCatalogPromise;
101454
- modelCatalogPromise = (async () => {
101455
- const models = [];
101456
- const sortModels = (entries) => entries.sort((a, b) => {
101457
- const p = a.provider.localeCompare(b.provider);
101458
- if (p !== 0) return p;
101459
- return a.name.localeCompare(b.name);
101805
+ async function applyRuntimeProviderModelDiscovery(params) {
101806
+ const requestedRoutes = new Set([...params.routes].map((route) => route.trim().toLowerCase()).filter(Boolean));
101807
+ if (requestedRoutes.size === 0) return [];
101808
+ const specializedRoutes = new Set([...requestedRoutes].filter((route) => SPECIALIZED_DISCOVERY_ROUTES.has(route)));
101809
+ const providerApiRoutes = [...requestedRoutes].filter((route) => !specializedRoutes.has(route));
101810
+ const interactiveRoutes = await discoverInteractiveRoutes({
101811
+ routes: requestedRoutes,
101812
+ cfg: params.cfg,
101813
+ store: params.store,
101814
+ agentDir: params.agentDir
101815
+ }).catch(() => /* @__PURE__ */ new Map());
101816
+ let discoveredRoutes = new Map(interactiveRoutes);
101817
+ if (providerApiRoutes.length > 0) try {
101818
+ const snapshot = await loadSnapshot({
101819
+ ...params,
101820
+ routes: providerApiRoutes
101460
101821
  });
101461
- try {
101462
- const cfg = params?.config ?? loadConfig();
101463
- await ensureFasedAgentModelsJson(cfg);
101464
- const piSdk = await importPiSdk();
101465
- const agentDir = resolveFasedAgentAgentDir();
101466
- const { join } = await import("node:path");
101467
- const authStorage = piSdk.discoverAuthStorage(agentDir);
101468
- const registry = new piSdk.ModelRegistry(authStorage, join(agentDir, "models.json"));
101469
- const entries = Array.isArray(registry) ? registry : registry.getAll();
101470
- const runtimeModels = [];
101471
- for (const entry of entries) runtimeModels.push(entry);
101472
- const providerPluginProviders = await loadProviderPluginCatalogProviders({
101473
- config: cfg,
101474
- agentDir
101475
- });
101476
- const providerExtensionCatalogProviders = await loadProviderExtensionCatalogProviders();
101477
- models.push(...buildFasedModelCatalogEntries({
101478
- config: cfg,
101479
- runtimeModels,
101480
- providerPluginProviders: {
101481
- ...providerExtensionCatalogProviders,
101482
- ...providerPluginProviders
101483
- },
101484
- includeMetadata: params?.includeMetadata,
101485
- onRuntimeEntryError: (error) => {
101486
- if (!hasLoggedModelCatalogError) {
101487
- hasLoggedModelCatalogError = true;
101488
- log$6.warn(`Failed to read model catalog entry: ${String(error)}`);
101489
- }
101490
- }
101491
- }));
101492
- applySyntheticCatalogFallbacks(models);
101493
- if (models.length === 0) modelCatalogPromise = null;
101494
- return sortModels(models);
101495
- } catch (error) {
101496
- if (!hasLoggedModelCatalogError) {
101497
- hasLoggedModelCatalogError = true;
101498
- log$6.warn(`Failed to load model catalog: ${String(error)}`);
101499
- }
101500
- modelCatalogPromise = null;
101501
- if (models.length > 0) return sortModels(models);
101502
- return [];
101503
- }
101504
- })();
101505
- return modelCatalogPromise;
101822
+ discoveredRoutes = new Map([...discoveredRoutes, ...snapshotRoutes(snapshot)]);
101823
+ } catch {}
101824
+ const retrievedAt = (/* @__PURE__ */ new Date()).toISOString();
101825
+ const authoritativeRoutes = new Set([...discoveredRoutes.keys()].filter((route) => requestedRoutes.has(route)));
101826
+ const replacedRoutes = new Set(providerApiRoutes);
101827
+ for (const route of specializedRoutes) replacedRoutes.add(route);
101828
+ const retained = params.catalog.filter((model) => !replacedRoutes.has(model.provider.trim().toLowerCase()));
101829
+ const discovered = [...authoritativeRoutes].flatMap((route) => mergeDiscoveredRoute({
101830
+ route,
101831
+ discovered: discoveredRoutes.get(route) ?? [],
101832
+ catalog: params.catalog,
101833
+ cfg: params.cfg,
101834
+ store: params.store,
101835
+ retrievedAt
101836
+ }));
101837
+ return [...retained, ...discovered].toSorted((left, right) => left.provider.localeCompare(right.provider) || (left.metadata?.recommendationRank ?? Number.MAX_SAFE_INTEGER) - (right.metadata?.recommendationRank ?? Number.MAX_SAFE_INTEGER) || left.name.localeCompare(right.name));
101506
101838
  }
101507
- /**
101508
- * Check if a model supports image input based on its catalog entry.
101509
- */
101510
- function modelSupportsVision(entry) {
101511
- return entry?.input?.includes("image") ?? false;
101839
+ function filterCatalogToAuthoritativeAvailability(catalog, store) {
101840
+ const specializedProviders = store ? new Set(Object.values(store.profiles ?? {}).map((profile) => profile.provider.trim().toLowerCase()).filter((provider) => SPECIALIZED_DISCOVERY_ROUTES.has(provider))) : /* @__PURE__ */ new Set();
101841
+ const byProvider = /* @__PURE__ */ new Map();
101842
+ for (const model of catalog) {
101843
+ const provider = model.provider.trim().toLowerCase();
101844
+ byProvider.set(provider, [...byProvider.get(provider) ?? [], model]);
101845
+ }
101846
+ return [...byProvider.entries()].flatMap(([provider, models]) => {
101847
+ if (models.some((model) => model.catalogSource === "provider-api")) return models.filter((model) => model.catalogSource === "provider-api");
101848
+ if (specializedProviders.has(provider)) return models.filter((model) => model.catalogSource === "runtime" || model.catalogSource === "provider-api");
101849
+ return models;
101850
+ });
101512
101851
  }
101513
- /**
101514
- * Find a model in the catalog by provider and model ID.
101515
- */
101516
- function findModelInCatalog(catalog, provider, modelId) {
101517
- const normalizedProvider = normalizeModelCatalogProviderId(provider);
101518
- const normalizedModelId = modelId.toLowerCase().trim();
101519
- return catalog.find((entry) => normalizeModelCatalogProviderId(entry.provider) === normalizedProvider && entry.id.toLowerCase() === normalizedModelId);
101852
+
101853
+ //#endregion
101854
+ //#region src/agents/authenticated-model-catalog.ts
101855
+ async function resolveAuthenticatedModelCatalog(params) {
101856
+ const initialScope = buildCredentialScopedAllowedModelSet({
101857
+ cfg: params.cfg,
101858
+ catalog: params.catalog,
101859
+ defaultProvider: params.defaultProvider,
101860
+ store: params.store
101861
+ });
101862
+ const discoveredCatalog = filterCatalogToAuthoritativeAvailability(await applyRuntimeProviderModelDiscovery({
101863
+ cfg: params.cfg,
101864
+ store: params.store,
101865
+ routes: initialScope.usableProviders,
101866
+ catalog: initialScope.usableCatalog,
101867
+ agentDir: params.agentDir
101868
+ }), params.store);
101869
+ return buildCredentialScopedAllowedModelSet({
101870
+ cfg: params.cfg,
101871
+ catalog: discoveredCatalog,
101872
+ defaultProvider: params.defaultProvider,
101873
+ storedProviders: initialScope.usableProviders
101874
+ });
101520
101875
  }
101521
101876
 
101522
101877
  //#endregion
@@ -106820,19 +107175,26 @@ function usesCodexResponsesLite(model) {
106820
107175
  }
106821
107176
  function createCodexResponsesLiteWrapper(baseStreamFn, params) {
106822
107177
  const underlying = baseStreamFn ?? streamSimple;
106823
- const appServer = createOpenAICodexAppServerStreamFn({ resolveToken: async () => {
106824
- if (params?.resolvedApiKey?.trim()) return params.resolvedApiKey.trim();
106825
- const agentDir = params?.agentDir ?? resolveFasedAgentAgentDir();
106826
- const store = ensureAuthProfileStore(agentDir, { allowKeychainPrompt: false });
106827
- const profileId = listProfilesForProvider(store, "openai-codex")[0];
106828
- if (!profileId) return;
106829
- return (await resolveApiKeyForProfile({
106830
- cfg: params?.cfg ?? {},
106831
- store,
106832
- profileId,
106833
- agentDir
106834
- }))?.apiKey;
106835
- } });
107178
+ const appServer = createOpenAICodexAppServerStreamFn({
107179
+ resolveExecutable: async () => {
107180
+ const runtime = await ensureOpenAICodexRuntimeComponent({ config: params?.cfg ?? loadConfig() });
107181
+ if (runtime.installed) await writeConfigFile(runtime.config);
107182
+ return runtime.executable;
107183
+ },
107184
+ resolveToken: async () => {
107185
+ if (params?.resolvedApiKey?.trim()) return params.resolvedApiKey.trim();
107186
+ const agentDir = params?.agentDir ?? resolveFasedAgentAgentDir();
107187
+ const store = ensureAuthProfileStore(agentDir, { allowKeychainPrompt: false });
107188
+ const profileId = listProfilesForProvider(store, "openai-codex")[0];
107189
+ if (!profileId) return;
107190
+ return (await resolveApiKeyForProfile({
107191
+ cfg: params?.cfg ?? {},
107192
+ store,
107193
+ profileId,
107194
+ agentDir
107195
+ }))?.apiKey;
107196
+ }
107197
+ });
106836
107198
  return (model, context, options) => {
106837
107199
  if (!usesCodexResponsesLite(model)) return underlying(model, context, options);
106838
107200
  return appServer(model, context, options);
@@ -107600,14 +107962,14 @@ function createCacheTrace(params) {
107600
107962
  //#region src/agents/embedded-pi-mcp.ts
107601
107963
  const BUNDLE_MCP_FILENAMES = [".mcp.json"];
107602
107964
  function normalizeConfiguredMcpServers(value) {
107603
- if (!isRecord$4(value)) return {};
107965
+ if (!isRecord$5(value)) return {};
107604
107966
  const result = {};
107605
- for (const [serverName, server] of Object.entries(value)) if (isRecord$4(server)) result[serverName] = { ...server };
107967
+ for (const [serverName, server] of Object.entries(value)) if (isRecord$5(server)) result[serverName] = { ...server };
107606
107968
  return result;
107607
107969
  }
107608
107970
  function extractMcpServerMap(raw) {
107609
- if (!isRecord$4(raw)) return {};
107610
- return normalizeConfiguredMcpServers(isRecord$4(raw.mcpServers) ? raw.mcpServers : isRecord$4(raw.servers) ? raw.servers : raw);
107971
+ if (!isRecord$5(raw)) return {};
107972
+ return normalizeConfiguredMcpServers(isRecord$5(raw.mcpServers) ? raw.mcpServers : isRecord$5(raw.servers) ? raw.servers : raw);
107611
107973
  }
107612
107974
  function expandBundlePath(value, rootDir) {
107613
107975
  return value.split("${CLAUDE_PLUGIN_ROOT}").join(rootDir);
@@ -107627,7 +107989,7 @@ function absolutizeBundleMcpServer(params) {
107627
107989
  if (typeof next.cwd === "string") next.cwd = normalizePathLike(next.cwd, params.baseDir, params.rootDir);
107628
107990
  if (typeof next.workingDirectory === "string") next.workingDirectory = normalizePathLike(next.workingDirectory, params.baseDir, params.rootDir);
107629
107991
  if (Array.isArray(next.args)) next.args = next.args.map((entry) => typeof entry === "string" ? normalizePathLike(entry, params.baseDir, params.rootDir) : entry);
107630
- if (isRecord$4(next.env)) next.env = Object.fromEntries(Object.entries(next.env).map(([key, value]) => [key, typeof value === "string" ? normalizePathLike(value, params.baseDir, params.rootDir) : value]));
107992
+ if (isRecord$5(next.env)) next.env = Object.fromEntries(Object.entries(next.env).map(([key, value]) => [key, typeof value === "string" ? normalizePathLike(value, params.baseDir, params.rootDir) : value]));
107631
107993
  return next;
107632
107994
  }
107633
107995
  function readBundleMcpFile(params) {
@@ -116050,7 +116412,7 @@ const signalOnboardingAdapter = {
116050
116412
  //#endregion
116051
116413
  //#region src/channels/plugins/status-issues/bluebubbles.ts
116052
116414
  function readBlueBubblesAccountStatus(value) {
116053
- if (!isRecord$4(value)) return null;
116415
+ if (!isRecord$5(value)) return null;
116054
116416
  return {
116055
116417
  accountId: value.accountId,
116056
116418
  enabled: value.enabled,
@@ -116062,7 +116424,7 @@ function readBlueBubblesAccountStatus(value) {
116062
116424
  };
116063
116425
  }
116064
116426
  function readBlueBubblesProbeResult(value) {
116065
- if (!isRecord$4(value)) return null;
116427
+ if (!isRecord$5(value)) return null;
116066
116428
  return {
116067
116429
  ok: typeof value.ok === "boolean" ? value.ok : void 0,
116068
116430
  status: typeof value.status === "number" ? value.status : null,
@@ -116151,4 +116513,4 @@ const LineConfigSchema = LineCommonConfigSchema.extend({
116151
116513
  }).strict();
116152
116514
 
116153
116515
  //#endregion
116154
- export { dispatchReplyWithBufferedBlockDispatcher as $, enforceWalletCustodyForAutonomousSend as $n, resolveWebhookTargets as $r, normalizeSlackSlug as $t, parseTtsDirectives as A, canonicalizeRealtimeTranscriptionProviderId as Ai, sendJson as An, loadOrCreateDeviceIdentity as Ar, registerUnhandledRejectionHandler as At, normalizeAccountId as B, extractDashscopeVideoUrls as Bi, requestBodyErrorToText as Bn, createInfoCard as Br, hasControlCommand as Bt, resolveEffectiveToolInventory as C, resolveCommandAuthorizedFromAuthorizers as Ci, agentCommand as Cn, emitAgentEvent as Cr, buildProviderRegistry as Ct, runEmbeddedPiAgent as D, getRealtimeVoiceProvider as Di, createDefaultDeps as Dn, GatewayClient as Dr, resolveMediaAttachmentLocalRoots as Dt, ACPX_PUSH_TEST_WRAPPER_ID as E, canonicalizeRealtimeVoiceProviderId as Ei, AcpRuntimeError as En, callGatewayScoped as Er, resolveAutoImageModel as Et, issuePairingChallenge as F, DEFAULT_VIDEO_GENERATION_TIMEOUT_MS as Fi, RequestBodyLimitError as Fn, processLineMessage as Fr, extractFileContentFromSource as Ft, logTypingFailure as G, resolveAllowlistMatchSimple as Gi, resolveAgentAvatar as Gn, createLoggerBackedRuntime as Gr, buildCommandsMessage as Gt, resolveLineAccount as H, resolveVideoGenerationReferenceUrls as Hi, resolveChannelMediaMaxBytes as Hn, resolveTelegramReactionLevel as Hr, isAbortRequestText as Ht, createTypingCallbacks as I, DEFAULT_VIDEO_RESOLUTION_TO_SIZE as Ii, installRequestBodyLimitGuard as In, stripMarkdown as Ir, extractImageContentFromSource as It, sleepWithAbort as J, BLUEBUBBLES_GROUP_ACTIONS as Ji, DEFAULT_FEDERATION_BASE_URL as Jn, pruneMapToMaxSize as Jr, normalizeGroupActivation as Jt, buildPairingReply as K, BLUEBUBBLES_ACTIONS as Ki, readWalletStatusSnapshot as Kn, createPersistentDedupe as Kr, buildCommandsMessagePaginated as Kt, resolveMentionGating as L, buildDashscopeVideoGenerationInput as Li, isRequestBodyLimitError as Ln, createReceiptCard as Lr, normalizeMimeList as Lt, findModelInCatalog as M, listRealtimeTranscriptionProviders as Mi, writeDone as Mn, signDevicePayload as Mr, DEFAULT_INPUT_IMAGE_MIMES as Mt, loadModelCatalog as N, normalizeRealtimeTranscriptionProviderId as Ni, DEFAULT_WEBHOOK_BODY_TIMEOUT_MS as Nn, verifyDeviceSignature as Nr, DEFAULT_INPUT_MAX_REDIRECTS as Nt, resolveTtsConfig as O, listRealtimeVoiceProviders as Oi, resolveAgentIdForRequest as On, ErrorCodes as Or, runCapability as Ot, modelSupportsVision as P, DEFAULT_VIDEO_GENERATION_DURATION_SECONDS as Pi, DEFAULT_WEBHOOK_MAX_BODY_BYTES as Pn, hasMarkdownToConvert as Pr, DEFAULT_INPUT_TIMEOUT_MS as Pt, shouldAckReactionForWhatsApp as Q, resolveFederationHandle as Qn, resolveSingleWebhookTargetAsync as Qr, normalizeAllowListLower as Qt, resolveMentionGatingWithBypass as R, buildDashscopeVideoGenerationParameters as Ri, readJsonBodyWithLimit as Rn, createActionCard as Rr, resolveInputFileLimits as Rt, getPublicGatewayIdentity as S, resolveEffectiveAllowFromLists as Si, resolveAssistantStreamDeltaText as Sn, tryResolveSatRuntimeIds as Sr, resolveChannelConfigWrites as St, ACPX_PUSH_TEST_METHOD as T, evaluateSenderGroupAccess as Ti, unregisterAcpRuntimeBackend as Tn, buildGatewayConnectionDetails as Tr, normalizeMediaAttachments as Tt, logAckFailure as U, registerPluginHttpRoute as Ui, runFederationAutoConnectOnce as Un, resolveTelegramInlineButtonsScope as Ur, subagent_registry_exports as Ut, resolveDefaultLineAccountId as V, pollDashscopeVideoTaskUntilComplete as Vi, deliver_exports as Vn, createListCard as Vr, shouldComputeCommandAuthorized as Vt, logInboundDrop as W, formatAllowlistMatchMeta as Wi, startFederationAutoConnect as Wn, waitForAbortSignal as Wr, enqueueSystemEvent as Wt, removeAckReactionAfterReply as X, resolveAgentPublicOrigin as Xn, rejectNonPostWebhookRequest as Xr, allowListMatches as Xt, recordInboundSession as Y, CHANNEL_MESSAGE_ACTION_NAMES as Yi, normalizeHandle as Yn, registerWebhookTarget as Yr, parseActivationCommand as Yt, shouldAckReaction as Z, resolveFederationBaseUrl as Zn, resolveSingleWebhookTarget as Zr, normalizeAllowList$2 as Zt, getGatewayUpdateStatus as _, resolveSenderCommandAuthorization as _i, recordPendingHistoryEntry as _n, SAT_RUNTIME_DEFAULTS as _r, getModelsPageSize as _t, normalizeIMessageMessagingTarget as a, isHttpsUrlAllowedByHostnameSuffixAllowlist as ai, isInsideCode as an, readWalletProviderRegistry as ar, formatInboundFromLabel as at, getStatusSummary as b, resolveDmGroupAccessWithCommandGate as bi, matchesMentionWithExplicit as bn, resolveSatMintProgramIdFromEnv as br, formatDurationPrecise as bt, addAllowlistUserEntriesFromConfigEntry as c, formatTextWithAttachmentLinks as ci, wrapExternalContent as cn, callLocalSocketSigner as cr, createReplyDispatcherWithTyping as ct, mergeAllowlist as d, buildOauthProviderAuthResult as di, DEFAULT_GROUP_HISTORY_LIMIT as dn, resolveLocalSignerSocketPath as dr, resolveStoredModelOverride as dt, normalizeWebhookPath as ei, resolveSlackAllowListMatch as en, createWalletProviderAdapter as er, dispatchReplyWithDispatcher as et, patchAllowlistUsersInConfigEntries as f, createScopedPairingAccess as fi, buildHistoryContextFromEntries as fn, resolveWalletRuntimeConfig as fr, buildModelsProviderData as ft, buildCommandsListResult as g, resolveChannelAccountConfigBasePath as gi, evictOldHistoryKeys as gn, syncSatMainnetRuntimeIds as gr, calculateTotalPages as gt, getAcpStatusSnapshot as h, chunkTextForOutbound as hi, clearHistoryEntriesIfEnabled as hn, getSatMainnetSyncStatus as hr, buildProviderKeyboard as ht, looksLikeIMessageTargetId as i, buildHostnameAllowlistPolicyFromSuffixAllowlist as ii, findCodeRegions as in, resolveWalletRolePolicyProfile as ir, formatInboundEnvelope as it, resolveModel as j, getRealtimeTranscriptionProvider as ji, setSseHeaders as jn, publicKeyRawBase64UrlFromPem as jr, DEFAULT_INPUT_IMAGE_MAX_BYTES as jt, textToSpeech as k, normalizeRealtimeVoiceProviderId as ki, resolveSessionKey as kn, errorShape as kr, isAudioAttachment as kt, buildAllowlistResolutionSummary as l, resolveOutboundMediaUrls as li, handleGatewayPostJsonEndpoint as ln, probeLocalSocketSignerHealth as lr, EmbeddedBlockChunker as lt, pushHandlers as m, buildAgentMediaPayload as mi, clearHistoryEntries as mn, buildAttestation as mr, buildModelsKeyboard as mt, collectBlueBubblesStatusIssues as n, extractToolSend as ni, formatReasoningMessage as nn, loadWalletProviderSecret as nr, createInboundDebouncer as nt, imessageOnboardingAdapter as o, normalizeHostnameSuffixAllowlist as oi, optionalStringEnum as on, resolveWalletUserRole as or, resolveEnvelopeFormatOptions as ot, summarizeMapping as p, fetchWithBearerAuthScopeFallback as pi, buildPendingHistoryContextFromMap as pn, fetchSolanaWalletAssetsViaRpc as pr, formatModelsAvailableHeader as pt, computeBackoff as q, BLUEBUBBLES_ACTION_NAMES as qi, createOrExecuteWalletSend as qn, createDedupeCache as qr, buildHelpMessage as qt, signalOnboardingAdapter as r, withTempDownloadPath as ri, stripReasoningTagsFromText as rn, resolveWalletPolicyConfig as rr, resolveInboundDebounceMs as rt, buildMediaPayload as s, createNormalizedOutboundDeliverer as si, stringEnum as sn, upsertNamedWallet as sr, dispatchInboundMessage as st, LineConfigSchema as t, resolveWebhookPath as ti, resolveSlackUserAllowed as tn, resolveWalletProviderId as tr, provider_dispatcher_exports as tt, canonicalizeAllowlistWithResolvedIds as u, sendMediaWithLeadingCaption as ui, buildAgentMessageFromConversationEntries as un, requireLocalSocketSignerPath as ur, getReplyFromConfig as ut, buildModelCatalogStatus as v, DM_GROUP_ACCESS_REASON as vi, recordPendingHistoryEntryIfEnabled as vn, resolveSatBondProgramIdFromEnv as vr, parseModelCallbackData as vt, executeAcpxPushTestRequest as w, resolveControlCommandGate as wi, registerAcpRuntimeBackend as wn, onAgentEvent as wr, createMediaAttachmentCache as wt, isDangerousNameMatchingEnabled as x, resolveDmGroupAccessWithLists as xi, normalizeMentionText as xn, resolveSatProgramIdFromEnv as xr, formatDurationSeconds as xt, loadGatewayModelCatalog as y, readStoreAllowFromForDmPolicy as yi, buildMentionRegexes as yn, resolveSatMintAddressFromEnv as yr, buildCommandsPaginationKeyboard as yt, listLineAccountIds as z, downloadDashscopeGeneratedVideos as zi, readRequestBodyWithLimit as zn, createImageCard as zr, image_exports as zt };
116516
+ export { createInboundDebouncer as $, enforceWalletCustodyForAutonomousSend as $n, resolveWebhookTargets as $r, formatReasoningMessage as $t, parseTtsDirectives as A, canonicalizeRealtimeTranscriptionProviderId as Ai, sendJson as An, loadOrCreateDeviceIdentity as Ar, DEFAULT_INPUT_MAX_REDIRECTS as At, logAckFailure as B, extractDashscopeVideoUrls as Bi, requestBodyErrorToText as Bn, createInfoCard as Br, subagent_registry_exports as Bt, resolveEffectiveToolInventory as C, resolveCommandAuthorizedFromAuthorizers as Ci, modelSupportsVision as Cn, emitAgentEvent as Cr, resolveAutoImageModel as Ct, runEmbeddedPiAgent as D, getRealtimeVoiceProvider as Di, createDefaultDeps as Dn, GatewayClient as Dr, registerUnhandledRejectionHandler as Dt, ACPX_PUSH_TEST_WRAPPER_ID as E, canonicalizeRealtimeVoiceProviderId as Ei, AcpRuntimeError as En, callGatewayScoped as Er, isAudioAttachment as Et, resolveMentionGatingWithBypass as F, DEFAULT_VIDEO_GENERATION_TIMEOUT_MS as Fi, RequestBodyLimitError as Fn, processLineMessage as Fr, resolveInputFileLimits as Ft, sleepWithAbort as G, resolveAllowlistMatchSimple as Gi, resolveAgentAvatar as Gn, createLoggerBackedRuntime as Gr, normalizeGroupActivation as Gt, logTypingFailure as H, resolveVideoGenerationReferenceUrls as Hi, resolveChannelMediaMaxBytes as Hn, resolveTelegramReactionLevel as Hr, buildCommandsMessage as Ht, listLineAccountIds as I, DEFAULT_VIDEO_RESOLUTION_TO_SIZE as Ii, installRequestBodyLimitGuard as In, stripMarkdown as Ir, image_exports as It, shouldAckReaction as J, BLUEBUBBLES_GROUP_ACTIONS as Ji, DEFAULT_FEDERATION_BASE_URL as Jn, pruneMapToMaxSize as Jr, normalizeAllowList$2 as Jt, recordInboundSession as K, BLUEBUBBLES_ACTIONS as Ki, readWalletStatusSnapshot as Kn, createPersistentDedupe as Kr, parseActivationCommand as Kt, normalizeAccountId as L, buildDashscopeVideoGenerationInput as Li, isRequestBodyLimitError as Ln, createReceiptCard as Lr, hasControlCommand as Lt, issuePairingChallenge as M, listRealtimeTranscriptionProviders as Mi, writeDone as Mn, signDevicePayload as Mr, extractFileContentFromSource as Mt, createTypingCallbacks as N, normalizeRealtimeTranscriptionProviderId as Ni, DEFAULT_WEBHOOK_BODY_TIMEOUT_MS as Nn, verifyDeviceSignature as Nr, extractImageContentFromSource as Nt, resolveTtsConfig as O, listRealtimeVoiceProviders as Oi, resolveAgentIdForRequest as On, ErrorCodes as Or, DEFAULT_INPUT_IMAGE_MAX_BYTES as Ot, resolveMentionGating as P, DEFAULT_VIDEO_GENERATION_DURATION_SECONDS as Pi, DEFAULT_WEBHOOK_MAX_BODY_BYTES as Pn, hasMarkdownToConvert as Pr, normalizeMimeList as Pt, provider_dispatcher_exports as Q, resolveFederationHandle as Qn, resolveSingleWebhookTargetAsync as Qr, resolveSlackUserAllowed as Qt, resolveDefaultLineAccountId as R, buildDashscopeVideoGenerationParameters as Ri, readJsonBodyWithLimit as Rn, createActionCard as Rr, shouldComputeCommandAuthorized as Rt, getPublicGatewayIdentity as S, resolveEffectiveAllowFromLists as Si, loadModelCatalog as Sn, tryResolveSatRuntimeIds as Sr, normalizeMediaAttachments as St, ACPX_PUSH_TEST_METHOD as T, evaluateSenderGroupAccess as Ti, unregisterAcpRuntimeBackend as Tn, buildGatewayConnectionDetails as Tr, runCapability as Tt, buildPairingReply as U, registerPluginHttpRoute as Ui, runFederationAutoConnectOnce as Un, resolveTelegramInlineButtonsScope as Ur, buildCommandsMessagePaginated as Ut, logInboundDrop as V, pollDashscopeVideoTaskUntilComplete as Vi, deliver_exports as Vn, createListCard as Vr, enqueueSystemEvent as Vt, computeBackoff as W, formatAllowlistMatchMeta as Wi, startFederationAutoConnect as Wn, waitForAbortSignal as Wr, buildHelpMessage as Wt, dispatchReplyWithBufferedBlockDispatcher as X, resolveAgentPublicOrigin as Xn, rejectNonPostWebhookRequest as Xr, normalizeSlackSlug as Xt, shouldAckReactionForWhatsApp as Y, CHANNEL_MESSAGE_ACTION_NAMES as Yi, normalizeHandle as Yn, registerWebhookTarget as Yr, normalizeAllowListLower as Yt, dispatchReplyWithDispatcher as Z, resolveFederationBaseUrl as Zn, resolveSingleWebhookTarget as Zr, resolveSlackAllowListMatch as Zt, getGatewayUpdateStatus as _, resolveSenderCommandAuthorization as _i, matchesMentionWithExplicit as _n, SAT_RUNTIME_DEFAULTS as _r, formatDurationPrecise as _t, normalizeIMessageMessagingTarget as a, isHttpsUrlAllowedByHostnameSuffixAllowlist as ai, wrapExternalContent as an, readWalletProviderRegistry as ar, createReplyDispatcherWithTyping as at, getStatusSummary as b, resolveDmGroupAccessWithCommandGate as bi, agentCommand as bn, resolveSatMintProgramIdFromEnv as br, buildProviderRegistry as bt, addAllowlistUserEntriesFromConfigEntry as c, formatTextWithAttachmentLinks as ci, DEFAULT_GROUP_HISTORY_LIMIT as cn, callLocalSocketSigner as cr, resolveStoredModelOverride as ct, mergeAllowlist as d, buildOauthProviderAuthResult as di, clearHistoryEntries as dn, resolveLocalSignerSocketPath as dr, buildModelsKeyboard as dt, normalizeWebhookPath as ei, stripReasoningTagsFromText as en, createWalletProviderAdapter as er, resolveInboundDebounceMs as et, patchAllowlistUsersInConfigEntries as f, createScopedPairingAccess as fi, clearHistoryEntriesIfEnabled as fn, resolveWalletRuntimeConfig as fr, buildProviderKeyboard as ft, buildCommandsListResult as g, resolveChannelAccountConfigBasePath as gi, buildMentionRegexes as gn, syncSatMainnetRuntimeIds as gr, buildCommandsPaginationKeyboard as gt, getAcpStatusSnapshot as h, chunkTextForOutbound as hi, recordPendingHistoryEntryIfEnabled as hn, getSatMainnetSyncStatus as hr, parseModelCallbackData as ht, looksLikeIMessageTargetId as i, buildHostnameAllowlistPolicyFromSuffixAllowlist as ii, stringEnum as in, resolveWalletRolePolicyProfile as ir, dispatchInboundMessage as it, resolveModel as j, getRealtimeTranscriptionProvider as ji, setSseHeaders as jn, publicKeyRawBase64UrlFromPem as jr, DEFAULT_INPUT_TIMEOUT_MS as jt, textToSpeech as k, normalizeRealtimeVoiceProviderId as ki, resolveSessionKey as kn, errorShape as kr, DEFAULT_INPUT_IMAGE_MIMES as kt, buildAllowlistResolutionSummary as l, resolveOutboundMediaUrls as li, buildHistoryContextFromEntries as ln, probeLocalSocketSignerHealth as lr, buildModelsProviderData as lt, pushHandlers as m, buildAgentMediaPayload as mi, recordPendingHistoryEntry as mn, buildAttestation as mr, getModelsPageSize as mt, collectBlueBubblesStatusIssues as n, extractToolSend as ni, isInsideCode as nn, loadWalletProviderSecret as nr, formatInboundFromLabel as nt, imessageOnboardingAdapter as o, normalizeHostnameSuffixAllowlist as oi, handleGatewayPostJsonEndpoint as on, resolveWalletUserRole as or, EmbeddedBlockChunker as ot, summarizeMapping as p, fetchWithBearerAuthScopeFallback as pi, evictOldHistoryKeys as pn, fetchSolanaWalletAssetsViaRpc as pr, calculateTotalPages as pt, removeAckReactionAfterReply as q, BLUEBUBBLES_ACTION_NAMES as qi, createOrExecuteWalletSend as qn, createDedupeCache as qr, allowListMatches as qt, signalOnboardingAdapter as r, withTempDownloadPath as ri, optionalStringEnum as rn, resolveWalletPolicyConfig as rr, resolveEnvelopeFormatOptions as rt, buildMediaPayload as s, createNormalizedOutboundDeliverer as si, buildAgentMessageFromConversationEntries as sn, upsertNamedWallet as sr, getReplyFromConfig as st, LineConfigSchema as t, resolveWebhookPath as ti, findCodeRegions as tn, resolveWalletProviderId as tr, formatInboundEnvelope as tt, canonicalizeAllowlistWithResolvedIds as u, sendMediaWithLeadingCaption as ui, buildPendingHistoryContextFromMap as un, requireLocalSocketSignerPath as ur, formatModelsAvailableHeader as ut, buildModelCatalogStatus as v, DM_GROUP_ACCESS_REASON as vi, normalizeMentionText as vn, resolveSatBondProgramIdFromEnv as vr, formatDurationSeconds as vt, executeAcpxPushTestRequest as w, resolveControlCommandGate as wi, registerAcpRuntimeBackend as wn, onAgentEvent as wr, resolveMediaAttachmentLocalRoots as wt, isDangerousNameMatchingEnabled as x, resolveDmGroupAccessWithLists as xi, findModelInCatalog as xn, resolveSatProgramIdFromEnv as xr, createMediaAttachmentCache as xt, loadGatewayModelCatalog as y, readStoreAllowFromForDmPolicy as yi, resolveAssistantStreamDeltaText as yn, resolveSatMintAddressFromEnv as yr, resolveChannelConfigWrites as yt, resolveLineAccount as z, downloadDashscopeGeneratedVideos as zi, readRequestBodyWithLimit as zn, createImageCard as zr, isAbortRequestText as zt };