indusagi 0.1.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 (422) hide show
  1. package/README.md +27 -0
  2. package/dist/agent/agent-loop.d.ts +21 -0
  3. package/dist/agent/agent-loop.d.ts.map +1 -0
  4. package/dist/agent/agent-loop.js +307 -0
  5. package/dist/agent/agent.d.ts +122 -0
  6. package/dist/agent/agent.d.ts.map +1 -0
  7. package/dist/agent/agent.js +347 -0
  8. package/dist/agent/index.d.ts +5 -0
  9. package/dist/agent/index.d.ts.map +1 -0
  10. package/dist/agent/index.js +8 -0
  11. package/dist/agent/proxy.d.ts +85 -0
  12. package/dist/agent/proxy.d.ts.map +1 -0
  13. package/dist/agent/proxy.js +267 -0
  14. package/dist/agent/types.d.ts +178 -0
  15. package/dist/agent/types.d.ts.map +1 -0
  16. package/dist/agent/types.js +1 -0
  17. package/dist/agent.d.ts +2 -0
  18. package/dist/agent.d.ts.map +1 -0
  19. package/dist/agent.js +1 -0
  20. package/dist/ai/api-registry.d.ts +20 -0
  21. package/dist/ai/api-registry.d.ts.map +1 -0
  22. package/dist/ai/api-registry.js +43 -0
  23. package/dist/ai/cli.d.ts +3 -0
  24. package/dist/ai/cli.d.ts.map +1 -0
  25. package/dist/ai/cli.js +115 -0
  26. package/dist/ai/env-api-keys.d.ts +9 -0
  27. package/dist/ai/env-api-keys.d.ts.map +1 -0
  28. package/dist/ai/env-api-keys.js +90 -0
  29. package/dist/ai/index.d.ts +20 -0
  30. package/dist/ai/index.d.ts.map +1 -0
  31. package/dist/ai/index.js +19 -0
  32. package/dist/ai/models.d.ts +21 -0
  33. package/dist/ai/models.d.ts.map +1 -0
  34. package/dist/ai/models.generated.d.ts +11500 -0
  35. package/dist/ai/models.generated.d.ts.map +1 -0
  36. package/dist/ai/models.generated.js +11350 -0
  37. package/dist/ai/models.js +47 -0
  38. package/dist/ai/providers/amazon-bedrock.d.ts +15 -0
  39. package/dist/ai/providers/amazon-bedrock.d.ts.map +1 -0
  40. package/dist/ai/providers/amazon-bedrock.js +510 -0
  41. package/dist/ai/providers/anthropic.d.ts +13 -0
  42. package/dist/ai/providers/anthropic.d.ts.map +1 -0
  43. package/dist/ai/providers/anthropic.js +584 -0
  44. package/dist/ai/providers/azure-openai-responses.d.ts +15 -0
  45. package/dist/ai/providers/azure-openai-responses.d.ts.map +1 -0
  46. package/dist/ai/providers/azure-openai-responses.js +183 -0
  47. package/dist/ai/providers/google-gemini-cli.d.ts +74 -0
  48. package/dist/ai/providers/google-gemini-cli.d.ts.map +1 -0
  49. package/dist/ai/providers/google-gemini-cli.js +807 -0
  50. package/dist/ai/providers/google-shared.d.ts +64 -0
  51. package/dist/ai/providers/google-shared.d.ts.map +1 -0
  52. package/dist/ai/providers/google-shared.js +300 -0
  53. package/dist/ai/providers/google-vertex.d.ts +15 -0
  54. package/dist/ai/providers/google-vertex.d.ts.map +1 -0
  55. package/dist/ai/providers/google-vertex.js +370 -0
  56. package/dist/ai/providers/google.d.ts +13 -0
  57. package/dist/ai/providers/google.d.ts.map +1 -0
  58. package/dist/ai/providers/google.js +351 -0
  59. package/dist/ai/providers/openai-codex-responses.d.ts +9 -0
  60. package/dist/ai/providers/openai-codex-responses.d.ts.map +1 -0
  61. package/dist/ai/providers/openai-codex-responses.js +341 -0
  62. package/dist/ai/providers/openai-completions.d.ts +15 -0
  63. package/dist/ai/providers/openai-completions.d.ts.map +1 -0
  64. package/dist/ai/providers/openai-completions.js +701 -0
  65. package/dist/ai/providers/openai-responses-shared.d.ts +17 -0
  66. package/dist/ai/providers/openai-responses-shared.d.ts.map +1 -0
  67. package/dist/ai/providers/openai-responses-shared.js +423 -0
  68. package/dist/ai/providers/openai-responses.d.ts +13 -0
  69. package/dist/ai/providers/openai-responses.d.ts.map +1 -0
  70. package/dist/ai/providers/openai-responses.js +182 -0
  71. package/dist/ai/providers/register-builtins.d.ts +3 -0
  72. package/dist/ai/providers/register-builtins.d.ts.map +1 -0
  73. package/dist/ai/providers/register-builtins.js +62 -0
  74. package/dist/ai/providers/simple-options.d.ts +8 -0
  75. package/dist/ai/providers/simple-options.d.ts.map +1 -0
  76. package/dist/ai/providers/simple-options.js +31 -0
  77. package/dist/ai/providers/transform-messages.d.ts +8 -0
  78. package/dist/ai/providers/transform-messages.d.ts.map +1 -0
  79. package/dist/ai/providers/transform-messages.js +149 -0
  80. package/dist/ai/stream.d.ts +8 -0
  81. package/dist/ai/stream.d.ts.map +1 -0
  82. package/dist/ai/stream.js +34 -0
  83. package/dist/ai/types.d.ts +234 -0
  84. package/dist/ai/types.d.ts.map +1 -0
  85. package/dist/ai/types.js +1 -0
  86. package/dist/ai/utils/event-stream.d.ts +21 -0
  87. package/dist/ai/utils/event-stream.d.ts.map +1 -0
  88. package/dist/ai/utils/event-stream.js +76 -0
  89. package/dist/ai/utils/json-parse.d.ts +9 -0
  90. package/dist/ai/utils/json-parse.d.ts.map +1 -0
  91. package/dist/ai/utils/json-parse.js +28 -0
  92. package/dist/ai/utils/oauth/anthropic.d.ts +17 -0
  93. package/dist/ai/utils/oauth/anthropic.d.ts.map +1 -0
  94. package/dist/ai/utils/oauth/anthropic.js +103 -0
  95. package/dist/ai/utils/oauth/github-copilot.d.ts +30 -0
  96. package/dist/ai/utils/oauth/github-copilot.d.ts.map +1 -0
  97. package/dist/ai/utils/oauth/github-copilot.js +280 -0
  98. package/dist/ai/utils/oauth/google-antigravity.d.ts +26 -0
  99. package/dist/ai/utils/oauth/google-antigravity.d.ts.map +1 -0
  100. package/dist/ai/utils/oauth/google-antigravity.js +355 -0
  101. package/dist/ai/utils/oauth/google-gemini-cli.d.ts +26 -0
  102. package/dist/ai/utils/oauth/google-gemini-cli.d.ts.map +1 -0
  103. package/dist/ai/utils/oauth/google-gemini-cli.js +461 -0
  104. package/dist/ai/utils/oauth/index.d.ts +50 -0
  105. package/dist/ai/utils/oauth/index.d.ts.map +1 -0
  106. package/dist/ai/utils/oauth/index.js +106 -0
  107. package/dist/ai/utils/oauth/openai-codex.d.ts +34 -0
  108. package/dist/ai/utils/oauth/openai-codex.d.ts.map +1 -0
  109. package/dist/ai/utils/oauth/openai-codex.js +379 -0
  110. package/dist/ai/utils/oauth/pkce.d.ts +13 -0
  111. package/dist/ai/utils/oauth/pkce.d.ts.map +1 -0
  112. package/dist/ai/utils/oauth/pkce.js +30 -0
  113. package/dist/ai/utils/oauth/types.d.ts +47 -0
  114. package/dist/ai/utils/oauth/types.d.ts.map +1 -0
  115. package/dist/ai/utils/oauth/types.js +1 -0
  116. package/dist/ai/utils/overflow.d.ts +51 -0
  117. package/dist/ai/utils/overflow.d.ts.map +1 -0
  118. package/dist/ai/utils/overflow.js +111 -0
  119. package/dist/ai/utils/sanitize-unicode.d.ts +22 -0
  120. package/dist/ai/utils/sanitize-unicode.d.ts.map +1 -0
  121. package/dist/ai/utils/sanitize-unicode.js +25 -0
  122. package/dist/ai/utils/typebox-helpers.d.ts +17 -0
  123. package/dist/ai/utils/typebox-helpers.d.ts.map +1 -0
  124. package/dist/ai/utils/typebox-helpers.js +20 -0
  125. package/dist/ai/utils/validation.d.ts +18 -0
  126. package/dist/ai/utils/validation.d.ts.map +1 -0
  127. package/dist/ai/utils/validation.js +71 -0
  128. package/dist/ai.d.ts +2 -0
  129. package/dist/ai.d.ts.map +1 -0
  130. package/dist/ai.js +1 -0
  131. package/dist/index.d.ts +5 -0
  132. package/dist/index.d.ts.map +1 -0
  133. package/dist/index.js +4 -0
  134. package/dist/tui/autocomplete.d.ts +47 -0
  135. package/dist/tui/autocomplete.d.ts.map +1 -0
  136. package/dist/tui/autocomplete.js +474 -0
  137. package/dist/tui/components/box.d.ts +24 -0
  138. package/dist/tui/components/box.d.ts.map +1 -0
  139. package/dist/tui/components/box.js +100 -0
  140. package/dist/tui/components/cancellable-loader.d.ts +22 -0
  141. package/dist/tui/components/cancellable-loader.d.ts.map +1 -0
  142. package/dist/tui/components/cancellable-loader.js +35 -0
  143. package/dist/tui/components/editor.d.ts +171 -0
  144. package/dist/tui/components/editor.d.ts.map +1 -0
  145. package/dist/tui/components/editor.js +1540 -0
  146. package/dist/tui/components/image.d.ts +28 -0
  147. package/dist/tui/components/image.d.ts.map +1 -0
  148. package/dist/tui/components/image.js +60 -0
  149. package/dist/tui/components/input.d.ts +25 -0
  150. package/dist/tui/components/input.d.ts.map +1 -0
  151. package/dist/tui/components/input.js +297 -0
  152. package/dist/tui/components/loader.d.ts +21 -0
  153. package/dist/tui/components/loader.d.ts.map +1 -0
  154. package/dist/tui/components/loader.js +45 -0
  155. package/dist/tui/components/markdown.d.ts +89 -0
  156. package/dist/tui/components/markdown.d.ts.map +1 -0
  157. package/dist/tui/components/markdown.js +525 -0
  158. package/dist/tui/components/select-list.d.ts +32 -0
  159. package/dist/tui/components/select-list.d.ts.map +1 -0
  160. package/dist/tui/components/select-list.js +147 -0
  161. package/dist/tui/components/settings-list.d.ts +50 -0
  162. package/dist/tui/components/settings-list.d.ts.map +1 -0
  163. package/dist/tui/components/settings-list.js +176 -0
  164. package/dist/tui/components/spacer.d.ts +12 -0
  165. package/dist/tui/components/spacer.d.ts.map +1 -0
  166. package/dist/tui/components/spacer.js +21 -0
  167. package/dist/tui/components/text.d.ts +19 -0
  168. package/dist/tui/components/text.d.ts.map +1 -0
  169. package/dist/tui/components/text.js +80 -0
  170. package/dist/tui/components/truncated-text.d.ts +13 -0
  171. package/dist/tui/components/truncated-text.d.ts.map +1 -0
  172. package/dist/tui/components/truncated-text.js +47 -0
  173. package/dist/tui/editor-component.d.ts +35 -0
  174. package/dist/tui/editor-component.d.ts.map +1 -0
  175. package/dist/tui/editor-component.js +1 -0
  176. package/dist/tui/fuzzy.d.ts +16 -0
  177. package/dist/tui/fuzzy.d.ts.map +1 -0
  178. package/dist/tui/fuzzy.js +106 -0
  179. package/dist/tui/index.d.ts +23 -0
  180. package/dist/tui/index.d.ts.map +1 -0
  181. package/dist/tui/index.js +31 -0
  182. package/dist/tui/keybindings.d.ts +39 -0
  183. package/dist/tui/keybindings.d.ts.map +1 -0
  184. package/dist/tui/keybindings.js +110 -0
  185. package/dist/tui/keys.d.ts +160 -0
  186. package/dist/tui/keys.d.ts.map +1 -0
  187. package/dist/tui/keys.js +939 -0
  188. package/dist/tui/stdin-buffer.d.ts +48 -0
  189. package/dist/tui/stdin-buffer.d.ts.map +1 -0
  190. package/dist/tui/stdin-buffer.js +315 -0
  191. package/dist/tui/terminal-image.d.ts +67 -0
  192. package/dist/tui/terminal-image.d.ts.map +1 -0
  193. package/dist/tui/terminal-image.js +277 -0
  194. package/dist/tui/terminal.d.ts +63 -0
  195. package/dist/tui/terminal.d.ts.map +1 -0
  196. package/dist/tui/terminal.js +174 -0
  197. package/dist/tui/tui.d.ts +191 -0
  198. package/dist/tui/tui.d.ts.map +1 -0
  199. package/dist/tui/tui.js +881 -0
  200. package/dist/tui/utils.d.ts +78 -0
  201. package/dist/tui/utils.d.ts.map +1 -0
  202. package/dist/tui/utils.js +801 -0
  203. package/dist/tui.d.ts +2 -0
  204. package/dist/tui.d.ts.map +1 -0
  205. package/dist/tui.js +1 -0
  206. package/dist/webui/ChatPanel.d.ts +28 -0
  207. package/dist/webui/ChatPanel.d.ts.map +1 -0
  208. package/dist/webui/ChatPanel.js +192 -0
  209. package/dist/webui/components/AgentInterface.d.ts +39 -0
  210. package/dist/webui/components/AgentInterface.d.ts.map +1 -0
  211. package/dist/webui/components/AgentInterface.js +370 -0
  212. package/dist/webui/components/AttachmentTile.d.ts +12 -0
  213. package/dist/webui/components/AttachmentTile.d.ts.map +1 -0
  214. package/dist/webui/components/AttachmentTile.js +110 -0
  215. package/dist/webui/components/ConsoleBlock.d.ts +12 -0
  216. package/dist/webui/components/ConsoleBlock.d.ts.map +1 -0
  217. package/dist/webui/components/ConsoleBlock.js +83 -0
  218. package/dist/webui/components/CustomProviderCard.d.ts +17 -0
  219. package/dist/webui/components/CustomProviderCard.d.ts.map +1 -0
  220. package/dist/webui/components/CustomProviderCard.js +109 -0
  221. package/dist/webui/components/ExpandableSection.d.ts +15 -0
  222. package/dist/webui/components/ExpandableSection.d.ts.map +1 -0
  223. package/dist/webui/components/ExpandableSection.js +62 -0
  224. package/dist/webui/components/Input.d.ts +26 -0
  225. package/dist/webui/components/Input.d.ts.map +1 -0
  226. package/dist/webui/components/Input.js +56 -0
  227. package/dist/webui/components/MessageEditor.d.ts +44 -0
  228. package/dist/webui/components/MessageEditor.d.ts.map +1 -0
  229. package/dist/webui/components/MessageEditor.js +413 -0
  230. package/dist/webui/components/MessageList.d.ts +14 -0
  231. package/dist/webui/components/MessageList.d.ts.map +1 -0
  232. package/dist/webui/components/MessageList.js +103 -0
  233. package/dist/webui/components/Messages.d.ts +94 -0
  234. package/dist/webui/components/Messages.d.ts.map +1 -0
  235. package/dist/webui/components/Messages.js +351 -0
  236. package/dist/webui/components/ProviderKeyInput.d.ts +16 -0
  237. package/dist/webui/components/ProviderKeyInput.d.ts.map +1 -0
  238. package/dist/webui/components/ProviderKeyInput.js +170 -0
  239. package/dist/webui/components/SandboxedIframe.d.ts +85 -0
  240. package/dist/webui/components/SandboxedIframe.d.ts.map +1 -0
  241. package/dist/webui/components/SandboxedIframe.js +510 -0
  242. package/dist/webui/components/StreamingMessageContainer.d.ts +19 -0
  243. package/dist/webui/components/StreamingMessageContainer.d.ts.map +1 -0
  244. package/dist/webui/components/StreamingMessageContainer.js +116 -0
  245. package/dist/webui/components/ThinkingBlock.d.ts +11 -0
  246. package/dist/webui/components/ThinkingBlock.d.ts.map +1 -0
  247. package/dist/webui/components/ThinkingBlock.js +57 -0
  248. package/dist/webui/components/message-renderer-registry.d.ts +12 -0
  249. package/dist/webui/components/message-renderer-registry.d.ts.map +1 -0
  250. package/dist/webui/components/message-renderer-registry.js +11 -0
  251. package/dist/webui/components/sandbox/ArtifactsRuntimeProvider.d.ts +35 -0
  252. package/dist/webui/components/sandbox/ArtifactsRuntimeProvider.d.ts.map +1 -0
  253. package/dist/webui/components/sandbox/ArtifactsRuntimeProvider.js +188 -0
  254. package/dist/webui/components/sandbox/AttachmentsRuntimeProvider.d.ts +17 -0
  255. package/dist/webui/components/sandbox/AttachmentsRuntimeProvider.d.ts.map +1 -0
  256. package/dist/webui/components/sandbox/AttachmentsRuntimeProvider.js +63 -0
  257. package/dist/webui/components/sandbox/ConsoleRuntimeProvider.d.ts +42 -0
  258. package/dist/webui/components/sandbox/ConsoleRuntimeProvider.d.ts.map +1 -0
  259. package/dist/webui/components/sandbox/ConsoleRuntimeProvider.js +160 -0
  260. package/dist/webui/components/sandbox/FileDownloadRuntimeProvider.d.ts +30 -0
  261. package/dist/webui/components/sandbox/FileDownloadRuntimeProvider.d.ts.map +1 -0
  262. package/dist/webui/components/sandbox/FileDownloadRuntimeProvider.js +96 -0
  263. package/dist/webui/components/sandbox/RuntimeMessageBridge.d.ts +19 -0
  264. package/dist/webui/components/sandbox/RuntimeMessageBridge.d.ts.map +1 -0
  265. package/dist/webui/components/sandbox/RuntimeMessageBridge.js +73 -0
  266. package/dist/webui/components/sandbox/RuntimeMessageRouter.d.ts +65 -0
  267. package/dist/webui/components/sandbox/RuntimeMessageRouter.d.ts.map +1 -0
  268. package/dist/webui/components/sandbox/RuntimeMessageRouter.js +167 -0
  269. package/dist/webui/components/sandbox/SandboxRuntimeProvider.d.ts +48 -0
  270. package/dist/webui/components/sandbox/SandboxRuntimeProvider.d.ts.map +1 -0
  271. package/dist/webui/components/sandbox/SandboxRuntimeProvider.js +1 -0
  272. package/dist/webui/dialogs/ApiKeyPromptDialog.d.ts +15 -0
  273. package/dist/webui/dialogs/ApiKeyPromptDialog.d.ts.map +1 -0
  274. package/dist/webui/dialogs/ApiKeyPromptDialog.js +78 -0
  275. package/dist/webui/dialogs/AttachmentOverlay.d.ts +32 -0
  276. package/dist/webui/dialogs/AttachmentOverlay.d.ts.map +1 -0
  277. package/dist/webui/dialogs/AttachmentOverlay.js +575 -0
  278. package/dist/webui/dialogs/CustomProviderDialog.d.ts +25 -0
  279. package/dist/webui/dialogs/CustomProviderDialog.d.ts.map +1 -0
  280. package/dist/webui/dialogs/CustomProviderDialog.js +269 -0
  281. package/dist/webui/dialogs/ModelSelector.d.ts +27 -0
  282. package/dist/webui/dialogs/ModelSelector.d.ts.map +1 -0
  283. package/dist/webui/dialogs/ModelSelector.js +319 -0
  284. package/dist/webui/dialogs/PersistentStorageDialog.d.ts +17 -0
  285. package/dist/webui/dialogs/PersistentStorageDialog.d.ts.map +1 -0
  286. package/dist/webui/dialogs/PersistentStorageDialog.js +146 -0
  287. package/dist/webui/dialogs/ProvidersModelsTab.d.ts +20 -0
  288. package/dist/webui/dialogs/ProvidersModelsTab.d.ts.map +1 -0
  289. package/dist/webui/dialogs/ProvidersModelsTab.js +190 -0
  290. package/dist/webui/dialogs/SessionListDialog.d.ts +19 -0
  291. package/dist/webui/dialogs/SessionListDialog.d.ts.map +1 -0
  292. package/dist/webui/dialogs/SessionListDialog.js +153 -0
  293. package/dist/webui/dialogs/SettingsDialog.d.ts +30 -0
  294. package/dist/webui/dialogs/SettingsDialog.d.ts.map +1 -0
  295. package/dist/webui/dialogs/SettingsDialog.js +228 -0
  296. package/dist/webui/index.d.ts +65 -0
  297. package/dist/webui/index.d.ts.map +1 -0
  298. package/dist/webui/index.js +67 -0
  299. package/dist/webui/prompts/prompts.d.ts +11 -0
  300. package/dist/webui/prompts/prompts.d.ts.map +1 -0
  301. package/dist/webui/prompts/prompts.js +271 -0
  302. package/dist/webui/storage/app-storage.d.ts +33 -0
  303. package/dist/webui/storage/app-storage.d.ts.map +1 -0
  304. package/dist/webui/storage/app-storage.js +37 -0
  305. package/dist/webui/storage/backends/indexeddb-storage-backend.d.ts +27 -0
  306. package/dist/webui/storage/backends/indexeddb-storage-backend.d.ts.map +1 -0
  307. package/dist/webui/storage/backends/indexeddb-storage-backend.js +165 -0
  308. package/dist/webui/storage/store.d.ts +23 -0
  309. package/dist/webui/storage/store.d.ts.map +1 -0
  310. package/dist/webui/storage/store.js +25 -0
  311. package/dist/webui/storage/stores/custom-providers-store.d.ts +25 -0
  312. package/dist/webui/storage/stores/custom-providers-store.d.ts.map +1 -0
  313. package/dist/webui/storage/stores/custom-providers-store.js +34 -0
  314. package/dist/webui/storage/stores/provider-keys-store.d.ts +14 -0
  315. package/dist/webui/storage/stores/provider-keys-store.d.ts.map +1 -0
  316. package/dist/webui/storage/stores/provider-keys-store.js +26 -0
  317. package/dist/webui/storage/stores/sessions-store.d.ts +32 -0
  318. package/dist/webui/storage/stores/sessions-store.d.ts.map +1 -0
  319. package/dist/webui/storage/stores/sessions-store.js +112 -0
  320. package/dist/webui/storage/stores/settings-store.d.ts +14 -0
  321. package/dist/webui/storage/stores/settings-store.d.ts.map +1 -0
  322. package/dist/webui/storage/stores/settings-store.js +27 -0
  323. package/dist/webui/storage/types.d.ts +176 -0
  324. package/dist/webui/storage/types.d.ts.map +1 -0
  325. package/dist/webui/storage/types.js +1 -0
  326. package/dist/webui/tools/artifacts/ArtifactElement.d.ts +9 -0
  327. package/dist/webui/tools/artifacts/ArtifactElement.d.ts.map +1 -0
  328. package/dist/webui/tools/artifacts/ArtifactElement.js +10 -0
  329. package/dist/webui/tools/artifacts/ArtifactPill.d.ts +4 -0
  330. package/dist/webui/tools/artifacts/ArtifactPill.d.ts.map +1 -0
  331. package/dist/webui/tools/artifacts/ArtifactPill.js +22 -0
  332. package/dist/webui/tools/artifacts/Console.d.ts +18 -0
  333. package/dist/webui/tools/artifacts/Console.d.ts.map +1 -0
  334. package/dist/webui/tools/artifacts/Console.js +94 -0
  335. package/dist/webui/tools/artifacts/DocxArtifact.d.ts +22 -0
  336. package/dist/webui/tools/artifacts/DocxArtifact.d.ts.map +1 -0
  337. package/dist/webui/tools/artifacts/DocxArtifact.js +207 -0
  338. package/dist/webui/tools/artifacts/ExcelArtifact.d.ts +24 -0
  339. package/dist/webui/tools/artifacts/ExcelArtifact.d.ts.map +1 -0
  340. package/dist/webui/tools/artifacts/ExcelArtifact.js +215 -0
  341. package/dist/webui/tools/artifacts/GenericArtifact.d.ts +19 -0
  342. package/dist/webui/tools/artifacts/GenericArtifact.d.ts.map +1 -0
  343. package/dist/webui/tools/artifacts/GenericArtifact.js +116 -0
  344. package/dist/webui/tools/artifacts/HtmlArtifact.d.ts +27 -0
  345. package/dist/webui/tools/artifacts/HtmlArtifact.d.ts.map +1 -0
  346. package/dist/webui/tools/artifacts/HtmlArtifact.js +188 -0
  347. package/dist/webui/tools/artifacts/ImageArtifact.d.ts +20 -0
  348. package/dist/webui/tools/artifacts/ImageArtifact.d.ts.map +1 -0
  349. package/dist/webui/tools/artifacts/ImageArtifact.js +119 -0
  350. package/dist/webui/tools/artifacts/MarkdownArtifact.d.ts +19 -0
  351. package/dist/webui/tools/artifacts/MarkdownArtifact.d.ts.map +1 -0
  352. package/dist/webui/tools/artifacts/MarkdownArtifact.js +81 -0
  353. package/dist/webui/tools/artifacts/PdfArtifact.d.ts +25 -0
  354. package/dist/webui/tools/artifacts/PdfArtifact.d.ts.map +1 -0
  355. package/dist/webui/tools/artifacts/PdfArtifact.js +183 -0
  356. package/dist/webui/tools/artifacts/SvgArtifact.d.ts +18 -0
  357. package/dist/webui/tools/artifacts/SvgArtifact.d.ts.map +1 -0
  358. package/dist/webui/tools/artifacts/SvgArtifact.js +77 -0
  359. package/dist/webui/tools/artifacts/TextArtifact.d.ts +19 -0
  360. package/dist/webui/tools/artifacts/TextArtifact.d.ts.map +1 -0
  361. package/dist/webui/tools/artifacts/TextArtifact.js +143 -0
  362. package/dist/webui/tools/artifacts/artifacts-tool-renderer.d.ts +11 -0
  363. package/dist/webui/tools/artifacts/artifacts-tool-renderer.d.ts.map +1 -0
  364. package/dist/webui/tools/artifacts/artifacts-tool-renderer.js +271 -0
  365. package/dist/webui/tools/artifacts/artifacts.d.ts +63 -0
  366. package/dist/webui/tools/artifacts/artifacts.d.ts.map +1 -0
  367. package/dist/webui/tools/artifacts/artifacts.js +658 -0
  368. package/dist/webui/tools/artifacts/index.d.ts +8 -0
  369. package/dist/webui/tools/artifacts/index.d.ts.map +1 -0
  370. package/dist/webui/tools/artifacts/index.js +7 -0
  371. package/dist/webui/tools/extract-document.d.ts +24 -0
  372. package/dist/webui/tools/extract-document.d.ts.map +1 -0
  373. package/dist/webui/tools/extract-document.js +215 -0
  374. package/dist/webui/tools/index.d.ts +16 -0
  375. package/dist/webui/tools/index.d.ts.map +1 -0
  376. package/dist/webui/tools/index.js +32 -0
  377. package/dist/webui/tools/javascript-repl.d.ts +44 -0
  378. package/dist/webui/tools/javascript-repl.d.ts.map +1 -0
  379. package/dist/webui/tools/javascript-repl.js +223 -0
  380. package/dist/webui/tools/renderer-registry.d.ts +23 -0
  381. package/dist/webui/tools/renderer-registry.d.ts.map +1 -0
  382. package/dist/webui/tools/renderer-registry.js +106 -0
  383. package/dist/webui/tools/renderers/BashRenderer.d.ts +10 -0
  384. package/dist/webui/tools/renderers/BashRenderer.d.ts.map +1 -0
  385. package/dist/webui/tools/renderers/BashRenderer.js +41 -0
  386. package/dist/webui/tools/renderers/CalculateRenderer.d.ts +10 -0
  387. package/dist/webui/tools/renderers/CalculateRenderer.d.ts.map +1 -0
  388. package/dist/webui/tools/renderers/CalculateRenderer.js +44 -0
  389. package/dist/webui/tools/renderers/DefaultRenderer.d.ts +6 -0
  390. package/dist/webui/tools/renderers/DefaultRenderer.d.ts.map +1 -0
  391. package/dist/webui/tools/renderers/DefaultRenderer.js +93 -0
  392. package/dist/webui/tools/renderers/GetCurrentTimeRenderer.d.ts +10 -0
  393. package/dist/webui/tools/renderers/GetCurrentTimeRenderer.d.ts.map +1 -0
  394. package/dist/webui/tools/renderers/GetCurrentTimeRenderer.js +71 -0
  395. package/dist/webui/tools/types.d.ts +10 -0
  396. package/dist/webui/tools/types.d.ts.map +1 -0
  397. package/dist/webui/tools/types.js +1 -0
  398. package/dist/webui/utils/attachment-utils.d.ts +19 -0
  399. package/dist/webui/utils/attachment-utils.d.ts.map +1 -0
  400. package/dist/webui/utils/attachment-utils.js +414 -0
  401. package/dist/webui/utils/auth-token.d.ts +3 -0
  402. package/dist/webui/utils/auth-token.d.ts.map +1 -0
  403. package/dist/webui/utils/auth-token.js +18 -0
  404. package/dist/webui/utils/format.d.ts +6 -0
  405. package/dist/webui/utils/format.d.ts.map +1 -0
  406. package/dist/webui/utils/format.js +46 -0
  407. package/dist/webui/utils/i18n.d.ts +636 -0
  408. package/dist/webui/utils/i18n.d.ts.map +1 -0
  409. package/dist/webui/utils/i18n.js +417 -0
  410. package/dist/webui/utils/model-discovery.d.ts +38 -0
  411. package/dist/webui/utils/model-discovery.d.ts.map +1 -0
  412. package/dist/webui/utils/model-discovery.js +242 -0
  413. package/dist/webui/utils/proxy-utils.d.ts +45 -0
  414. package/dist/webui/utils/proxy-utils.d.ts.map +1 -0
  415. package/dist/webui/utils/proxy-utils.js +115 -0
  416. package/dist/webui/utils/test-sessions.d.ts +359 -0
  417. package/dist/webui/utils/test-sessions.d.ts.map +1 -0
  418. package/dist/webui/utils/test-sessions.js +2324 -0
  419. package/dist/webui.d.ts +2 -0
  420. package/dist/webui.d.ts.map +1 -0
  421. package/dist/webui.js +1 -0
  422. package/package.json +105 -0
