privateer-agent 0.15.4 → 0.15.6

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 (229) hide show
  1. package/README.md +11 -0
  2. package/bin/boot-bundle.d.mts +2 -0
  3. package/bin/boot-bundle.mjs +44 -0
  4. package/bin/fresh-supervisor.d.mts +5 -1
  5. package/bin/fresh-supervisor.mjs +47 -10
  6. package/bin/privateer-launch.mjs +27 -3
  7. package/bin/privateer-subagent.mjs +5 -2
  8. package/bin/privateer-verify.mjs +12 -0
  9. package/bin/session-recovery.d.mts +53 -0
  10. package/bin/session-recovery.mjs +240 -0
  11. package/bin/session-seal-preload.mjs +17 -0
  12. package/bin/session-seal.d.mts +25 -0
  13. package/bin/session-seal.mjs +242 -0
  14. package/dist-boot/boot.mjs +3 -0
  15. package/dist-boot/c-27JKSMWL.mjs +1460 -0
  16. package/dist-boot/c-2BMRFV24.mjs +269 -0
  17. package/dist-boot/c-2CTF6JA3.mjs +166 -0
  18. package/dist-boot/c-2G3BBHRJ.mjs +84 -0
  19. package/dist-boot/c-2IDLKXX6.mjs +250 -0
  20. package/dist-boot/c-2NJD5VYM.mjs +8 -0
  21. package/dist-boot/c-2S5EEQPW.mjs +1602 -0
  22. package/dist-boot/c-2WRDCUVI.mjs +25 -0
  23. package/dist-boot/c-2YN3M256.mjs +14 -0
  24. package/dist-boot/c-37GM3GMU.mjs +187 -0
  25. package/dist-boot/c-3STKRSVO.mjs +2480 -0
  26. package/dist-boot/c-3TPV6TQQ.mjs +2320 -0
  27. package/dist-boot/c-3UVHLQDJ.mjs +225 -0
  28. package/dist-boot/c-42PUUZYC.mjs +697 -0
  29. package/dist-boot/c-4D5UMWVW.mjs +683 -0
  30. package/dist-boot/c-4ETZRMTA.mjs +46 -0
  31. package/dist-boot/c-4QT25BD5.mjs +1482 -0
  32. package/dist-boot/c-4WVR32AP.mjs +2579 -0
  33. package/dist-boot/c-5EMM567G.mjs +152 -0
  34. package/dist-boot/c-5FA4CV63.mjs +145 -0
  35. package/dist-boot/c-5GV3X3RB.mjs +14 -0
  36. package/dist-boot/c-5JCEPRIY.mjs +52 -0
  37. package/dist-boot/c-5NDKIIWT.mjs +16 -0
  38. package/dist-boot/c-5QL3AR26.mjs +4665 -0
  39. package/dist-boot/c-5XY6MFKN.mjs +5142 -0
  40. package/dist-boot/c-65UZIZC7.mjs +2897 -0
  41. package/dist-boot/c-6FUXKHOK.mjs +1969 -0
  42. package/dist-boot/c-6JHWQE4V.mjs +18242 -0
  43. package/dist-boot/c-6LOBR4I6.mjs +5280 -0
  44. package/dist-boot/c-6QHOZXKQ.mjs +14394 -0
  45. package/dist-boot/c-6ZO2SADQ.mjs +178 -0
  46. package/dist-boot/c-6ZORVVZP.mjs +1449 -0
  47. package/dist-boot/c-76QH4UCP.mjs +2441 -0
  48. package/dist-boot/c-77GO5L5Y.mjs +20982 -0
  49. package/dist-boot/c-7M23XFTN.mjs +5052 -0
  50. package/dist-boot/c-7TC367E2.mjs +32 -0
  51. package/dist-boot/c-7UOG7POX.mjs +1524 -0
  52. package/dist-boot/c-7VHP3FLN.mjs +376 -0
  53. package/dist-boot/c-A73JHZP2.mjs +13207 -0
  54. package/dist-boot/c-ABXULAFL.mjs +71 -0
  55. package/dist-boot/c-ANDD2AQO.mjs +74 -0
  56. package/dist-boot/c-AOY77AZL.mjs +1430 -0
  57. package/dist-boot/c-AXEPZ22I.mjs +108 -0
  58. package/dist-boot/c-B2Y7VNHU.mjs +427 -0
  59. package/dist-boot/c-B7VJUH73.mjs +77 -0
  60. package/dist-boot/c-BFW6CDVL.mjs +24 -0
  61. package/dist-boot/c-BHNIF2AR.mjs +188 -0
  62. package/dist-boot/c-BKF2O6BL.mjs +23 -0
  63. package/dist-boot/c-BOZXFTZN.mjs +8 -0
  64. package/dist-boot/c-BRNYJWZL.mjs +28 -0
  65. package/dist-boot/c-C3N4Z2HO.mjs +93 -0
  66. package/dist-boot/c-C4IV7ZFG.mjs +717 -0
  67. package/dist-boot/c-C5NK6UYV.mjs +793 -0
  68. package/dist-boot/c-C67644MB.mjs +1659 -0
  69. package/dist-boot/c-C6S2YB53.mjs +620 -0
  70. package/dist-boot/c-CDBEJSBF.mjs +37 -0
  71. package/dist-boot/c-CG47HBKU.mjs +435 -0
  72. package/dist-boot/c-CKCTWCT5.mjs +51 -0
  73. package/dist-boot/c-CN77DCGF.mjs +60 -0
  74. package/dist-boot/c-CRBXNKFO.mjs +1795 -0
  75. package/dist-boot/c-CRIHASQ6.mjs +973 -0
  76. package/dist-boot/c-CU4NGAUO.mjs +3786 -0
  77. package/dist-boot/c-CWRFLGQU.mjs +1883 -0
  78. package/dist-boot/c-CYQB2USO.mjs +32 -0
  79. package/dist-boot/c-DEE67DJO.mjs +379 -0
  80. package/dist-boot/c-DIFDBYOP.mjs +1258 -0
  81. package/dist-boot/c-DOSGVXDZ.mjs +34879 -0
  82. package/dist-boot/c-DR7XQI32.mjs +381 -0
  83. package/dist-boot/c-DTGPSB46.mjs +14666 -0
  84. package/dist-boot/c-DTHDNA4P.mjs +320 -0
  85. package/dist-boot/c-E4Z3Y5B5.mjs +3864 -0
  86. package/dist-boot/c-E66Z2TI7.mjs +203 -0
  87. package/dist-boot/c-EBU6RLRV.mjs +1527 -0
  88. package/dist-boot/c-EBZZNGSF.mjs +432 -0
  89. package/dist-boot/c-EC3LJ2KF.mjs +1032 -0
  90. package/dist-boot/c-EQBKXWNX.mjs +15829 -0
  91. package/dist-boot/c-EUEPIW4S.mjs +574 -0
  92. package/dist-boot/c-EX4YVWAT.mjs +378 -0
  93. package/dist-boot/c-EYZGSAJU.mjs +98 -0
  94. package/dist-boot/c-F75VRKY4.mjs +172 -0
  95. package/dist-boot/c-FH4NXKHV.mjs +177 -0
  96. package/dist-boot/c-FHNUCTEM.mjs +140 -0
  97. package/dist-boot/c-FJ5T42DS.mjs +5349 -0
  98. package/dist-boot/c-FPCNRL7G.mjs +1728 -0
  99. package/dist-boot/c-G4DLN7Q4.mjs +8 -0
  100. package/dist-boot/c-G56GYQFZ.mjs +2507 -0
  101. package/dist-boot/c-GLIOERDQ.mjs +1200 -0
  102. package/dist-boot/c-GMJ5HUBM.mjs +14 -0
  103. package/dist-boot/c-H3HSGMAQ.mjs +461 -0
  104. package/dist-boot/c-HIKTO6P7.mjs +275 -0
  105. package/dist-boot/c-I2MCJ34O.mjs +464 -0
  106. package/dist-boot/c-I3C6LBW4.mjs +765 -0
  107. package/dist-boot/c-I54OKQHW.mjs +387 -0
  108. package/dist-boot/c-IFSP3R4D.mjs +80 -0
  109. package/dist-boot/c-IZK77VB7.mjs +171 -0
  110. package/dist-boot/c-J3Y25UGE.mjs +54 -0
  111. package/dist-boot/c-J5IESS7W.mjs +27750 -0
  112. package/dist-boot/c-JJWZBY7L.mjs +254 -0
  113. package/dist-boot/c-JKTFXTGF.mjs +463 -0
  114. package/dist-boot/c-JN57AXQ4.mjs +77 -0
  115. package/dist-boot/c-KFIO6LUW.mjs +1096 -0
  116. package/dist-boot/c-KIEMEFWW.mjs +478 -0
  117. package/dist-boot/c-KIVXWBYD.mjs +28 -0
  118. package/dist-boot/c-KP6CRIP4.mjs +580 -0
  119. package/dist-boot/c-L26VOJX4.mjs +11558 -0
  120. package/dist-boot/c-L5GHWG5G.mjs +5988 -0
  121. package/dist-boot/c-M7NSQAKK.mjs +353 -0
  122. package/dist-boot/c-MCEWOPBW.mjs +56 -0
  123. package/dist-boot/c-MGPIEG7I.mjs +20 -0
  124. package/dist-boot/c-NREXJV3M.mjs +393 -0
  125. package/dist-boot/c-O5PP6CTX.mjs +162 -0
  126. package/dist-boot/c-OBQDHSXM.mjs +1774 -0
  127. package/dist-boot/c-OLQHHDD4.mjs +21 -0
  128. package/dist-boot/c-OXW4JQQH.mjs +319 -0
  129. package/dist-boot/c-P3D7ZUWN.mjs +1288 -0
  130. package/dist-boot/c-P4PQZVV5.mjs +948 -0
  131. package/dist-boot/c-P63T3XL2.mjs +26373 -0
  132. package/dist-boot/c-P6N5DQGZ.mjs +194 -0
  133. package/dist-boot/c-P7MLKQFC.mjs +58 -0
  134. package/dist-boot/c-PB3PZJL5.mjs +1276 -0
  135. package/dist-boot/c-PTN4S6G2.mjs +1259 -0
  136. package/dist-boot/c-PYCE5J7U.mjs +1083 -0
  137. package/dist-boot/c-Q4HYCRLB.mjs +19410 -0
  138. package/dist-boot/c-QUXMETGG.mjs +68 -0
  139. package/dist-boot/c-RDMJZCOX.mjs +356 -0
  140. package/dist-boot/c-ROGJK76M.mjs +17 -0
  141. package/dist-boot/c-RQJJ26T4.mjs +708 -0
  142. package/dist-boot/c-RSKCUPJF.mjs +7559 -0
  143. package/dist-boot/c-RVJU4O6P.mjs +37 -0
  144. package/dist-boot/c-S2RVHR3M.mjs +165 -0
  145. package/dist-boot/c-SKMK3PEE.mjs +91120 -0
  146. package/dist-boot/c-TI7SM4EG.mjs +20 -0
  147. package/dist-boot/c-TILJ6GXD.mjs +1235 -0
  148. package/dist-boot/c-TT6BCUJD.mjs +114 -0
  149. package/dist-boot/c-U4ITOXAN.mjs +2107 -0
  150. package/dist-boot/c-UGERXVO2.mjs +7120 -0
  151. package/dist-boot/c-UPBH5AXY.mjs +1363 -0
  152. package/dist-boot/c-US2PUNZL.mjs +597 -0
  153. package/dist-boot/c-UU4WZPPE.mjs +20 -0
  154. package/dist-boot/c-UWVIYPQS.mjs +39 -0
  155. package/dist-boot/c-V4RHQBPQ.mjs +17683 -0
  156. package/dist-boot/c-V5MRVK47.mjs +351 -0
  157. package/dist-boot/c-V6CL266R.mjs +1755 -0
  158. package/dist-boot/c-VJTMFKYE.mjs +14975 -0
  159. package/dist-boot/c-VJTRUKIB.mjs +773 -0
  160. package/dist-boot/c-W4IFSHPW.mjs +43 -0
  161. package/dist-boot/c-WETGB2CF.mjs +113 -0
  162. package/dist-boot/c-WO3QSZUU.mjs +1337 -0
  163. package/dist-boot/c-WQLH73TY.mjs +242 -0
  164. package/dist-boot/c-XL735JW5.mjs +500 -0
  165. package/dist-boot/c-Y7HADL5B.mjs +1107 -0
  166. package/dist-boot/c-YGQHSVSK.mjs +41 -0
  167. package/dist-boot/c-YMP2AMEB.mjs +10350 -0
  168. package/dist-boot/c-YRDO2WEF.mjs +12012 -0
  169. package/dist-boot/c-YUSTRATJ.mjs +8 -0
  170. package/dist-boot/c-Z2262R22.mjs +2697 -0
  171. package/dist-boot/c-Z4ALQMJC.mjs +709 -0
  172. package/dist-boot/c-Z5ZUQVUY.mjs +62 -0
  173. package/dist-boot/c-ZDZUKXF7.mjs +874 -0
  174. package/dist-boot/c-ZJYLGIC3.mjs +32 -0
  175. package/dist-boot/c-ZNA5CDMI.mjs +77 -0
  176. package/dist-boot/c-ZSO6DI3M.mjs +204 -0
  177. package/dist-boot/c-ZWUVHKMK.mjs +100 -0
  178. package/dist-boot/c-ZY4MESEW.mjs +832 -0
  179. package/dist-boot/c-ZZ5REI4L.mjs +329 -0
  180. package/dist-boot/cli.mjs +51 -0
  181. package/dist-boot/ext-anthropic-attribution.mjs +207 -0
  182. package/dist-boot/ext-pi-background-tasks.mjs +7234 -0
  183. package/dist-boot/ext-pi-subagents.mjs +37 -0
  184. package/dist-boot/ext-privateer-account.mjs +4426 -0
  185. package/dist-boot/ext-privateer-brand.mjs +5274 -0
  186. package/dist-boot/ext-privateer-codemode.mjs +37 -0
  187. package/dist-boot/ext-privateer-computer.mjs +626 -0
  188. package/dist-boot/ext-privateer-connect.mjs +1862 -0
  189. package/dist-boot/ext-privateer-context.mjs +323 -0
  190. package/dist-boot/ext-privateer-desktop.mjs +92 -0
  191. package/dist-boot/ext-privateer-final-audit.mjs +48 -0
  192. package/dist-boot/ext-privateer-fresh.mjs +81 -0
  193. package/dist-boot/ext-privateer-gate.mjs +5959 -0
  194. package/dist-boot/ext-privateer-hints.mjs +236 -0
  195. package/dist-boot/ext-privateer-media.mjs +2626 -0
  196. package/dist-boot/ext-privateer-models.mjs +3397 -0
  197. package/dist-boot/ext-privateer-posture.mjs +3006 -0
  198. package/dist-boot/ext-privateer-privacy.mjs +4578 -0
  199. package/dist-boot/ext-privateer-recovery.mjs +287 -0
  200. package/dist-boot/ext-privateer-speak.mjs +4754 -0
  201. package/dist-boot/ext-privateer-terminals.mjs +725 -0
  202. package/dist-boot/ext-privateer-tools.mjs +528 -0
  203. package/dist-boot/ext-privateer-truncation.mjs +74 -0
  204. package/dist-boot/ext-privateer-update.mjs +210 -0
  205. package/dist-boot/ext-privateer-vision.mjs +148 -0
  206. package/dist-boot/ext-privateer-web.mjs +543 -0
  207. package/dist-boot/ext-rpiv-ask-user-question.mjs +710 -0
  208. package/dist-boot/manifest.json +9 -0
  209. package/extensions/privateer-brand.ts +3 -1
  210. package/extensions/privateer-context.ts +4 -2
  211. package/extensions/privateer-final-audit.ts +17 -0
  212. package/extensions/privateer-gate.ts +55 -9
  213. package/extensions/privateer-recovery.ts +175 -0
  214. package/extensions/privateer-web.ts +4 -4
  215. package/package.json +3 -1
  216. package/patches/@earendil-works+pi-coding-agent+1.3.0.patch +199 -2
  217. package/patches/pi-background-tasks+2.6.10.patch +91 -7
  218. package/src/cli/chat.ts +7 -1
  219. package/src/config/moatManifest.json +2 -0
  220. package/src/config/whatsNew.json +4 -4
  221. package/src/context.ts +33 -5
  222. package/src/engine/finalAudit.ts +38 -0
  223. package/src/engine/stallWatchdog.ts +8 -1
  224. package/src/providers/account.ts +34 -3
  225. package/src/remote/attentionPush.ts +40 -0
  226. package/src/remote/liveTaskSession.ts +7 -1
  227. package/src/remote/relayClient.ts +38 -4
  228. package/src/remote/remoteBridge.ts +17 -0
  229. package/src/remote/transcriptSnapshot.ts +104 -0
