@ponythewhite/base-context 1.0.0 → 1.0.1

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 (285) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/NOTICE +0 -5
  3. package/README.md +44 -27
  4. package/dist/NOTICE +0 -5
  5. package/dist/base-context-runtime/pyproject.toml +1 -1
  6. package/dist/base-context-runtime/src/rlm/__init__.py +7 -5
  7. package/dist/base-context-runtime/test/test_subagent_registry.py +28 -1
  8. package/dist/base-context-runtime/uv.lock +1 -1
  9. package/dist/build-info.json +1 -1
  10. package/dist/bundle/amazon-bedrock.js +21 -0
  11. package/dist/bundle/{anthropic-YY4S534V.js → anthropic-UV5GZDGU.js} +5 -5
  12. package/dist/bundle/{azure-openai-responses-JRP6MIM3.js → azure-openai-responses-WSNPXLYC.js} +6 -6
  13. package/dist/bundle/{bundled-modules-P5HARVZA.js → bundled-modules-TXUMJ2XQ.js} +71 -16
  14. package/dist/bundle/chunk-27QCJ2AZ.js +2578 -0
  15. package/dist/bundle/{chunk-MZHTNNVA.js → chunk-4GXPNXOJ.js} +8 -0
  16. package/dist/bundle/{chunk-SC5KG5R4.js → chunk-DGNX7HQ3.js} +1 -7
  17. package/dist/bundle/{chunk-A53O363M.js → chunk-GRJFXLBM.js} +0 -1
  18. package/dist/bundle/chunk-HKINIBP4.js +29 -0
  19. package/dist/bundle/{chunk-UDSW6FNG.js → chunk-KTNETTHI.js} +1 -1
  20. package/dist/bundle/{chunk-BYVP7LWV.js → chunk-S3INFPZZ.js} +1861 -4662
  21. package/dist/bundle/{chunk-73DCPU3D.js → chunk-V3L54UD6.js} +1019 -3427
  22. package/dist/bundle/{chunk-U7AUVG3B.js → chunk-VSIYFWYI.js} +24 -6
  23. package/dist/bundle/{chunk-IW77OXFS.js → chunk-W46VZFI6.js} +0 -2099
  24. package/dist/bundle/{cli-main-O4X7GFGY.js → cli-main-BYMSRPH6.js} +8 -6
  25. package/dist/bundle/cli.js +2 -2
  26. package/dist/bundle/{google-AUTVGDGZ.js → google-T32FMD4G.js} +6 -6
  27. package/dist/bundle/{google-vertex-Q75D7RKS.js → google-vertex-56KP6I3B.js} +3 -3
  28. package/dist/bundle/{main-XKOW2BV6.js → main-ODOYCEQC.js} +7 -5
  29. package/dist/bundle/{mistral-7ESB7QUD.js → mistral-WGBMYIVU.js} +5 -5
  30. package/dist/bundle/{openai-codex-responses-LV3QRPN4.js → openai-codex-responses-PIV2RQ3G.js} +6 -6
  31. package/dist/bundle/{openai-completions-OJECLPXJ.js → openai-completions-64C3JPR4.js} +11 -22
  32. package/dist/bundle/{openai-responses-FN6HZMBC.js → openai-responses-UI7RSTDV.js} +6 -6
  33. package/dist/cli/args.d.ts.map +1 -1
  34. package/dist/cli/args.js +108 -59
  35. package/dist/cli/args.js.map +1 -1
  36. package/dist/cli/daemon-ps.d.ts +4 -3
  37. package/dist/cli/daemon-ps.d.ts.map +1 -1
  38. package/dist/cli/daemon-ps.js +6 -1
  39. package/dist/cli/daemon-ps.js.map +1 -1
  40. package/dist/cli/product-doctor.d.ts +0 -1
  41. package/dist/cli/product-doctor.d.ts.map +1 -1
  42. package/dist/cli/product-doctor.js +6 -3
  43. package/dist/cli/product-doctor.js.map +1 -1
  44. package/dist/config.d.ts +0 -3
  45. package/dist/config.d.ts.map +1 -1
  46. package/dist/config.js +0 -8
  47. package/dist/config.js.map +1 -1
  48. package/dist/core/agent-session-config.d.ts +1 -2
  49. package/dist/core/agent-session-config.d.ts.map +1 -1
  50. package/dist/core/agent-session-config.js +0 -3
  51. package/dist/core/agent-session-config.js.map +1 -1
  52. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  53. package/dist/core/agent-session-runtime.js +5 -4
  54. package/dist/core/agent-session-runtime.js.map +1 -1
  55. package/dist/core/agent-session-services.d.ts +5 -3
  56. package/dist/core/agent-session-services.d.ts.map +1 -1
  57. package/dist/core/agent-session-services.js +2 -27
  58. package/dist/core/agent-session-services.js.map +1 -1
  59. package/dist/core/agent-session.d.ts +10 -6
  60. package/dist/core/agent-session.d.ts.map +1 -1
  61. package/dist/core/agent-session.js +107 -107
  62. package/dist/core/agent-session.js.map +1 -1
  63. package/dist/core/auth-storage.d.ts +8 -35
  64. package/dist/core/auth-storage.d.ts.map +1 -1
  65. package/dist/core/auth-storage.js +33 -243
  66. package/dist/core/auth-storage.js.map +1 -1
  67. package/dist/core/cron-jobs.d.ts.map +1 -1
  68. package/dist/core/cron-jobs.js +7 -1
  69. package/dist/core/cron-jobs.js.map +1 -1
  70. package/dist/core/inference-coordinator.d.ts +6 -1
  71. package/dist/core/inference-coordinator.d.ts.map +1 -1
  72. package/dist/core/inference-coordinator.js +18 -2
  73. package/dist/core/inference-coordinator.js.map +1 -1
  74. package/dist/core/kernel/bootstrap.d.ts.map +1 -1
  75. package/dist/core/kernel/bootstrap.js +2 -2
  76. package/dist/core/kernel/bootstrap.js.map +1 -1
  77. package/dist/core/kernel/repl-manager.d.ts +2 -0
  78. package/dist/core/kernel/repl-manager.d.ts.map +1 -1
  79. package/dist/core/kernel/repl-manager.js +44 -1
  80. package/dist/core/kernel/repl-manager.js.map +1 -1
  81. package/dist/core/logging.d.ts +4 -3
  82. package/dist/core/logging.d.ts.map +1 -1
  83. package/dist/core/logging.js +6 -6
  84. package/dist/core/logging.js.map +1 -1
  85. package/dist/core/mcp/mcp-manager.d.ts.map +1 -1
  86. package/dist/core/mcp/mcp-manager.js +3 -3
  87. package/dist/core/mcp/mcp-manager.js.map +1 -1
  88. package/dist/core/model-registry.d.ts +1 -16
  89. package/dist/core/model-registry.d.ts.map +1 -1
  90. package/dist/core/model-registry.js +88 -196
  91. package/dist/core/model-registry.js.map +1 -1
  92. package/dist/core/model-resolver.d.ts +2 -19
  93. package/dist/core/model-resolver.d.ts.map +1 -1
  94. package/dist/core/model-resolver.js +36 -266
  95. package/dist/core/model-resolver.js.map +1 -1
  96. package/dist/core/provider-contracts.d.ts +5 -6
  97. package/dist/core/provider-contracts.d.ts.map +1 -1
  98. package/dist/core/provider-contracts.js +25 -36
  99. package/dist/core/provider-contracts.js.map +1 -1
  100. package/dist/core/provider-display-names.d.ts.map +1 -1
  101. package/dist/core/provider-display-names.js +0 -2
  102. package/dist/core/provider-display-names.js.map +1 -1
  103. package/dist/core/rlm-max-subagents.d.ts +32 -0
  104. package/dist/core/rlm-max-subagents.d.ts.map +1 -0
  105. package/dist/core/rlm-max-subagents.js +50 -0
  106. package/dist/core/rlm-max-subagents.js.map +1 -0
  107. package/dist/core/rlm-runtime.d.ts +3 -3
  108. package/dist/core/rlm-runtime.d.ts.map +1 -1
  109. package/dist/core/rlm-runtime.js.map +1 -1
  110. package/dist/core/sdk.d.ts +4 -3
  111. package/dist/core/sdk.d.ts.map +1 -1
  112. package/dist/core/sdk.js +27 -14
  113. package/dist/core/sdk.js.map +1 -1
  114. package/dist/core/settings-manager.d.ts +3 -16
  115. package/dist/core/settings-manager.d.ts.map +1 -1
  116. package/dist/core/settings-manager.js +12 -44
  117. package/dist/core/settings-manager.js.map +1 -1
  118. package/dist/core/slash-commands.d.ts.map +1 -1
  119. package/dist/core/slash-commands.js +6 -6
  120. package/dist/core/slash-commands.js.map +1 -1
  121. package/dist/index.d.ts +1 -1
  122. package/dist/index.d.ts.map +1 -1
  123. package/dist/index.js.map +1 -1
  124. package/dist/installer.mjs +2 -3
  125. package/dist/main.d.ts.map +1 -1
  126. package/dist/main.js +39 -34
  127. package/dist/main.js.map +1 -1
  128. package/dist/modes/acp/acp-mode.d.ts.map +1 -1
  129. package/dist/modes/acp/acp-mode.js +1 -1
  130. package/dist/modes/acp/acp-mode.js.map +1 -1
  131. package/dist/modes/agent-connection/daemon-agent-connection.d.ts +6 -2
  132. package/dist/modes/agent-connection/daemon-agent-connection.d.ts.map +1 -1
  133. package/dist/modes/agent-connection/daemon-agent-connection.js +13 -2
  134. package/dist/modes/agent-connection/daemon-agent-connection.js.map +1 -1
  135. package/dist/modes/agent-connection/in-process-agent-connection.d.ts +2 -0
  136. package/dist/modes/agent-connection/in-process-agent-connection.d.ts.map +1 -1
  137. package/dist/modes/agent-connection/in-process-agent-connection.js +6 -0
  138. package/dist/modes/agent-connection/in-process-agent-connection.js.map +1 -1
  139. package/dist/modes/agent-connection/types.d.ts +3 -0
  140. package/dist/modes/agent-connection/types.d.ts.map +1 -1
  141. package/dist/modes/agent-connection/types.js.map +1 -1
  142. package/dist/modes/agents-view/agents-view-mode.d.ts.map +1 -1
  143. package/dist/modes/agents-view/agents-view-mode.js +2 -19
  144. package/dist/modes/agents-view/agents-view-mode.js.map +1 -1
  145. package/dist/modes/daemon/daemon-mode.d.ts +5 -0
  146. package/dist/modes/daemon/daemon-mode.d.ts.map +1 -1
  147. package/dist/modes/daemon/daemon-mode.js +107 -12
  148. package/dist/modes/daemon/daemon-mode.js.map +1 -1
  149. package/dist/modes/daemon/daemon-protocol.d.ts +194 -165
  150. package/dist/modes/daemon/daemon-protocol.d.ts.map +1 -1
  151. package/dist/modes/daemon/daemon-protocol.js +16 -11
  152. package/dist/modes/daemon/daemon-protocol.js.map +1 -1
  153. package/dist/modes/daemon/daemon-rlm-capacity-coordinator.d.ts +19 -0
  154. package/dist/modes/daemon/daemon-rlm-capacity-coordinator.d.ts.map +1 -0
  155. package/dist/modes/daemon/daemon-rlm-capacity-coordinator.js +74 -0
  156. package/dist/modes/daemon/daemon-rlm-capacity-coordinator.js.map +1 -0
  157. package/dist/modes/daemon/daemon-rlm-capacity.d.ts +19 -0
  158. package/dist/modes/daemon/daemon-rlm-capacity.d.ts.map +1 -0
  159. package/dist/modes/daemon/daemon-rlm-capacity.js +85 -0
  160. package/dist/modes/daemon/daemon-rlm-capacity.js.map +1 -0
  161. package/dist/modes/daemon/daemon-session-summarizer.d.ts +2 -3
  162. package/dist/modes/daemon/daemon-session-summarizer.d.ts.map +1 -1
  163. package/dist/modes/daemon/daemon-session-summarizer.js +32 -23
  164. package/dist/modes/daemon/daemon-session-summarizer.js.map +1 -1
  165. package/dist/modes/daemon/daemon-state-root.d.ts +15 -0
  166. package/dist/modes/daemon/daemon-state-root.d.ts.map +1 -0
  167. package/dist/modes/daemon/daemon-state-root.js +40 -0
  168. package/dist/modes/daemon/daemon-state-root.js.map +1 -0
  169. package/dist/modes/daemon/daemon-supervisor-ownership.d.ts +2 -0
  170. package/dist/modes/daemon/daemon-supervisor-ownership.d.ts.map +1 -1
  171. package/dist/modes/daemon/daemon-supervisor-ownership.js +27 -0
  172. package/dist/modes/daemon/daemon-supervisor-ownership.js.map +1 -1
  173. package/dist/modes/daemon/daemon-supervisor.d.ts +10 -1
  174. package/dist/modes/daemon/daemon-supervisor.d.ts.map +1 -1
  175. package/dist/modes/daemon/daemon-supervisor.js +213 -20
  176. package/dist/modes/daemon/daemon-supervisor.js.map +1 -1
  177. package/dist/modes/daemon/daemon-worker-protocol.d.ts +28 -1
  178. package/dist/modes/daemon/daemon-worker-protocol.d.ts.map +1 -1
  179. package/dist/modes/daemon/daemon-worker-protocol.js +16 -2
  180. package/dist/modes/daemon/daemon-worker-protocol.js.map +1 -1
  181. package/dist/modes/daemon/saved-session-catalog.d.ts.map +1 -1
  182. package/dist/modes/daemon/saved-session-catalog.js +2 -0
  183. package/dist/modes/daemon/saved-session-catalog.js.map +1 -1
  184. package/dist/modes/interactive/auth-flows.d.ts +0 -6
  185. package/dist/modes/interactive/auth-flows.d.ts.map +1 -1
  186. package/dist/modes/interactive/auth-flows.js +6 -126
  187. package/dist/modes/interactive/auth-flows.js.map +1 -1
  188. package/dist/modes/interactive/components/configuration-menu.d.ts +3 -0
  189. package/dist/modes/interactive/components/configuration-menu.d.ts.map +1 -1
  190. package/dist/modes/interactive/components/configuration-menu.js +13 -2
  191. package/dist/modes/interactive/components/configuration-menu.js.map +1 -1
  192. package/dist/modes/interactive/components/footer.d.ts +1 -1
  193. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  194. package/dist/modes/interactive/components/footer.js +2 -2
  195. package/dist/modes/interactive/components/footer.js.map +1 -1
  196. package/dist/modes/interactive/components/index.d.ts +0 -1
  197. package/dist/modes/interactive/components/index.d.ts.map +1 -1
  198. package/dist/modes/interactive/components/index.js +0 -1
  199. package/dist/modes/interactive/components/index.js.map +1 -1
  200. package/dist/modes/interactive/components/login-dialog.d.ts +0 -1
  201. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  202. package/dist/modes/interactive/components/login-dialog.js +3 -40
  203. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  204. package/dist/modes/interactive/components/model-selector.d.ts +2 -0
  205. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  206. package/dist/modes/interactive/components/model-selector.js +13 -2
  207. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  208. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  209. package/dist/modes/interactive/components/oauth-selector.js +2 -11
  210. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  211. package/dist/modes/interactive/feature-hints.d.ts.map +1 -1
  212. package/dist/modes/interactive/feature-hints.js +0 -4
  213. package/dist/modes/interactive/feature-hints.js.map +1 -1
  214. package/dist/modes/interactive/interactive-mode.d.ts +3 -12
  215. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  216. package/dist/modes/interactive/interactive-mode.js +81 -507
  217. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  218. package/dist/modes/interactive/onboarding.d.ts +0 -3
  219. package/dist/modes/interactive/onboarding.d.ts.map +1 -1
  220. package/dist/modes/interactive/onboarding.js +0 -17
  221. package/dist/modes/interactive/onboarding.js.map +1 -1
  222. package/dist/modes/rpc/rpc-client.d.ts +2 -1
  223. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  224. package/dist/modes/rpc/rpc-client.js +24 -11
  225. package/dist/modes/rpc/rpc-client.js.map +1 -1
  226. package/dist/node/amazon-bedrock.d.ts +2 -0
  227. package/dist/node/amazon-bedrock.d.ts.map +1 -0
  228. package/dist/node/amazon-bedrock.js +6 -0
  229. package/dist/node/amazon-bedrock.js.map +1 -0
  230. package/dist/product-identity.d.ts +0 -1
  231. package/dist/product-identity.d.ts.map +1 -1
  232. package/dist/product-identity.js +0 -1
  233. package/dist/product-identity.js.map +1 -1
  234. package/docs/development.md +1 -1
  235. package/docs/fork-philosophy.md +4 -8
  236. package/docs/installation.md +83 -62
  237. package/docs/providers.md +23 -25
  238. package/docs/quickstart.md +19 -10
  239. package/docs/rlm-runtime.md +13 -5
  240. package/docs/rpc.md +4 -4
  241. package/docs/sdk.md +20 -11
  242. package/docs/sessions.md +0 -1
  243. package/docs/settings.md +9 -42
  244. package/docs/skills.md +0 -1
  245. package/docs/upstream-0.9.5.md +171 -0
  246. package/docs/usage.md +14 -10
  247. package/package.json +4 -4
  248. package/dist/core/agent-traces.d.ts +0 -149
  249. package/dist/core/agent-traces.d.ts.map +0 -1
  250. package/dist/core/agent-traces.js +0 -904
  251. package/dist/core/agent-traces.js.map +0 -1
  252. package/dist/core/prime-inference-auth.d.ts +0 -70
  253. package/dist/core/prime-inference-auth.d.ts.map +0 -1
  254. package/dist/core/prime-inference-auth.js +0 -352
  255. package/dist/core/prime-inference-auth.js.map +0 -1
  256. package/dist/core/prime-inference-model-selection.d.ts +0 -16
  257. package/dist/core/prime-inference-model-selection.d.ts.map +0 -1
  258. package/dist/core/prime-inference-model-selection.js +0 -16
  259. package/dist/core/prime-inference-model-selection.js.map +0 -1
  260. package/dist/core/prime-inference-models.d.ts +0 -6
  261. package/dist/core/prime-inference-models.d.ts.map +0 -1
  262. package/dist/core/prime-inference-models.js +0 -62
  263. package/dist/core/prime-inference-models.js.map +0 -1
  264. package/dist/core/telemetry.d.ts +0 -95
  265. package/dist/core/telemetry.d.ts.map +0 -1
  266. package/dist/core/telemetry.js +0 -637
  267. package/dist/core/telemetry.js.map +0 -1
  268. package/dist/modes/interactive/components/prime-onboarding-splash.d.ts +0 -39
  269. package/dist/modes/interactive/components/prime-onboarding-splash.d.ts.map +0 -1
  270. package/dist/modes/interactive/components/prime-onboarding-splash.js +0 -286
  271. package/dist/modes/interactive/components/prime-onboarding-splash.js.map +0 -1
  272. package/dist/modes/interactive/components/prime-team-selector.d.ts +0 -30
  273. package/dist/modes/interactive/components/prime-team-selector.d.ts.map +0 -1
  274. package/dist/modes/interactive/components/prime-team-selector.js +0 -166
  275. package/dist/modes/interactive/components/prime-team-selector.js.map +0 -1
  276. package/dist/skills/prime-intellect/SKILL.md +0 -87
  277. package/dist/skills/prime-intellect/references/compute.md +0 -45
  278. package/dist/skills/prime-intellect/references/environments.md +0 -73
  279. package/dist/skills/prime-intellect/references/inference.md +0 -47
  280. package/dist/skills/prime-intellect/references/sandboxes.md +0 -75
  281. package/skills/prime-intellect/SKILL.md +0 -87
  282. package/skills/prime-intellect/references/compute.md +0 -45
  283. package/skills/prime-intellect/references/environments.md +0 -73
  284. package/skills/prime-intellect/references/inference.md +0 -47
  285. package/skills/prime-intellect/references/sandboxes.md +0 -75
