forked from liuup/claude-code-analysis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueryContext.ts
More file actions
179 lines (171 loc) Β· 5.8 KB
/
queryContext.ts
File metadata and controls
179 lines (171 loc) Β· 5.8 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
/**
* Shared helpers for building the API cache-key prefix (systemPrompt,
* userContext, systemContext) for query() calls.
*
* Lives in its own file because it imports from context.ts and
* constants/prompts.ts, which are high in the dependency graph. Putting
* these imports in systemPrompt.ts or sideQuestion.ts (both reachable
* from commands.ts) would create cycles. Only entrypoint-layer files
* import from here (QueryEngine.ts, cli/print.ts).
*/
import type { Command } from '../commands.js'
import { getSystemPrompt } from '../constants/prompts.js'
import { getSystemContext, getUserContext } from '../context.js'
import type { MCPServerConnection } from '../services/mcp/types.js'
import type { AppState } from '../state/AppStateStore.js'
import type { Tools, ToolUseContext } from '../Tool.js'
import type { AgentDefinition } from '../tools/AgentTool/loadAgentsDir.js'
import type { Message } from '../types/message.js'
import { createAbortController } from './abortController.js'
import type { FileStateCache } from './fileStateCache.js'
import type { CacheSafeParams } from './forkedAgent.js'
import { getMainLoopModel } from './model/model.js'
import { asSystemPrompt } from './systemPromptType.js'
import {
shouldEnableThinkingByDefault,
type ThinkingConfig,
} from './thinking.js'
/**
* Fetch the three context pieces that form the API cache-key prefix:
* systemPrompt parts, userContext, systemContext.
*
* When customSystemPrompt is set, the default getSystemPrompt build and
* getSystemContext are skipped β the custom prompt replaces the default
* entirely, and systemContext would be appended to a default that isn't
* being used.
*
* Callers assemble the final systemPrompt from defaultSystemPrompt (or
* customSystemPrompt) + optional extras + appendSystemPrompt. QueryEngine
* injects coordinator userContext and memory-mechanics prompt on top;
* sideQuestion's fallback uses the base result directly.
*/
export async function fetchSystemPromptParts({
tools,
mainLoopModel,
additionalWorkingDirectories,
mcpClients,
customSystemPrompt,
}: {
tools: Tools
mainLoopModel: string
additionalWorkingDirectories: string[]
mcpClients: MCPServerConnection[]
customSystemPrompt: string | undefined
}): Promise<{
defaultSystemPrompt: string[]
userContext: { [k: string]: string }
systemContext: { [k: string]: string }
}> {
const [defaultSystemPrompt, userContext, systemContext] = await Promise.all([
customSystemPrompt !== undefined
? Promise.resolve([])
: getSystemPrompt(
tools,
mainLoopModel,
additionalWorkingDirectories,
mcpClients,
),
getUserContext(),
customSystemPrompt !== undefined ? Promise.resolve({}) : getSystemContext(),
])
return { defaultSystemPrompt, userContext, systemContext }
}
/**
* Build CacheSafeParams from raw inputs when getLastCacheSafeParams() is null.
*
* Used by the SDK side_question handler (print.ts) on resume before a turn
* completes β there's no stopHooks snapshot yet. Mirrors the system prompt
* assembly in QueryEngine.ts:ask() so the rebuilt prefix matches what the
* main loop will send, preserving the cache hit in the common case.
*
* May still miss the cache if the main loop applies extras this path doesn't
* know about (coordinator mode, memory-mechanics prompt). That's acceptable β
* the alternative is returning null and failing the side question entirely.
*/
export async function buildSideQuestionFallbackParams({
tools,
commands,
mcpClients,
messages,
readFileState,
getAppState,
setAppState,
customSystemPrompt,
appendSystemPrompt,
thinkingConfig,
agents,
}: {
tools: Tools
commands: Command[]
mcpClients: MCPServerConnection[]
messages: Message[]
readFileState: FileStateCache
getAppState: () => AppState
setAppState: (f: (prev: AppState) => AppState) => void
customSystemPrompt: string | undefined
appendSystemPrompt: string | undefined
thinkingConfig: ThinkingConfig | undefined
agents: AgentDefinition[]
}): Promise<CacheSafeParams> {
const mainLoopModel = getMainLoopModel()
const appState = getAppState()
const { defaultSystemPrompt, userContext, systemContext } =
await fetchSystemPromptParts({
tools,
mainLoopModel,
additionalWorkingDirectories: Array.from(
appState.toolPermissionContext.additionalWorkingDirectories.keys(),
),
mcpClients,
customSystemPrompt,
})
const systemPrompt = asSystemPrompt([
...(customSystemPrompt !== undefined
? [customSystemPrompt]
: defaultSystemPrompt),
...(appendSystemPrompt ? [appendSystemPrompt] : []),
])
// Strip in-progress assistant message (stop_reason === null) β same guard
// as btw.tsx. The SDK can fire side_question mid-turn.
const last = messages.at(-1)
const forkContextMessages =
last?.type === 'assistant' && last.message.stop_reason === null
? messages.slice(0, -1)
: messages
const toolUseContext: ToolUseContext = {
options: {
commands,
debug: false,
mainLoopModel,
tools,
verbose: false,
thinkingConfig:
thinkingConfig ??
(shouldEnableThinkingByDefault() !== false
? { type: 'adaptive' }
: { type: 'disabled' }),
mcpClients,
mcpResources: {},
isNonInteractiveSession: true,
agentDefinitions: { activeAgents: agents, allAgents: [] },
customSystemPrompt,
appendSystemPrompt,
},
abortController: createAbortController(),
readFileState,
getAppState,
setAppState,
messages: forkContextMessages,
setInProgressToolUseIDs: () => {},
setResponseLength: () => {},
updateFileHistoryState: () => {},
updateAttributionState: () => {},
}
return {
systemPrompt,
userContext,
systemContext,
toolUseContext,
forkContextMessages,
}
}