indusagi-coding-agent 0.1.28 → 0.1.30

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 (147) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/LICENSE.md +22 -0
  3. package/README.md +2 -0
  4. package/dist/core/messages.d.ts +1 -76
  5. package/dist/core/messages.d.ts.map +1 -1
  6. package/dist/core/messages.js +1 -122
  7. package/dist/core/messages.js.map +1 -1
  8. package/dist/core/session-manager.d.ts +1 -447
  9. package/dist/core/session-manager.d.ts.map +1 -1
  10. package/dist/core/session-manager.js +1 -1203
  11. package/dist/core/session-manager.js.map +1 -1
  12. package/package.json +2 -2
  13. package/docs/COMPLETE-GUIDE.md +0 -300
  14. package/docs/COMPREHENSIVE-CLI-SUMMARY.md +0 -900
  15. package/docs/MODES-ARCHITECTURE.md +0 -565
  16. package/docs/PRINT-MODE-GUIDE.md +0 -456
  17. package/docs/README.md +0 -78
  18. package/docs/RPC-GUIDE.md +0 -705
  19. package/docs/UTILS-IMPLEMENTATION-SUMMARY.md +0 -647
  20. package/docs/UTILS-MODULE-OVERVIEW.md +0 -1480
  21. package/docs/UTILS-QA-CHECKLIST.md +0 -1061
  22. package/docs/UTILS-USAGE-GUIDE.md +0 -1419
  23. package/docs/compaction.md +0 -390
  24. package/docs/custom-provider.md +0 -538
  25. package/docs/development.md +0 -69
  26. package/docs/extensions.md +0 -1733
  27. package/docs/hooks.md +0 -378
  28. package/docs/images/doom-extension.png +0 -0
  29. package/docs/images/interactive-mode.png +0 -0
  30. package/docs/images/tree-view.png +0 -0
  31. package/docs/json.md +0 -79
  32. package/docs/keybindings.md +0 -162
  33. package/docs/models.md +0 -193
  34. package/docs/packages.md +0 -163
  35. package/docs/prompt-templates.md +0 -67
  36. package/docs/providers.md +0 -147
  37. package/docs/rpc.md +0 -1048
  38. package/docs/sdk.md +0 -969
  39. package/docs/session.md +0 -412
  40. package/docs/settings.md +0 -219
  41. package/docs/shell-aliases.md +0 -13
  42. package/docs/skills.md +0 -226
  43. package/docs/subagents.md +0 -225
  44. package/docs/terminal-setup.md +0 -65
  45. package/docs/themes.md +0 -295
  46. package/docs/tree.md +0 -219
  47. package/docs/tui.md +0 -887
  48. package/docs/web-tools.md +0 -304
  49. package/docs/windows.md +0 -17
  50. package/examples/README.md +0 -25
  51. package/examples/extensions/README.md +0 -192
  52. package/examples/extensions/antigravity-image-gen.ts +0 -414
  53. package/examples/extensions/auto-commit-on-exit.ts +0 -49
  54. package/examples/extensions/bookmark.ts +0 -50
  55. package/examples/extensions/claude-rules.ts +0 -86
  56. package/examples/extensions/confirm-destructive.ts +0 -59
  57. package/examples/extensions/custom-compaction.ts +0 -115
  58. package/examples/extensions/custom-footer.ts +0 -65
  59. package/examples/extensions/custom-header.ts +0 -73
  60. package/examples/extensions/custom-provider-anthropic/index.ts +0 -605
  61. package/examples/extensions/custom-provider-anthropic/package-lock.json +0 -24
  62. package/examples/extensions/custom-provider-anthropic/package.json +0 -19
  63. package/examples/extensions/custom-provider-gitlab-duo/index.ts +0 -350
  64. package/examples/extensions/custom-provider-gitlab-duo/package.json +0 -16
  65. package/examples/extensions/custom-provider-gitlab-duo/test.ts +0 -83
  66. package/examples/extensions/dirty-repo-guard.ts +0 -56
  67. package/examples/extensions/doom-overlay/README.md +0 -46
  68. package/examples/extensions/doom-overlay/doom/build/doom.js +0 -21
  69. package/examples/extensions/doom-overlay/doom/build/doom.wasm +0 -0
  70. package/examples/extensions/doom-overlay/doom/build.sh +0 -152
  71. package/examples/extensions/doom-overlay/doom/doomgeneric_pi.c +0 -72
  72. package/examples/extensions/doom-overlay/doom-component.ts +0 -133
  73. package/examples/extensions/doom-overlay/doom-engine.ts +0 -173
  74. package/examples/extensions/doom-overlay/doom-keys.ts +0 -105
  75. package/examples/extensions/doom-overlay/index.ts +0 -74
  76. package/examples/extensions/doom-overlay/wad-finder.ts +0 -51
  77. package/examples/extensions/event-bus.ts +0 -43
  78. package/examples/extensions/file-trigger.ts +0 -41
  79. package/examples/extensions/git-checkpoint.ts +0 -53
  80. package/examples/extensions/handoff.ts +0 -151
  81. package/examples/extensions/hello.ts +0 -25
  82. package/examples/extensions/inline-bash.ts +0 -94
  83. package/examples/extensions/input-transform.ts +0 -43
  84. package/examples/extensions/interactive-shell.ts +0 -196
  85. package/examples/extensions/mac-system-theme.ts +0 -47
  86. package/examples/extensions/message-renderer.ts +0 -60
  87. package/examples/extensions/modal-editor.ts +0 -86
  88. package/examples/extensions/model-status.ts +0 -31
  89. package/examples/extensions/notify.ts +0 -25
  90. package/examples/extensions/overlay-qa-tests.ts +0 -882
  91. package/examples/extensions/overlay-test.ts +0 -151
  92. package/examples/extensions/permission-gate.ts +0 -34
  93. package/examples/extensions/pirate.ts +0 -47
  94. package/examples/extensions/plan-mode/README.md +0 -65
  95. package/examples/extensions/plan-mode/index.ts +0 -341
  96. package/examples/extensions/plan-mode/utils.ts +0 -168
  97. package/examples/extensions/preset.ts +0 -399
  98. package/examples/extensions/protected-paths.ts +0 -30
  99. package/examples/extensions/qna.ts +0 -120
  100. package/examples/extensions/question.ts +0 -265
  101. package/examples/extensions/questionnaire.ts +0 -428
  102. package/examples/extensions/rainbow-editor.ts +0 -88
  103. package/examples/extensions/sandbox/index.ts +0 -318
  104. package/examples/extensions/sandbox/package-lock.json +0 -92
  105. package/examples/extensions/sandbox/package.json +0 -19
  106. package/examples/extensions/send-user-message.ts +0 -97
  107. package/examples/extensions/session-name.ts +0 -27
  108. package/examples/extensions/shutdown-command.ts +0 -63
  109. package/examples/extensions/snake.ts +0 -344
  110. package/examples/extensions/space-invaders.ts +0 -561
  111. package/examples/extensions/ssh.ts +0 -220
  112. package/examples/extensions/status-line.ts +0 -40
  113. package/examples/extensions/subagent/README.md +0 -172
  114. package/examples/extensions/subagent/agents/planner.md +0 -37
  115. package/examples/extensions/subagent/agents/reviewer.md +0 -35
  116. package/examples/extensions/subagent/agents/scout.md +0 -50
  117. package/examples/extensions/subagent/agents/worker.md +0 -24
  118. package/examples/extensions/subagent/agents.ts +0 -127
  119. package/examples/extensions/subagent/index.ts +0 -964
  120. package/examples/extensions/subagent/prompts/implement-and-review.md +0 -10
  121. package/examples/extensions/subagent/prompts/implement.md +0 -10
  122. package/examples/extensions/subagent/prompts/scout-and-plan.md +0 -9
  123. package/examples/extensions/summarize.ts +0 -196
  124. package/examples/extensions/timed-confirm.ts +0 -70
  125. package/examples/extensions/todo.ts +0 -300
  126. package/examples/extensions/tool-override.ts +0 -144
  127. package/examples/extensions/tools.ts +0 -147
  128. package/examples/extensions/trigger-compact.ts +0 -40
  129. package/examples/extensions/truncated-tool.ts +0 -193
  130. package/examples/extensions/widget-placement.ts +0 -17
  131. package/examples/extensions/with-deps/index.ts +0 -36
  132. package/examples/extensions/with-deps/package-lock.json +0 -31
  133. package/examples/extensions/with-deps/package.json +0 -22
  134. package/examples/sdk/01-minimal.ts +0 -22
  135. package/examples/sdk/02-custom-model.ts +0 -50
  136. package/examples/sdk/03-custom-prompt.ts +0 -55
  137. package/examples/sdk/04-skills.ts +0 -46
  138. package/examples/sdk/05-tools.ts +0 -56
  139. package/examples/sdk/06-extensions.ts +0 -88
  140. package/examples/sdk/07-context-files.ts +0 -40
  141. package/examples/sdk/08-prompt-templates.ts +0 -47
  142. package/examples/sdk/09-api-keys-and-oauth.ts +0 -48
  143. package/examples/sdk/10-settings.ts +0 -38
  144. package/examples/sdk/11-sessions.ts +0 -48
  145. package/examples/sdk/12-full-control.ts +0 -82
  146. package/examples/sdk/13-codex-oauth.ts +0 -37
  147. package/examples/sdk/README.md +0 -144