@@ -1,5 +1,6 @@
1
1
  import type { AgentMessage, AgentOwnedStreamFn, StreamFn } from "@ponythewhite/base-context-agent";
2
2
  import { type Api, type AssistantMessage, type Context, type Model, type RequestTokenBudgetOptions, type SimpleStreamOptions } from "@ponythewhite/base-context-ai";
3
+ import type { AuthSourceToken } from "./auth-storage.js";
3
4
  import type { BoundRequestSink, NativeBranchRequestOutputWriter, NativeCompactionRequestOutputAssociation, NativePlannerRequestOutputWriter, RequestOwnerRef, RequestPurpose } from "./request-events.js";
4
5
  import { type RequestViewCommit, type RequestViewFixedPrepare, type RequestViewValidate } from "./request-view-selection.js";
5
6
  import type { SessionHistoryReadView } from "./session-history-index.js";
@@ -42,8 +43,12 @@ export declare const captureNativeBranchRequests: unique symbol;
42
43
  export declare const captureNativePlannerRequests: unique symbol;
43
44
  /** Internal native AgentSession reviewer invocation. */
44
45
  export declare const captureNativeReviewerRequests: unique symbol;
46
+ /** Consume the credential source resolved for this exact native request. Never persisted or sent to providers. */
47
+ export declare function takeNativeInferenceAuthSource(message: AssistantMessage): AuthSourceToken | undefined;
45
48
  /** Internal SDK auth/options resolver; transport stays the known instrumented AI dispatcher. */
46
- export declare function createNativeInferenceStream(resolveOptions: (model: Model<Api>, context: Context, options: SimpleStreamOptions | undefined) => Promise<SimpleStreamOptions>): StreamFn;
49
+ export declare function createNativeInferenceStream(resolveOptions: (model: Model<Api>, context: Context, options: SimpleStreamOptions | undefined) => Promise<SimpleStreamOptions & {
50
+ authSourceToken?: AuthSourceToken;
51
+ }>): StreamFn;
47
52
  /** Routes physical observations to the source writer. It owns no receipt store. */
