This repository was archived by the owner on Aug 21, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathprompt.ts
More file actions
403 lines (372 loc) · 11.3 KB
/
Copy pathprompt.ts
File metadata and controls
403 lines (372 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
/**
* Build Command Code wire messages from OpenAI-compatible chat messages,
* including text, images, PDFs, and generic file attachments.
*
* Laguna S 2.1 is text-only — images become placeholders (matching Command Code
* stripImages behavior) while text/PDF/file payloads are inlined when possible.
*/
import type {
WireAssistantContent,
WireMessage,
WireTool,
WireUserContent,
} from "./gateway-types.js";
import { toWireName } from "./mcp-names.js";
const IMAGE_OMITTED =
"[image omitted: the active model is text-only]";
function parseDataUrl(url: string): {
mediaType: string;
data: string;
} | null {
const match = /^data:([^;,]+)?(?:;charset=[^;,]+)?;base64,(.+)$/i.exec(
url.trim(),
);
if (!match) return null;
return {
mediaType: (match[1] || "application/octet-stream").toLowerCase(),
data: match[2],
};
}
function isHttpUrl(url: string): boolean {
return /^https?:\/\//i.test(url.trim());
}
function mediaLooksLikePdf(mediaType: string, urlHint = ""): boolean {
return (
mediaType.includes("pdf") ||
/\.pdf(\?|#|$)/i.test(urlHint) ||
(mediaType === "application/octet-stream" &&
/\.pdf(\?|#|$)/i.test(urlHint))
);
}
function mediaLooksLikeImage(mediaType: string): boolean {
return mediaType.startsWith("image/");
}
function mediaLooksLikeText(mediaType: string, name = ""): boolean {
if (mediaType.startsWith("text/")) return true;
if (
/json|xml|javascript|typescript|yaml|toml|markdown|csv|html|css/.test(
mediaType,
)
) {
return true;
}
return /\.(txt|md|json|js|ts|tsx|jsx|py|rs|go|java|c|cpp|h|css|html|yml|yaml|toml|csv|xml|sh|bash|zsh|sql)$/i.test(
name,
);
}
function tryDecodeBase64Text(data: string, limit = 200_000): string | null {
try {
const buf = Buffer.from(data, "base64");
if (buf.length > limit) {
return (
buf.subarray(0, limit).toString("utf8") +
`\n…[truncated ${buf.length - limit} bytes]`
);
}
const text = buf.toString("utf8");
// Reject if mostly non-printable.
const sample = text.slice(0, 2000);
const bad = [...sample].filter((ch) => {
const code = ch.charCodeAt(0);
return code < 9 || (code > 13 && code < 32);
}).length;
if (bad > sample.length * 0.05) return null;
return text;
} catch {
return null;
}
}
export function extractTextContent(content: unknown): string {
if (typeof content === "string") return content;
if (!Array.isArray(content)) return "";
return content
.map((part) => {
if (!part || typeof part !== "object") return "";
const p = part as { type?: string; text?: string };
if (p.type === "text" && typeof p.text === "string") return p.text;
return "";
})
.filter(Boolean)
.join("\n");
}
export function contentHasAttachments(content: unknown): boolean {
if (!Array.isArray(content)) return false;
return content.some((part) => {
if (!part || typeof part !== "object") return false;
const type = (part as { type?: unknown }).type;
return (
type === "image_url" ||
type === "input_image" ||
type === "file" ||
type === "input_file" ||
type === "image" ||
type === "document"
);
});
}
type AttachmentSink = {
texts: string[];
images: Array<{ dataUrl: string; mimeType: string }>;
vision: boolean;
};
function pushAttachmentPart(part: unknown, sink: AttachmentSink): void {
if (!part || typeof part !== "object") return;
const p = part as Record<string, unknown>;
const type = typeof p.type === "string" ? p.type : "";
if (type === "text" && typeof p.text === "string") {
sink.texts.push(p.text);
return;
}
if (type === "image_url" || type === "input_image" || type === "image") {
const imageUrl = p.image_url ?? p.image ?? p.url;
const url =
typeof imageUrl === "string"
? imageUrl
: imageUrl &&
typeof imageUrl === "object" &&
typeof (imageUrl as { url?: unknown }).url === "string"
? (imageUrl as { url: string }).url
: typeof p.data === "string"
? `data:${typeof p.media_type === "string" ? p.media_type : "image/png"};base64,${p.data}`
: null;
if (!url) return;
const parsed = parseDataUrl(url);
if (parsed && mediaLooksLikeImage(parsed.mediaType)) {
if (sink.vision) {
sink.images.push({
dataUrl: url,
mimeType: parsed.mediaType,
});
} else {
sink.texts.push(
`<attached_image>\n${IMAGE_OMITTED}\n(media_type=${parsed.mediaType})\n</attached_image>`,
);
}
return;
}
if (isHttpUrl(url)) {
if (sink.vision) {
sink.images.push({ dataUrl: url, mimeType: "image/*" });
} else {
sink.texts.push(
`<attached_image>\n${IMAGE_OMITTED}\n(url=${url})\n</attached_image>`,
);
}
}
return;
}
if (type === "file" || type === "input_file" || type === "document") {
const file = (p.file && typeof p.file === "object" ? p.file : p) as Record<
string,
unknown
>;
const url = typeof file.url === "string" ? file.url : null;
const data = typeof file.data === "string" ? file.data : null;
const mediaType =
typeof file.media_type === "string"
? file.media_type
: typeof file.mime_type === "string"
? file.mime_type
: "application/octet-stream";
const name =
typeof file.filename === "string"
? file.filename
: typeof file.name === "string"
? file.name
: "";
if (url) {
const parsed = parseDataUrl(url);
if (parsed) {
handleBinaryAttachment(sink, parsed.mediaType, parsed.data, name);
return;
}
if (isHttpUrl(url)) {
sink.texts.push(
`<attached_file name="${name || "remote"}" media_type="${mediaType}">\nRemote file URL: ${url}\n</attached_file>`,
);
}
return;
}
if (data) {
handleBinaryAttachment(sink, mediaType, data, name);
}
}
}
function handleBinaryAttachment(
sink: AttachmentSink,
mediaType: string,
data: string,
name: string,
): void {
if (mediaLooksLikeImage(mediaType)) {
const dataUrl = `data:${mediaType};base64,${data}`;
if (sink.vision) {
sink.images.push({ dataUrl, mimeType: mediaType });
} else {
sink.texts.push(
`<attached_image name="${name}">\n${IMAGE_OMITTED}\n</attached_image>`,
);
}
return;
}
if (mediaLooksLikePdf(mediaType, name)) {
sink.texts.push(
`<attached_pdf name="${name || "document.pdf"}">\n[PDF attachment base64 length=${data.length}. The active model is text-only; summarize from filename/context or ask the user for extracted text.]\n</attached_pdf>`,
);
return;
}
if (mediaLooksLikeText(mediaType, name)) {
const decoded = tryDecodeBase64Text(data);
if (decoded !== null) {
sink.texts.push(
`<attached_file name="${name || "file"}" media_type="${mediaType}">\n${decoded}\n</attached_file>`,
);
return;
}
}
sink.texts.push(
`<attached_file name="${name || "file"}" media_type="${mediaType}">\n[binary attachment, base64 length=${data.length}]\n</attached_file>`,
);
}
export function openaiContentToUserParts(
content: unknown,
vision: boolean,
): WireUserContent {
if (typeof content === "string") {
const text = content.trim();
return text ? [{ type: "text", text }] : [];
}
if (!Array.isArray(content)) return [];
const sink: AttachmentSink = { texts: [], images: [], vision };
for (const part of content) pushAttachmentPart(part, sink);
const out: WireUserContent = [];
for (const text of sink.texts) {
if (text.trim()) out.push({ type: "text", text });
}
for (const img of sink.images) {
out.push({
type: "image",
image: img.dataUrl,
mimeType: img.mimeType,
});
}
return out;
}
export type OpenAITool = {
type?: string;
function?: {
name?: string;
description?: string;
parameters?: Record<string, unknown>;
};
};
export type OpenAIMessage = {
role?: string;
content?: unknown;
tool_calls?: Array<{
id?: string;
type?: string;
function?: { name?: string; arguments?: string };
}>;
tool_call_id?: string;
name?: string;
};
export function openaiToolsToWire(tools: OpenAITool[]): WireTool[] {
return tools
.map((t) => {
const name = t.function?.name;
if (!name) return null;
return {
// Gateway expects MCP tools as mcp__<server>__<tool>; OpenCode
// names them <server>_<tool> natively. Map so agents see them.
name: toWireName(name),
description: t.function?.description || name,
input_schema:
(t.function?.parameters as Record<string, unknown>) || {
type: "object",
properties: {},
},
};
})
.filter((t): t is WireTool => Boolean(t));
}
/**
* Convert a full OpenAI chat history into Command Code wire messages.
* System messages are collected separately.
*/
export function openaiMessagesToWire(
messages: OpenAIMessage[],
options: { vision: boolean },
): { system: string; messages: WireMessage[] } {
const systemParts: string[] = [];
const wire: WireMessage[] = [];
const toolNames = new Map<string, string>();
for (const msg of messages) {
const role = msg.role || "";
if (role === "system" || role === "developer") {
const text = extractTextContent(msg.content).trim();
if (text) systemParts.push(text);
continue;
}
if (role === "user") {
const parts = openaiContentToUserParts(msg.content, options.vision);
if (parts.length > 0) wire.push({ role: "user", content: parts });
continue;
}
if (role === "assistant") {
const content: WireAssistantContent = [];
const text = extractTextContent(msg.content).trim();
if (text) content.push({ type: "text", text });
if (Array.isArray(msg.tool_calls)) {
for (const tc of msg.tool_calls) {
const id = tc.id || "";
const name = tc.function?.name || "";
if (!id || !name) continue;
toolNames.set(id, name);
let input: Record<string, unknown> = {};
try {
input = JSON.parse(tc.function?.arguments || "{}") as Record<
string,
unknown
>;
} catch {
input = { raw: tc.function?.arguments || "" };
}
content.push({
type: "tool-call",
toolCallId: id,
toolName: toWireName(name),
input,
});
}
}
if (content.length > 0) wire.push({ role: "assistant", content });
continue;
}
if (role === "tool") {
const toolCallId = msg.tool_call_id || "";
if (!toolCallId) continue;
const toolName = msg.name || toolNames.get(toolCallId) || "";
if (!toolName) {
throw new Error(
`Tool result ${toolCallId} has no matching assistant tool call`,
);
}
wire.push({
role: "tool",
content: [
{
type: "tool-result",
toolCallId,
toolName: toWireName(toolName),
output: {
type: "text",
value: extractTextContent(msg.content),
},
},
],
});
}
}
return { system: systemParts.join("\n\n"), messages: wire };
}