forked from ultraworkers/claw-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclaude.ts
More file actions
3419 lines (3212 loc) · 123 KB
/
Copy pathclaude.ts
File metadata and controls
3419 lines (3212 loc) · 123 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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type {
BetaContentBlock,
BetaContentBlockParam,
BetaImageBlockParam,
BetaJSONOutputFormat,
BetaMessage,
BetaMessageDeltaUsage,
BetaMessageStreamParams,
BetaOutputConfig,
BetaRawMessageStreamEvent,
BetaRequestDocumentBlock,
BetaStopReason,
BetaToolChoiceAuto,
BetaToolChoiceTool,
BetaToolResultBlockParam,
BetaToolUnion,
BetaUsage,
BetaMessageParam as MessageParam,
} from '@anthropic-ai/sdk/resources/beta/messages/messages.mjs'
import type { TextBlockParam } from '@anthropic-ai/sdk/resources/index.mjs'
import type { Stream } from '@anthropic-ai/sdk/streaming.mjs'
import { randomUUID } from 'crypto'
import {
getAPIProvider,
isFirstPartyAnthropicBaseUrl,
} from 'src/utils/model/providers.js'
import {
getAttributionHeader,
getCLISyspromptPrefix,
} from '../../constants/system.js'
import {
getEmptyToolPermissionContext,
type QueryChainTracking,
type Tool,
type ToolPermissionContext,
type Tools,
toolMatchesName,
} from '../../Tool.js'
import type { AgentDefinition } from '../../tools/AgentTool/loadAgentsDir.js'
import {
type ConnectorTextBlock,
type ConnectorTextDelta,
isConnectorTextBlock,
} from '../../types/connectorText.js'
import type {
AssistantMessage,
Message,
StreamEvent,
SystemAPIErrorMessage,
UserMessage,
} from '../../types/message.js'
import {
type CacheScope,
logAPIPrefix,
splitSysPromptPrefix,
toolToAPISchema,
} from '../../utils/api.js'
import { getOauthAccountInfo } from '../../utils/auth.js'
import {
getBedrockExtraBodyParamsBetas,
getMergedBetas,
getModelBetas,
} from '../../utils/betas.js'
import { getOrCreateUserID } from '../../utils/config.js'
import {
CAPPED_DEFAULT_MAX_TOKENS,
getModelMaxOutputTokens,
getSonnet1mExpTreatmentEnabled,
} from '../../utils/context.js'
import { resolveAppliedEffort } from '../../utils/effort.js'
import { isEnvTruthy } from '../../utils/envUtils.js'
import { errorMessage } from '../../utils/errors.js'
import { computeFingerprintFromMessages } from '../../utils/fingerprint.js'
import { captureAPIRequest, logError } from '../../utils/log.js'
import {
createAssistantAPIErrorMessage,
createUserMessage,
ensureToolResultPairing,
normalizeContentFromAPI,
normalizeMessagesForAPI,
stripAdvisorBlocks,
stripCallerFieldFromAssistantMessage,
stripToolReferenceBlocksFromUserMessage,
} from '../../utils/messages.js'
import {
getDefaultOpusModel,
getDefaultSonnetModel,
getSmallFastModel,
isNonCustomOpusModel,
} from '../../utils/model/model.js'
import {
asSystemPrompt,
type SystemPrompt,
} from '../../utils/systemPromptType.js'
import { tokenCountFromLastAPIResponse } from '../../utils/tokens.js'
import { getDynamicConfig_BLOCKS_ON_INIT } from '../analytics/growthbook.js'
import {
currentLimits,
extractQuotaStatusFromError,
extractQuotaStatusFromHeaders,
} from '../claudeAiLimits.js'
import { getAPIContextManagement } from '../compact/apiMicrocompact.js'
/* eslint-disable @typescript-eslint/no-require-imports */
const autoModeStateModule = feature('TRANSCRIPT_CLASSIFIER')
? (require('../../utils/permissions/autoModeState.js') as typeof import('../../utils/permissions/autoModeState.js'))
: null
import { feature } from 'bun:bundle'
import type { ClientOptions } from '@anthropic-ai/sdk'
import {
APIConnectionTimeoutError,
APIError,
APIUserAbortError,
} from '@anthropic-ai/sdk/error'
import {
getAfkModeHeaderLatched,
getCacheEditingHeaderLatched,
getFastModeHeaderLatched,
getLastApiCompletionTimestamp,
getPromptCache1hAllowlist,
getPromptCache1hEligible,
getSessionId,
getThinkingClearLatched,
setAfkModeHeaderLatched,
setCacheEditingHeaderLatched,
setFastModeHeaderLatched,
setLastMainRequestId,
setPromptCache1hAllowlist,
setPromptCache1hEligible,
setThinkingClearLatched,
} from 'src/bootstrap/state.js'
import {
AFK_MODE_BETA_HEADER,
CONTEXT_1M_BETA_HEADER,
CONTEXT_MANAGEMENT_BETA_HEADER,
EFFORT_BETA_HEADER,
FAST_MODE_BETA_HEADER,
PROMPT_CACHING_SCOPE_BETA_HEADER,
REDACT_THINKING_BETA_HEADER,
STRUCTURED_OUTPUTS_BETA_HEADER,
TASK_BUDGETS_BETA_HEADER,
} from 'src/constants/betas.js'
import type { QuerySource } from 'src/constants/querySource.js'
import type { Notification } from 'src/context/notifications.js'
import { addToTotalSessionCost } from 'src/cost-tracker.js'
import { getFeatureValue_CACHED_MAY_BE_STALE } from 'src/services/analytics/growthbook.js'
import type { AgentId } from 'src/types/ids.js'
import {
ADVISOR_TOOL_INSTRUCTIONS,
getExperimentAdvisorModels,
isAdvisorEnabled,
isValidAdvisorModel,
modelSupportsAdvisor,
} from 'src/utils/advisor.js'
import { getAgentContext } from 'src/utils/agentContext.js'
import { isClaudeAISubscriber } from 'src/utils/auth.js'
import {
getToolSearchBetaHeader,
modelSupportsStructuredOutputs,
shouldIncludeFirstPartyOnlyBetas,
shouldUseGlobalCacheScope,
} from 'src/utils/betas.js'
import { CLAUDE_IN_CHROME_MCP_SERVER_NAME } from 'src/utils/claudeInChrome/common.js'
import { CHROME_TOOL_SEARCH_INSTRUCTIONS } from 'src/utils/claudeInChrome/prompt.js'
import { getMaxThinkingTokensForModel } from 'src/utils/context.js'
import { logForDebugging } from 'src/utils/debug.js'
import { logForDiagnosticsNoPII } from 'src/utils/diagLogs.js'
import { type EffortValue, modelSupportsEffort } from 'src/utils/effort.js'
import {
isFastModeAvailable,
isFastModeCooldown,
isFastModeEnabled,
isFastModeSupportedByModel,
} from 'src/utils/fastMode.js'
import { returnValue } from 'src/utils/generators.js'
import { headlessProfilerCheckpoint } from 'src/utils/headlessProfiler.js'
import { isMcpInstructionsDeltaEnabled } from 'src/utils/mcpInstructionsDelta.js'
import { calculateUSDCost } from 'src/utils/modelCost.js'
import { endQueryProfile, queryCheckpoint } from 'src/utils/queryProfiler.js'
import {
modelSupportsAdaptiveThinking,
modelSupportsThinking,
type ThinkingConfig,
} from 'src/utils/thinking.js'
import {
extractDiscoveredToolNames,
isDeferredToolsDeltaEnabled,
isToolSearchEnabled,
} from 'src/utils/toolSearch.js'
import { API_MAX_MEDIA_PER_REQUEST } from '../../constants/apiLimits.js'
import { ADVISOR_BETA_HEADER } from '../../constants/betas.js'
import {
formatDeferredToolLine,
isDeferredTool,
TOOL_SEARCH_TOOL_NAME,
} from '../../tools/ToolSearchTool/prompt.js'
import { count } from '../../utils/array.js'
import { insertBlockAfterToolResults } from '../../utils/contentArray.js'
import { validateBoundedIntEnvVar } from '../../utils/envValidation.js'
import { safeParseJSON } from '../../utils/json.js'
import { getInferenceProfileBackingModel } from '../../utils/model/bedrock.js'
import {
normalizeModelStringForAPI,
parseUserSpecifiedModel,
} from '../../utils/model/model.js'
import {
startSessionActivity,
stopSessionActivity,
} from '../../utils/sessionActivity.js'
import { jsonStringify } from '../../utils/slowOperations.js'
import {
isBetaTracingEnabled,
type LLMRequestNewContext,
startLLMRequestSpan,
} from '../../utils/telemetry/sessionTracing.js'
/* eslint-enable @typescript-eslint/no-require-imports */
import {
type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
logEvent,
} from '../analytics/index.js'
import {
consumePendingCacheEdits,
getPinnedCacheEdits,
markToolsSentToAPIState,
pinCacheEdits,
} from '../compact/microCompact.js'
import { getInitializationStatus } from '../lsp/manager.js'
import { isToolFromMcpServer } from '../mcp/utils.js'
import { withStreamingVCR, withVCR } from '../vcr.js'
import { CLIENT_REQUEST_ID_HEADER, getAnthropicClient } from './client.js'
import {
API_ERROR_MESSAGE_PREFIX,
CUSTOM_OFF_SWITCH_MESSAGE,
getAssistantMessageFromError,
getErrorMessageIfRefusal,
} from './errors.js'
import {
EMPTY_USAGE,
type GlobalCacheStrategy,
logAPIError,
logAPIQuery,
logAPISuccessAndDuration,
type NonNullableUsage,
} from './logging.js'
import {
CACHE_TTL_1HOUR_MS,
checkResponseForCacheBreak,
recordPromptState,
} from './promptCacheBreakDetection.js'
import {
CannotRetryError,
FallbackTriggeredError,
is529Error,
type RetryContext,
withRetry,
} from './withRetry.js'
// Define a type that represents valid JSON values
type JsonValue = string | number | boolean | null | JsonObject | JsonArray
type JsonObject = { [key: string]: JsonValue }
type JsonArray = JsonValue[]
/**
* Assemble the extra body parameters for the API request, based on the
* CLAUDE_CODE_EXTRA_BODY environment variable if present and on any beta
* headers (primarily for Bedrock requests).
*
* @param betaHeaders - An array of beta headers to include in the request.
* @returns A JSON object representing the extra body parameters.
*/
export function getExtraBodyParams(betaHeaders?: string[]): JsonObject {
// Parse user's extra body parameters first
const extraBodyStr = process.env.CLAUDE_CODE_EXTRA_BODY
let result: JsonObject = {}
if (extraBodyStr) {
try {
// Parse as JSON, which can be null, boolean, number, string, array or object
const parsed = safeParseJSON(extraBodyStr)
// We expect an object with key-value pairs to spread into API parameters
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
// Shallow clone — safeParseJSON is LRU-cached and returns the same
// object reference for the same string. Mutating `result` below
// would poison the cache, causing stale values to persist.
result = { ...(parsed as JsonObject) }
} else {
logForDebugging(
`CLAUDE_CODE_EXTRA_BODY env var must be a JSON object, but was given ${extraBodyStr}`,
{ level: 'error' },
)
}
} catch (error) {
logForDebugging(
`Error parsing CLAUDE_CODE_EXTRA_BODY: ${errorMessage(error)}`,
{ level: 'error' },
)
}
}
// Anti-distillation: send fake_tools opt-in for 1P CLI only
if (
feature('ANTI_DISTILLATION_CC')
? process.env.CLAUDE_CODE_ENTRYPOINT === 'cli' &&
shouldIncludeFirstPartyOnlyBetas() &&
getFeatureValue_CACHED_MAY_BE_STALE(
'tengu_anti_distill_fake_tool_injection',
false,
)
: false
) {
result.anti_distillation = ['fake_tools']
}
// Handle beta headers if provided
if (betaHeaders && betaHeaders.length > 0) {
if (result.anthropic_beta && Array.isArray(result.anthropic_beta)) {
// Add to existing array, avoiding duplicates
const existingHeaders = result.anthropic_beta as string[]
const newHeaders = betaHeaders.filter(
header => !existingHeaders.includes(header),
)
result.anthropic_beta = [...existingHeaders, ...newHeaders]
} else {
// Create new array with the beta headers
result.anthropic_beta = betaHeaders
}
}
return result
}
export function getPromptCachingEnabled(model: string): boolean {
// Global disable takes precedence
if (isEnvTruthy(process.env.DISABLE_PROMPT_CACHING)) return false
// Check if we should disable for small/fast model
if (isEnvTruthy(process.env.DISABLE_PROMPT_CACHING_HAIKU)) {
const smallFastModel = getSmallFastModel()
if (model === smallFastModel) return false
}
// Check if we should disable for default Sonnet
if (isEnvTruthy(process.env.DISABLE_PROMPT_CACHING_SONNET)) {
const defaultSonnet = getDefaultSonnetModel()
if (model === defaultSonnet) return false
}
// Check if we should disable for default Opus
if (isEnvTruthy(process.env.DISABLE_PROMPT_CACHING_OPUS)) {
const defaultOpus = getDefaultOpusModel()
if (model === defaultOpus) return false
}
return true
}
export function getCacheControl({
scope,
querySource,
}: {
scope?: CacheScope
querySource?: QuerySource
} = {}): {
type: 'ephemeral'
ttl?: '1h'
scope?: CacheScope
} {
return {
type: 'ephemeral',
...(should1hCacheTTL(querySource) && { ttl: '1h' }),
...(scope === 'global' && { scope }),
}
}
/**
* Determines if 1h TTL should be used for prompt caching.
*
* Only applied when:
* 1. User is eligible (ant or subscriber within rate limits)
* 2. The query source matches a pattern in the GrowthBook allowlist
*
* GrowthBook config shape: { allowlist: string[] }
* Patterns support trailing '*' for prefix matching.
* Examples:
* - { allowlist: ["repl_main_thread*", "sdk"] } — main thread + SDK only
* - { allowlist: ["repl_main_thread*", "sdk", "agent:*"] } — also subagents
* - { allowlist: ["*"] } — all sources
*
* The allowlist is cached in STATE for session stability — prevents mixed
* TTLs when GrowthBook's disk cache updates mid-request.
*/
function should1hCacheTTL(querySource?: QuerySource): boolean {
// 3P Bedrock users get 1h TTL when opted in via env var — they manage their own billing
// No GrowthBook gating needed since 3P users don't have GrowthBook configured
if (
getAPIProvider() === 'bedrock' &&
isEnvTruthy(process.env.ENABLE_PROMPT_CACHING_1H_BEDROCK)
) {
return true
}
// Latch eligibility in bootstrap state for session stability — prevents
// mid-session overage flips from changing the cache_control TTL, which
// would bust the server-side prompt cache (~20K tokens per flip).
let userEligible = getPromptCache1hEligible()
if (userEligible === null) {
userEligible =
process.env.USER_TYPE === 'ant' ||
(isClaudeAISubscriber() && !currentLimits.isUsingOverage)
setPromptCache1hEligible(userEligible)
}
if (!userEligible) return false
// Cache allowlist in bootstrap state for session stability — prevents mixed
// TTLs when GrowthBook's disk cache updates mid-request
let allowlist = getPromptCache1hAllowlist()
if (allowlist === null) {
const config = getFeatureValue_CACHED_MAY_BE_STALE<{
allowlist?: string[]
}>('tengu_prompt_cache_1h_config', {})
allowlist = config.allowlist ?? []
setPromptCache1hAllowlist(allowlist)
}
return (
querySource !== undefined &&
allowlist.some(pattern =>
pattern.endsWith('*')
? querySource.startsWith(pattern.slice(0, -1))
: querySource === pattern,
)
)
}
/**
* Configure effort parameters for API request.
*
*/
function configureEffortParams(
effortValue: EffortValue | undefined,
outputConfig: BetaOutputConfig,
extraBodyParams: Record<string, unknown>,
betas: string[],
model: string,
): void {
if (!modelSupportsEffort(model) || 'effort' in outputConfig) {
return
}
if (effortValue === undefined) {
betas.push(EFFORT_BETA_HEADER)
} else if (typeof effortValue === 'string') {
// Send string effort level as is
outputConfig.effort = effortValue
betas.push(EFFORT_BETA_HEADER)
} else if (process.env.USER_TYPE === 'ant') {
// Numeric effort override - ant-only (uses anthropic_internal)
const existingInternal =
(extraBodyParams.anthropic_internal as Record<string, unknown>) || {}
extraBodyParams.anthropic_internal = {
...existingInternal,
effort_override: effortValue,
}
}
}
// output_config.task_budget — API-side token budget awareness for the model.
// Stainless SDK types don't yet include task_budget on BetaOutputConfig, so we
// define the wire shape locally and cast. The API validates on receipt; see
// api/api/schemas/messages/request/output_config.py:12-39 in the monorepo.
// Beta: task-budgets-2026-03-13 (EAP, claude-strudel-eap only as of Mar 2026).
type TaskBudgetParam = {
type: 'tokens'
total: number
remaining?: number
}
export function configureTaskBudgetParams(
taskBudget: Options['taskBudget'],
outputConfig: BetaOutputConfig & { task_budget?: TaskBudgetParam },
betas: string[],
): void {
if (
!taskBudget ||
'task_budget' in outputConfig ||
!shouldIncludeFirstPartyOnlyBetas()
) {
return
}
outputConfig.task_budget = {
type: 'tokens',
total: taskBudget.total,
...(taskBudget.remaining !== undefined && {
remaining: taskBudget.remaining,
}),
}
if (!betas.includes(TASK_BUDGETS_BETA_HEADER)) {
betas.push(TASK_BUDGETS_BETA_HEADER)
}
}
export function getAPIMetadata() {
// https://docs.google.com/document/d/1dURO9ycXXQCBS0V4Vhl4poDBRgkelFc5t2BNPoEgH5Q/edit?tab=t.0#heading=h.5g7nec5b09w5
let extra: JsonObject = {}
const extraStr = process.env.CLAUDE_CODE_EXTRA_METADATA
if (extraStr) {
const parsed = safeParseJSON(extraStr, false)
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
extra = parsed as JsonObject
} else {
logForDebugging(
`CLAUDE_CODE_EXTRA_METADATA env var must be a JSON object, but was given ${extraStr}`,
{ level: 'error' },
)
}
}
return {
user_id: jsonStringify({
...extra,
device_id: getOrCreateUserID(),
// Only include OAuth account UUID when actively using OAuth authentication
account_uuid: getOauthAccountInfo()?.accountUuid ?? '',
session_id: getSessionId(),
}),
}
}
export async function verifyApiKey(
apiKey: string,
isNonInteractiveSession: boolean,
): Promise<boolean> {
// Skip API verification if running in print mode (isNonInteractiveSession)
if (isNonInteractiveSession) {
return true
}
try {
// WARNING: if you change this to use a non-Haiku model, this request will fail in 1P unless it uses getCLISyspromptPrefix.
const model = getSmallFastModel()
const betas = getModelBetas(model)
return await returnValue(
withRetry(
() =>
getAnthropicClient({
apiKey,
maxRetries: 3,
model,
source: 'verify_api_key',
}),
async anthropic => {
const messages: MessageParam[] = [{ role: 'user', content: 'test' }]
// biome-ignore lint/plugin: API key verification is intentionally a minimal direct call
await anthropic.beta.messages.create({
model,
max_tokens: 1,
messages,
temperature: 1,
...(betas.length > 0 && { betas }),
metadata: getAPIMetadata(),
...getExtraBodyParams(),
})
return true
},
{ maxRetries: 2, model, thinkingConfig: { type: 'disabled' } }, // Use fewer retries for API key verification
),
)
} catch (errorFromRetry) {
let error = errorFromRetry
if (errorFromRetry instanceof CannotRetryError) {
error = errorFromRetry.originalError
}
logError(error)
// Check for authentication error
if (
error instanceof Error &&
error.message.includes(
'{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}',
)
) {
return false
}
throw error
}
}
export function userMessageToMessageParam(
message: UserMessage,
addCache = false,
enablePromptCaching: boolean,
querySource?: QuerySource,
): MessageParam {
if (addCache) {
if (typeof message.message.content === 'string') {
return {
role: 'user',
content: [
{
type: 'text',
text: message.message.content,
...(enablePromptCaching && {
cache_control: getCacheControl({ querySource }),
}),
},
],
}
} else {
return {
role: 'user',
content: message.message.content.map((_, i) => ({
..._,
...(i === message.message.content.length - 1
? enablePromptCaching
? { cache_control: getCacheControl({ querySource }) }
: {}
: {}),
})),
}
}
}
// Clone array content to prevent in-place mutations (e.g., insertCacheEditsBlock's
// splice) from contaminating the original message. Without cloning, multiple calls
// to addCacheBreakpoints share the same array and each splices in duplicate cache_edits.
return {
role: 'user',
content: Array.isArray(message.message.content)
? [...message.message.content]
: message.message.content,
}
}
export function assistantMessageToMessageParam(
message: AssistantMessage,
addCache = false,
enablePromptCaching: boolean,
querySource?: QuerySource,
): MessageParam {
if (addCache) {
if (typeof message.message.content === 'string') {
return {
role: 'assistant',
content: [
{
type: 'text',
text: message.message.content,
...(enablePromptCaching && {
cache_control: getCacheControl({ querySource }),
}),
},
],
}
} else {
return {
role: 'assistant',
content: message.message.content.map((_, i) => ({
..._,
...(i === message.message.content.length - 1 &&
_.type !== 'thinking' &&
_.type !== 'redacted_thinking' &&
(feature('CONNECTOR_TEXT') ? !isConnectorTextBlock(_) : true)
? enablePromptCaching
? { cache_control: getCacheControl({ querySource }) }
: {}
: {}),
})),
}
}
}
return {
role: 'assistant',
content: message.message.content,
}
}
export type Options = {
getToolPermissionContext: () => Promise<ToolPermissionContext>
model: string
toolChoice?: BetaToolChoiceTool | BetaToolChoiceAuto | undefined
isNonInteractiveSession: boolean
extraToolSchemas?: BetaToolUnion[]
maxOutputTokensOverride?: number
fallbackModel?: string
onStreamingFallback?: () => void
querySource: QuerySource
agents: AgentDefinition[]
allowedAgentTypes?: string[]
hasAppendSystemPrompt: boolean
fetchOverride?: ClientOptions['fetch']
enablePromptCaching?: boolean
skipCacheWrite?: boolean
temperatureOverride?: number
effortValue?: EffortValue
mcpTools: Tools
hasPendingMcpServers?: boolean
queryTracking?: QueryChainTracking
agentId?: AgentId // Only set for subagents
outputFormat?: BetaJSONOutputFormat
fastMode?: boolean
advisorModel?: string
addNotification?: (notif: Notification) => void
// API-side task budget (output_config.task_budget). Distinct from the
// tokenBudget.ts +500k auto-continue feature — this one is sent to the API
// so the model can pace itself. `remaining` is computed by the caller
// (query.ts decrements across the agentic loop).
taskBudget?: { total: number; remaining?: number }
}
export async function queryModelWithoutStreaming({
messages,
systemPrompt,
thinkingConfig,
tools,
signal,
options,
}: {
messages: Message[]
systemPrompt: SystemPrompt
thinkingConfig: ThinkingConfig
tools: Tools
signal: AbortSignal
options: Options
}): Promise<AssistantMessage> {
// Store the assistant message but continue consuming the generator to ensure
// logAPISuccessAndDuration gets called (which happens after all yields)
let assistantMessage: AssistantMessage | undefined
for await (const message of withStreamingVCR(messages, async function* () {
yield* queryModel(
messages,
systemPrompt,
thinkingConfig,
tools,
signal,
options,
)
})) {
if (message.type === 'assistant') {
assistantMessage = message
}
}
if (!assistantMessage) {
// If the signal was aborted, throw APIUserAbortError instead of a generic error
// This allows callers to handle abort scenarios gracefully
if (signal.aborted) {
throw new APIUserAbortError()
}
throw new Error('No assistant message found')
}
return assistantMessage
}
export async function* queryModelWithStreaming({
messages,
systemPrompt,
thinkingConfig,
tools,
signal,
options,
}: {
messages: Message[]
systemPrompt: SystemPrompt
thinkingConfig: ThinkingConfig
tools: Tools
signal: AbortSignal
options: Options
}): AsyncGenerator<
StreamEvent | AssistantMessage | SystemAPIErrorMessage,
void
> {
return yield* withStreamingVCR(messages, async function* () {
yield* queryModel(
messages,
systemPrompt,
thinkingConfig,
tools,
signal,
options,
)
})
}
/**
* Determines if an LSP tool should be deferred (tool appears with defer_loading: true)
* because LSP initialization is not yet complete.
*/
function shouldDeferLspTool(tool: Tool): boolean {
if (!('isLsp' in tool) || !tool.isLsp) {
return false
}
const status = getInitializationStatus()
// Defer when pending or not started
return status.status === 'pending' || status.status === 'not-started'
}
/**
* Per-attempt timeout for non-streaming fallback requests, in milliseconds.
* Reads API_TIMEOUT_MS when set so slow backends and the streaming path
* share the same ceiling.
*
* Remote sessions default to 120s to stay under CCR's container idle-kill
* (~5min) so a hung fallback to a wedged backend surfaces a clean
* APIConnectionTimeoutError instead of stalling past SIGKILL.
*
* Otherwise defaults to 300s — long enough for slow backends without
* approaching the API's 10-minute non-streaming boundary.
*/
function getNonstreamingFallbackTimeoutMs(): number {
const override = parseInt(process.env.API_TIMEOUT_MS || '', 10)
if (override) return override
return isEnvTruthy(process.env.CLAUDE_CODE_REMOTE) ? 120_000 : 300_000
}
/**
* Helper generator for non-streaming API requests.
* Encapsulates the common pattern of creating a withRetry generator,
* iterating to yield system messages, and returning the final BetaMessage.
*/
export async function* executeNonStreamingRequest(
clientOptions: {
model: string
fetchOverride?: Options['fetchOverride']
source: string
},
retryOptions: {
model: string
fallbackModel?: string
thinkingConfig: ThinkingConfig
fastMode?: boolean
signal: AbortSignal
initialConsecutive529Errors?: number
querySource?: QuerySource
},
paramsFromContext: (context: RetryContext) => BetaMessageStreamParams,
onAttempt: (attempt: number, start: number, maxOutputTokens: number) => void,
captureRequest: (params: BetaMessageStreamParams) => void,
/**
* Request ID of the failed streaming attempt this fallback is recovering
* from. Emitted in tengu_nonstreaming_fallback_error for funnel correlation.
*/
originatingRequestId?: string | null,
): AsyncGenerator<SystemAPIErrorMessage, BetaMessage> {
const fallbackTimeoutMs = getNonstreamingFallbackTimeoutMs()
const generator = withRetry(
() =>
getAnthropicClient({
maxRetries: 0,
model: clientOptions.model,
fetchOverride: clientOptions.fetchOverride,
source: clientOptions.source,
}),
async (anthropic, attempt, context) => {
const start = Date.now()
const retryParams = paramsFromContext(context)
captureRequest(retryParams)
onAttempt(attempt, start, retryParams.max_tokens)
const adjustedParams = adjustParamsForNonStreaming(
retryParams,
MAX_NON_STREAMING_TOKENS,
)
try {
// biome-ignore lint/plugin: non-streaming API call
return await anthropic.beta.messages.create(
{
...adjustedParams,
model: normalizeModelStringForAPI(adjustedParams.model),
},
{
signal: retryOptions.signal,
timeout: fallbackTimeoutMs,
},
)
} catch (err) {
// User aborts are not errors — re-throw immediately without logging
if (err instanceof APIUserAbortError) throw err
// Instrumentation: record when the non-streaming request errors (including
// timeouts). Lets us distinguish "fallback hung past container kill"
// (no event) from "fallback hit the bounded timeout" (this event).
logForDiagnosticsNoPII('error', 'cli_nonstreaming_fallback_error')
logEvent('tengu_nonstreaming_fallback_error', {
model:
clientOptions.model as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
error:
err instanceof Error
? (err.name as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS)
: ('unknown' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS),
attempt,
timeout_ms: fallbackTimeoutMs,
request_id: (originatingRequestId ??
'unknown') as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
})
throw err
}
},
{
model: retryOptions.model,
fallbackModel: retryOptions.fallbackModel,
thinkingConfig: retryOptions.thinkingConfig,
...(isFastModeEnabled() && { fastMode: retryOptions.fastMode }),
signal: retryOptions.signal,
initialConsecutive529Errors: retryOptions.initialConsecutive529Errors,
querySource: retryOptions.querySource,
},
)
let e
do {
e = await generator.next()
if (!e.done && e.value.type === 'system') {
yield e.value
}
} while (!e.done)
return e.value as BetaMessage
}
/**
* Extracts the request ID from the most recent assistant message in the
* conversation. Used to link consecutive API requests in analytics so we can
* join them for cache-hit-rate analysis and incremental token tracking.
*
* Deriving this from the message array (rather than global state) ensures each
* query chain (main thread, subagent, teammate) tracks its own request chain
* independently, and rollback/undo naturally updates the value.
*/
function getPreviousRequestIdFromMessages(
messages: Message[],
): string | undefined {
for (let i = messages.length - 1; i >= 0; i--) {
const msg = messages[i]!
if (msg.type === 'assistant' && msg.requestId) {
return msg.requestId
}
}
return undefined
}
function isMedia(
block: BetaContentBlockParam,
): block is BetaImageBlockParam | BetaRequestDocumentBlock {
return block.type === 'image' || block.type === 'document'
}
function isToolResult(
block: BetaContentBlockParam,
): block is BetaToolResultBlockParam {
return block.type === 'tool_result'
}
/**
* Ensures messages contain at most `limit` media items (images + documents).
* Strips oldest media first to preserve the most recent.
*/
export function stripExcessMediaItems(
messages: (UserMessage | AssistantMessage)[],
limit: number,
): (UserMessage | AssistantMessage)[] {
let toRemove = 0
for (const msg of messages) {
if (!Array.isArray(msg.message.content)) continue
for (const block of msg.message.content) {
if (isMedia(block)) toRemove++
if (isToolResult(block) && Array.isArray(block.content)) {
for (const nested of block.content) {
if (isMedia(nested)) toRemove++
}
}
}
}
toRemove -= limit
if (toRemove <= 0) return messages
return messages.map(msg => {
if (toRemove <= 0) return msg
const content = msg.message.content
if (!Array.isArray(content)) return msg
const before = toRemove
const stripped = content
.map(block => {
if (
toRemove <= 0 ||
!isToolResult(block) ||
!Array.isArray(block.content)
)
return block
const filtered = block.content.filter(n => {
if (toRemove > 0 && isMedia(n)) {
toRemove--
return false
}
return true
})
return filtered.length === block.content.length
? block
: { ...block, content: filtered }
})
.filter(block => {