@earendil-works/pi-coding-agent 1.0.4 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (189) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/dist/bundle/chunks/{anthropic-messages-Y22YDKSW.js → anthropic-messages-KT2ID7DZ.js} +1 -1
  3. package/dist/bundle/chunks/anthropic.js +1 -1
  4. package/dist/bundle/chunks/{azure-openai-responses-YJDJIIDQ.js → azure-openai-responses-6A4PNZTH.js} +1 -1
  5. package/dist/bundle/chunks/bedrock-converse-stream.js +2 -2
  6. package/dist/bundle/chunks/chunk-33CRHCAK.js +2 -0
  7. package/dist/bundle/chunks/{chunk-F4TCZWQO.js → chunk-BK6FEHYX.js} +3 -3
  8. package/dist/bundle/chunks/chunk-CH4ZBH45.js +11 -0
  9. package/dist/bundle/chunks/{chunk-XXKX4I4Z.js → chunk-GXLAGZ3Z.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-KIPSWGXN.js → chunk-HKYL362W.js} +1 -1
  11. package/dist/bundle/chunks/chunk-LPXNMA2W.js +2 -0
  12. package/dist/bundle/chunks/{chunk-TAOL3JFA.js → chunk-LTSARG5Q.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-VLMAON6X.js → chunk-MXTZIDYW.js} +3 -3
  14. package/dist/bundle/chunks/chunk-O7YIWAPD.js +2 -0
  15. package/dist/bundle/chunks/{chunk-H33F2TZD.js → chunk-OIM2DMFI.js} +66 -59
  16. package/dist/bundle/chunks/{chunk-64GOPQSC.js → chunk-OTL6MGLJ.js} +3 -3
  17. package/dist/bundle/chunks/{chunk-LD2P6SFZ.js → chunk-PMRZO46Y.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-FKGBRPJC.js → chunk-SYCGMWFH.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-YKYP4C4A.js → chunk-UH5J7I7X.js} +3 -3
  20. package/dist/bundle/chunks/{chunk-WE4MXUQS.js → chunk-VLRCF7MR.js} +1 -1
  21. package/dist/bundle/chunks/chunk-W5MPVSHA.js +82 -0
  22. package/dist/bundle/chunks/chunk-Y4NYF362.js +2 -0
  23. package/dist/bundle/chunks/{cli-FRW732V6.js → cli-OQYLWLA3.js} +2 -2
  24. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-U3AH4ODQ.js +2 -0
  25. package/dist/bundle/chunks/codemode-worker.js +2 -2
  26. package/dist/bundle/chunks/{easter-egg-3d-GBYHZI2E.js → easter-egg-3d-TQFQS342.js} +1 -1
  27. package/dist/bundle/chunks/{execute-MNHU53Y5.js → execute-7IRB5TUX.js} +11 -5
  28. package/dist/bundle/chunks/github-copilot.js +1 -1
  29. package/dist/bundle/chunks/{google-generative-ai-XMFHGQC5.js → google-generative-ai-X2VFFS4I.js} +1 -1
  30. package/dist/bundle/chunks/{google-vertex-4XRRNP74.js → google-vertex-KMGHFTSP.js} +1 -1
  31. package/dist/bundle/chunks/image-resize-worker.js +1 -1
  32. package/dist/bundle/chunks/{llama-cpp-classify-XT44PI3C.js → llama-cpp-classify-FYN623RH.js} +2 -2
  33. package/dist/bundle/chunks/{mistral-conversations-Q22M3IBG.js → mistral-conversations-PRZLM26U.js} +2 -2
  34. package/dist/bundle/chunks/openai-chatgpt.js +1 -1
  35. package/dist/bundle/chunks/{openai-codex-responses-4MYQSO5E.js → openai-codex-responses-ZSLJZYOE.js} +2 -2
  36. package/dist/bundle/chunks/openai-codex.js +1 -1
  37. package/dist/bundle/chunks/{openai-completions-OSRCWAAA.js → openai-completions-WWQW7S3V.js} +1 -1
  38. package/dist/bundle/chunks/openai-decisions-QLZKZLAK.js +5 -0
  39. package/dist/bundle/chunks/{openai-responses-UHF3DHNG.js → openai-responses-KV7QHJY6.js} +1 -1
  40. package/dist/bundle/chunks/{openrouter-images-ZVXWCSIM.js → openrouter-images-DUPG5DZO.js} +1 -1
  41. package/dist/bundle/chunks/{pi-messages-TM5SOOIW.js → pi-messages-YHKPQIHC.js} +1 -1
  42. package/dist/bundle/chunks/{runtime-FW2HXAJ6.js → runtime-ROGZ2EXI.js} +1 -1
  43. package/dist/bundle/chunks/typesafe-system-one-B4NNEG67.js +2 -0
  44. package/dist/bundle/chunks/{virtual-modules-LQIMBBGM.js → virtual-modules-4YN2GNVW.js} +1 -1
  45. package/dist/bundle/cli-runtime.js +1 -1
  46. package/dist/bundle/index.js +1 -1
  47. package/dist/bundle/rpc-entry.js +1 -1
  48. package/dist/cli/args.d.ts +1 -1
  49. package/dist/cli/args.d.ts.map +1 -1
  50. package/dist/cli/args.js +13 -1
  51. package/dist/cli/args.js.map +1 -1
  52. package/dist/core/agent-session.d.ts +7 -0
  53. package/dist/core/agent-session.d.ts.map +1 -1
  54. package/dist/core/agent-session.js +12 -7
  55. package/dist/core/agent-session.js.map +1 -1
  56. package/dist/core/bash-executor.d.ts.map +1 -1
  57. package/dist/core/bash-executor.js +40 -45
  58. package/dist/core/bash-executor.js.map +1 -1
  59. package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
  60. package/dist/core/export-html/tool-renderer.js +2 -0
  61. package/dist/core/export-html/tool-renderer.js.map +1 -1
  62. package/dist/core/extensions/types.d.ts +11 -0
  63. package/dist/core/extensions/types.d.ts.map +1 -1
  64. package/dist/core/extensions/types.js.map +1 -1
  65. package/dist/core/model-runtime.d.ts.map +1 -1
  66. package/dist/core/model-runtime.js +2 -1
  67. package/dist/core/model-runtime.js.map +1 -1
  68. package/dist/core/nested-tool-calls.d.ts +1 -0
  69. package/dist/core/nested-tool-calls.d.ts.map +1 -1
  70. package/dist/core/nested-tool-calls.js +1 -0
  71. package/dist/core/nested-tool-calls.js.map +1 -1
  72. package/dist/core/sdk.d.ts +4 -0
  73. package/dist/core/sdk.d.ts.map +1 -1
  74. package/dist/core/sdk.js +17 -5
  75. package/dist/core/sdk.js.map +1 -1
  76. package/dist/core/settings-manager.d.ts +13 -0
  77. package/dist/core/settings-manager.d.ts.map +1 -1
  78. package/dist/core/settings-manager.js +37 -13
  79. package/dist/core/settings-manager.js.map +1 -1
  80. package/dist/core/tools/renderers/bash.d.ts.map +1 -1
  81. package/dist/core/tools/renderers/bash.js +8 -3
  82. package/dist/core/tools/renderers/bash.js.map +1 -1
  83. package/dist/core/tools/renderers/edit.d.ts.map +1 -1
  84. package/dist/core/tools/renderers/edit.js +5 -4
  85. package/dist/core/tools/renderers/edit.js.map +1 -1
  86. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  87. package/dist/extensions/codemode/execute.js +63 -7
  88. package/dist/extensions/codemode/execute.js.map +1 -1
  89. package/dist/extensions/codemode/tool.js +2 -2
  90. package/dist/extensions/codemode/tool.js.map +1 -1
  91. package/dist/extensions/llama/provider.d.ts.map +1 -1
  92. package/dist/extensions/llama/provider.js +34 -11
  93. package/dist/extensions/llama/provider.js.map +1 -1
  94. package/dist/extensions/mcp/cli.js +17 -23
  95. package/dist/extensions/mcp/cli.js.map +1 -1
  96. package/dist/extensions/mcp/index.d.ts.map +1 -1
  97. package/dist/extensions/mcp/index.js +165 -64
  98. package/dist/extensions/mcp/index.js.map +1 -1
  99. package/dist/extensions/mcp/oauth.d.ts +5 -3
  100. package/dist/extensions/mcp/oauth.d.ts.map +1 -1
  101. package/dist/extensions/mcp/oauth.js +36 -10
  102. package/dist/extensions/mcp/oauth.js.map +1 -1
  103. package/dist/extensions/mcp/ui.d.ts +3 -3
  104. package/dist/extensions/mcp/ui.d.ts.map +1 -1
  105. package/dist/extensions/mcp/ui.js +10 -2
  106. package/dist/extensions/mcp/ui.js.map +1 -1
  107. package/dist/modes/interactive/components/bash-execution.d.ts +5 -1
  108. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  109. package/dist/modes/interactive/components/bash-execution.js +17 -14
  110. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  111. package/dist/modes/interactive/components/branch-summary-message.d.ts +2 -1
  112. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
  113. package/dist/modes/interactive/components/branch-summary-message.js +5 -2
  114. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  115. package/dist/modes/interactive/components/compaction-summary-message.d.ts +2 -1
  116. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -1
  117. package/dist/modes/interactive/components/compaction-summary-message.js +5 -2
  118. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -1
  119. package/dist/modes/interactive/components/custom-entry.d.ts +3 -1
  120. package/dist/modes/interactive/components/custom-entry.d.ts.map +1 -1
  121. package/dist/modes/interactive/components/custom-entry.js +8 -2
  122. package/dist/modes/interactive/components/custom-entry.js.map +1 -1
  123. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  124. package/dist/modes/interactive/components/custom-message.js +1 -0
  125. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  126. package/dist/modes/interactive/components/settings-selector.js +1 -1
  127. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  128. package/dist/modes/interactive/components/skill-invocation-message.d.ts +2 -1
  129. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
  130. package/dist/modes/interactive/components/skill-invocation-message.js +5 -2
  131. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
  132. package/dist/modes/interactive/components/tool-execution.d.ts +5 -0
  133. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  134. package/dist/modes/interactive/components/tool-execution.js +10 -0
  135. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  136. package/dist/modes/interactive/interactive-mode.d.ts +2 -0
  137. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  138. package/dist/modes/interactive/interactive-mode.js +50 -29
  139. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  140. package/dist/modes/interactive/program-status-reporter.d.ts +34 -0
  141. package/dist/modes/interactive/program-status-reporter.d.ts.map +1 -0
  142. package/dist/modes/interactive/program-status-reporter.js +110 -0
  143. package/dist/modes/interactive/program-status-reporter.js.map +1 -0
  144. package/dist/package-manager-cli.d.ts.map +1 -1
  145. package/dist/package-manager-cli.js +24 -0
  146. package/dist/package-manager-cli.js.map +1 -1
  147. package/dist/utils/ansi.d.ts +8 -0
  148. package/dist/utils/ansi.d.ts.map +1 -1
  149. package/dist/utils/ansi.js +30 -11
  150. package/dist/utils/ansi.js.map +1 -1
  151. package/dist/utils/clipboard.d.ts.map +1 -1
  152. package/dist/utils/clipboard.js +12 -11
  153. package/dist/utils/clipboard.js.map +1 -1
  154. package/dist/utils/image-resize-core.d.ts +12 -0
  155. package/dist/utils/image-resize-core.d.ts.map +1 -1
  156. package/dist/utils/image-resize-core.js +5 -0
  157. package/dist/utils/image-resize-core.js.map +1 -1
  158. package/dist/utils/image-resize-worker.js +3 -2
  159. package/dist/utils/image-resize-worker.js.map +1 -1
  160. package/dist/utils/image-resize.d.ts.map +1 -1
  161. package/dist/utils/image-resize.js +9 -10
  162. package/dist/utils/image-resize.js.map +1 -1
  163. package/docs/cli.md +4 -4
  164. package/docs/codemode.md +23 -3
  165. package/docs/environment-variables.md +1 -0
  166. package/docs/json.md +3 -3
  167. package/docs/llama-cpp.md +8 -1
  168. package/docs/message-types.md +22 -4
  169. package/docs/models.md +4 -1
  170. package/docs/providers.md +27 -0
  171. package/docs/settings.md +3 -3
  172. package/docs/terminal-setup.md +14 -0
  173. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  174. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  175. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  176. package/examples/extensions/gondolin/package-lock.json +2 -2
  177. package/examples/extensions/gondolin/package.json +1 -1
  178. package/examples/extensions/sandbox/package-lock.json +2 -2
  179. package/examples/extensions/sandbox/package.json +1 -1
  180. package/examples/extensions/with-deps/package-lock.json +2 -2
  181. package/examples/extensions/with-deps/package.json +1 -1
  182. package/package.json +12 -12
  183. package/dist/bundle/chunks/chunk-2QSWSXFK.js +0 -82
  184. package/dist/bundle/chunks/chunk-A3JYRWB6.js +0 -2
  185. package/dist/bundle/chunks/chunk-C47CLQZK.js +0 -2
  186. package/dist/bundle/chunks/chunk-HQHD6PZI.js +0 -2
  187. package/dist/bundle/chunks/chunk-KJUDFE6Y.js +0 -11
  188. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-NM3JRRWQ.js +0 -2
  189. package/dist/bundle/chunks/typesafe-system-one-PRR5K6CI.js +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"model-runtime.js","sourceRoot":"","sources":["../../src/core/model-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAqBN,kBAAkB,EAClB,YAAY,EASZ,UAAU,EAQV,WAAW,EAWX,gBAAgB,GAMhB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,sBAAsB,MAAM,qCAAqC,CAAC;AAC9E,OAAO,EACN,eAAe,EACf,qBAAqB,EACrB,gBAAgB,EAChB,qBAAqB,EACrB,gBAAgB,GAChB,MAAM,8CAA8C,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACzE,OAAO,EAAE,WAAW,IAAI,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,8BAA8B,EAAE,MAAM,mBAAmB,CAAC;AACpF,OAAO,EAGN,oBAAoB,EACpB,2BAA2B,EAE3B,iCAAiC,EACjC,6BAA6B,EAC7B,yBAAyB,GACzB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EACN,kBAAkB,EAClB,kBAAkB,EAClB,cAAc,EAId,iBAAiB,GACjB,MAAM,qBAAqB,CAAC;AA0C7B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IAAI,KAAK,CAAC,KAAK,CAAC,EAAE,EAAE,CAAC;QAC7E,IAAI,CAAC,MAAM;YAAE,MAAM,IAAI,KAAK,CAAC,GAAG,MAAM,kCAAkC,CAAC,CAAC;QAC1E,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAAC,QAAQ,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,GAAG,MAAM,6BAA6B,CAAC,CAAC;QACtG,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,aAAa,EAAE,kBAAkB,CAAC,MAAM,EAAE,KAAK,CAAC,aAAa,CAAC,EAAE,KAAK,EAAE,KAAK,CAAC,KAAK,EAAE,CAAC;IAC9G,CAAC;IAED,gDAAgD;IAChD,gBAAgB,CAAC,UAAkB,EAAE,OAAe;QACnD,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QACxD,OAAO,KAAK,IAAI,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;IAC5D,CAAC;CACD","sourcesContent":["import { dirname, join } from \"node:path\";\nimport {\n\ttype AnyModel,\n\ttype Api,\n\ttype ApiStreamOptions,\n\ttype AssistantImages,\n\ttype AssistantMessage,\n\ttype AssistantMessageEventStream,\n\ttype AuthCheck,\n\ttype AuthInteraction,\n\ttype AuthOperationOptions,\n\ttype AuthResult,\n\ttype AuthType,\n\ttype ClassifierApi,\n\ttype ClassifierContext,\n\ttype ClassifierModel,\n\ttype ClassifierOptions,\n\ttype ClassifierResult,\n\ttype Context,\n\ttype Credential,\n\ttype CredentialInfo,\n\ttype CredentialStore,\n\tclampThinkingLevel,\n\tcreateModels,\n\ttype DeferredCancelOptions,\n\ttype DeferredFetchOptions,\n\ttype DeferredHandle,\n\ttype ImageApi,\n\ttype ImageModel,\n\ttype ImagesContext,\n\ttype ImagesOptions,\n\ttype LoginOptions,\n\tlazyStream,\n\ttype Message,\n\ttype Model,\n\ttype Models,\n\ttype ModelsApiStreamOptions,\n\ttype ModelsClassifierOptions,\n\ttype ModelsDeferredCancelOptions,\n\ttype ModelsDeferredFetchOptions,\n\tModelsError,\n\ttype ModelsImagesOptions,\n\ttype ModelsRefreshOptions,\n\ttype ModelsRefreshResult,\n\ttype ModelsRequestTransforms,\n\ttype ModelsSimpleStreamOptions,\n\ttype ModelsStore,\n\ttype ModelThinkingLevel,\n\ttype ModelType,\n\ttype ModelTypeMap,\n\ttype MutableModels,\n\tnormalizeContext,\n\ttype Provider,\n\ttype ProviderHeaders,\n\ttype ProviderRequestOptions,\n\ttype SimpleStreamOptions,\n\ttype StreamOptions,\n} from \"@earendil-works/pi-ai\";\nimport * as builtinProviderCatalog from \"@earendil-works/pi-ai/providers/all\";\nimport {\n\tassertChatModel,\n\tassertClassifierModel,\n\tassertImageModel,\n\tclassifierErrorResult,\n\timageErrorResult,\n} from \"@earendil-works/pi-ai/utils/model-operations\";\nimport { getAgentDir } from \"../config.ts\";\nimport { operationSignal, raceWithAbortSignal } from \"../utils/abort.ts\";\nimport { AuthStorage as DefaultAuthStorage } from \"./auth-storage.ts\";\nimport { ModelConfig } from \"./model-config.ts\";\nimport { FileModelsStore, InMemoryCodingAgentModelsStore } from \"./models-store.ts\";\nimport {\n\ttype AuthStatus,\n\ttype CompatibilityRequestConfig,\n\tcomposeModelProvider,\n\tconfiguredRequestAuthStatus,\n\ttype ProviderConfigInput,\n\tresolveCompatibilityRequestConfig,\n\tresolveConfiguredModelHeaders,\n\tvalidateExtensionProvider,\n} from \"./provider-composer.ts\";\nimport { withRemoteCatalog } from \"./remote-catalog-provider.ts\";\nimport { RuntimeCredentials } from \"./runtime-credentials.ts\";\nimport {\n\tcreateVirtualModel,\n\tfindLatestResponse,\n\tisVirtualModel,\n\ttype ModelRoute,\n\ttype ModelRouteReason,\n\ttype VirtualModelDefinition,\n\twithVirtualModels,\n} from \"./virtual-models.ts\";\n\ninterface RegisteredVirtualModel {\n\tmodel: Model<Api>;\n\troute: VirtualModelDefinition[\"route\"];\n}\n\ninterface ModelRuntimeSnapshot {\n\tall: readonly Model<Api>[];\n\tavailable: readonly Model<Api>[];\n\tconfiguredProviders: ReadonlySet<string>;\n\tstoredProviders: ReadonlySet<string>;\n\tauth: ReadonlyMap<string, AuthCheck | undefined>;\n}\n\nexport interface CreateModelRuntimeOptions {\n\t/** Credential storage. Defaults to the file at authPath. */\n\tcredentials?: CredentialStore;\n\tauthPath?: string;\n\tmodelsPath?: string | null;\n\tmodelsStore?: ModelsStore;\n\tmodelsStorePath?: string;\n\t/** Allow create() to refresh model catalogs over the network. Defaults to false. */\n\tallowModelNetwork?: boolean;\n\t/** Timeout for the create-time network model refresh. */\n\tmodelRefreshTimeoutMs?: number;\n\tcatalogBaseUrl?: string;\n\t/** Optional caller cancellation for initial cache restoration and availability checks. */\n\tsignal?: AbortSignal;\n\t/** Skip initial catalog and availability refresh. Static models remain available. */\n\trefreshOnCreate?: boolean;\n}\n\nexport interface ModelRuntimeAuthOverrides extends AuthOperationOptions {\n\tapiKey?: string;\n\tenv?: Record<string, string>;\n\t/** Require this much remaining OAuth-token validity; defaults to five minutes. */\n\tminOAuthValidityMs?: number;\n}\n\nexport type CredentialSynchronizationOperation = \"login\" | \"logout\" | \"setRuntimeApiKey\" | \"removeRuntimeApiKey\";\n\n/** Credentials changed successfully, but the local model/auth snapshot could not be synchronized. */\nexport class CredentialSynchronizationError extends Error {\n\treadonly providerId: string;\n\treadonly operation: CredentialSynchronizationOperation;\n\treadonly credential: Credential | undefined;\n\n\tconstructor(\n\t\tproviderId: string,\n\t\toperation: CredentialSynchronizationOperation,\n\t\tcredential: Credential | undefined,\n\t\toptions: ErrorOptions,\n\t) {\n\t\tsuper(`Credential ${operation} committed for ${providerId}, but local synchronization failed`, options);\n\t\tthis.name = \"CredentialSynchronizationError\";\n\t\tthis.providerId = providerId;\n\t\tthis.operation = operation;\n\t\tthis.credential = credential;\n\t}\n}\n\nfunction mergeHeaders(\n\tbase: ProviderHeaders | undefined,\n\toverride: ProviderHeaders | undefined,\n): ProviderHeaders | undefined {\n\tif (!base && !override) return undefined;\n\tconst merged = { ...base };\n\tfor (const [name, value] of Object.entries(override ?? {})) {\n\t\tconst lowerName = name.toLowerCase();\n\t\tfor (const existingName of Object.keys(merged)) {\n\t\t\tif (existingName.toLowerCase() === lowerName) delete merged[existingName];\n\t\t}\n\t\tmerged[name] = value;\n\t}\n\treturn merged;\n}\n\n/** Configured pi-ai Models collection used by coding-agent and SDK consumers. */\nexport class ModelRuntime implements Models {\n\tprivate readonly models: MutableModels;\n\tprivate readonly credentials: RuntimeCredentials;\n\tprivate readonly defaultBuiltins: ReadonlyMap<string, Provider>;\n\tprivate readonly builtins = new Map<string, Provider>();\n\tprivate readonly nativeExtensionProviders = new Map<string, Provider>();\n\tprivate readonly extensionProviders = new Map<string, ProviderConfigInput>();\n\t/** Virtual models by provider id, then model id. */\n\tprivate readonly virtualModels = new Map<string, Map<string, RegisteredVirtualModel>>();\n\tprivate readonly compositionErrors = new Map<string, string>();\n\tprivate readonly modelsPath: string | undefined;\n\tprivate readonly modelNetworkEnabled: boolean;\n\tprivate config: ModelConfig;\n\tprivate snapshot: ModelRuntimeSnapshot = {\n\t\tall: [],\n\t\tavailable: [],\n\t\tconfiguredProviders: new Set(),\n\t\tstoredProviders: new Set(),\n\t\tauth: new Map(),\n\t};\n\tprivate availabilityRefreshSeq = 0;\n\tprivate availabilityErrorSeq = 0;\n\tprivate readonly providerAvailabilitySeq = new Map<string, number>();\n\tprivate availabilityError: string | undefined;\n\tprivate readonly credentialOperations = new Map<string, Promise<unknown>>();\n\n\tprivate constructor(\n\t\tcredentials: RuntimeCredentials,\n\t\tconfig: ModelConfig,\n\t\tmodelsPath: string | undefined,\n\t\tmodelsStore: ModelsStore,\n\t\tproviders: readonly Provider[],\n\t\tmodelNetworkEnabled: boolean,\n\t) {\n\t\tthis.credentials = credentials;\n\t\tthis.config = config;\n\t\tthis.modelsPath = modelsPath;\n\t\tthis.modelNetworkEnabled = modelNetworkEnabled;\n\t\tthis.defaultBuiltins = new Map(providers.map((provider) => [provider.id, provider]));\n\t\tfor (const [providerId, provider] of this.defaultBuiltins) this.builtins.set(providerId, provider);\n\t\tthis.models = createModels({ credentials, modelsStore });\n\t\tthis.rebuildProviders();\n\t}\n\n\tstatic async create(options: CreateModelRuntimeOptions = {}): Promise<ModelRuntime> {\n\t\tconst credentials = new RuntimeCredentials(options.credentials ?? DefaultAuthStorage.create(options.authPath));\n\t\tconst modelsPath =\n\t\t\toptions.modelsPath === null ? undefined : (options.modelsPath ?? join(getAgentDir(), \"models.json\"));\n\t\tconst config = await ModelConfig.load(modelsPath);\n\t\tconst modelsStore =\n\t\t\toptions.modelsStore ??\n\t\t\t(modelsPath\n\t\t\t\t? new FileModelsStore(options.modelsStorePath ?? join(dirname(modelsPath), \"models-store.json\"))\n\t\t\t\t: new InMemoryCodingAgentModelsStore());\n\t\tconst builtinModelDataGeneratedAt = builtinProviderCatalog.getBuiltinModelDataGeneratedAt();\n\t\tconst providers = builtinProviderCatalog\n\t\t\t.builtinProviders()\n\t\t\t.map((provider) =>\n\t\t\t\tprovider.id === \"radius\"\n\t\t\t\t\t? provider\n\t\t\t\t\t: withRemoteCatalog(provider, options.catalogBaseUrl, builtinModelDataGeneratedAt),\n\t\t\t);\n\t\tconst runtime = new ModelRuntime(\n\t\t\tcredentials,\n\t\t\tconfig,\n\t\t\tmodelsPath,\n\t\t\tmodelsStore,\n\t\t\tproviders,\n\t\t\tprocess.env.PI_OFFLINE === undefined,\n\t\t);\n\t\truntime.configureRadiusProviders();\n\t\truntime.rebuildProviders();\n\t\tconst refreshFromNetwork = runtime.modelNetworkEnabled && options.allowModelNetwork === true;\n\t\tconst controller =\n\t\t\trefreshFromNetwork && options.modelRefreshTimeoutMs !== undefined ? new AbortController() : undefined;\n\t\tconst timeout = controller ? setTimeout(() => controller.abort(), options.modelRefreshTimeoutMs) : undefined;\n\t\tconst signal = controller\n\t\t\t? options.signal\n\t\t\t\t? AbortSignal.any([options.signal, controller.signal])\n\t\t\t\t: controller.signal\n\t\t\t: options.signal;\n\t\ttry {\n\t\t\tif (options.refreshOnCreate !== false) {\n\t\t\t\tawait runtime.refresh({ allowNetwork: refreshFromNetwork, signal });\n\t\t\t}\n\t\t} finally {\n\t\t\tif (timeout) clearTimeout(timeout);\n\t\t}\n\t\treturn runtime;\n\t}\n\n\tprivate configureRadiusProviders(): void {\n\t\tthis.builtins.clear();\n\t\tfor (const [providerId, provider] of this.defaultBuiltins) this.builtins.set(providerId, provider);\n\t\tfor (const providerId of this.config.getProviderIds()) {\n\t\t\tconst config = this.config.getProvider(providerId);\n\t\t\tif (config?.oauth !== \"radius\" || !config.baseUrl) continue;\n\t\t\tthis.builtins.set(\n\t\t\t\tproviderId,\n\t\t\t\tbuiltinProviderCatalog.radiusProvider({\n\t\t\t\t\tid: providerId,\n\t\t\t\t\tname: config.name ?? providerId,\n\t\t\t\t\tgateway: config.baseUrl.replace(/\\/v1\\/?$/u, \"\"),\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate providerIds(): Set<string> {\n\t\treturn new Set([\n\t\t\t...this.builtins.keys(),\n\t\t\t...this.nativeExtensionProviders.keys(),\n\t\t\t...this.config.getProviderIds(),\n\t\t\t...this.extensionProviders.keys(),\n\t\t\t...this.virtualModels.keys(),\n\t\t]);\n\t}\n\n\t/** Returns the provider without virtual models, or undefined when only virtual models define it. */\n\tprivate recomposeProvider(providerId: string): Provider | undefined {\n\t\tconst provider = this.composeProvider(providerId);\n\t\tconst virtualModels = [...(this.virtualModels.get(providerId)?.values() ?? [])].map((entry) => entry.model);\n\t\tif (virtualModels.length > 0) this.models.setProvider(withVirtualModels(providerId, provider, virtualModels));\n\t\telse if (provider) this.models.setProvider(provider);\n\t\telse this.models.deleteProvider(providerId);\n\t\treturn provider;\n\t}\n\n\t/** The provider without virtual models, or undefined when nothing defines it. */\n\tprivate composeProvider(providerId: string): Provider | undefined {\n\t\tconst base = this.nativeExtensionProviders.get(providerId) ?? this.builtins.get(providerId);\n\t\tconst extension = this.extensionProviders.get(providerId);\n\t\tif (!this.config.getProvider(providerId) && !extension) {\n\t\t\t// No overlays: use the builtin untouched so its auth/login/stream behavior is exact.\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn base;\n\t\t}\n\t\ttry {\n\t\t\tconst provider = composeModelProvider(providerId, base, this.config, extension);\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn provider;\n\t\t} catch (error) {\n\t\t\tthis.compositionErrors.set(providerId, error instanceof Error ? error.message : String(error));\n\t\t\treturn base;\n\t\t}\n\t}\n\n\tprivate rebuildProviders(): void {\n\t\tthis.models.clearProviders();\n\t\tthis.compositionErrors.clear();\n\t\tfor (const providerId of this.providerIds()) this.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t}\n\n\tprivate updateModelSnapshot(): void {\n\t\tconst all = [...this.models.getModels()];\n\t\tthis.snapshot = {\n\t\t\t...this.snapshot,\n\t\t\tall,\n\t\t\tavailable: all.filter((model) => this.snapshot.configuredProviders.has(model.provider)),\n\t\t};\n\t}\n\n\tprivate async runAvailabilityRefresh(seq: number, errorSeq: number, signal: AbortSignal): Promise<void> {\n\t\tconst providers = this.models.getProviders();\n\t\tconst [available, checks, credentials] = await Promise.all([\n\t\t\tthis.models.getAvailable(undefined, { signal }),\n\t\t\tPromise.all(\n\t\t\t\tproviders.map(\n\t\t\t\t\tasync (provider): Promise<[string, AuthCheck | undefined]> => [\n\t\t\t\t\t\tprovider.id,\n\t\t\t\t\t\tawait this.models.checkAuth(provider.id, { signal }),\n\t\t\t\t\t],\n\t\t\t\t),\n\t\t\t),\n\t\t\tthis.credentials.list({ signal }),\n\t\t]);\n\t\tif (seq !== this.availabilityRefreshSeq) return;\n\t\tconst auth = new Map(checks);\n\t\tconst configuredProviders = new Set(\n\t\t\tchecks\n\t\t\t\t.filter((entry): entry is [string, AuthCheck] => entry[1] !== undefined)\n\t\t\t\t.map(([providerId]) => providerId),\n\t\t);\n\t\tthis.snapshot = {\n\t\t\tall: [...this.models.getModels()],\n\t\t\tavailable: [...available],\n\t\t\tconfiguredProviders,\n\t\t\tstoredProviders: new Set(credentials.map((entry) => entry.providerId)),\n\t\t\tauth,\n\t\t};\n\t\tif (errorSeq === this.availabilityErrorSeq) this.availabilityError = undefined;\n\t}\n\n\tprivate queueAvailabilityRefresh(signal?: AbortSignal): Promise<void> {\n\t\tconst seq = ++this.availabilityRefreshSeq;\n\t\tfor (const [providerId, providerSeq] of this.providerAvailabilitySeq) {\n\t\t\tthis.providerAvailabilitySeq.set(providerId, providerSeq + 1);\n\t\t}\n\t\tconst errorSeq = ++this.availabilityErrorSeq;\n\t\tconst effectiveSignal = operationSignal(signal);\n\t\treturn this.runAvailabilityRefresh(seq, errorSeq, effectiveSignal).catch((error) => {\n\t\t\tif (errorSeq === this.availabilityErrorSeq && !effectiveSignal.aborted) {\n\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t}\n\t\t\tthrow error;\n\t\t});\n\t}\n\n\tprivate async refreshProviderAvailability(providerId: string, signal: AbortSignal): Promise<void> {\n\t\t// Invalidate any full availability pass that started before this credential change.\n\t\t++this.availabilityRefreshSeq;\n\t\tconst providerSeq = (this.providerAvailabilitySeq.get(providerId) ?? 0) + 1;\n\t\tthis.providerAvailabilitySeq.set(providerId, providerSeq);\n\t\tconst errorSeq = ++this.availabilityErrorSeq;\n\t\ttry {\n\t\t\tconst [available, auth, credential] = await Promise.all([\n\t\t\t\tthis.models.getAvailable(providerId, { signal }),\n\t\t\t\tthis.models.checkAuth(providerId, { signal }),\n\t\t\t\tthis.credentials.read(providerId, { signal }),\n\t\t\t]);\n\t\t\tsignal.throwIfAborted();\n\t\t\tif (this.providerAvailabilitySeq.get(providerId) !== providerSeq) return;\n\t\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders);\n\t\t\tconst storedProviders = new Set(this.snapshot.storedProviders);\n\t\t\tconst authByProvider = new Map(this.snapshot.auth);\n\t\t\tif (auth) {\n\t\t\t\tconfiguredProviders.add(providerId);\n\t\t\t\tauthByProvider.set(providerId, auth);\n\t\t\t} else {\n\t\t\t\tconfiguredProviders.delete(providerId);\n\t\t\t\tauthByProvider.delete(providerId);\n\t\t\t}\n\t\t\tif (credential) storedProviders.add(providerId);\n\t\t\telse storedProviders.delete(providerId);\n\t\t\tconst all = [...this.models.getModels()];\n\t\t\tconst availableById = new Map(\n\t\t\t\t[...this.snapshot.available.filter((model) => model.provider !== providerId), ...available].map((model) => [\n\t\t\t\t\t`${model.provider}\\0${model.id}`,\n\t\t\t\t\tmodel,\n\t\t\t\t]),\n\t\t\t);\n\t\t\tthis.snapshot = {\n\t\t\t\tall,\n\t\t\t\tavailable: all.flatMap((model) => availableById.get(`${model.provider}\\0${model.id}`) ?? []),\n\t\t\t\tconfiguredProviders,\n\t\t\t\tstoredProviders,\n\t\t\t\tauth: authByProvider,\n\t\t\t};\n\t\t\tif (errorSeq === this.availabilityErrorSeq) this.availabilityError = undefined;\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\tthis.providerAvailabilitySeq.get(providerId) === providerSeq &&\n\t\t\t\terrorSeq === this.availabilityErrorSeq &&\n\t\t\t\t!signal.aborted\n\t\t\t) {\n\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tgetProviders(): readonly Provider[] {\n\t\treturn this.models.getProviders();\n\t}\n\n\tgetProvider(providerId: string): Provider | undefined {\n\t\treturn this.models.getProvider(providerId);\n\t}\n\n\tgetModels(providerId?: string): readonly Model<Api>[] {\n\t\treturn this.models.getModels(providerId);\n\t}\n\n\tgetModel(providerId: string, modelId: string): Model<Api> | undefined {\n\t\treturn this.models.getModel(providerId, modelId);\n\t}\n\n\tgetModelsOfType<TType extends ModelType>(type: TType, providerId?: string): readonly ModelTypeMap[TType][] {\n\t\treturn this.models.getModelsOfType(type, providerId);\n\t}\n\n\tgetModelOfType<TType extends ModelType>(\n\t\ttype: TType,\n\t\tproviderId: string,\n\t\tmodelId: string,\n\t): ModelTypeMap[TType] | undefined {\n\t\treturn this.models.getModelOfType(type, providerId, modelId);\n\t}\n\n\tgetAllModels(providerId?: string): readonly AnyModel[] {\n\t\treturn this.models.getAllModels(providerId);\n\t}\n\n\tgetAvailableOfType<TType extends ModelType>(\n\t\ttype: TType,\n\t\tproviderId?: string,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<readonly ModelTypeMap[TType][]> {\n\t\treturn this.models.getAvailableOfType(type, providerId, options);\n\t}\n\n\tgetAllAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly AnyModel[]> {\n\t\treturn this.models.getAllAvailable(providerId, options);\n\t}\n\n\tasync checkAuth(providerId: string, options?: AuthOperationOptions): Promise<AuthCheck | undefined> {\n\t\treturn this.models.checkAuth(providerId, options);\n\t}\n\n\tasync getAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly Model<Api>[]> {\n\t\tif (providerId) {\n\t\t\tconst errorSeq = ++this.availabilityErrorSeq;\n\t\t\ttry {\n\t\t\t\tconst available = await this.models.getAvailable(providerId, options);\n\t\t\t\tif (errorSeq === this.availabilityErrorSeq) this.availabilityError = undefined;\n\t\t\t\treturn available;\n\t\t\t} catch (error) {\n\t\t\t\tif (errorSeq === this.availabilityErrorSeq && !options?.signal?.aborted) {\n\t\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\tawait this.queueAvailabilityRefresh(options?.signal);\n\t\treturn this.snapshot.available;\n\t}\n\n\tgetAvailableSnapshot(): readonly Model<Api>[] {\n\t\treturn this.snapshot.available;\n\t}\n\n\tgetError(): string | undefined {\n\t\tconst errors: string[] = [];\n\t\tconst configError = this.config.getError();\n\t\tif (configError) errors.push(configError);\n\t\tfor (const [providerId, error] of this.compositionErrors) {\n\t\t\terrors.push(`Provider \"${providerId}\": ${error}`);\n\t\t}\n\t\tif (this.availabilityError) errors.push(`Availability refresh: ${this.availabilityError}`);\n\t\treturn errors.length > 0 ? errors.join(\"\\n\\n\") : undefined;\n\t}\n\n\tgetRegisteredProviderConfig(providerId: string): ProviderConfigInput | undefined {\n\t\treturn this.extensionProviders.get(providerId);\n\t}\n\n\tgetRegisteredProviderIds(): readonly string[] {\n\t\treturn [...new Set([...this.extensionProviders.keys(), ...this.nativeExtensionProviders.keys()])];\n\t}\n\n\tgetRegisteredNativeProvider(providerId: string): Provider | undefined {\n\t\treturn this.nativeExtensionProviders.get(providerId);\n\t}\n\n\t/** @internal Compatibility fallback for ModelRegistry when provider auth is unconfigured. */\n\tgetCompatibilityRequestConfig(model: Model<Api>): CompatibilityRequestConfig {\n\t\treturn resolveCompatibilityRequestConfig(\n\t\t\tmodel,\n\t\t\tthis.config.getProvider(model.provider),\n\t\t\tthis.extensionProviders.get(model.provider),\n\t\t);\n\t}\n\n\tisUsingOAuth(providerId: string): boolean {\n\t\treturn this.snapshot.auth.get(providerId)?.type === \"oauth\";\n\t}\n\n\tisUsingSubscription(providerId: string): boolean {\n\t\treturn this.isUsingOAuth(providerId) && this.models.getProvider(providerId)?.auth.oauth?.isSubscription === true;\n\t}\n\n\thasConfiguredAuth(providerId: string): boolean {\n\t\treturn this.snapshot.configuredProviders.has(providerId);\n\t}\n\n\tgetAuth(providerId: string, overrides?: ModelRuntimeAuthOverrides): Promise<AuthResult | undefined>;\n\tgetAuth(model: AnyModel, overrides?: ModelRuntimeAuthOverrides): Promise<AuthResult | undefined>;\n\tasync getAuth(\n\t\tproviderOrModel: string | AnyModel,\n\t\toverrides: ModelRuntimeAuthOverrides = {},\n\t): Promise<AuthResult | undefined> {\n\t\tif (typeof providerOrModel === \"string\") return this.models.getAuth(providerOrModel, overrides);\n\t\tconst resolution = await this.models.getAuth(providerOrModel, overrides);\n\t\tif (!resolution) return undefined;\n\t\tconst configuredHeaders = resolveConfiguredModelHeaders(\n\t\t\tproviderOrModel,\n\t\t\tthis.config.getProvider(providerOrModel.provider),\n\t\t\tthis.extensionProviders.get(providerOrModel.provider),\n\t\t\t{ ...(resolution.env ?? {}), ...(overrides.env ?? {}) },\n\t\t);\n\t\treturn {\n\t\t\t...resolution,\n\t\t\tauth: {\n\t\t\t\t...resolution.auth,\n\t\t\t\theaders: mergeHeaders(resolution.auth.headers, configuredHeaders),\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate enqueueCredentialOperation<T>(providerId: string, signal: AbortSignal, task: () => Promise<T>): Promise<T> {\n\t\tconst previous = this.credentialOperations.get(providerId) ?? Promise.resolve();\n\t\tlet markStarted: (() => void) | undefined;\n\t\tconst started = new Promise<void>((resolve) => {\n\t\t\tmarkStarted = resolve;\n\t\t});\n\t\tconst operation = (async () => {\n\t\t\tawait previous.catch(() => {});\n\t\t\tsignal.throwIfAborted();\n\t\t\tmarkStarted?.();\n\t\t\treturn task();\n\t\t})();\n\t\tconst tail = operation.catch(() => {});\n\t\tthis.credentialOperations.set(providerId, tail);\n\t\tvoid tail.then(() => {\n\t\t\tif (this.credentialOperations.get(providerId) === tail) this.credentialOperations.delete(providerId);\n\t\t});\n\t\treturn raceWithAbortSignal(started, signal).then(() => operation);\n\t}\n\n\tprivate async synchronizeCredentialState(\n\t\tproviderId: string,\n\t\toperation: CredentialSynchronizationOperation,\n\t\tcredential: Credential | undefined,\n\t\tsignal: AbortSignal,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tsignal.throwIfAborted();\n\t\t\tthis.recomposeProvider(providerId);\n\t\t\tconst compositionError = this.compositionErrors.get(providerId);\n\t\t\tif (compositionError) throw new Error(compositionError);\n\t\t\tconst result = await this.models.refresh({ allowNetwork: false, providers: [providerId], signal });\n\t\t\tif (result.aborted) signal.throwIfAborted();\n\t\t\tconst refreshError = result.errors.get(providerId);\n\t\t\tif (refreshError) throw refreshError;\n\t\t\tthis.updateModelSnapshot();\n\t\t\tawait this.refreshProviderAvailability(providerId, signal);\n\t\t} catch (cause) {\n\t\t\tthrow new CredentialSynchronizationError(providerId, operation, credential, { cause });\n\t\t}\n\t}\n\n\tsetRuntimeApiKey(providerId: string, apiKey: string, options: AuthOperationOptions = {}): Promise<void> {\n\t\tconst signal = operationSignal(options.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tthis.credentials.setRuntimeApiKey(providerId, apiKey);\n\t\t\tawait this.synchronizeCredentialState(\n\t\t\t\tproviderId,\n\t\t\t\t\"setRuntimeApiKey\",\n\t\t\t\t{ type: \"api_key\", key: apiKey },\n\t\t\t\tsignal,\n\t\t\t);\n\t\t});\n\t}\n\n\tremoveRuntimeApiKey(providerId: string, options: AuthOperationOptions = {}): Promise<void> {\n\t\tconst signal = operationSignal(options.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tthis.credentials.removeRuntimeApiKey(providerId);\n\t\t\tawait this.synchronizeCredentialState(providerId, \"removeRuntimeApiKey\", undefined, signal);\n\t\t});\n\t}\n\n\tlistCredentials(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]> {\n\t\treturn this.credentials.list(options);\n\t}\n\n\tgetProviderAuthStatus(providerId: string): AuthStatus {\n\t\tif (this.credentials.hasRuntimeApiKey(providerId)) return { configured: true, source: \"runtime\" };\n\t\tif (this.snapshot.storedProviders.has(providerId)) return { configured: true, source: \"stored\" };\n\t\tconst configured = configuredRequestAuthStatus(\n\t\t\tthis.config.getProvider(providerId),\n\t\t\tthis.extensionProviders.get(providerId),\n\t\t);\n\t\tif (configured) return configured;\n\t\tconst check = this.snapshot.auth.get(providerId);\n\t\treturn check ? { configured: true, source: \"environment\", label: check.source } : { configured: false };\n\t}\n\n\tprivate async prepareRequest<\n\t\tTModel extends AnyModel,\n\t\tTOptions extends ProviderRequestOptions<TModel> & ModelsRequestTransforms,\n\t>(\n\t\tmodel: TModel,\n\t\toptions: TOptions | undefined,\n\t): Promise<{\n\t\tprovider: Provider;\n\t\tmodel: TModel;\n\t\toptions: Omit<TOptions, \"transformHeaders\"> & ProviderRequestOptions<TModel>;\n\t}> {\n\t\tconst provider = this.models.getProvider(model.provider);\n\t\tif (!provider) throw new ModelsError(\"provider\", `Unknown provider: ${model.provider}`);\n\t\tconst resolution = await this.getAuth(model, {\n\t\t\tapiKey: options?.apiKey,\n\t\t\tenv: options?.env,\n\t\t\tsignal: options?.signal,\n\t\t});\n\t\tif (!resolution) throw new ModelsError(\"auth\", `Provider is not configured: ${model.provider}`);\n\n\t\tconst { transformHeaders, ...rawProviderOptions } = options ?? {};\n\t\tconst providerOptions = rawProviderOptions as Omit<TOptions, \"transformHeaders\"> & ProviderRequestOptions<TModel>;\n\t\tlet headers = mergeHeaders(resolution.auth.headers, providerOptions.headers);\n\t\tif (transformHeaders) headers = await transformHeaders(headers ?? {});\n\t\tconst env =\n\t\t\tresolution.env || providerOptions.env\n\t\t\t\t? { ...(resolution.env ?? {}), ...(providerOptions.env ?? {}) }\n\t\t\t\t: undefined;\n\t\tconst requestModel: TModel = resolution.auth.baseUrl ? { ...model, baseUrl: resolution.auth.baseUrl } : model;\n\t\treturn {\n\t\t\tprovider,\n\t\t\tmodel: requestModel,\n\t\t\toptions: {\n\t\t\t\t...providerOptions,\n\t\t\t\tapiKey: providerOptions.apiKey ?? resolution.auth.apiKey,\n\t\t\t\theaders,\n\t\t\t\tenv,\n\t\t\t} as Omit<TOptions, \"transformHeaders\"> & ProviderRequestOptions<TModel>,\n\t\t};\n\t}\n\n\tstream<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): AssistantMessageEventStream {\n\t\tconst transcript = normalizeContext(context);\n\t\treturn lazyStream(model, async () => {\n\t\t\tassertChatModel(model);\n\t\t\tconst prepared = await this.prepareRequest(\n\t\t\t\tmodel,\n\t\t\t\toptions as (StreamOptions & ModelsRequestTransforms) | undefined,\n\t\t\t);\n\t\t\treturn prepared.provider.stream(prepared.model, transcript, prepared.options as ApiStreamOptions<TApi>);\n\t\t});\n\t}\n\n\tcomplete<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): Promise<AssistantMessage> {\n\t\treturn this.stream(model, context, options).result();\n\t}\n\n\tstreamSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): AssistantMessageEventStream {\n\t\tconst transcript = normalizeContext(context);\n\t\tif (isVirtualModel(model)) {\n\t\t\t// Requests outside the agent loop are routed here. Callers sized them before routing, so\n\t\t\t// cap the output budget to the routed model.\n\t\t\treturn lazyStream(model, async () => {\n\t\t\t\tconst route = await this.resolveModel(model, transcript.messages, {\n\t\t\t\t\treason: \"direct\",\n\t\t\t\t\tthinkingLevel: options?.reasoning ?? \"off\",\n\t\t\t\t\tsignal: options?.signal,\n\t\t\t\t});\n\t\t\t\tconst { maxTokens: limit } = route.model;\n\t\t\t\tconst maxTokens = options?.maxTokens && limit > 0 ? Math.min(options.maxTokens, limit) : options?.maxTokens;\n\t\t\t\tconst reasoning = route.thinkingLevel === \"off\" ? undefined : route.thinkingLevel;\n\t\t\t\t// Caller credentials were resolved for the virtual model's provider. Another provider\n\t\t\t\t// resolves its own, so they are not sent to the wrong vendor.\n\t\t\t\tconst { apiKey, headers, env, ...rest } = options ?? {};\n\t\t\t\tconst auth = route.model.provider === model.provider ? { apiKey, headers, env } : {};\n\t\t\t\treturn this.streamSimple(route.model, context, { ...rest, ...auth, maxTokens, reasoning });\n\t\t\t});\n\t\t}\n\t\treturn lazyStream(model, async () => {\n\t\t\tassertChatModel(model);\n\t\t\tconst prepared = await this.prepareRequest(model, options);\n\t\t\treturn prepared.provider.streamSimple(prepared.model, transcript, prepared.options as SimpleStreamOptions);\n\t\t});\n\t}\n\n\tcompleteSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): Promise<AssistantMessage> {\n\t\treturn this.streamSimple(model, context, options).result();\n\t}\n\n\tstreamDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredFetchOptions,\n\t): AssistantMessageEventStream {\n\t\treturn lazyStream(model, async () => {\n\t\t\tassertChatModel(model);\n\t\t\tconst prepared = await this.prepareRequest(model, options);\n\t\t\tif (!prepared.provider.fetchDeferred) {\n\t\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support deferred responses`);\n\t\t\t}\n\t\t\treturn prepared.provider.fetchDeferred(prepared.model, handle, prepared.options as DeferredFetchOptions);\n\t\t});\n\t}\n\n\tasync fetchDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredFetchOptions,\n\t): Promise<AssistantMessage> {\n\t\treturn this.streamDeferred(model, handle, options).result();\n\t}\n\n\tasync cancelDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredCancelOptions,\n\t): Promise<void> {\n\t\tassertChatModel(model);\n\t\tconst prepared = await this.prepareRequest(model, options);\n\t\tif (!prepared.provider.cancelDeferred) {\n\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support deferred responses`);\n\t\t}\n\t\tawait prepared.provider.cancelDeferred(prepared.model, handle, prepared.options as DeferredCancelOptions);\n\t}\n\n\tasync generateImages(\n\t\tmodel: ImageModel<ImageApi>,\n\t\tcontext: ImagesContext,\n\t\toptions?: ModelsImagesOptions,\n\t): Promise<AssistantImages> {\n\t\ttry {\n\t\t\tassertImageModel(model);\n\t\t\tconst prepared = await this.prepareRequest(model, options);\n\t\t\tif (!prepared.provider.generateImages) {\n\t\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support image generation`);\n\t\t\t}\n\t\t\treturn await prepared.provider.generateImages(prepared.model, context, prepared.options as ImagesOptions);\n\t\t} catch (error) {\n\t\t\treturn imageErrorResult(model, error, options?.signal?.aborted);\n\t\t}\n\t}\n\n\tasync classify(\n\t\tmodel: ClassifierModel<ClassifierApi>,\n\t\tcontext: ClassifierContext,\n\t\toptions?: ModelsClassifierOptions,\n\t): Promise<ClassifierResult> {\n\t\ttry {\n\t\t\tassertClassifierModel(model);\n\t\t\tconst prepared = await this.prepareRequest(model, options);\n\t\t\tif (!prepared.provider.classify) {\n\t\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support classification`);\n\t\t\t}\n\t\t\treturn await prepared.provider.classify(prepared.model, context, prepared.options as ClassifierOptions);\n\t\t} catch (error) {\n\t\t\treturn classifierErrorResult(model, error, options?.signal?.aborted);\n\t\t}\n\t}\n\n\tlogin(\n\t\tproviderId: string,\n\t\ttype: AuthType,\n\t\tinteraction: AuthInteraction,\n\t\toptions?: LoginOptions,\n\t): Promise<Credential> {\n\t\tconst signal = operationSignal(interaction.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tconst credential = await this.models.login(providerId, type, { ...interaction, signal }, options);\n\t\t\tawait this.synchronizeCredentialState(providerId, \"login\", credential, signal);\n\t\t\treturn credential;\n\t\t});\n\t}\n\n\tlogout(providerId: string, options: AuthOperationOptions = {}): Promise<void> {\n\t\tconst signal = operationSignal(options.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tawait this.models.logout(providerId, { signal });\n\t\t\tawait this.synchronizeCredentialState(providerId, \"logout\", undefined, signal);\n\t\t});\n\t}\n\n\tasync refresh(options: ModelsRefreshOptions = {}): Promise<ModelsRefreshResult> {\n\t\tthis.config = await ModelConfig.load(this.modelsPath);\n\t\tthis.configureRadiusProviders();\n\t\tif (options.providers) {\n\t\t\tfor (const providerId of new Set(options.providers)) this.recomposeProvider(providerId);\n\t\t\tthis.updateModelSnapshot();\n\t\t} else {\n\t\t\tthis.rebuildProviders();\n\t\t}\n\t\tconst refreshOptions = {\n\t\t\t...options,\n\t\t\tallowNetwork: options.allowNetwork ?? this.modelNetworkEnabled,\n\t\t};\n\t\t// Published pi-ai builds before ModelsStore returned void and accepted a provider ID.\n\t\t// The fallback keeps source-mode CLI tests working without rebuilding workspace dependencies.\n\t\tconst result = ((await this.models.refresh(refreshOptions)) as ModelsRefreshResult | undefined) ?? {\n\t\t\taborted: refreshOptions.signal?.aborted ?? false,\n\t\t\terrors: new Map(),\n\t\t};\n\t\tconst errors = new Map(result.errors);\n\t\tthis.updateModelSnapshot();\n\t\tif (options.providers) {\n\t\t\tawait Promise.all(\n\t\t\t\t[...new Set(options.providers)].map(async (providerId) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.refreshProviderAvailability(providerId, operationSignal(options.signal));\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!options.signal?.aborted) {\n\t\t\t\t\t\t\terrors.set(providerId, error instanceof Error ? error : new Error(String(error)));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t);\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tawait this.queueAvailabilityRefresh(options.signal);\n\t\t\t} catch {\n\t\t\t\t// Availability errors are recorded by the latest pass; refreshed models remain usable.\n\t\t\t}\n\t\t}\n\t\treturn { aborted: result.aborted || (options.signal?.aborted ?? false), errors };\n\t}\n\n\tregisterNativeProvider(provider: Provider): void {\n\t\tif (!provider.id.trim()) throw new Error(\"Provider id must not be empty.\");\n\t\tthis.extensionProviders.delete(provider.id);\n\t\tthis.nativeExtensionProviders.set(provider.id, provider);\n\t\tthis.recomposeProvider(provider.id);\n\t\tthis.updateModelSnapshot();\n\t\tthis.markProvisionallyConfigured(\n\t\t\tprovider.id,\n\t\t\tconfiguredRequestAuthStatus(this.config.getProvider(provider.id), undefined),\n\t\t\tprovider.auth.oauth && !provider.auth.apiKey ? \"oauth\" : \"api_key\",\n\t\t);\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\t/**\n\t * Mark a newly registered provider as configured when it has a stored credential or a configured\n\t * API key. Availability checks run asynchronously, and callers such as initial model selection\n\t * read the snapshot before they finish. The next availability pass replaces this entry.\n\t */\n\tprivate markProvisionallyConfigured(\n\t\tproviderId: string,\n\t\tconfiguredStatus: AuthStatus | undefined,\n\t\ttype: AuthType,\n\t): void {\n\t\tif (!this.snapshot.storedProviders.has(providerId) && !configuredStatus?.configured) return;\n\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders).add(providerId);\n\t\tconst auth = new Map(this.snapshot.auth);\n\t\t// Never clobber a real check result.\n\t\tif (!auth.get(providerId)) auth.set(providerId, { type, source: \"configured provider\" });\n\t\tthis.snapshot = {\n\t\t\t...this.snapshot,\n\t\t\tauth,\n\t\t\tconfiguredProviders,\n\t\t\tavailable: this.snapshot.all.filter((model) => configuredProviders.has(model.provider)),\n\t\t};\n\t}\n\n\tregisterProvider(providerId: string, config: ProviderConfigInput): void {\n\t\t// Validate the incoming registration on its own, like the legacy registry:\n\t\t// a broken re-registration must throw without touching the stored config.\n\t\tvalidateExtensionProvider(providerId, this.builtins.get(providerId), this.config.getProvider(providerId), config);\n\t\tthis.nativeExtensionProviders.delete(providerId);\n\t\t// Re-registration merges defined values over the previous registration and\n\t\t// preserves undefined ones, matching the legacy ModelRegistry contract.\n\t\tconst previous = this.extensionProviders.get(providerId);\n\t\tconst effective: ProviderConfigInput = { ...previous };\n\t\tfor (const [key, value] of Object.entries(config)) {\n\t\t\tif (value !== undefined) (effective as Record<string, unknown>)[key] = value;\n\t\t}\n\t\tthis.extensionProviders.set(providerId, effective);\n\t\tthis.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tthis.markProvisionallyConfigured(\n\t\t\tproviderId,\n\t\t\tconfiguredRequestAuthStatus(this.config.getProvider(providerId), effective),\n\t\t\teffective.oauth && !effective.apiKey ? \"oauth\" : \"api_key\",\n\t\t);\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\tunregisterProvider(providerId: string): void {\n\t\tthis.extensionProviders.delete(providerId);\n\t\tthis.nativeExtensionProviders.delete(providerId);\n\t\tthis.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\t/**\n\t * Register a virtual model under `definition.provider`, which may also list physical models or\n\t * several virtual models. Re-registering the same provider and id replaces the virtual model.\n\t * Throws when the id belongs to a physical model of that provider.\n\t */\n\tregisterVirtualModel(definition: VirtualModelDefinition): void {\n\t\tconst { provider: providerId, id } = definition;\n\t\tif (!providerId.trim() || !id.trim()) throw new Error(\"Virtual model provider and id must not be empty.\");\n\t\tconst existing = this.models.getModel(providerId, id);\n\t\tif (existing && !isVirtualModel(existing)) {\n\t\t\tthrow new Error(`Virtual model ${providerId}/${id} conflicts with a physical model.`);\n\t\t}\n\t\tconst models = this.virtualModels.get(providerId) ?? new Map<string, RegisteredVirtualModel>();\n\t\tmodels.set(id, { model: createVirtualModel(definition), route: (request) => definition.route(request) });\n\t\tthis.virtualModels.set(providerId, models);\n\t\tif (!this.recomposeProvider(providerId) && !this.snapshot.configuredProviders.has(providerId)) {\n\t\t\t// A provider of only virtual models needs no credentials. Mark it configured now: session\n\t\t\t// restore checks auth before the refresh below lands.\n\t\t\tconst auth = new Map(this.snapshot.auth).set(providerId, { type: \"api_key\", source: \"virtual\" });\n\t\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders).add(providerId);\n\t\t\tthis.snapshot = { ...this.snapshot, auth, configuredProviders };\n\t\t}\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\tunregisterVirtualModel(providerId: string, id: string): void {\n\t\tconst models = this.virtualModels.get(providerId);\n\t\tif (!models?.delete(id)) return;\n\t\tif (models.size === 0) this.virtualModels.delete(providerId);\n\t\tthis.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\t/**\n\t * Ask a virtual model's router for the model and thinking level of one request. The router must\n\t * return a physical catalog model whose provider has credentials; the thinking level is clamped\n\t * to that model. Throws when routing fails.\n\t *\n\t * `previous` reports the latest successful response in `messages`. A retry passes the failed\n\t * response as `options.failed`; `messages` no longer contains it. `options.state` is the router\n\t * state stored by the caller, which also stores the returned state.\n\t */\n\tasync resolveModel(\n\t\tmodel: Model<Api>,\n\t\tmessages: readonly Message[],\n\t\toptions: {\n\t\t\treason: ModelRouteReason;\n\t\t\tthinkingLevel: ModelThinkingLevel;\n\t\t\tsignal?: AbortSignal;\n\t\t\tfailed?: AssistantMessage;\n\t\t\tstate?: unknown;\n\t\t},\n\t): Promise<ModelRoute> {\n\t\tconst name = `Virtual model ${model.provider}/${model.id}`;\n\t\tconst virtual = this.virtualModels.get(model.provider)?.get(model.id);\n\t\tif (!virtual) throw new Error(`${name} is not registered.`);\n\t\tconst { failed, ...request } = options;\n\t\tconst latest = findLatestResponse(messages);\n\t\tconst previousModel = latest && this.getPhysicalModel(latest.provider, latest.model);\n\t\t// A failed routing attempt names the virtual model; there is no physical request to report.\n\t\tconst failedModel = failed && this.getPhysicalModel(failed.provider, failed.model);\n\t\tconst route = await virtual.route({\n\t\t\t...request,\n\t\t\tmodel,\n\t\t\tprevious: previousModel && { model: previousModel, thinkingLevel: latest?.thinkingLevel },\n\t\t\tfailed: failedModel && failed && { model: failedModel, thinkingLevel: failed.thinkingLevel, message: failed },\n\t\t\tmessages,\n\t\t});\n\t\tconst target = this.getPhysicalModel(route.model.provider, route.model.id);\n\t\tconst routed = `${name} routed to ${route.model.provider}/${route.model.id}`;\n\t\tif (!target) throw new Error(`${routed}, which is not a physical model.`);\n\t\tif (!this.hasConfiguredAuth(target.provider)) throw new Error(`${routed}, which has no credentials.`);\n\t\treturn { model: target, thinkingLevel: clampThinkingLevel(target, route.thinkingLevel), state: route.state };\n\t}\n\n\t/** A catalog chat model that is not virtual. */\n\tgetPhysicalModel(providerId: string, modelId: string): Model<Api> | undefined {\n\t\tconst model = this.models.getModel(providerId, modelId);\n\t\treturn model && !isVirtualModel(model) ? model : undefined;\n\t}\n}\n"]}