@@ -1,605 +0,0 @@
1
- /**
2
- * Custom Provider Example
3
- *
4
- * Demonstrates registering a custom provider with:
5
- * - Custom API identifier ("custom-anthropic-api")
6
- * - Custom streamSimple implementation
7
- * - OAuth support for /login
8
- * - API key support via environment variable
9
- * - Two model definitions
10
- *
11
- * Usage:
12
- * # First install dependencies
13
- * cd packages/coding-agent/examples/extensions/custom-provider && npm install
14
- *
15
- * # With OAuth (run /login custom-anthropic first)
16
- * indusagi -e ./packages/coding-agent/examples/extensions/custom-provider
17
- *
18
- * # With API key
19
- * CUSTOM_ANTHROPIC_AINDUSAGI_KEY=sk-ant-... indusagi -e ./packages/coding-agent/examples/extensions/custom-provider
20
- *
21
- * Then use /model to select custom-anthropic/claude-sonnet-4-5
22
- */
23
-
24
- import Anthropic from "@anthropic-ai/sdk";
25
- import type { ContentBlockParam, MessageCreateParamsStreaming } from "@anthropic-ai/sdk/resources/messages.js";
26
- import {
27
- type Api,
28
- type AssistantMessage,
29
- type AssistantMessageEventStream,
30
- type Context,
31
- calculateCost,
32
- createAssistantMessageEventStream,
33
- type ImageContent,
34
- type Message,
35
- type Model,
36
- type OAuthCredentials,
37
- type OAuthLoginCallbacks,
38
- type SimpleStreamOptions,
39
- type StopReason,
40
- type TextContent,
41
- type ThinkingContent,
42
- type Tool,
43
- type ToolCall,
44
- type ToolResultMessage,
45
- } from "indusagi/ai";
46
- import type { ExtensionAPI } from "indusagi-coding-agent";
47
-
48
- // =============================================================================
49
- // OAuth Implementation (copied from packages/ai/src/utils/oauth/anthropic.ts)
50
- // =============================================================================
51
-
52
- const decode = (s: string) => atob(s);
53
- const CLIENT_ID = decode("OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl");
54
- const AUTHORIZE_URL = "https://claude.ai/oauth/authorize";
55
- const TOKEN_URL = "https://console.anthropic.com/v1/oauth/token";
56
- const REDIRECT_URI = "https://console.anthropic.com/oauth/code/callback";
57
- const SCOPES = "org:create_api_key user:profile user:inference";
58
-
59
- async function generatePKCE(): Promise<{ verifier: string; challenge: string }> {
60
- const array = new Uint8Array(32);
61
- crypto.getRandomValues(array);
62
- const verifier = btoa(String.fromCharCode(...array))
63
- .replace(/\+/g, "-")
64
- .replace(/\//g, "_")
65
- .replace(/=+$/, "");
66
-
67
- const encoder = new TextEncoder();
68
- const data = encoder.encode(verifier);
69
- const hash = await crypto.subtle.digest("SHA-256", data);
70
- const challenge = btoa(String.fromCharCode(...new Uint8Array(hash)))
71
- .replace(/\+/g, "-")
72
- .replace(/\//g, "_")
73
- .replace(/=+$/, "");
74
-
75
- return { verifier, challenge };
76
- }
77
-
78
- async function loginAnthropic(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
79
- const { verifier, challenge } = await generatePKCE();
80
-
81
- const authParams = new URLSearchParams({
82
- code: "true",
83
- client_id: CLIENT_ID,
84
- response_type: "code",
85
- redirect_uri: REDIRECT_URI,
86
- scope: SCOPES,
87
- code_challenge: challenge,
88
- code_challenge_method: "S256",
89
- state: verifier,
90
- });
91
-
92
- callbacks.onAuth({ url: `${AUTHORIZE_URL}?${authParams.toString()}` });
93
-
94
- const authCode = await callbacks.onPrompt({ message: "Paste the authorization code:" });
95
- const [code, state] = authCode.split("#");
96
-
97
- const tokenResponse = await fetch(TOKEN_URL, {
98
- method: "POST",
99
- headers: { "Content-Type": "application/json" },
100
- body: JSON.stringify({
101
- grant_type: "authorization_code",
102
- client_id: CLIENT_ID,
103
- code,
104
- state,
105
- redirect_uri: REDIRECT_URI,
106
- code_verifier: verifier,
107
- }),
108
- });
109
-
110
- if (!tokenResponse.ok) {
111
- throw new Error(`Token exchange failed: ${await tokenResponse.text()}`);
112
- }
113
-
114
- const data = (await tokenResponse.json()) as {
115
- access_token: string;
116
- refresh_token: string;
117
- expires_in: number;
118
- };
119
-
120
- return {
121
- refresh: data.refresh_token,
122
- access: data.access_token,
123
- expires: Date.now() + data.expires_in * 1000 - 5 * 60 * 1000,
124
- };
125
- }
126
-
127
- async function refreshAnthropicToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {
128
- const response = await fetch(TOKEN_URL, {
129
- method: "POST",
130
- headers: { "Content-Type": "application/json" },
131
- body: JSON.stringify({
132
- grant_type: "refresh_token",
133
- client_id: CLIENT_ID,
134
- refresh_token: credentials.refresh,
135
- }),
136
- });
137
-
138
- if (!response.ok) {
139
- throw new Error(`Token refresh failed: ${await response.text()}`);
140
- }
141
-
142
- const data = (await response.json()) as {
143
- access_token: string;
144
- refresh_token: string;
145
- expires_in: number;
146
- };
147
-
148
- return {
149
- refresh: data.refresh_token,
150
- access: data.access_token,
151
- expires: Date.now() + data.expires_in * 1000 - 5 * 60 * 1000,
152
- };
153
- }
154
-
155
- // =============================================================================
156
- // Streaming Implementation (simplified from packages/ai/src/providers/anthropic.ts)
157
- // =============================================================================
158
-
159
- // Claude Code tool names for OAuth stealth mode
160
- const claudeCodeTools = [
161
- "Read",
162
- "Write",
163
- "Edit",
164
- "Bash",
165
- "Grep",
166
- "Glob",
167
- "AskUserQuestion",
168
- "TodoWrite",
169
- "WebFetch",
170
- "WebSearch",
171
- ];
172
- const ccToolLookup = new Map(claudeCodeTools.map((t) => [t.toLowerCase(), t]));
173
- const toClaudeCodeName = (name: string) => ccToolLookup.get(name.toLowerCase()) ?? name;
174
- const fromClaudeCodeName = (name: string, tools?: Tool[]) => {
175
- const lowerName = name.toLowerCase();
176
- const matched = tools?.find((t) => t.name.toLowerCase() === lowerName);
177
- return matched?.name ?? name;
178
- };
179
-
180
- function isOAuthToken(apiKey: string): boolean {
181
- return apiKey.includes("sk-ant-oat");
182
- }
183
-
184
- function sanitizeSurrogates(text: string): string {
185
- return text.replace(/[\uD800-\uDFFF]/g, "\uFFFD");
186
- }
187
-
188
- function convertContentBlocks(
189
- content: (TextContent | ImageContent)[],
190
- ): string | Array<{ type: "text"; text: string } | { type: "image"; source: any }> {
191
- const hasImages = content.some((c) => c.type === "image");
192
- if (!hasImages) {
193
- return sanitizeSurrogates(content.map((c) => (c as TextContent).text).join("\n"));
194
- }
195
-
196
- const blocks = content.map((block) => {
197
- if (block.type === "text") {
198
- return { type: "text" as const, text: sanitizeSurrogates(block.text) };
199
- }
200
- return {
201
- type: "image" as const,
202
- source: {
203
- type: "base64" as const,
204
- media_type: block.mimeType,
205
- data: block.data,
206
- },
207
- };
208
- });
209
-
210
- if (!blocks.some((b) => b.type === "text")) {
211
- blocks.unshift({ type: "text" as const, text: "(see attached image)" });
212
- }
213
-
214
- return blocks;
215
- }
216
-
217
- function convertMessages(messages: Message[], isOAuth: boolean, _tools?: Tool[]): any[] {
218
- const params: any[] = [];
219
-
220
- for (let i = 0; i < messages.length; i++) {
221
- const msg = messages[i];
222
-
223
- if (msg.role === "user") {
224
- if (typeof msg.content === "string") {
225
- if (msg.content.trim()) {
226
- params.push({ role: "user", content: sanitizeSurrogates(msg.content) });
227
- }
228
- } else {
229
- const blocks: ContentBlockParam[] = msg.content.map((item) =>
230
- item.type === "text"
231
- ? { type: "text" as const, text: sanitizeSurrogates(item.text) }
232
- : {
233
- type: "image" as const,
234
- source: { type: "base64" as const, media_type: item.mimeType as any, data: item.data },
235
- },
236
- );
237
- if (blocks.length > 0) {
238
- params.push({ role: "user", content: blocks });
239
- }
240
- }
241
- } else if (msg.role === "assistant") {
242
- const blocks: ContentBlockParam[] = [];
243
- for (const block of msg.content) {
244
- if (block.type === "text" && block.text.trim()) {
245
- blocks.push({ type: "text", text: sanitizeSurrogates(block.text) });
246
- } else if (block.type === "thinking" && block.thinking.trim()) {
247
- if ((block as ThinkingContent).thinkingSignature) {
248
- blocks.push({
249
- type: "thinking" as any,
250
- thinking: sanitizeSurrogates(block.thinking),
251
- signature: (block as ThinkingContent).thinkingSignature!,
252
- });
253
- } else {
254
- blocks.push({ type: "text", text: sanitizeSurrogates(block.thinking) });
255
- }
256
- } else if (block.type === "toolCall") {
257
- blocks.push({
258
- type: "tool_use",
259
- id: block.id,
260
- name: isOAuth ? toClaudeCodeName(block.name) : block.name,
261
- input: block.arguments,
262
- });
263
- }
264
- }
265
- if (blocks.length > 0) {
266
- params.push({ role: "assistant", content: blocks });
267
- }
268
- } else if (msg.role === "toolResult") {
269
- const toolResults: any[] = [];
270
- toolResults.push({
271
- type: "tool_result",
272
- tool_use_id: msg.toolCallId,
273
- content: convertContentBlocks(msg.content),
274
- is_error: msg.isError,
275
- });
276
-
277
- let j = i + 1;
278
- while (j < messages.length && messages[j].role === "toolResult") {
279
- const nextMsg = messages[j] as ToolResultMessage;
280
- toolResults.push({
281
- type: "tool_result",
282
- tool_use_id: nextMsg.toolCallId,
283
- content: convertContentBlocks(nextMsg.content),
284
- is_error: nextMsg.isError,
285
- });
286
- j++;
287
- }
288
- i = j - 1;
289
- params.push({ role: "user", content: toolResults });
290
- }
291
- }
292
-
293
- // Add cache control to last user message
294
- if (params.length > 0) {
295
- const last = params[params.length - 1];
296
- if (last.role === "user" && Array.isArray(last.content)) {
297
- const lastBlock = last.content[last.content.length - 1];
298
- if (lastBlock) {
299
- lastBlock.cache_control = { type: "ephemeral" };
300
- }
301
- }
302
- }
303
-
304
- return params;
305
- }
306
-
307
- function convertTools(tools: Tool[], isOAuth: boolean): any[] {
308
- return tools.map((tool) => ({
309
- name: isOAuth ? toClaudeCodeName(tool.name) : tool.name,
310
- description: tool.description,
311
- input_schema: {
312
- type: "object",
313
- properties: (tool.parameters as any).properties || {},
314
- required: (tool.parameters as any).required || [],
315
- },
316
- }));
317
- }
318
-
319
- function mapStopReason(reason: string): StopReason {
320
- switch (reason) {
321
- case "end_turn":
322
- case "pause_turn":
323
- case "stop_sequence":
324
- return "stop";
325
- case "max_tokens":
326
- return "length";
327
- case "tool_use":
328
- return "toolUse";
329
- default:
330
- return "error";
331
- }
332
- }
333
-
334
- function streamCustomAnthropic(
335
- model: Model<Api>,
336
- context: Context,
337
- options?: SimpleStreamOptions,
338
- ): AssistantMessageEventStream {
339
- const stream = createAssistantMessageEventStream();
340
-
341
- (async () => {
342
- const output: AssistantMessage = {
343
- role: "assistant",
344
- content: [],
345
- api: model.api,
346
- provider: model.provider,
347
- model: model.id,
348
- usage: {
349
- input: 0,
350
- output: 0,
351
- cacheRead: 0,
352
- cacheWrite: 0,
353
- totalTokens: 0,
354
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
355
- },
356
- stopReason: "stop",
357
- timestamp: Date.now(),
358
- };
359
-
360
- try {
361
- const apiKey = options?.apiKey ?? "";
362
- const isOAuth = isOAuthToken(apiKey);
363
-
364
- // Configure client based on auth type
365
- const betaFeatures = ["fine-grained-tool-streaming-2025-05-14", "interleaved-thinking-2025-05-14"];
366
- const clientOptions: any = {
367
- baseURL: model.baseUrl,
368
- dangerouslyAllowBrowser: true,
369
- };
370
-
371
- if (isOAuth) {
372
- clientOptions.apiKey = null;
373
- clientOptions.authToken = apiKey;
374
- clientOptions.defaultHeaders = {
375
- accept: "application/json",
376
- "anthropic-dangerous-direct-browser-access": "true",
377
- "anthropic-beta": `claude-code-20250219,oauth-2025-04-20,${betaFeatures.join(",")}`,
378
- "user-agent": "claude-cli/2.1.2 (external, cli)",
379
- "x-app": "cli",
380
- };
381
- } else {
382
- clientOptions.apiKey = apiKey;
383
- clientOptions.defaultHeaders = {
384
- accept: "application/json",
385
- "anthropic-dangerous-direct-browser-access": "true",
386
- "anthropic-beta": betaFeatures.join(","),
387
- };
388
- }
389
-
390
- const client = new Anthropic(clientOptions);
391
-
392
- // Build request params
393
- const params: MessageCreateParamsStreaming = {
394
- model: model.id,
395
- messages: convertMessages(context.messages, isOAuth, context.tools),
396
- max_tokens: options?.maxTokens || Math.floor(model.maxTokens / 3),
397
- stream: true,
398
- };
399
-
400
- // System prompt with Claude Code identity for OAuth
401
- if (isOAuth) {
402
- params.system = [
403
- {
404
- type: "text",
405
- text: "You are Claude Code, Anthropic's official CLI for Claude.",
406
- cache_control: { type: "ephemeral" },
407
- },
408
- ];
409
- if (context.systemPrompt) {
410
- params.system.push({
411
- type: "text",
412
- text: sanitizeSurrogates(context.systemPrompt),
413
- cache_control: { type: "ephemeral" },
414
- });
415
- }
416
- } else if (context.systemPrompt) {
417
- params.system = [
418
- {
419
- type: "text",
420
- text: sanitizeSurrogates(context.systemPrompt),
421
- cache_control: { type: "ephemeral" },
422
- },
423
- ];
424
- }
425
-
426
- if (context.tools) {
427
- params.tools = convertTools(context.tools, isOAuth);
428
- }
429
-
430
- // Handle thinking/reasoning
431
- if (options?.reasoning && model.reasoning) {
432
- const defaultBudgets: Record<string, number> = {
433
- minimal: 1024,
434
- low: 4096,
435
- medium: 10240,
436
- high: 20480,
437
- };
438
- const customBudget = options.thinkingBudgets?.[options.reasoning as keyof typeof options.thinkingBudgets];
439
- params.thinking = {
440
- type: "enabled",
441
- budget_tokens: customBudget ?? defaultBudgets[options.reasoning] ?? 10240,
442
- };
443
- }
444
-
445
- const anthropicStream = client.messages.stream({ ...params }, { signal: options?.signal });
446
- stream.push({ type: "start", partial: output });
447
-
448
- type Block = (ThinkingContent | TextContent | (ToolCall & { partialJson: string })) & { index: number };
449
- const blocks = output.content as Block[];
450
-
451
- for await (const event of anthropicStream) {
452
- if (event.type === "message_start") {
453
- output.usage.input = event.message.usage.input_tokens || 0;
454
- output.usage.output = event.message.usage.output_tokens || 0;
455
- output.usage.cacheRead = (event.message.usage as any).cache_read_input_tokens || 0;
456
- output.usage.cacheWrite = (event.message.usage as any).cache_creation_input_tokens || 0;
457
- output.usage.totalTokens =
458
- output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
459
- calculateCost(model, output.usage);
460
- } else if (event.type === "content_block_start") {
461
- if (event.content_block.type === "text") {
462
- output.content.push({ type: "text", text: "", index: event.index } as any);
463
- stream.push({ type: "text_start", contentIndex: output.content.length - 1, partial: output });
464
- } else if (event.content_block.type === "thinking") {
465
- output.content.push({
466
- type: "thinking",
467
- thinking: "",
468
- thinkingSignature: "",
469
- index: event.index,
470
- } as any);
471
- stream.push({ type: "thinking_start", contentIndex: output.content.length - 1, partial: output });
472
- } else if (event.content_block.type === "tool_use") {
473
- output.content.push({
474
- type: "toolCall",
475
- id: event.content_block.id,
476
- name: isOAuth
477
- ? fromClaudeCodeName(event.content_block.name, context.tools)
478
- : event.content_block.name,
479
- arguments: {},
480
- partialJson: "",
481
- index: event.index,
482
- } as any);
483
- stream.push({ type: "toolcall_start", contentIndex: output.content.length - 1, partial: output });
484
- }
485
- } else if (event.type === "content_block_delta") {
486
- const index = blocks.findIndex((b) => b.index === event.index);
487
- const block = blocks[index];
488
- if (!block) continue;
489
-
490
- if (event.delta.type === "text_delta" && block.type === "text") {
491
- block.text += event.delta.text;
492
- stream.push({ type: "text_delta", contentIndex: index, delta: event.delta.text, partial: output });
493
- } else if (event.delta.type === "thinking_delta" && block.type === "thinking") {
494
- block.thinking += event.delta.thinking;
495
- stream.push({
496
- type: "thinking_delta",
497
- contentIndex: index,
498
- delta: event.delta.thinking,
499
- partial: output,
500
- });
501
- } else if (event.delta.type === "input_json_delta" && block.type === "toolCall") {
502
- (block as any).partialJson += event.delta.partial_json;
503
- try {
504
- block.arguments = JSON.parse((block as any).partialJson);
505
- } catch {}
506
- stream.push({
507
- type: "toolcall_delta",
508
- contentIndex: index,
509
- delta: event.delta.partial_json,
510
- partial: output,
511
- });
512
- } else if (event.delta.type === "signature_delta" && block.type === "thinking") {
513
- block.thinkingSignature = (block.thinkingSignature || "") + (event.delta as any).signature;
514
- }
515
- } else if (event.type === "content_block_stop") {
516
- const index = blocks.findIndex((b) => b.index === event.index);
517
- const block = blocks[index];
518
- if (!block) continue;
519
-
520
- delete (block as any).index;
521
- if (block.type === "text") {
522
- stream.push({ type: "text_end", contentIndex: index, content: block.text, partial: output });
523
- } else if (block.type === "thinking") {
524
- stream.push({ type: "thinking_end", contentIndex: index, content: block.thinking, partial: output });
525
- } else if (block.type === "toolCall") {
526
- try {
527
- block.arguments = JSON.parse((block as any).partialJson);
528
- } catch {}
529
- delete (block as any).partialJson;
530
- stream.push({ type: "toolcall_end", contentIndex: index, toolCall: block, partial: output });
531
- }
532
- } else if (event.type === "message_delta") {
533
- if ((event.delta as any).stop_reason) {
534
- output.stopReason = mapStopReason((event.delta as any).stop_reason);
535
- }
536
- output.usage.input = (event.usage as any).input_tokens || 0;
537
- output.usage.output = (event.usage as any).output_tokens || 0;
538
- output.usage.cacheRead = (event.usage as any).cache_read_input_tokens || 0;
539
- output.usage.cacheWrite = (event.usage as any).cache_creation_input_tokens || 0;
540
- output.usage.totalTokens =
541
- output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
542
- calculateCost(model, output.usage);
543
- }
544
- }
545
-
546
- if (options?.signal?.aborted) {
547
- throw new Error("Request was aborted");
548
- }
549
-
550
- stream.push({ type: "done", reason: output.stopReason as "stop" | "length" | "toolUse", message: output });
551
- stream.end();
552
- } catch (error) {
553
- for (const block of output.content) delete (block as any).index;
554
- output.stopReason = options?.signal?.aborted ? "aborted" : "error";
555
- output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
556
- stream.push({ type: "error", reason: output.stopReason, error: output });
557
- stream.end();
558
- }
559
- })();
560
-
561
- return stream;
562
- }
563
-
564
- // =============================================================================
565
- // Extension Entry Point
566
- // =============================================================================
567
-
568
- export default function (indusagi: ExtensionAPI) {
569
- indusagi.registerProvider("custom-anthropic", {
570
- baseUrl: "https://api.anthropic.com",
571
- apiKey: "CUSTOM_ANTHROPIC_AINDUSAGI_KEY",
572
- api: "custom-anthropic-api",
573
-
574
- models: [
575
- {
576
- id: "claude-opus-4-5",
577
- name: "Claude Opus 4.5 (Custom)",
578
- reasoning: true,
579
- input: ["text", "image"],
580
- cost: { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 },
581
- contextWindow: 200000,
582
- maxTokens: 64000,
583
- },
584
- {
585
- id: "claude-sonnet-4-5",
586
- name: "Claude Sonnet 4.5 (Custom)",
587
- reasoning: true,
588
- input: ["text", "image"],
589
- cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },
590
- contextWindow: 200000,
591
- maxTokens: 64000,
592
- },
593
- ],
594
-
595
- oauth: {
596
- name: "Custom Anthropic (Claude Pro/Max)",
597
- login: loginAnthropic,
598
- refreshToken: refreshAnthropicToken,
599
- getApiKey: (cred) => cred.access,
600
- },
601
-
602
- streamSimple: streamCustomAnthropic,
603
- });
604
- }
605
-
@@ -1,24 +0,0 @@
1
- {
2
- "name": "indusagi-extension-custom-provider",
3
- "version": "1.1.0",
4
- "lockfileVersion": 3,
5
- "requires": true,
6
- "packages": {
7
- "": {
8
- "name": "indusagi-extension-custom-provider",
9
- "version": "1.1.0",
10
- "dependencies": {
11
- "@anthropic-ai/sdk": "^0.52.0"
12
- }
13
- },
14
- "node_modules/@anthropic-ai/sdk": {
15
- "version": "0.52.0",
16
- "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.52.0.tgz",
17
- "integrity": "sha512-d4c+fg+xy9e46c8+YnrrgIQR45CZlAi7PwdzIfDXDM6ACxEZli1/fxhURsq30ZpMZy6LvSkr41jGq5aF5TD7rQ==",
18
- "license": "MIT",
19
- "bin": {
20
- "anthropic-ai-sdk": "bin/cli"
21
- }
22
- }
23
- }
24
- }
@@ -1,19 +0,0 @@
1
- {
2
- "name": "indusagi-extension-custom-provider-anthropic",
3
- "private": true,
4
- "version": "1.1.0",
5
- "type": "module",
6
- "scripts": {
7
- "clean": "echo 'nothing to clean'",
8
- "build": "echo 'nothing to build'",
9
- "check": "echo 'nothing to check'"
10
- },
11
- "indusagi": {
12
- "extensions": [
13
- "./index.ts"
14
- ]
15
- },
16
- "dependencies": {
17
- "@anthropic-ai/sdk": "^0.52.0"
18
- }
19
- }