48
53
  export declare class InferenceCoordinator {
49
54
  #private;
@@ -1 +1 @@
1
- {"version":3,"file":"inference-coordinator.d.ts","sourceRoot":"","sources":["../../src/core/inference-coordinator.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,kCAAkC,CAAC;AACnG,OAAO,EACN,KAAK,GAAG,EACR,KAAK,gBAAgB,EAErB,KAAK,OAAO,EAKZ,KAAK,KAAK,EAGV,KAAK,yBAAyB,EAC9B,KAAK,mBAAmB,EAExB,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EACX,gBAAgB,EAEhB,+BAA+B,EAC/B,wCAAwC,EACxC,gCAAgC,EAGhC,eAAe,EACf,cAAc,EAGd,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAKN,KAAK,iBAAiB,EACtB,KAAK,uBAAuB,EAC5B,KAAK,mBAAmB,EAExB,MAAM,6BAA6B,CAAC;AAErC,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAQzE,MAAM,WAAW,uBAAuB;IACvC,QAAQ,CAAC,OAAO,EAAE,cAAc,CAAC;IACjC,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IACpC,QAAQ,CAAC,cAAc,CAAC,EA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,EAAE,mBAAmB,GAAG,SAAS,EACxC,OAAO,EAAE,uBAAuB,GAC9B,OAAO,CAAC,YAAY,CAAC,CAUvB;YAEa,4BAA4B;IA0C1C,QAAQ,CACP,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,mBAAmB,GAAG,SAAS,EACxC,OAAO,EAAE,uBAAuB,GAC9B,OAAO,CAAC,gBAAgB,CAAC,CAkB3B;IAED,mBAAmB,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,uBAAuB,GAAG,yBAAyB,CAuBnG;IAED,UAAU,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,uBAAuB,GAAG,kBAAkB,CA4CnF;CACD;AAED,iGAAiG;AACjG,wBAAgB,iBAAiB,CAChC,QAAQ,EAAE,oBAAoB,GAAG,SAAS,EAC1C,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,mBAAmB,GAAG,SAAS,EACxC,OAAO,EAAE,uBAAuB,GAC9B,OAAO,CAAC,gBAAgB,CAAC,CAE3B;AAED,MAAM,MAAM,yBAAyB,GAAG,QAAQ,GAAG;IAClD,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACzB,sBAAsB,CAAC,CAAC,OAAO,EAAE,gBAAgB,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CAC3F,CAAC;AAEF,yFAAyF;AACzF,wBAAgB,4BAA4B,CAC3C,QAAQ,EAAE,QAAQ,EAClB,OAAO,EAAE,uBAAuB,GAC9B,yBAAyB,CAM3B","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport type { AgentMessage, AgentOwnedStreamFn, StreamFn } from \"@ponythewhite/base-context-agent\";\nimport {\n\ttype Api,\n\ttype AssistantMessage,\n\tassertBuiltInAttemptSupport,\n\ttype Context,\n\tcompleteSimple,\n\tinvokeRequestMeasurement,\n\tisLocalFauxStream,\n\tisTransientProviderFailure,\n\ttype Model,\n\ttype ProviderAttemptObserver,\n\tRequestTokenBudget,\n\ttype RequestTokenBudgetOptions,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n} from \"@ponythewhite/base-context-ai\";\nimport type {\n\tBoundRequestSink,\n\tContextEpochEntryRef,\n\tNativeBranchRequestOutputWriter,\n\tNativeCompactionRequestOutputAssociation,\n\tNativePlannerRequestOutputWriter,\n\tNativeRequestMetadata,\n\tNativeRequestOutputWriter,\n\tRequestOwnerRef,\n\tRequestPurpose,\n\tResolvedModelContract,\n\tSourceSnapshotRef,\n} from \"./request-events.js\";\nimport {\n\ttype CapturedRequestViewBoundary,\n\tcaptureRequestViewBoundary,\n\tmatchesRequestView,\n\tprepareFixedRequestView,\n\ttype RequestViewCommit,\n\ttype RequestViewFixedPrepare,\n\ttype RequestViewValidate,\n\tselectRequestView,\n} from \"./request-view-selection.js\";\nimport { hashTurnBody, MODEL_REQUEST_ID_HEADER, unwrapSemanticEdgeStreamFn } from \"./semantic-edges.js\";\nimport type { SessionHistoryReadView } from \"./session-history-index.js\";\nimport {\n\tcaptureNativeBranchOutputSource,\n\tcaptureNativeCompactionOutputSource,\n\tcaptureNativePlannerOutputSource,\n\tcaptureNativeRequestOutputSource,\n} from \"./session-manager.js\";\n\nexport interface InferenceRequestOptions {\n\treadonly purpose: RequestPurpose;\n\treadonly purposeDetail?: string;\n\treadonly operationId?: string;\n\treadonly parentOperationId?: string;\n\treadonly semanticEdgeId?: string;\n}\n\nexport interface InferenceSettlement {\n\treadonly message: AssistantMessage;\n\treadonly operationId: string;\n\treadonly attemptIds: readonly string[];\n\t/** Reporting is not a guarantee about an opaque adapter's hidden retries. */\n\treadonly physicalCoverage: \"reported\" | \"unestablished\" | \"local-simulation\";\n}\n\n/** Private completion identity carries this actual source, never descriptive sink labels. */\nexport interface NativeCompactionOutputBinding {\n\treadonly sink: BoundRequestSink;\n\treadonly output: NativeCompactionRequestOutputAssociation;\n}\n\ninterface NativeBranchOutputBinding {\n\treadonly owner: InferenceCoordinator;\n\treadonly write: NativeBranchRequestOutputWriter;\n}\n\ninterface NativePlannerOutputBinding {\n\treadonly owner: InferenceCoordinator;\n\treadonly write: NativePlannerRequestOutputWriter;\n}\n\nexport interface InferenceRun {\n\treadonly events: Awaited<ReturnType<StreamFn>>;\n\treadonly settled: Promise<InferenceSettlement>;\n}\n\nexport interface SessionRuntimeServices {\n\treadonly requests: InferenceCoordinator;\n}\n\ninterface ProviderRecoveryPolicy {\n\tenabled: boolean;\n\tbaseDelayMs: number;\n\tmaxRetryDelayMs: number;\n}\n\ninterface SinkUse {\n\treadonly sink: BoundRequestSink;\n\tactiveUsers: number;\n\tcaptures: number;\n\trelease?: Promise<void>;\n}\n\ninterface BoundOperation {\n\treadonly binding: SinkUse;\n\treadonly owner: Omit<RequestOwnerRef, \"sessionId\">;\n\treadonly metadata: Omit<NativeRequestMetadata, \"source\" | \"owner\" | \"contextEpoch\">;\n}\n\nconst REQUEST_STREAM_BINDING = Symbol(\"base-context.request-stream-binding\");\n/** Internal AgentSession built-in compaction entry, not a public inference option. */\nexport const captureNativeCompactionRequests = Symbol(\"base-context.native-compaction-requests\");\n/** Internal AgentSession built-in branch-summary invocation, never inherited by generic capture. */\nexport const captureNativeBranchRequests = Symbol(\"base-context.native-branch-requests\");\n/** Internal native AgentSession planner capture, never inherited by generic capture. */\nexport const captureNativePlannerRequests = Symbol(\"base-context.native-planner-requests\");\n/** Internal native AgentSession reviewer invocation. */\nexport const captureNativeReviewerRequests = Symbol(\"base-context.native-reviewer-requests\");\ninterface StreamBinding {\n\treadonly coordinator: InferenceCoordinator;\n\treadonly inner: StreamFn;\n}\ntype BoundStreamFn = AgentOwnedStreamFn & { [REQUEST_STREAM_BINDING]?: StreamBinding };\n\nfunction modelContract(model: Model<Api>): ResolvedModelContract {\n\treturn {\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tprofile: { id: \"native-default\", status: \"unvalidated\" },\n\t\tpricing: {\n\t\t\tstatus: \"unvalidated\",\n\t\t\tcurrency: \"USD\",\n\t\t\tunit: \"million-tokens\",\n\t\t\tcatalogRates: {\n\t\t\t\tinput: model.cost.input,\n\t\t\t\toutput: model.cost.output,\n\t\t\t\tcacheRead: model.cost.cacheRead,\n\t\t\t\tcacheWrite: model.cost.cacheWrite,\n\t\t\t},\n\t\t},\n\t};\n}\n\nconst nativeStreamFunctions = new WeakSet<StreamFn>();\n\n/** Internal SDK auth/options resolver; transport stays the known instrumented AI dispatcher. */\nexport function createNativeInferenceStream(\n\tresolveOptions: (\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t) => Promise<SimpleStreamOptions>,\n): StreamFn {\n\tconst dispatch: StreamFn = async (model, context, options) => {\n\t\tconst resolved = await resolveOptions(model, context, options);\n\t\treturn streamSimple(model, context, {\n\t\t\t...resolved,\n\t\t\tsignal: options?.signal,\n\t\t\tattempts: options?.attempts,\n\t\t\trequireProviderAttempts: true,\n\t\t});\n\t};\n\tnativeStreamFunctions.add(dispatch);\n\treturn dispatch;\n}\n\n/** Routes physical observations to the source writer. It owns no receipt store. */\nexport class InferenceCoordinator {\n\t#nativeCompactionOutput = false;\n\t#nativeBranchOutput = false;\n\t#nativePlannerOutput = false;\n\t#auxiliaryAttempts?: { remaining: number };\n\tprivate retryTurn = false;\n\tprivate requestViewBoundary?: CapturedRequestViewBoundary;\n\tprivate active = new Set<Promise<void>>();\n\tprivate capturedSink?: SinkUse;\n\tprivate captureReserved = false;\n\tprivate finishCapturePending?: () => void;\n\tprivate disposed = false;\n\tprivate disposal?: Promise<void>;\n\tprivate work = {\n\t\tpending: new Set<Promise<void>>(),\n\t\tsinks: new WeakMap<BoundRequestSink, SinkUse>(),\n\t\tmainOutputs: new WeakMap<AssistantMessage, NativeRequestOutputWriter>(),\n\t\tcompactionSettlements: new WeakMap<InferenceSettlement, NativeCompactionOutputBinding>(),\n\t\tcompactionCompletions: new WeakMap<Promise<AssistantMessage>, NativeCompactionOutputBinding>(),\n\t\tbranchSettlements: new WeakMap<InferenceSettlement, NativeBranchOutputBinding>(),\n\t\tbranchCompletions: new WeakMap<Promise<AssistantMessage>, NativeBranchOutputBinding>(),\n\t\tplannerSettlements: new WeakMap<InferenceSettlement, NativePlannerOutputBinding>(),\n\t\tplannerCompletions: new WeakMap<Promise<AssistantMessage>, NativePlannerOutputBinding>(),\n\t\tlisteners: new Set<() => void>(),\n\t\tadmissionOpen: true,\n\t\tcancellation: new AbortController(),\n\t\tbudget: undefined as RequestTokenBudget | undefined,\n\t\tbudgetMode: undefined as RequestTokenBudgetOptions[\"mode\"] | undefined,\n\t\tproviderRecoveryPolicy: undefined as (() => ProviderRecoveryPolicy) | undefined,\n\t};\n\n\tsetProviderRecoveryPolicy(policy: () => ProviderRecoveryPolicy): void {\n\t\tthis.work.providerRecoveryPolicy = policy;\n\t}\n\n\tget hasPending(): boolean {\n\t\treturn this.work.pending.size > 0;\n\t}\n\tget pendingCount(): number {\n\t\treturn this.work.pending.size;\n\t}\n\n\tonActivityChange(listener: () => void): () => void {\n\t\tthis.work.listeners.add(listener);\n\t\treturn () => this.work.listeners.delete(listener);\n\t}\n\n\tprivate notifyActivity(): void {\n\t\t// Observers can wake an existing owner, but cannot own request settlement.\n\t\tfor (const listener of this.work.listeners) {\n\t\t\ttry {\n\t\t\t\tlistener();\n\t\t\t} catch {\n\t\t\t\t/* Notification is not execution. */\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Consume only this owner's real returned object. Labels and replacement messages remain unassociated. */\n\tappendMainOutput(message: AssistantMessage, owner: object): Promise<string | undefined> | undefined {\n\t\tconst write = this.work.mainOutputs.get(message);\n\t\tthis.work.mainOutputs.delete(message);\n\t\treturn write?.(owner, message);\n\t}\n\n\t/** Opt this native invocation into output association; ordinary captures do not inherit that authority. */\n\t[captureNativeCompactionRequests](): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this);\n\t\tcaptured.#nativeCompactionOutput = true;\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 4 };\n\t\treturn captured;\n\t}\n\n\t[captureNativeBranchRequests](sink: BoundRequestSink): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this, sink);\n\t\tcaptured.#nativeBranchOutput = true;\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 2 };\n\t\treturn captured;\n\t}\n\n\ttakeBranchOutput(completion: Promise<AssistantMessage>): NativeBranchRequestOutputWriter | undefined {\n\t\tconst binding = this.work.branchCompletions.get(completion);\n\t\tthis.work.branchCompletions.delete(completion);\n\t\tif (!binding || !this.#nativeBranchOutput || binding.owner !== this) return undefined;\n\t\treturn binding.write;\n\t}\n\n\t[captureNativePlannerRequests](sink: BoundRequestSink): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this, sink);\n\t\tcaptured.#nativePlannerOutput = true;\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 2 };\n\t\treturn captured;\n\t}\n\n\t[captureNativeReviewerRequests](): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this);\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 2 };\n\t\treturn captured;\n\t}\n\n\ttakePlannerOutput(completion: Promise<AssistantMessage>): NativePlannerRequestOutputWriter | undefined {\n\t\tconst binding = this.work.plannerCompletions.get(completion);\n\t\tthis.work.plannerCompletions.delete(completion);\n\t\tif (!binding || !this.#nativePlannerOutput || binding.owner !== this) return undefined;\n\t\treturn binding.write;\n\t}\n\n\t/** Only the original completion promise and captured source can supply a projected-output link. */\n\ttakeCompactionOutput(completion: Promise<AssistantMessage>): NativeCompactionOutputBinding | undefined {\n\t\tconst binding = this.work.compactionCompletions.get(completion);\n\t\tthis.work.compactionCompletions.delete(completion);\n\t\treturn binding?.sink === this.capturedSink?.sink ? binding : undefined;\n\t}\n\n\t/** Owner teardown stops new sends, but never suppresses an admitted request's settlement. */\n\tstopAdmission(): void {\n\t\tthis.work.admissionOpen = false;\n\t\tthis.work.cancellation.abort();\n\t\tthis.notifyActivity();\n\t}\n\n\tasync waitForIdle(): Promise<void> {\n\t\twhile (this.work.pending.size > 0) await Promise.all([...this.work.pending]);\n\t}\n\n\tprepareTurnRetry(): void {\n\t\tthis.retryTurn = true;\n\t}\n\tclearTurnRetry(): void {\n\t\tthis.retryTurn = false;\n\t}\n\n\tconstructor(\n\t\tprivate readonly bindSink: () => BoundRequestSink,\n\t\tprivate readonly owner: () => Omit<RequestOwnerRef, \"sessionId\"> = () => ({}),\n\t\trequestTokenBudget?: RequestTokenBudgetOptions,\n\t) {\n\t\tif (requestTokenBudget) {\n\t\t\tthis.work.budget = new RequestTokenBudget(requestTokenBudget);\n\t\t\tthis.work.budgetMode = requestTokenBudget.mode;\n\t\t}\n\t}\n\n\t/** Copy the configured policy, not this owner's learned request observations. */\n\tgetRequestTokenBudgetOptions(): RequestTokenBudgetOptions | undefined {\n\t\treturn this.work.budget?.getOptions();\n\t}\n\n\tprivate assertAdmission(): void {\n\t\tif (this.disposed || !this.work.admissionOpen) throw new Error(\"Inference owner is closing\");\n\t}\n\n\tprivate sinkUse(sink: BoundRequestSink): SinkUse {\n\t\tlet binding = this.work.sinks.get(sink);\n\t\tif (!binding) {\n\t\t\tbinding = { sink, activeUsers: 0, captures: 0 };\n\t\t\tthis.work.sinks.set(sink, binding);\n\t\t}\n\t\treturn binding;\n\t}\n\n\tprivate releaseCapture(): void {\n\t\tif (this.captureReserved && this.capturedSink) {\n\t\t\tthis.captureReserved = false;\n\t\t\tthis.capturedSink.captures--;\n\t\t}\n\t}\n\n\t/** Capture an auxiliary operation's subject before asynchronous auth or UI work. */\n\tcapture(sink?: BoundRequestSink): InferenceCoordinator {\n\t\tthis.assertAdmission();\n\t\tconst owner = Object.freeze({ ...this.owner() });\n\t\tconst binding = this.sinkUse(sink ?? this.bindSink());\n\t\tbinding.sink.retain();\n\t\tbinding.release = undefined;\n\t\tbinding.captures++;\n\t\tconst captured = new InferenceCoordinator(\n\t\t\t() => binding.sink,\n\t\t\t() => owner,\n\t\t);\n\t\tcaptured.work = this.work;\n\t\t// Nested captures share the invocation's allowance, not its native output authority.\n\t\tcaptured.#auxiliaryAttempts = this.#auxiliaryAttempts;\n\t\tcaptured.capturedSink = binding;\n\t\tcaptured.captureReserved = true;\n\t\tlet release!: () => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\trelease = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tcaptured.finishCapturePending = () => {\n\t\t\tthis.work.pending.delete(pending);\n\t\t\tcaptured.finishCapturePending = undefined;\n\t\t\trelease();\n\t\t\tthis.notifyActivity();\n\t\t};\n\t\tthis.notifyActivity();\n\t\treturn captured;\n\t}\n\n\t/** Explicit Root-owned epoch boundary, on this same captured MAIN source only. */\n\tbindRequestViewBoundary(\n\t\tmessages: readonly AgentMessage[],\n\t\tcommit: RequestViewCommit,\n\t\tvalidate?: RequestViewValidate,\n\t\tfixedPrepare?: RequestViewFixedPrepare,\n\t): void {\n\t\tthis.assertAdmission();\n\t\tif (!this.capturedSink) throw new Error(\"Request view boundary requires a captured inference owner\");\n\t\tif (this.requestViewBoundary) throw new Error(\"Request view boundary is already bound\");\n\t\tthis.requestViewBoundary = captureRequestViewBoundary(messages, commit, validate, fixedPrepare);\n\t}\n\n\t/** Read through an explicit capture, never by recapturing the mutable current session. */\n\tasync readHistory<T>(read: (view: SessionHistoryReadView) => Promise<T>): Promise<T> {\n\t\tthis.assertAdmission();\n\t\tconst sink = this.capturedSink?.sink;\n\t\tif (!sink?.readHistory) throw new Error(\"Captured canonical history is unavailable\");\n\t\tlet finish!: () => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\tfinish = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tthis.active.add(pending);\n\t\tthis.notifyActivity();\n\t\ttry {\n\t\t\treturn await sink.readHistory(read);\n\t\t} finally {\n\t\t\tthis.active.delete(pending);\n\t\t\tthis.work.pending.delete(pending);\n\t\t\tfinish();\n\t\t\tthis.notifyActivity();\n\t\t}\n\t}\n\n\t/** Release an unused capture, or join this capture's admitted requests. */\n\tdispose(): Promise<void> {\n\t\tthis.disposed = true;\n\t\tthis.disposal ??= (async () => {\n\t\t\tthis.releaseCapture();\n\t\t\ttry {\n\t\t\t\tawait Promise.all([...this.active]);\n\t\t\t\tif (this.capturedSink) await this.finishSink(this.capturedSink, [], false, []);\n\t\t\t} finally {\n\t\t\t\tthis.finishCapturePending?.();\n\t\t\t}\n\t\t})();\n\t\treturn this.disposal;\n\t}\n\n\tprivate bindOperation(model: Model<Api>, request: InferenceRequestOptions, operationId: string): BoundOperation {\n\t\tthis.assertAdmission();\n\t\tconst owner = Object.freeze({ ...this.owner() });\n\t\tconst metadata = Object.freeze({\n\t\t\toperationId,\n\t\t\tparentOperationId: request.parentOperationId,\n\t\t\tsemanticEdgeId: request.semanticEdgeId,\n\t\t\tpurpose: request.purpose,\n\t\t\tpurposeDetail: request.purposeDetail,\n\t\t\tmodelContract: modelContract(model),\n\t\t});\n\t\treturn { binding: this.sinkUse(this.bindSink()), owner, metadata };\n\t}\n\n\tprivate async finishSink(\n\t\tbinding: SinkUse,\n\t\twrites: readonly Promise<void>[],\n\t\tactiveUser: boolean,\n\t\tfailures: unknown[],\n\t): Promise<void> {\n\t\tconst results = await Promise.allSettled([binding.sink.source, ...writes]);\n\t\tfor (const result of results) {\n\t\t\tif (result.status === \"rejected\") failures.push(result.reason);\n\t\t}\n\t\tif (activeUser) binding.activeUsers--;\n\t\ttry {\n\t\t\tif (binding.activeUsers === 0 && binding.captures === 0) {\n\t\t\t\tbinding.release ??= binding.sink.release();\n\t\t\t\tawait binding.release;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tfailures.push(error);\n\t\t}\n\t\tconst distinct = [...new Set(failures)];\n\t\tif (distinct.length === 1) throw distinct[0];\n\t\tif (distinct.length > 1) throw new AggregateError(distinct, \"Inference request or source cleanup failed\");\n\t}\n\n\t/** Hold one logical operation through settled sends and recovery delays. */\n\tprivate retainWork(binding: SinkUse): (failures?: unknown[]) => Promise<void> {\n\t\tthis.assertAdmission();\n\t\tbinding.sink.retain();\n\t\tbinding.release = undefined;\n\t\tbinding.captures++;\n\t\tlet finish!: () => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\tfinish = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tthis.active.add(pending);\n\t\tthis.notifyActivity();\n\t\tlet release: Promise<void> | undefined;\n\t\treturn (failures = []) => {\n\t\t\trelease ??= (async () => {\n\t\t\t\tbinding.captures--;\n\t\t\t\ttry {\n\t\t\t\t\tawait this.finishSink(binding, [], false, failures);\n\t\t\t\t} finally {\n\t\t\t\t\tthis.active.delete(pending);\n\t\t\t\t\tthis.work.pending.delete(pending);\n\t\t\t\t\tfinish();\n\t\t\t\t\tthis.notifyActivity();\n\t\t\t\t}\n\t\t\t})();\n\t\t\treturn release;\n\t\t};\n\t}\n\n\tprivate providerRecoveryWait(): (message: AssistantMessage, signal?: AbortSignal) => Promise<boolean> {\n\t\tlet nextDelayMs: number | undefined;\n\t\treturn async (message, callerSignal) => {\n\t\t\tconst policy = this.work.providerRecoveryPolicy?.();\n\t\t\tif (!policy?.enabled || !isTransientProviderFailure(message)) return false;\n\t\t\tthis.assertAdmission();\n\t\t\tconst signal = callerSignal\n\t\t\t\t? AbortSignal.any([callerSignal, this.work.cancellation.signal])\n\t\t\t\t: this.work.cancellation.signal;\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst delayMs = Math.min(nextDelayMs ?? policy.baseDelayMs, policy.maxRetryDelayMs);\n\t\t\tawait delay(delayMs, undefined, { signal });\n\t\t\tsignal.throwIfAborted();\n\t\t\tthis.assertAdmission();\n\t\t\tnextDelayMs = Math.min(delayMs * 2, policy.maxRetryDelayMs);\n\t\t\treturn this.work.providerRecoveryPolicy?.().enabled === true;\n\t\t};\n\t}\n\n\tprivate async execute(\n\t\toperation: BoundOperation,\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\tsend: StreamFn,\n\t\tbindMainOutput = false,\n\t): Promise<InferenceRun> {\n\t\tconst outputSource = bindMainOutput ? captureNativeRequestOutputSource(operation.binding.sink) : undefined;\n\t\tconst part =\n\t\t\toperation.metadata.purpose === \"summary\"\n\t\t\t\t? operation.metadata.purposeDetail === \"compaction\"\n\t\t\t\t\t? \"history\"\n\t\t\t\t\t: operation.metadata.purposeDetail === \"compaction-turn-prefix\"\n\t\t\t\t\t\t? \"turn-prefix\"\n\t\t\t\t\t\t: undefined\n\t\t\t\t: undefined;\n\t\tconst compactionSource =\n\t\t\tthis.#nativeCompactionOutput && part && this.capturedSink?.sink === operation.binding.sink\n\t\t\t\t? captureNativeCompactionOutputSource(operation.binding.sink)\n\t\t\t\t: undefined;\n\t\tconst branchSource =\n\t\t\tthis.#nativeBranchOutput &&\n\t\t\toperation.metadata.purpose === \"summary\" &&\n\t\t\toperation.metadata.purposeDetail === \"branch\" &&\n\t\t\tthis.capturedSink?.sink === operation.binding.sink\n\t\t\t\t? captureNativeBranchOutputSource(operation.binding.sink)\n\t\t\t\t: undefined;\n\t\tconst plannerSource =\n\t\t\tthis.#nativePlannerOutput &&\n\t\t\toperation.metadata.purpose === \"refine\" &&\n\t\t\toperation.metadata.purposeDetail === \"plan\" &&\n\t\t\tthis.capturedSink?.sink === operation.binding.sink\n\t\t\t\t? captureNativePlannerOutputSource(operation.binding.sink)\n\t\t\t\t: undefined;\n\t\tlet outputSourceRef: SourceSnapshotRef | undefined;\n\t\tlet release!: (completion?: PromiseLike<void>) => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\trelease = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tthis.active.add(pending);\n\t\tthis.notifyActivity();\n\t\tconst finish = () => {\n\t\t\tthis.work.pending.delete(pending);\n\t\t\tthis.active.delete(pending);\n\t\t\tthis.notifyActivity();\n\t\t};\n\t\tconst admittedAttempts: Array<{ attemptId: string; contextEpoch?: ContextEpochEntryRef }> = [];\n\t\tconst receiptWrites: Promise<void>[] = [];\n\t\tlet activeUser = false;\n\t\tlet localSimulation = false;\n\t\tlet budgetFailure: unknown;\n\t\tconst settle = async (result: Promise<AssistantMessage>): Promise<InferenceSettlement> => {\n\t\t\tconst failures: unknown[] = [];\n\t\t\tlet message: AssistantMessage | undefined;\n\t\t\ttry {\n\t\t\t\tmessage = await result;\n\t\t\t} catch (error) {\n\t\t\t\tfailures.push(error);\n\t\t\t}\n\t\t\tif (budgetFailure !== undefined && !failures.includes(budgetFailure)) failures.push(budgetFailure);\n\t\t\tawait this.finishSink(operation.binding, receiptWrites, activeUser, failures);\n\t\t\tif (message && outputSource && outputSourceRef) {\n\t\t\t\tconst write = outputSource({\n\t\t\t\t\toperationId: operation.metadata.operationId,\n\t\t\t\t\tattemptIds: admittedAttempts.map(({ attemptId }) => attemptId),\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (write) this.work.mainOutputs.set(message, write);\n\t\t\t}\n\t\t\tconst settlement: InferenceSettlement = {\n\t\t\t\tmessage: message!,\n\t\t\t\toperationId: operation.metadata.operationId,\n\t\t\t\tattemptIds: admittedAttempts.map(({ attemptId }) => attemptId),\n\t\t\t\tphysicalCoverage: admittedAttempts.length\n\t\t\t\t\t? \"reported\"\n\t\t\t\t\t: localSimulation\n\t\t\t\t\t\t? \"local-simulation\"\n\t\t\t\t\t\t: \"unestablished\",\n\t\t\t};\n\t\t\tif (part && compactionSource && outputSourceRef) {\n\t\t\t\tconst output = compactionSource({\n\t\t\t\t\toperationId: settlement.operationId,\n\t\t\t\t\tattemptIds: settlement.attemptIds,\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (output)\n\t\t\t\t\tthis.work.compactionSettlements.set(settlement, {\n\t\t\t\t\t\tsink: operation.binding.sink,\n\t\t\t\t\t\toutput: { ...output, part },\n\t\t\t\t\t});\n\t\t\t}\n\t\t\tif (branchSource && outputSourceRef) {\n\t\t\t\tconst write = branchSource({\n\t\t\t\t\toperationId: settlement.operationId,\n\t\t\t\t\tattemptIds: settlement.attemptIds,\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (write) this.work.branchSettlements.set(settlement, { owner: this, write });\n\t\t\t}\n\t\t\tif (plannerSource && outputSourceRef) {\n\t\t\t\tconst write = plannerSource({\n\t\t\t\t\toperationId: settlement.operationId,\n\t\t\t\t\tattemptIds: settlement.attemptIds,\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (write) this.work.plannerSettlements.set(settlement, { owner: this, write });\n\t\t\t}\n\t\t\treturn settlement;\n\t\t};\n\t\ttry {\n\t\t\tthis.assertAdmission();\n\t\t\toperation.binding.sink.retain();\n\t\t\toperation.binding.release = undefined;\n\t\t\toperation.binding.activeUsers++;\n\t\t\tactiveUser = true;\n\t\t\tthis.releaseCapture();\n\t\t\tthis.finishCapturePending?.();\n\t\t\t// Capture the opted-in budgeted invocation before source/auth waits. Callbacks and signals stay live handles.\n\t\t\tif (this.work.budget || (this.requestViewBoundary && operation.metadata.purpose === \"main\")) {\n\t\t\t\tmodel = structuredClone(model);\n\t\t\t\t// Agent tool objects also carry live executors. Snapshot only the native Tool definition.\n\t\t\t\tcontext = structuredClone({\n\t\t\t\t\t...context,\n\t\t\t\t\t...(context.tools\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\ttools: context.tools.map(({ name, description, parameters }) => ({\n\t\t\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t\t\tdescription,\n\t\t\t\t\t\t\t\t\tparameters,\n\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t});\n\t\t\t\toptions = options\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t...options,\n\t\t\t\t\t\t\theaders: options.headers ? { ...options.headers } : undefined,\n\t\t\t\t\t\t\tthinkingBudgets: options.thinkingBudgets ? { ...options.thinkingBudgets } : undefined,\n\t\t\t\t\t\t\tmetadata: options.metadata ? structuredClone(options.metadata) : undefined,\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined;\n\t\t\t}\n\t\t\tconst source = Object.freeze({ ...(await operation.binding.sink.source) });\n\t\t\toutputSourceRef = source;\n\t\t\tconst metadata: NativeRequestMetadata = {\n\t\t\t\t...operation.metadata,\n\t\t\t\tsource,\n\t\t\t\towner: Object.freeze({ ...operation.owner, sessionId: source.sessionId }),\n\t\t\t};\n\t\t\tif (send !== streamSimple && !nativeStreamFunctions.has(send)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Native inference cannot admit a custom or proxy StreamFn with unestablished physical-attempt coverage. Use the SDK's instrumented built-in API route instead.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tassertBuiltInAttemptSupport(model.api);\n\t\t\tif (!this.work.admissionOpen) throw new Error(\"Inference owner is closing\");\n\t\t\tconst parentBudget = this.work.budget;\n\t\t\tconst boundary = operation.metadata.purpose === \"main\" ? this.requestViewBoundary : undefined;\n\t\t\tconst budget = boundary ? parentBudget?.capture() : parentBudget;\n\t\t\tlet measuredForAdmission = false;\n\t\t\tconst measureRequest: ProviderAttemptObserver[\"measureRequest\"] =\n\t\t\t\tbudget || boundary?.validate\n\t\t\t\t\t? (representation) => {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tconst assessment = budget?.measure(representation);\n\t\t\t\t\t\t\t\tboundary?.validate?.(representation, assessment);\n\t\t\t\t\t\t\t\tif (budget && assessment) budget.assert(assessment);\n\t\t\t\t\t\t\t\tmeasuredForAdmission = true;\n\t\t\t\t\t\t\t\treturn assessment;\n\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\tbudgetFailure = error;\n\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined;\n\t\t\tconst canSelect =\n\t\t\t\t(budget || boundary?.fixedPrepare) && boundary && matchesRequestView(boundary, source, context);\n\t\t\tconst requiredPublic = Boolean(boundary?.pendingPublicMessageGroups?.length);\n\t\t\tif (requiredPublic && (!canSelect || boundary?.fixedPrepare))\n\t\t\t\tthrow new Error(\"Tool continuation requires a selectable native public request boundary\");\n\t\t\tlet publicAccepted = false;\n\t\t\tlet selectedContextEpoch: ContextEpochEntryRef | undefined;\n\t\t\tconst attempts: ProviderAttemptObserver = {\n\t\t\t\t...(requiredPublic\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tpendingPublicMessageGroups: boundary!.providerPendingPublicMessageGroups!.map((group) => [\n\t\t\t\t\t\t\t\t...group,\n\t\t\t\t\t\t\t]),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(measureRequest ? { measureRequest } : {}),\n\t\t\t\t...(canSelect\n\t\t\t\t\t? ({\n\t\t\t\t\t\t\tprepareRequest: async (representation, projection) => {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tselectedContextEpoch = undefined;\n\t\t\t\t\t\t\t\t\tpublicAccepted = false;\n\t\t\t\t\t\t\t\t\tif (JSON.parse(representation.body!).model !== model.id) return;\n\t\t\t\t\t\t\t\t\tif (boundary!.fixedPrepare) {\n\t\t\t\t\t\t\t\t\t\tconst assessment = budget?.measure(representation);\n\t\t\t\t\t\t\t\t\t\tif (budget && assessment) budget.assert(assessment);\n\t\t\t\t\t\t\t\t\t\tconst accepted = await prepareFixedRequestView(\n\t\t\t\t\t\t\t\t\t\t\tboundary!,\n\t\t\t\t\t\t\t\t\t\t\trepresentation,\n\t\t\t\t\t\t\t\t\t\t\tprojection,\n\t\t\t\t\t\t\t\t\t\t\tassessment,\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\tif (accepted) selectedContextEpoch = Object.freeze({ ...accepted });\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treturn await selectRequestView(\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t...boundary!,\n\t\t\t\t\t\t\t\t\t\t\tcommit: async (candidate) => {\n\t\t\t\t\t\t\t\t\t\t\t\tconst accepted = await boundary!.commit(candidate);\n\t\t\t\t\t\t\t\t\t\t\t\tif (accepted) selectedContextEpoch = Object.freeze({ ...accepted });\n\t\t\t\t\t\t\t\t\t\t\t\tpublicAccepted = Boolean(\n\t\t\t\t\t\t\t\t\t\t\t\t\taccepted &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcandidate.publicMessages &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcandidate.projection.publicWindow &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t!candidate.projection.pendingPublicMessageGroups?.length,\n\t\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\t\treturn accepted || undefined;\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\trepresentation,\n\t\t\t\t\t\t\t\t\t\tprojection,\n\t\t\t\t\t\t\t\t\t\tbudget!,\n\t\t\t\t\t\t\t\t\t\tthis.work.budgetMode === \"enforce\",\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\t\tbudgetFailure = error;\n\t\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t} satisfies Pick<ProviderAttemptObserver, \"prepareRequest\">)\n\t\t\t\t\t: {}),\n\t\t\t\tadmit: async (descriptor) => {\n\t\t\t\t\tif (requiredPublic && !publicAccepted)\n\t\t\t\t\t\tthrow new Error(\"Unaccepted tool continuation cannot enter native transport\");\n\t\t\t\t\tif (!this.work.admissionOpen) throw new Error(\"Inference owner is closing\");\n\t\t\t\t\t// An adapter without a serializer meter must not bypass an enforced budget.\n\t\t\t\t\tif (measureRequest && !descriptor.requestBudget && (budget || !measuredForAdmission)) {\n\t\t\t\t\t\tconst assessment = invokeRequestMeasurement(attempts, {\n\t\t\t\t\t\t\tapi: descriptor.api,\n\t\t\t\t\t\t\tprovider: descriptor.provider,\n\t\t\t\t\t\t\turl: \"\",\n\t\t\t\t\t\t\tbody: undefined,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (assessment) descriptor = { ...descriptor, requestBudget: assessment };\n\t\t\t\t\t}\n\t\t\t\t\tmeasuredForAdmission = false;\n\t\t\t\t\tif (this.#auxiliaryAttempts) {\n\t\t\t\t\t\tif (this.#auxiliaryAttempts.remaining === 0) {\n\t\t\t\t\t\t\tbudgetFailure ??= new Error(\"Native auxiliary operation attempt limit exhausted\");\n\t\t\t\t\t\t\tthrow budgetFailure;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Reserve synchronously before persistence; failures and cancellation do not refund it.\n\t\t\t\t\t\tthis.#auxiliaryAttempts.remaining--;\n\t\t\t\t\t}\n\t\t\t\t\tconst attemptId = randomUUID();\n\t\t\t\t\tconst contextEpoch = selectedContextEpoch ? Object.freeze({ ...selectedContextEpoch }) : undefined;\n\t\t\t\t\tconst write = operation.binding.sink.persist({\n\t\t\t\t\t\t...metadata,\n\t\t\t\t\t\t...(contextEpoch ? { contextEpoch } : {}),\n\t\t\t\t\t\ttype: \"attempt_admitted\",\n\t\t\t\t\t\tattemptId,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\tdescriptor,\n\t\t\t\t\t});\n\t\t\t\t\treceiptWrites.push(write);\n\t\t\t\t\tawait write;\n\t\t\t\t\tadmittedAttempts.push({ attemptId, contextEpoch });\n\t\t\t\t\treturn attemptId;\n\t\t\t\t},\n\t\t\t\tsettle: async (receipt) => {\n\t\t\t\t\tconst contextEpoch = admittedAttempts.find(\n\t\t\t\t\t\t(attempt) => attempt.attemptId === receipt.attemptId,\n\t\t\t\t\t)?.contextEpoch;\n\t\t\t\t\tconst write = operation.binding.sink.persist({\n\t\t\t\t\t\t...metadata,\n\t\t\t\t\t\t...(contextEpoch ? { contextEpoch } : {}),\n\t\t\t\t\t\ttype: \"attempt_settled\",\n\t\t\t\t\t\tattemptId: receipt.attemptId,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\treceipt,\n\t\t\t\t\t});\n\t\t\t\t\treceiptWrites.push(write);\n\t\t\t\t\tawait write;\n\t\t\t\t\tparentBudget?.observe(receipt);\n\t\t\t\t},\n\t\t\t};\n\t\t\tconst signal = options?.signal\n\t\t\t\t? AbortSignal.any([options.signal, this.work.cancellation.signal])\n\t\t\t\t: this.work.cancellation.signal;\n\t\t\tconst events = await send(model, context, { ...options, signal, attempts, requireProviderAttempts: true });\n\t\t\tlocalSimulation = isLocalFauxStream(events);\n\t\t\tconst settled = settle(events.result());\n\t\t\tevents.result = async () => (await settled).message;\n\t\t\t// Idle tracking observes rejection; callers still receive it through settled/result().\n\t\t\trelease(settled.then(finish, finish));\n\t\t\treturn { events, settled };\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tawait settle(Promise.reject(error));\n\t\t\t} finally {\n\t\t\t\tfinish();\n\t\t\t\trelease();\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync start(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\trequest: InferenceRequestOptions,\n\t): Promise<InferenceRun> {\n\t\tconst semanticEdgeId = request.semanticEdgeId ?? options?.headers?.[MODEL_REQUEST_ID_HEADER];\n\t\tconst operationId = request.operationId ?? semanticEdgeId ?? randomUUID();\n\t\treturn this.execute(\n\t\t\tthis.bindOperation(model, { ...request, semanticEdgeId }, operationId),\n\t\t\tmodel,\n\t\t\tcontext,\n\t\t\toptions,\n\t\t\tstreamSimple,\n\t\t);\n\t}\n\n\tprivate async completeWithProviderRecovery(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\trequest: InferenceRequestOptions,\n\t): Promise<InferenceSettlement> {\n\t\t// Retry the same request, not a caller's later mutable inputs. Keep callbacks/signals live.\n\t\tmodel = structuredClone(model);\n\t\tcontext = structuredClone({\n\t\t\t...context,\n\t\t\t...(context.tools\n\t\t\t\t? { tools: context.tools.map(({ name, description, parameters }) => ({ name, description, parameters })) }\n\t\t\t\t: {}),\n\t\t});\n\t\toptions = options\n\t\t\t? {\n\t\t\t\t\t...options,\n\t\t\t\t\theaders: options.headers ? { ...options.headers } : undefined,\n\t\t\t\t\tthinkingBudgets: options.thinkingBudgets ? { ...options.thinkingBudgets } : undefined,\n\t\t\t\t\tmetadata: options.metadata ? structuredClone(options.metadata) : undefined,\n\t\t\t\t}\n\t\t\t: undefined;\n\t\tconst semanticEdgeId = request.semanticEdgeId ?? options?.headers?.[MODEL_REQUEST_ID_HEADER];\n\t\tconst operationId = request.operationId ?? semanticEdgeId ?? randomUUID();\n\t\tconst operation = this.bindOperation(model, { ...request, semanticEdgeId }, operationId);\n\t\tconst release = this.retainWork(operation.binding);\n\t\tconst recover = this.providerRecoveryWait();\n\t\tlet failure: unknown;\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst settlement = await (await this.execute(operation, model, context, options, streamSimple)).settled;\n\t\t\t\t// Rejected execution/settlement, including local allowance exhaustion, never reaches recovery.\n\t\t\t\tif (!(await recover(settlement.message, options?.signal))) return settlement;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tfailure = error;\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tawait release(failure === undefined ? [] : [failure]);\n\t\t}\n\t}\n\n\tcomplete(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\trequest: InferenceRequestOptions,\n\t): Promise<AssistantMessage> {\n\t\tlet completion!: Promise<AssistantMessage>;\n\t\tcompletion = (async () => {\n\t\t\tconst settlement = this.work.providerRecoveryPolicy?.().enabled\n\t\t\t\t? await this.completeWithProviderRecovery(model, context, options, request)\n\t\t\t\t: await (await this.start(model, context, options, request)).settled;\n\t\t\tconst binding = this.work.compactionSettlements.get(settlement);\n\t\t\tthis.work.compactionSettlements.delete(settlement);\n\t\t\tif (binding) this.work.compactionCompletions.set(completion, binding);\n\t\t\tconst branchBinding = this.work.branchSettlements.get(settlement);\n\t\t\tthis.work.branchSettlements.delete(settlement);\n\t\t\tif (branchBinding) this.work.branchCompletions.set(completion, branchBinding);\n\t\t\tconst plannerBinding = this.work.plannerSettlements.get(settlement);\n\t\t\tthis.work.plannerSettlements.delete(settlement);\n\t\t\tif (plannerBinding) this.work.plannerCompletions.set(completion, plannerBinding);\n\t\t\treturn settlement.message;\n\t\t})();\n\t\treturn completion;\n\t}\n\n\tbindAuxiliaryStream(streamFn: StreamFn, request: InferenceRequestOptions): DisposableInferenceStream {\n\t\tconst captured = this.capture();\n\t\tconst release = captured.retainWork(captured.capturedSink!);\n\t\tconst recover = captured.providerRecoveryWait();\n\t\tconst stream = captured.bindStream(streamFn, request);\n\t\tlet disposal: Promise<void> | undefined;\n\t\treturn Object.assign(stream, {\n\t\t\trecoverProviderFailure: async (message: AssistantMessage, signal?: AbortSignal) => {\n\t\t\t\tif (!(await recover(message, signal))) return false;\n\t\t\t\tcaptured.prepareTurnRetry();\n\t\t\t\treturn true;\n\t\t\t},\n\t\t\tdispose: () => {\n\t\t\t\tdisposal ??= (async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait release();\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tawait captured.dispose();\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t\treturn disposal;\n\t\t\t},\n\t\t});\n\t}\n\n\tbindStream(streamFn: StreamFn, request: InferenceRequestOptions): AgentOwnedStreamFn {\n\t\tconst unwrapped = unwrapSemanticEdgeStreamFn(streamFn) as BoundStreamFn;\n\t\tconst inner = unwrapped[REQUEST_STREAM_BINDING]?.inner ?? unwrapped;\n\t\t// One Agent stream is serial. Keep only its latest binding for semantic retries.\n\t\t// A side question or child gets its own closure, not the parent's source binding.\n\t\tlet previous: BoundOperation | undefined;\n\t\tlet previousBody: string | undefined;\n\t\tconst wrapped: BoundStreamFn = async (model, context, options, streamContext) => {\n\t\t\tlet captured: InferenceCoordinator | undefined;\n\t\t\tif (streamContext !== undefined) {\n\t\t\t\tif (\n\t\t\t\t\t!(streamContext instanceof InferenceCoordinator) ||\n\t\t\t\t\tstreamContext.work !== this.work ||\n\t\t\t\t\t!streamContext.capturedSink\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(\"Native stream context is not a capture of this inference owner\");\n\t\t\t\tcaptured = streamContext;\n\t\t\t}\n\t\t\tconst executor = captured ?? this;\n\t\t\tconst semanticEdgeId = request.semanticEdgeId ?? options?.headers?.[MODEL_REQUEST_ID_HEADER];\n\t\t\t// Reuse the existing semantic body identity if its best-effort recorder is unavailable.\n\t\t\tconst body = semanticEdgeId ? undefined : hashTurnBody(model, context, options);\n\t\t\tconst retryId =\n\t\t\t\tthis.retryTurn && body !== undefined && body === previousBody ? previous?.metadata.operationId : undefined;\n\t\t\tthis.retryTurn = false;\n\t\t\tconst operationId = request.operationId ?? semanticEdgeId ?? retryId ?? randomUUID();\n\t\t\tpreviousBody = body;\n\t\t\tif (captured || previous?.metadata.operationId !== operationId) {\n\t\t\t\t// A semantic retry can reuse its operation ID, but compilation owns this exact source frontier.\n\t\t\t\tprevious = executor.bindOperation(model, { ...request, semanticEdgeId }, operationId);\n\t\t\t}\n\t\t\treturn (\n\t\t\t\tawait executor.execute(\n\t\t\t\t\tprevious,\n\t\t\t\t\tmodel,\n\t\t\t\t\tcontext,\n\t\t\t\t\toptions,\n\t\t\t\t\tinner,\n\t\t\t\t\tcaptured !== undefined && request.purpose === \"main\",\n\t\t\t\t)\n\t\t\t).events;\n\t\t};\n\t\twrapped[REQUEST_STREAM_BINDING] = { coordinator: this, inner };\n\t\treturn wrapped;\n\t}\n}\n\n/** Standalone helper embedding stays optional; native session callers always supply requests. */\nexport function completeInference(\n\trequests: InferenceCoordinator | undefined,\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions: SimpleStreamOptions | undefined,\n\trequest: InferenceRequestOptions,\n): Promise<AssistantMessage> {\n\treturn requests ? requests.complete(model, context, options, request) : completeSimple(model, context, options);\n}\n\nexport type DisposableInferenceStream = StreamFn & {\n\tdispose(): Promise<void>;\n\trecoverProviderFailure?(message: AssistantMessage, signal?: AbortSignal): Promise<boolean>;\n};\n\n/** Side questions keep the subject's writer, but get their own operation and purpose. */\nexport function bindAuxiliaryInferenceStream(\n\tstreamFn: StreamFn,\n\trequest: InferenceRequestOptions,\n): DisposableInferenceStream {\n\tconst inner = unwrapSemanticEdgeStreamFn(streamFn) as BoundStreamFn;\n\tconst binding = inner[REQUEST_STREAM_BINDING];\n\tif (binding) return binding.coordinator.bindAuxiliaryStream(binding.inner, request);\n\tconst stream: StreamFn = (model, context, options) => inner(model, context, options);\n\treturn Object.assign(stream, { dispose: async () => {} });\n}\n"]}
1
+ {"version":3,"file":"inference-coordinator.d.ts","sourceRoot":"","sources":["../../src/core/inference-coordinator.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,kCAAkC,CAAC;AACnG,OAAO,EACN,KAAK,GAAG,EACR,KAAK,gBAAgB,EAErB,KAAK,OAAO,EAKZ,KAAK,KAAK,EAGV,KAAK,yBAAyB,EAC9B,KAAK,mBAAmB,EAExB,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,KAAK,EACX,gBAAgB,EAEhB,+BAA+B,EAC/B,wCAAwC,EACxC,gCAAgC,EAGhC,eAAe,EACf,cAA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,GAAG,SAAS,EACxC,OAAO,EAAE,uBAAuB,GAC9B,OAAO,CAAC,gBAAgB,CAAC,CAE3B;AAED,MAAM,MAAM,yBAAyB,GAAG,QAAQ,GAAG;IAClD,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACzB,sBAAsB,CAAC,CAAC,OAAO,EAAE,gBAAgB,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CAC3F,CAAC;AAEF,yFAAyF;AACzF,wBAAgB,4BAA4B,CAC3C,QAAQ,EAAE,QAAQ,EAClB,OAAO,EAAE,uBAAuB,GAC9B,yBAAyB,CAM3B","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport type { AgentMessage, AgentOwnedStreamFn, StreamFn } from \"@ponythewhite/base-context-agent\";\nimport {\n\ttype Api,\n\ttype AssistantMessage,\n\tassertBuiltInAttemptSupport,\n\ttype Context,\n\tcompleteSimple,\n\tinvokeRequestMeasurement,\n\tisLocalFauxStream,\n\tisTransientProviderFailure,\n\ttype Model,\n\ttype ProviderAttemptObserver,\n\tRequestTokenBudget,\n\ttype RequestTokenBudgetOptions,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n} from \"@ponythewhite/base-context-ai\";\nimport type { AuthSourceToken } from \"./auth-storage.js\";\nimport type {\n\tBoundRequestSink,\n\tContextEpochEntryRef,\n\tNativeBranchRequestOutputWriter,\n\tNativeCompactionRequestOutputAssociation,\n\tNativePlannerRequestOutputWriter,\n\tNativeRequestMetadata,\n\tNativeRequestOutputWriter,\n\tRequestOwnerRef,\n\tRequestPurpose,\n\tResolvedModelContract,\n\tSourceSnapshotRef,\n} from \"./request-events.js\";\nimport {\n\ttype CapturedRequestViewBoundary,\n\tcaptureRequestViewBoundary,\n\tmatchesRequestView,\n\tprepareFixedRequestView,\n\ttype RequestViewCommit,\n\ttype RequestViewFixedPrepare,\n\ttype RequestViewValidate,\n\tselectRequestView,\n} from \"./request-view-selection.js\";\nimport { hashTurnBody, MODEL_REQUEST_ID_HEADER, unwrapSemanticEdgeStreamFn } from \"./semantic-edges.js\";\nimport type { SessionHistoryReadView } from \"./session-history-index.js\";\nimport {\n\tcaptureNativeBranchOutputSource,\n\tcaptureNativeCompactionOutputSource,\n\tcaptureNativePlannerOutputSource,\n\tcaptureNativeRequestOutputSource,\n} from \"./session-manager.js\";\n\nexport interface InferenceRequestOptions {\n\treadonly purpose: RequestPurpose;\n\treadonly purposeDetail?: string;\n\treadonly operationId?: string;\n\treadonly parentOperationId?: string;\n\treadonly semanticEdgeId?: string;\n}\n\nexport interface InferenceSettlement {\n\treadonly message: AssistantMessage;\n\treadonly operationId: string;\n\treadonly attemptIds: readonly string[];\n\t/** Reporting is not a guarantee about an opaque adapter's hidden retries. */\n\treadonly physicalCoverage: \"reported\" | \"unestablished\" | \"local-simulation\";\n}\n\n/** Private completion identity carries this actual source, never descriptive sink labels. */\nexport interface NativeCompactionOutputBinding {\n\treadonly sink: BoundRequestSink;\n\treadonly output: NativeCompactionRequestOutputAssociation;\n}\n\ninterface NativeBranchOutputBinding {\n\treadonly owner: InferenceCoordinator;\n\treadonly write: NativeBranchRequestOutputWriter;\n}\n\ninterface NativePlannerOutputBinding {\n\treadonly owner: InferenceCoordinator;\n\treadonly write: NativePlannerRequestOutputWriter;\n}\n\nexport interface InferenceRun {\n\treadonly events: Awaited<ReturnType<StreamFn>>;\n\treadonly settled: Promise<InferenceSettlement>;\n}\n\nexport interface SessionRuntimeServices {\n\treadonly requests: InferenceCoordinator;\n}\n\ninterface ProviderRecoveryPolicy {\n\tenabled: boolean;\n\tbaseDelayMs: number;\n\tmaxRetryDelayMs: number;\n}\n\ninterface SinkUse {\n\treadonly sink: BoundRequestSink;\n\tactiveUsers: number;\n\tcaptures: number;\n\trelease?: Promise<void>;\n}\n\ninterface BoundOperation {\n\treadonly binding: SinkUse;\n\treadonly owner: Omit<RequestOwnerRef, \"sessionId\">;\n\treadonly metadata: Omit<NativeRequestMetadata, \"source\" | \"owner\" | \"contextEpoch\">;\n}\n\nconst REQUEST_STREAM_BINDING = Symbol(\"base-context.request-stream-binding\");\n/** Internal AgentSession built-in compaction entry, not a public inference option. */\nexport const captureNativeCompactionRequests = Symbol(\"base-context.native-compaction-requests\");\n/** Internal AgentSession built-in branch-summary invocation, never inherited by generic capture. */\nexport const captureNativeBranchRequests = Symbol(\"base-context.native-branch-requests\");\n/** Internal native AgentSession planner capture, never inherited by generic capture. */\nexport const captureNativePlannerRequests = Symbol(\"base-context.native-planner-requests\");\n/** Internal native AgentSession reviewer invocation. */\nexport const captureNativeReviewerRequests = Symbol(\"base-context.native-reviewer-requests\");\ninterface StreamBinding {\n\treadonly coordinator: InferenceCoordinator;\n\treadonly inner: StreamFn;\n}\ntype BoundStreamFn = AgentOwnedStreamFn & { [REQUEST_STREAM_BINDING]?: StreamBinding };\n\nfunction modelContract(model: Model<Api>): ResolvedModelContract {\n\treturn {\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tprofile: { id: \"native-default\", status: \"unvalidated\" },\n\t\tpricing: {\n\t\t\tstatus: \"unvalidated\",\n\t\t\tcurrency: \"USD\",\n\t\t\tunit: \"million-tokens\",\n\t\t\tcatalogRates: {\n\t\t\t\tinput: model.cost.input,\n\t\t\t\toutput: model.cost.output,\n\t\t\t\tcacheRead: model.cost.cacheRead,\n\t\t\t\tcacheWrite: model.cost.cacheWrite,\n\t\t\t},\n\t\t},\n\t};\n}\n\nconst nativeStreamFunctions = new WeakSet<StreamFn>();\nconst nativeAuthSources = new WeakMap<AssistantMessage, AuthSourceToken>();\n\n/** Consume the credential source resolved for this exact native request. Never persisted or sent to providers. */\nexport function takeNativeInferenceAuthSource(message: AssistantMessage): AuthSourceToken | undefined {\n\tconst source = nativeAuthSources.get(message);\n\tnativeAuthSources.delete(message);\n\treturn source;\n}\n\n/** Internal SDK auth/options resolver; transport stays the known instrumented AI dispatcher. */\nexport function createNativeInferenceStream(\n\tresolveOptions: (\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t) => Promise<SimpleStreamOptions & { authSourceToken?: AuthSourceToken }>,\n): StreamFn {\n\tconst dispatch: StreamFn = async (model, context, options) => {\n\t\tconst { authSourceToken, ...resolved } = await resolveOptions(model, context, options);\n\t\tconst events = streamSimple(model, context, {\n\t\t\t...resolved,\n\t\t\tsignal: options?.signal,\n\t\t\tattempts: options?.attempts,\n\t\t\trequireProviderAttempts: true,\n\t\t});\n\t\tif (authSourceToken) {\n\t\t\tconst source = { ...authSourceToken };\n\t\t\tconst result = events.result().then((message) => {\n\t\t\t\tnativeAuthSources.set(message, source);\n\t\t\t\treturn message;\n\t\t\t});\n\t\t\tevents.result = () => result;\n\t\t}\n\t\treturn events;\n\t};\n\tnativeStreamFunctions.add(dispatch);\n\treturn dispatch;\n}\n\n/** Routes physical observations to the source writer. It owns no receipt store. */\nexport class InferenceCoordinator {\n\t#nativeCompactionOutput = false;\n\t#nativeBranchOutput = false;\n\t#nativePlannerOutput = false;\n\t#auxiliaryAttempts?: { remaining: number };\n\tprivate retryTurn = false;\n\tprivate requestViewBoundary?: CapturedRequestViewBoundary;\n\tprivate active = new Set<Promise<void>>();\n\tprivate capturedSink?: SinkUse;\n\tprivate captureReserved = false;\n\tprivate finishCapturePending?: () => void;\n\tprivate disposed = false;\n\tprivate disposal?: Promise<void>;\n\tprivate work = {\n\t\tpending: new Set<Promise<void>>(),\n\t\tsinks: new WeakMap<BoundRequestSink, SinkUse>(),\n\t\tmainOutputs: new WeakMap<AssistantMessage, NativeRequestOutputWriter>(),\n\t\tcompactionSettlements: new WeakMap<InferenceSettlement, NativeCompactionOutputBinding>(),\n\t\tcompactionCompletions: new WeakMap<Promise<AssistantMessage>, NativeCompactionOutputBinding>(),\n\t\tbranchSettlements: new WeakMap<InferenceSettlement, NativeBranchOutputBinding>(),\n\t\tbranchCompletions: new WeakMap<Promise<AssistantMessage>, NativeBranchOutputBinding>(),\n\t\tplannerSettlements: new WeakMap<InferenceSettlement, NativePlannerOutputBinding>(),\n\t\tplannerCompletions: new WeakMap<Promise<AssistantMessage>, NativePlannerOutputBinding>(),\n\t\tlisteners: new Set<() => void>(),\n\t\tadmissionOpen: true,\n\t\tcancellation: new AbortController(),\n\t\tbudget: undefined as RequestTokenBudget | undefined,\n\t\tbudgetMode: undefined as RequestTokenBudgetOptions[\"mode\"] | undefined,\n\t\tproviderRecoveryPolicy: undefined as (() => ProviderRecoveryPolicy) | undefined,\n\t};\n\n\tsetProviderRecoveryPolicy(policy: () => ProviderRecoveryPolicy): void {\n\t\tthis.work.providerRecoveryPolicy = policy;\n\t}\n\n\tget hasPending(): boolean {\n\t\treturn this.work.pending.size > 0;\n\t}\n\tget pendingCount(): number {\n\t\treturn this.work.pending.size;\n\t}\n\n\tonActivityChange(listener: () => void): () => void {\n\t\tthis.work.listeners.add(listener);\n\t\treturn () => this.work.listeners.delete(listener);\n\t}\n\n\tprivate notifyActivity(): void {\n\t\t// Observers can wake an existing owner, but cannot own request settlement.\n\t\tfor (const listener of this.work.listeners) {\n\t\t\ttry {\n\t\t\t\tlistener();\n\t\t\t} catch {\n\t\t\t\t/* Notification is not execution. */\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Consume only this owner's real returned object. Labels and replacement messages remain unassociated. */\n\tappendMainOutput(message: AssistantMessage, owner: object): Promise<string | undefined> | undefined {\n\t\tconst write = this.work.mainOutputs.get(message);\n\t\tthis.work.mainOutputs.delete(message);\n\t\treturn write?.(owner, message);\n\t}\n\n\t/** Opt this native invocation into output association; ordinary captures do not inherit that authority. */\n\t[captureNativeCompactionRequests](): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this);\n\t\tcaptured.#nativeCompactionOutput = true;\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 4 };\n\t\treturn captured;\n\t}\n\n\t[captureNativeBranchRequests](sink: BoundRequestSink): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this, sink);\n\t\tcaptured.#nativeBranchOutput = true;\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 2 };\n\t\treturn captured;\n\t}\n\n\ttakeBranchOutput(completion: Promise<AssistantMessage>): NativeBranchRequestOutputWriter | undefined {\n\t\tconst binding = this.work.branchCompletions.get(completion);\n\t\tthis.work.branchCompletions.delete(completion);\n\t\tif (!binding || !this.#nativeBranchOutput || binding.owner !== this) return undefined;\n\t\treturn binding.write;\n\t}\n\n\t[captureNativePlannerRequests](sink: BoundRequestSink): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this, sink);\n\t\tcaptured.#nativePlannerOutput = true;\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 2 };\n\t\treturn captured;\n\t}\n\n\t[captureNativeReviewerRequests](): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this);\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 2 };\n\t\treturn captured;\n\t}\n\n\ttakePlannerOutput(completion: Promise<AssistantMessage>): NativePlannerRequestOutputWriter | undefined {\n\t\tconst binding = this.work.plannerCompletions.get(completion);\n\t\tthis.work.plannerCompletions.delete(completion);\n\t\tif (!binding || !this.#nativePlannerOutput || binding.owner !== this) return undefined;\n\t\treturn binding.write;\n\t}\n\n\t/** Only the original completion promise and captured source can supply a projected-output link. */\n\ttakeCompactionOutput(completion: Promise<AssistantMessage>): NativeCompactionOutputBinding | undefined {\n\t\tconst binding = this.work.compactionCompletions.get(completion);\n\t\tthis.work.compactionCompletions.delete(completion);\n\t\treturn binding?.sink === this.capturedSink?.sink ? binding : undefined;\n\t}\n\n\t/** Owner teardown stops new sends, but never suppresses an admitted request's settlement. */\n\tstopAdmission(): void {\n\t\tthis.work.admissionOpen = false;\n\t\tthis.work.cancellation.abort();\n\t\tthis.notifyActivity();\n\t}\n\n\tasync waitForIdle(): Promise<void> {\n\t\twhile (this.work.pending.size > 0) await Promise.all([...this.work.pending]);\n\t}\n\n\tprepareTurnRetry(): void {\n\t\tthis.retryTurn = true;\n\t}\n\tclearTurnRetry(): void {\n\t\tthis.retryTurn = false;\n\t}\n\n\tconstructor(\n\t\tprivate readonly bindSink: () => BoundRequestSink,\n\t\tprivate readonly owner: () => Omit<RequestOwnerRef, \"sessionId\"> = () => ({}),\n\t\trequestTokenBudget?: RequestTokenBudgetOptions,\n\t) {\n\t\tif (requestTokenBudget) {\n\t\t\tthis.work.budget = new RequestTokenBudget(requestTokenBudget);\n\t\t\tthis.work.budgetMode = requestTokenBudget.mode;\n\t\t}\n\t}\n\n\t/** Copy the configured policy, not this owner's learned request observations. */\n\tgetRequestTokenBudgetOptions(): RequestTokenBudgetOptions | undefined {\n\t\treturn this.work.budget?.getOptions();\n\t}\n\n\tprivate assertAdmission(): void {\n\t\tif (this.disposed || !this.work.admissionOpen) throw new Error(\"Inference owner is closing\");\n\t}\n\n\tprivate sinkUse(sink: BoundRequestSink): SinkUse {\n\t\tlet binding = this.work.sinks.get(sink);\n\t\tif (!binding) {\n\t\t\tbinding = { sink, activeUsers: 0, captures: 0 };\n\t\t\tthis.work.sinks.set(sink, binding);\n\t\t}\n\t\treturn binding;\n\t}\n\n\tprivate releaseCapture(): void {\n\t\tif (this.captureReserved && this.capturedSink) {\n\t\t\tthis.captureReserved = false;\n\t\t\tthis.capturedSink.captures--;\n\t\t}\n\t}\n\n\t/** Capture an auxiliary operation's subject before asynchronous auth or UI work. */\n\tcapture(sink?: BoundRequestSink): InferenceCoordinator {\n\t\tthis.assertAdmission();\n\t\tconst owner = Object.freeze({ ...this.owner() });\n\t\tconst binding = this.sinkUse(sink ?? this.bindSink());\n\t\tbinding.sink.retain();\n\t\tbinding.release = undefined;\n\t\tbinding.captures++;\n\t\tconst captured = new InferenceCoordinator(\n\t\t\t() => binding.sink,\n\t\t\t() => owner,\n\t\t);\n\t\tcaptured.work = this.work;\n\t\t// Nested captures share the invocation's allowance, not its native output authority.\n\t\tcaptured.#auxiliaryAttempts = this.#auxiliaryAttempts;\n\t\tcaptured.capturedSink = binding;\n\t\tcaptured.captureReserved = true;\n\t\tlet release!: () => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\trelease = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tcaptured.finishCapturePending = () => {\n\t\t\tthis.work.pending.delete(pending);\n\t\t\tcaptured.finishCapturePending = undefined;\n\t\t\trelease();\n\t\t\tthis.notifyActivity();\n\t\t};\n\t\tthis.notifyActivity();\n\t\treturn captured;\n\t}\n\n\t/** Explicit Root-owned epoch boundary, on this same captured MAIN source only. */\n\tbindRequestViewBoundary(\n\t\tmessages: readonly AgentMessage[],\n\t\tcommit: RequestViewCommit,\n\t\tvalidate?: RequestViewValidate,\n\t\tfixedPrepare?: RequestViewFixedPrepare,\n\t): void {\n\t\tthis.assertAdmission();\n\t\tif (!this.capturedSink) throw new Error(\"Request view boundary requires a captured inference owner\");\n\t\tif (this.requestViewBoundary) throw new Error(\"Request view boundary is already bound\");\n\t\tthis.requestViewBoundary = captureRequestViewBoundary(messages, commit, validate, fixedPrepare);\n\t}\n\n\t/** Read through an explicit capture, never by recapturing the mutable current session. */\n\tasync readHistory<T>(read: (view: SessionHistoryReadView) => Promise<T>): Promise<T> {\n\t\tthis.assertAdmission();\n\t\tconst sink = this.capturedSink?.sink;\n\t\tif (!sink?.readHistory) throw new Error(\"Captured canonical history is unavailable\");\n\t\tlet finish!: () => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\tfinish = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tthis.active.add(pending);\n\t\tthis.notifyActivity();\n\t\ttry {\n\t\t\treturn await sink.readHistory(read);\n\t\t} finally {\n\t\t\tthis.active.delete(pending);\n\t\t\tthis.work.pending.delete(pending);\n\t\t\tfinish();\n\t\t\tthis.notifyActivity();\n\t\t}\n\t}\n\n\t/** Release an unused capture, or join this capture's admitted requests. */\n\tdispose(): Promise<void> {\n\t\tthis.disposed = true;\n\t\tthis.disposal ??= (async () => {\n\t\t\tthis.releaseCapture();\n\t\t\ttry {\n\t\t\t\tawait Promise.all([...this.active]);\n\t\t\t\tif (this.capturedSink) await this.finishSink(this.capturedSink, [], false, []);\n\t\t\t} finally {\n\t\t\t\tthis.finishCapturePending?.();\n\t\t\t}\n\t\t})();\n\t\treturn this.disposal;\n\t}\n\n\tprivate bindOperation(model: Model<Api>, request: InferenceRequestOptions, operationId: string): BoundOperation {\n\t\tthis.assertAdmission();\n\t\tconst owner = Object.freeze({ ...this.owner() });\n\t\tconst metadata = Object.freeze({\n\t\t\toperationId,\n\t\t\tparentOperationId: request.parentOperationId,\n\t\t\tsemanticEdgeId: request.semanticEdgeId,\n\t\t\tpurpose: request.purpose,\n\t\t\tpurposeDetail: request.purposeDetail,\n\t\t\tmodelContract: modelContract(model),\n\t\t});\n\t\treturn { binding: this.sinkUse(this.bindSink()), owner, metadata };\n\t}\n\n\tprivate async finishSink(\n\t\tbinding: SinkUse,\n\t\twrites: readonly Promise<void>[],\n\t\tactiveUser: boolean,\n\t\tfailures: unknown[],\n\t): Promise<void> {\n\t\tconst results = await Promise.allSettled([binding.sink.source, ...writes]);\n\t\tfor (const result of results) {\n\t\t\tif (result.status === \"rejected\") failures.push(result.reason);\n\t\t}\n\t\tif (activeUser) binding.activeUsers--;\n\t\ttry {\n\t\t\tif (binding.activeUsers === 0 && binding.captures === 0) {\n\t\t\t\tbinding.release ??= binding.sink.release();\n\t\t\t\tawait binding.release;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tfailures.push(error);\n\t\t}\n\t\tconst distinct = [...new Set(failures)];\n\t\tif (distinct.length === 1) throw distinct[0];\n\t\tif (distinct.length > 1) throw new AggregateError(distinct, \"Inference request or source cleanup failed\");\n\t}\n\n\t/** Hold one logical operation through settled sends and recovery delays. */\n\tprivate retainWork(binding: SinkUse): (failures?: unknown[]) => Promise<void> {\n\t\tthis.assertAdmission();\n\t\tbinding.sink.retain();\n\t\tbinding.release = undefined;\n\t\tbinding.captures++;\n\t\tlet finish!: () => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\tfinish = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tthis.active.add(pending);\n\t\tthis.notifyActivity();\n\t\tlet release: Promise<void> | undefined;\n\t\treturn (failures = []) => {\n\t\t\trelease ??= (async () => {\n\t\t\t\tbinding.captures--;\n\t\t\t\ttry {\n\t\t\t\t\tawait this.finishSink(binding, [], false, failures);\n\t\t\t\t} finally {\n\t\t\t\t\tthis.active.delete(pending);\n\t\t\t\t\tthis.work.pending.delete(pending);\n\t\t\t\t\tfinish();\n\t\t\t\t\tthis.notifyActivity();\n\t\t\t\t}\n\t\t\t})();\n\t\t\treturn release;\n\t\t};\n\t}\n\n\tprivate providerRecoveryWait(): (message: AssistantMessage, signal?: AbortSignal) => Promise<boolean> {\n\t\tlet nextDelayMs: number | undefined;\n\t\treturn async (message, callerSignal) => {\n\t\t\tconst policy = this.work.providerRecoveryPolicy?.();\n\t\t\tif (!policy?.enabled || !isTransientProviderFailure(message)) return false;\n\t\t\tthis.assertAdmission();\n\t\t\tconst signal = callerSignal\n\t\t\t\t? AbortSignal.any([callerSignal, this.work.cancellation.signal])\n\t\t\t\t: this.work.cancellation.signal;\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst delayMs = Math.min(nextDelayMs ?? policy.baseDelayMs, policy.maxRetryDelayMs);\n\t\t\tawait delay(delayMs, undefined, { signal });\n\t\t\tsignal.throwIfAborted();\n\t\t\tthis.assertAdmission();\n\t\t\tnextDelayMs = Math.min(delayMs * 2, policy.maxRetryDelayMs);\n\t\t\treturn this.work.providerRecoveryPolicy?.().enabled === true;\n\t\t};\n\t}\n\n\tprivate async execute(\n\t\toperation: BoundOperation,\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\tsend: StreamFn,\n\t\tbindMainOutput = false,\n\t): Promise<InferenceRun> {\n\t\tconst outputSource = bindMainOutput ? captureNativeRequestOutputSource(operation.binding.sink) : undefined;\n\t\tconst part =\n\t\t\toperation.metadata.purpose === \"summary\"\n\t\t\t\t? operation.metadata.purposeDetail === \"compaction\"\n\t\t\t\t\t? \"history\"\n\t\t\t\t\t: operation.metadata.purposeDetail === \"compaction-turn-prefix\"\n\t\t\t\t\t\t? \"turn-prefix\"\n\t\t\t\t\t\t: undefined\n\t\t\t\t: undefined;\n\t\tconst compactionSource =\n\t\t\tthis.#nativeCompactionOutput && part && this.capturedSink?.sink === operation.binding.sink\n\t\t\t\t? captureNativeCompactionOutputSource(operation.binding.sink)\n\t\t\t\t: undefined;\n\t\tconst branchSource =\n\t\t\tthis.#nativeBranchOutput &&\n\t\t\toperation.metadata.purpose === \"summary\" &&\n\t\t\toperation.metadata.purposeDetail === \"branch\" &&\n\t\t\tthis.capturedSink?.sink === operation.binding.sink\n\t\t\t\t? captureNativeBranchOutputSource(operation.binding.sink)\n\t\t\t\t: undefined;\n\t\tconst plannerSource =\n\t\t\tthis.#nativePlannerOutput &&\n\t\t\toperation.metadata.purpose === \"refine\" &&\n\t\t\toperation.metadata.purposeDetail === \"plan\" &&\n\t\t\tthis.capturedSink?.sink === operation.binding.sink\n\t\t\t\t? captureNativePlannerOutputSource(operation.binding.sink)\n\t\t\t\t: undefined;\n\t\tlet outputSourceRef: SourceSnapshotRef | undefined;\n\t\tlet release!: (completion?: PromiseLike<void>) => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\trelease = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tthis.active.add(pending);\n\t\tthis.notifyActivity();\n\t\tconst finish = () => {\n\t\t\tthis.work.pending.delete(pending);\n\t\t\tthis.active.delete(pending);\n\t\t\tthis.notifyActivity();\n\t\t};\n\t\tconst admittedAttempts: Array<{ attemptId: string; contextEpoch?: ContextEpochEntryRef }> = [];\n\t\tconst receiptWrites: Promise<void>[] = [];\n\t\tlet activeUser = false;\n\t\tlet localSimulation = false;\n\t\tlet budgetFailure: unknown;\n\t\tconst settle = async (result: Promise<AssistantMessage>): Promise<InferenceSettlement> => {\n\t\t\tconst failures: unknown[] = [];\n\t\t\tlet message: AssistantMessage | undefined;\n\t\t\ttry {\n\t\t\t\tmessage = await result;\n\t\t\t} catch (error) {\n\t\t\t\tfailures.push(error);\n\t\t\t}\n\t\t\tif (budgetFailure !== undefined && !failures.includes(budgetFailure)) failures.push(budgetFailure);\n\t\t\tawait this.finishSink(operation.binding, receiptWrites, activeUser, failures);\n\t\t\tif (message && outputSource && outputSourceRef) {\n\t\t\t\tconst write = outputSource({\n\t\t\t\t\toperationId: operation.metadata.operationId,\n\t\t\t\t\tattemptIds: admittedAttempts.map(({ attemptId }) => attemptId),\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (write) this.work.mainOutputs.set(message, write);\n\t\t\t}\n\t\t\tconst settlement: InferenceSettlement = {\n\t\t\t\tmessage: message!,\n\t\t\t\toperationId: operation.metadata.operationId,\n\t\t\t\tattemptIds: admittedAttempts.map(({ attemptId }) => attemptId),\n\t\t\t\tphysicalCoverage: admittedAttempts.length\n\t\t\t\t\t? \"reported\"\n\t\t\t\t\t: localSimulation\n\t\t\t\t\t\t? \"local-simulation\"\n\t\t\t\t\t\t: \"unestablished\",\n\t\t\t};\n\t\t\tif (part && compactionSource && outputSourceRef) {\n\t\t\t\tconst output = compactionSource({\n\t\t\t\t\toperationId: settlement.operationId,\n\t\t\t\t\tattemptIds: settlement.attemptIds,\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (output)\n\t\t\t\t\tthis.work.compactionSettlements.set(settlement, {\n\t\t\t\t\t\tsink: operation.binding.sink,\n\t\t\t\t\t\toutput: { ...output, part },\n\t\t\t\t\t});\n\t\t\t}\n\t\t\tif (branchSource && outputSourceRef) {\n\t\t\t\tconst write = branchSource({\n\t\t\t\t\toperationId: settlement.operationId,\n\t\t\t\t\tattemptIds: settlement.attemptIds,\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (write) this.work.branchSettlements.set(settlement, { owner: this, write });\n\t\t\t}\n\t\t\tif (plannerSource && outputSourceRef) {\n\t\t\t\tconst write = plannerSource({\n\t\t\t\t\toperationId: settlement.operationId,\n\t\t\t\t\tattemptIds: settlement.attemptIds,\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (write) this.work.plannerSettlements.set(settlement, { owner: this, write });\n\t\t\t}\n\t\t\treturn settlement;\n\t\t};\n\t\ttry {\n\t\t\tthis.assertAdmission();\n\t\t\toperation.binding.sink.retain();\n\t\t\toperation.binding.release = undefined;\n\t\t\toperation.binding.activeUsers++;\n\t\t\tactiveUser = true;\n\t\t\tthis.releaseCapture();\n\t\t\tthis.finishCapturePending?.();\n\t\t\t// Capture the opted-in budgeted invocation before source/auth waits. Callbacks and signals stay live handles.\n\t\t\tif (this.work.budget || (this.requestViewBoundary && operation.metadata.purpose === \"main\")) {\n\t\t\t\tmodel = structuredClone(model);\n\t\t\t\t// Agent tool objects also carry live executors. Snapshot only the native Tool definition.\n\t\t\t\tcontext = structuredClone({\n\t\t\t\t\t...context,\n\t\t\t\t\t...(context.tools\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\ttools: context.tools.map(({ name, description, parameters }) => ({\n\t\t\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t\t\tdescription,\n\t\t\t\t\t\t\t\t\tparameters,\n\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t});\n\t\t\t\toptions = options\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t...options,\n\t\t\t\t\t\t\theaders: options.headers ? { ...options.headers } : undefined,\n\t\t\t\t\t\t\tthinkingBudgets: options.thinkingBudgets ? { ...options.thinkingBudgets } : undefined,\n\t\t\t\t\t\t\tmetadata: options.metadata ? structuredClone(options.metadata) : undefined,\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined;\n\t\t\t}\n\t\t\tconst source = Object.freeze({ ...(await operation.binding.sink.source) });\n\t\t\toutputSourceRef = source;\n\t\t\tconst metadata: NativeRequestMetadata = {\n\t\t\t\t...operation.metadata,\n\t\t\t\tsource,\n\t\t\t\towner: Object.freeze({ ...operation.owner, sessionId: source.sessionId }),\n\t\t\t};\n\t\t\tif (send !== streamSimple && !nativeStreamFunctions.has(send)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Native inference cannot admit a custom or proxy StreamFn with unestablished physical-attempt coverage. Use the SDK's instrumented built-in API route instead.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tassertBuiltInAttemptSupport(model.api);\n\t\t\tif (!this.work.admissionOpen) throw new Error(\"Inference owner is closing\");\n\t\t\tconst parentBudget = this.work.budget;\n\t\t\tconst boundary = operation.metadata.purpose === \"main\" ? this.requestViewBoundary : undefined;\n\t\t\tconst budget = boundary ? parentBudget?.capture() : parentBudget;\n\t\t\tlet measuredForAdmission = false;\n\t\t\tconst measureRequest: ProviderAttemptObserver[\"measureRequest\"] =\n\t\t\t\tbudget || boundary?.validate\n\t\t\t\t\t? (representation) => {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tconst assessment = budget?.measure(representation);\n\t\t\t\t\t\t\t\tboundary?.validate?.(representation, assessment);\n\t\t\t\t\t\t\t\tif (budget && assessment) budget.assert(assessment);\n\t\t\t\t\t\t\t\tmeasuredForAdmission = true;\n\t\t\t\t\t\t\t\treturn assessment;\n\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\tbudgetFailure = error;\n\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined;\n\t\t\tconst canSelect =\n\t\t\t\t(budget || boundary?.fixedPrepare) && boundary && matchesRequestView(boundary, source, context);\n\t\t\tconst requiredPublic = Boolean(boundary?.pendingPublicMessageGroups?.length);\n\t\t\tif (requiredPublic && (!canSelect || boundary?.fixedPrepare))\n\t\t\t\tthrow new Error(\"Tool continuation requires a selectable native public request boundary\");\n\t\t\tlet publicAccepted = false;\n\t\t\tlet selectedContextEpoch: ContextEpochEntryRef | undefined;\n\t\t\tconst attempts: ProviderAttemptObserver = {\n\t\t\t\t...(requiredPublic\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tpendingPublicMessageGroups: boundary!.providerPendingPublicMessageGroups!.map((group) => [\n\t\t\t\t\t\t\t\t...group,\n\t\t\t\t\t\t\t]),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(measureRequest ? { measureRequest } : {}),\n\t\t\t\t...(canSelect\n\t\t\t\t\t? ({\n\t\t\t\t\t\t\tprepareRequest: async (representation, projection) => {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tselectedContextEpoch = undefined;\n\t\t\t\t\t\t\t\t\tpublicAccepted = false;\n\t\t\t\t\t\t\t\t\tif (JSON.parse(representation.body!).model !== model.id) return;\n\t\t\t\t\t\t\t\t\tif (boundary!.fixedPrepare) {\n\t\t\t\t\t\t\t\t\t\tconst assessment = budget?.measure(representation);\n\t\t\t\t\t\t\t\t\t\tif (budget && assessment) budget.assert(assessment);\n\t\t\t\t\t\t\t\t\t\tconst accepted = await prepareFixedRequestView(\n\t\t\t\t\t\t\t\t\t\t\tboundary!,\n\t\t\t\t\t\t\t\t\t\t\trepresentation,\n\t\t\t\t\t\t\t\t\t\t\tprojection,\n\t\t\t\t\t\t\t\t\t\t\tassessment,\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\tif (accepted) selectedContextEpoch = Object.freeze({ ...accepted });\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treturn await selectRequestView(\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t...boundary!,\n\t\t\t\t\t\t\t\t\t\t\tcommit: async (candidate) => {\n\t\t\t\t\t\t\t\t\t\t\t\tconst accepted = await boundary!.commit(candidate);\n\t\t\t\t\t\t\t\t\t\t\t\tif (accepted) selectedContextEpoch = Object.freeze({ ...accepted });\n\t\t\t\t\t\t\t\t\t\t\t\tpublicAccepted = Boolean(\n\t\t\t\t\t\t\t\t\t\t\t\t\taccepted &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcandidate.publicMessages &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcandidate.projection.publicWindow &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t!candidate.projection.pendingPublicMessageGroups?.length,\n\t\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\t\treturn accepted || undefined;\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\trepresentation,\n\t\t\t\t\t\t\t\t\t\tprojection,\n\t\t\t\t\t\t\t\t\t\tbudget!,\n\t\t\t\t\t\t\t\t\t\tthis.work.budgetMode === \"enforce\",\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\t\tbudgetFailure = error;\n\t\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t} satisfies Pick<ProviderAttemptObserver, \"prepareRequest\">)\n\t\t\t\t\t: {}),\n\t\t\t\tadmit: async (descriptor) => {\n\t\t\t\t\tif (requiredPublic && !publicAccepted)\n\t\t\t\t\t\tthrow new Error(\"Unaccepted tool continuation cannot enter native transport\");\n\t\t\t\t\tif (!this.work.admissionOpen) throw new Error(\"Inference owner is closing\");\n\t\t\t\t\t// An adapter without a serializer meter must not bypass an enforced budget.\n\t\t\t\t\tif (measureRequest && !descriptor.requestBudget && (budget || !measuredForAdmission)) {\n\t\t\t\t\t\tconst assessment = invokeRequestMeasurement(attempts, {\n\t\t\t\t\t\t\tapi: descriptor.api,\n\t\t\t\t\t\t\tprovider: descriptor.provider,\n\t\t\t\t\t\t\turl: \"\",\n\t\t\t\t\t\t\tbody: undefined,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (assessment) descriptor = { ...descriptor, requestBudget: assessment };\n\t\t\t\t\t}\n\t\t\t\t\tmeasuredForAdmission = false;\n\t\t\t\t\tif (this.#auxiliaryAttempts) {\n\t\t\t\t\t\tif (this.#auxiliaryAttempts.remaining === 0) {\n\t\t\t\t\t\t\tbudgetFailure ??= new Error(\"Native auxiliary operation attempt limit exhausted\");\n\t\t\t\t\t\t\tthrow budgetFailure;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Reserve synchronously before persistence; failures and cancellation do not refund it.\n\t\t\t\t\t\tthis.#auxiliaryAttempts.remaining--;\n\t\t\t\t\t}\n\t\t\t\t\tconst attemptId = randomUUID();\n\t\t\t\t\tconst contextEpoch = selectedContextEpoch ? Object.freeze({ ...selectedContextEpoch }) : undefined;\n\t\t\t\t\tconst write = operation.binding.sink.persist({\n\t\t\t\t\t\t...metadata,\n\t\t\t\t\t\t...(contextEpoch ? { contextEpoch } : {}),\n\t\t\t\t\t\ttype: \"attempt_admitted\",\n\t\t\t\t\t\tattemptId,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\tdescriptor,\n\t\t\t\t\t});\n\t\t\t\t\treceiptWrites.push(write);\n\t\t\t\t\tawait write;\n\t\t\t\t\tadmittedAttempts.push({ attemptId, contextEpoch });\n\t\t\t\t\treturn attemptId;\n\t\t\t\t},\n\t\t\t\tsettle: async (receipt) => {\n\t\t\t\t\tconst contextEpoch = admittedAttempts.find(\n\t\t\t\t\t\t(attempt) => attempt.attemptId === receipt.attemptId,\n\t\t\t\t\t)?.contextEpoch;\n\t\t\t\t\tconst write = operation.binding.sink.persist({\n\t\t\t\t\t\t...metadata,\n\t\t\t\t\t\t...(contextEpoch ? { contextEpoch } : {}),\n\t\t\t\t\t\ttype: \"attempt_settled\",\n\t\t\t\t\t\tattemptId: receipt.attemptId,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\treceipt,\n\t\t\t\t\t});\n\t\t\t\t\treceiptWrites.push(write);\n\t\t\t\t\tawait write;\n\t\t\t\t\tparentBudget?.observe(receipt);\n\t\t\t\t},\n\t\t\t};\n\t\t\tconst signal = options?.signal\n\t\t\t\t? AbortSignal.any([options.signal, this.work.cancellation.signal])\n\t\t\t\t: this.work.cancellation.signal;\n\t\t\tconst events = await send(model, context, { ...options, signal, attempts, requireProviderAttempts: true });\n\t\t\tlocalSimulation = isLocalFauxStream(events);\n\t\t\tconst settled = settle(events.result());\n\t\t\tevents.result = async () => (await settled).message;\n\t\t\t// Idle tracking observes rejection; callers still receive it through settled/result().\n\t\t\trelease(settled.then(finish, finish));\n\t\t\treturn { events, settled };\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tawait settle(Promise.reject(error));\n\t\t\t} finally {\n\t\t\t\tfinish();\n\t\t\t\trelease();\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync start(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\trequest: InferenceRequestOptions,\n\t): Promise<InferenceRun> {\n\t\tconst semanticEdgeId = request.semanticEdgeId ?? options?.headers?.[MODEL_REQUEST_ID_HEADER];\n\t\tconst operationId = request.operationId ?? semanticEdgeId ?? randomUUID();\n\t\treturn this.execute(\n\t\t\tthis.bindOperation(model, { ...request, semanticEdgeId }, operationId),\n\t\t\tmodel,\n\t\t\tcontext,\n\t\t\toptions,\n\t\t\tstreamSimple,\n\t\t);\n\t}\n\n\tprivate async completeWithProviderRecovery(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\trequest: InferenceRequestOptions,\n\t): Promise<InferenceSettlement> {\n\t\t// Retry the same request, not a caller's later mutable inputs. Keep callbacks/signals live.\n\t\tmodel = structuredClone(model);\n\t\tcontext = structuredClone({\n\t\t\t...context,\n\t\t\t...(context.tools\n\t\t\t\t? { tools: context.tools.map(({ name, description, parameters }) => ({ name, description, parameters })) }\n\t\t\t\t: {}),\n\t\t});\n\t\toptions = options\n\t\t\t? {\n\t\t\t\t\t...options,\n\t\t\t\t\theaders: options.headers ? { ...options.headers } : undefined,\n\t\t\t\t\tthinkingBudgets: options.thinkingBudgets ? { ...options.thinkingBudgets } : undefined,\n\t\t\t\t\tmetadata: options.metadata ? structuredClone(options.metadata) : undefined,\n\t\t\t\t}\n\t\t\t: undefined;\n\t\tconst semanticEdgeId = request.semanticEdgeId ?? options?.headers?.[MODEL_REQUEST_ID_HEADER];\n\t\tconst operationId = request.operationId ?? semanticEdgeId ?? randomUUID();\n\t\tconst operation = this.bindOperation(model, { ...request, semanticEdgeId }, operationId);\n\t\tconst release = this.retainWork(operation.binding);\n\t\tconst recover = this.providerRecoveryWait();\n\t\tlet failure: unknown;\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst settlement = await (await this.execute(operation, model, context, options, streamSimple)).settled;\n\t\t\t\t// Rejected execution/settlement, including local allowance exhaustion, never reaches recovery.\n\t\t\t\tif (!(await recover(settlement.message, options?.signal))) return settlement;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tfailure = error;\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tawait release(failure === undefined ? [] : [failure]);\n\t\t}\n\t}\n\n\tcomplete(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\trequest: InferenceRequestOptions,\n\t): Promise<AssistantMessage> {\n\t\tlet completion!: Promise<AssistantMessage>;\n\t\tcompletion = (async () => {\n\t\t\tconst settlement = this.work.providerRecoveryPolicy?.().enabled\n\t\t\t\t? await this.completeWithProviderRecovery(model, context, options, request)\n\t\t\t\t: await (await this.start(model, context, options, request)).settled;\n\t\t\tconst binding = this.work.compactionSettlements.get(settlement);\n\t\t\tthis.work.compactionSettlements.delete(settlement);\n\t\t\tif (binding) this.work.compactionCompletions.set(completion, binding);\n\t\t\tconst branchBinding = this.work.branchSettlements.get(settlement);\n\t\t\tthis.work.branchSettlements.delete(settlement);\n\t\t\tif (branchBinding) this.work.branchCompletions.set(completion, branchBinding);\n\t\t\tconst plannerBinding = this.work.plannerSettlements.get(settlement);\n\t\t\tthis.work.plannerSettlements.delete(settlement);\n\t\t\tif (plannerBinding) this.work.plannerCompletions.set(completion, plannerBinding);\n\t\t\treturn settlement.message;\n\t\t})();\n\t\treturn completion;\n\t}\n\n\tbindAuxiliaryStream(streamFn: StreamFn, request: InferenceRequestOptions): DisposableInferenceStream {\n\t\tconst captured = this.capture();\n\t\tconst release = captured.retainWork(captured.capturedSink!);\n\t\tconst recover = captured.providerRecoveryWait();\n\t\tconst stream = captured.bindStream(streamFn, request);\n\t\tlet disposal: Promise<void> | undefined;\n\t\treturn Object.assign(stream, {\n\t\t\trecoverProviderFailure: async (message: AssistantMessage, signal?: AbortSignal) => {\n\t\t\t\tif (!(await recover(message, signal))) return false;\n\t\t\t\tcaptured.prepareTurnRetry();\n\t\t\t\treturn true;\n\t\t\t},\n\t\t\tdispose: () => {\n\t\t\t\tdisposal ??= (async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait release();\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tawait captured.dispose();\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t\treturn disposal;\n\t\t\t},\n\t\t});\n\t}\n\n\tbindStream(streamFn: StreamFn, request: InferenceRequestOptions): AgentOwnedStreamFn {\n\t\tconst unwrapped = unwrapSemanticEdgeStreamFn(streamFn) as BoundStreamFn;\n\t\tconst inner = unwrapped[REQUEST_STREAM_BINDING]?.inner ?? unwrapped;\n\t\t// One Agent stream is serial. Keep only its latest binding for semantic retries.\n\t\t// A side question or child gets its own closure, not the parent's source binding.\n\t\tlet previous: BoundOperation | undefined;\n\t\tlet previousBody: string | undefined;\n\t\tconst wrapped: BoundStreamFn = async (model, context, options, streamContext) => {\n\t\t\tlet captured: InferenceCoordinator | undefined;\n\t\t\tif (streamContext !== undefined) {\n\t\t\t\tif (\n\t\t\t\t\t!(streamContext instanceof InferenceCoordinator) ||\n\t\t\t\t\tstreamContext.work !== this.work ||\n\t\t\t\t\t!streamContext.capturedSink\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(\"Native stream context is not a capture of this inference owner\");\n\t\t\t\tcaptured = streamContext;\n\t\t\t}\n\t\t\tconst executor = captured ?? this;\n\t\t\tconst semanticEdgeId = request.semanticEdgeId ?? options?.headers?.[MODEL_REQUEST_ID_HEADER];\n\t\t\t// Reuse the existing semantic body identity if its best-effort recorder is unavailable.\n\t\t\tconst body = semanticEdgeId ? undefined : hashTurnBody(model, context, options);\n\t\t\tconst retryId =\n\t\t\t\tthis.retryTurn && body !== undefined && body === previousBody ? previous?.metadata.operationId : undefined;\n\t\t\tthis.retryTurn = false;\n\t\t\tconst operationId = request.operationId ?? semanticEdgeId ?? retryId ?? randomUUID();\n\t\t\tpreviousBody = body;\n\t\t\tif (captured || previous?.metadata.operationId !== operationId) {\n\t\t\t\t// A semantic retry can reuse its operation ID, but compilation owns this exact source frontier.\n\t\t\t\tprevious = executor.bindOperation(model, { ...request, semanticEdgeId }, operationId);\n\t\t\t}\n\t\t\treturn (\n\t\t\t\tawait executor.execute(\n\t\t\t\t\tprevious,\n\t\t\t\t\tmodel,\n\t\t\t\t\tcontext,\n\t\t\t\t\toptions,\n\t\t\t\t\tinner,\n\t\t\t\t\tcaptured !== undefined && request.purpose === \"main\",\n\t\t\t\t)\n\t\t\t).events;\n\t\t};\n\t\twrapped[REQUEST_STREAM_BINDING] = { coordinator: this, inner };\n\t\treturn wrapped;\n\t}\n}\n\n/** Standalone helper embedding stays optional; native session callers always supply requests. */\nexport function completeInference(\n\trequests: InferenceCoordinator | undefined,\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions: SimpleStreamOptions | undefined,\n\trequest: InferenceRequestOptions,\n): Promise<AssistantMessage> {\n\treturn requests ? requests.complete(model, context, options, request) : completeSimple(model, context, options);\n}\n\nexport type DisposableInferenceStream = StreamFn & {\n\tdispose(): Promise<void>;\n\trecoverProviderFailure?(message: AssistantMessage, signal?: AbortSignal): Promise<boolean>;\n};\n\n/** Side questions keep the subject's writer, but get their own operation and purpose. */\nexport function bindAuxiliaryInferenceStream(\n\tstreamFn: StreamFn,\n\trequest: InferenceRequestOptions,\n): DisposableInferenceStream {\n\tconst inner = unwrapSemanticEdgeStreamFn(streamFn) as BoundStreamFn;\n\tconst binding = inner[REQUEST_STREAM_BINDING];\n\tif (binding) return binding.coordinator.bindAuxiliaryStream(binding.inner, request);\n\tconst stream: StreamFn = (model, context, options) => inner(model, context, options);\n\treturn Object.assign(stream, { dispose: async () => {} });\n}\n"]}
@@ -33,16 +33,32 @@ function modelContract(model) {
33
33
  };
34
34
  }
