@apholdings/jensen-code 0.0.4 → 0.0.5

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 (157) hide show
  1. package/dist/cli/args.d.ts.map +1 -1
  2. package/dist/cli/args.js +6 -6
  3. package/dist/cli/args.js.map +1 -1
  4. package/dist/config.d.ts +6 -5
  5. package/dist/config.d.ts.map +1 -1
  6. package/dist/config.js +32 -25
  7. package/dist/config.js.map +1 -1
  8. package/dist/core/agent-session.d.ts.map +1 -1
  9. package/dist/core/agent-session.js +10 -0
  10. package/dist/core/agent-session.js.map +1 -1
  11. package/dist/index.d.ts +1 -1
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +1 -1
  14. package/dist/index.js.map +1 -1
  15. package/dist/modes/interactive/components/assistant-message.d.ts +1 -6
  16. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  17. package/dist/modes/interactive/components/assistant-message.js +10 -40
  18. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  19. package/dist/modes/interactive/components/custom-editor.d.ts +1 -0
  20. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  21. package/dist/modes/interactive/components/custom-editor.js +5 -0
  22. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  23. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  24. package/dist/modes/interactive/components/tool-execution.js +1 -2
  25. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  26. package/dist/modes/interactive/components/top-bar.d.ts.map +1 -1
  27. package/dist/modes/interactive/components/top-bar.js +1 -1
  28. package/dist/modes/interactive/components/top-bar.js.map +1 -1
  29. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  30. package/dist/modes/interactive/components/user-message.js +1 -1
  31. package/dist/modes/interactive/components/user-message.js.map +1 -1
  32. package/dist/modes/interactive/interactive-mode.d.ts +6 -3
  33. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  34. package/dist/modes/interactive/interactive-mode.js +204 -86
  35. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  36. package/dist/utils/frontmatter.d.ts.map +1 -1
  37. package/dist/utils/frontmatter.js +8 -4
  38. package/dist/utils/frontmatter.js.map +1 -1
  39. package/dist/utils/tools-manager.d.ts.map +1 -1
  40. package/dist/utils/tools-manager.js +2 -2
  41. package/dist/utils/tools-manager.js.map +1 -1
  42. package/examples/extensions/osgrep.ts +643 -0
  43. package/examples/extensions/subagent/agents.ts +150 -37
  44. package/examples/extensions/subagent/index.ts +634 -513
  45. package/package.json +2 -2
  46. package/examples/README.md +0 -25
  47. package/examples/extensions/README.md +0 -206
  48. package/examples/extensions/antigravity-image-gen.ts +0 -415
  49. package/examples/extensions/auto-commit-on-exit.ts +0 -49
  50. package/examples/extensions/bash-spawn-hook.ts +0 -30
  51. package/examples/extensions/bookmark.ts +0 -50
  52. package/examples/extensions/built-in-tool-renderer.ts +0 -246
  53. package/examples/extensions/claude-rules.ts +0 -86
  54. package/examples/extensions/commands.ts +0 -72
  55. package/examples/extensions/confirm-destructive.ts +0 -59
  56. package/examples/extensions/custom-compaction.ts +0 -114
  57. package/examples/extensions/custom-footer.ts +0 -64
  58. package/examples/extensions/custom-header.ts +0 -73
  59. package/examples/extensions/custom-provider-anthropic/index.ts +0 -604
  60. package/examples/extensions/custom-provider-anthropic/package-lock.json +0 -24
  61. package/examples/extensions/custom-provider-anthropic/package.json +0 -19
  62. package/examples/extensions/custom-provider-gitlab-duo/index.ts +0 -349
  63. package/examples/extensions/custom-provider-gitlab-duo/package.json +0 -16
  64. package/examples/extensions/custom-provider-gitlab-duo/test.ts +0 -82
  65. package/examples/extensions/custom-provider-qwen-cli/index.ts +0 -345
  66. package/examples/extensions/custom-provider-qwen-cli/package.json +0 -16
  67. package/examples/extensions/dirty-repo-guard.ts +0 -56
  68. package/examples/extensions/doom-overlay/README.md +0 -46
  69. package/examples/extensions/doom-overlay/doom/build/doom.js +0 -21
  70. package/examples/extensions/doom-overlay/doom/build/doom.wasm +0 -0
  71. package/examples/extensions/doom-overlay/doom/build.sh +0 -152
  72. package/examples/extensions/doom-overlay/doom/doomgeneric_pi.c +0 -72
  73. package/examples/extensions/doom-overlay/doom-component.ts +0 -132
  74. package/examples/extensions/doom-overlay/doom-engine.ts +0 -173
  75. package/examples/extensions/doom-overlay/doom-keys.ts +0 -104
  76. package/examples/extensions/doom-overlay/index.ts +0 -74
  77. package/examples/extensions/doom-overlay/wad-finder.ts +0 -51
  78. package/examples/extensions/dynamic-resources/SKILL.md +0 -8
  79. package/examples/extensions/dynamic-resources/dynamic.json +0 -79
  80. package/examples/extensions/dynamic-resources/dynamic.md +0 -5
  81. package/examples/extensions/dynamic-resources/index.ts +0 -15
  82. package/examples/extensions/dynamic-tools.ts +0 -74
  83. package/examples/extensions/event-bus.ts +0 -43
  84. package/examples/extensions/file-trigger.ts +0 -41
  85. package/examples/extensions/git-checkpoint.ts +0 -53
  86. package/examples/extensions/handoff.ts +0 -150
  87. package/examples/extensions/hello.ts +0 -25
  88. package/examples/extensions/inline-bash.ts +0 -94
  89. package/examples/extensions/input-transform.ts +0 -43
  90. package/examples/extensions/interactive-shell.ts +0 -196
  91. package/examples/extensions/mac-system-theme.ts +0 -47
  92. package/examples/extensions/message-renderer.ts +0 -59
  93. package/examples/extensions/minimal-mode.ts +0 -426
  94. package/examples/extensions/modal-editor.ts +0 -85
  95. package/examples/extensions/model-status.ts +0 -31
  96. package/examples/extensions/notify.ts +0 -55
  97. package/examples/extensions/overlay-qa-tests.ts +0 -1348
  98. package/examples/extensions/overlay-test.ts +0 -150
  99. package/examples/extensions/permission-gate.ts +0 -34
  100. package/examples/extensions/pirate.ts +0 -47
  101. package/examples/extensions/plan-mode/README.md +0 -65
  102. package/examples/extensions/plan-mode/index.ts +0 -340
  103. package/examples/extensions/plan-mode/utils.ts +0 -168
  104. package/examples/extensions/preset.ts +0 -398
  105. package/examples/extensions/protected-paths.ts +0 -30
  106. package/examples/extensions/provider-payload.ts +0 -14
  107. package/examples/extensions/qna.ts +0 -119
  108. package/examples/extensions/question.ts +0 -264
  109. package/examples/extensions/questionnaire.ts +0 -427
  110. package/examples/extensions/rainbow-editor.ts +0 -88
  111. package/examples/extensions/reload-runtime.ts +0 -37
  112. package/examples/extensions/rpc-demo.ts +0 -124
  113. package/examples/extensions/sandbox/index.ts +0 -318
  114. package/examples/extensions/sandbox/package-lock.json +0 -92
  115. package/examples/extensions/sandbox/package.json +0 -19
  116. package/examples/extensions/send-user-message.ts +0 -97
  117. package/examples/extensions/session-name.ts +0 -27
  118. package/examples/extensions/shutdown-command.ts +0 -63
  119. package/examples/extensions/snake.ts +0 -343
  120. package/examples/extensions/space-invaders.ts +0 -560
  121. package/examples/extensions/ssh.ts +0 -220
  122. package/examples/extensions/status-line.ts +0 -40
  123. package/examples/extensions/subagent/README.md +0 -172
  124. package/examples/extensions/subagent/agents/planner.md +0 -37
  125. package/examples/extensions/subagent/agents/reviewer.md +0 -35
  126. package/examples/extensions/subagent/agents/scout.md +0 -50
  127. package/examples/extensions/subagent/agents/worker.md +0 -24
  128. package/examples/extensions/subagent/prompts/implement-and-review.md +0 -10
  129. package/examples/extensions/subagent/prompts/implement.md +0 -10
  130. package/examples/extensions/subagent/prompts/scout-and-plan.md +0 -9
  131. package/examples/extensions/summarize.ts +0 -195
  132. package/examples/extensions/system-prompt-header.ts +0 -17
  133. package/examples/extensions/timed-confirm.ts +0 -70
  134. package/examples/extensions/titlebar-spinner.ts +0 -58
  135. package/examples/extensions/todo.ts +0 -299
  136. package/examples/extensions/tool-override.ts +0 -143
  137. package/examples/extensions/tools.ts +0 -146
  138. package/examples/extensions/trigger-compact.ts +0 -40
  139. package/examples/extensions/truncated-tool.ts +0 -192
  140. package/examples/extensions/widget-placement.ts +0 -17
  141. package/examples/extensions/with-deps/index.ts +0 -32
  142. package/examples/extensions/with-deps/package-lock.json +0 -31
  143. package/examples/extensions/with-deps/package.json +0 -22
  144. package/examples/rpc-extension-ui.ts +0 -632
  145. package/examples/sdk/01-minimal.ts +0 -22
  146. package/examples/sdk/02-custom-model.ts +0 -49
  147. package/examples/sdk/03-custom-prompt.ts +0 -55
  148. package/examples/sdk/04-skills.ts +0 -46
  149. package/examples/sdk/05-tools.ts +0 -56
  150. package/examples/sdk/06-extensions.ts +0 -88
  151. package/examples/sdk/07-context-files.ts +0 -40
  152. package/examples/sdk/08-prompt-templates.ts +0 -47
  153. package/examples/sdk/09-api-keys-and-oauth.ts +0 -48
  154. package/examples/sdk/10-settings.ts +0 -51
  155. package/examples/sdk/11-sessions.ts +0 -48
  156. package/examples/sdk/12-full-control.ts +0 -82
  157. package/examples/sdk/README.md +0 -145
@@ -1,604 +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
- * pi -e ./packages/coding-agent/examples/extensions/custom-provider
17
- *
18
- * # With API key
19
- * CUSTOM_ANTHROPIC_API_KEY=sk-ant-... pi -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 "@apholdings/jensen-ai";
46
- import type { ExtensionAPI } from "@apholdings/jensen-code";
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 (pi: ExtensionAPI) {
569
- pi.registerProvider("custom-anthropic", {
570
- baseUrl: "https://api.anthropic.com",
571
- apiKey: "CUSTOM_ANTHROPIC_API_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
- }
@@ -1,24 +0,0 @@
1
- {
2
- "name": "pi-extension-custom-provider",
3
- "version": "1.8.1",
4
- "lockfileVersion": 3,
5
- "requires": true,
6
- "packages": {
7
- "": {
8
- "name": "pi-extension-custom-provider",
9
- "version": "1.8.1",
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": "pi-extension-custom-provider-anthropic",
3
- "private": true,
4
- "version": "1.8.1",
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
- "pi": {
12
- "extensions": [
13
- "./index.ts"
14
- ]
15
- },
16
- "dependencies": {
17
- "@anthropic-ai/sdk": "^0.52.0"
18
- }
19
- }