1
+ {"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CAAC,iBAAiB,CAAC,MAAM,CAAC,QAAQ,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,GAAG,MAAM,6BAA6B,CAAC,CAAC;QACtG,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,aAAa,EAAE,kBAAkB,CAAC,MAAM,EAAE,KAAK,CAAC,aAAa,CAAC,EAAE,KAAK,EAAE,KAAK,CAAC,KAAK,EAAE,CAAC;IAC9G,CAAC;IAED,gDAAgD;IAChD,gBAAgB,CAAC,UAAkB,EAAE,OAAe;QACnD,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QACxD,OAAO,KAAK,IAAI,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;IAC5D,CAAC;CACD","sourcesContent":["import { dirname, join } from \"node:path\";\nimport {\n\ttype AnyModel,\n\ttype Api,\n\ttype ApiStreamOptions,\n\ttype AssistantImages,\n\ttype AssistantMessage,\n\ttype AssistantMessageEventStream,\n\ttype AuthCheck,\n\ttype AuthInteraction,\n\ttype AuthOperationOptions,\n\ttype AuthResult,\n\ttype AuthType,\n\ttype ClassifierApi,\n\ttype ClassifierContext,\n\ttype ClassifierModel,\n\ttype ClassifierOptions,\n\ttype ClassifierResult,\n\ttype Context,\n\ttype Credential,\n\ttype CredentialInfo,\n\ttype CredentialStore,\n\tclampThinkingLevel,\n\tcreateModels,\n\ttype DeferredCancelOptions,\n\ttype DeferredFetchOptions,\n\ttype DeferredHandle,\n\ttype ImageApi,\n\ttype ImageModel,\n\ttype ImagesContext,\n\ttype ImagesOptions,\n\ttype LoginOptions,\n\tlazyStream,\n\ttype Message,\n\ttype Model,\n\ttype Models,\n\ttype ModelsApiStreamOptions,\n\ttype ModelsClassifierOptions,\n\ttype ModelsDeferredCancelOptions,\n\ttype ModelsDeferredFetchOptions,\n\tModelsError,\n\ttype ModelsImagesOptions,\n\ttype ModelsRefreshOptions,\n\ttype ModelsRefreshResult,\n\ttype ModelsRequestTransforms,\n\ttype ModelsSimpleStreamOptions,\n\ttype ModelsStore,\n\ttype ModelThinkingLevel,\n\ttype ModelType,\n\ttype ModelTypeMap,\n\ttype MutableModels,\n\tnormalizeContext,\n\ttype Provider,\n\ttype ProviderHeaders,\n\ttype ProviderRequestOptions,\n\ttype SimpleStreamOptions,\n\ttype StreamOptions,\n} from \"@earendil-works/pi-ai\";\nimport * as builtinProviderCatalog from \"@earendil-works/pi-ai/providers/all\";\nimport {\n\tassertChatModel,\n\tassertClassifierInputSupported,\n\tassertClassifierModel,\n\tassertImageModel,\n\tclassifierErrorResult,\n\timageErrorResult,\n} from \"@earendil-works/pi-ai/utils/model-operations\";\nimport { getAgentDir } from \"../config.ts\";\nimport { operationSignal, raceWithAbortSignal } from \"../utils/abort.ts\";\nimport { AuthStorage as DefaultAuthStorage } from \"./auth-storage.ts\";\nimport { ModelConfig } from \"./model-config.ts\";\nimport { FileModelsStore, InMemoryCodingAgentModelsStore } from \"./models-store.ts\";\nimport {\n\ttype AuthStatus,\n\ttype CompatibilityRequestConfig,\n\tcomposeModelProvider,\n\tconfiguredRequestAuthStatus,\n\ttype ProviderConfigInput,\n\tresolveCompatibilityRequestConfig,\n\tresolveConfiguredModelHeaders,\n\tvalidateExtensionProvider,\n} from \"./provider-composer.ts\";\nimport { withRemoteCatalog } from \"./remote-catalog-provider.ts\";\nimport { RuntimeCredentials } from \"./runtime-credentials.ts\";\nimport {\n\tcreateVirtualModel,\n\tfindLatestResponse,\n\tisVirtualModel,\n\ttype ModelRoute,\n\ttype ModelRouteReason,\n\ttype VirtualModelDefinition,\n\twithVirtualModels,\n} from \"./virtual-models.ts\";\n\ninterface RegisteredVirtualModel {\n\tmodel: Model<Api>;\n\troute: VirtualModelDefinition[\"route\"];\n}\n\ninterface ModelRuntimeSnapshot {\n\tall: readonly Model<Api>[];\n\tavailable: readonly Model<Api>[];\n\tconfiguredProviders: ReadonlySet<string>;\n\tstoredProviders: ReadonlySet<string>;\n\tauth: ReadonlyMap<string, AuthCheck | undefined>;\n}\n\nexport interface CreateModelRuntimeOptions {\n\t/** Credential storage. Defaults to the file at authPath. */\n\tcredentials?: CredentialStore;\n\tauthPath?: string;\n\tmodelsPath?: string | null;\n\tmodelsStore?: ModelsStore;\n\tmodelsStorePath?: string;\n\t/** Allow create() to refresh model catalogs over the network. Defaults to false. */\n\tallowModelNetwork?: boolean;\n\t/** Timeout for the create-time network model refresh. */\n\tmodelRefreshTimeoutMs?: number;\n\tcatalogBaseUrl?: string;\n\t/** Optional caller cancellation for initial cache restoration and availability checks. */\n\tsignal?: AbortSignal;\n\t/** Skip initial catalog and availability refresh. Static models remain available. */\n\trefreshOnCreate?: boolean;\n}\n\nexport interface ModelRuntimeAuthOverrides extends AuthOperationOptions {\n\tapiKey?: string;\n\tenv?: Record<string, string>;\n\t/** Require this much remaining OAuth-token validity; defaults to five minutes. */\n\tminOAuthValidityMs?: number;\n}\n\nexport type CredentialSynchronizationOperation = \"login\" | \"logout\" | \"setRuntimeApiKey\" | \"removeRuntimeApiKey\";\n\n/** Credentials changed successfully, but the local model/auth snapshot could not be synchronized. */\nexport class CredentialSynchronizationError extends Error {\n\treadonly providerId: string;\n\treadonly operation: CredentialSynchronizationOperation;\n\treadonly credential: Credential | undefined;\n\n\tconstructor(\n\t\tproviderId: string,\n\t\toperation: CredentialSynchronizationOperation,\n\t\tcredential: Credential | undefined,\n\t\toptions: ErrorOptions,\n\t) {\n\t\tsuper(`Credential ${operation} committed for ${providerId}, but local synchronization failed`, options);\n\t\tthis.name = \"CredentialSynchronizationError\";\n\t\tthis.providerId = providerId;\n\t\tthis.operation = operation;\n\t\tthis.credential = credential;\n\t}\n}\n\nfunction mergeHeaders(\n\tbase: ProviderHeaders | undefined,\n\toverride: ProviderHeaders | undefined,\n): ProviderHeaders | undefined {\n\tif (!base && !override) return undefined;\n\tconst merged = { ...base };\n\tfor (const [name, value] of Object.entries(override ?? {})) {\n\t\tconst lowerName = name.toLowerCase();\n\t\tfor (const existingName of Object.keys(merged)) {\n\t\t\tif (existingName.toLowerCase() === lowerName) delete merged[existingName];\n\t\t}\n\t\tmerged[name] = value;\n\t}\n\treturn merged;\n}\n\n/** Configured pi-ai Models collection used by coding-agent and SDK consumers. */\nexport class ModelRuntime implements Models {\n\tprivate readonly models: MutableModels;\n\tprivate readonly credentials: RuntimeCredentials;\n\tprivate readonly defaultBuiltins: ReadonlyMap<string, Provider>;\n\tprivate readonly builtins = new Map<string, Provider>();\n\tprivate readonly nativeExtensionProviders = new Map<string, Provider>();\n\tprivate readonly extensionProviders = new Map<string, ProviderConfigInput>();\n\t/** Virtual models by provider id, then model id. */\n\tprivate readonly virtualModels = new Map<string, Map<string, RegisteredVirtualModel>>();\n\tprivate readonly compositionErrors = new Map<string, string>();\n\tprivate readonly modelsPath: string | undefined;\n\tprivate readonly modelNetworkEnabled: boolean;\n\tprivate config: ModelConfig;\n\tprivate snapshot: ModelRuntimeSnapshot = {\n\t\tall: [],\n\t\tavailable: [],\n\t\tconfiguredProviders: new Set(),\n\t\tstoredProviders: new Set(),\n\t\tauth: new Map(),\n\t};\n\tprivate availabilityRefreshSeq = 0;\n\tprivate availabilityErrorSeq = 0;\n\tprivate readonly providerAvailabilitySeq = new Map<string, number>();\n\tprivate availabilityError: string | undefined;\n\tprivate readonly credentialOperations = new Map<string, Promise<unknown>>();\n\n\tprivate constructor(\n\t\tcredentials: RuntimeCredentials,\n\t\tconfig: ModelConfig,\n\t\tmodelsPath: string | undefined,\n\t\tmodelsStore: ModelsStore,\n\t\tproviders: readonly Provider[],\n\t\tmodelNetworkEnabled: boolean,\n\t) {\n\t\tthis.credentials = credentials;\n\t\tthis.config = config;\n\t\tthis.modelsPath = modelsPath;\n\t\tthis.modelNetworkEnabled = modelNetworkEnabled;\n\t\tthis.defaultBuiltins = new Map(providers.map((provider) => [provider.id, provider]));\n\t\tfor (const [providerId, provider] of this.defaultBuiltins) this.builtins.set(providerId, provider);\n\t\tthis.models = createModels({ credentials, modelsStore });\n\t\tthis.rebuildProviders();\n\t}\n\n\tstatic async create(options: CreateModelRuntimeOptions = {}): Promise<ModelRuntime> {\n\t\tconst credentials = new RuntimeCredentials(options.credentials ?? DefaultAuthStorage.create(options.authPath));\n\t\tconst modelsPath =\n\t\t\toptions.modelsPath === null ? undefined : (options.modelsPath ?? join(getAgentDir(), \"models.json\"));\n\t\tconst config = await ModelConfig.load(modelsPath);\n\t\tconst modelsStore =\n\t\t\toptions.modelsStore ??\n\t\t\t(modelsPath\n\t\t\t\t? new FileModelsStore(options.modelsStorePath ?? join(dirname(modelsPath), \"models-store.json\"))\n\t\t\t\t: new InMemoryCodingAgentModelsStore());\n\t\tconst builtinModelDataGeneratedAt = builtinProviderCatalog.getBuiltinModelDataGeneratedAt();\n\t\tconst providers = builtinProviderCatalog\n\t\t\t.builtinProviders()\n\t\t\t.map((provider) =>\n\t\t\t\tprovider.id === \"radius\"\n\t\t\t\t\t? provider\n\t\t\t\t\t: withRemoteCatalog(provider, options.catalogBaseUrl, builtinModelDataGeneratedAt),\n\t\t\t);\n\t\tconst runtime = new ModelRuntime(\n\t\t\tcredentials,\n\t\t\tconfig,\n\t\t\tmodelsPath,\n\t\t\tmodelsStore,\n\t\t\tproviders,\n\t\t\tprocess.env.PI_OFFLINE === undefined,\n\t\t);\n\t\truntime.configureRadiusProviders();\n\t\truntime.rebuildProviders();\n\t\tconst refreshFromNetwork = runtime.modelNetworkEnabled && options.allowModelNetwork === true;\n\t\tconst controller =\n\t\t\trefreshFromNetwork && options.modelRefreshTimeoutMs !== undefined ? new AbortController() : undefined;\n\t\tconst timeout = controller ? setTimeout(() => controller.abort(), options.modelRefreshTimeoutMs) : undefined;\n\t\tconst signal = controller\n\t\t\t? options.signal\n\t\t\t\t? AbortSignal.any([options.signal, controller.signal])\n\t\t\t\t: controller.signal\n\t\t\t: options.signal;\n\t\ttry {\n\t\t\tif (options.refreshOnCreate !== false) {\n\t\t\t\tawait runtime.refresh({ allowNetwork: refreshFromNetwork, signal });\n\t\t\t}\n\t\t} finally {\n\t\t\tif (timeout) clearTimeout(timeout);\n\t\t}\n\t\treturn runtime;\n\t}\n\n\tprivate configureRadiusProviders(): void {\n\t\tthis.builtins.clear();\n\t\tfor (const [providerId, provider] of this.defaultBuiltins) this.builtins.set(providerId, provider);\n\t\tfor (const providerId of this.config.getProviderIds()) {\n\t\t\tconst config = this.config.getProvider(providerId);\n\t\t\tif (config?.oauth !== \"radius\" || !config.baseUrl) continue;\n\t\t\tthis.builtins.set(\n\t\t\t\tproviderId,\n\t\t\t\tbuiltinProviderCatalog.radiusProvider({\n\t\t\t\t\tid: providerId,\n\t\t\t\t\tname: config.name ?? providerId,\n\t\t\t\t\tgateway: config.baseUrl.replace(/\\/v1\\/?$/u, \"\"),\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate providerIds(): Set<string> {\n\t\treturn new Set([\n\t\t\t...this.builtins.keys(),\n\t\t\t...this.nativeExtensionProviders.keys(),\n\t\t\t...this.config.getProviderIds(),\n\t\t\t...this.extensionProviders.keys(),\n\t\t\t...this.virtualModels.keys(),\n\t\t]);\n\t}\n\n\t/** Returns the provider without virtual models, or undefined when only virtual models define it. */\n\tprivate recomposeProvider(providerId: string): Provider | undefined {\n\t\tconst provider = this.composeProvider(providerId);\n\t\tconst virtualModels = [...(this.virtualModels.get(providerId)?.values() ?? [])].map((entry) => entry.model);\n\t\tif (virtualModels.length > 0) this.models.setProvider(withVirtualModels(providerId, provider, virtualModels));\n\t\telse if (provider) this.models.setProvider(provider);\n\t\telse this.models.deleteProvider(providerId);\n\t\treturn provider;\n\t}\n\n\t/** The provider without virtual models, or undefined when nothing defines it. */\n\tprivate composeProvider(providerId: string): Provider | undefined {\n\t\tconst base = this.nativeExtensionProviders.get(providerId) ?? this.builtins.get(providerId);\n\t\tconst extension = this.extensionProviders.get(providerId);\n\t\tif (!this.config.getProvider(providerId) && !extension) {\n\t\t\t// No overlays: use the builtin untouched so its auth/login/stream behavior is exact.\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn base;\n\t\t}\n\t\ttry {\n\t\t\tconst provider = composeModelProvider(providerId, base, this.config, extension);\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn provider;\n\t\t} catch (error) {\n\t\t\tthis.compositionErrors.set(providerId, error instanceof Error ? error.message : String(error));\n\t\t\treturn base;\n\t\t}\n\t}\n\n\tprivate rebuildProviders(): void {\n\t\tthis.models.clearProviders();\n\t\tthis.compositionErrors.clear();\n\t\tfor (const providerId of this.providerIds()) this.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t}\n\n\tprivate updateModelSnapshot(): void {\n\t\tconst all = [...this.models.getModels()];\n\t\tthis.snapshot = {\n\t\t\t...this.snapshot,\n\t\t\tall,\n\t\t\tavailable: all.filter((model) => this.snapshot.configuredProviders.has(model.provider)),\n\t\t};\n\t}\n\n\tprivate async runAvailabilityRefresh(seq: number, errorSeq: number, signal: AbortSignal): Promise<void> {\n\t\tconst providers = this.models.getProviders();\n\t\tconst [available, checks, credentials] = await Promise.all([\n\t\t\tthis.models.getAvailable(undefined, { signal }),\n\t\t\tPromise.all(\n\t\t\t\tproviders.map(\n\t\t\t\t\tasync (provider): Promise<[string, AuthCheck | undefined]> => [\n\t\t\t\t\t\tprovider.id,\n\t\t\t\t\t\tawait this.models.checkAuth(provider.id, { signal }),\n\t\t\t\t\t],\n\t\t\t\t),\n\t\t\t),\n\t\t\tthis.credentials.list({ signal }),\n\t\t]);\n\t\tif (seq !== this.availabilityRefreshSeq) return;\n\t\tconst auth = new Map(checks);\n\t\tconst configuredProviders = new Set(\n\t\t\tchecks\n\t\t\t\t.filter((entry): entry is [string, AuthCheck] => entry[1] !== undefined)\n\t\t\t\t.map(([providerId]) => providerId),\n\t\t);\n\t\tthis.snapshot = {\n\t\t\tall: [...this.models.getModels()],\n\t\t\tavailable: [...available],\n\t\t\tconfiguredProviders,\n\t\t\tstoredProviders: new Set(credentials.map((entry) => entry.providerId)),\n\t\t\tauth,\n\t\t};\n\t\tif (errorSeq === this.availabilityErrorSeq) this.availabilityError = undefined;\n\t}\n\n\tprivate queueAvailabilityRefresh(signal?: AbortSignal): Promise<void> {\n\t\tconst seq = ++this.availabilityRefreshSeq;\n\t\tfor (const [providerId, providerSeq] of this.providerAvailabilitySeq) {\n\t\t\tthis.providerAvailabilitySeq.set(providerId, providerSeq + 1);\n\t\t}\n\t\tconst errorSeq = ++this.availabilityErrorSeq;\n\t\tconst effectiveSignal = operationSignal(signal);\n\t\treturn this.runAvailabilityRefresh(seq, errorSeq, effectiveSignal).catch((error) => {\n\t\t\tif (errorSeq === this.availabilityErrorSeq && !effectiveSignal.aborted) {\n\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t}\n\t\t\tthrow error;\n\t\t});\n\t}\n\n\tprivate async refreshProviderAvailability(providerId: string, signal: AbortSignal): Promise<void> {\n\t\t// Invalidate any full availability pass that started before this credential change.\n\t\t++this.availabilityRefreshSeq;\n\t\tconst providerSeq = (this.providerAvailabilitySeq.get(providerId) ?? 0) + 1;\n\t\tthis.providerAvailabilitySeq.set(providerId, providerSeq);\n\t\tconst errorSeq = ++this.availabilityErrorSeq;\n\t\ttry {\n\t\t\tconst [available, auth, credential] = await Promise.all([\n\t\t\t\tthis.models.getAvailable(providerId, { signal }),\n\t\t\t\tthis.models.checkAuth(providerId, { signal }),\n\t\t\t\tthis.credentials.read(providerId, { signal }),\n\t\t\t]);\n\t\t\tsignal.throwIfAborted();\n\t\t\tif (this.providerAvailabilitySeq.get(providerId) !== providerSeq) return;\n\t\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders);\n\t\t\tconst storedProviders = new Set(this.snapshot.storedProviders);\n\t\t\tconst authByProvider = new Map(this.snapshot.auth);\n\t\t\tif (auth) {\n\t\t\t\tconfiguredProviders.add(providerId);\n\t\t\t\tauthByProvider.set(providerId, auth);\n\t\t\t} else {\n\t\t\t\tconfiguredProviders.delete(providerId);\n\t\t\t\tauthByProvider.delete(providerId);\n\t\t\t}\n\t\t\tif (credential) storedProviders.add(providerId);\n\t\t\telse storedProviders.delete(providerId);\n\t\t\tconst all = [...this.models.getModels()];\n\t\t\tconst availableById = new Map(\n\t\t\t\t[...this.snapshot.available.filter((model) => model.provider !== providerId), ...available].map((model) => [\n\t\t\t\t\t`${model.provider}\\0${model.id}`,\n\t\t\t\t\tmodel,\n\t\t\t\t]),\n\t\t\t);\n\t\t\tthis.snapshot = {\n\t\t\t\tall,\n\t\t\t\tavailable: all.flatMap((model) => availableById.get(`${model.provider}\\0${model.id}`) ?? []),\n\t\t\t\tconfiguredProviders,\n\t\t\t\tstoredProviders,\n\t\t\t\tauth: authByProvider,\n\t\t\t};\n\t\t\tif (errorSeq === this.availabilityErrorSeq) this.availabilityError = undefined;\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\tthis.providerAvailabilitySeq.get(providerId) === providerSeq &&\n\t\t\t\terrorSeq === this.availabilityErrorSeq &&\n\t\t\t\t!signal.aborted\n\t\t\t) {\n\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tgetProviders(): readonly Provider[] {\n\t\treturn this.models.getProviders();\n\t}\n\n\tgetProvider(providerId: string): Provider | undefined {\n\t\treturn this.models.getProvider(providerId);\n\t}\n\n\tgetModels(providerId?: string): readonly Model<Api>[] {\n\t\treturn this.models.getModels(providerId);\n\t}\n\n\tgetModel(providerId: string, modelId: string): Model<Api> | undefined {\n\t\treturn this.models.getModel(providerId, modelId);\n\t}\n\n\tgetModelsOfType<TType extends ModelType>(type: TType, providerId?: string): readonly ModelTypeMap[TType][] {\n\t\treturn this.models.getModelsOfType(type, providerId);\n\t}\n\n\tgetModelOfType<TType extends ModelType>(\n\t\ttype: TType,\n\t\tproviderId: string,\n\t\tmodelId: string,\n\t): ModelTypeMap[TType] | undefined {\n\t\treturn this.models.getModelOfType(type, providerId, modelId);\n\t}\n\n\tgetAllModels(providerId?: string): readonly AnyModel[] {\n\t\treturn this.models.getAllModels(providerId);\n\t}\n\n\tgetAvailableOfType<TType extends ModelType>(\n\t\ttype: TType,\n\t\tproviderId?: string,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<readonly ModelTypeMap[TType][]> {\n\t\treturn this.models.getAvailableOfType(type, providerId, options);\n\t}\n\n\tgetAllAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly AnyModel[]> {\n\t\treturn this.models.getAllAvailable(providerId, options);\n\t}\n\n\tasync checkAuth(providerId: string, options?: AuthOperationOptions): Promise<AuthCheck | undefined> {\n\t\treturn this.models.checkAuth(providerId, options);\n\t}\n\n\tasync getAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly Model<Api>[]> {\n\t\tif (providerId) {\n\t\t\tconst errorSeq = ++this.availabilityErrorSeq;\n\t\t\ttry {\n\t\t\t\tconst available = await this.models.getAvailable(providerId, options);\n\t\t\t\tif (errorSeq === this.availabilityErrorSeq) this.availabilityError = undefined;\n\t\t\t\treturn available;\n\t\t\t} catch (error) {\n\t\t\t\tif (errorSeq === this.availabilityErrorSeq && !options?.signal?.aborted) {\n\t\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\tawait this.queueAvailabilityRefresh(options?.signal);\n\t\treturn this.snapshot.available;\n\t}\n\n\tgetAvailableSnapshot(): readonly Model<Api>[] {\n\t\treturn this.snapshot.available;\n\t}\n\n\tgetError(): string | undefined {\n\t\tconst errors: string[] = [];\n\t\tconst configError = this.config.getError();\n\t\tif (configError) errors.push(configError);\n\t\tfor (const [providerId, error] of this.compositionErrors) {\n\t\t\terrors.push(`Provider \"${providerId}\": ${error}`);\n\t\t}\n\t\tif (this.availabilityError) errors.push(`Availability refresh: ${this.availabilityError}`);\n\t\treturn errors.length > 0 ? errors.join(\"\\n\\n\") : undefined;\n\t}\n\n\tgetRegisteredProviderConfig(providerId: string): ProviderConfigInput | undefined {\n\t\treturn this.extensionProviders.get(providerId);\n\t}\n\n\tgetRegisteredProviderIds(): readonly string[] {\n\t\treturn [...new Set([...this.extensionProviders.keys(), ...this.nativeExtensionProviders.keys()])];\n\t}\n\n\tgetRegisteredNativeProvider(providerId: string): Provider | undefined {\n\t\treturn this.nativeExtensionProviders.get(providerId);\n\t}\n\n\t/** @internal Compatibility fallback for ModelRegistry when provider auth is unconfigured. */\n\tgetCompatibilityRequestConfig(model: Model<Api>): CompatibilityRequestConfig {\n\t\treturn resolveCompatibilityRequestConfig(\n\t\t\tmodel,\n\t\t\tthis.config.getProvider(model.provider),\n\t\t\tthis.extensionProviders.get(model.provider),\n\t\t);\n\t}\n\n\tisUsingOAuth(providerId: string): boolean {\n\t\treturn this.snapshot.auth.get(providerId)?.type === \"oauth\";\n\t}\n\n\tisUsingSubscription(providerId: string): boolean {\n\t\treturn this.isUsingOAuth(providerId) && this.models.getProvider(providerId)?.auth.oauth?.isSubscription === true;\n\t}\n\n\thasConfiguredAuth(providerId: string): boolean {\n\t\treturn this.snapshot.configuredProviders.has(providerId);\n\t}\n\n\tgetAuth(providerId: string, overrides?: ModelRuntimeAuthOverrides): Promise<AuthResult | undefined>;\n\tgetAuth(model: AnyModel, overrides?: ModelRuntimeAuthOverrides): Promise<AuthResult | undefined>;\n\tasync getAuth(\n\t\tproviderOrModel: string | AnyModel,\n\t\toverrides: ModelRuntimeAuthOverrides = {},\n\t): Promise<AuthResult | undefined> {\n\t\tif (typeof providerOrModel === \"string\") return this.models.getAuth(providerOrModel, overrides);\n\t\tconst resolution = await this.models.getAuth(providerOrModel, overrides);\n\t\tif (!resolution) return undefined;\n\t\tconst configuredHeaders = resolveConfiguredModelHeaders(\n\t\t\tproviderOrModel,\n\t\t\tthis.config.getProvider(providerOrModel.provider),\n\t\t\tthis.extensionProviders.get(providerOrModel.provider),\n\t\t\t{ ...(resolution.env ?? {}), ...(overrides.env ?? {}) },\n\t\t);\n\t\treturn {\n\t\t\t...resolution,\n\t\t\tauth: {\n\t\t\t\t...resolution.auth,\n\t\t\t\theaders: mergeHeaders(resolution.auth.headers, configuredHeaders),\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate enqueueCredentialOperation<T>(providerId: string, signal: AbortSignal, task: () => Promise<T>): Promise<T> {\n\t\tconst previous = this.credentialOperations.get(providerId) ?? Promise.resolve();\n\t\tlet markStarted: (() => void) | undefined;\n\t\tconst started = new Promise<void>((resolve) => {\n\t\t\tmarkStarted = resolve;\n\t\t});\n\t\tconst operation = (async () => {\n\t\t\tawait previous.catch(() => {});\n\t\t\tsignal.throwIfAborted();\n\t\t\tmarkStarted?.();\n\t\t\treturn task();\n\t\t})();\n\t\tconst tail = operation.catch(() => {});\n\t\tthis.credentialOperations.set(providerId, tail);\n\t\tvoid tail.then(() => {\n\t\t\tif (this.credentialOperations.get(providerId) === tail) this.credentialOperations.delete(providerId);\n\t\t});\n\t\treturn raceWithAbortSignal(started, signal).then(() => operation);\n\t}\n\n\tprivate async synchronizeCredentialState(\n\t\tproviderId: string,\n\t\toperation: CredentialSynchronizationOperation,\n\t\tcredential: Credential | undefined,\n\t\tsignal: AbortSignal,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tsignal.throwIfAborted();\n\t\t\tthis.recomposeProvider(providerId);\n\t\t\tconst compositionError = this.compositionErrors.get(providerId);\n\t\t\tif (compositionError) throw new Error(compositionError);\n\t\t\tconst result = await this.models.refresh({ allowNetwork: false, providers: [providerId], signal });\n\t\t\tif (result.aborted) signal.throwIfAborted();\n\t\t\tconst refreshError = result.errors.get(providerId);\n\t\t\tif (refreshError) throw refreshError;\n\t\t\tthis.updateModelSnapshot();\n\t\t\tawait this.refreshProviderAvailability(providerId, signal);\n\t\t} catch (cause) {\n\t\t\tthrow new CredentialSynchronizationError(providerId, operation, credential, { cause });\n\t\t}\n\t}\n\n\tsetRuntimeApiKey(providerId: string, apiKey: string, options: AuthOperationOptions = {}): Promise<void> {\n\t\tconst signal = operationSignal(options.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tthis.credentials.setRuntimeApiKey(providerId, apiKey);\n\t\t\tawait this.synchronizeCredentialState(\n\t\t\t\tproviderId,\n\t\t\t\t\"setRuntimeApiKey\",\n\t\t\t\t{ type: \"api_key\", key: apiKey },\n\t\t\t\tsignal,\n\t\t\t);\n\t\t});\n\t}\n\n\tremoveRuntimeApiKey(providerId: string, options: AuthOperationOptions = {}): Promise<void> {\n\t\tconst signal = operationSignal(options.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tthis.credentials.removeRuntimeApiKey(providerId);\n\t\t\tawait this.synchronizeCredentialState(providerId, \"removeRuntimeApiKey\", undefined, signal);\n\t\t});\n\t}\n\n\tlistCredentials(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]> {\n\t\treturn this.credentials.list(options);\n\t}\n\n\tgetProviderAuthStatus(providerId: string): AuthStatus {\n\t\tif (this.credentials.hasRuntimeApiKey(providerId)) return { configured: true, source: \"runtime\" };\n\t\tif (this.snapshot.storedProviders.has(providerId)) return { configured: true, source: \"stored\" };\n\t\tconst configured = configuredRequestAuthStatus(\n\t\t\tthis.config.getProvider(providerId),\n\t\t\tthis.extensionProviders.get(providerId),\n\t\t);\n\t\tif (configured) return configured;\n\t\tconst check = this.snapshot.auth.get(providerId);\n\t\treturn check ? { configured: true, source: \"environment\", label: check.source } : { configured: false };\n\t}\n\n\tprivate async prepareRequest<\n\t\tTModel extends AnyModel,\n\t\tTOptions extends ProviderRequestOptions<TModel> & ModelsRequestTransforms,\n\t>(\n\t\tmodel: TModel,\n\t\toptions: TOptions | undefined,\n\t): Promise<{\n\t\tprovider: Provider;\n\t\tmodel: TModel;\n\t\toptions: Omit<TOptions, \"transformHeaders\"> & ProviderRequestOptions<TModel>;\n\t}> {\n\t\tconst provider = this.models.getProvider(model.provider);\n\t\tif (!provider) throw new ModelsError(\"provider\", `Unknown provider: ${model.provider}`);\n\t\tconst resolution = await this.getAuth(model, {\n\t\t\tapiKey: options?.apiKey,\n\t\t\tenv: options?.env,\n\t\t\tsignal: options?.signal,\n\t\t});\n\t\tif (!resolution) throw new ModelsError(\"auth\", `Provider is not configured: ${model.provider}`);\n\n\t\tconst { transformHeaders, ...rawProviderOptions } = options ?? {};\n\t\tconst providerOptions = rawProviderOptions as Omit<TOptions, \"transformHeaders\"> & ProviderRequestOptions<TModel>;\n\t\tlet headers = mergeHeaders(resolution.auth.headers, providerOptions.headers);\n\t\tif (transformHeaders) headers = await transformHeaders(headers ?? {});\n\t\tconst env =\n\t\t\tresolution.env || providerOptions.env\n\t\t\t\t? { ...(resolution.env ?? {}), ...(providerOptions.env ?? {}) }\n\t\t\t\t: undefined;\n\t\tconst requestModel: TModel = resolution.auth.baseUrl ? { ...model, baseUrl: resolution.auth.baseUrl } : model;\n\t\treturn {\n\t\t\tprovider,\n\t\t\tmodel: requestModel,\n\t\t\toptions: {\n\t\t\t\t...providerOptions,\n\t\t\t\tapiKey: providerOptions.apiKey ?? resolution.auth.apiKey,\n\t\t\t\theaders,\n\t\t\t\tenv,\n\t\t\t} as Omit<TOptions, \"transformHeaders\"> & ProviderRequestOptions<TModel>,\n\t\t};\n\t}\n\n\tstream<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): AssistantMessageEventStream {\n\t\tconst transcript = normalizeContext(context);\n\t\treturn lazyStream(model, async () => {\n\t\t\tassertChatModel(model);\n\t\t\tconst prepared = await this.prepareRequest(\n\t\t\t\tmodel,\n\t\t\t\toptions as (StreamOptions & ModelsRequestTransforms) | undefined,\n\t\t\t);\n\t\t\treturn prepared.provider.stream(prepared.model, transcript, prepared.options as ApiStreamOptions<TApi>);\n\t\t});\n\t}\n\n\tcomplete<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): Promise<AssistantMessage> {\n\t\treturn this.stream(model, context, options).result();\n\t}\n\n\tstreamSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): AssistantMessageEventStream {\n\t\tconst transcript = normalizeContext(context);\n\t\tif (isVirtualModel(model)) {\n\t\t\t// Requests outside the agent loop are routed here. Callers sized them before routing, so\n\t\t\t// cap the output budget to the routed model.\n\t\t\treturn lazyStream(model, async () => {\n\t\t\t\tconst route = await this.resolveModel(model, transcript.messages, {\n\t\t\t\t\treason: \"direct\",\n\t\t\t\t\tthinkingLevel: options?.reasoning ?? \"off\",\n\t\t\t\t\tsignal: options?.signal,\n\t\t\t\t});\n\t\t\t\tconst { maxTokens: limit } = route.model;\n\t\t\t\tconst maxTokens = options?.maxTokens && limit > 0 ? Math.min(options.maxTokens, limit) : options?.maxTokens;\n\t\t\t\tconst reasoning = route.thinkingLevel === \"off\" ? undefined : route.thinkingLevel;\n\t\t\t\t// Caller credentials were resolved for the virtual model's provider. Another provider\n\t\t\t\t// resolves its own, so they are not sent to the wrong vendor.\n\t\t\t\tconst { apiKey, headers, env, ...rest } = options ?? {};\n\t\t\t\tconst auth = route.model.provider === model.provider ? { apiKey, headers, env } : {};\n\t\t\t\treturn this.streamSimple(route.model, context, { ...rest, ...auth, maxTokens, reasoning });\n\t\t\t});\n\t\t}\n\t\treturn lazyStream(model, async () => {\n\t\t\tassertChatModel(model);\n\t\t\tconst prepared = await this.prepareRequest(model, options);\n\t\t\treturn prepared.provider.streamSimple(prepared.model, transcript, prepared.options as SimpleStreamOptions);\n\t\t});\n\t}\n\n\tcompleteSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): Promise<AssistantMessage> {\n\t\treturn this.streamSimple(model, context, options).result();\n\t}\n\n\tstreamDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredFetchOptions,\n\t): AssistantMessageEventStream {\n\t\treturn lazyStream(model, async () => {\n\t\t\tassertChatModel(model);\n\t\t\tconst prepared = await this.prepareRequest(model, options);\n\t\t\tif (!prepared.provider.fetchDeferred) {\n\t\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support deferred responses`);\n\t\t\t}\n\t\t\treturn prepared.provider.fetchDeferred(prepared.model, handle, prepared.options as DeferredFetchOptions);\n\t\t});\n\t}\n\n\tasync fetchDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredFetchOptions,\n\t): Promise<AssistantMessage> {\n\t\treturn this.streamDeferred(model, handle, options).result();\n\t}\n\n\tasync cancelDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredCancelOptions,\n\t): Promise<void> {\n\t\tassertChatModel(model);\n\t\tconst prepared = await this.prepareRequest(model, options);\n\t\tif (!prepared.provider.cancelDeferred) {\n\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support deferred responses`);\n\t\t}\n\t\tawait prepared.provider.cancelDeferred(prepared.model, handle, prepared.options as DeferredCancelOptions);\n\t}\n\n\tasync generateImages(\n\t\tmodel: ImageModel<ImageApi>,\n\t\tcontext: ImagesContext,\n\t\toptions?: ModelsImagesOptions,\n\t): Promise<AssistantImages> {\n\t\ttry {\n\t\t\tassertImageModel(model);\n\t\t\tconst prepared = await this.prepareRequest(model, options);\n\t\t\tif (!prepared.provider.generateImages) {\n\t\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support image generation`);\n\t\t\t}\n\t\t\treturn await prepared.provider.generateImages(prepared.model, context, prepared.options as ImagesOptions);\n\t\t} catch (error) {\n\t\t\treturn imageErrorResult(model, error, options?.signal?.aborted);\n\t\t}\n\t}\n\n\tasync classify(\n\t\tmodel: ClassifierModel<ClassifierApi>,\n\t\tcontext: ClassifierContext,\n\t\toptions?: ModelsClassifierOptions,\n\t): Promise<ClassifierResult> {\n\t\ttry {\n\t\t\tassertClassifierModel(model);\n\t\t\tassertClassifierInputSupported(model, context);\n\t\t\tconst prepared = await this.prepareRequest(model, options);\n\t\t\tif (!prepared.provider.classify) {\n\t\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support classification`);\n\t\t\t}\n\t\t\treturn await prepared.provider.classify(prepared.model, context, prepared.options as ClassifierOptions);\n\t\t} catch (error) {\n\t\t\treturn classifierErrorResult(model, error, options?.signal?.aborted);\n\t\t}\n\t}\n\n\tlogin(\n\t\tproviderId: string,\n\t\ttype: AuthType,\n\t\tinteraction: AuthInteraction,\n\t\toptions?: LoginOptions,\n\t): Promise<Credential> {\n\t\tconst signal = operationSignal(interaction.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tconst credential = await this.models.login(providerId, type, { ...interaction, signal }, options);\n\t\t\tawait this.synchronizeCredentialState(providerId, \"login\", credential, signal);\n\t\t\treturn credential;\n\t\t});\n\t}\n\n\tlogout(providerId: string, options: AuthOperationOptions = {}): Promise<void> {\n\t\tconst signal = operationSignal(options.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tawait this.models.logout(providerId, { signal });\n\t\t\tawait this.synchronizeCredentialState(providerId, \"logout\", undefined, signal);\n\t\t});\n\t}\n\n\tasync refresh(options: ModelsRefreshOptions = {}): Promise<ModelsRefreshResult> {\n\t\tthis.config = await ModelConfig.load(this.modelsPath);\n\t\tthis.configureRadiusProviders();\n\t\tif (options.providers) {\n\t\t\tfor (const providerId of new Set(options.providers)) this.recomposeProvider(providerId);\n\t\t\tthis.updateModelSnapshot();\n\t\t} else {\n\t\t\tthis.rebuildProviders();\n\t\t}\n\t\tconst refreshOptions = {\n\t\t\t...options,\n\t\t\tallowNetwork: options.allowNetwork ?? this.modelNetworkEnabled,\n\t\t};\n\t\t// Published pi-ai builds before ModelsStore returned void and accepted a provider ID.\n\t\t// The fallback keeps source-mode CLI tests working without rebuilding workspace dependencies.\n\t\tconst result = ((await this.models.refresh(refreshOptions)) as ModelsRefreshResult | undefined) ?? {\n\t\t\taborted: refreshOptions.signal?.aborted ?? false,\n\t\t\terrors: new Map(),\n\t\t};\n\t\tconst errors = new Map(result.errors);\n\t\tthis.updateModelSnapshot();\n\t\tif (options.providers) {\n\t\t\tawait Promise.all(\n\t\t\t\t[...new Set(options.providers)].map(async (providerId) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.refreshProviderAvailability(providerId, operationSignal(options.signal));\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!options.signal?.aborted) {\n\t\t\t\t\t\t\terrors.set(providerId, error instanceof Error ? error : new Error(String(error)));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t);\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tawait this.queueAvailabilityRefresh(options.signal);\n\t\t\t} catch {\n\t\t\t\t// Availability errors are recorded by the latest pass; refreshed models remain usable.\n\t\t\t}\n\t\t}\n\t\treturn { aborted: result.aborted || (options.signal?.aborted ?? false), errors };\n\t}\n\n\tregisterNativeProvider(provider: Provider): void {\n\t\tif (!provider.id.trim()) throw new Error(\"Provider id must not be empty.\");\n\t\tthis.extensionProviders.delete(provider.id);\n\t\tthis.nativeExtensionProviders.set(provider.id, provider);\n\t\tthis.recomposeProvider(provider.id);\n\t\tthis.updateModelSnapshot();\n\t\tthis.markProvisionallyConfigured(\n\t\t\tprovider.id,\n\t\t\tconfiguredRequestAuthStatus(this.config.getProvider(provider.id), undefined),\n\t\t\tprovider.auth.oauth && !provider.auth.apiKey ? \"oauth\" : \"api_key\",\n\t\t);\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\t/**\n\t * Mark a newly registered provider as configured when it has a stored credential or a configured\n\t * API key. Availability checks run asynchronously, and callers such as initial model selection\n\t * read the snapshot before they finish. The next availability pass replaces this entry.\n\t */\n\tprivate markProvisionallyConfigured(\n\t\tproviderId: string,\n\t\tconfiguredStatus: AuthStatus | undefined,\n\t\ttype: AuthType,\n\t): void {\n\t\tif (!this.snapshot.storedProviders.has(providerId) && !configuredStatus?.configured) return;\n\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders).add(providerId);\n\t\tconst auth = new Map(this.snapshot.auth);\n\t\t// Never clobber a real check result.\n\t\tif (!auth.get(providerId)) auth.set(providerId, { type, source: \"configured provider\" });\n\t\tthis.snapshot = {\n\t\t\t...this.snapshot,\n\t\t\tauth,\n\t\t\tconfiguredProviders,\n\t\t\tavailable: this.snapshot.all.filter((model) => configuredProviders.has(model.provider)),\n\t\t};\n\t}\n\n\tregisterProvider(providerId: string, config: ProviderConfigInput): void {\n\t\t// Validate the incoming registration on its own, like the legacy registry:\n\t\t// a broken re-registration must throw without touching the stored config.\n\t\tvalidateExtensionProvider(providerId, this.builtins.get(providerId), this.config.getProvider(providerId), config);\n\t\tthis.nativeExtensionProviders.delete(providerId);\n\t\t// Re-registration merges defined values over the previous registration and\n\t\t// preserves undefined ones, matching the legacy ModelRegistry contract.\n\t\tconst previous = this.extensionProviders.get(providerId);\n\t\tconst effective: ProviderConfigInput = { ...previous };\n\t\tfor (const [key, value] of Object.entries(config)) {\n\t\t\tif (value !== undefined) (effective as Record<string, unknown>)[key] = value;\n\t\t}\n\t\tthis.extensionProviders.set(providerId, effective);\n\t\tthis.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tthis.markProvisionallyConfigured(\n\t\t\tproviderId,\n\t\t\tconfiguredRequestAuthStatus(this.config.getProvider(providerId), effective),\n\t\t\teffective.oauth && !effective.apiKey ? \"oauth\" : \"api_key\",\n\t\t);\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\tunregisterProvider(providerId: string): void {\n\t\tthis.extensionProviders.delete(providerId);\n\t\tthis.nativeExtensionProviders.delete(providerId);\n\t\tthis.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\t/**\n\t * Register a virtual model under `definition.provider`, which may also list physical models or\n\t * several virtual models. Re-registering the same provider and id replaces the virtual model.\n\t * Throws when the id belongs to a physical model of that provider.\n\t */\n\tregisterVirtualModel(definition: VirtualModelDefinition): void {\n\t\tconst { provider: providerId, id } = definition;\n\t\tif (!providerId.trim() || !id.trim()) throw new Error(\"Virtual model provider and id must not be empty.\");\n\t\tconst existing = this.models.getModel(providerId, id);\n\t\tif (existing && !isVirtualModel(existing)) {\n\t\t\tthrow new Error(`Virtual model ${providerId}/${id} conflicts with a physical model.`);\n\t\t}\n\t\tconst models = this.virtualModels.get(providerId) ?? new Map<string, RegisteredVirtualModel>();\n\t\tmodels.set(id, { model: createVirtualModel(definition), route: (request) => definition.route(request) });\n\t\tthis.virtualModels.set(providerId, models);\n\t\tif (!this.recomposeProvider(providerId) && !this.snapshot.configuredProviders.has(providerId)) {\n\t\t\t// A provider of only virtual models needs no credentials. Mark it configured now: session\n\t\t\t// restore checks auth before the refresh below lands.\n\t\t\tconst auth = new Map(this.snapshot.auth).set(providerId, { type: \"api_key\", source: \"virtual\" });\n\t\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders).add(providerId);\n\t\t\tthis.snapshot = { ...this.snapshot, auth, configuredProviders };\n\t\t}\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\tunregisterVirtualModel(providerId: string, id: string): void {\n\t\tconst models = this.virtualModels.get(providerId);\n\t\tif (!models?.delete(id)) return;\n\t\tif (models.size === 0) this.virtualModels.delete(providerId);\n\t\tthis.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\t/**\n\t * Ask a virtual model's router for the model and thinking level of one request. The router must\n\t * return a physical catalog model whose provider has credentials; the thinking level is clamped\n\t * to that model. Throws when routing fails.\n\t *\n\t * `previous` reports the latest successful response in `messages`. A retry passes the failed\n\t * response as `options.failed`; `messages` no longer contains it. `options.state` is the router\n\t * state stored by the caller, which also stores the returned state.\n\t */\n\tasync resolveModel(\n\t\tmodel: Model<Api>,\n\t\tmessages: readonly Message[],\n\t\toptions: {\n\t\t\treason: ModelRouteReason;\n\t\t\tthinkingLevel: ModelThinkingLevel;\n\t\t\tsignal?: AbortSignal;\n\t\t\tfailed?: AssistantMessage;\n\t\t\tstate?: unknown;\n\t\t},\n\t): Promise<ModelRoute> {\n\t\tconst name = `Virtual model ${model.provider}/${model.id}`;\n\t\tconst virtual = this.virtualModels.get(model.provider)?.get(model.id);\n\t\tif (!virtual) throw new Error(`${name} is not registered.`);\n\t\tconst { failed, ...request } = options;\n\t\tconst latest = findLatestResponse(messages);\n\t\tconst previousModel = latest && this.getPhysicalModel(latest.provider, latest.model);\n\t\t// A failed routing attempt names the virtual model; there is no physical request to report.\n\t\tconst failedModel = failed && this.getPhysicalModel(failed.provider, failed.model);\n\t\tconst route = await virtual.route({\n\t\t\t...request,\n\t\t\tmodel,\n\t\t\tprevious: previousModel && { model: previousModel, thinkingLevel: latest?.thinkingLevel },\n\t\t\tfailed: failedModel && failed && { model: failedModel, thinkingLevel: failed.thinkingLevel, message: failed },\n\t\t\tmessages,\n\t\t});\n\t\tconst target = this.getPhysicalModel(route.model.provider, route.model.id);\n\t\tconst routed = `${name} routed to ${route.model.provider}/${route.model.id}`;\n\t\tif (!target) throw new Error(`${routed}, which is not a physical model.`);\n\t\tif (!this.hasConfiguredAuth(target.provider)) throw new Error(`${routed}, which has no credentials.`);\n\t\treturn { model: target, thinkingLevel: clampThinkingLevel(target, route.thinkingLevel), state: route.state };\n\t}\n\n\t/** A catalog chat model that is not virtual. */\n\tgetPhysicalModel(providerId: string, modelId: string): Model<Api> | undefined {\n\t\tconst model = this.models.getModel(providerId, modelId);\n\t\treturn model && !isVirtualModel(model) ? model : undefined;\n\t}\n}\n"]}
@@ -72,6 +72,7 @@ export type NestedToolExecutionEvent = {
72
72
  toolName: string;
73
73
  result: AgentToolResult<unknown>;
74
74
  isError: boolean;
75
+ durationMs?: number;
75
76
  parentToolCallId: string;
76
77
  };
