@mariozechner/pi-coding-agent 0.49.3 → 0.50.0
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.
- package/CHANGELOG.md +99 -1
- package/README.md +310 -1230
- package/dist/cli/args.d.ts +5 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +57 -23
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/config-selector.d.ts +14 -0
- package/dist/cli/config-selector.d.ts.map +1 -0
- package/dist/cli/config-selector.js +31 -0
- package/dist/cli/config-selector.js.map +1 -0
- package/dist/cli/session-picker.d.ts.map +1 -1
- package/dist/cli/session-picker.js +1 -1
- package/dist/cli/session-picker.js.map +1 -1
- package/dist/core/agent-session.d.ts +53 -34
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +262 -67
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-storage.d.ts +8 -18
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +39 -55
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +2 -1
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/diagnostics.d.ts +15 -0
- package/dist/core/diagnostics.d.ts.map +1 -0
- package/dist/core/diagnostics.js +2 -0
- package/dist/core/diagnostics.js.map +1 -0
- package/dist/core/export-html/template.css +9 -0
- package/dist/core/export-html/template.js +6 -4
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/loader.d.ts +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +10 -1
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +9 -3
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +39 -12
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +112 -1
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/footer-data-provider.d.ts +9 -2
- package/dist/core/footer-data-provider.d.ts.map +1 -1
- package/dist/core/footer-data-provider.js +13 -0
- package/dist/core/footer-data-provider.js.map +1 -1
- package/dist/core/model-registry.d.ts +42 -2
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +154 -44
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +3 -2
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/package-manager.d.ts +129 -0
- package/dist/core/package-manager.d.ts.map +1 -0
- package/dist/core/package-manager.js +1148 -0
- package/dist/core/package-manager.js.map +1 -0
- package/dist/core/prompt-templates.d.ts +6 -0
- package/dist/core/prompt-templates.d.ts.map +1 -1
- package/dist/core/prompt-templates.js +114 -54
- package/dist/core/prompt-templates.js.map +1 -1
- package/dist/core/resource-loader.d.ts +160 -0
- package/dist/core/resource-loader.d.ts.map +1 -0
- package/dist/core/resource-loader.js +604 -0
- package/dist/core/resource-loader.js.map +1 -0
- package/dist/core/sdk.d.ts +14 -105
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +52 -304
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +45 -1
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-manager.d.ts +34 -16
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +104 -25
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/skills.d.ts +18 -10
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/skills.js +126 -93
- package/dist/core/skills.js.map +1 -1
- package/dist/core/system-prompt.d.ts +3 -27
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +16 -103
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +2 -1
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +4 -4
- package/dist/core/tools/read.js.map +1 -1
- package/dist/index.d.ts +12 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -6
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +209 -97
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/bordered-loader.d.ts +5 -1
- package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -1
- package/dist/modes/interactive/components/bordered-loader.js +29 -9
- package/dist/modes/interactive/components/bordered-loader.js.map +1 -1
- package/dist/modes/interactive/components/config-selector.d.ts +71 -0
- package/dist/modes/interactive/components/config-selector.d.ts.map +1 -0
- package/dist/modes/interactive/components/config-selector.js +468 -0
- package/dist/modes/interactive/components/config-selector.js.map +1 -0
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +4 -0
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/index.d.ts +1 -0
- package/dist/modes/interactive/components/index.d.ts.map +1 -1
- package/dist/modes/interactive/components/index.js +1 -0
- package/dist/modes/interactive/components/index.js.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.js +3 -4
- package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts +18 -1
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +195 -87
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/components/skill-invocation-message.d.ts +17 -0
- package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -0
- package/dist/modes/interactive/components/skill-invocation-message.js +47 -0
- package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -0
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +5 -5
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +42 -2
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +535 -200
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/theme/dark.json +1 -1
- package/dist/modes/interactive/theme/light.json +1 -1
- package/dist/modes/interactive/theme/theme-schema.json +8 -1
- package/dist/modes/interactive/theme/theme.d.ts +8 -1
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +72 -25
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +25 -89
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +32 -92
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/utils/git.d.ts +2 -0
- package/dist/utils/git.d.ts.map +1 -0
- package/dist/utils/git.js +6 -0
- package/dist/utils/git.js.map +1 -0
- package/dist/utils/shell.d.ts +1 -0
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +14 -1
- package/dist/utils/shell.js.map +1 -1
- package/dist/utils/sleep.d.ts +5 -0
- package/dist/utils/sleep.d.ts.map +1 -0
- package/dist/utils/sleep.js +17 -0
- package/dist/utils/sleep.js.map +1 -0
- package/docs/compaction.md +23 -21
- package/docs/custom-provider.md +538 -0
- package/docs/development.md +69 -0
- package/docs/extensions.md +180 -118
- package/docs/images/doom-extension.png +0 -0
- package/docs/images/interactive-mode.png +0 -0
- package/docs/images/tree-view.png +0 -0
- package/docs/json.md +79 -0
- package/docs/keybindings.md +162 -0
- package/docs/models.md +193 -0
- package/docs/packages.md +163 -0
- package/docs/prompt-templates.md +67 -0
- package/docs/providers.md +147 -0
- package/docs/sdk.md +111 -178
- package/docs/session.md +167 -16
- package/docs/settings.md +216 -0
- package/docs/shell-aliases.md +13 -0
- package/docs/skills.md +111 -202
- package/docs/terminal-setup.md +65 -0
- package/docs/themes.md +295 -0
- package/docs/tui.md +36 -5
- package/docs/windows.md +17 -0
- package/examples/README.md +1 -0
- package/examples/extensions/README.md +22 -2
- package/examples/extensions/bookmark.ts +50 -0
- package/examples/extensions/custom-provider-anthropic/index.ts +604 -0
- package/examples/extensions/custom-provider-anthropic/package-lock.json +24 -0
- package/examples/extensions/custom-provider-anthropic/package.json +19 -0
- package/examples/extensions/custom-provider-gitlab-duo/index.ts +349 -0
- package/examples/extensions/custom-provider-gitlab-duo/package.json +16 -0
- package/examples/extensions/custom-provider-gitlab-duo/test.ts +82 -0
- package/examples/extensions/doom-overlay/doom/build.sh +1 -1
- package/examples/extensions/event-bus.ts +43 -0
- package/examples/extensions/message-renderer.ts +59 -0
- package/examples/extensions/session-name.ts +27 -0
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/examples/sdk/02-custom-model.ts +3 -3
- package/examples/sdk/03-custom-prompt.ts +20 -9
- package/examples/sdk/04-skills.ts +26 -27
- package/examples/sdk/06-extensions.ts +15 -6
- package/examples/sdk/07-context-files.ts +22 -18
- package/examples/sdk/08-prompt-templates.ts +19 -14
- package/examples/sdk/09-api-keys-and-oauth.ts +5 -12
- package/examples/sdk/10-settings.ts +3 -3
- package/examples/sdk/12-full-control.ts +16 -7
- package/examples/sdk/README.md +24 -30
- package/package.json +4 -4
- package/docs/theme.md +0 -617
- package/examples/extensions/chalk-logger.ts +0 -26
|
@@ -0,0 +1,604 @@
|
|
|
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 "@mariozechner/pi-ai";
|
|
46
|
+
import type { ExtensionAPI } from "@mariozechner/pi-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 (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
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "pi-extension-custom-provider",
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"lockfileVersion": 3,
|
|
5
|
+
"requires": true,
|
|
6
|
+
"packages": {
|
|
7
|
+
"": {
|
|
8
|
+
"name": "pi-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
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "pi-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
|
+
"pi": {
|
|
12
|
+
"extensions": [
|
|
13
|
+
"./index.ts"
|
|
14
|
+
]
|
|
15
|
+
},
|
|
16
|
+
"dependencies": {
|
|
17
|
+
"@anthropic-ai/sdk": "^0.52.0"
|
|
18
|
+
}
|
|
19
|
+
}
|