-
Notifications
You must be signed in to change notification settings - Fork 244
Expand file tree
/
Copy pathclaude-sdk-one-shot.ts
More file actions
403 lines (374 loc) · 13.4 KB
/
Copy pathclaude-sdk-one-shot.ts
File metadata and controls
403 lines (374 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
import { completeSimple, type UserMessage as PiUserMessage } from '@mariozechner/pi-ai';
import type { ApiTestInput, ApiTestResult } from '../../renderer/types';
import { PROVIDER_PRESETS, type AppConfig, type CustomProtocolType } from '../config/config-store';
import {
normalizeAnthropicBaseUrl,
normalizeOllamaBaseUrl,
normalizeOpenAICompatibleBaseUrl,
resolveOllamaCredentials,
resolveOpenAICredentials,
shouldAllowEmptyAnthropicApiKey,
shouldAllowEmptyGeminiApiKey,
} from '../config/auth-utils';
import { log, logWarn } from '../utils/logger';
import { normalizeGeneratedTitle } from '../session/session-title-utils';
import { getSharedAuthStorage } from './shared-auth';
import {
applyPiModelRuntimeOverrides,
buildSyntheticPiModel,
inferPiApi,
resolvePiModelString,
resolvePiRegistryModel,
resolvePiRouteProtocol,
resolveSyntheticPiModelFallback,
} from './pi-model-resolution';
import {
isGeminiSdkProbeUnavailableError,
probeGeminiRelayGenerateContent,
} from '../config/gemini-relay-probe';
const NETWORK_ERROR_RE =
/enotfound|econnrefused|etimedout|eai_again|enetunreach|timed?\s*out|timeout|abort|network\s*error/i;
const AUTH_ERROR_RE =
/authentication[_\s-]?failed|\bunauthorized\b|invalid[_\s-]?api[_\s-]?key|api[_\s-]?key[_\s-]?invalid|api[_\s]+key[_\s]+not[_\s]+valid|\bforbidden\b|permission[_\s-]?denied|\b401\b|\b403\b/i;
const RATE_LIMIT_RE = /rate[_\s-]?limit|too\s+many\s+requests|429/i;
const SERVER_ERROR_RE = /server[_\s-]?error|internal\s+server\s+error|\b5\d\d\b/i;
const PROBE_ACK = 'sdk_probe_ok';
const LOCAL_ANTHROPIC_PLACEHOLDER_KEY = 'sk-ant-local-proxy';
const LOCAL_GEMINI_PLACEHOLDER_KEY = 'sk-gemini-local-proxy';
function resolveProbeBaseUrl(input: ApiTestInput): string | undefined {
const configured = input.baseUrl?.trim();
if (configured) return configured;
if (input.provider !== 'custom') {
return PROVIDER_PRESETS[input.provider]?.baseUrl;
}
return undefined;
}
function resolveProbeApiKey(
input: ApiTestInput,
resolvedCustomProtocol: CustomProtocolType,
effectiveBaseUrl: string | undefined,
explicitApiKey: string | undefined,
config: AppConfig
): string {
const candidateApiKey = explicitApiKey ?? config.apiKey?.trim() ?? '';
if (candidateApiKey) {
return candidateApiKey;
}
if (input.provider === 'ollama') {
return (
resolveOllamaCredentials({
provider: input.provider,
customProtocol: resolvedCustomProtocol,
apiKey: '',
baseUrl: effectiveBaseUrl,
})?.apiKey || ''
);
}
if (
input.provider === 'openai' ||
input.provider === 'openrouter' ||
(input.provider === 'custom' && resolvedCustomProtocol === 'openai')
) {
return (
resolveOpenAICredentials({
provider: input.provider,
customProtocol: resolvedCustomProtocol,
apiKey: '',
baseUrl: effectiveBaseUrl,
})?.apiKey || ''
);
}
if (
shouldAllowEmptyAnthropicApiKey({
provider: input.provider,
customProtocol: resolvedCustomProtocol,
baseUrl: effectiveBaseUrl,
})
) {
return LOCAL_ANTHROPIC_PLACEHOLDER_KEY;
}
if (
shouldAllowEmptyGeminiApiKey({
provider: input.provider,
customProtocol: resolvedCustomProtocol,
baseUrl: effectiveBaseUrl,
})
) {
return LOCAL_GEMINI_PLACEHOLDER_KEY;
}
return '';
}
function buildProbeConfig(input: ApiTestInput, config: AppConfig): AppConfig {
const resolvedBaseUrl = resolveProbeBaseUrl(input);
const normalizedInputApiKey = typeof input.apiKey === 'string' ? input.apiKey.trim() : undefined;
const resolvedCustomProtocol = resolvePiRouteProtocol(
input.provider,
input.customProtocol
) as CustomProtocolType;
const effectiveRawBaseUrl = resolvedBaseUrl || '';
const effectiveBaseUrl =
input.provider === 'ollama'
? normalizeOllamaBaseUrl(effectiveRawBaseUrl) || effectiveRawBaseUrl
: resolvedCustomProtocol === 'openai'
? normalizeOpenAICompatibleBaseUrl(effectiveRawBaseUrl) || effectiveRawBaseUrl
: resolvedCustomProtocol === 'gemini'
? effectiveRawBaseUrl
: normalizeAnthropicBaseUrl(effectiveRawBaseUrl);
const effectiveApiKey = resolveProbeApiKey(
input,
resolvedCustomProtocol,
effectiveBaseUrl,
normalizedInputApiKey,
config
);
return {
...config,
provider: input.provider,
customProtocol: resolvedCustomProtocol,
apiKey: effectiveApiKey,
baseUrl: effectiveBaseUrl,
model: typeof input.model === 'string' ? input.model.trim() : config.model,
};
}
function mapPiAiError(errorText: string, durationMs: number, provider?: string): ApiTestResult {
const details = errorText.trim();
const lowered = details.toLowerCase();
if (AUTH_ERROR_RE.test(lowered)) {
return { ok: false, latencyMs: durationMs, errorType: 'unauthorized', details };
}
if (RATE_LIMIT_RE.test(lowered)) {
return { ok: false, latencyMs: durationMs, errorType: 'rate_limited', details };
}
if (SERVER_ERROR_RE.test(lowered)) {
return { ok: false, latencyMs: durationMs, errorType: 'server_error', details };
}
if (provider === 'ollama' && /econnrefused/i.test(lowered)) {
return { ok: false, latencyMs: durationMs, errorType: 'ollama_not_running', details };
}
if (NETWORK_ERROR_RE.test(lowered)) {
return { ok: false, latencyMs: durationMs, errorType: 'network_error', details };
}
return { ok: false, latencyMs: durationMs, errorType: 'unknown', details };
}
/**
* Run a simple one-shot prompt via pi-ai model directly (no agent session needed).
*/
export async function runPiAiOneShot(
prompt: string,
systemPrompt: string,
config: AppConfig,
options?: {
temperature?: number;
maxTokens?: number;
signal?: AbortSignal;
}
): Promise<{ text: string; hasThinking: boolean; durationMs: number }> {
const modelString = resolvePiModelString(config);
const keyProvider = config.customProtocol || config.provider || 'anthropic';
const parts = modelString.split('/');
const provider = parts.length >= 2 ? parts[0] : keyProvider || 'anthropic';
// Normalize base URL for OpenAI-compatible providers (strips copy-pasted endpoint suffixes)
const routeProtocol = resolvePiRouteProtocol(config.provider, config.customProtocol);
const rawBaseUrl = config.baseUrl?.trim() || undefined;
const effectiveBaseUrl =
routeProtocol === 'openai' && config.provider !== 'ollama'
? normalizeOpenAICompatibleBaseUrl(rawBaseUrl) || rawBaseUrl
: rawBaseUrl;
let piModel = resolvePiRegistryModel(modelString, {
configProvider: keyProvider,
customBaseUrl: effectiveBaseUrl,
rawProvider: config.provider || 'anthropic',
customProtocol: config.customProtocol,
});
if (!piModel) {
// Synthetic fallback for unknown/custom models
const effectiveProtocol = resolvePiRouteProtocol(
config.provider,
config.customProtocol
) as CustomProtocolType;
const api = effectiveBaseUrl ? inferPiApi(effectiveProtocol) : undefined;
const synthetic = resolveSyntheticPiModelFallback({
rawModel: config.model,
resolvedModelString: modelString,
rawProvider: config.provider,
routeProtocol: effectiveProtocol,
baseUrl: effectiveBaseUrl,
});
piModel = buildSyntheticPiModel(
synthetic.modelId,
synthetic.provider,
effectiveProtocol,
effectiveBaseUrl || '',
api
);
piModel = applyPiModelRuntimeOverrides(piModel, {
configProvider: keyProvider,
customBaseUrl: effectiveBaseUrl,
rawProvider: config.provider || 'anthropic',
customProtocol: config.customProtocol,
});
logWarn('[OneShot] Model not in pi-ai registry, using synthetic model:', modelString, '→', api);
}
// piModel is guaranteed non-undefined after synthetic fallback
const resolvedModel = piModel!;
// Set API key via AuthStorage (for agent sessions) AND env vars (for pi-ai completeSimple)
const apiKey = config.apiKey?.trim();
if (apiKey) {
const authStorage = getSharedAuthStorage();
// Set for the config provider
authStorage.setRuntimeApiKey(provider, apiKey);
// Also set for the model's native provider if different
if (resolvedModel.provider !== provider) {
authStorage.setRuntimeApiKey(resolvedModel.provider, apiKey);
}
}
const start = Date.now();
// Use pi-ai's completeSimple for a one-shot call
// Pass apiKey directly in options — completeSimple uses options.apiKey || env var
const userMsg: PiUserMessage = { role: 'user', content: prompt, timestamp: Date.now() };
log(
'[OneShot] Calling completeSimple:',
resolvedModel.provider,
resolvedModel.id,
'baseUrl:',
resolvedModel.baseUrl,
'api:',
resolvedModel.api
);
const response = await completeSimple(
resolvedModel,
{
systemPrompt,
messages: [userMsg],
},
{ ...options, apiKey: apiKey || undefined }
);
// pi-ai resolves (not rejects) on provider errors — the error details
// live in stopReason/errorMessage on the response object. Surface them
// so callers (probe, title-gen) get a meaningful error via mapPiAiError.
if (response.stopReason === 'error' || response.stopReason === 'aborted') {
logWarn('[OneShot] Provider error-as-resolve:', response.stopReason, response.errorMessage);
throw new Error(response.errorMessage || 'Provider returned an error');
}
// Extract text and thinking content from response
const textBlocks = response.content.filter((b) => b.type === 'text');
const thinkingBlocks = response.content.filter((b) => b.type === 'thinking');
const text = textBlocks
.map((b) => (b as { text: string }).text)
.join('')
.trim();
const hasThinking = thinkingBlocks.some(
(b) => (b as { thinking: string }).thinking?.trim().length > 0
);
log(
'[OneShot] Response:',
text ? text.substring(0, 200) : '(empty)',
'blocks:',
response.content.length,
'textBlocks:',
textBlocks.length,
'thinkingBlocks:',
thinkingBlocks.length
);
return { text, hasThinking, durationMs: Date.now() - start };
}
function normalizeProbeAck(raw: string): string {
// Strip markdown formatting and quotes around/between words, but preserve
// underscores inside words (PROBE_ACK = 'sdk_probe_ok' contains underscores).
return raw
.replace(/(?<!\w)[*_~`"']+|[*_~`"']+(?!\w)/g, '')
.replace(/[.,!?;:]+$/g, '')
.trim()
.toLowerCase();
}
export async function probeWithClaudeSdk(
input: ApiTestInput,
config: AppConfig
): Promise<ApiTestResult> {
const probeConfig = buildProbeConfig(input, config);
if (input.provider === 'custom' && !probeConfig.baseUrl?.trim()) {
return { ok: false, errorType: 'missing_base_url' };
}
if (!probeConfig.model?.trim()) {
return { ok: false, errorType: 'unknown', details: 'missing_model' };
}
if (!probeConfig.apiKey?.trim()) {
return { ok: false, errorType: 'missing_key', details: 'API key is required.' };
}
const probeStart = Date.now();
try {
const result = await runPiAiOneShot(
`What is 2+2? After answering, also include this token: ${PROBE_ACK}`,
`You are a connectivity test. Answer briefly, then include the token: ${PROBE_ACK}`,
probeConfig
);
if (!result.text && !result.hasThinking) {
return {
ok: false,
latencyMs: result.durationMs,
errorType: 'unknown',
details: 'empty_probe_response',
};
}
// Thinking models may respond only with reasoning content and no text —
// treat as successful probe since the model is reachable and responding.
if (!result.text && result.hasThinking) {
log(
'[Probe] Thinking-only response — treating as ok (model reachable, cannot validate ack text)'
);
return { ok: true, latencyMs: result.durationMs };
}
if (!normalizeProbeAck(result.text).includes(PROBE_ACK)) {
return {
ok: false,
latencyMs: result.durationMs,
errorType: 'unknown',
details: `probe_response_mismatch:${result.text.slice(0, 120)}`,
};
}
return { ok: true, latencyMs: result.durationMs };
} catch (error) {
const details = error instanceof Error ? error.message : String(error);
const elapsed = Date.now() - probeStart;
const route = resolvePiRouteProtocol(input.provider, probeConfig.customProtocol);
const relayBaseUrl = probeConfig.baseUrl?.trim();
if (
route === 'gemini' &&
relayBaseUrl &&
probeConfig.apiKey &&
probeConfig.model &&
isGeminiSdkProbeUnavailableError(details)
) {
logWarn('[Probe] Gemini SDK probe failed, trying HTTP generateContent:', details);
const httpResult = await probeGeminiRelayGenerateContent({
baseUrl: relayBaseUrl,
apiKey: probeConfig.apiKey,
model: probeConfig.model,
});
if (httpResult.ok) {
return httpResult;
}
}
return mapPiAiError(details, elapsed, input.provider);
}
}
export async function generateTitleWithClaudeSdk(
titlePrompt: string,
config: AppConfig
): Promise<string | null> {
try {
const result = await runPiAiOneShot(
titlePrompt,
'Generate a concise title. Reply with only the title text and no extra markup.',
config
);
const title = normalizeGeneratedTitle(result.text);
if (!title && result.hasThinking) {
logWarn('[SessionTitle] Thinking model returned reasoning only — no usable title text');
}
return title;
} catch (error) {
logWarn('[SessionTitle] pi-ai title generation failed:', error);
return null;
}
}