77
78
  export interface NestedToolCallHost {
@@ -1 +1 @@
1
- {"version":3,"file":"nested-tool-calls.d.ts","sourceRoot":"","sources":["../../src/core/nested-tool-calls.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EACX,SAAS,EACT,aAAa,EACb,oBAAoB,EACpB,eAAe,EACf,uBAAuB,EACvB,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAc,oBAAoB,EAAE,eAAe,EAAe,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAGnH;;;;GAIG;AACH,eAAO,MAAM,kBAAkB;aAC9B,QAAQ,EAAE,GAAG;aACb,uBAAuB;aACvB,qBAAqB;aACrB,aAAa,EAAE,GAAG;CACT,CAAC;AAIX,4FAA4F;AAC5F,MAAM,WAAW,iBAAiB;IACjC,qEAAqE;IACrE,KAAK,EAAE,eAAe,GAAG,SAAS,CAAC;IACnC,4EAA4E;IAC5E,KAAK,EAAE,KAAK,GAAG,SAAS,CAAC;CACzB;AAED;;;GAGG;AACH,qBAAa,kBAAkB;IAC9B,OAAO,CAAC,QAAQ,CAAC,KAAK,CAA8B;IACpD,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA2C;IACrE,OAAO,CAAC,QAAQ,CAAQ;IACxB,OAAO,CAAC,aAAa,CAAK;IAC1B,oFAAoF;IACpF,OAAO,CAAC,KAAK,CAAoB;IAEjC,8EAA8E;IAC9E,KAAK,CAAC,QAAQ,EAAE,aAAa,GAAG,oBAAoB,GAAG,SAAS,CAqB/D;IAED,MAAM,CAAC,MAAM,EAAE,oBAAoB,GAAG,SAAS,EAAE,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,GAAG,IAAI,CAM1F;IAED,QAAQ,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAE3B;IAED,IAAI,UAAU,IAAI,KAAK,GAAG,SAAS,CAElC;IAED,4EAA4E;IAC5E,QAAQ,IAAI,eAAe,GAAG,SAA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,EAAE,MAAM,CAAC;IACpB,gBAAgB,EAAE,MAAM,CAAC;CACxB,CAAC;AAEL,MAAM,WAAW,kBAAkB;IAClC,0CAA0C;IAC1C,QAAQ,IAAI,SAAS,SAAS,EAAE,CAAC;IACjC,sGAAsG;IACtG,YAAY,IAAI,OAAO,CAAC;IACxB,yFAAyF;IACzF,WAAW,CACV,QAAQ,EAAE,aAAa,EACvB,gBAAgB,EAAE,MAAM,EACxB,MAAM,EAAE,WAAW,GAAG,SAAS,EAC/B,QAAQ,EAAE,CAAC,aAAa,EAAE,eAAe,CAAC,OAAO,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,GAClE,OAAO,CAAC,oBAAoB,CAAC,CAAC;IACjC,IAAI,CAAC,KAAK,EAAE,wBAAwB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACrD;AAiBD,qBAAa,oBAAoB;IAChC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAqB;IAC1C,iDAAiD;IACjD,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAgC;IACvD,8DAA8D;IAC9D,OAAO,CAAC,SAAS,CAAoC;IAErD,YAAY,IAAI,EAAE,kBAAkB,EAEnC;IAED;;;OAGG;IACG,OAAO,CACZ,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,OAAO,EACb,OAAO,GAAE,qBAA0B,GACjC,OAAO,CAAC,oBAAoB,CAAC,CAqE/B;IAED,iFAAiF;IACjF,UAAU,CAAC,UAAU,EAAE,MAAM,GAAG,iBAAiB,GAAG,SAAS,CAK5D;IAED,KAAK,IAAI,IAAI,CAEZ;CACD"}
@@ -159,6 +159,7 @@ export class NestedToolCallRunner {
159
159
  toolName: name,
160
160
  result: outcome.result,
161
161
  isError: outcome.isError,
162
+ ...(outcome.durationMs === undefined ? {} : { durationMs: outcome.durationMs }),
162
163
  parentToolCallId: callerId,
163
164
  });
164
165
  return outcome;
@@ -1 +1 @@
1
- {"version":3,"file":"nested-tool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YACtB,OAAO,EAAE,OAAO,CAAC,OAAO;YACxB,gBAAgB,EAAE,QAAQ;SAC1B,CAAC,CAAC;QACH,OAAO,OAAO,CAAC;IAChB,CAAC;IAED,iFAAiF;IACjF,UAAU,CAAC,UAAkB;QAC5B,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QAC1C,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAC/B,IAAI,CAAC,KAAK;YAAE,OAAO,SAAS,CAAC;QAC7B,OAAO,EAAE,KAAK,EAAE,KAAK,CAAC,QAAQ,CAAC,QAAQ,EAAE,EAAE,KAAK,EAAE,KAAK,CAAC,QAAQ,CAAC,UAAU,EAAE,CAAC;IAC/E,CAAC;IAED,KAAK;QACJ,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;IACrB,CAAC;CACD","sourcesContent":["/**\n * Tool calls that a tool makes while it runs (`ctx.executeTool()`), for example from codemode\n * scripts. The agent loop does not know about them: the session runs each one through the agent's\n * tool pipeline (`runToolCall`) with its own hooks, emits `tool_execution_*` events with\n * `parentToolCallId`, and records the calls and their usage on the model-issued call's tool result\n * message.\n *\n * Nothing here runs until a tool calls `ctx.executeTool()`.\n */\n\nimport type {\n\tAgentTool,\n\tAgentToolCall,\n\tAgentToolCallOutcome,\n\tAgentToolResult,\n\tAgentToolUpdateCallback,\n} from \"@earendil-works/pi-agent-core\";\nimport type { JsonObject, NestedToolCallRecord, NestedToolCalls, TextContent, Usage } from \"@earendil-works/pi-ai\";\nimport { combineUsage } from \"./usage-totals.ts\";\n\n/**\n * Limits of the nested-call record on a tool result: arguments\n * over the per-call or total size are omitted, calls beyond the count are dropped, and the record\n * is marked incomplete when any of that happens.\n */\nexport const NESTED_CALL_LIMITS = {\n\tmaxCalls: 256,\n\tmaxArgumentBytesPerCall: 8 * 1024,\n\tmaxArgumentBytesTotal: 32 * 1024,\n\tmaxErrorChars: 500,\n} as const;\n\nconst encoder = new TextEncoder();\n\n/** What the nested calls of one model-issued tool call leave on its tool result message. */\nexport interface NestedCallSummary {\n\t/** Becomes `nestedCalls`. Undefined when no nested call was made. */\n\tcalls: NestedToolCalls | undefined;\n\t/** Summed `usage` of the nested results, added to the message's `usage`. */\n\tusage: Usage | undefined;\n}\n\n/**\n * Collects the nested calls of one model-issued tool call, including calls made by nested tools.\n * The snapshot becomes `nestedCalls` on the tool result message.\n */\nexport class NestedCallRecorder {\n\tprivate readonly calls: NestedToolCallRecord[] = [];\n\tprivate readonly startedAt = new Map<NestedToolCallRecord, number>();\n\tprivate complete = true;\n\tprivate argumentBytes = 0;\n\t/** Summed usage of every nested result, including calls dropped from the record. */\n\tprivate usage: Usage | undefined;\n\n\t/** Record a call as it starts. Returns undefined when the call is dropped. */\n\tstart(toolCall: AgentToolCall): NestedToolCallRecord | undefined {\n\t\tif (this.calls.length >= NESTED_CALL_LIMITS.maxCalls) {\n\t\t\tthis.complete = false;\n\t\t\treturn undefined;\n\t\t}\n\t\tconst record: NestedToolCallRecord = { id: toolCall.id, name: toolCall.name, status: \"unfinished\" };\n\t\tconst json = JSON.stringify(toolCall.arguments ?? {});\n\t\tconst bytes = encoder.encode(json).length;\n\t\tif (\n\t\t\tbytes > NESTED_CALL_LIMITS.maxArgumentBytesPerCall ||\n\t\t\tthis.argumentBytes + bytes > NESTED_CALL_LIMITS.maxArgumentBytesTotal\n\t\t) {\n\t\t\trecord.argumentsBytes = bytes;\n\t\t\tthis.complete = false;\n\t\t} else {\n\t\t\trecord.arguments = JSON.parse(json) as JsonObject;\n\t\t\tthis.argumentBytes += bytes;\n\t\t}\n\t\tthis.calls.push(record);\n\t\tthis.startedAt.set(record, performance.now());\n\t\treturn record;\n\t}\n\n\tfinish(record: NestedToolCallRecord | undefined, isError: boolean, errorText: string): void {\n\t\tif (!record) return;\n\t\trecord.status = isError ? \"error\" : \"ok\";\n\t\trecord.durationMs = Math.round(performance.now() - (this.startedAt.get(record) ?? performance.now()));\n\t\tthis.startedAt.delete(record);\n\t\tif (isError && errorText) record.error = errorText.slice(0, NESTED_CALL_LIMITS.maxErrorChars);\n\t}\n\n\taddUsage(usage: Usage): void {\n\t\tthis.usage = this.usage ? combineUsage(this.usage, usage) : usage;\n\t}\n\n\tget totalUsage(): Usage | undefined {\n\t\treturn this.usage;\n\t}\n\n\t/** Copy of the record so far, or undefined when no nested call was made. */\n\tsnapshot(): NestedToolCalls | undefined {\n\t\tif (this.calls.length === 0 && this.complete) return undefined;\n\t\tconst calls = this.calls.map((call) => ({ ...call }));\n\t\treturn { calls, complete: this.complete && calls.every((call) => call.status !== \"unfinished\") };\n\t}\n}\n\nexport interface NestedToolCallOptions {\n\t/** Defaults to the calling tool's signal. */\n\tsignal?: AbortSignal;\n\t/** Receives partial results of the nested tool, in addition to `tool_execution_update` events. */\n\tonUpdate?: AgentToolUpdateCallback;\n}\n\n/** `tool_execution_*` events of nested calls. */\nexport type NestedToolExecutionEvent =\n\t| { type: \"tool_execution_start\"; toolCallId: string; toolName: string; args: unknown; parentToolCallId: string }\n\t| {\n\t\t\ttype: \"tool_execution_update\";\n\t\t\ttoolCallId: string;\n\t\t\ttoolName: string;\n\t\t\targs: unknown;\n\t\t\tpartialResult: AgentToolResult<unknown>;\n\t\t\tparentToolCallId: string;\n\t }\n\t| {\n\t\t\ttype: \"tool_execution_end\";\n\t\t\ttoolCallId: string;\n\t\t\ttoolName: string;\n\t\t\tresult: AgentToolResult<unknown>;\n\t\t\tisError: boolean;\n\t\t\tparentToolCallId: string;\n\t };\n\nexport interface NestedToolCallHost {\n\t/** Tools nested calls resolve against. */\n\tgetTools(): readonly AgentTool[];\n\t/** Whether every nested call runs exclusively, as when the agent executes tool calls sequentially. */\n\tisSequential(): boolean;\n\t/** Run the call through the tool pipeline, with hooks that report `parentToolCallId`. */\n\trunToolCall(\n\t\ttoolCall: AgentToolCall,\n\t\tparentToolCallId: string,\n\t\tsignal: AbortSignal | undefined,\n\t\tonUpdate: (partialResult: AgentToolResult<unknown>) => Promise<void>,\n\t): Promise<AgentToolCallOutcome>;\n\temit(event: NestedToolExecutionEvent): Promise<void>;\n}\n\n/** Calls below one model-issued call share its recorder. */\ninterface CallScope {\n\trecorder: NestedCallRecorder;\n\tnextId: number;\n\t/** Set inside a call that holds the exclusive queue, so its own nested calls do not wait on it. */\n\tholdsQueue: boolean;\n}\n\nfunction textOf(result: AgentToolResult<unknown>): string {\n\treturn (result.content ?? [])\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n}\n\nexport class NestedToolCallRunner {\n\tprivate readonly host: NestedToolCallHost;\n\t/** Scopes by the id of the calling tool call. */\n\tprivate readonly scopes = new Map<string, CallScope>();\n\t/** Serializes nested calls that must not run concurrently. */\n\tprivate queueTail: Promise<void> = Promise.resolve();\n\n\tconstructor(host: NestedToolCallHost) {\n\t\tthis.host = host;\n\t}\n\n\t/**\n\t * Run `name` on behalf of the call `callerId`. The nested call gets the id `<callerId>/<n>`.\n\t * Never rejects for tool failures: they come back as `isError: true`.\n\t */\n\tasync execute(\n\t\tcallerId: string,\n\t\tname: string,\n\t\targs: unknown,\n\t\toptions: NestedToolCallOptions = {},\n\t): Promise<AgentToolCallOutcome> {\n\t\tlet scope = this.scopes.get(callerId);\n\t\tif (!scope) {\n\t\t\tscope = { recorder: new NestedCallRecorder(), nextId: 1, holdsQueue: false };\n\t\t\tthis.scopes.set(callerId, scope);\n\t\t}\n\t\tconst toolCall: AgentToolCall = {\n\t\t\ttype: \"toolCall\",\n\t\t\tid: `${callerId}/${scope.nextId++}`,\n\t\t\tname,\n\t\t\targuments: (args ?? {}) as AgentToolCall[\"arguments\"],\n\t\t};\n\t\tconst record = scope.recorder.start(toolCall);\n\t\tawait this.host.emit({\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: name,\n\t\t\targs: toolCall.arguments,\n\t\t\tparentToolCallId: callerId,\n\t\t});\n\n\t\tconst exclusive =\n\t\t\t!scope.holdsQueue &&\n\t\t\t(this.host.isSequential() ||\n\t\t\t\tthis.host.getTools().find((tool) => tool.name === name)?.executionMode === \"sequential\");\n\t\tlet release: (() => void) | undefined;\n\t\tif (exclusive) {\n\t\t\tconst previous = this.queueTail;\n\t\t\tthis.queueTail = new Promise((resolve) => {\n\t\t\t\trelease = resolve;\n\t\t\t});\n\t\t\tawait previous;\n\t\t}\n\t\tthis.scopes.set(toolCall.id, {\n\t\t\trecorder: scope.recorder,\n\t\t\tnextId: 1,\n\t\t\tholdsQueue: scope.holdsQueue || exclusive,\n\t\t});\n\t\tlet outcome: AgentToolCallOutcome;\n\t\ttry {\n\t\t\toutcome = await this.host.runToolCall(toolCall, callerId, options.signal, async (partialResult) => {\n\t\t\t\toptions.onUpdate?.(partialResult);\n\t\t\t\tawait this.host.emit({\n\t\t\t\t\ttype: \"tool_execution_update\",\n\t\t\t\t\ttoolCallId: toolCall.id,\n\t\t\t\t\ttoolName: name,\n\t\t\t\t\targs: toolCall.arguments,\n\t\t\t\t\tpartialResult,\n\t\t\t\t\tparentToolCallId: callerId,\n\t\t\t\t});\n\t\t\t});\n\t\t} finally {\n\t\t\tthis.scopes.delete(toolCall.id);\n\t\t\trelease?.();\n\t\t}\n\n\t\tscope.recorder.finish(record, outcome.isError, textOf(outcome.result));\n\t\t// Nested results are not persisted, so their usage is only counted through the recorder.\n\t\tif (outcome.result.usage) scope.recorder.addUsage(outcome.result.usage);\n\t\tawait this.host.emit({\n\t\t\ttype: \"tool_execution_end\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: name,\n\t\t\tresult: outcome.result,\n\t\t\tisError: outcome.isError,\n\t\t\tparentToolCallId: callerId,\n\t\t});\n\t\treturn outcome;\n\t}\n\n\t/** Remove and return the record of the nested calls a model-issued call made. */\n\ttakeRecord(toolCallId: string): NestedCallSummary | undefined {\n\t\tconst scope = this.scopes.get(toolCallId);\n\t\tthis.scopes.delete(toolCallId);\n\t\tif (!scope) return undefined;\n\t\treturn { calls: scope.recorder.snapshot(), usage: scope.recorder.totalUsage };\n\t}\n\n\tclear(): void {\n\t\tthis.scopes.clear();\n\t}\n}\n"]}
1
+ {"version":3,"file":"nested-tool-calls.js","sourceRoot":"","sources":["../../src/core/nested-tool-calls.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAUH,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD;;;;GAIG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG;IACjC,QAAQ,EAAE,GAAG;IACb,uBAAuB,EAAE,CAAC,GAAG,IAAI;IACjC,qBAAqB,EAAE,EAAE,GAAG,IAAI;IAChC,aAAa,EAAE,GAAG;CACT,CAAC;AAEX,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAUlC;;;GAGG;AACH,MAAM,OAAO,kBAAkB;IACb,KAAK,GAA2B,EAAE,CAAC;IACnC,SAAS,GAAG,IAAI,GAAG,EAAgC,CAAC;IAC7D,QAAQ,GAAG,IAAI,CAAC;IAChB,aAAa,GAAG,CAAC,CAAC;IAC1B,oFAAoF;IAC5E,KAAK,CAAoB;IAEjC,8EAA8E;IAC9E,KAAK,CAAC,QAAuB;QAC5B,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,IAAI,kBAAkB,CAAC,QAAQ,EAAE,CAAC;YACtD,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAC;YACtB,OAAO,SAAS,CAAC;QAClB,CAAC;QACD,MAAM,MAAM,GAAyB,EAAE,EAAE,EAAE,QAAQ,CAAC,EAAE,EAAE,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,YAAY,EAAE,CAAC;QACpG,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,SAAS,IAAI,EAAE,CAAC,CAAC;QACtD,MAAM,KAAK,GAAG,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC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CAAC,IAAI,CAAC,IAAI,CAAC;YACpB,IAAI,EAAE,oBAAoB;YAC1B,UAAU,EAAE,QAAQ,CAAC,EAAE;YACvB,QAAQ,EAAE,IAAI;YACd,MAAM,EAAE,OAAO,CAAC,MAAM;YACtB,OAAO,EAAE,OAAO,CAAC,OAAO;YACxB,GAAG,CAAC,OAAO,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,OAAO,CAAC,UAAU,EAAE,CAAC;YAC/E,gBAAgB,EAAE,QAAQ;SAC1B,CAAC,CAAC;QACH,OAAO,OAAO,CAAC;IAChB,CAAC;IAED,iFAAiF;IACjF,UAAU,CAAC,UAAkB;QAC5B,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QAC1C,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAC/B,IAAI,CAAC,KAAK;YAAE,OAAO,SAAS,CAAC;QAC7B,OAAO,EAAE,KAAK,EAAE,KAAK,CAAC,QAAQ,CAAC,QAAQ,EAAE,EAAE,KAAK,EAAE,KAAK,CAAC,QAAQ,CAAC,UAAU,EAAE,CAAC;IAC/E,CAAC;IAED,KAAK;QACJ,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;IACrB,CAAC;CACD","sourcesContent":["/**\n * Tool calls that a tool makes while it runs (`ctx.executeTool()`), for example from codemode\n * scripts. The agent loop does not know about them: the session runs each one through the agent's\n * tool pipeline (`runToolCall`) with its own hooks, emits `tool_execution_*` events with\n * `parentToolCallId`, and records the calls and their usage on the model-issued call's tool result\n * message.\n *\n * Nothing here runs until a tool calls `ctx.executeTool()`.\n */\n\nimport type {\n\tAgentTool,\n\tAgentToolCall,\n\tAgentToolCallOutcome,\n\tAgentToolResult,\n\tAgentToolUpdateCallback,\n} from \"@earendil-works/pi-agent-core\";\nimport type { JsonObject, NestedToolCallRecord, NestedToolCalls, TextContent, Usage } from \"@earendil-works/pi-ai\";\nimport { combineUsage } from \"./usage-totals.ts\";\n\n/**\n * Limits of the nested-call record on a tool result: arguments\n * over the per-call or total size are omitted, calls beyond the count are dropped, and the record\n * is marked incomplete when any of that happens.\n */\nexport const NESTED_CALL_LIMITS = {\n\tmaxCalls: 256,\n\tmaxArgumentBytesPerCall: 8 * 1024,\n\tmaxArgumentBytesTotal: 32 * 1024,\n\tmaxErrorChars: 500,\n} as const;\n\nconst encoder = new TextEncoder();\n\n/** What the nested calls of one model-issued tool call leave on its tool result message. */\nexport interface NestedCallSummary {\n\t/** Becomes `nestedCalls`. Undefined when no nested call was made. */\n\tcalls: NestedToolCalls | undefined;\n\t/** Summed `usage` of the nested results, added to the message's `usage`. */\n\tusage: Usage | undefined;\n}\n\n/**\n * Collects the nested calls of one model-issued tool call, including calls made by nested tools.\n * The snapshot becomes `nestedCalls` on the tool result message.\n */\nexport class NestedCallRecorder {\n\tprivate readonly calls: NestedToolCallRecord[] = [];\n\tprivate readonly startedAt = new Map<NestedToolCallRecord, number>();\n\tprivate complete = true;\n\tprivate argumentBytes = 0;\n\t/** Summed usage of every nested result, including calls dropped from the record. */\n\tprivate usage: Usage | undefined;\n\n\t/** Record a call as it starts. Returns undefined when the call is dropped. */\n\tstart(toolCall: AgentToolCall): NestedToolCallRecord | undefined {\n\t\tif (this.calls.length >= NESTED_CALL_LIMITS.maxCalls) {\n\t\t\tthis.complete = false;\n\t\t\treturn undefined;\n\t\t}\n\t\tconst record: NestedToolCallRecord = { id: toolCall.id, name: toolCall.name, status: \"unfinished\" };\n\t\tconst json = JSON.stringify(toolCall.arguments ?? {});\n\t\tconst bytes = encoder.encode(json).length;\n\t\tif (\n\t\t\tbytes > NESTED_CALL_LIMITS.maxArgumentBytesPerCall ||\n\t\t\tthis.argumentBytes + bytes > NESTED_CALL_LIMITS.maxArgumentBytesTotal\n\t\t) {\n\t\t\trecord.argumentsBytes = bytes;\n\t\t\tthis.complete = false;\n\t\t} else {\n\t\t\trecord.arguments = JSON.parse(json) as JsonObject;\n\t\t\tthis.argumentBytes += bytes;\n\t\t}\n\t\tthis.calls.push(record);\n\t\tthis.startedAt.set(record, performance.now());\n\t\treturn record;\n\t}\n\n\tfinish(record: NestedToolCallRecord | undefined, isError: boolean, errorText: string): void {\n\t\tif (!record) return;\n\t\trecord.status = isError ? \"error\" : \"ok\";\n\t\trecord.durationMs = Math.round(performance.now() - (this.startedAt.get(record) ?? performance.now()));\n\t\tthis.startedAt.delete(record);\n\t\tif (isError && errorText) record.error = errorText.slice(0, NESTED_CALL_LIMITS.maxErrorChars);\n\t}\n\n\taddUsage(usage: Usage): void {\n\t\tthis.usage = this.usage ? combineUsage(this.usage, usage) : usage;\n\t}\n\n\tget totalUsage(): Usage | undefined {\n\t\treturn this.usage;\n\t}\n\n\t/** Copy of the record so far, or undefined when no nested call was made. */\n\tsnapshot(): NestedToolCalls | undefined {\n\t\tif (this.calls.length === 0 && this.complete) return undefined;\n\t\tconst calls = this.calls.map((call) => ({ ...call }));\n\t\treturn { calls, complete: this.complete && calls.every((call) => call.status !== \"unfinished\") };\n\t}\n}\n\nexport interface NestedToolCallOptions {\n\t/** Defaults to the calling tool's signal. */\n\tsignal?: AbortSignal;\n\t/** Receives partial results of the nested tool, in addition to `tool_execution_update` events. */\n\tonUpdate?: AgentToolUpdateCallback;\n}\n\n/** `tool_execution_*` events of nested calls. */\nexport type NestedToolExecutionEvent =\n\t| { type: \"tool_execution_start\"; toolCallId: string; toolName: string; args: unknown; parentToolCallId: string }\n\t| {\n\t\t\ttype: \"tool_execution_update\";\n\t\t\ttoolCallId: string;\n\t\t\ttoolName: string;\n\t\t\targs: unknown;\n\t\t\tpartialResult: AgentToolResult<unknown>;\n\t\t\tparentToolCallId: string;\n\t }\n\t| {\n\t\t\ttype: \"tool_execution_end\";\n\t\t\ttoolCallId: string;\n\t\t\ttoolName: string;\n\t\t\tresult: AgentToolResult<unknown>;\n\t\t\tisError: boolean;\n\t\t\tdurationMs?: number;\n\t\t\tparentToolCallId: string;\n\t };\n\nexport interface NestedToolCallHost {\n\t/** Tools nested calls resolve against. */\n\tgetTools(): readonly AgentTool[];\n\t/** Whether every nested call runs exclusively, as when the agent executes tool calls sequentially. */\n\tisSequential(): boolean;\n\t/** Run the call through the tool pipeline, with hooks that report `parentToolCallId`. */\n\trunToolCall(\n\t\ttoolCall: AgentToolCall,\n\t\tparentToolCallId: string,\n\t\tsignal: AbortSignal | undefined,\n\t\tonUpdate: (partialResult: AgentToolResult<unknown>) => Promise<void>,\n\t): Promise<AgentToolCallOutcome>;\n\temit(event: NestedToolExecutionEvent): Promise<void>;\n}\n\n/** Calls below one model-issued call share its recorder. */\ninterface CallScope {\n\trecorder: NestedCallRecorder;\n\tnextId: number;\n\t/** Set inside a call that holds the exclusive queue, so its own nested calls do not wait on it. */\n\tholdsQueue: boolean;\n}\n\nfunction textOf(result: AgentToolResult<unknown>): string {\n\treturn (result.content ?? [])\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n}\n\nexport class NestedToolCallRunner {\n\tprivate readonly host: NestedToolCallHost;\n\t/** Scopes by the id of the calling tool call. */\n\tprivate readonly scopes = new Map<string, CallScope>();\n\t/** Serializes nested calls that must not run concurrently. */\n\tprivate queueTail: Promise<void> = Promise.resolve();\n\n\tconstructor(host: NestedToolCallHost) {\n\t\tthis.host = host;\n\t}\n\n\t/**\n\t * Run `name` on behalf of the call `callerId`. The nested call gets the id `<callerId>/<n>`.\n\t * Never rejects for tool failures: they come back as `isError: true`.\n\t */\n\tasync execute(\n\t\tcallerId: string,\n\t\tname: string,\n\t\targs: unknown,\n\t\toptions: NestedToolCallOptions = {},\n\t): Promise<AgentToolCallOutcome> {\n\t\tlet scope = this.scopes.get(callerId);\n\t\tif (!scope) {\n\t\t\tscope = { recorder: new NestedCallRecorder(), nextId: 1, holdsQueue: false };\n\t\t\tthis.scopes.set(callerId, scope);\n\t\t}\n\t\tconst toolCall: AgentToolCall = {\n\t\t\ttype: \"toolCall\",\n\t\t\tid: `${callerId}/${scope.nextId++}`,\n\t\t\tname,\n\t\t\targuments: (args ?? {}) as AgentToolCall[\"arguments\"],\n\t\t};\n\t\tconst record = scope.recorder.start(toolCall);\n\t\tawait this.host.emit({\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: name,\n\t\t\targs: toolCall.arguments,\n\t\t\tparentToolCallId: callerId,\n\t\t});\n\n\t\tconst exclusive =\n\t\t\t!scope.holdsQueue &&\n\t\t\t(this.host.isSequential() ||\n\t\t\t\tthis.host.getTools().find((tool) => tool.name === name)?.executionMode === \"sequential\");\n\t\tlet release: (() => void) | undefined;\n\t\tif (exclusive) {\n\t\t\tconst previous = this.queueTail;\n\t\t\tthis.queueTail = new Promise((resolve) => {\n\t\t\t\trelease = resolve;\n\t\t\t});\n\t\t\tawait previous;\n\t\t}\n\t\tthis.scopes.set(toolCall.id, {\n\t\t\trecorder: scope.recorder,\n\t\t\tnextId: 1,\n\t\t\tholdsQueue: scope.holdsQueue || exclusive,\n\t\t});\n\t\tlet outcome: AgentToolCallOutcome;\n\t\ttry {\n\t\t\toutcome = await this.host.runToolCall(toolCall, callerId, options.signal, async (partialResult) => {\n\t\t\t\toptions.onUpdate?.(partialResult);\n\t\t\t\tawait this.host.emit({\n\t\t\t\t\ttype: \"tool_execution_update\",\n\t\t\t\t\ttoolCallId: toolCall.id,\n\t\t\t\t\ttoolName: name,\n\t\t\t\t\targs: toolCall.arguments,\n\t\t\t\t\tpartialResult,\n\t\t\t\t\tparentToolCallId: callerId,\n\t\t\t\t});\n\t\t\t});\n\t\t} finally {\n\t\t\tthis.scopes.delete(toolCall.id);\n\t\t\trelease?.();\n\t\t}\n\n\t\tscope.recorder.finish(record, outcome.isError, textOf(outcome.result));\n\t\t// Nested results are not persisted, so their usage is only counted through the recorder.\n\t\tif (outcome.result.usage) scope.recorder.addUsage(outcome.result.usage);\n\t\tawait this.host.emit({\n\t\t\ttype: \"tool_execution_end\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: name,\n\t\t\tresult: outcome.result,\n\t\t\tisError: outcome.isError,\n\t\t\t...(outcome.durationMs === undefined ? {} : { durationMs: outcome.durationMs }),\n\t\t\tparentToolCallId: callerId,\n\t\t});\n\t\treturn outcome;\n\t}\n\n\t/** Remove and return the record of the nested calls a model-issued call made. */\n\ttakeRecord(toolCallId: string): NestedCallSummary | undefined {\n\t\tconst scope = this.scopes.get(toolCallId);\n\t\tthis.scopes.delete(toolCallId);\n\t\tif (!scope) return undefined;\n\t\treturn { calls: scope.recorder.snapshot(), usage: scope.recorder.totalUsage };\n\t}\n\n\tclear(): void {\n\t\tthis.scopes.clear();\n\t}\n}\n"]}
@@ -41,6 +41,10 @@ export interface CreateAgentSessionOptions {
41
41
  * enabled. MCP tools stay registered for codemode and tool search unless an
42
42
  * entry starts with `mcp__`; then only matching MCP tools are kept. An empty
43
43
  * list, like `noTools: "all"`, disables MCP tools too.
44
+ *
45
+ * A list of only `+name` and `-name` entries is not an allowlist: it adds tools
46
+ * to or removes them from the default selection, like the `defaultTools` setting.
47
+ * These entries take exact names. Mixing them with plain entries throws.
44
48
  */
45
49
  tools?: string[];
46
50
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AACA,OAAO,EAAgD,KAAK,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAEjH,OAAO,EAAoC,KAAK,KAAK,EAAgB,MAAM,8BAA8B,CAAC;AAG1G,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAIlD,OAAO,KAAK,EAAmB,oBAAoB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAItH,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,OAAO,KAAK,EAAE,cAAc,EAAE,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M,WAAW,wBAAwB;IACxC,0BAA0B;IAC1B,OAAO,EAAE,YAAY,CAAC;IACtB,mEAAmE;IACnE,gBAAgB,EAAE,oBAAoB,CAAC;IACvC,wEAAwE;IACxE,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAID,cAAc,4BAA4B,CAAC;AAC3C,YAAY,EACX,YAAY,EACZ,uBAAuB,EACvB,gBAAgB,EAChB,gBAAgB,EAChB,eAAe,EACf,gBAAgB,EAChB,kBAAkB,EAClB,cAAc,GACd,MAAM,uBAAuB,CAAC;AAC/B,YAAY,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC5D,YAAY,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACzC,YAAY,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAE7C,OAAO,EACN,qBAAqB,EAErB,iBAAiB,EACjB,mBAAmB,EACnB,cAAc,EACd,cAAc,EACd,cAAc,EACd,eAAe,EACf,cAAc,EACd,cAAc,EACd,YAAY,EACZ,oBAAoB,GACpB,CAAC;AAQF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,GAAE,yBAA8B,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAwSnH"}
package/dist/core/sdk.js CHANGED
@@ -14,7 +14,7 @@ import { ModelRuntime } from "./model-runtime.js";
14
14
  import { mergeProviderAttributionHeaders } from "./provider-attribution.js";
15
15
  import { DefaultResourceLoader } from "./resource-loader.js";
16
16
  import { getDefaultSessionDir, SessionManager } from "./session-manager.js";
17
- import { DEFAULT_TOOL_NAMES, SettingsManager } from "./settings-manager.js";
17
+ import { applyToolModifiers, DEFAULT_TOOL_NAMES, getToolListError, isToolModifier, SettingsManager, } from "./settings-manager.js";
18
18
  import { time } from "./timings.js";
19
19
  import { createBashTool, createCodingTools, createEditTool, createFindTool, createGrepTool, createLsTool, createPowerShellTool, createReadOnlyTools, createReadTool, createWriteTool, withFileMutationQueue, } from "./tools/index.js";
20
20
  import { getBranchSelection } from "./virtual-models.js";
@@ -142,11 +142,22 @@ export async function createAgentSession(options = {}) {
142
142
  else {
143
143
  thinkingLevel = clampThinkingLevel(model, thinkingLevel);
144
144
  }
145
- const configuredDefaultToolNames = settingsManager.getDefaultTools();
146
- const allowedToolNames = options.tools ?? (options.noTools === "all" ? [] : undefined);
145
+ const toolListError = options.tools ? getToolListError(options.tools) : undefined;
146
+ if (toolListError)
147
+ throw new Error(`Invalid tools option: ${toolListError}`);
148
+ const defaultToolNames = options.noTools ? [] : (settingsManager.getDefaultTools() ?? DEFAULT_TOOL_NAMES);
149
+ // A `tools` list of only `+name`/`-name` entries changes the default selection instead of
150
+ // replacing it, like the `defaultTools` setting.
151
+ const toolModifiers = options.tools?.some(isToolModifier) ? options.tools : undefined;
152
+ const selectedToolNames = toolModifiers ? applyToolModifiers(defaultToolNames, toolModifiers) : options.tools;
153
+ const allowedToolNames = toolModifiers
154
+ ? options.noTools === "all"
155
+ ? selectedToolNames
156
+ : undefined
157
+ : (options.tools ?? (options.noTools === "all" ? [] : undefined));
147
158
  const excludedToolNames = options.excludeTools;
148
159
  const isExcludedTool = excludedToolNames ? createToolNameMatcher(excludedToolNames) : undefined;
149
- const initialActiveToolNames = (options.tools ?? (options.noTools ? [] : (configuredDefaultToolNames ?? DEFAULT_TOOL_NAMES))).filter((name) => !isExcludedTool?.(name));
160
+ const initialActiveToolNames = (selectedToolNames ?? defaultToolNames).filter((name) => !isExcludedTool?.(name));
150
161
  // Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)
151
162
  const convertToLlmWithBlockImages = (messages) => {
152
163
  const converted = convertToLlm(messages);
@@ -300,7 +311,8 @@ export async function createAgentSession(options = {}) {
300
311
  modelRuntime,
301
312
  cacheWarmer,
302
313
  initialActiveToolNames,
303
- usesDefaultTools: options.tools === undefined && !options.noTools,
314
+ usesDefaultTools: (options.tools === undefined || toolModifiers !== undefined) && !options.noTools,
315
+ defaultToolModifiers: toolModifiers,
304
316
  allowedToolNames,
305
317
  excludedToolNames,
306
318
  extensionRunnerRef,