@@ -0,0 +1,1258 @@
1
+ import{createRequire as __pvCR}from"node:module";import{fileURLToPath as __pvF}from"node:url";import{dirname as __pvD}from"node:path";const require=__pvCR(import.meta.url);const __pvUrl=(r)=>new URL(r,import.meta.url).href;const __pvFile=(r)=>__pvF(new URL(r,import.meta.url));
2
+ import {
3
+ buildCopilotDynamicHeaders,
4
+ hasCopilotVisionInput
5
+ } from "./c-UWVIYPQS.mjs";
6
+ import {
7
+ adjustMaxTokensForThinking,
8
+ buildBaseOptions,
9
+ clampMaxTokensToContext,
10
+ getJsonSchemaToolParameters,
11
+ getPiUserAgent,
12
+ resolveJsonSchemaStrictSampling,
13
+ splitErrorToolResultImages,
14
+ transformMessages
15
+ } from "./c-C6S2YB53.mjs";
16
+ import {
17
+ sanitizeSurrogates
18
+ } from "./c-5GV3X3RB.mjs";
19
+ import {
20
+ retryProviderRequest
21
+ } from "./c-EYZGSAJU.mjs";
22
+ import {
23
+ headersToRecord
24
+ } from "./c-ZJYLGIC3.mjs";
25
+ import {
26
+ Anthropic
27
+ } from "./c-6QHOZXKQ.mjs";
28
+ import {
29
+ ANTHROPIC_FEDERATION_RULE_ID_ENV,
30
+ ANTHROPIC_IDENTITY_TOKEN_FILE_ENV,
31
+ ANTHROPIC_ORGANIZATION_ID_ENV,
32
+ ANTHROPIC_SERVICE_ACCOUNT_ID_ENV,
33
+ ANTHROPIC_WORKSPACE_ID_ENV
34
+ } from "./c-O5PP6CTX.mjs";
35
+ import {
36
+ getProviderEnvValue
37
+ } from "./c-CDBEJSBF.mjs";
38
+ import {
39
+ parseJsonWithRepair,
40
+ parseStreamingJson,
41
+ parseToolCallArguments
42
+ } from "./c-DEE67DJO.mjs";
43
+ import {
44
+ calculateCost,
45
+ getCurrentTools,
46
+ getInitialSystemMessage,
47
+ getSystemMessageText,
48
+ renderSystemMessageUpdate,
49
+ resolveTranscript
50
+ } from "./c-WO3QSZUU.mjs";
51
+ import {
52
+ AssistantMessageEventStream,
53
+ appendAssistantMessageDiagnostic
54
+ } from "./c-S2RVHR3M.mjs";
55
+ import {
56
+ __name
57
+ } from "./c-CN77DCGF.mjs";
58
+
59
+ // node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js
60
+ function resolveCacheRetention(cacheRetention, env) {
61
+ if (cacheRetention) {
62
+ return cacheRetention;
63
+ }
64
+ if (getProviderEnvValue("PI_CACHE_RETENTION", env) === "long") {
65
+ return "long";
66
+ }
67
+ return "short";
68
+ }
69
+ __name(resolveCacheRetention, "resolveCacheRetention");
70
+ function getCacheControl(model, cacheRetention, env) {
71
+ const retention = resolveCacheRetention(cacheRetention, env);
72
+ if (retention === "none") {
73
+ return { retention };
74
+ }
75
+ const ttl = retention === "long" && getAnthropicCompat(model).supportsLongCacheRetention ? "1h" : void 0;
76
+ return {
77
+ retention,
78
+ cacheControl: { type: "ephemeral", ...ttl && { ttl } }
79
+ };
80
+ }
81
+ __name(getCacheControl, "getCacheControl");
82
+ var claudeCodeVersion = "2.1.280";
83
+ var claudeCodeTools = [
84
+ "Read",
85
+ "Write",
86
+ "Edit",
87
+ "Bash",
88
+ "Grep",
89
+ "Glob",
90
+ "AskUserQuestion",
91
+ "EnterPlanMode",
92
+ "ExitPlanMode",
93
+ "KillShell",
94
+ "NotebookEdit",
95
+ "Skill",
96
+ "Task",
97
+ "TaskOutput",
98
+ "TodoWrite",
99
+ "WebFetch",
100
+ "WebSearch"
101
+ ];
102
+ var ccToolLookup = new Map(claudeCodeTools.map((t) => [t.toLowerCase(), t]));
103
+ var toClaudeCodeName = /* @__PURE__ */ __name((name) => ccToolLookup.get(name.toLowerCase()) ?? name, "toClaudeCodeName");
104
+ var fromClaudeCodeName = /* @__PURE__ */ __name((name, tools) => {
105
+ if (tools && tools.length > 0) {
106
+ const lowerName = name.toLowerCase();
107
+ const matchedTool = tools.find((tool) => tool.name.toLowerCase() === lowerName);
108
+ if (matchedTool)
109
+ return matchedTool.name;
110
+ }
111
+ return name;
112
+ }, "fromClaudeCodeName");
113
+ function convertImageBlock(image) {
114
+ return {
115
+ type: "image",
116
+ source: {
117
+ type: "base64",
118
+ media_type: image.mimeType,
119
+ data: image.data
120
+ }
121
+ };
122
+ }
123
+ __name(convertImageBlock, "convertImageBlock");
124
+ function convertContentBlocks(content) {
125
+ const hasImages = content.some((c) => c.type === "image");
126
+ if (!hasImages) {
127
+ return sanitizeSurrogates(content.map((c) => c.text).join("\n"));
128
+ }
129
+ const blocks = content.map((block) => {
130
+ if (block.type === "text") {
131
+ return {
132
+ type: "text",
133
+ text: sanitizeSurrogates(block.text)
134
+ };
135
+ }
136
+ return convertImageBlock(block);
137
+ });
138
+ const hasText = blocks.some((b) => b.type === "text");
139
+ if (!hasText) {
140
+ blocks.unshift({
141
+ type: "text",
142
+ text: "(see attached image)"
143
+ });
144
+ }
145
+ return blocks;
146
+ }
147
+ __name(convertContentBlocks, "convertContentBlocks");
148
+ var FINE_GRAINED_TOOL_STREAMING_BETA = "fine-grained-tool-streaming-2025-05-14";
149
+ var INTERLEAVED_THINKING_BETA = "interleaved-thinking-2025-05-14";
150
+ var SERVER_SIDE_FALLBACK_BETA = "server-side-fallback-2026-07-01";
151
+ var MID_CONVERSATION_OUTPUT_CONFIG_BETA = "mid-conversation-output-config-2026-07-01";
152
+ var THINKING_BINDING_CONTROLS_BETA = "thinking-binding-controls-2026-08-01";
153
+ var INLINE_TOOLS_BETA = "inline-tools-2026-09-15";
154
+ var DEFERRED_TOOL_PLACEHOLDER = {
155
+ name: "__pi_deferred_placeholder__",
156
+ description: "Reserved placeholder. Never available. Never call this.",
157
+ input_schema: { type: "object", properties: {}, required: [] },
158
+ defer_loading: true
159
+ };
160
+ function shouldUseServerSideFallbackBeta(model) {
161
+ return (model.compat?.allowedFallbackModels?.length ?? 0) > 0;
162
+ }
163
+ __name(shouldUseServerSideFallbackBeta, "shouldUseServerSideFallbackBeta");
164
+ function getAnthropicCompat(model) {
165
+ const isOpenRouter = model.provider === "openrouter" || model.baseUrl.includes("openrouter.ai");
166
+ return {
167
+ supportsEagerToolInputStreaming: model.compat?.supportsEagerToolInputStreaming ?? true,
168
+ supportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? true,
169
+ sendSessionAffinityHeaders: model.compat?.sendSessionAffinityHeaders ?? isOpenRouter,
170
+ sessionAffinityFormat: model.compat?.sessionAffinityFormat ?? (isOpenRouter ? "openrouter" : void 0),
171
+ supportsCacheControlOnTools: model.compat?.supportsCacheControlOnTools ?? true,
172
+ supportsTemperature: model.compat?.supportsTemperature ?? true,
173
+ allowEmptySignature: model.compat?.allowEmptySignature ?? false,
174
+ supportsStrictTools: model.compat?.supportsStrictTools ?? false,
175
+ supportsMidConvoSystemMessages: model.compat?.supportsMidConvoSystemMessages ?? false,
176
+ supportsMidConvoToolChanges: model.compat?.supportsMidConvoToolChanges ?? false
177
+ };
178
+ }
179
+ __name(getAnthropicCompat, "getAnthropicCompat");
180
+ function mergeHeaders(...headerSources) {
181
+ const merged = {};
182
+ for (const headers of headerSources) {
183
+ if (headers) {
184
+ Object.assign(merged, headers);
185
+ }
186
+ }
187
+ return merged;
188
+ }
189
+ __name(mergeHeaders, "mergeHeaders");
190
+ function mergeClientHeaders(...headerSources) {
191
+ return mergeHeaders({ "User-Agent": getPiUserAgent() }, ...headerSources);
192
+ }
193
+ __name(mergeClientHeaders, "mergeClientHeaders");
194
+ function hasHeader(headers, name) {
195
+ if (!headers)
196
+ return false;
197
+ const expected = name.toLowerCase();
198
+ for (const [key, value] of Object.entries(headers)) {
199
+ if (key.toLowerCase() === expected && value !== null && value.trim().length > 0)
200
+ return true;
201
+ }
202
+ return false;
203
+ }
204
+ __name(hasHeader, "hasHeader");
205
+ function hasRequestAuth(apiKey, headers) {
206
+ return !!apiKey || hasHeader(headers, "authorization") || hasHeader(headers, "x-api-key") || hasHeader(headers, "cf-aig-authorization");
207
+ }
208
+ __name(hasRequestAuth, "hasRequestAuth");
209
+ function assertRequestAuth(provider, apiKey, headers) {
210
+ if (!hasRequestAuth(apiKey, headers))
211
+ throw new Error(`No API key for provider: ${provider}`);
212
+ }
213
+ __name(assertRequestAuth, "assertRequestAuth");
214
+ var PiAnthropic = class extends Anthropic {
215
+ static {
216
+ __name(this, "PiAnthropic");
217
+ }
218
+ _shouldResolveDefaultCredentials() {
219
+ return false;
220
+ }
221
+ };
222
+ function getAnthropicFederation(model, apiKey, headers, env) {
223
+ if (model.provider !== "anthropic" || hasRequestAuth(apiKey, headers))
224
+ return void 0;
225
+ const federationRuleId = getProviderEnvValue(ANTHROPIC_FEDERATION_RULE_ID_ENV, env);
226
+ const organizationId = getProviderEnvValue(ANTHROPIC_ORGANIZATION_ID_ENV, env);
227
+ const identityTokenFile = getProviderEnvValue(ANTHROPIC_IDENTITY_TOKEN_FILE_ENV, env);
228
+ if (!federationRuleId || !organizationId || !identityTokenFile)
229
+ return void 0;
230
+ return {
231
+ organization_id: organizationId,
232
+ workspace_id: getProviderEnvValue(ANTHROPIC_WORKSPACE_ID_ENV, env),
233
+ authentication: {
234
+ type: "oidc_federation",
235
+ federation_rule_id: federationRuleId,
236
+ service_account_id: getProviderEnvValue(ANTHROPIC_SERVICE_ACCOUNT_ID_ENV, env),
237
+ identity_token: { source: "file", path: identityTokenFile }
238
+ }
239
+ };
240
+ }
241
+ __name(getAnthropicFederation, "getAnthropicFederation");
242
+ var federationClient;
243
+ var ANTHROPIC_MESSAGE_EVENTS = /* @__PURE__ */ new Set([
244
+ "message_start",
245
+ "message_delta",
246
+ "message_stop",
247
+ "content_block_start",
248
+ "content_block_delta",
249
+ "content_block_stop"
250
+ ]);
251
+ function flushSseEvent(state) {
252
+ if (!state.event && state.data.length === 0) {
253
+ return null;
254
+ }
255
+ const event = {
256
+ event: state.event,
257
+ data: state.data.join("\n"),
258
+ raw: [...state.raw]
259
+ };
260
+ state.event = null;
261
+ state.data = [];
262
+ state.raw = [];
263
+ return event;
264
+ }
265
+ __name(flushSseEvent, "flushSseEvent");
266
+ function decodeSseLine(line, state) {
267
+ if (line === "") {
268
+ return flushSseEvent(state);
269
+ }
270
+ state.raw.push(line);
271
+ if (line.startsWith(":")) {
272
+ return null;
273
+ }
274
+ const delimiterIndex = line.indexOf(":");
275
+ const fieldName = delimiterIndex === -1 ? line : line.slice(0, delimiterIndex);
276
+ let value = delimiterIndex === -1 ? "" : line.slice(delimiterIndex + 1);
277
+ if (value.startsWith(" ")) {
278
+ value = value.slice(1);
279
+ }
280
+ if (fieldName === "event") {
281
+ state.event = value;
282
+ } else if (fieldName === "data") {
283
+ state.data.push(value);
284
+ }
285
+ return null;
286
+ }
287
+ __name(decodeSseLine, "decodeSseLine");
288
+ function nextLineBreakIndex(text) {
289
+ const carriageReturnIndex = text.indexOf("\r");
290
+ const newlineIndex = text.indexOf("\n");
291
+ if (carriageReturnIndex === -1) {
292
+ return newlineIndex;
293
+ }
294
+ if (newlineIndex === -1) {
295
+ return carriageReturnIndex;
296
+ }
297
+ return Math.min(carriageReturnIndex, newlineIndex);
298
+ }
299
+ __name(nextLineBreakIndex, "nextLineBreakIndex");
300
+ function consumeLine(text) {
301
+ const lineBreakIndex = nextLineBreakIndex(text);
302
+ if (lineBreakIndex === -1) {
303
+ return null;
304
+ }
305
+ let nextIndex = lineBreakIndex + 1;
306
+ if (text[lineBreakIndex] === "\r" && text[nextIndex] === "\n") {
307
+ nextIndex += 1;
308
+ }
309
+ return {
310
+ line: text.slice(0, lineBreakIndex),
311
+ rest: text.slice(nextIndex)
312
+ };
313
+ }
314
+ __name(consumeLine, "consumeLine");
315
+ async function* iterateSseMessages(body, signal) {
316
+ const reader = body.getReader();
317
+ const decoder = new TextDecoder();
318
+ const state = { event: null, data: [], raw: [] };
319
+ let buffer = "";
320
+ try {
321
+ while (true) {
322
+ if (signal?.aborted) {
323
+ throw new Error("Request was aborted");
324
+ }
325
+ const { value, done } = await reader.read();
326
+ if (done) {
327
+ break;
328
+ }
329
+ buffer += decoder.decode(value, { stream: true });
330
+ let consumed2 = consumeLine(buffer);
331
+ while (consumed2) {
332
+ buffer = consumed2.rest;
333
+ const event = decodeSseLine(consumed2.line, state);
334
+ if (event) {
335
+ yield event;
336
+ }
337
+ consumed2 = consumeLine(buffer);
338
+ }
339
+ }
340
+ buffer += decoder.decode();
341
+ let consumed = consumeLine(buffer);
342
+ while (consumed) {
343
+ buffer = consumed.rest;
344
+ const event = decodeSseLine(consumed.line, state);
345
+ if (event) {
346
+ yield event;
347
+ }
348
+ consumed = consumeLine(buffer);
349
+ }
350
+ if (buffer.length > 0) {
351
+ const event = decodeSseLine(buffer, state);
352
+ if (event) {
353
+ yield event;
354
+ }
355
+ }
356
+ const trailingEvent = flushSseEvent(state);
357
+ if (trailingEvent) {
358
+ yield trailingEvent;
359
+ }
360
+ } finally {
361
+ reader.releaseLock();
362
+ }
363
+ }
364
+ __name(iterateSseMessages, "iterateSseMessages");
365
+ async function* iterateAnthropicEvents(response, signal) {
366
+ if (!response.body) {
367
+ throw new Error("Attempted to iterate over an Anthropic response with no body");
368
+ }
369
+ let sawMessageStart = false;
370
+ let sawMessageEnd = false;
371
+ for await (const sse of iterateSseMessages(response.body, signal)) {
372
+ if (sse.event === "error") {
373
+ throw new Error(sse.data);
374
+ }
375
+ if (!ANTHROPIC_MESSAGE_EVENTS.has(sse.event ?? "")) {
376
+ continue;
377
+ }
378
+ try {
379
+ const event = parseJsonWithRepair(sse.data);
380
+ if (event.type === "message_start") {
381
+ sawMessageStart = true;
382
+ } else if (event.type === "message_stop") {
383
+ sawMessageEnd = true;
384
+ }
385
+ yield event;
386
+ } catch (error) {
387
+ const message = error instanceof Error ? error.message : String(error);
388
+ throw new Error(`Could not parse Anthropic SSE event ${sse.event}: ${message}; data=${sse.data}; raw=${sse.raw.join("\\n")}`);
389
+ }
390
+ }
391
+ if (sawMessageStart && !sawMessageEnd) {
392
+ throw new Error("Anthropic stream ended before message_stop");
393
+ }
394
+ }
395
+ __name(iterateAnthropicEvents, "iterateAnthropicEvents");
396
+ var stream = /* @__PURE__ */ __name((model, context, options) => {
397
+ const stream2 = new AssistantMessageEventStream();
398
+ const normalizedContext = resolveTranscript(context, getAnthropicCompat(model).supportsMidConvoSystemMessages);
399
+ const currentTools = getCurrentTools(normalizedContext.messages);
400
+ (async () => {
401
+ const output = {
402
+ role: "assistant",
403
+ content: [],
404
+ api: model.api,
405
+ provider: model.provider,
406
+ model: model.id,
407
+ usage: {
408
+ input: 0,
409
+ output: 0,
410
+ cacheRead: 0,
411
+ cacheWrite: 0,
412
+ totalTokens: 0,
413
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
414
+ },
415
+ stopReason: "pending",
416
+ timestamp: Date.now()
417
+ };
418
+ try {
419
+ let client;
420
+ let isOAuth;
421
+ let usageModel = model;
422
+ let inputTransformations;
423
+ if (options?.client) {
424
+ client = options.client;
425
+ isOAuth = false;
426
+ } else {
427
+ const apiKey = options?.apiKey;
428
+ const federation = getAnthropicFederation(model, apiKey, options?.headers, options?.env);
429
+ if (!federation)
430
+ assertRequestAuth(model.provider, apiKey, options?.headers);
431
+ let copilotDynamicHeaders;
432
+ if (model.provider === "github-copilot") {
433
+ const hasImages = hasCopilotVisionInput(normalizedContext.messages);
434
+ copilotDynamicHeaders = buildCopilotDynamicHeaders({
435
+ messages: normalizedContext.messages,
436
+ hasImages
437
+ });
438
+ }
439
+ const cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env);
440
+ const cacheSessionId = cacheRetention === "none" ? void 0 : options?.sessionId;
441
+ const created = createClient(model, apiKey, options?.headers, options?.fetch, copilotDynamicHeaders, cacheSessionId, federation);
442
+ client = created.client;
443
+ isOAuth = created.isOAuthToken;
444
+ }
445
+ const requestOptions = {
446
+ ...options?.signal ? { signal: options.signal } : {},
447
+ ...options?.timeoutMs !== void 0 ? { timeout: options.timeoutMs } : {},
448
+ maxRetries: 0
449
+ };
450
+ let disablePreferredStrictTools = false;
451
+ let response;
452
+ for (; ; ) {
453
+ options?.signal?.throwIfAborted();
454
+ const built = buildParams(model, normalizedContext, isOAuth, options, disablePreferredStrictTools);
455
+ if (built.providerThinkingLevel)
456
+ output.providerThinkingLevel = built.providerThinkingLevel;
457
+ let params = built.params;
458
+ const nextParams = await options?.onPayload?.(params, model);
459
+ if (nextParams !== void 0) {
460
+ params = { ...nextParams, stream: true };
461
+ }
462
+ try {
463
+ response = await retryProviderRequest(() => client.beta.messages.create(params, requestOptions).asResponse(), {
464
+ maxRetries: options?.maxRetries,
465
+ maxRetryDelayMs: options?.maxRetryDelayMs,
466
+ signal: options?.signal
467
+ });
468
+ break;
469
+ } catch (error) {
470
+ if (options?.signal?.aborted || disablePreferredStrictTools || !built.hasPreferredStrictTools || !(error instanceof Anthropic.APIError) || error.status !== 400 || error.type !== "invalid_request_error" || ![
471
+ "The compiled grammar is too large",
472
+ "Too many strict tools (",
473
+ "Schemas contains too many parameters with union types ("
474
+ ].some((message) => error.message.includes(message))) {
475
+ throw error;
476
+ }
477
+ disablePreferredStrictTools = true;
478
+ appendAssistantMessageDiagnostic(output, {
479
+ type: "anthropic_strict_tools_fallback",
480
+ timestamp: Date.now(),
481
+ error: { message: error.message },
482
+ details: { reason: "strict_tool_limits_exceeded" }
483
+ });
484
+ }
485
+ }
486
+ await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);
487
+ stream2.push({ type: "start", partial: output });
488
+ const blocks = output.content;
489
+ for await (const event of iterateAnthropicEvents(response, options?.signal)) {
490
+ await options?.onProviderStreamEvent?.(event, model);
491
+ if (event.type === "message_start") {
492
+ output.responseId = event.message.id;
493
+ const transformations = event.message.input_transformations;
494
+ if (Array.isArray(transformations))
495
+ inputTransformations = transformations;
496
+ const responseModel = event.message.model;
497
+ if (responseModel !== model.id)
498
+ output.responseModel = responseModel;
499
+ const fallbackCost = responseModel === model.id ? void 0 : model.compat?.allowedFallbackModels?.find((fallback) => fallback.provider === model.provider && fallback.model === responseModel)?.cost;
500
+ usageModel = fallbackCost ? { ...model, id: responseModel, cost: fallbackCost } : model;
501
+ output.usage.input = event.message.usage.input_tokens || 0;
502
+ output.usage.output = event.message.usage.output_tokens || 0;
503
+ output.usage.cacheRead = event.message.usage.cache_read_input_tokens || 0;
504
+ output.usage.cacheWrite = event.message.usage.cache_creation_input_tokens || 0;
505
+ output.usage.cacheWrite1h = event.message.usage.cache_creation?.ephemeral_1h_input_tokens || 0;
506
+ output.usage.totalTokens = output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
507
+ calculateCost(usageModel, output.usage);
508
+ } else if (event.type === "content_block_start") {
509
+ if (event.content_block.type === "fallback") {
510
+ if (output.content.length > 0) {
511
+ throw new Error("Anthropic performed an unsupported mid-output model fallback");
512
+ }
513
+ continue;
514
+ }
515
+ if (event.content_block.type === "text") {
516
+ const block = {
517
+ type: "text",
518
+ text: event.content_block.text ?? "",
519
+ index: event.index
520
+ };
521
+ output.content.push(block);
522
+ stream2.push({ type: "text_start", contentIndex: output.content.length - 1, partial: output });
523
+ } else if (event.content_block.type === "thinking") {
524
+ const block = {
525
+ type: "thinking",
526
+ thinking: event.content_block.thinking ?? "",
527
+ thinkingSignature: event.content_block.signature ?? "",
528
+ index: event.index
529
+ };
530
+ output.content.push(block);
531
+ stream2.push({ type: "thinking_start", contentIndex: output.content.length - 1, partial: output });
532
+ } else if (event.content_block.type === "redacted_thinking") {
533
+ const block = {
534
+ type: "thinking",
535
+ thinking: "[Reasoning redacted]",
536
+ thinkingSignature: event.content_block.data,
537
+ redacted: true,
538
+ index: event.index
539
+ };
540
+ output.content.push(block);
541
+ stream2.push({ type: "thinking_start", contentIndex: output.content.length - 1, partial: output });
542
+ } else if (event.content_block.type === "tool_use") {
543
+ const block = {
544
+ type: "toolCall",
545
+ id: event.content_block.id,
546
+ name: isOAuth ? fromClaudeCodeName(event.content_block.name, currentTools) : event.content_block.name,
547
+ arguments: event.content_block.input ?? {},
548
+ partialJson: "",
549
+ index: event.index
550
+ };
551
+ output.content.push(block);
552
+ stream2.push({ type: "toolcall_start", contentIndex: output.content.length - 1, partial: output });
553
+ }
554
+ } else if (event.type === "content_block_delta") {
555
+ if (event.delta.type === "text_delta") {
556
+ const index = blocks.findIndex((b) => b.index === event.index);
557
+ const block = blocks[index];
558
+ if (block && block.type === "text") {
559
+ block.text += event.delta.text;
560
+ stream2.push({
561
+ type: "text_delta",
562
+ contentIndex: index,
563
+ delta: event.delta.text,
564
+ partial: output
565
+ });
566
+ }
567
+ } else if (event.delta.type === "thinking_delta") {
568
+ const index = blocks.findIndex((b) => b.index === event.index);
569
+ const block = blocks[index];
570
+ if (block && block.type === "thinking") {
571
+ block.thinking += event.delta.thinking;
572
+ stream2.push({
573
+ type: "thinking_delta",
574
+ contentIndex: index,
575
+ delta: event.delta.thinking,
576
+ partial: output
577
+ });
578
+ }
579
+ } else if (event.delta.type === "input_json_delta") {
580
+ const index = blocks.findIndex((b) => b.index === event.index);
581
+ const block = blocks[index];
582
+ if (block && block.type === "toolCall") {
583
+ block.partialJson += event.delta.partial_json;
584
+ block.arguments = parseStreamingJson(block.partialJson);
585
+ stream2.push({
586
+ type: "toolcall_delta",
587
+ contentIndex: index,
588
+ delta: event.delta.partial_json,
589
+ partial: output
590
+ });
591
+ }
592
+ } else if (event.delta.type === "signature_delta") {
593
+ const index = blocks.findIndex((b) => b.index === event.index);
594
+ const block = blocks[index];
595
+ if (block && block.type === "thinking") {
596
+ block.thinkingSignature = block.thinkingSignature || "";
597
+ block.thinkingSignature += event.delta.signature;
598
+ }
599
+ }
600
+ } else if (event.type === "content_block_stop") {
601
+ const index = blocks.findIndex((b) => b.index === event.index);
602
+ const block = blocks[index];
603
+ if (block) {
604
+ delete block.index;
605
+ if (block.type === "text") {
606
+ stream2.push({
607
+ type: "text_end",
608
+ contentIndex: index,
609
+ content: block.text,
610
+ partial: output
611
+ });
612
+ } else if (block.type === "thinking") {
613
+ stream2.push({
614
+ type: "thinking_end",
615
+ contentIndex: index,
616
+ content: block.thinking,
617
+ partial: output
618
+ });
619
+ } else if (block.type === "toolCall") {
620
+ Object.assign(block, parseToolCallArguments(block.partialJson));
621
+ delete block.partialJson;
622
+ stream2.push({
623
+ type: "toolcall_end",
624
+ contentIndex: index,
625
+ toolCall: block,
626
+ partial: output
627
+ });
628
+ }
629
+ }
630
+ } else if (event.type === "message_delta") {
631
+ const transformations = event.input_transformations;
632
+ if (Array.isArray(transformations))
633
+ inputTransformations = transformations;
634
+ if (event.delta.stop_reason) {
635
+ output.rawStopReason = event.delta.stop_reason;
636
+ const stopReasonResult = mapStopReason(event.delta.stop_reason, event.delta.stop_details);
637
+ output.stopReason = stopReasonResult.stopReason;
638
+ if (stopReasonResult.errorMessage) {
639
+ output.errorMessage = stopReasonResult.errorMessage;
640
+ }
641
+ }
642
+ if (event.usage) {
643
+ if (event.usage.input_tokens != null) {
644
+ output.usage.input = event.usage.input_tokens;
645
+ }
646
+ if (event.usage.output_tokens != null) {
647
+ output.usage.output = event.usage.output_tokens;
648
+ }
649
+ if (event.usage.cache_read_input_tokens != null) {
650
+ output.usage.cacheRead = event.usage.cache_read_input_tokens;
651
+ }
652
+ if (event.usage.cache_creation_input_tokens != null) {
653
+ output.usage.cacheWrite = event.usage.cache_creation_input_tokens;
654
+ }
655
+ const cacheCreation = event.usage.cache_creation;
656
+ if (cacheCreation?.ephemeral_1h_input_tokens != null) {
657
+ output.usage.cacheWrite1h = cacheCreation.ephemeral_1h_input_tokens;
658
+ }
659
+ const thinkingTokens = event.usage.output_tokens_details?.thinking_tokens;
660
+ if (thinkingTokens != null) {
661
+ output.usage.reasoning = thinkingTokens;
662
+ }
663
+ }
664
+ output.usage.totalTokens = output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
665
+ calculateCost(usageModel, output.usage);
666
+ }
667
+ }
668
+ if (options?.signal?.aborted) {
669
+ throw new Error("Request was aborted");
670
+ }
671
+ if (output.stopReason === "pending") {
672
+ throw new Error("Anthropic stream ended without a stop reason");
673
+ }
674
+ if (output.stopReason === "aborted" || output.stopReason === "error") {
675
+ throw new Error(output.errorMessage || "An unknown error occurred");
676
+ }
677
+ if (inputTransformations && inputTransformations.length > 0) {
678
+ appendAssistantMessageDiagnostic(output, {
679
+ type: "anthropic_input_transformations",
680
+ timestamp: Date.now(),
681
+ details: {
682
+ transformations: inputTransformations.map((transformation) => ({
683
+ type: transformation.type ?? void 0,
684
+ path: transformation.path ?? void 0,
685
+ reason: transformation.reason ?? void 0
686
+ }))
687
+ }
688
+ });
689
+ }
690
+ stream2.push({ type: "done", reason: output.stopReason, message: output });
691
+ stream2.end();
692
+ } catch (error) {
693
+ for (const block of output.content) {
694
+ delete block.index;
695
+ delete block.partialJson;
696
+ }
697
+ output.stopReason = options?.signal?.aborted ? "aborted" : "error";
698
+ output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
699
+ stream2.push({ type: "error", reason: output.stopReason, error: output });
700
+ stream2.end();
701
+ }
702
+ })();
703
+ return stream2;
704
+ }, "stream");
705
+ function mapThinkingLevelToEffort(model, level) {
706
+ const mapped = level ? model.thinkingLevelMap?.[level] : void 0;
707
+ if (typeof mapped === "string")
708
+ return mapped;
709
+ switch (level) {
710
+ case "minimal":
711
+ case "low":
712
+ return "low";
713
+ case "medium":
714
+ return "medium";
715
+ case "high":
716
+ return "high";
717
+ default:
718
+ return "high";
719
+ }
720
+ }
721
+ __name(mapThinkingLevelToEffort, "mapThinkingLevelToEffort");
722
+ var streamSimple = /* @__PURE__ */ __name((model, context, options) => {
723
+ if (!getAnthropicFederation(model, options?.apiKey, options?.headers, options?.env)) {
724
+ assertRequestAuth(model.provider, options?.apiKey, options?.headers);
725
+ }
726
+ const base = {
727
+ ...buildBaseOptions(model, context, options, options?.apiKey),
728
+ toolChoice: options?.toolChoice
729
+ };
730
+ if (!options?.reasoning) {
731
+ return stream(model, context, {
732
+ ...base,
733
+ thinkingEnabled: false
734
+ });
735
+ }
736
+ if (model.compat?.forceAdaptiveThinking === true) {
737
+ const effort = mapThinkingLevelToEffort(model, options.reasoning);
738
+ return stream(model, context, {
739
+ ...base,
740
+ thinkingEnabled: true,
741
+ effort
742
+ });
743
+ }
744
+ const adjusted = adjustMaxTokensForThinking(base.maxTokens, model.maxTokens, options.reasoning, options.thinkingBudgets);
745
+ const maxTokens = clampMaxTokensToContext(model, context, adjusted.maxTokens);
746
+ return stream(model, context, {
747
+ ...base,
748
+ maxTokens,
749
+ thinkingEnabled: true,
750
+ thinkingBudgetTokens: Math.min(adjusted.thinkingBudget, Math.max(0, maxTokens - 1024))
751
+ });
752
+ }, "streamSimple");
753
+ function isOAuthToken(apiKey) {
754
+ return apiKey.includes("sk-ant-oat");
755
+ }
756
+ __name(isOAuthToken, "isOAuthToken");
757
+ function createClient(model, apiKey, optionsHeaders, fetch, dynamicHeaders, sessionId, federation) {
758
+ if (model.provider === "github-copilot") {
759
+ const client2 = new PiAnthropic({
760
+ apiKey: null,
761
+ authToken: apiKey ?? null,
762
+ baseURL: model.baseUrl,
763
+ dangerouslyAllowBrowser: true,
764
+ fetch,
765
+ defaultHeaders: mergeClientHeaders({
766
+ accept: "application/json",
767
+ "anthropic-dangerous-direct-browser-access": "true"
768
+ }, model.headers, dynamicHeaders, optionsHeaders)
769
+ });
770
+ return { client: client2, isOAuthToken: false };
771
+ }
772
+ if (apiKey && isOAuthToken(apiKey)) {
773
+ const client2 = new PiAnthropic({
774
+ apiKey: null,
775
+ authToken: apiKey,
776
+ baseURL: model.baseUrl,
777
+ dangerouslyAllowBrowser: true,
778
+ fetch,
779
+ defaultHeaders: mergeClientHeaders({
780
+ accept: "application/json",
781
+ "anthropic-dangerous-direct-browser-access": "true",
782
+ "user-agent": `claude-cli/${claudeCodeVersion}`,
783
+ "x-app": "cli"
784
+ }, model.headers, optionsHeaders)
785
+ });
786
+ return { client: client2, isOAuthToken: true };
787
+ }
788
+ const compat = getAnthropicCompat(model);
789
+ const sessionAffinityHeaders = {};
790
+ if (sessionId && compat.sendSessionAffinityHeaders) {
791
+ const header = compat.sessionAffinityFormat === "openrouter" ? "x-session-id" : "x-session-affinity";
792
+ sessionAffinityHeaders[header] = sessionId;
793
+ }
794
+ const defaultHeaders = mergeClientHeaders({
795
+ accept: "application/json",
796
+ "anthropic-dangerous-direct-browser-access": "true"
797
+ }, sessionAffinityHeaders, model.headers, optionsHeaders);
798
+ if (federation) {
799
+ const key = JSON.stringify([model.baseUrl, federation]);
800
+ if (federationClient?.key !== key || federationClient.fetch !== fetch) {
801
+ const client2 = new PiAnthropic({
802
+ apiKey: null,
803
+ authToken: null,
804
+ config: federation,
805
+ baseURL: model.baseUrl,
806
+ dangerouslyAllowBrowser: true,
807
+ fetch
808
+ });
809
+ federationClient = { key, fetch, client: client2 };
810
+ }
811
+ return { client: federationClient.client.withOptions({ defaultHeaders }), isOAuthToken: false };
812
+ }
813
+ const client = new PiAnthropic({
814
+ apiKey: apiKey ?? null,
815
+ authToken: null,
816
+ baseURL: model.baseUrl,
817
+ dangerouslyAllowBrowser: true,
818
+ fetch,
819
+ defaultHeaders
820
+ });
821
+ return { client, isOAuthToken: false };
822
+ }
823
+ __name(createClient, "createClient");
824
+ function getBetaFeatures(model, context, isOAuthToken2, nativeToolChanges, options) {
825
+ let configuredFeatures;
826
+ for (const headers of [model.headers, options?.headers]) {
827
+ for (const [name, value] of Object.entries(headers ?? {})) {
828
+ if (name.toLowerCase() === "anthropic-beta")
829
+ configuredFeatures = value;
830
+ }
831
+ }
832
+ if (configuredFeatures === null)
833
+ return [];
834
+ if (configuredFeatures !== void 0) {
835
+ return [
836
+ ...new Set(configuredFeatures.split(",").map((feature) => feature.trim()).filter((feature) => feature.length > 0))
837
+ ];
838
+ }
839
+ const features = [];
840
+ if (isOAuthToken2)
841
+ features.push("claude-code-20250219", "oauth-2025-04-20");
842
+ if (shouldUseFineGrainedToolStreamingBeta(model, context))
843
+ features.push(FINE_GRAINED_TOOL_STREAMING_BETA);
844
+ if (model.reasoning && options?.thinkingEnabled === true && (options.interleavedThinking ?? true) && model.compat?.forceAdaptiveThinking !== true) {
845
+ features.push(INTERLEAVED_THINKING_BETA);
846
+ }
847
+ if (shouldUseServerSideFallbackBeta(model))
848
+ features.push(SERVER_SIDE_FALLBACK_BETA);
849
+ if (model.compat?.supportsMidConvoEffort === true) {
850
+ features.push(MID_CONVERSATION_OUTPUT_CONFIG_BETA, THINKING_BINDING_CONTROLS_BETA);
851
+ }
852
+ if (nativeToolChanges)
853
+ features.push(INLINE_TOOLS_BETA);
854
+ return [...new Set(features)];
855
+ }
856
+ __name(getBetaFeatures, "getBetaFeatures");
857
+ function buildParams(model, context, isOAuthToken2, options, disablePreferredStrictTools = false) {
858
+ const { cacheControl } = getCacheControl(model, options?.cacheRetention, options?.env);
859
+ const compat = getAnthropicCompat(model);
860
+ const initialSystemMessage = getInitialSystemMessage(context.messages);
861
+ const initialSystemText = initialSystemMessage ? getSystemMessageText(initialSystemMessage) : "";
862
+ const transformedMessages = transformMessages(context.messages, model, normalizeToolCallId);
863
+ const conversationMessages = initialSystemMessage ? transformedMessages.slice(1) : transformedMessages;
864
+ let hasPreferredStrictTools = false;
865
+ const convertToolDefinitions = /* @__PURE__ */ __name((tools, toolCacheControl2) => {
866
+ const definitions = convertTools(tools, isOAuthToken2, compat.supportsEagerToolInputStreaming, compat.supportsStrictTools, toolCacheControl2, disablePreferredStrictTools);
867
+ if (definitions.some((definition, index) => {
868
+ const config = tools[index].constrainedSampling;
869
+ return definition.strict === true && config && config.type === "json_schema" && config.strict === "prefer";
870
+ })) {
871
+ hasPreferredStrictTools = true;
872
+ }
873
+ return definitions;
874
+ }, "convertToolDefinitions");
875
+ const initialTools = initialSystemMessage?.toolsAdded ?? [];
876
+ const nativeToolChanges = compat.supportsMidConvoSystemMessages && compat.supportsMidConvoToolChanges && initialTools.length > 0;
877
+ const thinkingDisabled = model.reasoning && options?.thinkingEnabled === false && model.thinkingLevelMap?.off !== null;
878
+ const effortMessages = model.compat?.supportsMidConvoEffort === true && !thinkingDisabled;
879
+ const converted = convertMessages(conversationMessages, isOAuthToken2, cacheControl, compat.allowEmptySignature, effortMessages ? model.provider : void 0, nativeToolChanges ? convertToolDefinitions : void 0);
880
+ const activeEffort = options?.effort ?? "high";
881
+ const betaFeatures = getBetaFeatures(model, context, isOAuthToken2, nativeToolChanges, options);
882
+ const params = {
883
+ model: model.id,
884
+ messages: effortMessages ? insertThinkingLevelMessages(converted, activeEffort) : converted.messages,
885
+ max_tokens: options?.maxTokens ?? model.maxTokens,
886
+ stream: true,
887
+ ...betaFeatures.length > 0 ? { betas: betaFeatures } : {}
888
+ };
889
+ if (isOAuthToken2) {
890
+ params.system = [
891
+ {
892
+ type: "text",
893
+ text: "You are Claude Code, Anthropic's official CLI for Claude.",
894
+ ...cacheControl ? { cache_control: cacheControl } : {}
895
+ }
896
+ ];
897
+ if (initialSystemText) {
898
+ params.system.push({
899
+ type: "text",
900
+ text: sanitizeSurrogates(initialSystemText),
901
+ ...cacheControl ? { cache_control: cacheControl } : {}
902
+ });
903
+ }
904
+ } else if (initialSystemText) {
905
+ params.system = [
906
+ {
907
+ type: "text",
908
+ text: sanitizeSurrogates(initialSystemText),
909
+ ...cacheControl ? { cache_control: cacheControl } : {}
910
+ }
911
+ ];
912
+ }
913
+ if (options?.temperature !== void 0 && !options?.thinkingEnabled && model.compat?.supportsMidConvoEffort !== true && compat.supportsTemperature) {
914
+ params.temperature = options.temperature;
915
+ }
916
+ const toolCacheControl = compat.supportsCacheControlOnTools ? cacheControl : void 0;
917
+ if (nativeToolChanges) {
918
+ params.tools = [...convertToolDefinitions(initialTools, toolCacheControl), DEFERRED_TOOL_PLACEHOLDER];
919
+ } else {
920
+ const tools = getCurrentTools(context.messages);
921
+ if (tools.length > 0) {
922
+ params.tools = convertToolDefinitions(tools, toolCacheControl);
923
+ }
924
+ }
925
+ if (thinkingDisabled) {
926
+ params.thinking = { type: "disabled" };
927
+ } else if (effortMessages) {
928
+ params.thinking = {
929
+ type: "adaptive",
930
+ display: options?.thinkingDisplay ?? "summarized",
931
+ block_binding: { prefix_mismatch_behavior: "drop_block" }
932
+ };
933
+ params.output_config = { effort: "high" };
934
+ } else if (model.reasoning && options?.thinkingEnabled) {
935
+ const display = options.thinkingDisplay ?? "summarized";
936
+ if (model.compat?.forceAdaptiveThinking === true) {
937
+ params.thinking = { type: "adaptive", display };
938
+ if (options.effort) {
939
+ params.output_config = { effort: options.effort };
940
+ }
941
+ } else {
942
+ params.thinking = {
943
+ type: "enabled",
944
+ budget_tokens: options.thinkingBudgetTokens || 1024,
945
+ display
946
+ };
947
+ }
948
+ }
949
+ if (options?.metadata) {
950
+ const userId = options.metadata.user_id;
951
+ if (typeof userId === "string") {
952
+ params.metadata = { user_id: userId };
953
+ }
954
+ }
955
+ if (options?.toolChoice) {
956
+ if (typeof options.toolChoice === "string") {
957
+ params.tool_choice = { type: options.toolChoice };
958
+ } else {
959
+ params.tool_choice = options.toolChoice;
960
+ }
961
+ }
962
+ const allowedFallbackModels = model.compat?.allowedFallbackModels;
963
+ if (allowedFallbackModels && allowedFallbackModels.length > 0) {
964
+ params.fallbacks = allowedFallbackModels.map((fallback) => ({ model: fallback.model }));
965
+ }
966
+ return { params, hasPreferredStrictTools, providerThinkingLevel: effortMessages ? activeEffort : void 0 };
967
+ }
968
+ __name(buildParams, "buildParams");
969
+ function normalizeToolCallId(id) {
970
+ return id.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64);
971
+ }
972
+ __name(normalizeToolCallId, "normalizeToolCallId");
973
+ function convertToolResult(msg, content = msg.content) {
974
+ return {
975
+ type: "tool_result",
976
+ tool_use_id: msg.toolCallId,
977
+ content: convertContentBlocks(content),
978
+ is_error: msg.isError
979
+ };
980
+ }
981
+ __name(convertToolResult, "convertToolResult");
982
+ function convertMessages(transformedMessages, isOAuthToken2, cacheControl, allowEmptySignature = false, managedProvider, convertToolDefinitions) {
983
+ const params = [];
984
+ const assistantLevels = /* @__PURE__ */ new Map();
985
+ const pendingSystemMessages = [];
986
+ const flushPendingSystemMessages = /* @__PURE__ */ __name(() => {
987
+ params.push(...pendingSystemMessages);
988
+ pendingSystemMessages.length = 0;
989
+ }, "flushPendingSystemMessages");
990
+ for (let i = 0; i < transformedMessages.length; i++) {
991
+ const msg = transformedMessages[i];
992
+ if (msg.role === "system") {
993
+ const text = renderSystemMessageUpdate(msg);
994
+ const blocks = [];
995
+ if (text.length > 0)
996
+ blocks.push({ type: "text", text: sanitizeSurrogates(text) });
997
+ if (convertToolDefinitions) {
998
+ const added = msg.toolsAdded ?? [];
999
+ const redefined = new Set(added.map((tool) => tool.name));
1000
+ for (const tool of msg.toolsRemoved ?? []) {
1001
+ if (redefined.has(tool.name))
1002
+ continue;
1003
+ blocks.push({
1004
+ type: "tool_removal",
1005
+ tool: { type: "tool_reference", name: isOAuthToken2 ? toClaudeCodeName(tool.name) : tool.name }
1006
+ });
1007
+ }
1008
+ for (const definition of convertToolDefinitions(added)) {
1009
+ blocks.push({ type: "tool_addition", tool: { type: "tool_definition", definition } });
1010
+ }
1011
+ }
1012
+ if (blocks.length > 0)
1013
+ pendingSystemMessages.push({ role: "system", content: blocks });
1014
+ } else if (msg.role === "user") {
1015
+ if (typeof msg.content === "string") {
1016
+ if (msg.content.trim().length > 0) {
1017
+ params.push({
1018
+ role: "user",
1019
+ content: sanitizeSurrogates(msg.content)
1020
+ });
1021
+ }
1022
+ } else {
1023
+ const blocks = msg.content.map((item) => {
1024
+ if (item.type === "text") {
1025
+ return {
1026
+ type: "text",
1027
+ text: sanitizeSurrogates(item.text)
1028
+ };
1029
+ } else {
1030
+ return convertImageBlock(item);
1031
+ }
1032
+ });
1033
+ const filteredBlocks = blocks.filter((b) => {
1034
+ if (b.type === "text") {
1035
+ return b.text.trim().length > 0;
1036
+ }
1037
+ return true;
1038
+ });
1039
+ if (filteredBlocks.length === 0)
1040
+ continue;
1041
+ params.push({
1042
+ role: "user",
1043
+ content: filteredBlocks
1044
+ });
1045
+ }
1046
+ } else if (msg.role === "assistant") {
1047
+ flushPendingSystemMessages();
1048
+ const blocks = [];
1049
+ for (const block of msg.content) {
1050
+ if (block.type === "text") {
1051
+ if (block.text.trim().length === 0)
1052
+ continue;
1053
+ blocks.push({
1054
+ type: "text",
1055
+ text: sanitizeSurrogates(block.text)
1056
+ });
1057
+ } else if (block.type === "thinking") {
1058
+ if (block.redacted) {
1059
+ blocks.push({
1060
+ type: "redacted_thinking",
1061
+ data: block.thinkingSignature
1062
+ });
1063
+ continue;
1064
+ }
1065
+ const thinkingSignature = block.thinkingSignature;
1066
+ const hasThinkingSignature = !!thinkingSignature && thinkingSignature.trim().length > 0;
1067
+ if (block.thinking.trim().length === 0 && !hasThinkingSignature)
1068
+ continue;
1069
+ if (!hasThinkingSignature) {
1070
+ blocks.push(allowEmptySignature ? {
1071
+ type: "thinking",
1072
+ thinking: sanitizeSurrogates(block.thinking),
1073
+ signature: ""
1074
+ } : {
1075
+ type: "text",
1076
+ text: sanitizeSurrogates(block.thinking)
1077
+ });
1078
+ } else {
1079
+ blocks.push({
1080
+ type: "thinking",
1081
+ thinking: sanitizeSurrogates(block.thinking),
1082
+ signature: thinkingSignature
1083
+ });
1084
+ }
1085
+ } else if (block.type === "toolCall") {
1086
+ blocks.push({
1087
+ type: "tool_use",
1088
+ id: block.id,
1089
+ name: isOAuthToken2 ? toClaudeCodeName(block.name) : block.name,
1090
+ input: block.arguments ?? {}
1091
+ });
1092
+ }
1093
+ }
1094
+ if (blocks.length === 0)
1095
+ continue;
1096
+ const messageIndex = params.length;
1097
+ params.push({
1098
+ role: "assistant",
1099
+ content: blocks
1100
+ });
1101
+ if (managedProvider !== void 0 && msg.api === "anthropic-messages" && msg.provider === managedProvider && isAnthropicEffort(msg.providerThinkingLevel)) {
1102
+ assistantLevels.set(messageIndex, msg.providerThinkingLevel);
1103
+ }
1104
+ } else if (msg.role === "toolResult") {
1105
+ const toolResults = [];
1106
+ const errorImages = [];
1107
+ let j = i;
1108
+ while (j < transformedMessages.length && transformedMessages[j].role === "toolResult") {
1109
+ const toolMsg = transformedMessages[j];
1110
+ const split = splitErrorToolResultImages(toolMsg);
1111
+ toolResults.push(convertToolResult(toolMsg, split?.content));
1112
+ if (split) {
1113
+ errorImages.push({ type: "text", text: split.caption }, ...split.images.map(convertImageBlock));
1114
+ }
1115
+ j++;
1116
+ }
1117
+ i = j - 1;
1118
+ params.push({
1119
+ role: "user",
1120
+ content: [...toolResults, ...errorImages]
1121
+ });
1122
+ }
1123
+ }
1124
+ flushPendingSystemMessages();
1125
+ if (cacheControl && params.length > 0) {
1126
+ const lastMessage = params[params.length - 1];
1127
+ if (lastMessage.role === "user" || lastMessage.role === "system") {
1128
+ if (Array.isArray(lastMessage.content)) {
1129
+ const lastBlock = lastMessage.content[lastMessage.content.length - 1];
1130
+ if (lastBlock && (lastBlock.type === "text" || lastBlock.type === "image" || lastBlock.type === "tool_result" || lastBlock.type === "tool_addition" || lastBlock.type === "tool_removal")) {
1131
+ lastBlock.cache_control = cacheControl;
1132
+ }
1133
+ } else if (typeof lastMessage.content === "string") {
1134
+ lastMessage.content = [
1135
+ {
1136
+ type: "text",
1137
+ text: lastMessage.content,
1138
+ cache_control: cacheControl
1139
+ }
1140
+ ];
1141
+ }
1142
+ }
1143
+ }
1144
+ return { messages: params, assistantLevels };
1145
+ }
1146
+ __name(convertMessages, "convertMessages");
1147
+ function isAnthropicEffort(value) {
1148
+ return value === "low" || value === "medium" || value === "high" || value === "xhigh" || value === "max";
1149
+ }
1150
+ __name(isAnthropicEffort, "isAnthropicEffort");
1151
+ function insertThinkingLevelMessages(converted, activeEffort) {
1152
+ const messages = [];
1153
+ for (let index = 0; index < converted.messages.length; index++) {
1154
+ const historicalEffort = converted.assistantLevels.get(index);
1155
+ if (historicalEffort !== void 0) {
1156
+ messages.push({ role: "system", content: [], output_config: { effort: historicalEffort } });
1157
+ }
1158
+ messages.push(converted.messages[index]);
1159
+ }
1160
+ messages.push({ role: "system", content: [], output_config: { effort: activeEffort } });
1161
+ return messages;
1162
+ }
1163
+ __name(insertThinkingLevelMessages, "insertThinkingLevelMessages");
1164
+ function shouldUseFineGrainedToolStreamingBeta(model, context) {
1165
+ return getCurrentTools(context.messages).length > 0 && !getAnthropicCompat(model).supportsEagerToolInputStreaming;
1166
+ }
1167
+ __name(shouldUseFineGrainedToolStreamingBeta, "shouldUseFineGrainedToolStreamingBeta");
1168
+ var ANTHROPIC_STRICT_UNSUPPORTED_KEYWORDS = /* @__PURE__ */ new Set([
1169
+ "minimum",
1170
+ "maximum",
1171
+ "exclusiveMinimum",
1172
+ "exclusiveMaximum",
1173
+ "multipleOf",
1174
+ "maxItems",
1175
+ "uniqueItems",
1176
+ "minContains",
1177
+ "maxContains",
1178
+ "minProperties",
1179
+ "maxProperties"
1180
+ ]);
1181
+ var ANTHROPIC_STRICT_STRING_FORMATS = /* @__PURE__ */ new Set([
1182
+ "date-time",
1183
+ "time",
1184
+ "date",
1185
+ "duration",
1186
+ "email",
1187
+ "hostname",
1188
+ "uri",
1189
+ "ipv4",
1190
+ "ipv6",
1191
+ "uuid"
1192
+ ]);
1193
+ var isAnthropicStrictUnsupportedKeyword = /* @__PURE__ */ __name((key, value) => {
1194
+ if (ANTHROPIC_STRICT_UNSUPPORTED_KEYWORDS.has(key))
1195
+ return true;
1196
+ if (key === "minItems")
1197
+ return value !== 0 && value !== 1;
1198
+ if (key === "format")
1199
+ return typeof value !== "string" || !ANTHROPIC_STRICT_STRING_FORMATS.has(value);
1200
+ return false;
1201
+ }, "isAnthropicStrictUnsupportedKeyword");
1202
+ function convertTools(tools, isOAuthToken2, supportsEagerToolInputStreaming, supportsStrictTools, cacheControl, disablePreferredStrictTools = false) {
1203
+ if (!tools)
1204
+ return [];
1205
+ return tools.map((tool, index) => {
1206
+ const config = tool.constrainedSampling;
1207
+ const strict = disablePreferredStrictTools && config && config.type === "json_schema" && config.strict === "prefer" ? void 0 : resolveJsonSchemaStrictSampling(tool, supportsStrictTools, isAnthropicStrictUnsupportedKeyword);
1208
+ const parameters = getJsonSchemaToolParameters(tool, strict);
1209
+ const schema = parameters;
1210
+ const legacyInputSchema = {
1211
+ type: "object",
1212
+ properties: schema.properties ?? {},
1213
+ required: schema.required ?? []
1214
+ };
1215
+ const inputSchema = strict === true ? {
1216
+ ...parameters,
1217
+ ...legacyInputSchema
1218
+ } : legacyInputSchema;
1219
+ return {
1220
+ name: isOAuthToken2 ? toClaudeCodeName(tool.name) : tool.name,
1221
+ description: tool.description,
1222
+ ...supportsEagerToolInputStreaming ? { eager_input_streaming: true } : {},
1223
+ ...strict === true ? { strict: true } : {},
1224
+ input_schema: inputSchema,
1225
+ ...cacheControl && index === tools.length - 1 ? { cache_control: cacheControl } : {}
1226
+ };
1227
+ });
1228
+ }
1229
+ __name(convertTools, "convertTools");
1230
+ function mapStopReason(reason, stopDetails) {
1231
+ switch (reason) {
1232
+ case "end_turn":
1233
+ return { stopReason: "stop" };
1234
+ case "max_tokens":
1235
+ return { stopReason: "length" };
1236
+ case "tool_use":
1237
+ return { stopReason: "toolUse" };
1238
+ case "refusal":
1239
+ return {
1240
+ stopReason: "error",
1241
+ errorMessage: stopDetails?.explanation || `The model refused to complete the request`
1242
+ };
1243
+ case "pause_turn":
1244
+ return { stopReason: "stop" };
1245
+ case "stop_sequence":
1246
+ return { stopReason: "stop" };
1247
+ // We don't supply stop sequences, so this should never happen
1248
+ case "sensitive":
1249
+ return { stopReason: "error", errorMessage: "Provider stopped with: sensitive" };
1250
+ default:
1251
+ throw new Error(`Unhandled stop reason: ${reason}`);
1252
+ }
1253
+ }
1254
+ __name(mapStopReason, "mapStopReason");
1255
+ export {
1256
+ stream,
1257
+ streamSimple
1258
+ };