pi-codebuddy-sdk 0.1.17 → 0.1.19
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/README.md +12 -15
- package/package.json +4 -3
- package/src/agents-md.ts +39 -0
- package/src/askcodebuddy-ui.ts +90 -0
- package/src/config.ts +46 -0
- package/src/convert.ts +105 -0
- package/src/index.ts +1784 -92
- package/src/models.ts +19 -0
- package/src/query-state.ts +80 -0
- package/src/skills.ts +21 -0
- package/src/provider.ts +0 -289
package/src/index.ts
CHANGED
|
@@ -1,97 +1,1789 @@
|
|
|
1
|
+
import { calculateCost, StringEnum, type AssistantMessage, type AssistantMessageEventStream, type Context, type Model, type SimpleStreamOptions, type Tool } from "@earendil-works/pi-ai";
|
|
2
|
+
import * as piAi from "@earendil-works/pi-ai";
|
|
3
|
+
|
|
4
|
+
import { buildSessionContext, compact, keyHint, type CompactionEntry, type ExtensionAPI, type ExtensionUIContext } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { query, type EffortLevel, type SDKMessage, type SDKUserMessage } from "@tencent-ai/agent-sdk";
|
|
6
|
+
import type { Base64ImageSource, ContentBlockParam, MessageParam } from "@tencent-ai/agent-sdk";
|
|
7
|
+
import { Type } from "typebox";
|
|
8
|
+
import { Text } from "@earendil-works/pi-tui";
|
|
9
|
+
import { appendFileSync, mkdirSync, realpathSync, statSync } from "fs";
|
|
10
|
+
import { homedir } from "os";
|
|
11
|
+
import { dirname, join } from "path";
|
|
12
|
+
import { PROVIDER_ID, messageContentToText, convertPiMessages } from "./convert.js";
|
|
13
|
+
import { buildModels, codebuddyModelId, resolveModel as _resolveModel } from "./models.js";
|
|
14
|
+
import { extractSkillsBlock } from "./skills.js";
|
|
15
|
+
|
|
16
|
+
import { QueryContext, ctx } from "./query-state.js";
|
|
17
|
+
import { loadConfig, type Config } from "./config.js";
|
|
18
|
+
import { extractAgentsAppend } from "./agents-md.js";
|
|
19
|
+
import { buildActionSummary, type ToolCallState } from "./askcodebuddy-ui.js";
|
|
20
|
+
|
|
21
|
+
// Compat (#2): use factory if available (pi-ai ≥0.66), else fall back to constructor (gsd-pi etc.)
|
|
22
|
+
const _piAi = piAi as any;
|
|
23
|
+
const newAssistantMessageEventStream: () => AssistantMessageEventStream =
|
|
24
|
+
typeof _piAi.createAssistantMessageEventStream === "function"
|
|
25
|
+
? _piAi.createAssistantMessageEventStream
|
|
26
|
+
: () => new _piAi.AssistantMessageEventStream();
|
|
27
|
+
|
|
28
|
+
// --- Debug logging ---
|
|
29
|
+
// CODEBUDDY_DEBUG=1 enables debug logging to ~/.pi/agent/codebuddy-sdk.log
|
|
30
|
+
|
|
31
|
+
const DEBUG = process.env.CODEBUDDY_DEBUG === "1";
|
|
32
|
+
const DEBUG_LOG_PATH = process.env.CODEBUDDY_DEBUG_PATH || join(homedir(), ".pi", "agent", "codebuddy-sdk.log");
|
|
33
|
+
const DIAG_LOG_PATH = join(homedir(), ".pi", "agent", "codebuddy-sdk-diag.log");
|
|
34
|
+
|
|
35
|
+
// Ensure log directories exist when debug is enabled
|
|
36
|
+
if (DEBUG) {
|
|
37
|
+
try {
|
|
38
|
+
mkdirSync(dirname(DEBUG_LOG_PATH), { recursive: true });
|
|
39
|
+
mkdirSync(dirname(DIAG_LOG_PATH), { recursive: true });
|
|
40
|
+
} catch {
|
|
41
|
+
// If directory creation fails, debug functions will throw on first use
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Unique per module evaluation — confirms whether subagents share module state
|
|
46
|
+
const moduleInstanceId = Math.random().toString(36).slice(2, 8);
|
|
47
|
+
|
|
48
|
+
function debug(...args: unknown[]) {
|
|
49
|
+
if (!DEBUG) return;
|
|
50
|
+
const ts = new Date().toISOString();
|
|
51
|
+
const fmt = (a: unknown): string => {
|
|
52
|
+
if (typeof a === "string") return a;
|
|
53
|
+
if (a instanceof Error) return `${a.name}: ${a.message}${a.stack ? "\n" + a.stack : ""}`;
|
|
54
|
+
return JSON.stringify(a);
|
|
55
|
+
};
|
|
56
|
+
const msg = args.map(fmt).join(" ");
|
|
57
|
+
appendFileSync(DEBUG_LOG_PATH, `[${ts}] [${moduleInstanceId}] ${msg}\n`);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Per-query CLI debug capture. When CODEBUDDY_DEBUG=1, ask the CodeBuddy
|
|
61
|
+
// CLI subprocess to write its own debug log to a file we choose, and also
|
|
62
|
+
// forward its stderr into our debug stream. Drops straight into the real SDK's
|
|
63
|
+
// Options — see @tencent-ai/agent-sdk sdk.d.ts:1245 (debug, debugFile,
|
|
64
|
+
// stderr). Without this, CC's internal view of the world is invisible to us
|
|
65
|
+
// and "No conversation found" / empty-error reports are unactionable.
|
|
66
|
+
let nextCliDebugSeq = 1;
|
|
67
|
+
function makeCliDebugOptions(tag: string): { debug?: boolean; debugFile?: string; stderr?: (data: string) => void } {
|
|
68
|
+
if (!DEBUG) return {};
|
|
69
|
+
const seq = nextCliDebugSeq++;
|
|
70
|
+
const ts = new Date().toISOString().replace(/[:.]/g, "-");
|
|
71
|
+
const logDir = join(dirname(DEBUG_LOG_PATH), "cc-cli-logs");
|
|
72
|
+
try { mkdirSync(logDir, { recursive: true }); } catch { /* ignore */ }
|
|
73
|
+
const debugFile = join(logDir, `${ts}-${tag}-${seq}.log`);
|
|
74
|
+
debug(`cli-debug: ${tag} #${seq} → ${debugFile}`);
|
|
75
|
+
return {
|
|
76
|
+
debug: true,
|
|
77
|
+
debugFile,
|
|
78
|
+
stderr: (data: string) => {
|
|
79
|
+
for (const line of data.split(/\r?\n/)) {
|
|
80
|
+
if (line) debug(`[cli-stderr ${tag}#${seq}] ${line}`);
|
|
81
|
+
}
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Unconditional diagnostic dump — for "should never happen" paths */
|
|
87
|
+
function diagDump(label: string, data: Record<string, unknown>) {
|
|
88
|
+
const ts = new Date().toISOString();
|
|
89
|
+
const entry = { ts, moduleInstanceId, label, ...data };
|
|
90
|
+
appendFileSync(DIAG_LOG_PATH, JSON.stringify(entry) + "\n");
|
|
91
|
+
debug(`DIAG: ${label} (see ${DIAG_LOG_PATH})`);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// --- Constants ---
|
|
95
|
+
|
|
96
|
+
// Global key to prevent re-registration of the provider across module reloads.
|
|
97
|
+
//
|
|
98
|
+
// Extensions like pi-subagents spawn a subagent and it loads this module
|
|
99
|
+
// again. Without this guard, the subagent's call to registerProvider() would
|
|
100
|
+
// overwrite the parent's `streamSimple` function reference in the shared
|
|
101
|
+
// ModelRegistry. When the parent later delivers a tool result, it would call
|
|
102
|
+
// the subagent's `streamSimple` (which has empty state) instead of its own.
|
|
103
|
+
//
|
|
104
|
+
// By storing the active streamSimple in a Symbol.for() global (shared across all
|
|
105
|
+
// module instances), we ensure only the FIRST instance to register takes effect.
|
|
106
|
+
// Subsequent instances wrap the stored function instead of overwriting it.
|
|
107
|
+
//
|
|
108
|
+
// On session_shutdown (including /reload), clearSession() resets this so a fresh
|
|
109
|
+
// registration can occur for the next session.
|
|
110
|
+
const ACTIVE_STREAM_SIMPLE_KEY = Symbol.for("codebuddy-sdk:activeStreamSimple");
|
|
111
|
+
|
|
112
|
+
const SDK_TO_PI_TOOL_NAME: Record<string, string> = {
|
|
113
|
+
read: "read", write: "write", edit: "edit", bash: "bash",
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
// MODELS — hardcoded for CodeBuddy provider
|
|
117
|
+
const MODELS = buildModels([
|
|
118
|
+
{ id: "hy3-preview-agent-ioa", name: "Hunyuan 3", reasoning: false, input: ["text"], contextWindow: 131072, maxTokens: 8192 },
|
|
119
|
+
{ id: "claude-sonnet-4.6", name: "Claude Sonnet 4.6", reasoning: true, input: ["text", "image"], contextWindow: 200000, maxTokens: 8192 },
|
|
120
|
+
{ id: "deepseek-v4-pro-ioa", name: "DeepSeek V4 Pro", reasoning: false, input: ["text"], contextWindow: 131072, maxTokens: 8192 },
|
|
121
|
+
{ id: "glm-5.2-ioa", name: "GLM 5.2", reasoning: false, input: ["text"], contextWindow: 131072, maxTokens: 8192 },
|
|
122
|
+
] as any);
|
|
123
|
+
let providerSettings: NonNullable<Config["provider"]> = {};
|
|
124
|
+
let longContextSettings: any = { plan: "pro", longContextExtraUsage: false };
|
|
125
|
+
|
|
126
|
+
function resolveModel(input: string) {
|
|
127
|
+
return _resolveModel(MODELS, input) as any;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// --- Error handling ---
|
|
131
|
+
|
|
132
|
+
function errorMessage(err: unknown): string {
|
|
133
|
+
if (err instanceof Error) return err.message;
|
|
134
|
+
if (err && typeof err === "object") {
|
|
135
|
+
const obj = err as Record<string, unknown>;
|
|
136
|
+
if (typeof obj.message === "string") return obj.message;
|
|
137
|
+
if (typeof obj.error === "string") return obj.error;
|
|
138
|
+
try { return JSON.stringify(err); } catch {}
|
|
139
|
+
}
|
|
140
|
+
return String(err);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// AskCodebuddy mode presets — controls which CC tools are blocked per mode.
|
|
144
|
+
// Only block tools that can't work (no pi TUI for user interaction).
|
|
145
|
+
// Other CC tools (Agent, SendMessage, RemoteTrigger, Tasks, etc.) are intentionally not blocked.
|
|
146
|
+
const ASKCLAUDE_ALWAYS_BLOCKED = [
|
|
147
|
+
"AskUserQuestion", "EnterPlanMode", "ExitPlanMode",
|
|
148
|
+
"ToolSearch", // probes for blocked tools, wastes tokens
|
|
149
|
+
"ScheduleWakeup", // no harness to fire wakeup from inside a delegated subagent
|
|
150
|
+
];
|
|
151
|
+
const MODE_DISALLOWED_TOOLS: Record<string, string[]> = {
|
|
152
|
+
full: [
|
|
153
|
+
...ASKCLAUDE_ALWAYS_BLOCKED,
|
|
154
|
+
],
|
|
155
|
+
read: [
|
|
156
|
+
...ASKCLAUDE_ALWAYS_BLOCKED,
|
|
157
|
+
"Write", "Edit", "Bash", "NotebookEdit",
|
|
158
|
+
"EnterWorktree", "ExitWorktree", "CronCreate", "CronDelete", "TeamCreate", "TeamDelete",
|
|
159
|
+
],
|
|
160
|
+
none: [
|
|
161
|
+
...ASKCLAUDE_ALWAYS_BLOCKED,
|
|
162
|
+
"Read", "Write", "Edit", "Glob", "Grep", "Bash", "Agent",
|
|
163
|
+
"NotebookEdit", "EnterWorktree", "ExitWorktree",
|
|
164
|
+
"CronCreate", "CronDelete", "TeamCreate", "TeamDelete",
|
|
165
|
+
"WebFetch", "WebSearch",
|
|
166
|
+
],
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
// --- Session persistence ---
|
|
170
|
+
|
|
171
|
+
interface SessionState {
|
|
172
|
+
sessionId: string;
|
|
173
|
+
cursor: number;
|
|
174
|
+
cwd: string;
|
|
175
|
+
// Force the next syncSharedSession call down the REBUILD path. Set when
|
|
176
|
+
// pi has mutated its messages array out from under us (compact, tree
|
|
177
|
+
// navigation) or after an abort left the JSONL in an indeterminate state.
|
|
178
|
+
// REBUILD wipes and rewrites the file to match pi's current history.
|
|
179
|
+
needsRebuild?: boolean;
|
|
180
|
+
// Set ONLY after an abort. The killed CC subprocess may still be flushing
|
|
181
|
+
// a late "[Request interrupted by user]" record to the session JSONL.
|
|
182
|
+
// Reusing the same sessionId/path would race that orphan write into our
|
|
183
|
+
// fresh file and break CC's parent-uuid chain on the next resume. When
|
|
184
|
+
// this flag is set, REBUILD takes a fresh UUID and skips deleteSession
|
|
185
|
+
// so the orphan writes land on a dead inode. Compact/tree do NOT set
|
|
186
|
+
// this — there's no concurrent CC writer during those events, so
|
|
187
|
+
// in-place rebuild (preserve UUID, deleteSession + createSession) is safe.
|
|
188
|
+
forceRotate?: boolean;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
let sharedSession: SessionState | null = null;
|
|
192
|
+
|
|
193
|
+
// Convert pi messages to Anthropic API format for session import.
|
|
194
|
+
// Lossy: non-Anthropic thinking blocks are dropped (no valid signature), and only
|
|
195
|
+
// text/image/toolCall block types are handled. If all blocks in an assistant message
|
|
196
|
+
// are filtered, the message is dropped — which can create invalid sequences (e.g.
|
|
197
|
+
// two user messages in a row, or tool_result without preceding tool_use).
|
|
198
|
+
function convertAndImportMessages(
|
|
199
|
+
session: ReturnType<typeof createSession>,
|
|
200
|
+
messages: Context["messages"],
|
|
201
|
+
customToolNameToSdk?: Map<string, string>,
|
|
202
|
+
): void {
|
|
203
|
+
const { anthropicMessages, sanitizedIds } = convertPiMessages(messages, customToolNameToSdk);
|
|
204
|
+
|
|
205
|
+
debug(`convertAndImportMessages: ${messages.length} pi msgs → ${anthropicMessages.length} anthropic msgs`);
|
|
206
|
+
debug(`convertAndImportMessages: imported roles:`, anthropicMessages.map((m, i) => {
|
|
207
|
+
const c = m.content;
|
|
208
|
+
if (typeof c === "string") return `[${i}]${m.role}:text`;
|
|
209
|
+
if (Array.isArray(c)) return `[${i}]${m.role}:${(c).map((b) => b.type).join("+")}`;
|
|
210
|
+
return `[${i}]${m.role}:?`;
|
|
211
|
+
}).join(" "));
|
|
212
|
+
if (sanitizedIds.size > 0) {
|
|
213
|
+
debug(`convertAndImportMessages: sanitized ${sanitizedIds.size} tool IDs:`,
|
|
214
|
+
[...sanitizedIds.entries()].map(([orig, clean]) => orig === clean ? orig : `${orig}→${clean}`).join(", "));
|
|
215
|
+
}
|
|
216
|
+
// Pre-repair for debug logging; importMessages also repairs internally (idempotent).
|
|
217
|
+
const repaired = repairToolPairing(anthropicMessages);
|
|
218
|
+
if (repaired.length !== anthropicMessages.length) {
|
|
219
|
+
debug(`convertAndImportMessages: repairToolPairing ${anthropicMessages.length} → ${repaired.length} msgs`);
|
|
220
|
+
}
|
|
221
|
+
if (repaired.length) session.importMessages(repaired);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// Pi doesn't pass tool results directly — it appends them to the context and calls
|
|
225
|
+
// debug logging at the extraction boundary.
|
|
226
|
+
function extractAllToolResults(context: Context): McpResult[] {
|
|
227
|
+
const { results, stopIdx } = _extractAllToolResults(context.messages as unknown as Array<{ role: string; [key: string]: unknown }>);
|
|
228
|
+
debug(`extractAllToolResults: ${results.length} results from ${context.messages.length} msgs, stopped at index ${stopIdx}`);
|
|
229
|
+
debug(`extractAllToolResults: all msg roles:`, context.messages.map((m, i) => `[${i}]${m.role}`).join(" "));
|
|
230
|
+
for (let r = 0; r < results.length; r++) {
|
|
231
|
+
debug(`extractAllToolResults: result[${r}] id=${results[r].toolCallId}${results[r].isError ? " ERROR" : ""} preview:`, JSON.stringify(results[r].content).slice(0, 150));
|
|
232
|
+
}
|
|
233
|
+
return results;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Extract the last user message from context as a prompt string. Returns null if last message is not a user message. */
|
|
237
|
+
function extractUserPrompt(messages: Context["messages"]): string | null {
|
|
238
|
+
const last = messages[messages.length - 1];
|
|
239
|
+
if (!last || last.role !== "user") return null;
|
|
240
|
+
if (typeof last.content === "string") return last.content;
|
|
241
|
+
return messageContentToText(last.content) || "";
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Extract the last user message as ContentBlockParam[] (preserving images).
|
|
245
|
+
* Returns null if no images — caller should fall back to string prompt. */
|
|
246
|
+
function extractUserPromptBlocks(messages: Context["messages"]): ContentBlockParam[] | null {
|
|
247
|
+
const last = messages[messages.length - 1];
|
|
248
|
+
if (!last || last.role !== "user") return null;
|
|
249
|
+
if (typeof last.content === "string") {
|
|
250
|
+
debug(`extractUserPromptBlocks: content is string (length=${last.content.length})`);
|
|
251
|
+
return null;
|
|
252
|
+
}
|
|
253
|
+
if (!Array.isArray(last.content)) {
|
|
254
|
+
debug(`extractUserPromptBlocks: content is ${typeof last.content}`);
|
|
255
|
+
return null;
|
|
256
|
+
}
|
|
257
|
+
debug(`extractUserPromptBlocks: ${last.content.length} blocks, types=${last.content.map((b: any) => b.type).join(",")}`);
|
|
258
|
+
let hasImage = false;
|
|
259
|
+
const blocks: ContentBlockParam[] = [];
|
|
260
|
+
for (const block of last.content) {
|
|
261
|
+
if (block.type === "text" && block.text) {
|
|
262
|
+
blocks.push({ type: "text", text: block.text });
|
|
263
|
+
} else if (block.type === "image") {
|
|
264
|
+
debug(`image block: mimeType=${(block as any).mimeType}, data length=${((block as any).data ?? "").length}, keys=${Object.keys(block).join(",")}`);
|
|
265
|
+
if (!(block as any).data || !(block as any).mimeType) {
|
|
266
|
+
debug(`image block missing data or mimeType, skipping`);
|
|
267
|
+
continue;
|
|
268
|
+
}
|
|
269
|
+
hasImage = true;
|
|
270
|
+
blocks.push({
|
|
271
|
+
type: "image",
|
|
272
|
+
source: { type: "base64", media_type: block.mimeType as Base64ImageSource["media_type"], data: block.data },
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
return hasImage ? blocks : null;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
async function* wrapPromptStream(blocks: ContentBlockParam[]): AsyncIterable<SDKUserMessage> {
|
|
280
|
+
yield {
|
|
281
|
+
type: "user",
|
|
282
|
+
message: { role: "user", content: blocks } as MessageParam,
|
|
283
|
+
parent_tool_use_id: null,
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function newAssistantOutput(model: Model<any>, text: string, stopReason: AssistantMessage["stopReason"], errorMessage?: string): AssistantMessage {
|
|
288
|
+
return {
|
|
289
|
+
role: "assistant",
|
|
290
|
+
content: text ? [{ type: "text", text }] : [],
|
|
291
|
+
api: model.api,
|
|
292
|
+
provider: model.provider,
|
|
293
|
+
model: model.id,
|
|
294
|
+
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0,
|
|
295
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
|
|
296
|
+
stopReason,
|
|
297
|
+
...(errorMessage ? { errorMessage } : {}),
|
|
298
|
+
timestamp: Date.now(),
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function extractIsolatedSummaryPrompt(messages: Context["messages"]): string {
|
|
303
|
+
if (messages.length !== 1 || messages[0].role !== "user") {
|
|
304
|
+
throw new Error(
|
|
305
|
+
`isolatedStreamFn: expected exactly 1 user message, got ${messages.length} ` +
|
|
306
|
+
`(${messages.map((m) => m.role).join(",")})`,
|
|
307
|
+
);
|
|
308
|
+
}
|
|
309
|
+
const promptText = extractUserPrompt(messages);
|
|
310
|
+
if (!promptText) throw new Error("isolatedStreamFn: summarization prompt is empty");
|
|
311
|
+
return promptText;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function resultErrorText(message: SDKMessage): string {
|
|
315
|
+
const result = message as SDKMessage & { subtype?: string; errors?: unknown; error?: unknown };
|
|
316
|
+
if (Array.isArray(result.errors)) return result.errors.map(String).join("\n");
|
|
317
|
+
if (typeof result.error === "string") return result.error;
|
|
318
|
+
return `CodeBuddy summary failed: ${result.subtype ?? "unknown result"}`;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function isolatedStreamFn(model: Model<any>, context: Context, options?: SimpleStreamOptions): AssistantMessageEventStream {
|
|
322
|
+
const stream = newAssistantMessageEventStream();
|
|
323
|
+
void runIsolatedSummary(model, context, options, stream);
|
|
324
|
+
return stream;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
async function runIsolatedSummary(
|
|
328
|
+
model: Model<any>,
|
|
329
|
+
context: Context,
|
|
330
|
+
options: SimpleStreamOptions | undefined,
|
|
331
|
+
stream: AssistantMessageEventStream,
|
|
332
|
+
): Promise<void> {
|
|
333
|
+
let sdkQuery: ReturnType<typeof query> | undefined;
|
|
334
|
+
let wasAborted = false;
|
|
335
|
+
const onAbort = () => {
|
|
336
|
+
wasAborted = true;
|
|
337
|
+
void sdkQuery?.interrupt().catch(() => {});
|
|
338
|
+
try { sdkQuery?.interrupt(); } catch {}
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
try {
|
|
342
|
+
const promptText = extractIsolatedSummaryPrompt(context.messages);
|
|
343
|
+
const cwd = (options as { cwd?: string } | undefined)?.cwd ?? process.cwd();
|
|
344
|
+
const claudeExecutable = loadConfig(cwd).provider?.pathToClaudeCodeExecutable;
|
|
345
|
+
const cliModel = codebuddyModelId(model);
|
|
346
|
+
debug(`compact summary: spawn model=${cliModel} registeredModel=${model.id} promptLen=${promptText.length}`);
|
|
347
|
+
|
|
348
|
+
sdkQuery = query({
|
|
349
|
+
prompt: promptText,
|
|
350
|
+
options: {
|
|
351
|
+
cwd,
|
|
352
|
+
env: { ...process.env, DISABLE_AUTO_COMPACT: "1", CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1" },
|
|
353
|
+
tools: [],
|
|
354
|
+
strictMcpConfig: true,
|
|
355
|
+
|
|
356
|
+
skills: [],
|
|
357
|
+
persistSession: false,
|
|
358
|
+
systemPrompt: context.systemPrompt,
|
|
359
|
+
model: cliModel,
|
|
360
|
+
maxTurns: 1,
|
|
361
|
+
...(claudeExecutable ? { pathToClaudeCodeExecutable: claudeExecutable } : {}),
|
|
362
|
+
...makeCliDebugOptions("compact-summary"),
|
|
363
|
+
},
|
|
364
|
+
});
|
|
365
|
+
|
|
366
|
+
if (options?.signal) {
|
|
367
|
+
if (options.signal.aborted) onAbort();
|
|
368
|
+
else options.signal.addEventListener("abort", onAbort, { once: true });
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
let assistantText = "";
|
|
372
|
+
let finalText = "";
|
|
373
|
+
let errorText: string | undefined;
|
|
374
|
+
let firstEventLogged = false;
|
|
375
|
+
|
|
376
|
+
for await (const message of sdkQuery) {
|
|
377
|
+
if (!firstEventLogged) {
|
|
378
|
+
debug(`compact summary: first event type=${message.type}`);
|
|
379
|
+
firstEventLogged = true;
|
|
380
|
+
}
|
|
381
|
+
if (wasAborted) break;
|
|
382
|
+
|
|
383
|
+
if (message.type === "assistant") {
|
|
384
|
+
for (const block of (message as any).message?.content ?? []) {
|
|
385
|
+
if (block.type === "text" && typeof block.text === "string") assistantText += block.text;
|
|
386
|
+
}
|
|
387
|
+
} else if (message.type === "result") {
|
|
388
|
+
logServedContextWindow("compact summary", message, model);
|
|
389
|
+
if (message.subtype === "success") {
|
|
390
|
+
finalText = message.result || assistantText;
|
|
391
|
+
} else {
|
|
392
|
+
errorText = resultErrorText(message);
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
if (wasAborted) {
|
|
398
|
+
const output = newAssistantOutput(model, "", "aborted", "Operation aborted");
|
|
399
|
+
debug("compact summary: aborted");
|
|
400
|
+
stream.push({ type: "error", reason: "aborted", error: output });
|
|
401
|
+
stream.end();
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
const text = finalText || assistantText;
|
|
406
|
+
if (errorText || !text.trim()) {
|
|
407
|
+
const msg = errorText ?? "CodeBuddy summary returned empty text";
|
|
408
|
+
debug(`compact summary: error ${msg}`);
|
|
409
|
+
stream.push({ type: "error", reason: "error", error: newAssistantOutput(model, "", "error", msg) });
|
|
410
|
+
stream.end();
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
debug(`compact summary: done textLen=${text.length}`);
|
|
415
|
+
stream.push({ type: "done", reason: "stop", message: newAssistantOutput(model, text, "stop") });
|
|
416
|
+
stream.end();
|
|
417
|
+
} catch (err) {
|
|
418
|
+
const msg = errorMessage(err);
|
|
419
|
+
debug("runIsolatedSummary threw; pushing terminal error", err);
|
|
420
|
+
stream.push({ type: "error", reason: "error", error: newAssistantOutput(model, "", "error", msg) });
|
|
421
|
+
stream.end();
|
|
422
|
+
} finally {
|
|
423
|
+
options?.signal?.removeEventListener("abort", onAbort);
|
|
424
|
+
try { sdkQuery?.interrupt(); } catch {}
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
function reinjectPriorCompactionFileOps(branchEntries: Array<{ type: string; details?: unknown }>, preparation: { fileOps: { read: Set<string>; edited: Set<string> } }): void {
|
|
429
|
+
const prior = [...branchEntries]
|
|
430
|
+
.reverse()
|
|
431
|
+
.find((entry): entry is CompactionEntry => entry.type === "compaction");
|
|
432
|
+
const details = prior?.details as { readFiles?: unknown; modifiedFiles?: unknown } | undefined;
|
|
433
|
+
if (!Array.isArray(details?.readFiles) || !Array.isArray(details?.modifiedFiles)) return;
|
|
434
|
+
for (const file of details.readFiles) preparation.fileOps.read.add(String(file));
|
|
435
|
+
for (const file of details.modifiedFiles) preparation.fileOps.edited.add(String(file));
|
|
436
|
+
debug(`compact takeover: re-injected prior file ops read=${details.readFiles.length} modified=${details.modifiedFiles.length}`);
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
interface SyncResult {
|
|
440
|
+
sessionId: string | null;
|
|
441
|
+
preserveSharedSession?: boolean;
|
|
442
|
+
}
|
|
443
|
+
|
|
1
444
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
* Architecture follows pi-claude-bridge:
|
|
5
|
-
* - Stateless: one sdk.query() per Pi turn
|
|
6
|
-
* - No Pi systemPrompt forwarding — CodeBuddy uses its own default
|
|
7
|
-
* - No MCP tool bridge — CodeBuddy SDK tools are used natively
|
|
8
|
-
* - Only the latest user message is forwarded (Pi manages conversation)
|
|
9
|
-
*
|
|
10
|
-
* Two files: index.ts (registration + model discovery), provider.ts (streaming).
|
|
445
|
+
* Ensure the shared session has all messages up to (but not including) the last user message.
|
|
446
|
+
* Returns session ID to resume from, or null if no resume needed.
|
|
11
447
|
*/
|
|
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
|
-
|
|
448
|
+
// Read the session file we just wrote and sanity-check it. Warns instead of
|
|
449
|
+
// throwing — CC may be more tolerant than our checks, so a false positive
|
|
450
|
+
// shouldn't block the user. Pure logic is in session-verify.js; this wrapper
|
|
451
|
+
// fans each warning out to debug log + piUI notify + diagDump.
|
|
452
|
+
function verifyWrittenSession(
|
|
453
|
+
jsonlPath: string,
|
|
454
|
+
expectedSessionId: string,
|
|
455
|
+
expectedRecordCount: number,
|
|
456
|
+
cwd: string,
|
|
457
|
+
): void {
|
|
458
|
+
const warnings = _verifyWrittenSession(jsonlPath, expectedSessionId, expectedRecordCount);
|
|
459
|
+
for (const msg of warnings) {
|
|
460
|
+
debug(`WARNING session verify: ${msg}`);
|
|
461
|
+
piUI?.notify(
|
|
462
|
+
`Session file issue: ${msg}\n` +
|
|
463
|
+
`cwd=${cwd} realpath=${safeRealpath(cwd)} CLAUDE_CONFIG_DIR=${process.env.CLAUDE_CONFIG_DIR ?? "(unset)"}\n` +
|
|
464
|
+
`Please copy and paste this message into a new issue at https://github.com/elidickinson/pi-codebuddy-sdk/issues/new` +
|
|
465
|
+
(DEBUG ? ` and attach ${DEBUG_LOG_PATH}` : ` (rerun with CODEBUDDY_DEBUG=1 to capture a debug log)`),
|
|
466
|
+
"warning",
|
|
467
|
+
);
|
|
468
|
+
diagDump("session_verify_fail", { msg, jsonlPath, cwd, realpath: safeRealpath(cwd), claudeConfigDir: process.env.CLAUDE_CONFIG_DIR ?? null });
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
function safeRealpath(p: string): string {
|
|
473
|
+
try { return realpathSync(p); } catch (e) { return `<failed: ${(e as Error).message}>`; }
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
// Diagnostic snapshot of where a session file was just written. Catches the
|
|
477
|
+
// class of bugs where pi writes to ~/.claude/projects/<X> but CC SDK reads
|
|
478
|
+
// from ~/.claude/projects/<Y> (symlinks, CLAUDE_CONFIG_DIR, hash mismatch).
|
|
479
|
+
function debugSessionPaths(label: string, cwd: string, jsonlPath: string): void {
|
|
480
|
+
const realCwd = safeRealpath(cwd);
|
|
481
|
+
let fileSize: number | null = null;
|
|
482
|
+
let fileExists = false;
|
|
483
|
+
try {
|
|
484
|
+
const st = statSync(jsonlPath);
|
|
485
|
+
fileExists = true;
|
|
486
|
+
fileSize = st.size;
|
|
487
|
+
} catch { /* file may not exist yet */ }
|
|
488
|
+
debug(`${label}: cwd=${cwd}`);
|
|
489
|
+
if (realCwd !== cwd) debug(`${label}: realpath(cwd)=${realCwd} (DIFFERS — symlink-resolved path is what CC SDK uses)`);
|
|
490
|
+
debug(`${label}: jsonlPath=${jsonlPath}`);
|
|
491
|
+
debug(`${label}: fileExists=${fileExists}${fileSize != null ? ` size=${fileSize}` : ""}`);
|
|
492
|
+
debug(`${label}: env.CLAUDE_CONFIG_DIR=${process.env.CLAUDE_CONFIG_DIR ?? "(unset)"} HOME=${process.env.HOME ?? "(unset)"}`);
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
// Two semantic paths:
|
|
496
|
+
// REUSE — pi's history is in sync with the existing sharedSession (or drifted
|
|
497
|
+
// only by the trailing final-assistant message that pi appends after
|
|
498
|
+
// streamSimple returns, which CC's own persisted session already has).
|
|
499
|
+
// Returns the existing sessionId. Keeps CC's prompt cache warm.
|
|
500
|
+
// REBUILD — no session yet, or pi's history has diverged (non-trailing
|
|
501
|
+
// missed messages, e.g. another provider took a turn). Wipes the existing
|
|
502
|
+
// session file (if any) and writes a fresh one containing all prior
|
|
503
|
+
// messages, reusing the same sessionId across rebuilds so UUIDs stay
|
|
504
|
+
// stable for the lifetime of pi's session.
|
|
505
|
+
//
|
|
506
|
+
// Why a full rebuild rather than patching:
|
|
507
|
+
// Injecting deltas into an existing session creates a branch that CC's
|
|
508
|
+
// --resume doesn't follow (documented attempt prior to this). A complete
|
|
509
|
+
// overwrite at the same path is simpler and correct.
|
|
510
|
+
//
|
|
511
|
+
// Why reuse the sessionId across rebuilds:
|
|
512
|
+
// CC re-reads the JSONL on every --resume call — no in-process UUID
|
|
513
|
+
// caching. Validated in tests/exp-session-clear.mjs, including the case
|
|
514
|
+
// where CC had appended its own tool_use/tool_result records between
|
|
515
|
+
// rebuilds. Preserving the UUID means stable log correlation across
|
|
516
|
+
// provider switches and no orphaned session files.
|
|
517
|
+
//
|
|
518
|
+
// Log strings still say "Case 1/2/3/4" so existing diagnostics (int-cache.sh,
|
|
519
|
+
// int-session-resume.mjs) keep grepping the same anchors.
|
|
520
|
+
function syncSharedSession(
|
|
521
|
+
messages: Context["messages"],
|
|
522
|
+
cwd: string,
|
|
523
|
+
customToolNameToSdk?: Map<string, string>,
|
|
524
|
+
modelId?: string,
|
|
525
|
+
): SyncResult {
|
|
526
|
+
const priorMessages = messages.slice(0, -1); // everything before the new user prompt
|
|
527
|
+
|
|
528
|
+
// REUSE path
|
|
529
|
+
//
|
|
530
|
+
// Guard on priorMessages.length >= cursor: a shorter incoming context cannot
|
|
531
|
+
// be a continuation of the cached session. This is the general invariant for
|
|
532
|
+
// pi-side history rewrites such as /compact and session_tree: without it,
|
|
533
|
+
// missed = [].slice(cursor) can falsely hit REUSE and resume an unrelated
|
|
534
|
+
// longer CC session. See issue #25.
|
|
535
|
+
if (sharedSession && !sharedSession.needsRebuild && priorMessages.length >= sharedSession.cursor) {
|
|
536
|
+
const missed = priorMessages.slice(sharedSession.cursor);
|
|
537
|
+
const trailingAssistantOnly =
|
|
538
|
+
missed.length === 1 && (missed[0] as { role?: string }).role === "assistant";
|
|
539
|
+
if (missed.length === 0 || trailingAssistantOnly) {
|
|
540
|
+
if (trailingAssistantOnly) {
|
|
541
|
+
sharedSession = { ...sharedSession, cursor: priorMessages.length, cwd };
|
|
542
|
+
}
|
|
543
|
+
debug(`Case 3: ${trailingAssistantOnly ? "advanced cursor past trailing assistant, " : ""}resuming session ${sharedSession.sessionId.slice(0, 8)}, cursor=${sharedSession.cursor}`);
|
|
544
|
+
debug(`syncResult: path=reuse sessionId=${sharedSession.sessionId} cursor=${sharedSession.cursor}`);
|
|
545
|
+
return { sessionId: sharedSession.sessionId };
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
// Only reachable when needsRebuild is false — user-facing history rewrites
|
|
549
|
+
// (/compact, session_tree, /new, fork) always set needsRebuild or clear
|
|
550
|
+
// sharedSession before the next syncSharedSession call. In practice this
|
|
551
|
+
// fires only for isolated compact-summary subprocesses.
|
|
552
|
+
if (sharedSession && !sharedSession.needsRebuild && priorMessages.length < sharedSession.cursor) {
|
|
553
|
+
debug(`Case 1 synthetic: clean start for shorter context, preserving shared session ${sharedSession.sessionId.slice(0, 8)}, cursor=${sharedSession.cursor}`);
|
|
554
|
+
debug(`syncResult: path=clean-start preserve-shared sessionId=${sharedSession.sessionId} cursor=${sharedSession.cursor}`);
|
|
555
|
+
return { sessionId: null, preserveSharedSession: true };
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
// REBUILD path
|
|
559
|
+
if (priorMessages.length === 0) {
|
|
560
|
+
debug(`Case 1: clean start, ${messages.length} total messages`);
|
|
561
|
+
debug(`syncResult: path=clean-start`);
|
|
562
|
+
return { sessionId: null };
|
|
563
|
+
}
|
|
564
|
+
const previousSessionId = sharedSession?.sessionId;
|
|
565
|
+
const previousCursor = sharedSession?.cursor ?? 0;
|
|
566
|
+
// preserveId: rebuild in place (deleteSession + createSession with the
|
|
567
|
+
// existing UUID), so prompt-cache UUIDs stay stable for log correlation
|
|
568
|
+
// and for any tools that key off them. Skipped only when there's a
|
|
569
|
+
// concurrent writer we shouldn't race — see forceRotate docs above.
|
|
570
|
+
const preserveId = previousSessionId !== undefined && !sharedSession?.forceRotate;
|
|
571
|
+
if (preserveId) {
|
|
572
|
+
// Wipe prior jsonl + companion dir (no-op if nothing to wipe).
|
|
573
|
+
deleteSession(previousSessionId!, cwd, process.env.CLAUDE_CONFIG_DIR);
|
|
574
|
+
}
|
|
575
|
+
const session = createSession({
|
|
576
|
+
projectPath: cwd,
|
|
577
|
+
claudeDir: process.env.CLAUDE_CONFIG_DIR,
|
|
578
|
+
...(preserveId ? { sessionId: previousSessionId } : {}),
|
|
579
|
+
...(modelId ? { model: modelId } : {}),
|
|
580
|
+
});
|
|
581
|
+
convertAndImportMessages(session, priorMessages, customToolNameToSdk);
|
|
582
|
+
session.save();
|
|
583
|
+
verifyWrittenSession(session.jsonlPath, session.sessionId, session.messages.length, cwd);
|
|
584
|
+
sharedSession = { sessionId: session.sessionId, cursor: priorMessages.length, cwd };
|
|
585
|
+
if (previousSessionId === undefined) {
|
|
586
|
+
debug(`Case 2: first turn with ${priorMessages.length} prior messages → session ${session.sessionId.slice(0, 8)}, ${session.messages.length} records`);
|
|
587
|
+
} else if (preserveId) {
|
|
588
|
+
const missedCount = priorMessages.length - previousCursor;
|
|
589
|
+
debug(`Case 4: ${missedCount} missed messages, ${priorMessages.length} total → rewrote session ${session.sessionId.slice(0, 8)} (same id), ${session.messages.length} records`);
|
|
590
|
+
} else {
|
|
591
|
+
debug(`Case 4 post-abort: ${priorMessages.length} total → new session ${session.sessionId.slice(0, 8)} (was ${previousSessionId.slice(0, 8)}, rotated to avoid race with orphan writer), ${session.messages.length} records`);
|
|
592
|
+
}
|
|
593
|
+
debugSessionPaths(`${session.sessionId.slice(0, 8)}`, cwd, session.jsonlPath);
|
|
594
|
+
debug(`syncResult: path=rebuild sessionId=${session.sessionId} priors=${priorMessages.length} ${previousSessionId === undefined ? "first" : preserveId ? "preserved" : "rotated-post-abort"}`);
|
|
595
|
+
return { sessionId: session.sessionId };
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
// @internal
|
|
599
|
+
export const __test = {
|
|
600
|
+
resetSharedSession() {
|
|
601
|
+
sharedSession = null;
|
|
602
|
+
},
|
|
603
|
+
setSharedSession(state: SessionState | null) {
|
|
604
|
+
sharedSession = state;
|
|
605
|
+
},
|
|
606
|
+
getSharedSession() {
|
|
607
|
+
return sharedSession;
|
|
608
|
+
},
|
|
609
|
+
syncSharedSession,
|
|
88
610
|
};
|
|
89
611
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
612
|
+
// --- Provider helpers: tool name mapping ---
|
|
613
|
+
|
|
614
|
+
function mapToolName(name: string, customToolNameToPi?: Map<string, string>): string {
|
|
615
|
+
const normalized = name.toLowerCase();
|
|
616
|
+
const builtin = SDK_TO_PI_TOOL_NAME[normalized];
|
|
617
|
+
if (builtin) return builtin;
|
|
618
|
+
if (customToolNameToPi) {
|
|
619
|
+
const mapped = customToolNameToPi.get(name) ?? customToolNameToPi.get(normalized);
|
|
620
|
+
if (mapped) return mapped;
|
|
621
|
+
}
|
|
622
|
+
if (normalized.startsWith(MCP_TOOL_PREFIX)) return name.slice(MCP_TOOL_PREFIX.length);
|
|
623
|
+
return name;
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
// Renames for CodeBuddy SDK param names that differ from pi's native names.
|
|
627
|
+
// Keys not listed here pass through unchanged, so new pi params work automatically.
|
|
628
|
+
const SDK_KEY_RENAMES: Record<string, Record<string, string>> = {
|
|
629
|
+
read: { file_path: "path" },
|
|
630
|
+
write: { file_path: "path" },
|
|
631
|
+
edit: { file_path: "path", old_string: "oldText", new_string: "newText", old_text: "oldText", new_text: "newText" },
|
|
632
|
+
};
|
|
633
|
+
|
|
634
|
+
// Maps SDK tool args to pi tool args via key renaming + pass-through.
|
|
635
|
+
// Pi's own prepareArguments hooks handle any structural transforms (e.g. edit oldText/newText → edits[]).
|
|
636
|
+
function mapToolArgs(
|
|
637
|
+
toolName: string, args: Record<string, unknown> | undefined,
|
|
638
|
+
): Record<string, unknown> {
|
|
639
|
+
const input = args ?? {};
|
|
640
|
+
const renames = SDK_KEY_RENAMES[toolName.toLowerCase()];
|
|
641
|
+
const result: Record<string, unknown> = {};
|
|
642
|
+
for (const [key, value] of Object.entries(input)) {
|
|
643
|
+
const piKey = renames?.[key] ?? key;
|
|
644
|
+
if (!(piKey in result)) result[piKey] = value; // first alias wins
|
|
645
|
+
}
|
|
646
|
+
// Pi bash has no default timeout; add a safety default
|
|
647
|
+
if (toolName.toLowerCase() === "bash" && result.timeout == null) {
|
|
648
|
+
result.timeout = 120;
|
|
649
|
+
}
|
|
650
|
+
return result;
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
// --- Provider helpers: tool resolution ---
|
|
654
|
+
|
|
655
|
+
// --- Provider helpers: tool bridge ---
|
|
656
|
+
|
|
657
|
+
// --- Query state ---
|
|
658
|
+
// QueryContext lives in query-state.js so tests can import it without
|
|
659
|
+
// activating the extension.
|
|
660
|
+
|
|
661
|
+
// Global (not query state):
|
|
662
|
+
let piUI: ExtensionUIContext | null = null;
|
|
663
|
+
const activeQueryContexts = new Set<QueryContext>();
|
|
664
|
+
|
|
665
|
+
function contextForToolResults(results: McpResult[]): QueryContext | undefined {
|
|
666
|
+
for (const result of results) {
|
|
667
|
+
const id = result.toolCallId;
|
|
668
|
+
if (!id) continue;
|
|
669
|
+
for (const queryCtx of activeQueryContexts) {
|
|
670
|
+
if (queryCtx.pendingToolCalls.has(id) || queryCtx.pendingResults.has(id) || queryCtx.turnToolCallIds.includes(id)) {
|
|
671
|
+
return queryCtx;
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
return undefined;
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
|
|
679
|
+
// Creates an MCP server that bridges pi tools to the SDK. Each tool handler
|
|
680
|
+
// blocks on a Promise until pi delivers the tool result via streamSimple.
|
|
681
|
+
// Handlers are assigned toolCallIds from turnToolCallIds (populated when the SDK
|
|
682
|
+
// emits tool_use blocks). Results are matched by ID, not position.
|
|
683
|
+
// Handlers close over the captured `queryCtx`, ensuring they operate on the
|
|
684
|
+
// correct query's state while multiple queries run concurrently.
|
|
685
|
+
// ponytail: MCP bridge function removed
|
|
686
|
+
// --- Usage helpers ---
|
|
687
|
+
|
|
688
|
+
function updateUsage(output: AssistantMessage, usage: Record<string, number | undefined>, model: Model<any>): void {
|
|
689
|
+
if (usage.input_tokens != null) output.usage.input = usage.input_tokens;
|
|
690
|
+
if (usage.output_tokens != null) output.usage.output = usage.output_tokens;
|
|
691
|
+
if (usage.cache_read_input_tokens != null) output.usage.cacheRead = usage.cache_read_input_tokens;
|
|
692
|
+
if (usage.cache_creation_input_tokens != null) output.usage.cacheWrite = usage.cache_creation_input_tokens;
|
|
693
|
+
// CodeBuddy may report reasoning/thinking tokens separately, while pi's Usage type does not model that field.
|
|
694
|
+
const reasoning = usage.reasoning_tokens ?? usage.thinking_tokens;
|
|
695
|
+
if (reasoning != null) (output.usage as typeof output.usage & { reasoning?: number }).reasoning = reasoning;
|
|
696
|
+
output.usage.totalTokens = output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
|
|
697
|
+
calculateCost(model, output.usage);
|
|
698
|
+
const promptTokens = output.usage.input + output.usage.cacheRead + output.usage.cacheWrite;
|
|
699
|
+
const cachePct = promptTokens > 0 ? Math.round(output.usage.cacheRead / promptTokens * 100) : 0;
|
|
700
|
+
const reasoningText = reasoning != null ? ` reasoning=${reasoning}` : "";
|
|
701
|
+
debug(`usage: in=${output.usage.input} out=${output.usage.output} cacheRead=${output.usage.cacheRead} cacheWrite=${output.usage.cacheWrite} total=${output.usage.totalTokens}${reasoningText} cachePct=${cachePct}% model=${model.id}`);
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
// Log the *served* context window reported by an SDK result message
|
|
705
|
+
// (modelUsage[id].contextWindow), which can differ from the window pi
|
|
706
|
+
// registered (model.contextWindow) when the runtime entitlement doesn't
|
|
707
|
+
// match the docs — e.g. bare Opus served 200K on Pro, or [1m] not honored.
|
|
708
|
+
// The result message's modelUsage is otherwise discarded; this makes the
|
|
709
|
+
// gap observable. See issue #18.
|
|
710
|
+
function logServedContextWindow(label: string, message: SDKMessage, model: Model<any>): void {
|
|
711
|
+
const modelUsage = (message as any).modelUsage as Record<string, { contextWindow?: number; maxOutputTokens?: number }> | undefined;
|
|
712
|
+
if (!modelUsage) return;
|
|
713
|
+
for (const [k, v] of Object.entries(modelUsage)) {
|
|
714
|
+
debug(`${label}: served contextWindow=${v.contextWindow ?? "?"} maxOutputTokens=${v.maxOutputTokens ?? "?"} servedModel=${k} registered=${model.contextWindow}`);
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
// --- Effort level mapping ---
|
|
719
|
+
// Pi reasoning levels → CC SDK effort levels
|
|
720
|
+
|
|
721
|
+
const REASONING_TO_EFFORT: Record<string, EffortLevel> = {
|
|
722
|
+
minimal: "low", low: "low", medium: "medium", high: "high", xhigh: "max",
|
|
723
|
+
};
|
|
724
|
+
|
|
725
|
+
// --- Provider helpers: misc ---
|
|
726
|
+
|
|
727
|
+
function mapStopReason(reason: string | undefined): "stop" | "length" | "toolUse" {
|
|
728
|
+
switch (reason) {
|
|
729
|
+
case "tool_use": return "toolUse";
|
|
730
|
+
case "max_tokens": return "length";
|
|
731
|
+
case "end_turn": default: return "stop";
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
function parsePartialJson(input: string, fallback: Record<string, unknown>): Record<string, unknown> {
|
|
736
|
+
if (!input) return fallback;
|
|
737
|
+
try { return JSON.parse(input); } catch { return fallback; }
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
|
|
741
|
+
// --- Provider: streaming function ---
|
|
742
|
+
//
|
|
743
|
+
// Push-based streaming with MCP tool bridge:
|
|
744
|
+
// 1. streamSimple starts a query() and kicks off consumeQuery() in background
|
|
745
|
+
// 2. consumeQuery() iterates the SDK generator, pushing events to currentPiStream
|
|
746
|
+
// 3. On tool_use: ends the current pi stream, nulls it out. The MCP handler
|
|
747
|
+
// blocks the generator naturally — no events arrive until resolved.
|
|
748
|
+
// 4. Pi executes the tool, calls streamSimple again. We swap in the new stream,
|
|
749
|
+
// resolve the MCP handler, and the generator unblocks — events flow to new stream.
|
|
750
|
+
//
|
|
751
|
+
// Note: resetTurnState clears turnSawStreamEvent while the generator may still
|
|
752
|
+
// have queued messages from the previous turn. This is safe because step 3 nulls
|
|
753
|
+
// currentPiStream, so any leftover messages hit the `!ctx().currentPiStream` guard
|
|
754
|
+
// in consumeQuery and are skipped before resetTurnState runs.
|
|
755
|
+
|
|
756
|
+
const completedStreams = new WeakSet<object>();
|
|
757
|
+
|
|
758
|
+
function markStreamComplete(stream: AssistantMessageEventStream | null): void {
|
|
759
|
+
if (stream) completedStreams.add(stream as object);
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
function claimCurrentPiStream(stream: AssistantMessageEventStream, label: string, c: QueryContext): void {
|
|
763
|
+
if (c.currentPiStream && !completedStreams.has(c.currentPiStream as object)) {
|
|
764
|
+
debug(`WARNING: currentPiStream overwritten before terminal event (${label}); activeQuery=${Boolean(c.activeQuery)} pendingHandlers=${c.pendingToolCalls.size}`);
|
|
765
|
+
}
|
|
766
|
+
c.currentPiStream = stream;
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
function ensureTurnStarted(c: QueryContext): void {
|
|
770
|
+
if (!c.turnStarted && c.currentPiStream && c.turnOutput) {
|
|
771
|
+
c.currentPiStream!.push({ type: "start", partial: c.turnOutput });
|
|
772
|
+
c.turnStarted = true;
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
function finalizeCurrentStream(c: QueryContext, stopReason?: string): void {
|
|
777
|
+
if (!c.currentPiStream || !c.turnOutput) return;
|
|
778
|
+
debug(`provider: finalizeCurrentStream called, stopReason=${stopReason}, turnOutput=${JSON.stringify({stopReason: c.turnOutput!.stopReason, error: c.turnOutput!.errorMessage})}`);
|
|
779
|
+
if (!c.turnStarted) ensureTurnStarted(c);
|
|
780
|
+
const reason = stopReason === "length" ? "length" : "stop";
|
|
781
|
+
const stream = c.currentPiStream;
|
|
782
|
+
stream!.push({ type: "done", reason, message: c.turnOutput });
|
|
783
|
+
markStreamComplete(stream);
|
|
784
|
+
stream!.end();
|
|
785
|
+
c.currentPiStream = null;
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
/** Maps Anthropic stream events to pi stream events (text, thinking, toolcall).
|
|
789
|
+
* On message_stop with tool_use: ends currentPiStream so pi can execute the tool. */
|
|
790
|
+
function processStreamEvent(
|
|
791
|
+
message: SDKMessage,
|
|
792
|
+
customToolNameToPi: Map<string, string>,
|
|
793
|
+
model: Model<any>,
|
|
794
|
+
c: QueryContext,
|
|
795
|
+
): void {
|
|
796
|
+
if (!c.currentPiStream || !c.turnOutput) return;
|
|
797
|
+
c.turnSawStreamEvent = true;
|
|
798
|
+
const event = (message as SDKMessage & { event: any }).event;
|
|
799
|
+
|
|
800
|
+
if (event?.type === "message_start") {
|
|
801
|
+
c.turnToolCallIds = [];
|
|
802
|
+
c.nextHandlerIdx = 0;
|
|
803
|
+
if (event.message?.usage) updateUsage(c.turnOutput, event.message.usage, model);
|
|
804
|
+
return;
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
if (event?.type === "content_block_start") {
|
|
808
|
+
ensureTurnStarted(c);
|
|
809
|
+
if (event.content_block?.type === "text") {
|
|
810
|
+
c.turnBlocks.push({ type: "text", text: "", index: event.index });
|
|
811
|
+
c.currentPiStream!.push({ type: "text_start", contentIndex: c.turnBlocks.length - 1, partial: c.turnOutput });
|
|
812
|
+
} else if (event.content_block?.type === "thinking") {
|
|
813
|
+
c.turnBlocks.push({ type: "thinking", thinking: "", thinkingSignature: "", index: event.index });
|
|
814
|
+
c.currentPiStream!.push({ type: "thinking_start", contentIndex: c.turnBlocks.length - 1, partial: c.turnOutput });
|
|
815
|
+
} else if (event.content_block?.type === "tool_use") {
|
|
816
|
+
c.turnSawToolCall = true;
|
|
817
|
+
c.turnToolCallIds.push(event.content_block.id);
|
|
818
|
+
c.turnBlocks.push({
|
|
819
|
+
type: "toolCall", id: event.content_block.id,
|
|
820
|
+
name: mapToolName(event.content_block.name, customToolNameToPi),
|
|
821
|
+
arguments: (event.content_block.input as Record<string, unknown>) ?? {},
|
|
822
|
+
partialJson: "", index: event.index,
|
|
823
|
+
});
|
|
824
|
+
c.currentPiStream!.push({ type: "toolcall_start", contentIndex: c.turnBlocks.length - 1, partial: c.turnOutput });
|
|
825
|
+
} else {
|
|
826
|
+
debug("processStreamEvent: unhandled content_block_start type", event.content_block?.type);
|
|
827
|
+
}
|
|
828
|
+
return;
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
if (event?.type === "content_block_delta") {
|
|
832
|
+
const index = c.turnBlocks.findIndex((b: any) => b.index === event.index);
|
|
833
|
+
const block = c.turnBlocks[index];
|
|
834
|
+
if (!block) return;
|
|
835
|
+
if (event.delta?.type === "text_delta" && block.type === "text") {
|
|
836
|
+
block.text += event.delta.text;
|
|
837
|
+
c.currentPiStream!.push({ type: "text_delta", contentIndex: index, delta: event.delta.text, partial: c.turnOutput });
|
|
838
|
+
} else if (event.delta?.type === "thinking_delta" && block.type === "thinking") {
|
|
839
|
+
block.thinking += event.delta.thinking;
|
|
840
|
+
c.currentPiStream!.push({ type: "thinking_delta", contentIndex: index, delta: event.delta.thinking, partial: c.turnOutput });
|
|
841
|
+
} else if (event.delta?.type === "input_json_delta" && block.type === "toolCall") {
|
|
842
|
+
block.partialJson += event.delta.partial_json;
|
|
843
|
+
block.arguments = parsePartialJson(block.partialJson, block.arguments);
|
|
844
|
+
c.currentPiStream!.push({ type: "toolcall_delta", contentIndex: index, delta: event.delta.partial_json, partial: c.turnOutput });
|
|
845
|
+
} else if (event.delta?.type === "signature_delta" && block.type === "thinking") {
|
|
846
|
+
block.thinkingSignature = (block.thinkingSignature ?? "") + event.delta.signature;
|
|
847
|
+
} else {
|
|
848
|
+
debug("processStreamEvent: unhandled content_block_delta type", event.delta?.type);
|
|
849
|
+
}
|
|
850
|
+
return;
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
if (event?.type === "content_block_stop") {
|
|
854
|
+
const index = c.turnBlocks.findIndex((b: any) => b.index === event.index);
|
|
855
|
+
const block = c.turnBlocks[index];
|
|
856
|
+
if (!block) return;
|
|
857
|
+
delete block.index;
|
|
858
|
+
if (block.type === "text") {
|
|
859
|
+
c.currentPiStream!.push({ type: "text_end", contentIndex: index, content: block.text, partial: c.turnOutput });
|
|
860
|
+
} else if (block.type === "thinking") {
|
|
861
|
+
c.currentPiStream!.push({ type: "thinking_end", contentIndex: index, content: block.thinking, partial: c.turnOutput });
|
|
862
|
+
} else if (block.type === "toolCall") {
|
|
863
|
+
c.turnSawToolCall = true;
|
|
864
|
+
block.arguments = mapToolArgs(
|
|
865
|
+
block.name, parsePartialJson(block.partialJson, block.arguments),
|
|
866
|
+
);
|
|
867
|
+
delete block.partialJson;
|
|
868
|
+
c.currentPiStream!.push({ type: "toolcall_end", contentIndex: index, toolCall: block, partial: c.turnOutput });
|
|
869
|
+
}
|
|
870
|
+
return;
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
if (event?.type === "message_delta") {
|
|
874
|
+
c.turnOutput.stopReason = mapStopReason(event.delta?.stop_reason);
|
|
875
|
+
if (event.usage) updateUsage(c.turnOutput, event.usage, model);
|
|
876
|
+
return;
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
if (event?.type === "message_stop" && c.turnSawToolCall) {
|
|
880
|
+
// Tool call complete — end this pi stream. The SDK will still yield an
|
|
881
|
+
// assistant message for this turn, but currentPiStream=null causes
|
|
882
|
+
// consumeQuery to skip it. The MCP handler blocks the generator until
|
|
883
|
+
// pi delivers the tool result via the next streamSimple call.
|
|
884
|
+
c.turnOutput.stopReason = "toolUse";
|
|
885
|
+
const stream = c.currentPiStream;
|
|
886
|
+
stream!.push({ type: "done", reason: "toolUse", message: c.turnOutput });
|
|
887
|
+
markStreamComplete(stream);
|
|
888
|
+
stream!.end();
|
|
889
|
+
c.currentPiStream = null;
|
|
890
|
+
|
|
891
|
+
// Cursor is updated by the next streamSimple call (tool result delivery path)
|
|
892
|
+
// which sets cursor = context.messages.length with the post-tool-result context.
|
|
893
|
+
return;
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
if (event?.type !== "message_stop" && event?.type !== "ping") {
|
|
897
|
+
debug("processStreamEvent: unhandled event type", event?.type);
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
// The SDK always yields `assistant` messages (completed content blocks) after streaming.
|
|
902
|
+
// When stream_events already delivered the content, this is a no-op. But after
|
|
903
|
+
// resetTurnState (e.g. tool result delivery), if the next turn's assistant message
|
|
904
|
+
// arrives before any stream_events, this is the primary content path. Must maintain
|
|
905
|
+
// the same stream lifecycle as processStreamEvent — including ending the stream on
|
|
906
|
+
// tool_use to prevent deadlock with the MCP handler.
|
|
907
|
+
function processAssistantMessage(message: SDKMessage, model: Model<any>, customToolNameToPi: Map<string, string>, c: QueryContext): void {
|
|
908
|
+
if (c.turnSawStreamEvent) return;
|
|
909
|
+
const assistantMsg = (message as any).message;
|
|
910
|
+
if (!assistantMsg?.content) return;
|
|
911
|
+
c.turnToolCallIds = [];
|
|
912
|
+
c.nextHandlerIdx = 0;
|
|
913
|
+
debug(`processAssistantMessage fallback: ${assistantMsg.content.length} blocks, types=${assistantMsg.content.map((b: any) => b.type).join(",")}`);
|
|
914
|
+
for (const block of assistantMsg.content) {
|
|
915
|
+
if (block.type === "text" && block.text) {
|
|
916
|
+
ensureTurnStarted(c);
|
|
917
|
+
c.turnBlocks.push({ type: "text", text: block.text });
|
|
918
|
+
const idx = c.turnBlocks.length - 1;
|
|
919
|
+
c.currentPiStream?.push({ type: "text_start", contentIndex: idx, partial: c.turnOutput });
|
|
920
|
+
c.currentPiStream?.push({ type: "text_delta", contentIndex: idx, delta: block.text, partial: c.turnOutput });
|
|
921
|
+
c.currentPiStream?.push({ type: "text_end", contentIndex: idx, content: block.text, partial: c.turnOutput });
|
|
922
|
+
} else if (block.type === "thinking") {
|
|
923
|
+
ensureTurnStarted(c);
|
|
924
|
+
c.turnBlocks.push({ type: "thinking", thinking: block.thinking ?? "", thinkingSignature: block.signature ?? "" });
|
|
925
|
+
const idx = c.turnBlocks.length - 1;
|
|
926
|
+
c.currentPiStream?.push({ type: "thinking_start", contentIndex: idx, partial: c.turnOutput });
|
|
927
|
+
if (block.thinking) c.currentPiStream?.push({ type: "thinking_delta", contentIndex: idx, delta: block.thinking, partial: c.turnOutput });
|
|
928
|
+
c.currentPiStream?.push({ type: "thinking_end", contentIndex: idx, content: block.thinking ?? "", partial: c.turnOutput });
|
|
929
|
+
} else if (block.type === "tool_use") {
|
|
930
|
+
ensureTurnStarted(c);
|
|
931
|
+
c.turnSawToolCall = true;
|
|
932
|
+
c.turnToolCallIds.push(block.id);
|
|
933
|
+
const mappedArgs = mapToolArgs(mapToolName(block.name, customToolNameToPi), block.input);
|
|
934
|
+
c.turnBlocks.push({
|
|
935
|
+
type: "toolCall", id: block.id,
|
|
936
|
+
name: mapToolName(block.name, customToolNameToPi),
|
|
937
|
+
arguments: mappedArgs,
|
|
938
|
+
});
|
|
939
|
+
const idx = c.turnBlocks.length - 1;
|
|
940
|
+
const toolBlock = c.turnBlocks[idx];
|
|
941
|
+
c.currentPiStream?.push({ type: "toolcall_start", contentIndex: idx, partial: c.turnOutput });
|
|
942
|
+
c.currentPiStream?.push({ type: "toolcall_end", contentIndex: idx, toolCall: toolBlock as any, partial: c.turnOutput });
|
|
943
|
+
} else {
|
|
944
|
+
debug("processAssistantMessage: unhandled block type", block.type);
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
if (assistantMsg.usage && c.turnOutput) updateUsage(c.turnOutput, assistantMsg.usage, model);
|
|
948
|
+
|
|
949
|
+
// End the stream on tool_use, same as processStreamEvent's message_stop handler.
|
|
950
|
+
if (c.turnSawToolCall && c.currentPiStream && c.turnOutput) {
|
|
951
|
+
c.turnOutput.stopReason = "toolUse";
|
|
952
|
+
const stream = c.currentPiStream;
|
|
953
|
+
stream.push({ type: "done", reason: "toolUse", message: c.turnOutput });
|
|
954
|
+
markStreamComplete(stream);
|
|
955
|
+
stream.end();
|
|
956
|
+
c.currentPiStream = null;
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
/** Background consumer: iterates the SDK generator, pushing events to currentPiStream.
|
|
961
|
+
* Runs until the query ends. Per turn, the SDK yields stream_events (deltas), then
|
|
962
|
+
* an assistant message (completed blocks). On tool_use, the stream is ended by
|
|
963
|
+
* whichever path handles it first (processStreamEvent or processAssistantMessage),
|
|
964
|
+
* and the MCP handler blocks the generator until pi delivers the tool result. */
|
|
965
|
+
async function consumeQuery(
|
|
966
|
+
sdkQuery: ReturnType<typeof query>,
|
|
967
|
+
customToolNameToPi: Map<string, string>,
|
|
968
|
+
model: Model<any>,
|
|
969
|
+
wasAborted: () => boolean,
|
|
970
|
+
queryCtx: QueryContext,
|
|
971
|
+
): Promise<{ capturedSessionId?: string }> {
|
|
972
|
+
let capturedSessionId: string | undefined;
|
|
973
|
+
|
|
974
|
+
for await (const message of sdkQuery) {
|
|
975
|
+
if (wasAborted()) break;
|
|
976
|
+
if (!queryCtx.currentPiStream || !queryCtx.turnOutput) continue;
|
|
977
|
+
|
|
978
|
+
switch (message.type) {
|
|
979
|
+
case "stream_event":
|
|
980
|
+
processStreamEvent(message, customToolNameToPi, model, queryCtx);
|
|
981
|
+
break;
|
|
982
|
+
case "assistant":
|
|
983
|
+
processAssistantMessage(message, model, customToolNameToPi, queryCtx);
|
|
984
|
+
break;
|
|
985
|
+
case "result":
|
|
986
|
+
logServedContextWindow("result", message, model);
|
|
987
|
+
if (!queryCtx.turnSawStreamEvent && message.subtype === "success") {
|
|
988
|
+
ensureTurnStarted(queryCtx);
|
|
989
|
+
const text = message.result || "";
|
|
990
|
+
queryCtx.turnBlocks.push({ type: "text", text });
|
|
991
|
+
const idx = queryCtx.turnBlocks.length - 1;
|
|
992
|
+
queryCtx.currentPiStream?.push({ type: "text_start", contentIndex: idx, partial: queryCtx.turnOutput });
|
|
993
|
+
queryCtx.currentPiStream?.push({ type: "text_delta", contentIndex: idx, delta: text, partial: queryCtx.turnOutput });
|
|
994
|
+
queryCtx.currentPiStream?.push({ type: "text_end", contentIndex: idx, content: text, partial: queryCtx.turnOutput });
|
|
995
|
+
}
|
|
996
|
+
break;
|
|
997
|
+
case "system":
|
|
998
|
+
if ((message as any).subtype === "init" && (message as any).session_id) {
|
|
999
|
+
capturedSessionId = (message as any).session_id;
|
|
1000
|
+
}
|
|
1001
|
+
break;
|
|
1002
|
+
case "user":
|
|
1003
|
+
break; // SDK echo of user prompt — not needed
|
|
1004
|
+
case "rate_limit_event": {
|
|
1005
|
+
const info = (message as any).rate_limit_info;
|
|
1006
|
+
debug("consumeQuery: rate_limit_event", JSON.stringify(info).slice(0, 300));
|
|
1007
|
+
if (info?.status === "rejected") {
|
|
1008
|
+
const resetsAt = info.resetsAt ? new Date(info.resetsAt).toLocaleTimeString() : "unknown";
|
|
1009
|
+
piUI?.notify(`Claude rate limited (${info.rateLimitType ?? "unknown"}) — resets at ${resetsAt}`, "warning");
|
|
1010
|
+
} else if (info?.status === "allowed_warning") {
|
|
1011
|
+
piUI?.notify(`Claude rate limit warning: ${Math.round(info.utilization ?? 0)}% used (${info.rateLimitType ?? ""})`, "warning");
|
|
1012
|
+
}
|
|
1013
|
+
break;
|
|
1014
|
+
}
|
|
1015
|
+
default:
|
|
1016
|
+
debug("consumeQuery: unhandled SDK message type", message.type);
|
|
1017
|
+
break;
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
// DEBUG: trace when consumeQuery exits
|
|
1022
|
+
debug(`consumeQuery: for-await loop exited, wasAborted=${wasAborted()}, capturedSessionId=${capturedSessionId?.slice(0, 8) ?? "none"}`);
|
|
1023
|
+
|
|
1024
|
+
return { capturedSessionId };
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
/** Provider entry point. Pi calls this for each new prompt and each tool result.
|
|
1028
|
+
* Two cases: tool result delivery (active query) or fresh query. */
|
|
1029
|
+
function streamClaudeAgentSdk(model: Model<any>, context: Context, options?: SimpleStreamOptions): AssistantMessageEventStream {
|
|
1030
|
+
const stream = newAssistantMessageEventStream();
|
|
1031
|
+
|
|
1032
|
+
// DEBUG: trace followUp message triggering
|
|
1033
|
+
const lastMsgRole = context.messages[context.messages.length - 1]?.role;
|
|
1034
|
+
debug(`provider: streamClaudeAgentSdk called, activeQuery=${!!ctx().activeQuery}, lastMsgRole=${lastMsgRole}, isReentrant=${ctx().activeQuery !== null}`);
|
|
1035
|
+
|
|
1036
|
+
const activeQuery = ctx().activeQuery !== null;
|
|
1037
|
+
const allResults = activeQueryContexts.size > 0 ? extractAllToolResults(context) : [];
|
|
1038
|
+
const resultCtx = allResults.length > 0 ? contextForToolResults(allResults) : undefined;
|
|
1039
|
+
const isReentrantUserQuery = activeQuery && lastMsgRole === "user" && allResults.length === 0;
|
|
1040
|
+
if (isReentrantUserQuery) {
|
|
1041
|
+
debug(`provider: active query user-only call treated as reentrant fresh query, waitingHandlers=${ctx().pendingToolCalls.size}, ctx.msgs=${context.messages.length}`);
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
// --- Tool result delivery ---
|
|
1045
|
+
// Pi appends tool results to context and calls back. Extract this turn's results
|
|
1046
|
+
// (everything after the last assistant message) and match against waiting MCP
|
|
1047
|
+
// handlers. Results that arrive before their handler get queued in pendingResults.
|
|
1048
|
+
if (resultCtx) {
|
|
1049
|
+
claimCurrentPiStream(stream, "tool-result", resultCtx);
|
|
1050
|
+
resultCtx.resetTurnState(model);
|
|
1051
|
+
debug(`provider: tool results, ${allResults.length} results, ${resultCtx.pendingToolCalls.size} waiting handlers, ctx.msgs=${context.messages.length}`);
|
|
1052
|
+
for (const result of allResults) {
|
|
1053
|
+
const id = result.toolCallId;
|
|
1054
|
+
if (id && resultCtx.pendingToolCalls.has(id)) {
|
|
1055
|
+
const pending = resultCtx.pendingToolCalls.get(id)!;
|
|
1056
|
+
resultCtx.pendingToolCalls.delete(id);
|
|
1057
|
+
debug(`provider: resolving ${pending.toolName} [${id}]${result.isError ? " (error)" : ""}`, JSON.stringify(result.content).slice(0, 200));
|
|
1058
|
+
pending.resolve(result);
|
|
1059
|
+
} else if (id) {
|
|
1060
|
+
resultCtx.pendingResults.set(id, result);
|
|
1061
|
+
debug(`provider: queued result [${id}] (${resultCtx.pendingResults.size} pending)`);
|
|
1062
|
+
} else {
|
|
1063
|
+
debug(`WARNING: tool result without toolCallId, cannot match`);
|
|
1064
|
+
}
|
|
1065
|
+
if (resultCtx.pendingToolCalls.size > 0 && resultCtx.pendingResults.size > 0) {
|
|
1066
|
+
debug(`BUG: both maps non-empty! handlers=${resultCtx.pendingToolCalls.size} results=${resultCtx.pendingResults.size}`);
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
if (resultCtx.pendingToolCalls.size > 0) {
|
|
1070
|
+
debug(`WARNING: ${resultCtx.pendingToolCalls.size} MCP handlers still waiting after delivering ${allResults.length} results`);
|
|
1071
|
+
piUI?.notify(`Claude bridge: ${resultCtx.pendingToolCalls.size} tool handler(s) still waiting — provider may be stuck`, "warning");
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
// Detect user messages (steer/followUp) that pi injected into context
|
|
1075
|
+
// during the active query. This happens when:
|
|
1076
|
+
// - User sends a steer while a tool is executing; pi drains the steer
|
|
1077
|
+
// queue at the turn boundary and appends it to context alongside the
|
|
1078
|
+
// tool result, then calls the provider again.
|
|
1079
|
+
// - A followUp is delivered between tool-result turns.
|
|
1080
|
+
// The bridge can't forward these mid-query (the SDK query is in progress),
|
|
1081
|
+
// so we save them for replay as continuation queries after consumeQuery ends.
|
|
1082
|
+
if (lastMsgRole === "user") {
|
|
1083
|
+
const userPrompt = extractUserPrompt(context.messages);
|
|
1084
|
+
if (userPrompt) {
|
|
1085
|
+
resultCtx.deferredUserMessages.push(userPrompt);
|
|
1086
|
+
debug(`provider: deferred user message for replay after query: ${userPrompt.slice(0, 60)}`);
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
if (sharedSession) sharedSession.cursor = context.messages.length;
|
|
1091
|
+
resultCtx.latestCursor = Math.max(resultCtx.latestCursor, context.messages.length);
|
|
1092
|
+
return stream;
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
// --- Orphaned tool result (e.g. user aborted a tool call) ---
|
|
1096
|
+
// The query is gone but pi still delivered the result. Nothing to do — just
|
|
1097
|
+
// emit end_turn so pi waits for the next real user message.
|
|
1098
|
+
const lastMsg = context.messages[context.messages.length - 1];
|
|
1099
|
+
if (lastMsg?.role === "toolResult") {
|
|
1100
|
+
debug(`provider: orphaned tool result after abort, emitting end_turn`);
|
|
1101
|
+
if (sharedSession) sharedSession.cursor = context.messages.length;
|
|
1102
|
+
const c = ctx(); // capture current context for the microtask
|
|
1103
|
+
queueMicrotask(() => {
|
|
1104
|
+
c.resetTurnState(model);
|
|
1105
|
+
stream.push({ type: "done", reason: "stop", message: c.turnOutput });
|
|
1106
|
+
markStreamComplete(stream);
|
|
1107
|
+
stream.end();
|
|
1108
|
+
});
|
|
1109
|
+
return stream;
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
// --- Fresh query ---
|
|
1113
|
+
|
|
1114
|
+
// 1. Determine reentrancy. Reentrant queries get their own QueryContext so
|
|
1115
|
+
// background subagents can run concurrently with the parent query.
|
|
1116
|
+
const isReentrant = activeQuery;
|
|
1117
|
+
const queryCtx = isReentrant ? new QueryContext() : ctx();
|
|
1118
|
+
debug(`provider: fresh query setup, isReentrant=${isReentrant}, activeContexts=${activeQueryContexts.size}`);
|
|
1119
|
+
|
|
1120
|
+
// 2. Fresh child context — constructor already gave us clean Maps and empty
|
|
1121
|
+
// arrays. For a reused top-level context, clear explicitly.
|
|
1122
|
+
claimCurrentPiStream(stream, "fresh-query", queryCtx);
|
|
1123
|
+
queryCtx.pendingToolCalls.clear();
|
|
1124
|
+
queryCtx.pendingResults.clear();
|
|
1125
|
+
queryCtx.deferredUserMessages = [];
|
|
1126
|
+
queryCtx.resetTurnState(model);
|
|
1127
|
+
queryCtx.latestCursor = 0;
|
|
1128
|
+
|
|
1129
|
+
// ponytail: MCP bridge removed — CodeBuddy uses native tools
|
|
1130
|
+
const mcpTools: any[] = [];
|
|
1131
|
+
const customToolNameToSdk = new Map<string, string>();
|
|
1132
|
+
const customToolNameToPi = new Map<string, string>();
|
|
1133
|
+
const cwd = (options as { cwd?: string } | undefined)?.cwd ?? process.cwd();
|
|
1134
|
+
const syncResult = syncSharedSession(context.messages, cwd, customToolNameToSdk, model.id);
|
|
1135
|
+
const { sessionId: resumeSessionId } = syncResult;
|
|
1136
|
+
const promptBlocks = extractUserPromptBlocks(context.messages);
|
|
1137
|
+
let promptText = extractUserPrompt(context.messages) ?? "";
|
|
1138
|
+
|
|
1139
|
+
// Guard: empty prompt means the last context message isn't a user message.
|
|
1140
|
+
// This should never happen with per-query state — dump diagnostics if it does.
|
|
1141
|
+
if (!promptText && !promptBlocks) {
|
|
1142
|
+
diagDump("empty_prompt", {
|
|
1143
|
+
contextLength: context.messages.length,
|
|
1144
|
+
lastMsgRole: lastMsg?.role,
|
|
1145
|
+
isReentrant,
|
|
1146
|
+
activeQueryContexts: activeQueryContexts.size,
|
|
1147
|
+
activeQueryExists: queryCtx.activeQuery !== null,
|
|
1148
|
+
sharedSession: sharedSession ? { sessionId: sharedSession.sessionId.slice(0, 8), cursor: sharedSession.cursor } : null,
|
|
1149
|
+
messageRoles: context.messages.map((m, i) => `[${i}]${m.role}`).join(" "),
|
|
1150
|
+
});
|
|
1151
|
+
// Recover: use a continuation prompt so the SDK doesn't send an empty text block
|
|
1152
|
+
promptText = "[continue]";
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
const prompt: string | AsyncIterable<SDKUserMessage> = promptBlocks
|
|
1156
|
+
? wrapPromptStream(promptBlocks)
|
|
1157
|
+
: promptText;
|
|
1158
|
+
// ponytail: MCP bridge removed
|
|
1159
|
+
const mcpServers = {};
|
|
1160
|
+
const appendSystemPrompt = providerSettings.appendSystemPrompt !== false;
|
|
1161
|
+
const agentsAppend = appendSystemPrompt ? extractAgentsAppend() : undefined;
|
|
1162
|
+
const skillsAppend = appendSystemPrompt ? extractSkillsBlock(context.systemPrompt) : undefined;
|
|
1163
|
+
const appendParts = [agentsAppend, skillsAppend].filter((part): part is string => Boolean(part));
|
|
1164
|
+
const systemPromptAppend = appendParts.length > 0 ? appendParts.join("\n\n") : undefined;
|
|
1165
|
+
|
|
1166
|
+
// MCP auto-loading suppression: CC reads MCP servers from ~/.claude.json (top-level
|
|
1167
|
+
// + per-project) and .mcp.json. Since pi executes tools (not CC), those are pure
|
|
1168
|
+
// token overhead. --strict-mcp-config tells the binary to use ONLY mcpServers passed
|
|
1169
|
+
// programmatically and ignore filesystem MCP entries — applied unconditionally because
|
|
1170
|
+
// settingSources=undefined does NOT give isolation (the CC default loads all sources).
|
|
1171
|
+
// ponytail: removed settingSources for CodeBuddy
|
|
1172
|
+
const settingSources = undefined
|
|
1173
|
+
? undefined
|
|
1174
|
+
: providerSettings.settingSources ?? ["user", "project"];
|
|
1175
|
+
const strictMcpConfigEnabled = providerSettings.strictMcpConfig !== false;
|
|
1176
|
+
const claudeExecutable = providerSettings.pathToClaudeCodeExecutable;
|
|
1177
|
+
|
|
1178
|
+
// Prefer the model's own thinkingLevelMap when present (pi-ai 0.72+ ships
|
|
1179
|
+
// per-model overrides — e.g. opus-4-7 wants xhigh→xhigh, not xhigh→max).
|
|
1180
|
+
// Fall back to our generic table for older pi-ai or unmapped levels.
|
|
1181
|
+
const effort = options?.reasoning
|
|
1182
|
+
? ((model as any).thinkingLevelMap?.[options.reasoning] as EffortLevel | undefined)
|
|
1183
|
+
?? REASONING_TO_EFFORT[options.reasoning]
|
|
1184
|
+
: undefined;
|
|
1185
|
+
|
|
1186
|
+
// cliModel is the actual id sent to CodeBuddy (may carry [1m]); model.id is the
|
|
1187
|
+
// pi-registered id. Log cliModel so debug lines reflect what CC actually received.
|
|
1188
|
+
const cliModel = codebuddyModelId(model);
|
|
1189
|
+
const extraArgs: Record<string, string | null> = { model: cliModel };
|
|
1190
|
+
if (strictMcpConfigEnabled) extraArgs["strict-mcp-config"] = null;
|
|
1191
|
+
// Opus 4.7 defaults thinking.display to "omitted" (empty thinking text in stream).
|
|
1192
|
+
// Force summarized so thinking_delta events arrive. See anthropics/claude-agent-sdk-python#830.
|
|
1193
|
+
if (effort) extraArgs["thinking-display"] = "summarized";
|
|
1194
|
+
|
|
1195
|
+
// Suppress claude.ai cloud MCP servers (Figma/Canva/etc. auto-discovered via OAuth
|
|
1196
|
+
// when the user is logged into Anthropic). These are a separate code path from
|
|
1197
|
+
// filesystem MCP and are NOT blocked by --strict-mcp-config or settingSources=undefined.
|
|
1198
|
+
// The native CC binary gates them on env var ENABLE_CLAUDEAI_MCP_SERVERS: setting it
|
|
1199
|
+
// to "0"/"false"/"no"/"off" makes the loader return early before any cloud fetch.
|
|
1200
|
+
// DISABLE_AUTO_COMPACT=1: pi owns context-management and propagates its own
|
|
1201
|
+
// /compact via session_compact (see handler in default export). Letting CC
|
|
1202
|
+
// also autocompact would double-flush the prompt cache and races pi's
|
|
1203
|
+
// threshold with CC's, including CC's anti-thrashing guard (issue #8).
|
|
1204
|
+
// Manual /compact in CC still works (we never invoke it).
|
|
1205
|
+
const childEnv = { ...process.env, ENABLE_CLAUDEAI_MCP_SERVERS: "0", DISABLE_AUTO_COMPACT: "1" };
|
|
1206
|
+
const queryOptions: NonNullable<Parameters<typeof query>[0]["options"]> = {
|
|
1207
|
+
cwd,
|
|
1208
|
+
env: childEnv,
|
|
1209
|
+
tools: [],
|
|
1210
|
+
permissionMode: "bypassPermissions",
|
|
1211
|
+
includePartialMessages: true,
|
|
1212
|
+
systemPrompt: {
|
|
1213
|
+
type: "preset", preset: "codebuddy",
|
|
1214
|
+
append: systemPromptAppend ? systemPromptAppend : undefined,
|
|
1215
|
+
},
|
|
1216
|
+
extraArgs,
|
|
1217
|
+
...(effort ? { effort } : {}),
|
|
1218
|
+
...(resumeSessionId ? { resume: resumeSessionId } : {}),
|
|
1219
|
+
...(claudeExecutable ? { pathToClaudeCodeExecutable: claudeExecutable } : {}),
|
|
1220
|
+
...makeCliDebugOptions("provider"),
|
|
1221
|
+
};
|
|
1222
|
+
|
|
1223
|
+
debug("provider: fresh query",
|
|
1224
|
+
`model=${cliModel} msgs=${context.messages.length} tools=${mcpTools.length}`,
|
|
1225
|
+
`resume=${resumeSessionId?.slice(0, 8) ?? "none"} effort=${effort ?? "default"}`,
|
|
1226
|
+
`appendSys=${appendSystemPrompt} strictMcp=${strictMcpConfigEnabled}`,
|
|
1227
|
+
`prompt=${promptText.slice(0, 60)}${promptBlocks ? " [+images]" : ""}`);
|
|
1228
|
+
|
|
1229
|
+
// 3. Start SDK query and claim it for this context
|
|
1230
|
+
let wasAborted = false;
|
|
1231
|
+
const sdkQuery = query({ prompt, options: queryOptions });
|
|
1232
|
+
queryCtx.activeQuery = sdkQuery;
|
|
1233
|
+
activeQueryContexts.add(queryCtx);
|
|
1234
|
+
|
|
1235
|
+
// 4. Capture context for abort handling
|
|
1236
|
+
const abortCtx = queryCtx;
|
|
1237
|
+
|
|
1238
|
+
const requestAbort = () => {
|
|
1239
|
+
// interrupt() asks the CLI to stop gracefully; close() kills it immediately.
|
|
1240
|
+
// Both are needed — interrupt alone lets the current API call finish.
|
|
1241
|
+
void sdkQuery.interrupt().catch(() => {});
|
|
1242
|
+
try { sdkQuery.interrupt(); } catch {}
|
|
1243
|
+
};
|
|
1244
|
+
const onAbort = () => {
|
|
1245
|
+
wasAborted = true;
|
|
1246
|
+
// Prevent stale deferred messages from being replayed by parent on pop
|
|
1247
|
+
abortCtx.deferredUserMessages = [];
|
|
1248
|
+
for (const pending of abortCtx.pendingToolCalls.values()) { pending.resolve({ content: [{ type: "text", text: "Operation aborted" }] }); }
|
|
1249
|
+
abortCtx.pendingToolCalls.clear();
|
|
1250
|
+
abortCtx.pendingResults.clear();
|
|
1251
|
+
requestAbort();
|
|
1252
|
+
};
|
|
1253
|
+
if (options?.signal) {
|
|
1254
|
+
if (options.signal.aborted) onAbort();
|
|
1255
|
+
else options.signal.addEventListener("abort", onAbort, { once: true });
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
// Background consumer — runs until query ends
|
|
1259
|
+
consumeQuery(sdkQuery, customToolNameToPi, model, () => wasAborted, queryCtx)
|
|
1260
|
+
.then(async ({ capturedSessionId }) => {
|
|
1261
|
+
debug(`provider: consumeQuery completed, stopReason=${queryCtx.turnOutput?.stopReason}, error=${queryCtx.turnOutput?.errorMessage}, aborted=${wasAborted}`);
|
|
1262
|
+
|
|
1263
|
+
// --- Abort detection in normal completion path ---
|
|
1264
|
+
if (wasAborted || options?.signal?.aborted) {
|
|
1265
|
+
if (sharedSession) sharedSession = { ...sharedSession, needsRebuild: true, forceRotate: true };
|
|
1266
|
+
queryCtx.deferredUserMessages = [];
|
|
1267
|
+
debug(`provider: abort detected, marked sharedSession needsRebuild + forceRotate`);
|
|
1268
|
+
if (queryCtx.turnOutput) {
|
|
1269
|
+
queryCtx.turnOutput.stopReason = "aborted";
|
|
1270
|
+
queryCtx.turnOutput.errorMessage = "Operation aborted";
|
|
1271
|
+
}
|
|
1272
|
+
const stream = queryCtx.currentPiStream;
|
|
1273
|
+
stream?.push({ type: "error", reason: "aborted", error: queryCtx.turnOutput! });
|
|
1274
|
+
markStreamComplete(stream);
|
|
1275
|
+
stream?.end();
|
|
1276
|
+
queryCtx.currentPiStream = null;
|
|
1277
|
+
return;
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
// --- Capture session ID ---
|
|
1281
|
+
const sessionId = capturedSessionId ?? sharedSession?.sessionId;
|
|
1282
|
+
if (syncResult.preserveSharedSession) {
|
|
1283
|
+
if (capturedSessionId && capturedSessionId !== sharedSession?.sessionId) {
|
|
1284
|
+
deleteSession(capturedSessionId, cwd, process.env.CLAUDE_CONFIG_DIR);
|
|
1285
|
+
debug(`provider: query done, deleted ephemeral session ${capturedSessionId.slice(0, 8)} to preserve shared session`);
|
|
1286
|
+
}
|
|
1287
|
+
debug(`provider: query done, ignoring captured session ${capturedSessionId?.slice(0, 8) ?? "none"} to preserve shared session`);
|
|
1288
|
+
} else if (sessionId) {
|
|
1289
|
+
const cursor = Math.max(context.messages.length, queryCtx.latestCursor, sharedSession?.cursor ?? 0);
|
|
1290
|
+
debug(`provider: query done, session=${sessionId.slice(0, 8)}, cursor=${cursor}`);
|
|
1291
|
+
sharedSession = { sessionId, cursor, cwd };
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
// --- Replay deferred user messages as continuation queries ---
|
|
1295
|
+
try {
|
|
1296
|
+
while (queryCtx.deferredUserMessages.length > 0 && !isReentrant && !wasAborted) {
|
|
1297
|
+
const steerPrompt = queryCtx.deferredUserMessages.shift()!;
|
|
1298
|
+
debug(`provider: replaying deferred user message: ${steerPrompt.slice(0, 60)}`);
|
|
1299
|
+
queryCtx.resetTurnState(model);
|
|
1300
|
+
|
|
1301
|
+
const resumeId = sharedSession?.sessionId;
|
|
1302
|
+
if (!resumeId) {
|
|
1303
|
+
debug(`WARNING: no session to resume for deferred message, dropping`);
|
|
1304
|
+
break;
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
const contOptions = { ...queryOptions, resume: resumeId, ...makeCliDebugOptions("continuation") };
|
|
1308
|
+
const contQuery = query({ prompt: steerPrompt, options: contOptions });
|
|
1309
|
+
queryCtx.activeQuery = contQuery;
|
|
1310
|
+
|
|
1311
|
+
debug(`provider: continuation query, model=${cliModel}, resume=${resumeId.slice(0, 8)}, prompt=${steerPrompt.slice(0, 60)}`);
|
|
1312
|
+
|
|
1313
|
+
try {
|
|
1314
|
+
const { capturedSessionId: contSid } = await consumeQuery(contQuery, customToolNameToPi, model, () => wasAborted, queryCtx);
|
|
1315
|
+
const sid = contSid ?? sharedSession?.sessionId;
|
|
1316
|
+
if (sid) {
|
|
1317
|
+
sharedSession = { sessionId: sid, cursor: sharedSession?.cursor ?? 0, cwd };
|
|
1318
|
+
}
|
|
1319
|
+
} catch (contError) {
|
|
1320
|
+
debug(`provider: continuation query error:`, contError);
|
|
1321
|
+
break;
|
|
1322
|
+
} finally {
|
|
1323
|
+
contQuery.interrupt();
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
} finally {
|
|
1327
|
+
queryCtx.activeQuery = sdkQuery;
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
if (!isReentrant && queryCtx.activeQuery === sdkQuery) {
|
|
1331
|
+
debug("provider: clearing activeQuery before final stream completion");
|
|
1332
|
+
queryCtx.activeQuery = null;
|
|
1333
|
+
}
|
|
1334
|
+
finalizeCurrentStream(queryCtx, queryCtx.turnOutput?.stopReason);
|
|
1335
|
+
})
|
|
1336
|
+
.catch((error) => {
|
|
1337
|
+
debug(`provider: query error, model=${cliModel}, aborted=${Boolean(options?.signal?.aborted)}, error=`, error);
|
|
1338
|
+
if ((wasAborted || options?.signal?.aborted) && sharedSession) {
|
|
1339
|
+
sharedSession = { ...sharedSession, needsRebuild: true, forceRotate: true };
|
|
1340
|
+
} else {
|
|
1341
|
+
sharedSession = null;
|
|
1342
|
+
}
|
|
1343
|
+
queryCtx.deferredUserMessages = [];
|
|
1344
|
+
if (queryCtx.turnOutput) {
|
|
1345
|
+
queryCtx.turnOutput.stopReason = options?.signal?.aborted ? "aborted" : "error";
|
|
1346
|
+
queryCtx.turnOutput.errorMessage = error instanceof Error ? error.message : String(error);
|
|
1347
|
+
}
|
|
1348
|
+
if (!isReentrant && queryCtx.activeQuery === sdkQuery) {
|
|
1349
|
+
for (const pending of queryCtx.pendingToolCalls.values()) { pending.resolve({ content: [{ type: "text", text: "Query ended" }] }); }
|
|
1350
|
+
queryCtx.pendingToolCalls.clear();
|
|
1351
|
+
queryCtx.pendingResults.clear();
|
|
1352
|
+
debug("provider: clearing activeQuery before error stream completion");
|
|
1353
|
+
queryCtx.activeQuery = null;
|
|
1354
|
+
}
|
|
1355
|
+
const stream = queryCtx.currentPiStream;
|
|
1356
|
+
stream?.push({ type: "error", reason: (queryCtx.turnOutput?.stopReason ?? "error") as "aborted" | "error", error: queryCtx.turnOutput! });
|
|
1357
|
+
markStreamComplete(stream);
|
|
1358
|
+
stream?.end();
|
|
1359
|
+
queryCtx.currentPiStream = null;
|
|
1360
|
+
})
|
|
1361
|
+
.finally(() => {
|
|
1362
|
+
if (options?.signal) options.signal.removeEventListener("abort", onAbort);
|
|
1363
|
+
if (queryCtx.activeQuery === sdkQuery) {
|
|
1364
|
+
// Drain pending handlers for this query
|
|
1365
|
+
for (const pending of queryCtx.pendingToolCalls.values()) { pending.resolve({ content: [{ type: "text", text: "Query ended" }] }); }
|
|
1366
|
+
queryCtx.pendingToolCalls.clear();
|
|
1367
|
+
queryCtx.pendingResults.clear();
|
|
1368
|
+
queryCtx.activeQuery = null;
|
|
1369
|
+
}
|
|
1370
|
+
activeQueryContexts.delete(queryCtx);
|
|
1371
|
+
sdkQuery.interrupt();
|
|
1372
|
+
});
|
|
1373
|
+
|
|
1374
|
+
return stream;
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
// --- AskCodebuddy: prompt and wait ---
|
|
1378
|
+
|
|
1379
|
+
async function promptAndWait(
|
|
1380
|
+
prompt: string,
|
|
1381
|
+
mode: "full" | "read" | "none",
|
|
1382
|
+
toolCalls: Map<string, ToolCallState>,
|
|
1383
|
+
signal?: AbortSignal,
|
|
1384
|
+
options?: {
|
|
1385
|
+
systemPrompt?: string;
|
|
1386
|
+
appendSkills?: boolean;
|
|
1387
|
+
onStreamUpdate?: (responseText: string) => void;
|
|
1388
|
+
model?: string;
|
|
1389
|
+
thinking?: string;
|
|
1390
|
+
isolated?: boolean;
|
|
1391
|
+
context?: Context["messages"];
|
|
1392
|
+
},
|
|
1393
|
+
): Promise<{ responseText: string; stopReason: string }> {
|
|
1394
|
+
const cwd = process.cwd();
|
|
1395
|
+
const requestedModel = options?.model ?? "opus";
|
|
1396
|
+
const model = resolveModel(requestedModel);
|
|
1397
|
+
const modelId = model?.id ?? requestedModel;
|
|
1398
|
+
const cliModel = model ? codebuddyModelId(model) : modelId;
|
|
1399
|
+
|
|
1400
|
+
// Session resume for shared mode — reuse provider's session if it exists,
|
|
1401
|
+
// otherwise create one from pi's context.
|
|
1402
|
+
// Note: doesn't update sharedSession.cursor after completion, so the next
|
|
1403
|
+
// provider call will see missed messages and trigger a Case 4 rebuild.
|
|
1404
|
+
let resumeSessionId: string | null = null;
|
|
1405
|
+
if (!options?.isolated && options?.context?.length) {
|
|
1406
|
+
if (sharedSession) {
|
|
1407
|
+
// Provider already has a session — just resume from it
|
|
1408
|
+
// Any missed messages from other providers were already handled by the provider's Case 4
|
|
1409
|
+
resumeSessionId = sharedSession.sessionId;
|
|
1410
|
+
} else {
|
|
1411
|
+
// No provider session yet — create one from pi's context
|
|
1412
|
+
const contextWithPrompt = [...options.context, { role: "user" as const, content: prompt, timestamp: Date.now() }];
|
|
1413
|
+
const sync = syncSharedSession(contextWithPrompt as Context["messages"], cwd, undefined, modelId);
|
|
1414
|
+
resumeSessionId = sync.sessionId;
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1418
|
+
// Mode → disallowed tools
|
|
1419
|
+
const disallowedTools = MODE_DISALLOWED_TOOLS[mode] ?? [];
|
|
1420
|
+
|
|
1421
|
+
// Skills append
|
|
1422
|
+
const skillsBlock = options?.appendSkills !== false && options?.systemPrompt
|
|
1423
|
+
? extractSkillsBlock(options.systemPrompt) : undefined;
|
|
1424
|
+
|
|
1425
|
+
// Effort
|
|
1426
|
+
const effort = options?.thinking && options.thinking !== "off"
|
|
1427
|
+
? REASONING_TO_EFFORT[options.thinking] : undefined;
|
|
1428
|
+
|
|
1429
|
+
const claudeExecutable = providerSettings.pathToClaudeCodeExecutable;
|
|
1430
|
+
|
|
1431
|
+
const extraArgs: Record<string, string | null> = {
|
|
1432
|
+
"strict-mcp-config": null,
|
|
1433
|
+
model: cliModel,
|
|
1434
|
+
};
|
|
1435
|
+
if (effort) extraArgs["thinking-display"] = "summarized";
|
|
1436
|
+
|
|
1437
|
+
debug("askCodebuddy:",
|
|
1438
|
+
`mode=${mode} model=${modelId} cliModel=${cliModel} effort=${effort ?? "default"}`,
|
|
1439
|
+
`isolated=${options?.isolated ?? false} resume=${resumeSessionId?.slice(0, 8) ?? "none"}`,
|
|
1440
|
+
`skills=${Boolean(skillsBlock)} promptLen=${prompt.length}`);
|
|
1441
|
+
|
|
1442
|
+
const sdkQuery = query({
|
|
1443
|
+
prompt,
|
|
1444
|
+
options: {
|
|
1445
|
+
cwd,
|
|
1446
|
+
env: { ...process.env, ENABLE_CLAUDEAI_MCP_SERVERS: "0", DISABLE_AUTO_COMPACT: "1" },
|
|
1447
|
+
permissionMode: "bypassPermissions",
|
|
1448
|
+
...(disallowedTools.length ? { disallowedTools } : {}),
|
|
1449
|
+
...(effort ? { effort } : {}),
|
|
1450
|
+
systemPrompt: skillsBlock
|
|
1451
|
+
? { type: "preset", preset: "codebuddy", append: skillsBlock }
|
|
1452
|
+
: undefined,
|
|
1453
|
+
|
|
1454
|
+
extraArgs,
|
|
1455
|
+
...(resumeSessionId ? { resume: resumeSessionId } : {}),
|
|
1456
|
+
...(options?.isolated ? { persistSession: false } : {}),
|
|
1457
|
+
...(claudeExecutable ? { pathToClaudeCodeExecutable: claudeExecutable } : {}),
|
|
1458
|
+
...makeCliDebugOptions("askclaude"),
|
|
1459
|
+
},
|
|
1460
|
+
});
|
|
1461
|
+
|
|
1462
|
+
// Abort handling
|
|
1463
|
+
let wasAborted = false;
|
|
1464
|
+
const onAbort = () => {
|
|
1465
|
+
wasAborted = true;
|
|
1466
|
+
sdkQuery.interrupt().catch(() => { try { sdkQuery.interrupt(); } catch {} });
|
|
1467
|
+
};
|
|
1468
|
+
if (signal?.aborted) { onAbort(); throw new Error("Aborted"); }
|
|
1469
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1470
|
+
|
|
1471
|
+
let responseText = "";
|
|
1472
|
+
let sdkMessageCount = 0;
|
|
1473
|
+
let textDeltaCount = 0;
|
|
1474
|
+
let resultSubtype: string | undefined;
|
|
1475
|
+
|
|
1476
|
+
try {
|
|
1477
|
+
for await (const message of sdkQuery) {
|
|
1478
|
+
if (wasAborted) break;
|
|
1479
|
+
sdkMessageCount++;
|
|
1480
|
+
|
|
1481
|
+
switch (message.type) {
|
|
1482
|
+
case "stream_event": {
|
|
1483
|
+
const event = (message as SDKMessage & { event: any }).event;
|
|
1484
|
+
// Text deltas → accumulate and stream
|
|
1485
|
+
if (event?.type === "content_block_delta" && event.delta?.type === "text_delta") {
|
|
1486
|
+
responseText += event.delta.text;
|
|
1487
|
+
textDeltaCount++;
|
|
1488
|
+
options?.onStreamUpdate?.(responseText);
|
|
1489
|
+
}
|
|
1490
|
+
// Tool call start → track for action summary progress
|
|
1491
|
+
if (event?.type === "content_block_start" && event.content_block?.type === "tool_use") {
|
|
1492
|
+
debug(`askCodebuddy: tool_use start: ${event.content_block.name}`);
|
|
1493
|
+
toolCalls.set(event.content_block.id, {
|
|
1494
|
+
name: mapToolName(event.content_block.name),
|
|
1495
|
+
status: "running",
|
|
1496
|
+
});
|
|
1497
|
+
}
|
|
1498
|
+
break;
|
|
1499
|
+
}
|
|
1500
|
+
case "assistant": {
|
|
1501
|
+
// Update tool calls with full input for action summary
|
|
1502
|
+
for (const block of (message as any).message?.content ?? []) {
|
|
1503
|
+
if (block.type === "tool_use") {
|
|
1504
|
+
toolCalls.set(block.id, {
|
|
1505
|
+
name: mapToolName(block.name),
|
|
1506
|
+
status: "complete",
|
|
1507
|
+
rawInput: block.input,
|
|
1508
|
+
});
|
|
1509
|
+
}
|
|
1510
|
+
}
|
|
1511
|
+
break;
|
|
1512
|
+
}
|
|
1513
|
+
case "result": {
|
|
1514
|
+
resultSubtype = message.subtype;
|
|
1515
|
+
const r = message as any;
|
|
1516
|
+
if (r.usage) {
|
|
1517
|
+
debug(`askCodebuddy: result usage: in=${r.usage.input_tokens} out=${r.usage.output_tokens} cacheRead=${r.usage.cache_read_input_tokens ?? 0} cacheWrite=${r.usage.cache_creation_input_tokens ?? 0} turns=${r.num_turns ?? "?"}`);
|
|
1518
|
+
}
|
|
1519
|
+
if (!responseText && message.subtype === "success" && message.result) {
|
|
1520
|
+
responseText = message.result;
|
|
1521
|
+
}
|
|
1522
|
+
break;
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
const stopReason = wasAborted ? "cancelled" : "stop";
|
|
1528
|
+
debug(`askCodebuddy: done`,
|
|
1529
|
+
`stopReason=${stopReason} resultSubtype=${resultSubtype ?? "none"}`,
|
|
1530
|
+
`sdkMessages=${sdkMessageCount} textDeltas=${textDeltaCount} responseLen=${responseText.length}`,
|
|
1531
|
+
`toolCalls=${toolCalls.size}`);
|
|
1532
|
+
return { responseText, stopReason };
|
|
1533
|
+
} finally {
|
|
1534
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1535
|
+
sdkQuery.interrupt();
|
|
1536
|
+
}
|
|
1537
|
+
}
|
|
1538
|
+
|
|
1539
|
+
// --- Extension registration ---
|
|
1540
|
+
|
|
1541
|
+
const DEFAULT_TOOL_DESCRIPTION_FULL = "Delegate to CodeBuddy for a second opinion or analysis (code review, architecture questions, debugging theories), or to autonomously handle a task. Defaults to read-only mode — use full mode when the user wants to delegate a task that requires changes. Prefer to handle straightforward tasks yourself.";
|
|
1542
|
+
const DEFAULT_TOOL_DESCRIPTION = "Delegate to CodeBuddy for a second opinion or analysis (code review, architecture questions, debugging theories). Read-only — CodeBuddy can explore the codebase but not make changes. Prefer to handle straightforward tasks yourself.";
|
|
1543
|
+
|
|
1544
|
+
const PREVIEW_MAX_CHARS = 1000;
|
|
1545
|
+
const PREVIEW_MAX_LINES = 6;
|
|
1546
|
+
|
|
1547
|
+
let askCodebuddyToolName = "AskCodebuddy";
|
|
1548
|
+
|
|
1549
|
+
export default function (pi: ExtensionAPI) {
|
|
1550
|
+
// Disable non-essential CodeBuddy traffic (update checks, MCP registry, telemetry)
|
|
1551
|
+
process.env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = "1";
|
|
1552
|
+
|
|
1553
|
+
const config = loadConfig(process.cwd());
|
|
1554
|
+
debug("loadConfig:", JSON.stringify(config));
|
|
1555
|
+
providerSettings = config.provider ?? {};
|
|
1556
|
+
// We need these settings to know if we're eligible for 1M context on certain models
|
|
1557
|
+
longContextSettings = {
|
|
1558
|
+
plan: providerSettings.plan ?? "pro",
|
|
1559
|
+
longContextExtraUsage: providerSettings.longContextExtraUsage ?? false,
|
|
1560
|
+
};
|
|
1561
|
+
const registeredModels = MODELS; // ponytail: no long-context suffix for CodeBuddy
|
|
1562
|
+
|
|
1563
|
+
// Reset shared session on pi session lifecycle events
|
|
1564
|
+
const clearSession = (event: string) => {
|
|
1565
|
+
debug(`${event}: clearing session ${sharedSession?.sessionId?.slice(0, 8) ?? "none"}`);
|
|
1566
|
+
sharedSession = null;
|
|
1567
|
+
|
|
1568
|
+
// Clear the global streamSimple if this instance registered it.
|
|
1569
|
+
// This allows /reload to work — the old instance clears the flag so
|
|
1570
|
+
// the new instance can register fresh without wrapping stale state.
|
|
1571
|
+
const g = globalThis as Record<symbol, any>;
|
|
1572
|
+
if (g[ACTIVE_STREAM_SIMPLE_KEY] === streamClaudeAgentSdk) {
|
|
1573
|
+
debug(`${event}: clearing ACTIVE_STREAM_SIMPLE_KEY`);
|
|
1574
|
+
g[ACTIVE_STREAM_SIMPLE_KEY] = undefined;
|
|
1575
|
+
}
|
|
1576
|
+
};
|
|
1577
|
+
pi.on("session_start", (event, ctx) => {
|
|
1578
|
+
piUI = ctx.ui;
|
|
1579
|
+
if (event.reason === "new" || event.reason === "resume" || event.reason === "fork") {
|
|
1580
|
+
clearSession(`session_start:${event.reason}`);
|
|
1581
|
+
}
|
|
1582
|
+
});
|
|
1583
|
+
pi.on("session_shutdown", () => clearSession("session_shutdown"));
|
|
1584
|
+
|
|
1585
|
+
pi.on("session_before_compact", async (event, ctx) => {
|
|
1586
|
+
if (ctx.model?.baseUrl !== "codebuddy-local") return undefined;
|
|
1587
|
+
debug(
|
|
1588
|
+
`session_before_compact: takeover reason=${event.reason} willRetry=${event.willRetry} ` +
|
|
1589
|
+
`isSplitTurn=${event.preparation.isSplitTurn} messages=${event.preparation.messagesToSummarize.length} ` +
|
|
1590
|
+
`turnPrefix=${event.preparation.turnPrefixMessages.length}`,
|
|
1591
|
+
);
|
|
1592
|
+
try {
|
|
1593
|
+
reinjectPriorCompactionFileOps(event.branchEntries, event.preparation);
|
|
1594
|
+
const compaction = await compact(
|
|
1595
|
+
event.preparation,
|
|
1596
|
+
ctx.model,
|
|
1597
|
+
undefined,
|
|
1598
|
+
undefined,
|
|
1599
|
+
event.customInstructions,
|
|
1600
|
+
event.signal,
|
|
1601
|
+
undefined,
|
|
1602
|
+
isolatedStreamFn,
|
|
1603
|
+
undefined,
|
|
1604
|
+
);
|
|
1605
|
+
debug(`session_before_compact: takeover complete summaryLen=${compaction.summary.length}`);
|
|
1606
|
+
return { compaction };
|
|
1607
|
+
} catch (err) {
|
|
1608
|
+
const msg = errorMessage(err);
|
|
1609
|
+
debug("session_before_compact: takeover failed; cancelling to avoid native compact fallback", err);
|
|
1610
|
+
ctx.ui?.notify?.(
|
|
1611
|
+
`Claude bridge compact failed (${msg}); cancelled to avoid known hang. Retry, switch model, or reduce context.`,
|
|
1612
|
+
"error",
|
|
1613
|
+
);
|
|
1614
|
+
return { cancel: true };
|
|
1615
|
+
}
|
|
1616
|
+
});
|
|
1617
|
+
|
|
1618
|
+
// pi /compact and session-tree navigation (rewind / fork-at-point /
|
|
1619
|
+
// branch switch) both mutate pi's messages array out from under the
|
|
1620
|
+
// bridge. syncSharedSession's REUSE check would otherwise see
|
|
1621
|
+
// slice(cursor) === [] (or skip entries) and keep --resume'ing a CC
|
|
1622
|
+
// session that no longer matches pi's history. /compact in particular
|
|
1623
|
+
// triggers CC's autocompact-thrashing guard (issue #8). Force the next
|
|
1624
|
+
// call down the REBUILD path so CC sees the current history.
|
|
1625
|
+
const markRebuild = (event: string) => {
|
|
1626
|
+
if (sharedSession) {
|
|
1627
|
+
debug(`${event}: marking needsRebuild on session ${sharedSession.sessionId.slice(0, 8)}`);
|
|
1628
|
+
sharedSession = { ...sharedSession, needsRebuild: true };
|
|
1629
|
+
}
|
|
1630
|
+
};
|
|
1631
|
+
pi.on("session_compact", (event) => markRebuild(`session_compact:${event.reason}:willRetry=${event.willRetry}`));
|
|
1632
|
+
pi.on("session_tree", () => markRebuild("session_tree"));
|
|
1633
|
+
|
|
1634
|
+
// --- Provider ---
|
|
1635
|
+
//
|
|
1636
|
+
// Guard against re-registration when the module is loaded multiple times
|
|
1637
|
+
// (e.g., when spawning subagents). The shared ModelRegistry would otherwise
|
|
1638
|
+
// overwrite the parent's streamSimple, breaking tool result delivery.
|
|
1639
|
+
// See ACTIVE_STREAM_SIMPLE_KEY for the full mechanism.
|
|
1640
|
+
|
|
1641
|
+
const g = globalThis as Record<symbol, any>;
|
|
1642
|
+
if (!g[ACTIVE_STREAM_SIMPLE_KEY]) {
|
|
1643
|
+
// First instance: store our streamSimple and register.
|
|
1644
|
+
g[ACTIVE_STREAM_SIMPLE_KEY] = streamClaudeAgentSdk;
|
|
1645
|
+
pi.registerProvider(PROVIDER_ID, {
|
|
1646
|
+
baseUrl: "codebuddy-local",
|
|
1647
|
+
apiKey: "not-used",
|
|
1648
|
+
api: "codebuddy-sdk",
|
|
1649
|
+
models: registeredModels,
|
|
1650
|
+
// Cast: pi-ai AssistantMessageEventStream diamond dep between pi-coding-agent and pi-agent-core
|
|
1651
|
+
streamSimple: streamClaudeAgentSdk as any,
|
|
1652
|
+
});
|
|
1653
|
+
} else {
|
|
1654
|
+
// Subsequent instance (subagent session): skip registration entirely.
|
|
1655
|
+
// The subagent already has access to codebuddy-sdk models via the shared
|
|
1656
|
+
// ModelRegistry from the parent's registration. Calls to those models
|
|
1657
|
+
// route through the parent's streamSimple via reentrant QueryContexts.
|
|
1658
|
+
debug(`provider: skipping re-registration, parent instance active (module=${moduleInstanceId})`);
|
|
1659
|
+
}
|
|
1660
|
+
|
|
1661
|
+
// --- AskCodebuddy tool ---
|
|
1662
|
+
|
|
1663
|
+
const askConf = config.askCodebuddy;
|
|
1664
|
+
const allowFull = askConf?.allowFullMode !== false;
|
|
1665
|
+
const defaultMode = askConf?.defaultMode ?? "read";
|
|
1666
|
+
const defaultIsolated = askConf?.defaultIsolated ?? false;
|
|
1667
|
+
askCodebuddyToolName = askConf?.name ?? "AskCodebuddy";
|
|
1668
|
+
|
|
1669
|
+
const modeValues = allowFull ? ["read", "full", "none"] as const : ["read", "none"] as const;
|
|
1670
|
+
let modeDesc = `"read" (default): questions about the codebase — review, analysis, explain. "none": general knowledge only (no file access).`;
|
|
1671
|
+
if (allowFull) modeDesc += ` "full": allows writing and bash execution (careful: runs without feedback to pi).`;
|
|
1672
|
+
|
|
1673
|
+
if (askConf?.enabled !== false) {
|
|
1674
|
+
const askCodebuddyParams = Type.Object({
|
|
1675
|
+
prompt: Type.String({ description: "The question or task for CodeBuddy. By default Claude sees the full conversation history. Don't research up front, let Claude explore." }),
|
|
1676
|
+
mode: Type.Optional(StringEnum(modeValues, { description: modeDesc })),
|
|
1677
|
+
model: Type.Optional(Type.String({ description: 'Claude model (e.g. "opus", "sonnet", "haiku", or full ID). Defaults to "opus".' })),
|
|
1678
|
+
thinking: Type.Optional(StringEnum(["off", "minimal", "low", "medium", "high", "xhigh"] as const, { description: "Thinking effort level. Omit to use CodeBuddy's default." })),
|
|
1679
|
+
isolated: Type.Optional(Type.Boolean({ description: "When true, Claude sees only this prompt (clean session). When false (default), Claude sees the full conversation history." })),
|
|
1680
|
+
});
|
|
1681
|
+
pi.registerTool<typeof askCodebuddyParams>({
|
|
1682
|
+
name: askConf?.name ?? "AskCodebuddy",
|
|
1683
|
+
label: askConf?.label ?? "Ask CodeBuddy",
|
|
1684
|
+
description: askConf?.description ?? (allowFull ? DEFAULT_TOOL_DESCRIPTION_FULL : DEFAULT_TOOL_DESCRIPTION),
|
|
1685
|
+
parameters: askCodebuddyParams,
|
|
1686
|
+
renderCall(args, theme) {
|
|
1687
|
+
let text = theme.fg("mdLink", theme.bold("AskCodebuddy "));
|
|
1688
|
+
const mode = args.mode ?? defaultMode;
|
|
1689
|
+
const tags: string[] = [];
|
|
1690
|
+
if (mode !== defaultMode) tags.push(`mode=${mode}`);
|
|
1691
|
+
if (args.model) tags.push(`model=${args.model}`);
|
|
1692
|
+
if (args.thinking) tags.push(`thinking=${args.thinking}`);
|
|
1693
|
+
if (args.isolated) tags.push("isolated");
|
|
1694
|
+
if (tags.length) text += `${theme.fg("accent", `[${tags.join(", ")}]`)} `;
|
|
1695
|
+
const truncated = args.prompt.length > PREVIEW_MAX_CHARS ? args.prompt.substring(0, PREVIEW_MAX_CHARS) : args.prompt;
|
|
1696
|
+
const lines = truncated.split("\n").slice(0, PREVIEW_MAX_LINES);
|
|
1697
|
+
text += theme.fg("muted", `"${lines.join("\n")}"`);
|
|
1698
|
+
if (args.prompt.length > PREVIEW_MAX_CHARS || args.prompt.split("\n").length > PREVIEW_MAX_LINES) text += theme.fg("dim", " …");
|
|
1699
|
+
return new Text(text, 0, 0);
|
|
1700
|
+
},
|
|
1701
|
+
renderResult(result, { expanded, isPartial }, theme) {
|
|
1702
|
+
if (isPartial) {
|
|
1703
|
+
const status = result.content[0]?.type === "text" ? result.content[0].text : "working...";
|
|
1704
|
+
return new Text(theme.fg("mdLink", "◉ CodeBuddy ") + theme.fg("muted", status), 0, 0);
|
|
1705
|
+
}
|
|
1706
|
+
|
|
1707
|
+
const details = result.details as { prompt?: string; executionTime?: number; actions?: string; error?: boolean } | undefined;
|
|
1708
|
+
const body = result.content[0]?.type === "text" ? result.content[0].text : "";
|
|
1709
|
+
|
|
1710
|
+
let text = details?.error
|
|
1711
|
+
? theme.fg("error", "✗ CodeBuddy error")
|
|
1712
|
+
: theme.fg("mdLink", "✓ CodeBuddy");
|
|
1713
|
+
|
|
1714
|
+
if (details?.executionTime) text += ` ${theme.fg("dim", `${(details.executionTime / 1000).toFixed(1)}s`)}`;
|
|
1715
|
+
if (details?.actions) text += ` ${theme.fg("muted", details.actions)}`;
|
|
1716
|
+
|
|
1717
|
+
if (expanded) {
|
|
1718
|
+
if (details?.prompt) text += `\n${theme.fg("dim", `Prompt: ${details.prompt}`)}`;
|
|
1719
|
+
if (details?.prompt && body) text += `\n${theme.fg("dim", "─".repeat(40))}`;
|
|
1720
|
+
if (body) text += `\n${theme.fg("toolOutput", body)}`;
|
|
1721
|
+
} else {
|
|
1722
|
+
const truncated = body.length > PREVIEW_MAX_CHARS ? body.substring(0, PREVIEW_MAX_CHARS) : body;
|
|
1723
|
+
const lines = truncated.split("\n").slice(0, PREVIEW_MAX_LINES);
|
|
1724
|
+
if (lines.length) text += `\n${theme.fg("toolOutput", lines.join("\n"))}`;
|
|
1725
|
+
if (body.length > PREVIEW_MAX_CHARS || body.split("\n").length > PREVIEW_MAX_LINES) text += `\n${theme.fg("dim", `… (${keyHint("app.tools.expand", "to expand")})`)}`;
|
|
1726
|
+
|
|
1727
|
+
}
|
|
1728
|
+
|
|
1729
|
+
return new Text(text, 0, 0);
|
|
1730
|
+
},
|
|
1731
|
+
async execute(_id, params, signal, onUpdate, ctx) {
|
|
1732
|
+
// Guard: circular delegation
|
|
1733
|
+
if (ctx.model?.baseUrl === "codebuddy-local") {
|
|
1734
|
+
debug("askCodebuddy: blocked circular delegation (active provider is codebuddy-sdk)");
|
|
1735
|
+
return {
|
|
1736
|
+
content: [{ type: "text" as const, text: "Error: AskCodebuddy cannot be used when the active provider is codebuddy-sdk — you're already running through CodeBuddy." }],
|
|
1737
|
+
details: { error: true },
|
|
1738
|
+
};
|
|
1739
|
+
}
|
|
1740
|
+
|
|
1741
|
+
const mode = (params.mode ?? defaultMode) as "full" | "read" | "none";
|
|
1742
|
+
const isolated = params.isolated ?? defaultIsolated;
|
|
1743
|
+
const toolCalls = new Map<string, ToolCallState>();
|
|
1744
|
+
const start = Date.now();
|
|
1745
|
+
|
|
1746
|
+
const progressInterval = setInterval(() => {
|
|
1747
|
+
const elapsed = ((Date.now() - start) / 1000).toFixed(0);
|
|
1748
|
+
const summary = buildActionSummary(toolCalls);
|
|
1749
|
+
const status = summary ? `${elapsed}s — ${summary}` : `${elapsed}s — working...`;
|
|
1750
|
+
onUpdate?.({
|
|
1751
|
+
content: [{ type: "text", text: status }],
|
|
1752
|
+
details: { prompt: params.prompt, executionTime: Date.now() - start },
|
|
1753
|
+
});
|
|
1754
|
+
}, 1000);
|
|
1755
|
+
|
|
1756
|
+
try {
|
|
1757
|
+
const result = await promptAndWait(params.prompt, mode, toolCalls, signal, {
|
|
1758
|
+
systemPrompt: ctx.getSystemPrompt(),
|
|
1759
|
+
appendSkills: askConf?.appendSkills,
|
|
1760
|
+
model: params.model,
|
|
1761
|
+
thinking: params.thinking,
|
|
1762
|
+
isolated,
|
|
1763
|
+
context: isolated ? undefined : buildSessionContext(ctx.sessionManager.getBranch()).messages as Context["messages"],
|
|
1764
|
+
});
|
|
1765
|
+
clearInterval(progressInterval);
|
|
1766
|
+
onUpdate?.({ content: [{ type: "text", text: "" }], details: {} });
|
|
1767
|
+
const executionTime = Date.now() - start;
|
|
1768
|
+
const actions = buildActionSummary(toolCalls);
|
|
1769
|
+
|
|
1770
|
+
const text = actions
|
|
1771
|
+
? `${result.responseText}\n\n[CodeBuddy actions: ${actions}]`
|
|
1772
|
+
: result.responseText;
|
|
1773
|
+
return {
|
|
1774
|
+
content: [{ type: "text" as const, text }],
|
|
1775
|
+
details: { prompt: params.prompt, executionTime, actions },
|
|
1776
|
+
};
|
|
1777
|
+
} catch (err) {
|
|
1778
|
+
clearInterval(progressInterval);
|
|
1779
|
+
debug(`askCodebuddy error: mode=${mode}, model=${params.model ?? "default"}, isolated=${isolated}, elapsed=${((Date.now() - start) / 1000).toFixed(1)}s, error=`, err);
|
|
1780
|
+
const msg = errorMessage(err);
|
|
1781
|
+
return {
|
|
1782
|
+
content: [{ type: "text" as const, text: `Error: ${msg}` }],
|
|
1783
|
+
details: { prompt: params.prompt, executionTime: Date.now() - start, error: true },
|
|
1784
|
+
};
|
|
1785
|
+
}
|
|
1786
|
+
},
|
|
1787
|
+
});
|
|
1788
|
+
}
|
|
97
1789
|
}
|