@@ -0,0 +1,807 @@
1
+ /**
2
+ * Google Gemini CLI / Antigravity provider.
3
+ * Shared implementation for both google-gemini-cli and google-antigravity providers.
4
+ * Uses the Cloud Code Assist API endpoint to access Gemini and Claude models.
5
+ */
6
+ import { calculateCost } from "../models.js";
7
+ import { AssistantMessageEventStream } from "../utils/event-stream.js";
8
+ import { sanitizeSurrogates } from "../utils/sanitize-unicode.js";
9
+ import { convertMessages, convertTools, isThinkingPart, mapStopReasonString, mapToolChoice, retainThoughtSignature, } from "./google-shared.js";
10
+ import { buildBaseOptions, clampReasoning } from "./simple-options.js";
11
+ const DEFAULT_ENDPOINT = "https://cloudcode-pa.googleapis.com";
12
+ const ANTIGRAVITY_DAILY_ENDPOINT = "https://daily-cloudcode-pa.sandbox.googleapis.com";
13
+ const ANTIGRAVITY_ENDPOINT_FALLBACKS = [ANTIGRAVITY_DAILY_ENDPOINT, DEFAULT_ENDPOINT];
14
+ // Headers for Gemini CLI (prod endpoint)
15
+ const GEMINI_CLI_HEADERS = {
16
+ "User-Agent": "google-cloud-sdk vscode_cloudshelleditor/0.1",
17
+ "X-Goog-Api-Client": "gl-node/22.17.0",
18
+ "Client-Metadata": JSON.stringify({
19
+ ideType: "IDE_UNSPECIFIED",
20
+ platform: "PLATFORM_UNSPECIFIED",
21
+ pluginType: "GEMINI",
22
+ }),
23
+ };
24
+ // Headers for Antigravity (sandbox endpoint) - requires specific User-Agent
25
+ const ANTIGRAVITY_HEADERS = {
26
+ "User-Agent": "antigravity/1.11.5 darwin/arm64",
27
+ "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1",
28
+ "Client-Metadata": JSON.stringify({
29
+ ideType: "IDE_UNSPECIFIED",
30
+ platform: "PLATFORM_UNSPECIFIED",
31
+ pluginType: "GEMINI",
32
+ }),
33
+ };
34
+ // Antigravity system instruction (ported from CLIProxyAPI v6.6.89).
35
+ const ANTIGRAVITY_SYSTEM_INSTRUCTION = `<identity>
36
+ You are Antigravity, a powerful agentic AI coding assistant designed by the Google DeepMind team working on Advanced Agentic Coding.
37
+ You are pair programming with a USER to solve their coding task. The task may require creating a new codebase, modifying or debugging an existing codebase, or simply answering a question.
38
+ The USER will send you requests, which you must always prioritize addressing. Along with each USER request, we will attach additional metadata about their current state, such as what files they have open and where their cursor is.
39
+ This information may or may not be relevant to the coding task, it is up for you to decide.
40
+ </identity>
41
+
42
+ <tool_calling>
43
+ Call tools as you normally would. The following list provides additional guidance to help you avoid errors:
44
+ - **Absolute paths only**. When using tools that accept file path arguments, ALWAYS use the absolute file path.
45
+ </tool_calling>
46
+
47
+ <web_application_development>
48
+ ## Technology Stack
49
+ Your web applications should be built using the following technologies:
50
+ 1. **Core**: Use HTML for structure and JavaScript for logic.
51
+ 2. **Styling (CSS)**: Use Vanilla CSS for maximum flexibility and control. Avoid using TailwindCSS unless the USER explicitly requests it; in this case, first confirm which TailwindCSS version to use.
52
+ 3. **Web App**: If the USER specifies that they want a more complex web app, use a framework like Next.js or Vite. Only do this if the USER explicitly requests a web app.
53
+ 4. **New Project Creation**: If you need to use a framework for a new app, use \`npx\` with the appropriate script, but there are some rules to follow:
54
+ - Use \`npx -y\` to automatically install the script and its dependencies
55
+ - You MUST run the command with \`--help\` flag to see all available options first
56
+ - Initialize the app in the current directory with \`./\` (example: \`npx -y create-vite-app@latest ./\`)
57
+ - You should run in non-interactive mode so that the user doesn't need to input anything
58
+ 5. **Running Locally**: When running locally, use \`npm run dev\` or equivalent dev server. Only build the production bundle if the USER explicitly requests it or you are validating the code for correctness.
59
+
60
+ # Design Aesthetics
61
+ 1. **Use Rich Aesthetics**: The USER should be wowed at first glance by the design. Use best practices in modern web design (e.g. vibrant colors, dark modes, glassmorphism, and dynamic animations) to create a stunning first impression. Failure to do this is UNACCEPTABLE.
62
+ 2. **Prioritize Visual Excellence**: Implement designs that will WOW the user and feel extremely premium:
63
+ - Avoid generic colors (plain red, blue, green). Use curated, harmonious color palettes (e.g., HSL tailored colors, sleek dark modes).
64
+ - Using modern typography (e.g., from Google Fonts like Inter, Roboto, or Outfit) instead of browser defaults.
65
+ - Use smooth gradients
66
+ - Add subtle micro-animations for enhanced user experience
67
+ 3. **Use a Dynamic Design**: An interface that feels responsive and alive encourages interaction. Achieve this with hover effects and interactive elements. Micro-animations, in particular, are highly effective for improving user engagement.
68
+ 4. **Premium Designs**: Make a design that feels premium and state of the art. Avoid creating simple minimum viable products.
69
+ 5. **Don't use placeholders**: If you need an image, use your generate_image tool to create a working demonstration.
70
+
71
+ ## Implementation Workflow
72
+ Follow this systematic approach when building web applications:
73
+ 1. **Plan and Understand**:
74
+ - Fully understand the user's requirements
75
+ - Draw inspiration from modern, beautiful, and dynamic web designs
76
+ - Outline the features needed for the initial version
77
+ 2. **Build the Foundation**:
78
+ - Start by creating/modifying \`index.css\`
79
+ - Implement the core design system with all tokens and utilities
80
+ 3. **Create Components**:
81
+ - Build necessary components using your design system
82
+ - Ensure all components use predefined styles, not ad-hoc utilities
83
+ - Keep components focused and reusable
84
+ 4. **Assemble Pages**:
85
+ - Update the main application to incorporate your design and components
86
+ - Ensure proper routing and navigation
87
+ - Implement responsive layouts
88
+ 5. **Polish and Optimize**:
89
+ - Review the overall user experience
90
+ - Ensure smooth interactions and transitions
91
+ - Optimize performance where needed
92
+
93
+ ## SEO Best Practices
94
+ Automatically implement SEO best practices on every page:
95
+ - **Title Tags**: Include proper, descriptive title tags for each page
96
+ - **Meta Descriptions**: Add compelling meta descriptions that accurately summarize page content
97
+ - **Heading Structure**: Use a single \`<h1>\` per page with proper heading hierarchy
98
+ - **Semantic HTML**: Use appropriate HTML5 semantic elements
99
+ - **Unique IDs**: Ensure all interactive elements have unique, descriptive IDs for browser testing
100
+ - **Performance**: Ensure fast page load times through optimization
101
+ CRITICAL REMINDER: AESTHETICS ARE VERY IMPORTANT. If your web app looks simple and basic then you have FAILED!
102
+ </web_application_development>
103
+ <ephemeral_message>
104
+ There will be an <EPHEMERAL_MESSAGE> appearing in the conversation at times. This is not coming from the user, but instead injected by the system as important information to pay attention to.
105
+ Do not respond to nor acknowledge those messages, but do follow them strictly.
106
+ </ephemeral_message>
107
+
108
+ <communication_style>
109
+ - **Formatting**. Format your responses in github-style markdown to make your responses easier for the USER to parse. For example, use headers to organize your responses and bolded or italicized text to highlight important keywords. Use backticks to format file, directory, function, and class names. If providing a URL to the user, format this in markdown as well, for example \`[label](example.com)\`.
110
+ - **Proactiveness**. As an agent, you are allowed to be proactive, but only in the course of completing the user's task. For example, if the user asks you to add a new component, you can edit the code, verify build and test statuses, and take any other obvious follow-up actions, such as performing additional research. However, avoid surprising the user. For example, if the user asks HOW to approach something, you should answer their question and instead of jumping into editing a file.
111
+ - **Helpfulness**. Respond like a helpful software engineer who is explaining your work to a friendly collaborator on the project. Acknowledge mistakes or any backtracking you do as a result of new information.
112
+ - **Ask for clarification**. If you are unsure about the USER's intent, always ask for clarification rather than making assumptions.
113
+ </communication_style>`;
114
+ // Counter for generating unique tool call IDs
115
+ let toolCallCounter = 0;
116
+ // Retry configuration
117
+ const MAX_RETRIES = 3;
118
+ const BASE_DELAY_MS = 1000;
119
+ const MAX_EMPTY_STREAM_RETRIES = 2;
120
+ const EMPTY_STREAM_BASE_DELAY_MS = 500;
121
+ const CLAUDE_THINKING_BETA_HEADER = "interleaved-thinking-2025-05-14";
122
+ /**
123
+ * Extract retry delay from Gemini error response (in milliseconds).
124
+ * Checks headers first (Retry-After, x-ratelimit-reset, x-ratelimit-reset-after),
125
+ * then parses body patterns like:
126
+ * - "Your quota will reset after 39s"
127
+ * - "Your quota will reset after 18h31m10s"
128
+ * - "Please retry in Xs" or "Please retry in Xms"
129
+ * - "retryDelay": "34.074824224s" (JSON field)
130
+ */
131
+ export function extractRetryDelay(errorText, response) {
132
+ const normalizeDelay = (ms) => (ms > 0 ? Math.ceil(ms + 1000) : undefined);
133
+ const headers = response instanceof Headers ? response : response?.headers;
134
+ if (headers) {
135
+ const retryAfter = headers.get("retry-after");
136
+ if (retryAfter) {
137
+ const retryAfterSeconds = Number(retryAfter);
138
+ if (Number.isFinite(retryAfterSeconds)) {
139
+ const delay = normalizeDelay(retryAfterSeconds * 1000);
140
+ if (delay !== undefined) {
141
+ return delay;
142
+ }
143
+ }
144
+ const retryAfterDate = new Date(retryAfter);
145
+ const retryAfterMs = retryAfterDate.getTime();
146
+ if (!Number.isNaN(retryAfterMs)) {
147
+ const delay = normalizeDelay(retryAfterMs - Date.now());
148
+ if (delay !== undefined) {
149
+ return delay;
150
+ }
151
+ }
152
+ }
153
+ const rateLimitReset = headers.get("x-ratelimit-reset");
154
+ if (rateLimitReset) {
155
+ const resetSeconds = Number.parseInt(rateLimitReset, 10);
156
+ if (!Number.isNaN(resetSeconds)) {
157
+ const delay = normalizeDelay(resetSeconds * 1000 - Date.now());
158
+ if (delay !== undefined) {
159
+ return delay;
160
+ }
161
+ }
162
+ }
163
+ const rateLimitResetAfter = headers.get("x-ratelimit-reset-after");
164
+ if (rateLimitResetAfter) {
165
+ const resetAfterSeconds = Number(rateLimitResetAfter);
166
+ if (Number.isFinite(resetAfterSeconds)) {
167
+ const delay = normalizeDelay(resetAfterSeconds * 1000);
168
+ if (delay !== undefined) {
169
+ return delay;
170
+ }
171
+ }
172
+ }
173
+ }
174
+ // Pattern 1: "Your quota will reset after ..." (formats: "18h31m10s", "10m15s", "6s", "39s")
175
+ const durationMatch = errorText.match(/reset after (?:(\d+)h)?(?:(\d+)m)?(\d+(?:\.\d+)?)s/i);
176
+ if (durationMatch) {
177
+ const hours = durationMatch[1] ? parseInt(durationMatch[1], 10) : 0;
178
+ const minutes = durationMatch[2] ? parseInt(durationMatch[2], 10) : 0;
179
+ const seconds = parseFloat(durationMatch[3]);
180
+ if (!Number.isNaN(seconds)) {
181
+ const totalMs = ((hours * 60 + minutes) * 60 + seconds) * 1000;
182
+ const delay = normalizeDelay(totalMs);
183
+ if (delay !== undefined) {
184
+ return delay;
185
+ }
186
+ }
187
+ }
188
+ // Pattern 2: "Please retry in X[ms|s]"
189
+ const retryInMatch = errorText.match(/Please retry in ([0-9.]+)(ms|s)/i);
190
+ if (retryInMatch?.[1]) {
191
+ const value = parseFloat(retryInMatch[1]);
192
+ if (!Number.isNaN(value) && value > 0) {
193
+ const ms = retryInMatch[2].toLowerCase() === "ms" ? value : value * 1000;
194
+ const delay = normalizeDelay(ms);
195
+ if (delay !== undefined) {
196
+ return delay;
197
+ }
198
+ }
199
+ }
200
+ // Pattern 3: "retryDelay": "34.074824224s" (JSON field in error details)
201
+ const retryDelayMatch = errorText.match(/"retryDelay":\s*"([0-9.]+)(ms|s)"/i);
202
+ if (retryDelayMatch?.[1]) {
203
+ const value = parseFloat(retryDelayMatch[1]);
204
+ if (!Number.isNaN(value) && value > 0) {
205
+ const ms = retryDelayMatch[2].toLowerCase() === "ms" ? value : value * 1000;
206
+ const delay = normalizeDelay(ms);
207
+ if (delay !== undefined) {
208
+ return delay;
209
+ }
210
+ }
211
+ }
212
+ return undefined;
213
+ }
214
+ function isClaudeThinkingModel(modelId) {
215
+ const normalized = modelId.toLowerCase();
216
+ return normalized.includes("claude") && normalized.includes("thinking");
217
+ }
218
+ /**
219
+ * Check if an error is retryable (rate limit, server error, network error, etc.)
220
+ */
221
+ function isRetryableError(status, errorText) {
222
+ if (status === 429 || status === 500 || status === 502 || status === 503 || status === 504) {
223
+ return true;
224
+ }
225
+ return /resource.?exhausted|rate.?limit|overloaded|service.?unavailable|other.?side.?closed/i.test(errorText);
226
+ }
227
+ /**
228
+ * Extract a clean, user-friendly error message from Google API error response.
229
+ * Parses JSON error responses and returns just the message field.
230
+ */
231
+ function extractErrorMessage(errorText) {
232
+ try {
233
+ const parsed = JSON.parse(errorText);
234
+ if (parsed.error?.message) {
235
+ return parsed.error.message;
236
+ }
237
+ }
238
+ catch {
239
+ // Not JSON, return as-is
240
+ }
241
+ return errorText;
242
+ }
243
+ /**
244
+ * Sleep for a given number of milliseconds, respecting abort signal.
245
+ */
246
+ function sleep(ms, signal) {
247
+ return new Promise((resolve, reject) => {
248
+ if (signal?.aborted) {
249
+ reject(new Error("Request was aborted"));
250
+ return;
251
+ }
252
+ const timeout = setTimeout(resolve, ms);
253
+ signal?.addEventListener("abort", () => {
254
+ clearTimeout(timeout);
255
+ reject(new Error("Request was aborted"));
256
+ });
257
+ });
258
+ }
259
+ export const streamGoogleGeminiCli = (model, context, options) => {
260
+ const stream = new AssistantMessageEventStream();
261
+ (async () => {
262
+ const output = {
263
+ role: "assistant",
264
+ content: [],
265
+ api: "google-gemini-cli",
266
+ provider: model.provider,
267
+ model: model.id,
268
+ usage: {
269
+ input: 0,
270
+ output: 0,
271
+ cacheRead: 0,
272
+ cacheWrite: 0,
273
+ totalTokens: 0,
274
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
275
+ },
276
+ stopReason: "stop",
277
+ timestamp: Date.now(),
278
+ };
279
+ try {
280
+ // apiKey is JSON-encoded: { token, projectId }
281
+ const apiKeyRaw = options?.apiKey;
282
+ if (!apiKeyRaw) {
283
+ throw new Error("Google Cloud Code Assist requires OAuth authentication. Use /login to authenticate.");
284
+ }
285
+ let accessToken;
286
+ let projectId;
287
+ try {
288
+ const parsed = JSON.parse(apiKeyRaw);
289
+ accessToken = parsed.token;
290
+ projectId = parsed.projectId;
291
+ }
292
+ catch {
293
+ throw new Error("Invalid Google Cloud Code Assist credentials. Use /login to re-authenticate.");
294
+ }
295
+ if (!accessToken || !projectId) {
296
+ throw new Error("Missing token or projectId in Google Cloud credentials. Use /login to re-authenticate.");
297
+ }
298
+ const isAntigravity = model.provider === "google-antigravity";
299
+ const baseUrl = model.baseUrl?.trim();
300
+ const endpoints = baseUrl ? [baseUrl] : isAntigravity ? ANTIGRAVITY_ENDPOINT_FALLBACKS : [DEFAULT_ENDPOINT];
301
+ const requestBody = buildRequest(model, context, projectId, options, isAntigravity);
302
+ options?.onPayload?.(requestBody);
303
+ const headers = isAntigravity ? ANTIGRAVITY_HEADERS : GEMINI_CLI_HEADERS;
304
+ const requestHeaders = {
305
+ Authorization: `Bearer ${accessToken}`,
306
+ "Content-Type": "application/json",
307
+ Accept: "text/event-stream",
308
+ ...headers,
309
+ ...(isClaudeThinkingModel(model.id) ? { "anthropic-beta": CLAUDE_THINKING_BETA_HEADER } : {}),
310
+ ...options?.headers,
311
+ };
312
+ const requestBodyJson = JSON.stringify(requestBody);
313
+ // Fetch with retry logic for rate limits and transient errors
314
+ let response;
315
+ let lastError;
316
+ let requestUrl;
317
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
318
+ if (options?.signal?.aborted) {
319
+ throw new Error("Request was aborted");
320
+ }
321
+ try {
322
+ const endpoint = endpoints[Math.min(attempt, endpoints.length - 1)];
323
+ requestUrl = `${endpoint}/v1internal:streamGenerateContent?alt=sse`;
324
+ response = await fetch(requestUrl, {
325
+ method: "POST",
326
+ headers: requestHeaders,
327
+ body: requestBodyJson,
328
+ signal: options?.signal,
329
+ });
330
+ if (response.ok) {
331
+ break; // Success, exit retry loop
332
+ }
333
+ const errorText = await response.text();
334
+ // Check if retryable
335
+ if (attempt < MAX_RETRIES && isRetryableError(response.status, errorText)) {
336
+ // Use server-provided delay or exponential backoff
337
+ const serverDelay = extractRetryDelay(errorText, response);
338
+ const delayMs = serverDelay ?? BASE_DELAY_MS * 2 ** attempt;
339
+ await sleep(delayMs, options?.signal);
340
+ continue;
341
+ }
342
+ // Not retryable or max retries exceeded
343
+ throw new Error(`Cloud Code Assist API error (${response.status}): ${extractErrorMessage(errorText)}`);
344
+ }
345
+ catch (error) {
346
+ // Check for abort - fetch throws AbortError, our code throws "Request was aborted"
347
+ if (error instanceof Error) {
348
+ if (error.name === "AbortError" || error.message === "Request was aborted") {
349
+ throw new Error("Request was aborted");
350
+ }
351
+ }
352
+ // Extract detailed error message from fetch errors (Node includes cause)
353
+ lastError = error instanceof Error ? error : new Error(String(error));
354
+ if (lastError.message === "fetch failed" && lastError.cause instanceof Error) {
355
+ lastError = new Error(`Network error: ${lastError.cause.message}`);
356
+ }
357
+ // Network errors are retryable
358
+ if (attempt < MAX_RETRIES) {
359
+ const delayMs = BASE_DELAY_MS * 2 ** attempt;
360
+ await sleep(delayMs, options?.signal);
361
+ continue;
362
+ }
363
+ throw lastError;
364
+ }
365
+ }
366
+ if (!response || !response.ok) {
367
+ throw lastError ?? new Error("Failed to get response after retries");
368
+ }
369
+ let started = false;
370
+ const ensureStarted = () => {
371
+ if (!started) {
372
+ stream.push({ type: "start", partial: output });
373
+ started = true;
374
+ }
375
+ };
376
+ const resetOutput = () => {
377
+ output.content = [];
378
+ output.usage = {
379
+ input: 0,
380
+ output: 0,
381
+ cacheRead: 0,
382
+ cacheWrite: 0,
383
+ totalTokens: 0,
384
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
385
+ };
386
+ output.stopReason = "stop";
387
+ output.errorMessage = undefined;
388
+ output.timestamp = Date.now();
389
+ started = false;
390
+ };
391
+ const streamResponse = async (activeResponse) => {
392
+ if (!activeResponse.body) {
393
+ throw new Error("No response body");
394
+ }
395
+ let hasContent = false;
396
+ let currentBlock = null;
397
+ const blocks = output.content;
398
+ const blockIndex = () => blocks.length - 1;
399
+ // Read SSE stream
400
+ const reader = activeResponse.body.getReader();
401
+ const decoder = new TextDecoder();
402
+ let buffer = "";
403
+ // Set up abort handler to cancel reader when signal fires
404
+ const abortHandler = () => {
405
+ void reader.cancel().catch(() => { });
406
+ };
407
+ options?.signal?.addEventListener("abort", abortHandler);
408
+ try {
409
+ while (true) {
410
+ // Check abort signal before each read
411
+ if (options?.signal?.aborted) {
412
+ throw new Error("Request was aborted");
413
+ }
414
+ const { done, value } = await reader.read();
415
+ if (done)
416
+ break;
417
+ buffer += decoder.decode(value, { stream: true });
418
+ const lines = buffer.split("\n");
419
+ buffer = lines.pop() || "";
420
+ for (const line of lines) {
421
+ if (!line.startsWith("data:"))
422
+ continue;
423
+ const jsonStr = line.slice(5).trim();
424
+ if (!jsonStr)
425
+ continue;
426
+ let chunk;
427
+ try {
428
+ chunk = JSON.parse(jsonStr);
429
+ }
430
+ catch {
431
+ continue;
432
+ }
433
+ // Unwrap the response
434
+ const responseData = chunk.response;
435
+ if (!responseData)
436
+ continue;
437
+ const candidate = responseData.candidates?.[0];
438
+ if (candidate?.content?.parts) {
439
+ for (const part of candidate.content.parts) {
440
+ if (part.text !== undefined) {
441
+ hasContent = true;
442
+ const isThinking = isThinkingPart(part);
443
+ if (!currentBlock ||
444
+ (isThinking && currentBlock.type !== "thinking") ||
445
+ (!isThinking && currentBlock.type !== "text")) {
446
+ if (currentBlock) {
447
+ if (currentBlock.type === "text") {
448
+ stream.push({
449
+ type: "text_end",
450
+ contentIndex: blocks.length - 1,
451
+ content: currentBlock.text,
452
+ partial: output,
453
+ });
454
+ }
455
+ else {
456
+ stream.push({
457
+ type: "thinking_end",
458
+ contentIndex: blockIndex(),
459
+ content: currentBlock.thinking,
460
+ partial: output,
461
+ });
462
+ }
463
+ }
464
+ if (isThinking) {
465
+ currentBlock = { type: "thinking", thinking: "", thinkingSignature: undefined };
466
+ output.content.push(currentBlock);
467
+ ensureStarted();
468
+ stream.push({
469
+ type: "thinking_start",
470
+ contentIndex: blockIndex(),
471
+ partial: output,
472
+ });
473
+ }
474
+ else {
475
+ currentBlock = { type: "text", text: "" };
476
+ output.content.push(currentBlock);
477
+ ensureStarted();
478
+ stream.push({ type: "text_start", contentIndex: blockIndex(), partial: output });
479
+ }
480
+ }
481
+ if (currentBlock.type === "thinking") {
482
+ currentBlock.thinking += part.text;
483
+ currentBlock.thinkingSignature = retainThoughtSignature(currentBlock.thinkingSignature, part.thoughtSignature);
484
+ stream.push({
485
+ type: "thinking_delta",
486
+ contentIndex: blockIndex(),
487
+ delta: part.text,
488
+ partial: output,
489
+ });
490
+ }
491
+ else {
492
+ currentBlock.text += part.text;
493
+ currentBlock.textSignature = retainThoughtSignature(currentBlock.textSignature, part.thoughtSignature);
494
+ stream.push({
495
+ type: "text_delta",
496
+ contentIndex: blockIndex(),
497
+ delta: part.text,
498
+ partial: output,
499
+ });
500
+ }
501
+ }
502
+ if (part.functionCall) {
503
+ hasContent = true;
504
+ if (currentBlock) {
505
+ if (currentBlock.type === "text") {
506
+ stream.push({
507
+ type: "text_end",
508
+ contentIndex: blockIndex(),
509
+ content: currentBlock.text,
510
+ partial: output,
511
+ });
512
+ }
513
+ else {
514
+ stream.push({
515
+ type: "thinking_end",
516
+ contentIndex: blockIndex(),
517
+ content: currentBlock.thinking,
518
+ partial: output,
519
+ });
520
+ }
521
+ currentBlock = null;
522
+ }
523
+ const providedId = part.functionCall.id;
524
+ const needsNewId = !providedId ||
525
+ output.content.some((b) => b.type === "toolCall" && b.id === providedId);
526
+ const toolCallId = needsNewId
527
+ ? `${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`
528
+ : providedId;
529
+ const toolCall = {
530
+ type: "toolCall",
531
+ id: toolCallId,
532
+ name: part.functionCall.name || "",
533
+ arguments: part.functionCall.args ?? {},
534
+ ...(part.thoughtSignature && { thoughtSignature: part.thoughtSignature }),
535
+ };
536
+ output.content.push(toolCall);
537
+ ensureStarted();
538
+ stream.push({ type: "toolcall_start", contentIndex: blockIndex(), partial: output });
539
+ stream.push({
540
+ type: "toolcall_delta",
541
+ contentIndex: blockIndex(),
542
+ delta: JSON.stringify(toolCall.arguments),
543
+ partial: output,
544
+ });
545
+ stream.push({
546
+ type: "toolcall_end",
547
+ contentIndex: blockIndex(),
548
+ toolCall,
549
+ partial: output,
550
+ });
551
+ }
552
+ }
553
+ }
554
+ if (candidate?.finishReason) {
555
+ output.stopReason = mapStopReasonString(candidate.finishReason);
556
+ if (output.content.some((b) => b.type === "toolCall")) {
557
+ output.stopReason = "toolUse";
558
+ }
559
+ }
560
+ if (responseData.usageMetadata) {
561
+ // promptTokenCount includes cachedContentTokenCount, so subtract to get fresh input
562
+ const promptTokens = responseData.usageMetadata.promptTokenCount || 0;
563
+ const cacheReadTokens = responseData.usageMetadata.cachedContentTokenCount || 0;
564
+ output.usage = {
565
+ input: promptTokens - cacheReadTokens,
566
+ output: (responseData.usageMetadata.candidatesTokenCount || 0) +
567
+ (responseData.usageMetadata.thoughtsTokenCount || 0),
568
+ cacheRead: cacheReadTokens,
569
+ cacheWrite: 0,
570
+ totalTokens: responseData.usageMetadata.totalTokenCount || 0,
571
+ cost: {
572
+ input: 0,
573
+ output: 0,
574
+ cacheRead: 0,
575
+ cacheWrite: 0,
576
+ total: 0,
577
+ },
578
+ };
579
+ calculateCost(model, output.usage);
580
+ }
581
+ }
582
+ }
583
+ }
584
+ finally {
585
+ options?.signal?.removeEventListener("abort", abortHandler);
586
+ }
587
+ if (currentBlock) {
588
+ if (currentBlock.type === "text") {
589
+ stream.push({
590
+ type: "text_end",
591
+ contentIndex: blockIndex(),
592
+ content: currentBlock.text,
593
+ partial: output,
594
+ });
595
+ }
596
+ else {
597
+ stream.push({
598
+ type: "thinking_end",
599
+ contentIndex: blockIndex(),
600
+ content: currentBlock.thinking,
601
+ partial: output,
602
+ });
603
+ }
604
+ }
605
+ return hasContent;
606
+ };
607
+ let receivedContent = false;
608
+ let currentResponse = response;
609
+ for (let emptyAttempt = 0; emptyAttempt <= MAX_EMPTY_STREAM_RETRIES; emptyAttempt++) {
610
+ if (options?.signal?.aborted) {
611
+ throw new Error("Request was aborted");
612
+ }
613
+ if (emptyAttempt > 0) {
614
+ const backoffMs = EMPTY_STREAM_BASE_DELAY_MS * 2 ** (emptyAttempt - 1);
615
+ await sleep(backoffMs, options?.signal);
616
+ if (!requestUrl) {
617
+ throw new Error("Missing request URL");
618
+ }
619
+ currentResponse = await fetch(requestUrl, {
620
+ method: "POST",
621
+ headers: requestHeaders,
622
+ body: requestBodyJson,
623
+ signal: options?.signal,
624
+ });
625
+ if (!currentResponse.ok) {
626
+ const retryErrorText = await currentResponse.text();
627
+ throw new Error(`Cloud Code Assist API error (${currentResponse.status}): ${retryErrorText}`);
628
+ }
629
+ }
630
+ const streamed = await streamResponse(currentResponse);
631
+ if (streamed) {
632
+ receivedContent = true;
633
+ break;
634
+ }
635
+ if (emptyAttempt < MAX_EMPTY_STREAM_RETRIES) {
636
+ resetOutput();
637
+ }
638
+ }
639
+ if (!receivedContent) {
640
+ throw new Error("Cloud Code Assist API returned an empty response");
641
+ }
642
+ if (options?.signal?.aborted) {
643
+ throw new Error("Request was aborted");
644
+ }
645
+ if (output.stopReason === "aborted" || output.stopReason === "error") {
646
+ throw new Error("An unknown error occurred");
647
+ }
648
+ stream.push({ type: "done", reason: output.stopReason, message: output });
649
+ stream.end();
650
+ }
651
+ catch (error) {
652
+ for (const block of output.content) {
653
+ if ("index" in block) {
654
+ delete block.index;
655
+ }
656
+ }
657
+ output.stopReason = options?.signal?.aborted ? "aborted" : "error";
658
+ output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
659
+ stream.push({ type: "error", reason: output.stopReason, error: output });
660
+ stream.end();
661
+ }
662
+ })();
663
+ return stream;
664
+ };
665
+ export const streamSimpleGoogleGeminiCli = (model, context, options) => {
666
+ const apiKey = options?.apiKey;
667
+ if (!apiKey) {
668
+ throw new Error("Google Cloud Code Assist requires OAuth authentication. Use /login to authenticate.");
669
+ }
670
+ const base = buildBaseOptions(model, options, apiKey);
671
+ if (!options?.reasoning) {
672
+ return streamGoogleGeminiCli(model, context, {
673
+ ...base,
674
+ thinking: { enabled: false },
675
+ });
676
+ }
677
+ const effort = clampReasoning(options.reasoning);
678
+ if (model.id.includes("3-pro") || model.id.includes("3-flash")) {
679
+ return streamGoogleGeminiCli(model, context, {
680
+ ...base,
681
+ thinking: {
682
+ enabled: true,
683
+ level: getGeminiCliThinkingLevel(effort, model.id),
684
+ },
685
+ });
686
+ }
687
+ const defaultBudgets = {
688
+ minimal: 1024,
689
+ low: 2048,
690
+ medium: 8192,
691
+ high: 16384,
692
+ };
693
+ const budgets = { ...defaultBudgets, ...options.thinkingBudgets };
694
+ const minOutputTokens = 1024;
695
+ let thinkingBudget = budgets[effort];
696
+ const maxTokens = Math.min((base.maxTokens || 0) + thinkingBudget, model.maxTokens);
697
+ if (maxTokens <= thinkingBudget) {
698
+ thinkingBudget = Math.max(0, maxTokens - minOutputTokens);
699
+ }
700
+ return streamGoogleGeminiCli(model, context, {
701
+ ...base,
702
+ maxTokens,
703
+ thinking: {
704
+ enabled: true,
705
+ budgetTokens: thinkingBudget,
706
+ },
707
+ });
708
+ };
709
+ export function buildRequest(model, context, projectId, options = {}, isAntigravity = false) {
710
+ const contents = convertMessages(model, context);
711
+ const generationConfig = {};
712
+ if (options.temperature !== undefined) {
713
+ generationConfig.temperature = options.temperature;
714
+ }
715
+ if (options.maxTokens !== undefined) {
716
+ generationConfig.maxOutputTokens = options.maxTokens;
717
+ }
718
+ // Thinking config
719
+ if (options.thinking?.enabled && model.reasoning) {
720
+ generationConfig.thinkingConfig = {
721
+ includeThoughts: true,
722
+ };
723
+ // Gemini 3 models use thinkingLevel, older models use thinkingBudget
724
+ if (options.thinking.level !== undefined) {
725
+ // Cast to any since our GoogleThinkingLevel mirrors Google's ThinkingLevel enum values
726
+ generationConfig.thinkingConfig.thinkingLevel = options.thinking.level;
727
+ }
728
+ else if (options.thinking.budgetTokens !== undefined) {
729
+ generationConfig.thinkingConfig.thinkingBudget = options.thinking.budgetTokens;
730
+ }
731
+ }
732
+ const request = {
733
+ contents,
734
+ };
735
+ request.sessionId = options.sessionId;
736
+ // System instruction must be object with parts, not plain string
737
+ if (context.systemPrompt) {
738
+ request.systemInstruction = {
739
+ parts: [{ text: sanitizeSurrogates(context.systemPrompt) }],
740
+ };
741
+ }
742
+ if (Object.keys(generationConfig).length > 0) {
743
+ request.generationConfig = generationConfig;
744
+ }
745
+ if (context.tools && context.tools.length > 0) {
746
+ request.tools = convertTools(context.tools);
747
+ if (options.toolChoice) {
748
+ request.toolConfig = {
749
+ functionCallingConfig: {
750
+ mode: mapToolChoice(options.toolChoice),
751
+ },
752
+ };
753
+ }
754
+ }
755
+ if (isAntigravity) {
756
+ const existingText = request.systemInstruction?.parts?.[0]?.text || "";
757
+ const bridgePrompt = `# CRITICAL: Environment Override
758
+
759
+ IGNORE ALL INSTRUCTIONS ABOVE THIS LINE. The following overrides are mandatory:
760
+
761
+ - You are Pi, NOT Antigravity
762
+ - Use RELATIVE paths, never absolute paths
763
+ - IGNORE all <web_application_development> guidelines above (no glassmorphism, no "premium aesthetics", no design opinions)
764
+ - IGNORE <communication_style> above
765
+ - IGNORE <ephemeral_message> handling above
766
+ - Follow ONLY the instructions below
767
+ `;
768
+ request.systemInstruction = {
769
+ role: "user",
770
+ parts: [
771
+ {
772
+ text: `${ANTIGRAVITY_SYSTEM_INSTRUCTION}\n\n${bridgePrompt}${existingText ? `\n${existingText}` : ""}`,
773
+ },
774
+ ],
775
+ };
776
+ }
777
+ return {
778
+ project: projectId,
779
+ model: model.id,
780
+ request,
781
+ ...(isAntigravity ? { requestType: "agent" } : {}),
782
+ userAgent: isAntigravity ? "antigravity" : "pi-coding-agent",
783
+ requestId: `${isAntigravity ? "agent" : "pi"}-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,
784
+ };
785
+ }
786
+ function getGeminiCliThinkingLevel(effort, modelId) {
787
+ if (modelId.includes("3-pro")) {
788
+ switch (effort) {
789
+ case "minimal":
790
+ case "low":
791
+ return "LOW";
792
+ case "medium":
793
+ case "high":
794
+ return "HIGH";
795
+ }
796
+ }
797
+ switch (effort) {
798
+ case "minimal":
799
+ return "MINIMAL";
800
+ case "low":
801
+ return "LOW";
802
+ case "medium":
803
+ return "MEDIUM";
804
+ case "high":
805
+ return "HIGH";
806
+ }
807
+ }