35
35
  const nativeStreamFunctions = new WeakSet();
36
+ const nativeAuthSources = new WeakMap();
37
+ /** Consume the credential source resolved for this exact native request. Never persisted or sent to providers. */
38
+ export function takeNativeInferenceAuthSource(message) {
39
+ const source = nativeAuthSources.get(message);
40
+ nativeAuthSources.delete(message);
41
+ return source;
42
+ }
36
43
  /** Internal SDK auth/options resolver; transport stays the known instrumented AI dispatcher. */
37
44
  export function createNativeInferenceStream(resolveOptions) {
38
45
  const dispatch = async (model, context, options) => {
39
- const resolved = await resolveOptions(model, context, options);
40
- return streamSimple(model, context, {
46
+ const { authSourceToken, ...resolved } = await resolveOptions(model, context, options);
47
+ const events = streamSimple(model, context, {
41
48
  ...resolved,
42
49
  signal: options?.signal,
43
50
  attempts: options?.attempts,
44
51
  requireProviderAttempts: true,
45
52
  });
53
+ if (authSourceToken) {
54
+ const source = { ...authSourceToken };
55
+ const result = events.result().then((message) => {
56
+ nativeAuthSources.set(message, source);
57
+ return message;
58
+ });
59
+ events.result = () => result;
60
+ }
61
+ return events;
46
62
  };
47
63
  nativeStreamFunctions.add(dispatch);
48
64
  return dispatch;