@narumitw/pi-btw 0.60.2 → 0.61.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -4
- package/dist/index.ts +1685 -1029
- package/dist/index.ts.map +4 -4
- package/docs/workflows.md +10 -2
- package/package.json +1 -1
- package/src/btw.ts +43 -160
- package/src/conversation-context.ts +74 -0
- package/src/fullscreen-ui.ts +196 -7
- package/src/main-thread-updates.ts +40 -0
- package/src/menu.ts +34 -2
- package/src/settings.ts +49 -0
- package/src/side-thread.ts +40 -37
- package/src/transcript-pager.ts +9 -1
- package/src/workspace-layout.ts +559 -0
package/docs/workflows.md
CHANGED
|
@@ -17,8 +17,16 @@ Opening and closing without a new result does not reorder them.
|
|
|
17
17
|
|
|
18
18
|
## Read, select, and search
|
|
19
19
|
|
|
20
|
-
The
|
|
21
|
-
The
|
|
20
|
+
The dedicated workspace keeps answers above the editor and identifies itself with a fixed `btw · side thread` header.
|
|
21
|
+
The default **Fullscreen** layout gives the side thread the complete workspace.
|
|
22
|
+
**Side thread left** and **Side thread right** place it beside Pi's native, live main-thread rendering; terminals narrower than 80 columns show only the side thread.
|
|
23
|
+
A single muted divider separates the panes; click either pane to move keyboard focus to it.
|
|
24
|
+
Drag the divider with the primary mouse button to resize the side thread between 20% and 80% of the workspace.
|
|
25
|
+
Releasing the button saves that side-thread ratio for either pane placement; a failed save restores the last saved width and reports the error.
|
|
26
|
+
Pi's search and keyboard viewport controls apply to the active pane.
|
|
27
|
+
The mouse wheel scrolls the pane under the pointer without moving keyboard focus, and a narrow terminal returns focus to the visible side thread.
|
|
28
|
+
A branch selected through **Start from main thread tree…** supplies side-model context but does not replace the active main thread shown in the other pane.
|
|
29
|
+
The main agent may keep running, and the main pane redraws its progress while either pane is active.
|
|
22
30
|
Submit each question with Enter; successful prior questions and answers remain available to the side model.
|
|
23
31
|
|
|
24
32
|
Drag the primary mouse button across the transcript to select text.
|
package/package.json
CHANGED
package/src/btw.ts
CHANGED
|
@@ -1,11 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
clampThinkingLevel,
|
|
4
|
-
getSupportedThinkingLevels,
|
|
5
|
-
type Model,
|
|
6
|
-
type ProviderHeaders,
|
|
7
|
-
} from "@earendil-works/pi-ai";
|
|
8
|
-
import { BorderedLoader, type ExtensionAPI, type ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
1
|
+
import { type Api, clampThinkingLevel, getSupportedThinkingLevels, type Model } from "@earendil-works/pi-ai";
|
|
2
|
+
import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
9
3
|
import type { MenuContext, RunMenuResult } from "@narumitw/pi-tui-kit";
|
|
10
4
|
import {
|
|
11
5
|
type BtwBringToMainSegment,
|
|
@@ -18,7 +12,9 @@ import {
|
|
|
18
12
|
getAnsweredTurns,
|
|
19
13
|
summarizeBringToMain,
|
|
20
14
|
} from "./bring-to-main.js";
|
|
15
|
+
import { buildConversationContext } from "./conversation-context.js";
|
|
21
16
|
import { type RunBtwFullscreen, runBtwFullscreen } from "./fullscreen-ui.js";
|
|
17
|
+
import { registerBtwMainThreadUpdates } from "./main-thread-updates.js";
|
|
22
18
|
import { pickMainEntry } from "./main-tree-picker.js";
|
|
23
19
|
import {
|
|
24
20
|
type BtwCommandMenuResult,
|
|
@@ -29,6 +25,8 @@ import {
|
|
|
29
25
|
} from "./menu.js";
|
|
30
26
|
import {
|
|
31
27
|
type BtwSettings,
|
|
28
|
+
effectiveBtwLayout,
|
|
29
|
+
effectiveBtwSidePaneRatio,
|
|
32
30
|
effectiveFullscreenCopyOnSelect,
|
|
33
31
|
effectiveRememberThinkingLevelChanges,
|
|
34
32
|
parseBtwModelReference,
|
|
@@ -53,8 +51,11 @@ import {
|
|
|
53
51
|
type TranscriptPagerAction,
|
|
54
52
|
} from "./transcript-pager.js";
|
|
55
53
|
|
|
54
|
+
export { buildConversationContext } from "./conversation-context.js";
|
|
56
55
|
export {
|
|
56
|
+
BTW_LAYOUTS,
|
|
57
57
|
BTW_SETTINGS_FILE,
|
|
58
|
+
type BtwLayout,
|
|
58
59
|
type BtwSettings,
|
|
59
60
|
type BtwSettingsLoadResult,
|
|
60
61
|
normalizeBtwSettings,
|
|
@@ -69,19 +70,20 @@ export {
|
|
|
69
70
|
} from "./side-thread.js";
|
|
70
71
|
export { sanitizeSingleLine } from "./text.js";
|
|
71
72
|
|
|
72
|
-
const MAX_CONTEXT_CHARS = 40_000;
|
|
73
|
-
|
|
74
73
|
interface LoadBtwThinkingLevelOptions {
|
|
75
74
|
settingsPath?: string;
|
|
76
75
|
warn?: (message: string) => void;
|
|
77
76
|
}
|
|
78
77
|
|
|
79
|
-
type BtwModelRegistry = Pick<ExtensionCommandContext["modelRegistry"], "find" | "
|
|
78
|
+
type BtwModelRegistry = Pick<ExtensionCommandContext["modelRegistry"], "find" | "getAvailable">;
|
|
80
79
|
|
|
81
80
|
type BtwCompletionRegistry = Pick<ExtensionCommandContext["modelRegistry"], "streamSimple">;
|
|
82
81
|
|
|
83
82
|
export function createModelRegistryCompleteSimple(modelRegistry: BtwCompletionRegistry): CompleteSimpleFunction {
|
|
84
|
-
|
|
83
|
+
const completeSimple: CompleteSimpleFunction = async (model, context, options) =>
|
|
84
|
+
modelRegistry.streamSimple(model, context, options).result();
|
|
85
|
+
completeSimple.appliesRequestHeaderTransforms = true;
|
|
86
|
+
return completeSimple;
|
|
85
87
|
}
|
|
86
88
|
|
|
87
89
|
interface ResolveBtwModelOptions {
|
|
@@ -93,7 +95,8 @@ interface ResolveBtwModelOptions {
|
|
|
93
95
|
|
|
94
96
|
export interface ResolvedBtwModel {
|
|
95
97
|
model: Model<Api>;
|
|
96
|
-
|
|
98
|
+
/** @deprecated Pi resolves request authentication through modelRegistry.streamSimple(). */
|
|
99
|
+
auth?: SideQuestionAuth;
|
|
97
100
|
}
|
|
98
101
|
|
|
99
102
|
export interface BtwThreadState {
|
|
@@ -112,6 +115,10 @@ export async function resolveBtwModel({
|
|
|
112
115
|
warn,
|
|
113
116
|
}: ResolveBtwModelOptions): Promise<ResolvedBtwModel | undefined> {
|
|
114
117
|
const reportWarning = (message: string) => warn?.(sanitizeSingleLine(message));
|
|
118
|
+
const availableModels = modelRegistry.getAvailable();
|
|
119
|
+
const isAvailable = (model: Model<Api>): boolean =>
|
|
120
|
+
availableModels.some((candidate) => candidate.provider === model.provider && candidate.id === model.id);
|
|
121
|
+
|
|
115
122
|
if (settings.model) {
|
|
116
123
|
const fallback = currentModel ? `${currentModel.provider}/${currentModel.id}` : "the current model";
|
|
117
124
|
const reference = parseBtwModelReference(settings.model);
|
|
@@ -122,52 +129,19 @@ export async function resolveBtwModel({
|
|
|
122
129
|
const configuredModel = modelRegistry.find(reference.provider, reference.modelId);
|
|
123
130
|
if (!configuredModel) {
|
|
124
131
|
reportWarning(`pi-btw model ${settings.model} was not found; falling back to ${fallback}.`);
|
|
132
|
+
} else if (isAvailable(configuredModel)) {
|
|
133
|
+
return { model: configuredModel };
|
|
125
134
|
} else {
|
|
126
135
|
const sameAsCurrent =
|
|
127
136
|
configuredModel === currentModel ||
|
|
128
137
|
(configuredModel.provider === currentModel?.provider && configuredModel.id === currentModel.id);
|
|
129
138
|
const fallbackAction = sameAsCurrent ? "no distinct current model is available" : `falling back to ${fallback}`;
|
|
130
|
-
|
|
131
|
-
const auth = await modelRegistry.getApiKeyAndHeaders(configuredModel);
|
|
132
|
-
if (auth.ok && hasRequestAuth(auth)) {
|
|
133
|
-
return {
|
|
134
|
-
model: auth.baseUrl ? { ...configuredModel, baseUrl: auth.baseUrl } : configuredModel,
|
|
135
|
-
auth,
|
|
136
|
-
};
|
|
137
|
-
}
|
|
138
|
-
const reason = auth.ok ? "has no request credentials" : auth.error;
|
|
139
|
-
reportWarning(`pi-btw model ${settings.model} is unavailable (${reason}); ${fallbackAction}.`);
|
|
140
|
-
} catch (error: unknown) {
|
|
141
|
-
reportWarning(`pi-btw model ${settings.model} credentials failed (${formatError(error)}); ${fallbackAction}.`);
|
|
142
|
-
}
|
|
139
|
+
reportWarning(`pi-btw model ${settings.model} is unavailable; ${fallbackAction}.`);
|
|
143
140
|
if (sameAsCurrent) return undefined;
|
|
144
141
|
}
|
|
145
142
|
}
|
|
146
143
|
|
|
147
|
-
|
|
148
|
-
try {
|
|
149
|
-
const auth = await modelRegistry.getApiKeyAndHeaders(currentModel);
|
|
150
|
-
if (auth.ok && hasRequestAuth(auth)) {
|
|
151
|
-
// Direct provider streams bypass Pi's request preparation, including OAuth routing.
|
|
152
|
-
return {
|
|
153
|
-
model: auth.baseUrl ? { ...currentModel, baseUrl: auth.baseUrl } : currentModel,
|
|
154
|
-
auth,
|
|
155
|
-
};
|
|
156
|
-
}
|
|
157
|
-
} catch {
|
|
158
|
-
// The caller reports the final lack of an available model.
|
|
159
|
-
}
|
|
160
|
-
return undefined;
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
function hasRequestAuth(auth: SideQuestionAuth): boolean {
|
|
164
|
-
return Boolean(
|
|
165
|
-
auth.apiKey || providerHeadersHaveValue(auth.headers) || (auth.env && Object.keys(auth.env).length > 0),
|
|
166
|
-
);
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
function providerHeadersHaveValue(headers: ProviderHeaders | undefined): boolean {
|
|
170
|
-
return headers !== undefined && Object.values(headers).some((value) => value !== null);
|
|
144
|
+
return currentModel && isAvailable(currentModel) ? { model: currentModel } : undefined;
|
|
171
145
|
}
|
|
172
146
|
|
|
173
147
|
export async function loadBtwThinkingLevel(
|
|
@@ -182,7 +156,7 @@ export async function loadBtwThinkingLevel(
|
|
|
182
156
|
|
|
183
157
|
options.warn?.(
|
|
184
158
|
sanitizeSingleLine(
|
|
185
|
-
`pi-btw settings ignored: ${settings.reason}; expected optional model "provider/model-id", omitted thinkingLevel for Same as main thread or thinkingLevel "${BTW_THINKING_LEVELS.join('" | "')}", boolean rememberThinkingLevelChanges, and
|
|
159
|
+
`pi-btw settings ignored: ${settings.reason}; expected optional model "provider/model-id", omitted thinkingLevel for Same as main thread or thinkingLevel "${BTW_THINKING_LEVELS.join('" | "')}", boolean rememberThinkingLevelChanges, boolean fullscreenCopyOnSelect, layout "fullscreen" | "left-pane" | "right-pane", and sidePaneRatio from 0.2 to 0.8. Using current Pi thinking level.`,
|
|
186
160
|
),
|
|
187
161
|
);
|
|
188
162
|
return currentThinkingLevel;
|
|
@@ -211,9 +185,9 @@ function notifySafely(
|
|
|
211
185
|
}
|
|
212
186
|
}
|
|
213
187
|
|
|
214
|
-
// Keep
|
|
215
|
-
//
|
|
216
|
-
//
|
|
188
|
+
// Keep the command coordinator intact: its injectable menu, request, resume, and
|
|
189
|
+
// delivery flows share the same thread-state and test seams; settings, keybinding
|
|
190
|
+
// policy, terminal ownership, and rendering live in separate modules.
|
|
217
191
|
export interface BtwExtensionDependencies {
|
|
218
192
|
showCommandMenu?: (
|
|
219
193
|
pi: ExtensionAPI,
|
|
@@ -222,7 +196,7 @@ export interface BtwExtensionDependencies {
|
|
|
222
196
|
) => Promise<BtwCommandMenuResult>;
|
|
223
197
|
pickMainEntry?: typeof pickMainEntry;
|
|
224
198
|
loadSettings?: typeof loadSettingsForCommand;
|
|
225
|
-
resolveModel?: typeof
|
|
199
|
+
resolveModel?: typeof resolveBtwModelForCommand;
|
|
226
200
|
runThread?: typeof runBtwThread;
|
|
227
201
|
runFullscreen?: RunBtwFullscreen;
|
|
228
202
|
}
|
|
@@ -231,9 +205,10 @@ export default function btw(pi: ExtensionAPI, dependencies: BtwExtensionDependen
|
|
|
231
205
|
const showCommandMenu = dependencies.showCommandMenu ?? showCommandMenuForBtw;
|
|
232
206
|
const pickEntry = dependencies.pickMainEntry ?? pickMainEntry;
|
|
233
207
|
const loadSettings = dependencies.loadSettings ?? loadSettingsForCommand;
|
|
234
|
-
const resolveModel = dependencies.resolveModel ??
|
|
208
|
+
const resolveModel = dependencies.resolveModel ?? resolveBtwModelForCommand;
|
|
235
209
|
const runThread = dependencies.runThread ?? runBtwThread;
|
|
236
210
|
const runFullscreen = dependencies.runFullscreen ?? runBtwFullscreen;
|
|
211
|
+
const subscribeMainThreadUpdates = registerBtwMainThreadUpdates(pi);
|
|
237
212
|
// Pi creates a fresh extension instance after session replacement or reload.
|
|
238
213
|
const resumableThreads = new Map<string, BtwThreadState>();
|
|
239
214
|
let nextThreadNumber = 1;
|
|
@@ -333,6 +308,11 @@ export default function btw(pi: ExtensionAPI, dependencies: BtwExtensionDependen
|
|
|
333
308
|
},
|
|
334
309
|
{
|
|
335
310
|
copyOnSelect: effectiveFullscreenCopyOnSelect(settings),
|
|
311
|
+
layout: effectiveBtwLayout(settings),
|
|
312
|
+
sidePaneRatio: effectiveBtwSidePaneRatio(settings),
|
|
313
|
+
persistSidePaneRatio: (ratio, signal) =>
|
|
314
|
+
updateBtwSettings({ sidePaneRatio: ratio }, { signal }).then(() => undefined),
|
|
315
|
+
subscribeMainThreadUpdates: (listener) => subscribeMainThreadUpdates(ctx.sessionManager, listener),
|
|
336
316
|
...(settings.keybindings ? { keybindings: settings.keybindings } : {}),
|
|
337
317
|
},
|
|
338
318
|
);
|
|
@@ -373,40 +353,17 @@ type ModelResolutionOutcome =
|
|
|
373
353
|
| { kind: "unavailable" }
|
|
374
354
|
| { kind: "selected"; selected: ResolvedBtwModel };
|
|
375
355
|
|
|
376
|
-
async function
|
|
356
|
+
async function resolveBtwModelForCommand(
|
|
377
357
|
settings: BtwSettings,
|
|
378
358
|
ctx: ExtensionCommandContext,
|
|
379
359
|
): Promise<ModelResolutionOutcome> {
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
settled = true;
|
|
386
|
-
done({ kind: "cancelled" });
|
|
387
|
-
};
|
|
388
|
-
|
|
389
|
-
resolveBtwModel({
|
|
390
|
-
settings,
|
|
391
|
-
currentModel: ctx.model,
|
|
392
|
-
modelRegistry: ctx.modelRegistry,
|
|
393
|
-
warn: (message) => {
|
|
394
|
-
if (!settled) notifySafely(ctx, message, "warning");
|
|
395
|
-
},
|
|
396
|
-
})
|
|
397
|
-
.then((selected) => {
|
|
398
|
-
if (settled) return;
|
|
399
|
-
settled = true;
|
|
400
|
-
done(selected ? { kind: "selected", selected } : { kind: "unavailable" });
|
|
401
|
-
})
|
|
402
|
-
.catch(() => {
|
|
403
|
-
if (settled) return;
|
|
404
|
-
settled = true;
|
|
405
|
-
done({ kind: "unavailable" });
|
|
406
|
-
});
|
|
407
|
-
|
|
408
|
-
return loader;
|
|
360
|
+
const selected = await resolveBtwModel({
|
|
361
|
+
settings,
|
|
362
|
+
currentModel: ctx.model,
|
|
363
|
+
modelRegistry: ctx.modelRegistry,
|
|
364
|
+
warn: (message) => notifySafely(ctx, message, "warning"),
|
|
409
365
|
});
|
|
366
|
+
return selected ? { kind: "selected", selected } : { kind: "unavailable" };
|
|
410
367
|
}
|
|
411
368
|
|
|
412
369
|
interface RunBtwThreadDependencies {
|
|
@@ -859,7 +816,6 @@ async function askThreadQuestion(
|
|
|
859
816
|
question,
|
|
860
817
|
model: selected.model,
|
|
861
818
|
thinkingLevel,
|
|
862
|
-
auth: selected.auth,
|
|
863
819
|
signal: view.signal,
|
|
864
820
|
completeSimple: createModelRegistryCompleteSimple(ctx.modelRegistry),
|
|
865
821
|
sessionId: readBtwSessionId(ctx),
|
|
@@ -892,76 +848,3 @@ async function showThreadComposer(
|
|
|
892
848
|
}),
|
|
893
849
|
);
|
|
894
850
|
}
|
|
895
|
-
|
|
896
|
-
type MessageContentBlock = {
|
|
897
|
-
type?: string;
|
|
898
|
-
text?: string;
|
|
899
|
-
name?: string;
|
|
900
|
-
arguments?: unknown;
|
|
901
|
-
result?: unknown;
|
|
902
|
-
};
|
|
903
|
-
|
|
904
|
-
type SessionMessage = {
|
|
905
|
-
role?: string;
|
|
906
|
-
content?: unknown;
|
|
907
|
-
stopReason?: string;
|
|
908
|
-
};
|
|
909
|
-
|
|
910
|
-
type SessionEntry = {
|
|
911
|
-
type: string;
|
|
912
|
-
message?: SessionMessage;
|
|
913
|
-
};
|
|
914
|
-
|
|
915
|
-
export function buildConversationContext(entries: readonly SessionEntry[]) {
|
|
916
|
-
const sections: string[] = [];
|
|
917
|
-
|
|
918
|
-
for (const entry of entries) {
|
|
919
|
-
if (entry.type !== "message" || !entry.message?.role) continue;
|
|
920
|
-
|
|
921
|
-
const role = entry.message.role;
|
|
922
|
-
if (role !== "user" && role !== "assistant") continue;
|
|
923
|
-
|
|
924
|
-
const contentLines = extractContentLines(entry.message.content);
|
|
925
|
-
if (contentLines.length === 0) continue;
|
|
926
|
-
|
|
927
|
-
const label = role === "user" ? "User" : "Assistant";
|
|
928
|
-
const status =
|
|
929
|
-
entry.message.stopReason && entry.message.stopReason !== "stop" ? ` (${entry.message.stopReason})` : "";
|
|
930
|
-
sections.push(`${label}${status}: ${contentLines.join("\n")}`);
|
|
931
|
-
}
|
|
932
|
-
|
|
933
|
-
return truncateFromStart(sections.join("\n\n"), MAX_CONTEXT_CHARS);
|
|
934
|
-
}
|
|
935
|
-
|
|
936
|
-
function extractContentLines(content: unknown): string[] {
|
|
937
|
-
if (typeof content === "string") return [content.trim()].filter(Boolean);
|
|
938
|
-
if (!Array.isArray(content)) return [];
|
|
939
|
-
|
|
940
|
-
const lines: string[] = [];
|
|
941
|
-
for (const part of content) {
|
|
942
|
-
if (!part || typeof part !== "object") continue;
|
|
943
|
-
const block = part as MessageContentBlock;
|
|
944
|
-
if (block.type === "text" && typeof block.text === "string") {
|
|
945
|
-
lines.push(block.text.trim());
|
|
946
|
-
} else if (block.type === "toolCall" && typeof block.name === "string") {
|
|
947
|
-
lines.push(`Tool call: ${block.name}(${formatJson(block.arguments)})`);
|
|
948
|
-
} else if (block.type === "toolResult" && typeof block.name === "string") {
|
|
949
|
-
lines.push(`Tool result from ${block.name}: ${formatJson(block.result)}`);
|
|
950
|
-
}
|
|
951
|
-
}
|
|
952
|
-
return lines.filter(Boolean);
|
|
953
|
-
}
|
|
954
|
-
|
|
955
|
-
function formatJson(value: unknown) {
|
|
956
|
-
if (value === undefined) return "";
|
|
957
|
-
try {
|
|
958
|
-
return JSON.stringify(value);
|
|
959
|
-
} catch {
|
|
960
|
-
return String(value);
|
|
961
|
-
}
|
|
962
|
-
}
|
|
963
|
-
|
|
964
|
-
function truncateFromStart(text: string, maxChars: number) {
|
|
965
|
-
if (text.length <= maxChars) return text;
|
|
966
|
-
return `[Earlier context omitted; showing the last ${maxChars} characters.]\n${text.slice(-maxChars)}`;
|
|
967
|
-
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
const MAX_CONTEXT_CHARS = 40_000;
|
|
2
|
+
|
|
3
|
+
type MessageContentBlock = {
|
|
4
|
+
type?: string;
|
|
5
|
+
text?: string;
|
|
6
|
+
name?: string;
|
|
7
|
+
arguments?: unknown;
|
|
8
|
+
result?: unknown;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
type SessionMessage = {
|
|
12
|
+
role?: string;
|
|
13
|
+
content?: unknown;
|
|
14
|
+
stopReason?: string;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export type BtwSessionEntry = {
|
|
18
|
+
type: string;
|
|
19
|
+
message?: SessionMessage;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export function buildConversationContext(entries: readonly BtwSessionEntry[]): string {
|
|
23
|
+
const sections: string[] = [];
|
|
24
|
+
|
|
25
|
+
for (const entry of entries) {
|
|
26
|
+
if (entry.type !== "message" || !entry.message?.role) continue;
|
|
27
|
+
|
|
28
|
+
const role = entry.message.role;
|
|
29
|
+
if (role !== "user" && role !== "assistant") continue;
|
|
30
|
+
|
|
31
|
+
const contentLines = extractContentLines(entry.message.content);
|
|
32
|
+
if (contentLines.length === 0) continue;
|
|
33
|
+
|
|
34
|
+
const label = role === "user" ? "User" : "Assistant";
|
|
35
|
+
const status =
|
|
36
|
+
entry.message.stopReason && entry.message.stopReason !== "stop" ? ` (${entry.message.stopReason})` : "";
|
|
37
|
+
sections.push(`${label}${status}: ${contentLines.join("\n")}`);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
return truncateFromStart(sections.join("\n\n"), MAX_CONTEXT_CHARS);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function extractContentLines(content: unknown): string[] {
|
|
44
|
+
if (typeof content === "string") return [content.trim()].filter(Boolean);
|
|
45
|
+
if (!Array.isArray(content)) return [];
|
|
46
|
+
|
|
47
|
+
const lines: string[] = [];
|
|
48
|
+
for (const part of content) {
|
|
49
|
+
if (!part || typeof part !== "object") continue;
|
|
50
|
+
const block = part as MessageContentBlock;
|
|
51
|
+
if (block.type === "text" && typeof block.text === "string") {
|
|
52
|
+
lines.push(block.text.trim());
|
|
53
|
+
} else if (block.type === "toolCall" && typeof block.name === "string") {
|
|
54
|
+
lines.push(`Tool call: ${block.name}(${formatJson(block.arguments)})`);
|
|
55
|
+
} else if (block.type === "toolResult" && typeof block.name === "string") {
|
|
56
|
+
lines.push(`Tool result from ${block.name}: ${formatJson(block.result)}`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return lines.filter(Boolean);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function formatJson(value: unknown): string {
|
|
63
|
+
if (value === undefined) return "";
|
|
64
|
+
try {
|
|
65
|
+
return JSON.stringify(value);
|
|
66
|
+
} catch {
|
|
67
|
+
return String(value);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function truncateFromStart(text: string, maxChars: number): string {
|
|
72
|
+
if (text.length <= maxChars) return text;
|
|
73
|
+
return `[Earlier context omitted; showing the last ${maxChars} characters.]\n${text.slice(-maxChars)}`;
|
|
74
|
+
}
|