opencode-m365-copilot 2.2.0 → 2.3.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 +158 -16
- package/dist/{agent-CRSlpTfS.mjs → agent-DPNplWJY.mjs} +1 -1
- package/dist/cli.mjs +6 -4
- package/dist/{dist-CcVQZgN5.mjs → dist-QjFnJhR3.mjs} +1 -1
- package/dist/{login-B-1yNcEb.mjs → login-Cts_gng-.mjs} +2 -2
- package/dist/plugin.mjs +12 -2
- package/dist/{server-BRXlKFEJ.mjs → server-DXznAk1h.mjs} +953 -73
- package/dist/server.d.mts +38 -0
- package/dist/server.mjs +1 -1
- package/package.json +1 -1
|
@@ -61,26 +61,24 @@ const DEFAULT_MODEL = "quick";
|
|
|
61
61
|
const MODELS = [
|
|
62
62
|
m("work", "Ask your mail, Teams & files", "magic", false, true),
|
|
63
63
|
m("work-think", "Ask your mail, Teams & files (Think Deeper)", "Gpt_5_5_Reasoning", true, true),
|
|
64
|
-
m("gpt-
|
|
65
|
-
m("gpt-
|
|
64
|
+
m("gpt-6.2-sol", "GPT-6.2 Sol", "Gpt_62_Sol_Reasoning", true),
|
|
65
|
+
m("gpt-6.1-sol", "GPT-6.1 Sol", "Gpt_61_Sol_Reasoning", true),
|
|
66
|
+
m("gpt-6-sol", "GPT-6 Sol", "Gpt_6_Sol_Reasoning", true),
|
|
66
67
|
m("gpt-5.6-think-deeper", "GPT-5.6 (Think Deeper)", "Gpt_5_6_Reasoning", true),
|
|
67
68
|
m("gpt-5.5-think-deeper", "GPT-5.5 (Think Deeper)", "Gpt_5_5_Reasoning", true),
|
|
68
69
|
m("gpt-5.5", "GPT-5.5", "Gpt_5_5_Chat", false),
|
|
69
70
|
m("gpt-5.5-quick", "GPT-5.5 (Quick)", "Gpt_5_5_Chat", false),
|
|
70
71
|
m("m365-copilot", "M365 Copilot (Auto)", "magic", false),
|
|
71
|
-
m("auto", "M365 Copilot (Auto)", "magic", false),
|
|
72
72
|
m("quick", "GPT (Quick)", "Gpt_5_5_Chat", false),
|
|
73
73
|
m("think-deeper", "GPT (Think Deeper)", "Gpt_5_5_Reasoning", true),
|
|
74
|
+
m("gpt-5.6", "GPT-5.6 (unreliable tool calls)", "Gpt_5_6_Chat", false),
|
|
75
|
+
m("gpt-5.6-quick", "GPT-5.6 (Quick, unreliable tool calls)", "Gpt_5_6_Chat", false),
|
|
74
76
|
m("claude-sonnet", "Claude Sonnet (via M365)", "Claude_Sonnet", false),
|
|
75
|
-
m("claude", "Claude Sonnet (via M365)", "Claude_Sonnet", false),
|
|
76
77
|
m("claude-sonnet-think-deeper", "Claude Sonnet (Think Deeper)", "Claude_Sonnet_Reasoning", true),
|
|
77
|
-
m("gpt-5.4", "GPT-5.4 (Think Deeper)", "Gpt_5_4_Reasoning", true),
|
|
78
78
|
m("gpt-5.4-think-deeper", "GPT-5.4 (Think Deeper)", "Gpt_5_4_Reasoning", true),
|
|
79
79
|
m("gpt-5.4-quick", "GPT-5.4 (Quick)", "Gpt_5_4_Chat", false),
|
|
80
|
-
m("gpt-5.3", "GPT-5.3 (Quick)", "Gpt_5_3_Chat", false),
|
|
81
80
|
m("gpt-5.3-quick", "GPT-5.3 (Quick)", "Gpt_5_3_Chat", false),
|
|
82
81
|
m("gpt-5.3-think-deeper", "GPT-5.3 (Think Deeper)", "Gpt_5_3_Reasoning", true),
|
|
83
|
-
m("gpt-5.2", "GPT-5.2 (Quick)", "Gpt_5_2_Chat", false),
|
|
84
82
|
m("gpt-5.2-quick", "GPT-5.2 (Quick)", "Gpt_5_2_Chat", false),
|
|
85
83
|
m("gpt-5.2-think-deeper", "GPT-5.2 (Think Deeper)", "Gpt_5_2_Reasoning", true),
|
|
86
84
|
m(LOCAL_TITLE_MODEL, "Local titler (no M365 call)", null, false)
|
|
@@ -107,11 +105,32 @@ function pickerName(name, tone, grounded) {
|
|
|
107
105
|
if (tone === null) return name;
|
|
108
106
|
return `${grounded ? "Work" : "Code"} · ${name}`;
|
|
109
107
|
}
|
|
108
|
+
/**
|
|
109
|
+
* Ids we accept but no longer advertise, each mapped to the canonical id it means.
|
|
110
|
+
*
|
|
111
|
+
* Each pair used to be advertised twice under one picker name, so opencode listed the
|
|
112
|
+
* model twice. The canonical id is the descriptive one: `m365-copilot` is the id the
|
|
113
|
+
* README documents and measured, and the GPT ids carry their tone suffix like their
|
|
114
|
+
* siblings (`-quick`, `-think-deeper`). The short forms stay accepted, with or without
|
|
115
|
+
* the `m365/` prefix, so saved configs keep working.
|
|
116
|
+
*/
|
|
117
|
+
const MODEL_ALIASES = {
|
|
118
|
+
auto: "m365-copilot",
|
|
119
|
+
claude: "claude-sonnet",
|
|
120
|
+
"gpt-5.4": "gpt-5.4-think-deeper",
|
|
121
|
+
"gpt-5.3": "gpt-5.3-quick",
|
|
122
|
+
"gpt-5.2": "gpt-5.2-quick"
|
|
123
|
+
};
|
|
110
124
|
const BY_ID = new Map(MODELS.map((model) => [model.id, model]));
|
|
125
|
+
for (const [alias, canonical] of Object.entries(MODEL_ALIASES)) {
|
|
126
|
+
const model = BY_ID.get(canonical);
|
|
127
|
+
if (!model) throw new Error(`model alias ${alias} points at unknown id ${canonical}`);
|
|
128
|
+
BY_ID.set(alias, model);
|
|
129
|
+
}
|
|
111
130
|
/**
|
|
112
131
|
* Look up a model, falling back to the default for anything we do not know.
|
|
113
132
|
*
|
|
114
|
-
* Harnesses routinely send ids we never advertised (
|
|
133
|
+
* Harnesses routinely send ids we never advertised (`MODEL_ALIASES`, stale config, a model
|
|
115
134
|
* string typed by hand). Answering on the default beats rejecting the request.
|
|
116
135
|
*/
|
|
117
136
|
function resolveModel(id) {
|
|
@@ -132,6 +151,44 @@ function isLocalModel(id) {
|
|
|
132
151
|
function listModelIds() {
|
|
133
152
|
return MODELS.map((model) => model.id);
|
|
134
153
|
}
|
|
154
|
+
/**
|
|
155
|
+
* - Reasoning GPT tones keep the agent (agent-less GPT-5.x made no tool calls in the
|
|
156
|
+
* reference project, 0/4), but under the default framing they say they cannot reach
|
|
157
|
+
* the workspace, even after a command succeeded. The reference project's `relay`
|
|
158
|
+
* framing, where the user asks to be guided through their own terminal, took that to
|
|
159
|
+
* 30/30. Ours said it on the first reply in 8 of 8 runs.
|
|
160
|
+
* - Chat GPT tones work as they are.
|
|
161
|
+
* - Claude stays as it was: with the agent, which M365 answers on GPT. The reference
|
|
162
|
+
* project ran Claude without the agent and with `relay` (193/200), but without the
|
|
163
|
+
* agent an account with no Claude licence refuses every tool turn
|
|
164
|
+
* (`ClaudeUnavailableForLicense`), where today it quietly gets GPT. Unmeasured on a
|
|
165
|
+
* licensed account, so not adopted.
|
|
166
|
+
*/
|
|
167
|
+
/**
|
|
168
|
+
* GPT-6 Sol tones. With the declarative agent attached they serve only on a premium
|
|
169
|
+
* account; on any other account that is a dead route (`InternalError`, no content).
|
|
170
|
+
* Nothing on the token says which kind of account it is, so they always go agent-less.
|
|
171
|
+
* Agent-less, Sol runs commands in a remote bash sandbox of its own, so the relay note
|
|
172
|
+
* names it and asks for the user's terminal instead. From the reference project's
|
|
173
|
+
* protocol notes (`m365-copilot-api.md`, the Sol rows and quirk #21).
|
|
174
|
+
*/
|
|
175
|
+
const SOL_TONE = /^Gpt_\d+_Sol_Reasoning$/;
|
|
176
|
+
const SOL_SANDBOX = "the bash sandbox with /mnt/data and /home/oai";
|
|
177
|
+
function toolRouteFor(tone) {
|
|
178
|
+
if (tone && SOL_TONE.test(tone)) return {
|
|
179
|
+
framing: "relay",
|
|
180
|
+
agent: false,
|
|
181
|
+
sandbox: SOL_SANDBOX
|
|
182
|
+
};
|
|
183
|
+
if (tone?.startsWith("Gpt_") && tone.endsWith("_Reasoning")) return {
|
|
184
|
+
framing: "relay",
|
|
185
|
+
agent: true
|
|
186
|
+
};
|
|
187
|
+
return {
|
|
188
|
+
framing: "default",
|
|
189
|
+
agent: true
|
|
190
|
+
};
|
|
191
|
+
}
|
|
135
192
|
// src/fenced.ts
|
|
136
193
|
/** Info strings we accept as "this is a shell block", beyond the tool's own name. */
|
|
137
194
|
const SHELL_FENCE_INFOS = /* @__PURE__ */ new Set([
|
|
@@ -246,27 +303,13 @@ function shapeOf(tool) {
|
|
|
246
303
|
function buildToolPrompt(tools, options = {}) {
|
|
247
304
|
if (tools.length === 0) return "";
|
|
248
305
|
const shell = findShellTool(tools);
|
|
306
|
+
if (options.framing === "relay") return buildRelayPrompt(tools, shell, options.sandbox);
|
|
249
307
|
const useShellFraming = options.shellFraming ?? Boolean(shell);
|
|
250
308
|
const lines = [];
|
|
251
309
|
lines.push("<tools>");
|
|
252
310
|
lines.push("You are working in a real workspace with real files. These tools are available, and a fenced block is an action the runtime executes for you — not an illustration.");
|
|
253
311
|
lines.push("");
|
|
254
|
-
for (const tool of tools)
|
|
255
|
-
const shape = shapeOf(tool);
|
|
256
|
-
const description = tool.function.description?.trim();
|
|
257
|
-
if (description) lines.push(`${tool.function.name} — ${firstSentence(description)}`);
|
|
258
|
-
lines.push("```" + tool.function.name);
|
|
259
|
-
for (const header of shape.headers) lines.push(`${header}: ${placeholderFor(header, shape.tool)}`);
|
|
260
|
-
if (shape.editPair) {
|
|
261
|
-
lines.push(SEARCH_MARKER);
|
|
262
|
-
lines.push("the exact existing text");
|
|
263
|
-
lines.push(DIVIDER_MARKER);
|
|
264
|
-
lines.push("the replacement text");
|
|
265
|
-
lines.push(REPLACE_MARKER);
|
|
266
|
-
} else if (shape.bodyParam) lines.push(`<${shape.bodyParam}>`);
|
|
267
|
-
lines.push("```");
|
|
268
|
-
lines.push("");
|
|
269
|
-
}
|
|
312
|
+
for (const tool of tools) lines.push(...describeTool(tool), "");
|
|
270
313
|
if (useShellFraming && shell) lines.push(`Prefer doing the whole step by writing one \`\`\`${shell.function.name} block: heredocs to create files, sed to edit, cat/ls/grep to inspect.`);
|
|
271
314
|
if (options.firstTurn ?? true) lines.push("You have not run anything yet, so do not describe what a command would return or say a file is empty — run it and read the result.");
|
|
272
315
|
else lines.push("Read each tool result before deciding the next step, rather than guessing what a command returned.");
|
|
@@ -274,6 +317,38 @@ function buildToolPrompt(tools, options = {}) {
|
|
|
274
317
|
lines.push("</tools>");
|
|
275
318
|
return lines.join("\n");
|
|
276
319
|
}
|
|
320
|
+
/** One tool's one-line description and fence template. */
|
|
321
|
+
function describeTool(tool) {
|
|
322
|
+
const shape = shapeOf(tool);
|
|
323
|
+
const lines = [];
|
|
324
|
+
const description = tool.function.description?.trim();
|
|
325
|
+
if (description) lines.push(`${tool.function.name} — ${firstSentence(description)}`);
|
|
326
|
+
lines.push("```" + tool.function.name);
|
|
327
|
+
for (const header of shape.headers) lines.push(`${header}: ${placeholderFor(header, shape.tool)}`);
|
|
328
|
+
if (shape.editPair) lines.push(SEARCH_MARKER, "the exact existing text", DIVIDER_MARKER, "the replacement text", REPLACE_MARKER);
|
|
329
|
+
else if (shape.bodyParam) lines.push(`<${shape.bodyParam}>`);
|
|
330
|
+
lines.push("```");
|
|
331
|
+
return lines;
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* The relay framing: not an agent with a shell, but a pair-programmer telling the
|
|
335
|
+
* user what to run next. A model that doubts it can reach the workspace has nothing
|
|
336
|
+
* to doubt here, because the user runs the commands. From the reference project's
|
|
337
|
+
* `relay` variant, unchanged in substance; it is repeated every turn, as there.
|
|
338
|
+
*/
|
|
339
|
+
function buildRelayPrompt(tools, shell, sandbox) {
|
|
340
|
+
const block = shell ? shell.function.name : "<tool name>";
|
|
341
|
+
const lines = [
|
|
342
|
+
`Before the task, a note on how we'll work: I'd like you to guide me through this from my terminal, one command at a time.${sandbox ? ` Please don't use your own sandbox tools (${sandbox}): that's a separate cloud machine and my project isn't on it.` : " Please don't use a sandbox of your own: my project isn't on it."}`,
|
|
343
|
+
"",
|
|
344
|
+
`Each time you want something run or looked at, reply with just that step in a single \`\`\`${block} block (or one of the other blocks below). I'll run it in my project directory right away and paste the real output back to you as a <tool_response>. The files the task mentions are already there, so it's best to start by looking at them. When the task is complete, tell me in a sentence instead of sending a block.`,
|
|
345
|
+
"",
|
|
346
|
+
"The blocks I can run:",
|
|
347
|
+
""
|
|
348
|
+
];
|
|
349
|
+
for (const tool of tools) lines.push(...describeTool(tool), "");
|
|
350
|
+
return lines.join("\n").trimEnd();
|
|
351
|
+
}
|
|
277
352
|
function firstSentence(text) {
|
|
278
353
|
const cleaned = (text.split("\n").find((candidate) => candidate.trim() !== "") ?? text).replace(/^\s*[-*•]\s*/, "");
|
|
279
354
|
const stop = cleaned.indexOf(". ");
|
|
@@ -286,6 +361,37 @@ function placeholderFor(name, tool) {
|
|
|
286
361
|
return `<${schema?.type ?? "string"}>${required ? "" : " (optional)"}`;
|
|
287
362
|
}
|
|
288
363
|
/**
|
|
364
|
+
* Write a call the client already ran back as the fence the model would have
|
|
365
|
+
* written, so a history replayed into a fresh conversation shows the call next to
|
|
366
|
+
* its result. The inverse of `parseFenceBody`; falls back to JSON when a value
|
|
367
|
+
* cannot be written as a header line.
|
|
368
|
+
*/
|
|
369
|
+
function renderToolCall(name, rawArguments, tools) {
|
|
370
|
+
const tool = tools.find((candidate) => candidate.function.name === name);
|
|
371
|
+
let args;
|
|
372
|
+
try {
|
|
373
|
+
args = JSON.parse(rawArguments || "{}");
|
|
374
|
+
} catch {
|
|
375
|
+
args = {};
|
|
376
|
+
}
|
|
377
|
+
const json = () => "```" + name + "\n" + (rawArguments || "{}") + "\n```";
|
|
378
|
+
if (!tool || typeof args !== "object" || args === null) return json();
|
|
379
|
+
const shape = shapeOf(tool);
|
|
380
|
+
const lines = [];
|
|
381
|
+
for (const key of Object.keys(args)) {
|
|
382
|
+
if (key === shape.bodyParam || shape.editPair?.includes(key)) continue;
|
|
383
|
+
const value = args[key];
|
|
384
|
+
if (value === void 0 || value === null) continue;
|
|
385
|
+
if (typeof value === "object" || String(value).includes("\n")) return json();
|
|
386
|
+
lines.push(`${key}: ${String(value)}`);
|
|
387
|
+
}
|
|
388
|
+
if (shape.editPair) {
|
|
389
|
+
const [from, to] = shape.editPair;
|
|
390
|
+
if (typeof args[from] === "string" && typeof args[to] === "string") lines.push(SEARCH_MARKER, args[from], DIVIDER_MARKER, args[to], REPLACE_MARKER);
|
|
391
|
+
} else if (shape.bodyParam && typeof args[shape.bodyParam] === "string") lines.push(args[shape.bodyParam]);
|
|
392
|
+
return "```" + name + "\n" + lines.join("\n") + "\n```";
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
289
395
|
* Extract fenced blocks, honouring the CommonMark rule that a fence is closed only by
|
|
290
396
|
* a run of at least as many backticks as opened it.
|
|
291
397
|
*
|
|
@@ -326,6 +432,15 @@ function extractFences(source) {
|
|
|
326
432
|
}
|
|
327
433
|
return fences;
|
|
328
434
|
}
|
|
435
|
+
/**
|
|
436
|
+
* The body of the first closed fence whose info string names `name` (case-insensitive),
|
|
437
|
+
* or undefined. For a tool whose body the proxy reads itself rather than mapping it
|
|
438
|
+
* onto parameters.
|
|
439
|
+
*/
|
|
440
|
+
function firstFenceBody(source, name) {
|
|
441
|
+
const wanted = name.toLowerCase();
|
|
442
|
+
return extractFences(unglueFenceOpeners(source.replace(/\r\n?/g, "\n"))).find((fence) => (fence.info.split(/\s+/)[0] ?? "").toLowerCase() === wanted)?.body;
|
|
443
|
+
}
|
|
329
444
|
function charOffset(lines, lineIndex) {
|
|
330
445
|
let offset = 0;
|
|
331
446
|
for (let i = 0; i < lineIndex && i < lines.length; i += 1) offset += lines[i].length + 1;
|
|
@@ -372,13 +487,27 @@ function stripInventedJson(text) {
|
|
|
372
487
|
result = result.replace(/^\s*\{\s*"final"\s*:\s*(?:"(?:[^"\\]|\\.)*"|[^}]*)\}\s*$/gm, "");
|
|
373
488
|
return result.trim();
|
|
374
489
|
}
|
|
490
|
+
/**
|
|
491
|
+
* Move a fence opener glued to the end of a prose line onto its own line.
|
|
492
|
+
*
|
|
493
|
+
* M365 sometimes writes `…before drafting anything.```shell` with no line break, so the
|
|
494
|
+
* block rendered as text, nothing ran, and the user had to say "resume" (seen live,
|
|
495
|
+
* 2026-11-19). Only an opener with an info word ends the line; an inline ```bash```
|
|
496
|
+
* span does not match, and an unclosed fence is still ignored by `extractFences`.
|
|
497
|
+
*/
|
|
498
|
+
function unglueFenceOpeners(text) {
|
|
499
|
+
return text.replace(/^(.*[^`\s])(`{3,}[A-Za-z][\w-]*)[ \t]*$/gm, "$1\n$2");
|
|
500
|
+
}
|
|
375
501
|
/** Parse a raw M365 response into OpenAI-shaped tool calls plus any prose. */
|
|
376
502
|
function parseToolCalls(source, tools, options = {}) {
|
|
377
|
-
const cleaned = stripInventedJson(source.replace(/\r\n?/g, "\n"));
|
|
378
|
-
|
|
503
|
+
const cleaned = unglueFenceOpeners(stripInventedJson(source.replace(/\r\n?/g, "\n")));
|
|
504
|
+
const none = (text) => ({
|
|
379
505
|
toolCalls: [],
|
|
380
|
-
text
|
|
381
|
-
|
|
506
|
+
text,
|
|
507
|
+
skippedCalls: 0,
|
|
508
|
+
inventedResult: false
|
|
509
|
+
});
|
|
510
|
+
if (tools.length === 0) return none(cleaned);
|
|
382
511
|
const shell = findShellTool(tools);
|
|
383
512
|
const byName = new Map(tools.map((tool) => [tool.function.name.toLowerCase(), tool]));
|
|
384
513
|
const toolFor = (fence) => {
|
|
@@ -388,29 +517,29 @@ function parseToolCalls(source, tools, options = {}) {
|
|
|
388
517
|
const invented = cleaned.search(/<tool_(?:response|result)\b/i);
|
|
389
518
|
const actionable = invented === -1 ? cleaned : cleaned.slice(0, invented);
|
|
390
519
|
const fences = extractFences(actionable);
|
|
391
|
-
if (!(fences.length > 0 && actionable.slice(0, fences[0].start).trim() === "" && Boolean(toolFor(fences[0]))) && isProseDocument(actionable)) return
|
|
392
|
-
toolCalls: [],
|
|
393
|
-
text: cleaned
|
|
394
|
-
};
|
|
520
|
+
if (!(fences.length > 0 && actionable.slice(0, fences[0].start).trim() === "" && Boolean(toolFor(fences[0]))) && isProseDocument(actionable)) return none(cleaned);
|
|
395
521
|
const calls = [];
|
|
396
522
|
const consumed = [];
|
|
523
|
+
let skippedCalls = 0;
|
|
397
524
|
for (const fence of fences) {
|
|
398
525
|
const tool = toolFor(fence);
|
|
399
526
|
if (!tool) continue;
|
|
527
|
+
if (calls.length > 0 && !options.allowMultiple) {
|
|
528
|
+
skippedCalls += 1;
|
|
529
|
+
continue;
|
|
530
|
+
}
|
|
400
531
|
calls.push({
|
|
401
532
|
name: tool.function.name,
|
|
402
533
|
arguments: parseFenceBody(fence.body, tool)
|
|
403
534
|
});
|
|
404
535
|
consumed.push(fence);
|
|
405
|
-
if (!options.allowMultiple) break;
|
|
406
536
|
}
|
|
407
|
-
if (calls.length === 0) return
|
|
408
|
-
toolCalls: [],
|
|
409
|
-
text: cleaned
|
|
410
|
-
};
|
|
537
|
+
if (calls.length === 0) return none(cleaned);
|
|
411
538
|
return {
|
|
412
539
|
toolCalls: calls,
|
|
413
|
-
text: ""
|
|
540
|
+
text: "",
|
|
541
|
+
skippedCalls,
|
|
542
|
+
inventedResult: invented !== -1
|
|
414
543
|
};
|
|
415
544
|
}
|
|
416
545
|
/** Names models use for a file path, compared without case or underscores. */
|
|
@@ -633,6 +762,7 @@ function resolveOptions(raw) {
|
|
|
633
762
|
setDefaultModel: bool(options.setDefaultModel, true),
|
|
634
763
|
setSmallModel: bool(options.setSmallModel, true),
|
|
635
764
|
leanSystemPrompt: bool(options.leanSystemPrompt, false),
|
|
765
|
+
mcpProxy: bool(options.mcpProxy, false),
|
|
636
766
|
baseUrl: typeof options.baseUrl === "string" ? options.baseUrl : void 0,
|
|
637
767
|
apiKey: typeof options.apiKey === "string" && options.apiKey !== "" ? options.apiKey : void 0
|
|
638
768
|
};
|
|
@@ -704,6 +834,7 @@ const OUR_OPTION_KEYS = /* @__PURE__ */ new Set([
|
|
|
704
834
|
"setDefaultModel",
|
|
705
835
|
"setSmallModel",
|
|
706
836
|
"leanSystemPrompt",
|
|
837
|
+
"mcpProxy",
|
|
707
838
|
"baseUrl",
|
|
708
839
|
"apiKey"
|
|
709
840
|
]);
|
|
@@ -1036,7 +1167,7 @@ function createTokenClient(options = {}) {
|
|
|
1036
1167
|
const cache = /* @__PURE__ */ new Map();
|
|
1037
1168
|
async function client() {
|
|
1038
1169
|
if (app) return app;
|
|
1039
|
-
const { PublicClientApplication } = await import("./dist-
|
|
1170
|
+
const { PublicClientApplication } = await import("./dist-QjFnJhR3.mjs");
|
|
1040
1171
|
app = new PublicClientApplication({
|
|
1041
1172
|
auth: {
|
|
1042
1173
|
clientId: CLIENT_ID,
|
|
@@ -1099,6 +1230,533 @@ function authCodeFromUrl(rawUrl) {
|
|
|
1099
1230
|
}
|
|
1100
1231
|
return url.searchParams.get("code") ?? void 0;
|
|
1101
1232
|
}
|
|
1233
|
+
// src/codemode.ts
|
|
1234
|
+
const HEADING = /^# Code Mode[ \t]*$/m;
|
|
1235
|
+
const NAMESPACE_LINE = /^- \S+ \(\d+ tools?\)/;
|
|
1236
|
+
const ENTRY_LINE = /^ {2}(?:- )?(tools[.[].*)$/;
|
|
1237
|
+
const PATH_SEGMENT = /\.([A-Za-z_$][\w$]*)|\["([^"]+)"\]/y;
|
|
1238
|
+
/** Where the section ended before the catalogue was parsed by depth; the fallback when it has no entries. */
|
|
1239
|
+
const LEGACY_END = /^# |^Skills provide |^<[a-z_]+>/m;
|
|
1240
|
+
/** A structured block at column 0 always ends the catalogue, even mid-signature. */
|
|
1241
|
+
const BLOCK_LINE = /^<\/?[a-z_]+>/;
|
|
1242
|
+
function splitLines(text, from) {
|
|
1243
|
+
const lines = [];
|
|
1244
|
+
let start = from;
|
|
1245
|
+
while (start < text.length) {
|
|
1246
|
+
const newline = text.indexOf("\n", start);
|
|
1247
|
+
const end = newline === -1 ? text.length : newline + 1;
|
|
1248
|
+
lines.push({
|
|
1249
|
+
text: text.slice(start, newline === -1 ? text.length : newline),
|
|
1250
|
+
start,
|
|
1251
|
+
end
|
|
1252
|
+
});
|
|
1253
|
+
start = end;
|
|
1254
|
+
}
|
|
1255
|
+
return lines;
|
|
1256
|
+
}
|
|
1257
|
+
/**
|
|
1258
|
+
* Walk one line of a TypeScript signature, tracking bracket depth outside comments and
|
|
1259
|
+
* string literals. Returns the new state, plus where a ` // ` line comment starts at
|
|
1260
|
+
* depth 0 (the entry's description), if one does.
|
|
1261
|
+
*/
|
|
1262
|
+
function scanLine(line, state) {
|
|
1263
|
+
let quote;
|
|
1264
|
+
for (let i = 0; i < line.length; i++) {
|
|
1265
|
+
const char = line[i];
|
|
1266
|
+
if (state.inComment) {
|
|
1267
|
+
if (char === "*" && line[i + 1] === "/") {
|
|
1268
|
+
state.inComment = false;
|
|
1269
|
+
i++;
|
|
1270
|
+
}
|
|
1271
|
+
continue;
|
|
1272
|
+
}
|
|
1273
|
+
if (quote) {
|
|
1274
|
+
if (char === "\\") i++;
|
|
1275
|
+
else if (char === quote) quote = void 0;
|
|
1276
|
+
continue;
|
|
1277
|
+
}
|
|
1278
|
+
if (char === "/" && line[i + 1] === "*") {
|
|
1279
|
+
state.inComment = true;
|
|
1280
|
+
i++;
|
|
1281
|
+
} else if (char === "/" && line[i + 1] === "/") return state.depth <= 0 ? { descriptionAt: i + 2 } : {};
|
|
1282
|
+
else if (char === "\"" || char === "'" || char === "`") quote = char;
|
|
1283
|
+
else if ("({[".includes(char)) state.depth++;
|
|
1284
|
+
else if (")}]".includes(char)) state.depth--;
|
|
1285
|
+
}
|
|
1286
|
+
return {};
|
|
1287
|
+
}
|
|
1288
|
+
function splitPath(path) {
|
|
1289
|
+
if (!path.startsWith("tools")) return void 0;
|
|
1290
|
+
const segments = [];
|
|
1291
|
+
PATH_SEGMENT.lastIndex = 5;
|
|
1292
|
+
while (PATH_SEGMENT.lastIndex < path.length) {
|
|
1293
|
+
const match = PATH_SEGMENT.exec(path);
|
|
1294
|
+
if (!match) return void 0;
|
|
1295
|
+
segments.push(match[1] ?? match[2]);
|
|
1296
|
+
}
|
|
1297
|
+
if (segments.length < 2) return void 0;
|
|
1298
|
+
return {
|
|
1299
|
+
namespace: segments[0],
|
|
1300
|
+
name: segments.slice(1).join(".")
|
|
1301
|
+
};
|
|
1302
|
+
}
|
|
1303
|
+
/** Parse the Code Mode catalogue out of a system prompt, or undefined if there is none. */
|
|
1304
|
+
function parseCodeModeCatalog(systemText) {
|
|
1305
|
+
const heading = HEADING.exec(systemText);
|
|
1306
|
+
if (!heading) return void 0;
|
|
1307
|
+
const start = heading.index;
|
|
1308
|
+
const lines = splitLines(systemText, start + heading[0].length);
|
|
1309
|
+
const tools = [];
|
|
1310
|
+
let catalogueEnd;
|
|
1311
|
+
let preamble = "";
|
|
1312
|
+
let i = 0;
|
|
1313
|
+
for (; i < lines.length && !NAMESPACE_LINE.test(lines[i].text); i++) {
|
|
1314
|
+
if (/^# |^<[a-z_]+>/.test(lines[i].text)) break;
|
|
1315
|
+
preamble += `${lines[i].text}\n`;
|
|
1316
|
+
}
|
|
1317
|
+
const partial = /\bcatalog(?:ue)? is partial\b/i.test(preamble);
|
|
1318
|
+
while (i < lines.length) {
|
|
1319
|
+
const line = lines[i];
|
|
1320
|
+
if (NAMESPACE_LINE.test(line.text)) {
|
|
1321
|
+
catalogueEnd = line.end;
|
|
1322
|
+
i++;
|
|
1323
|
+
continue;
|
|
1324
|
+
}
|
|
1325
|
+
const entry = ENTRY_LINE.exec(line.text);
|
|
1326
|
+
if (entry) {
|
|
1327
|
+
const state = {
|
|
1328
|
+
depth: 0,
|
|
1329
|
+
inComment: false
|
|
1330
|
+
};
|
|
1331
|
+
const entryLines = [];
|
|
1332
|
+
let description = "";
|
|
1333
|
+
let j = i;
|
|
1334
|
+
for (; j < lines.length; j++) {
|
|
1335
|
+
const current = lines[j];
|
|
1336
|
+
if (j > i && !state.inComment && state.depth > 0 && BLOCK_LINE.test(current.text)) break;
|
|
1337
|
+
if (j > i && (NAMESPACE_LINE.test(current.text) || ENTRY_LINE.test(current.text)) && state.depth > 0 && !state.inComment) break;
|
|
1338
|
+
const text = j === i ? entry[1] : current.text;
|
|
1339
|
+
entryLines.push(text);
|
|
1340
|
+
const { descriptionAt } = scanLine(text, state);
|
|
1341
|
+
if (state.depth <= 0 && !state.inComment) {
|
|
1342
|
+
if (descriptionAt !== void 0) description = text.slice(descriptionAt).trim();
|
|
1343
|
+
j++;
|
|
1344
|
+
break;
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
const signature = entryLines.join("\n");
|
|
1348
|
+
const path = signature.slice(0, signature.indexOf("(")).trim();
|
|
1349
|
+
const parts = splitPath(path);
|
|
1350
|
+
if (parts) tools.push({
|
|
1351
|
+
path,
|
|
1352
|
+
...parts,
|
|
1353
|
+
signature,
|
|
1354
|
+
description
|
|
1355
|
+
});
|
|
1356
|
+
catalogueEnd = lines[j - 1].end;
|
|
1357
|
+
i = j;
|
|
1358
|
+
continue;
|
|
1359
|
+
}
|
|
1360
|
+
if (line.text.trim() === "") {
|
|
1361
|
+
i++;
|
|
1362
|
+
continue;
|
|
1363
|
+
}
|
|
1364
|
+
break;
|
|
1365
|
+
}
|
|
1366
|
+
let end;
|
|
1367
|
+
if (catalogueEnd === void 0) {
|
|
1368
|
+
const next = systemText.slice(start + heading[0].length).search(LEGACY_END);
|
|
1369
|
+
end = next === -1 ? systemText.length : start + heading[0].length + next;
|
|
1370
|
+
} else {
|
|
1371
|
+
end = catalogueEnd;
|
|
1372
|
+
while (end < systemText.length && systemText[end] === "\n") end++;
|
|
1373
|
+
}
|
|
1374
|
+
return {
|
|
1375
|
+
tools,
|
|
1376
|
+
partial,
|
|
1377
|
+
section: {
|
|
1378
|
+
start,
|
|
1379
|
+
end
|
|
1380
|
+
}
|
|
1381
|
+
};
|
|
1382
|
+
}
|
|
1383
|
+
/**
|
|
1384
|
+
* Remove opencode 2's whole `# Code Mode` section, from its heading to the end of the
|
|
1385
|
+
* catalogue. Text without one is returned unchanged.
|
|
1386
|
+
*/
|
|
1387
|
+
function stripCodeModeSection(systemText) {
|
|
1388
|
+
const catalog = parseCodeModeCatalog(systemText);
|
|
1389
|
+
if (!catalog) return systemText;
|
|
1390
|
+
return systemText.slice(0, catalog.section.start) + systemText.slice(catalog.section.end);
|
|
1391
|
+
}
|
|
1392
|
+
/** Score for a query that names a tool exactly, or a namespace's whole prefix. */
|
|
1393
|
+
const EXACT_SCORE = 1e3;
|
|
1394
|
+
const NAME_WEIGHT = 3;
|
|
1395
|
+
const DESCRIPTION_WEIGHT = 1;
|
|
1396
|
+
/** Tools named per server in the summary, and servers named, before "+N more". */
|
|
1397
|
+
const SUMMARY_TOOLS_PER_SERVER = 4;
|
|
1398
|
+
const SUMMARY_SERVERS = 8;
|
|
1399
|
+
/** A call path: `tools` then dotted identifiers or `["bracketed"]` names, nothing else. */
|
|
1400
|
+
const CALL_PATH = /^tools(?:\.[A-Za-z_$][\w$]*|\["[^"\\]+"\])+$/;
|
|
1401
|
+
const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
|
|
1402
|
+
/** Group `[key, value]` pairs by key, keeping first-seen order. */
|
|
1403
|
+
function groupBy(items, key, value) {
|
|
1404
|
+
const groups = /* @__PURE__ */ new Map();
|
|
1405
|
+
for (const item of items) {
|
|
1406
|
+
const group = groups.get(key(item)) ?? [];
|
|
1407
|
+
group.push(value(item));
|
|
1408
|
+
groups.set(key(item), group);
|
|
1409
|
+
}
|
|
1410
|
+
return groups;
|
|
1411
|
+
}
|
|
1412
|
+
/** `server (a, b, +3 more), other (c)`, at most eight servers, then how many more. */
|
|
1413
|
+
function summarise(servers) {
|
|
1414
|
+
const entries = [...servers].slice(0, SUMMARY_SERVERS).map(([server, tools]) => {
|
|
1415
|
+
if (tools.length === 0) return server;
|
|
1416
|
+
const shown = tools.slice(0, SUMMARY_TOOLS_PER_SERVER);
|
|
1417
|
+
const more = tools.length - shown.length;
|
|
1418
|
+
return `${server} (${[...shown, ...more > 0 ? [`+${more} more`] : []].join(", ")})`;
|
|
1419
|
+
});
|
|
1420
|
+
const hidden = servers.size - SUMMARY_SERVERS;
|
|
1421
|
+
return entries.join(", ") + (hidden > 0 ? `, and ${hidden} more servers` : "");
|
|
1422
|
+
}
|
|
1423
|
+
/** The catalogue grouped by namespace, as one line: `github (create_issue, +2 more), slack (post_message)`. */
|
|
1424
|
+
function summariseCatalog(catalog) {
|
|
1425
|
+
return summarise(groupBy(catalog, (tool) => tool.namespace, (tool) => tool.name));
|
|
1426
|
+
}
|
|
1427
|
+
/**
|
|
1428
|
+
* The virtual tool offered to M365 in place of the catalogue. Gentle wording on
|
|
1429
|
+
* purpose: see `buildToolPrompt` on why prompt shape matters more than size.
|
|
1430
|
+
*
|
|
1431
|
+
* The description stays on one line with no sentence break: the tool block shows only
|
|
1432
|
+
* a description's first sentence, and the summary is what tells the model a search is
|
|
1433
|
+
* worth making and which words to use.
|
|
1434
|
+
*/
|
|
1435
|
+
function mcpTool(catalog, partial) {
|
|
1436
|
+
const count = catalog.length;
|
|
1437
|
+
const noun = count === 1 ? "tool" : "tools";
|
|
1438
|
+
const summary = summariseCatalog(catalog) + (partial ? ", and more not listed" : "");
|
|
1439
|
+
return {
|
|
1440
|
+
type: "function",
|
|
1441
|
+
function: {
|
|
1442
|
+
name: "mcp",
|
|
1443
|
+
description: `Use ${count}${partial ? "+" : ""} ${noun} from my MCP servers — ${summary} — by searching with a few words about what you want to do; the result shows how to call each match.`,
|
|
1444
|
+
parameters: {
|
|
1445
|
+
type: "object",
|
|
1446
|
+
properties: {
|
|
1447
|
+
search: {
|
|
1448
|
+
type: "string",
|
|
1449
|
+
description: "A few words describing the tool you need"
|
|
1450
|
+
},
|
|
1451
|
+
call: {
|
|
1452
|
+
type: "string",
|
|
1453
|
+
description: "The path of a tool a search showed you, with its arguments below"
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
}
|
|
1458
|
+
};
|
|
1459
|
+
}
|
|
1460
|
+
/** Lowercase words of two or more characters. */
|
|
1461
|
+
function words(text) {
|
|
1462
|
+
return text.toLowerCase().split(/[^a-z0-9]+/).filter((word) => word.length >= 2);
|
|
1463
|
+
}
|
|
1464
|
+
/** A tool name's words: split on `_`, `-` and camelCase boundaries. */
|
|
1465
|
+
function nameWords(name) {
|
|
1466
|
+
return words(name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2"));
|
|
1467
|
+
}
|
|
1468
|
+
/** Every way a model might write a tool's full name. */
|
|
1469
|
+
function spellings(tool) {
|
|
1470
|
+
return [
|
|
1471
|
+
tool.path,
|
|
1472
|
+
`${tool.namespace}.${tool.name}`,
|
|
1473
|
+
`${tool.namespace}_${tool.name}`,
|
|
1474
|
+
`tools.${tool.namespace}.${tool.name}`
|
|
1475
|
+
].map((spelling) => spelling.toLowerCase());
|
|
1476
|
+
}
|
|
1477
|
+
function isNamespacePrefix(query, namespace) {
|
|
1478
|
+
const ns = namespace.toLowerCase();
|
|
1479
|
+
return [
|
|
1480
|
+
`${ns}_`,
|
|
1481
|
+
`${ns}.`,
|
|
1482
|
+
`tools.${ns}`,
|
|
1483
|
+
`tools.${ns}.`
|
|
1484
|
+
].includes(query);
|
|
1485
|
+
}
|
|
1486
|
+
function scoreTool(query, queryWords, tool) {
|
|
1487
|
+
if (query === tool.name.toLowerCase() || spellings(tool).includes(query)) return EXACT_SCORE;
|
|
1488
|
+
if (isNamespacePrefix(query, tool.namespace)) return EXACT_SCORE;
|
|
1489
|
+
const inName = /* @__PURE__ */ new Set([...nameWords(tool.namespace), ...nameWords(tool.name)]);
|
|
1490
|
+
const inDescription = new Set(words(tool.description));
|
|
1491
|
+
let score = 0;
|
|
1492
|
+
for (const word of queryWords) {
|
|
1493
|
+
if (inName.has(word)) score += NAME_WEIGHT;
|
|
1494
|
+
if (inDescription.has(word)) score += DESCRIPTION_WEIGHT;
|
|
1495
|
+
}
|
|
1496
|
+
return score;
|
|
1497
|
+
}
|
|
1498
|
+
/**
|
|
1499
|
+
* Rank the catalogue against a search. Name (and namespace) hits weigh 3, description
|
|
1500
|
+
* hits 1; an exact name or path, or a namespace prefix, scores top. Tools that score
|
|
1501
|
+
* zero are dropped; ties keep catalogue order.
|
|
1502
|
+
*/
|
|
1503
|
+
function searchCatalog(query, catalog, limit = 5) {
|
|
1504
|
+
const normalised = query.trim().toLowerCase();
|
|
1505
|
+
if (!normalised) return [];
|
|
1506
|
+
const queryWords = [...new Set(words(normalised))];
|
|
1507
|
+
return catalog.map((tool, index) => ({
|
|
1508
|
+
tool,
|
|
1509
|
+
index,
|
|
1510
|
+
score: scoreTool(normalised, queryWords, tool)
|
|
1511
|
+
})).filter((entry) => entry.score > 0).sort((a, b) => b.score - a.score || a.index - b.index).slice(0, Math.max(0, limit)).map((entry) => entry.tool);
|
|
1512
|
+
}
|
|
1513
|
+
/**
|
|
1514
|
+
* The top-level parameter names of a catalogue signature: the keys of its first
|
|
1515
|
+
* argument's object type, outside doc comments and nested types.
|
|
1516
|
+
*/
|
|
1517
|
+
function argumentNames(signature) {
|
|
1518
|
+
const open = signature.indexOf("(");
|
|
1519
|
+
if (open === -1) return [];
|
|
1520
|
+
const names = [];
|
|
1521
|
+
let depth = 0;
|
|
1522
|
+
let inComment = false;
|
|
1523
|
+
let token = "";
|
|
1524
|
+
for (let i = open; i < signature.length; i++) {
|
|
1525
|
+
const char = signature[i];
|
|
1526
|
+
if (inComment) {
|
|
1527
|
+
if (char === "*" && signature[i + 1] === "/") {
|
|
1528
|
+
inComment = false;
|
|
1529
|
+
i++;
|
|
1530
|
+
}
|
|
1531
|
+
continue;
|
|
1532
|
+
}
|
|
1533
|
+
if (char === "/" && signature[i + 1] === "*") {
|
|
1534
|
+
inComment = true;
|
|
1535
|
+
i++;
|
|
1536
|
+
continue;
|
|
1537
|
+
}
|
|
1538
|
+
if ("({[<".includes(char)) {
|
|
1539
|
+
depth++;
|
|
1540
|
+
token = "";
|
|
1541
|
+
} else if (")}]".includes(char) || char === ">" && signature[i - 1] !== "=") {
|
|
1542
|
+
depth--;
|
|
1543
|
+
if (depth === 0) break;
|
|
1544
|
+
token = "";
|
|
1545
|
+
} else if (depth === 2 && (char === ":" || char === "?" && signature[i + 1] === ":")) {
|
|
1546
|
+
const name = token.trim();
|
|
1547
|
+
if (IDENTIFIER.test(name) && !names.includes(name)) names.push(name);
|
|
1548
|
+
token = "";
|
|
1549
|
+
if (char === "?") i++;
|
|
1550
|
+
} else if (depth === 2 && (char === "," || char === "\n")) token = "";
|
|
1551
|
+
else token += char;
|
|
1552
|
+
}
|
|
1553
|
+
return names;
|
|
1554
|
+
}
|
|
1555
|
+
/** The fence that calls a tool, with a placeholder for each of its parameters. */
|
|
1556
|
+
function callExample(tool) {
|
|
1557
|
+
const names = argumentNames(tool.signature);
|
|
1558
|
+
const args = names.length === 0 ? "" : `\n{${names.map((name) => `"${name}": "..."`).join(", ")}}`;
|
|
1559
|
+
return `\`\`\`mcp\ncall: ${tool.path}` + args + "\n```";
|
|
1560
|
+
}
|
|
1561
|
+
/**
|
|
1562
|
+
* The message sent back to M365 with a search's matches. It reads as a tool result:
|
|
1563
|
+
* each match's signature as opencode wrote it, then how to call one.
|
|
1564
|
+
*/
|
|
1565
|
+
function renderSearchResult(query, matches, total) {
|
|
1566
|
+
if (matches.length === 0) return `No tool matched "${query}". Try other words: ${total} tools are available.`;
|
|
1567
|
+
const lines = [
|
|
1568
|
+
`<tool_response tool="mcp">`,
|
|
1569
|
+
`Tools matching "${query}":`,
|
|
1570
|
+
""
|
|
1571
|
+
];
|
|
1572
|
+
for (const tool of matches) lines.push(`- ${tool.signature}`, "");
|
|
1573
|
+
lines.push("To call one, reply with an mcp block: `call:` and its path, then its arguments as a JSON object. For example:", callExample(matches[0]), "</tool_response>");
|
|
1574
|
+
return lines.join("\n");
|
|
1575
|
+
}
|
|
1576
|
+
/** The JSON number grammar: no leading zeros, hex, `+`, bare `.5` or `Infinity`. */
|
|
1577
|
+
const JSON_NUMBER = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
|
|
1578
|
+
/** A header value's own type: a JSON number, boolean or null is coerced; quotes are unwrapped. */
|
|
1579
|
+
function headerValue(raw) {
|
|
1580
|
+
const value = raw.trim();
|
|
1581
|
+
if (/^"(?:[^"\\]|\\.)*"$/.test(value)) try {
|
|
1582
|
+
return JSON.parse(value);
|
|
1583
|
+
} catch {
|
|
1584
|
+
return value.slice(1, -1);
|
|
1585
|
+
}
|
|
1586
|
+
if (/^'.*'$|^`.*`$/.test(value)) return value.slice(1, -1);
|
|
1587
|
+
if (value === "true") return true;
|
|
1588
|
+
if (value === "false") return false;
|
|
1589
|
+
if (value === "null") return null;
|
|
1590
|
+
if (JSON_NUMBER.test(value)) return Number(value);
|
|
1591
|
+
return value;
|
|
1592
|
+
}
|
|
1593
|
+
function isPlainObject$1(value) {
|
|
1594
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1595
|
+
}
|
|
1596
|
+
/** Read a call's arguments: a JSON object, or `key: value` lines. Empty means none. */
|
|
1597
|
+
function parseArguments(body) {
|
|
1598
|
+
const text = body.trim();
|
|
1599
|
+
if (text === "") return { args: {} };
|
|
1600
|
+
if (text.startsWith("{") || text.startsWith("[")) {
|
|
1601
|
+
let value;
|
|
1602
|
+
try {
|
|
1603
|
+
value = JSON.parse(text);
|
|
1604
|
+
} catch {
|
|
1605
|
+
return { invalid: "the arguments are not valid JSON" };
|
|
1606
|
+
}
|
|
1607
|
+
return isPlainObject$1(value) ? { args: value } : { invalid: "the arguments must be a JSON object" };
|
|
1608
|
+
}
|
|
1609
|
+
const args = {};
|
|
1610
|
+
for (const line of text.split("\n")) {
|
|
1611
|
+
if (line.trim() === "") continue;
|
|
1612
|
+
const header = /^\s*([A-Za-z_$][\w$]*)\s*:\s?(.*)$/.exec(line);
|
|
1613
|
+
if (!header) return { invalid: `"${line.trim()}" is neither a JSON object nor a key: value line` };
|
|
1614
|
+
args[header[1]] = headerValue(header[2]);
|
|
1615
|
+
}
|
|
1616
|
+
return { args };
|
|
1617
|
+
}
|
|
1618
|
+
/** A path as written: unwrap quotes and backticks, and split off a JS-style `(args)`. */
|
|
1619
|
+
function splitCallValue(raw) {
|
|
1620
|
+
let value = raw.trim();
|
|
1621
|
+
const wrapped = /^([`'])(.*)\1;?$/.exec(value);
|
|
1622
|
+
if (wrapped) value = wrapped[2].trim();
|
|
1623
|
+
value = value.replace(/;$/, "").trim();
|
|
1624
|
+
const paren = value.indexOf("(");
|
|
1625
|
+
if (paren !== -1 && value.endsWith(")")) return {
|
|
1626
|
+
path: value.slice(0, paren).trim(),
|
|
1627
|
+
inline: value.slice(paren + 1, -1)
|
|
1628
|
+
};
|
|
1629
|
+
return { path: value };
|
|
1630
|
+
}
|
|
1631
|
+
/**
|
|
1632
|
+
* Read an `mcp` block's body: `search: <words>`, or `call: <path>` followed by the
|
|
1633
|
+
* arguments. A body with no header is a search.
|
|
1634
|
+
*/
|
|
1635
|
+
function parseMcpBlock(body) {
|
|
1636
|
+
const lines = body.replace(/\r\n?/g, "\n").split("\n");
|
|
1637
|
+
while (lines.length > 0 && lines[0].trim() === "") lines.shift();
|
|
1638
|
+
if (lines.length === 0) return {
|
|
1639
|
+
kind: "invalid",
|
|
1640
|
+
reason: "the block is empty"
|
|
1641
|
+
};
|
|
1642
|
+
const header = /^\s*(search|call)\s*:\s?(.*)$/i.exec(lines[0]);
|
|
1643
|
+
if (!header) {
|
|
1644
|
+
const text = lines.join("\n").trim();
|
|
1645
|
+
if (text.startsWith("{")) return {
|
|
1646
|
+
kind: "invalid",
|
|
1647
|
+
reason: "the arguments need a `call:` line naming the tool"
|
|
1648
|
+
};
|
|
1649
|
+
return {
|
|
1650
|
+
kind: "search",
|
|
1651
|
+
query: text
|
|
1652
|
+
};
|
|
1653
|
+
}
|
|
1654
|
+
const rest = lines.slice(1).join("\n");
|
|
1655
|
+
if (header[1].toLowerCase() === "search") {
|
|
1656
|
+
const query = [header[2].trim(), rest.trim()].filter(Boolean).join(" ");
|
|
1657
|
+
return query ? {
|
|
1658
|
+
kind: "search",
|
|
1659
|
+
query
|
|
1660
|
+
} : {
|
|
1661
|
+
kind: "invalid",
|
|
1662
|
+
reason: "the search is empty"
|
|
1663
|
+
};
|
|
1664
|
+
}
|
|
1665
|
+
const { path, inline } = splitCallValue(header[2]);
|
|
1666
|
+
if (!path) return {
|
|
1667
|
+
kind: "invalid",
|
|
1668
|
+
reason: "`call:` names no tool"
|
|
1669
|
+
};
|
|
1670
|
+
const parsed = parseArguments(inline !== void 0 && rest.trim() === "" ? inline : rest);
|
|
1671
|
+
if ("invalid" in parsed) return {
|
|
1672
|
+
kind: "invalid",
|
|
1673
|
+
reason: parsed.invalid
|
|
1674
|
+
};
|
|
1675
|
+
return {
|
|
1676
|
+
kind: "call",
|
|
1677
|
+
path,
|
|
1678
|
+
args: parsed.args
|
|
1679
|
+
};
|
|
1680
|
+
}
|
|
1681
|
+
/**
|
|
1682
|
+
* The exact path to call for what the model wrote, or undefined if it may not be
|
|
1683
|
+
* called. A catalogued tool is accepted however the model spelled it; when opencode
|
|
1684
|
+
* says the catalogue is partial, any well-formed `tools` path is too, because opencode's
|
|
1685
|
+
* own search can return tools the catalogue leaves out.
|
|
1686
|
+
*/
|
|
1687
|
+
function resolveCallPath(written, catalog, partial) {
|
|
1688
|
+
const wanted = written.trim().toLowerCase();
|
|
1689
|
+
const known = catalog.find((tool) => spellings(tool).includes(wanted));
|
|
1690
|
+
if (known) return known.path;
|
|
1691
|
+
if (partial && CALL_PATH.test(written.trim())) return written.trim();
|
|
1692
|
+
}
|
|
1693
|
+
/** A complete answer to M365 for a path that is not a tool. */
|
|
1694
|
+
function renderUnknownTool(path) {
|
|
1695
|
+
return [
|
|
1696
|
+
`<tool_response tool="mcp">`,
|
|
1697
|
+
`There is no tool ${path}. Search first, and call a path exactly as the search shows it:`,
|
|
1698
|
+
"```mcp\nsearch: a few words about what you want to do\n```",
|
|
1699
|
+
"</tool_response>"
|
|
1700
|
+
].join("\n");
|
|
1701
|
+
}
|
|
1702
|
+
/** A complete answer to M365 for an `mcp` block it could not read, with the expected shape. */
|
|
1703
|
+
function renderInvalidMcpBlock(reason) {
|
|
1704
|
+
return [
|
|
1705
|
+
`<tool_response tool="mcp">`,
|
|
1706
|
+
`That mcp block could not be read: ${reason}. Search with:`,
|
|
1707
|
+
"```mcp\nsearch: a few words about what you want to do\n```",
|
|
1708
|
+
"or call a tool a search showed you, with its arguments as a JSON object:",
|
|
1709
|
+
"```mcp\ncall: tools.<server>.<tool>\n{\"<argument>\": \"<value>\"}\n```",
|
|
1710
|
+
"</tool_response>"
|
|
1711
|
+
].join("\n");
|
|
1712
|
+
}
|
|
1713
|
+
/** The code opencode's `execute` runs for a call. */
|
|
1714
|
+
function callCode(path, args) {
|
|
1715
|
+
return "return await " + path + "(" + JSON.stringify(args) + ");";
|
|
1716
|
+
}
|
|
1717
|
+
/** The code opencode's `execute` runs for a search of its own (a partial catalogue). */
|
|
1718
|
+
function searchCode(query) {
|
|
1719
|
+
return "return await search(" + JSON.stringify(query) + ");";
|
|
1720
|
+
}
|
|
1721
|
+
const CALL_CODE = /^return await (tools(?:\.[A-Za-z_$][\w$]*|\["[^"\\]+"\])+)\((\{[\s\S]*\})\);$/;
|
|
1722
|
+
const SEARCH_CODE = /^return await search\(("(?:[^"\\]|\\[\s\S])*")\);$/;
|
|
1723
|
+
/**
|
|
1724
|
+
* The inverse of `callCode` and `searchCode`: the `mcp` request an `execute` call's code
|
|
1725
|
+
* came from, or undefined for code the proxy did not write.
|
|
1726
|
+
*/
|
|
1727
|
+
function executeCodeToMcp(code) {
|
|
1728
|
+
if (typeof code !== "string") return void 0;
|
|
1729
|
+
const call = CALL_CODE.exec(code);
|
|
1730
|
+
if (call) {
|
|
1731
|
+
try {
|
|
1732
|
+
const args = JSON.parse(call[2]);
|
|
1733
|
+
if (isPlainObject$1(args) && callCode(call[1], args) === code) return {
|
|
1734
|
+
kind: "call",
|
|
1735
|
+
path: call[1],
|
|
1736
|
+
args
|
|
1737
|
+
};
|
|
1738
|
+
} catch {
|
|
1739
|
+
return;
|
|
1740
|
+
}
|
|
1741
|
+
return;
|
|
1742
|
+
}
|
|
1743
|
+
const search = SEARCH_CODE.exec(code);
|
|
1744
|
+
if (search) try {
|
|
1745
|
+
const query = JSON.parse(search[1]);
|
|
1746
|
+
if (typeof query === "string") return {
|
|
1747
|
+
kind: "search",
|
|
1748
|
+
query
|
|
1749
|
+
};
|
|
1750
|
+
} catch {
|
|
1751
|
+
return;
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
/** Write a request back as the `mcp` fence the model wrote, for history replay. */
|
|
1755
|
+
function renderMcpFence(request) {
|
|
1756
|
+
if (request.kind === "search") return `\`\`\`mcp\nsearch: ${request.query}\n\`\`\``;
|
|
1757
|
+
const args = Object.keys(request.args).length === 0 ? "" : `\n${JSON.stringify(request.args)}`;
|
|
1758
|
+
return `\`\`\`mcp\ncall: ${request.path}` + args + "\n```";
|
|
1759
|
+
}
|
|
1102
1760
|
// node_modules/ws/lib/constants.js
|
|
1103
1761
|
var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
1104
1762
|
const BINARY_TYPES = [
|
|
@@ -10716,12 +11374,15 @@ function condenseSystemPrompt(text, tools, options = {}) {
|
|
|
10716
11374
|
if (requires.some((name) => toolNames.has(name))) continue;
|
|
10717
11375
|
result = result.replace(new RegExp(`<${tag}>[\\s\\S]*?</${tag}>`, "g"), "");
|
|
10718
11376
|
}
|
|
10719
|
-
|
|
10720
|
-
|
|
10721
|
-
|
|
10722
|
-
|
|
10723
|
-
|
|
10724
|
-
|
|
11377
|
+
result = outsideUserRules(result, (harness) => {
|
|
11378
|
+
let text = harness;
|
|
11379
|
+
if (!toolNames.has("execute")) {
|
|
11380
|
+
text = stripCodeModeSection(text);
|
|
11381
|
+
text = dropLines(text, /`execute`/);
|
|
11382
|
+
}
|
|
11383
|
+
if (!toolNames.has("skill")) text = dropLines(text, /^Skills provide |\bskill tool\b|invoke a skill directly/);
|
|
11384
|
+
return dropLines(text, /^- Prefer parallelizing independent tool calls|^- Prefer dedicated tools over shell commands/);
|
|
11385
|
+
});
|
|
10725
11386
|
if (options.replaceProseWith !== void 0) {
|
|
10726
11387
|
const { leadingBlocks, instructions, blocks } = splitSystemPrompt(result);
|
|
10727
11388
|
result = [
|
|
@@ -10733,6 +11394,28 @@ function condenseSystemPrompt(text, tools, options = {}) {
|
|
|
10733
11394
|
}
|
|
10734
11395
|
return result.replace(/\n{3,}/g, "\n\n").trim();
|
|
10735
11396
|
}
|
|
11397
|
+
/**
|
|
11398
|
+
* Apply `trim` to everything except the user's rules files.
|
|
11399
|
+
*
|
|
11400
|
+
* opencode puts each rules file under an `Instructions from: <path>` line, and follows
|
|
11401
|
+
* the last with its own `Today's date:` line and `<env>`. A rules section runs until the
|
|
11402
|
+
* next of those. Rules files are Markdown with blank lines of their own, so a blank
|
|
11403
|
+
* line is not a boundary.
|
|
11404
|
+
*/
|
|
11405
|
+
function outsideUserRules(text, trim) {
|
|
11406
|
+
const out = [];
|
|
11407
|
+
let cursor = 0;
|
|
11408
|
+
for (const start of text.matchAll(/^Instructions from:[ \t]*\S.*$/gm)) {
|
|
11409
|
+
if (start.index < cursor) continue;
|
|
11410
|
+
out.push(trim(text.slice(cursor, start.index)));
|
|
11411
|
+
const after = start.index + start[0].length;
|
|
11412
|
+
const next = text.slice(after).search(/^(?:Instructions from:|Today's date:|<[a-z_]+>)/m);
|
|
11413
|
+
cursor = next === -1 ? text.length : after + next;
|
|
11414
|
+
out.push(text.slice(start.index, cursor));
|
|
11415
|
+
}
|
|
11416
|
+
out.push(trim(text.slice(cursor)));
|
|
11417
|
+
return out.join("");
|
|
11418
|
+
}
|
|
10736
11419
|
/** Remove every line matching `pattern`. */
|
|
10737
11420
|
function dropLines(text, pattern) {
|
|
10738
11421
|
return text.split("\n").filter((line) => !pattern.test(line)).join("\n");
|
|
@@ -10794,9 +11477,14 @@ function buildTurnPrompt(messages, tools, sentMessageCount, options = {}) {
|
|
|
10794
11477
|
const systemText = messages.filter((message) => message.role === "system" || message.role === "developer").map(contentOf).filter(Boolean).join("\n\n");
|
|
10795
11478
|
if (systemText) parts.push(condenseSystemPrompt(systemText, tools, { ...options.leanSystemPrompt !== void 0 ? { replaceProseWith: options.leanSystemPrompt } : {} }));
|
|
10796
11479
|
}
|
|
10797
|
-
if (tools.length > 0) parts.push(buildToolPrompt(tools, {
|
|
11480
|
+
if (tools.length > 0) parts.push(buildToolPrompt(tools, {
|
|
11481
|
+
firstTurn: isFirstTurn,
|
|
11482
|
+
...options.framing ? { framing: options.framing } : {},
|
|
11483
|
+
...options.sandbox ? { sandbox: options.sandbox } : {}
|
|
11484
|
+
}));
|
|
10798
11485
|
const callsById = /* @__PURE__ */ new Map();
|
|
10799
11486
|
for (const message of messages) for (const call of message.tool_calls ?? []) callsById.set(call.id, call.function);
|
|
11487
|
+
if (options.note) parts.push(options.note);
|
|
10800
11488
|
for (const message of messages.slice(sentMessageCount)) {
|
|
10801
11489
|
if (message.role === "system" || message.role === "developer") continue;
|
|
10802
11490
|
if (message.role === "tool") {
|
|
@@ -10806,6 +11494,7 @@ function buildTurnPrompt(messages, tools, sentMessageCount, options = {}) {
|
|
|
10806
11494
|
if (message.role === "assistant") {
|
|
10807
11495
|
const text = contentOf(message);
|
|
10808
11496
|
if (text) parts.push(text);
|
|
11497
|
+
for (const call of message.tool_calls ?? []) parts.push(options.renderCall?.(call.function.name, call.function.arguments) ?? renderToolCall(call.function.name, call.function.arguments, options.historyTools ?? tools));
|
|
10809
11498
|
continue;
|
|
10810
11499
|
}
|
|
10811
11500
|
const text = contentOf(message) || (hasImagePart(message) ? "(See the attached image.)" : "");
|
|
@@ -10825,7 +11514,21 @@ function renderToolResult(message, callsById) {
|
|
|
10825
11514
|
if (call?.name) attributes.push(`tool="${escapeAttribute(call.name)}"`);
|
|
10826
11515
|
const summary = summariseArguments(call?.arguments);
|
|
10827
11516
|
if (summary) attributes.push(`command="${escapeAttribute(summary)}"`);
|
|
10828
|
-
return `${attributes.length > 0 ? `<tool_response ${attributes.join(" ")}>` : "<tool_response>"}\n${contentOf(message)}\n</tool_response>`;
|
|
11517
|
+
return `${attributes.length > 0 ? `<tool_response ${attributes.join(" ")}>` : "<tool_response>"}\n${unwrapToolError(contentOf(message))}\n</tool_response>`;
|
|
11518
|
+
}
|
|
11519
|
+
/**
|
|
11520
|
+
* opencode reports a failed tool as `{"error":{"type":"tool.execution","message":"…"},"content":[]}`,
|
|
11521
|
+
* with the message's newlines escaped. Its messages are good ("Update the arguments
|
|
11522
|
+
* and call the tool again"); the envelope just hides them.
|
|
11523
|
+
*/
|
|
11524
|
+
function unwrapToolError(content) {
|
|
11525
|
+
if (!content.startsWith("{\"error\"")) return content;
|
|
11526
|
+
try {
|
|
11527
|
+
const message = JSON.parse(content)?.error?.message;
|
|
11528
|
+
return typeof message === "string" ? `Error: ${message}` : content;
|
|
11529
|
+
} catch {
|
|
11530
|
+
return content;
|
|
11531
|
+
}
|
|
10829
11532
|
}
|
|
10830
11533
|
/** The most identifying argument value, for the label. */
|
|
10831
11534
|
function summariseArguments(raw) {
|
|
@@ -10843,7 +11546,10 @@ function escapeAttribute(value) {
|
|
|
10843
11546
|
return value.replace(/"/g, """).replace(/\n/g, " ");
|
|
10844
11547
|
}
|
|
10845
11548
|
function buildCompletion(result, options) {
|
|
10846
|
-
const { toolCalls, text } =
|
|
11549
|
+
const { toolCalls, text } = options.toolCalls ? {
|
|
11550
|
+
toolCalls: options.toolCalls,
|
|
11551
|
+
text: ""
|
|
11552
|
+
} : parseToolCalls(result.text, options.tools, { allowMultiple: options.allowMultiple ?? false });
|
|
10847
11553
|
const hasCalls = toolCalls.length > 0;
|
|
10848
11554
|
return {
|
|
10849
11555
|
id: `chatcmpl-${randomUUID()}`,
|
|
@@ -10973,7 +11679,8 @@ function looksLikeGiveUp(reply) {
|
|
|
10973
11679
|
* Disengaged filter. Once tools have run it must not say nothing has — a prompt that
|
|
10974
11680
|
* contradicts the transcript is one the model stops trusting.
|
|
10975
11681
|
*/
|
|
10976
|
-
function nudgeFor(midTask) {
|
|
11682
|
+
function nudgeFor(midTask, framing = "default") {
|
|
11683
|
+
if (framing === "relay") return midTask ? "I ran each block you sent on my machine, and the output is above. What should I run next? Send it in one block and I'll run it." : "My project is right here on my machine. Send me the first command in one block and I'll run it and paste the output back.";
|
|
10977
11684
|
return midTask ? "Your earlier tool blocks really ran on this machine, and their results are in this conversation. Please continue with one tool block for the next step." : "The files are on this machine, and the tools listed earlier run here for you when you write a tool block. Please take the first step now with one tool block.";
|
|
10978
11685
|
}
|
|
10979
11686
|
// src/server.ts
|
|
@@ -11018,6 +11725,14 @@ const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
|
|
|
11018
11725
|
function generateApiKey() {
|
|
11019
11726
|
return randomBytes(32).toString("base64url");
|
|
11020
11727
|
}
|
|
11728
|
+
/**
|
|
11729
|
+
* `mcp` blocks the proxy answers itself per request — searches, unknown paths and
|
|
11730
|
+
* unreadable blocks — before the reply goes back to the client as it is.
|
|
11731
|
+
*/
|
|
11732
|
+
const MAX_MCP_SEARCHES = 3;
|
|
11733
|
+
/** opencode 2's tool that runs Code Mode JavaScript: the proxy emits it, M365 never sees it. */
|
|
11734
|
+
const EXECUTE_TOOL_NAME = "execute";
|
|
11735
|
+
const isExecute = (tool) => tool.function.name.toLowerCase() === EXECUTE_TOOL_NAME;
|
|
11021
11736
|
async function startServer(deps) {
|
|
11022
11737
|
const pool = new ConversationPool();
|
|
11023
11738
|
const host = deps.host ?? "127.0.0.1";
|
|
@@ -11147,15 +11862,18 @@ async function handleChatCompletion(request, response, context) {
|
|
|
11147
11862
|
}
|
|
11148
11863
|
const model = resolveModel(body.model);
|
|
11149
11864
|
const requested = body.tools ?? [];
|
|
11150
|
-
const
|
|
11151
|
-
if (
|
|
11152
|
-
log.info(`trimmed toolset ${requested.length} -> ${
|
|
11865
|
+
const kept = context.deps.lean !== false ? selectLeanTools(requested) : requested;
|
|
11866
|
+
if (kept.length !== requested.length) {
|
|
11867
|
+
log.info(`trimmed toolset ${requested.length} -> ${kept.length}`, kept.map((t) => t.function.name).join(","));
|
|
11153
11868
|
const concern = describeToolSelection(requested);
|
|
11154
11869
|
if (concern && !warnedAboutToolSelection) {
|
|
11155
11870
|
warnedAboutToolSelection = true;
|
|
11156
11871
|
log.warn(concern);
|
|
11157
11872
|
}
|
|
11158
11873
|
}
|
|
11874
|
+
const catalog = context.deps.mcpProxy === true ? mcpCatalogFor(body, requested) : void 0;
|
|
11875
|
+
const tools = catalog ? [...kept.filter((tool) => !isExecute(tool)), mcpTool(catalog.tools, catalog.partial)] : kept;
|
|
11876
|
+
if (catalog) log.info(`offering mcp over ${catalog.tools.length}${catalog.partial ? "+" : ""} Code Mode tools`, catalog.tools.map((tool) => tool.path).join(","));
|
|
11159
11877
|
if (isLocalModel(model.id) || request.headers["x-m365-request-kind"] === "title") {
|
|
11160
11878
|
respondWithTitle(response, body, model.id);
|
|
11161
11879
|
return;
|
|
@@ -11169,7 +11887,7 @@ async function handleChatCompletion(request, response, context) {
|
|
|
11169
11887
|
conversation.turn = previous.then(() => current);
|
|
11170
11888
|
await previous;
|
|
11171
11889
|
try {
|
|
11172
|
-
await runTurn(request, response, context, body, conversation, model, tools);
|
|
11890
|
+
await runTurn(request, response, context, body, conversation, model, tools, catalog, requested);
|
|
11173
11891
|
} finally {
|
|
11174
11892
|
release();
|
|
11175
11893
|
}
|
|
@@ -11184,16 +11902,29 @@ function defaultTurnLog() {
|
|
|
11184
11902
|
}
|
|
11185
11903
|
return envTurnLog;
|
|
11186
11904
|
}
|
|
11187
|
-
async function runTurn(request, response, context, body, conversation, model, tools) {
|
|
11905
|
+
async function runTurn(request, response, context, body, conversation, model, tools, catalog, requested = tools) {
|
|
11188
11906
|
if (body.messages.length < conversation.sentMessageCount) conversation.sentMessageCount = 0;
|
|
11189
11907
|
conversation.session ??= new CopilotSession({
|
|
11190
11908
|
getToken: context.deps.getToken,
|
|
11191
11909
|
...context.deps.endpoint ? { endpoint: context.deps.endpoint } : {}
|
|
11192
11910
|
});
|
|
11193
11911
|
const effectiveTools = model.grounded ? [] : tools;
|
|
11912
|
+
const mcp = model.grounded ? void 0 : catalog;
|
|
11913
|
+
const clientTools = mcp ? effectiveTools.filter((tool) => tool.function.name !== "mcp") : effectiveTools;
|
|
11914
|
+
const executeName = requested.find(isExecute)?.function.name ?? EXECUTE_TOOL_NAME;
|
|
11194
11915
|
const images = collectImages(body.messages, conversation.sentMessageCount);
|
|
11195
|
-
const
|
|
11196
|
-
|
|
11916
|
+
const note = effectiveTools.length > 0 && conversation.sentMessageCount > 0 ? conversation.note : void 0;
|
|
11917
|
+
conversation.note = void 0;
|
|
11918
|
+
const route = toolRouteFor(model.tone);
|
|
11919
|
+
const prompt = buildTurnPrompt(mcp ? relabelProxyCalls(body.messages) : body.messages, effectiveTools, conversation.sentMessageCount, {
|
|
11920
|
+
framing: route.framing,
|
|
11921
|
+
...route.sandbox ? { sandbox: route.sandbox } : {},
|
|
11922
|
+
...context.deps.leanSystemPrompt !== void 0 ? { leanSystemPrompt: context.deps.leanSystemPrompt } : {},
|
|
11923
|
+
...note ? { note } : {},
|
|
11924
|
+
...effectiveTools.length > 0 ? { historyTools: [...effectiveTools, ...requested] } : {},
|
|
11925
|
+
...mcp ? { renderCall: renderProxyCall } : {}
|
|
11926
|
+
});
|
|
11927
|
+
const agent = effectiveTools.length > 0 && route.agent ? await context.agentId() : null;
|
|
11197
11928
|
const abort = new AbortController();
|
|
11198
11929
|
request.on("close", () => {
|
|
11199
11930
|
if (!response.writableEnded) abort.abort();
|
|
@@ -11208,6 +11939,7 @@ async function runTurn(request, response, context, body, conversation, model, to
|
|
|
11208
11939
|
model: model.id,
|
|
11209
11940
|
tone: model.tone,
|
|
11210
11941
|
agent: Boolean(agent),
|
|
11942
|
+
...effectiveTools.length > 0 ? { framing: route.framing } : {},
|
|
11211
11943
|
tools: effectiveTools.map((tool) => tool.function.name),
|
|
11212
11944
|
...fields
|
|
11213
11945
|
});
|
|
@@ -11227,6 +11959,7 @@ async function runTurn(request, response, context, body, conversation, model, to
|
|
|
11227
11959
|
...result.resultValue ? { resultValue: result.resultValue } : {},
|
|
11228
11960
|
...extra
|
|
11229
11961
|
});
|
|
11962
|
+
let logged = {};
|
|
11230
11963
|
try {
|
|
11231
11964
|
let result = await conversation.session.run(prompt, {
|
|
11232
11965
|
...turnOptions,
|
|
@@ -11236,27 +11969,157 @@ async function runTurn(request, response, context, body, conversation, model, to
|
|
|
11236
11969
|
if (effectiveTools.length > 0 && parseToolCalls(result.text, effectiveTools).toolCalls.length === 0 && looksLikeGiveUp(result.text)) {
|
|
11237
11970
|
recordTurn(result);
|
|
11238
11971
|
const midTask = body.messages.some((message) => message.role === "tool");
|
|
11239
|
-
result = await conversation.session.run(nudgeFor(midTask), turnOptions);
|
|
11240
|
-
|
|
11241
|
-
}
|
|
11972
|
+
result = await conversation.session.run(nudgeFor(midTask, route.framing), turnOptions);
|
|
11973
|
+
logged = { nudged: true };
|
|
11974
|
+
}
|
|
11975
|
+
let proxyCall;
|
|
11976
|
+
for (let answered = 0; mcp;) {
|
|
11977
|
+
if (parseToolCalls(result.text, effectiveTools).toolCalls[0]?.name !== "mcp") break;
|
|
11978
|
+
const ask = parseMcpBlock(firstFenceBody(result.text, "mcp") ?? "");
|
|
11979
|
+
let answer;
|
|
11980
|
+
let next = {};
|
|
11981
|
+
if (ask.kind === "call") {
|
|
11982
|
+
const path = resolveCallPath(ask.path, mcp.tools, mcp.partial);
|
|
11983
|
+
if (path) {
|
|
11984
|
+
proxyCall = {
|
|
11985
|
+
name: executeName,
|
|
11986
|
+
arguments: { code: callCode(path, ask.args) }
|
|
11987
|
+
};
|
|
11988
|
+
logged = {
|
|
11989
|
+
...logged,
|
|
11990
|
+
mcpCall: path
|
|
11991
|
+
};
|
|
11992
|
+
break;
|
|
11993
|
+
}
|
|
11994
|
+
answer = renderUnknownTool(ask.path);
|
|
11995
|
+
} else if (ask.kind === "search") {
|
|
11996
|
+
const matches = searchCatalog(ask.query, mcp.tools);
|
|
11997
|
+
if (matches.length === 0 && mcp.partial) {
|
|
11998
|
+
proxyCall = {
|
|
11999
|
+
name: executeName,
|
|
12000
|
+
arguments: { code: searchCode(ask.query) }
|
|
12001
|
+
};
|
|
12002
|
+
logged = {
|
|
12003
|
+
...logged,
|
|
12004
|
+
mcpCall: "search"
|
|
12005
|
+
};
|
|
12006
|
+
break;
|
|
12007
|
+
}
|
|
12008
|
+
answer = renderSearchResult(ask.query, matches, mcp.tools.length);
|
|
12009
|
+
next = { mcpSearch: ask.query };
|
|
12010
|
+
} else answer = renderInvalidMcpBlock(ask.reason);
|
|
12011
|
+
if (answered >= 3) break;
|
|
12012
|
+
answered += 1;
|
|
12013
|
+
recordTurn(result, logged);
|
|
12014
|
+
result = await conversation.session.run(answer, turnOptions);
|
|
12015
|
+
logged = next;
|
|
12016
|
+
}
|
|
12017
|
+
recordTurn(result, logged);
|
|
12018
|
+
if (mcp && !proxyCall) result = {
|
|
12019
|
+
...result,
|
|
12020
|
+
text: stripMcpCalls(result.text)
|
|
12021
|
+
};
|
|
11242
12022
|
conversation.sentMessageCount = body.messages.length + 1;
|
|
12023
|
+
const allowMultiple = context.deps.allowMultiTool ?? false;
|
|
12024
|
+
const parsed = proxyCall ? {
|
|
12025
|
+
toolCalls: [proxyCall],
|
|
12026
|
+
text: "",
|
|
12027
|
+
skippedCalls: 0,
|
|
12028
|
+
inventedResult: false
|
|
12029
|
+
} : parseToolCalls(result.text, clientTools, { allowMultiple });
|
|
12030
|
+
conversation.note = noteAbout(parsed);
|
|
11243
12031
|
if (!streaming) {
|
|
11244
12032
|
sendJson(response, 200, buildCompletion(result, {
|
|
11245
12033
|
model: model.id,
|
|
11246
|
-
tools:
|
|
11247
|
-
allowMultiple
|
|
12034
|
+
tools: clientTools,
|
|
12035
|
+
allowMultiple,
|
|
12036
|
+
...proxyCall ? { toolCalls: [proxyCall] } : {}
|
|
11248
12037
|
}));
|
|
11249
12038
|
return;
|
|
11250
12039
|
}
|
|
11251
|
-
finishStream(response, streamId, model.id,
|
|
12040
|
+
finishStream(response, streamId, model.id, parsed, canStreamText);
|
|
11252
12041
|
} catch (error) {
|
|
11253
12042
|
logTurn({ error: error instanceof Error ? `${error.name}: ${error.message}` : String(error) });
|
|
12043
|
+
if (error instanceof DisengagedError) {
|
|
12044
|
+
conversation.session.reset();
|
|
12045
|
+
conversation.sentMessageCount = 0;
|
|
12046
|
+
}
|
|
11254
12047
|
handleTurnFailure(response, error, streaming, effectiveTools.length);
|
|
11255
12048
|
}
|
|
11256
12049
|
}
|
|
12050
|
+
/**
|
|
12051
|
+
* One line for the next turn when the last reply was not run as written. Without
|
|
12052
|
+
* it the model assumes every block it wrote ran, and the reference project measured
|
|
12053
|
+
* early "task already complete" endings falling from 9 in 56 runs to 0 in 70 once
|
|
12054
|
+
* it was told.
|
|
12055
|
+
*/
|
|
12056
|
+
function noteAbout(parsed) {
|
|
12057
|
+
const first = parsed.toolCalls[0];
|
|
12058
|
+
if (!first) return void 0;
|
|
12059
|
+
const lines = [];
|
|
12060
|
+
if (parsed.skippedCalls > 0) {
|
|
12061
|
+
const others = parsed.skippedCalls === 1 ? "1 other" : `${parsed.skippedCalls} others`;
|
|
12062
|
+
lines.push(`Only the first tool call in your last reply (${first.name}) ran; the ${others} did not run. Send any that are still needed, one per reply.`);
|
|
12063
|
+
}
|
|
12064
|
+
if (parsed.inventedResult) lines.push("The result you predicted after your call was set aside; the real one is below.");
|
|
12065
|
+
return lines.length > 0 ? lines.join(" ") : void 0;
|
|
12066
|
+
}
|
|
12067
|
+
/**
|
|
12068
|
+
* Drop every `mcp` block from a reply. Past the search cap the client gets the
|
|
12069
|
+
* reply's prose (and any real call in it), never a call to the proxy's own tool.
|
|
12070
|
+
*/
|
|
12071
|
+
function stripMcpCalls(text) {
|
|
12072
|
+
const stripped = text.replace(MCP_FENCE, "");
|
|
12073
|
+
return stripped === text ? text : stripped.replace(/\n{3,}/g, "\n\n").trim();
|
|
12074
|
+
}
|
|
12075
|
+
const MCP_FENCE = /^[ \t]*(`{3,}|~{3,})[ \t]*mcp(?![\w-])[^\n]*\n[\s\S]*?^[ \t]*\1[ \t]*$\n?/gim;
|
|
12076
|
+
/**
|
|
12077
|
+
* opencode 2's Code Mode catalogue for a request, when the proxy should stand in for
|
|
12078
|
+
* it: the system prompt carries one, and the request offers `execute` to run calls.
|
|
12079
|
+
*/
|
|
12080
|
+
function mcpCatalogFor(body, requested) {
|
|
12081
|
+
if (!requested.some(isExecute)) return void 0;
|
|
12082
|
+
const catalog = parseCodeModeCatalog(body.messages.filter((message) => message.role === "system" || message.role === "developer").map(contentOf).join("\n\n"));
|
|
12083
|
+
return catalog && (catalog.tools.length > 0 || catalog.partial) ? catalog : void 0;
|
|
12084
|
+
}
|
|
12085
|
+
/** The code of an `execute` call's raw arguments, if it has one. */
|
|
12086
|
+
function executeCode(rawArguments) {
|
|
12087
|
+
try {
|
|
12088
|
+
const code = JSON.parse(rawArguments || "{}")?.code;
|
|
12089
|
+
return typeof code === "string" ? code : void 0;
|
|
12090
|
+
} catch {
|
|
12091
|
+
return;
|
|
12092
|
+
}
|
|
12093
|
+
}
|
|
12094
|
+
/**
|
|
12095
|
+
* Name the proxy's own `execute` calls `mcp` in the history, so they replay as the
|
|
12096
|
+
* `mcp` blocks the model wrote and their results are labelled as the `mcp` tool's.
|
|
12097
|
+
* Any other `execute` call is left as it is.
|
|
12098
|
+
*/
|
|
12099
|
+
function relabelProxyCalls(messages) {
|
|
12100
|
+
return messages.map((message) => {
|
|
12101
|
+
if (!message.tool_calls?.some((call) => call.function.name.toLowerCase() === EXECUTE_TOOL_NAME)) return message;
|
|
12102
|
+
return {
|
|
12103
|
+
...message,
|
|
12104
|
+
tool_calls: message.tool_calls.map((call) => call.function.name.toLowerCase() === EXECUTE_TOOL_NAME && executeCodeToMcp(executeCode(call.function.arguments)) ? {
|
|
12105
|
+
...call,
|
|
12106
|
+
function: {
|
|
12107
|
+
...call.function,
|
|
12108
|
+
name: "mcp"
|
|
12109
|
+
}
|
|
12110
|
+
} : call)
|
|
12111
|
+
};
|
|
12112
|
+
});
|
|
12113
|
+
}
|
|
12114
|
+
/** A relabelled call, written back as its `mcp` block. */
|
|
12115
|
+
function renderProxyCall(name, rawArguments) {
|
|
12116
|
+
if (name !== "mcp") return void 0;
|
|
12117
|
+
const request = executeCodeToMcp(executeCode(rawArguments));
|
|
12118
|
+
return request ? renderMcpFence(request) : void 0;
|
|
12119
|
+
}
|
|
11257
12120
|
/** Emit the closing frames of a streamed turn. */
|
|
11258
|
-
function finishStream(response, streamId, model,
|
|
11259
|
-
const { toolCalls, text } =
|
|
12121
|
+
function finishStream(response, streamId, model, parsed, alreadyStreamedText) {
|
|
12122
|
+
const { toolCalls, text } = parsed;
|
|
11260
12123
|
if (toolCalls.length > 0) {
|
|
11261
12124
|
response.write(streamChunk(streamId, model, { toolCalls: toolCalls.map(toOpenAiToolCall) }));
|
|
11262
12125
|
response.write(streamChunk(streamId, model, { finishReason: "tool_calls" }));
|
|
@@ -11275,20 +12138,19 @@ function handleTurnFailure(response, error, streaming, toolCount) {
|
|
|
11275
12138
|
return;
|
|
11276
12139
|
}
|
|
11277
12140
|
if (error instanceof DisengagedError) {
|
|
11278
|
-
|
|
11279
|
-
finishWithError(response, streaming, NON_RETRYABLE, "m365_disengaged", `M365 Copilot disengaged.${hint}`);
|
|
12141
|
+
refuse(response, streaming, "m365_disengaged", `M365 Copilot disengaged.${toolCount >= 12 ? ` The request carried ${toolCount} tools; M365 disengages persistently above roughly 12. Reduce the toolset — see the lean profile in the opencode plugin.` : " M365 refused to engage with this prompt. The next request starts a fresh conversation with the whole history; if that disengages too, reduce the toolset or simplify the prompt."}`);
|
|
11280
12142
|
return;
|
|
11281
12143
|
}
|
|
11282
12144
|
if (error instanceof M365ThrottledError) {
|
|
11283
|
-
|
|
12145
|
+
refuse(response, streaming, "m365_throttled", error.message);
|
|
11284
12146
|
return;
|
|
11285
12147
|
}
|
|
11286
12148
|
if (error instanceof M365UnavailableError) {
|
|
11287
|
-
|
|
12149
|
+
refuse(response, streaming, "m365_not_served", error.message);
|
|
11288
12150
|
return;
|
|
11289
12151
|
}
|
|
11290
12152
|
if (error instanceof TurnRejectedError) {
|
|
11291
|
-
|
|
12153
|
+
refuse(response, streaming, "m365_turn_rejected", error.message);
|
|
11292
12154
|
return;
|
|
11293
12155
|
}
|
|
11294
12156
|
const message = error instanceof Error ? error.message : String(error);
|
|
@@ -11298,17 +12160,35 @@ function handleTurnFailure(response, error, streaming, toolCount) {
|
|
|
11298
12160
|
}
|
|
11299
12161
|
finishWithError(response, streaming, 502, "upstream_error", message);
|
|
11300
12162
|
}
|
|
12163
|
+
/**
|
|
12164
|
+
* Report an M365 refusal so that opencode does not retry it.
|
|
12165
|
+
*
|
|
12166
|
+
* opencode streams, so the refusal reaches it inside a stream that already answered
|
|
12167
|
+
* 200, and it decides from the body alone (measured against 2.2.5's classifier, see
|
|
12168
|
+
* test/opencode-retry.ts). It retries a code containing "unavailable", a message
|
|
12169
|
+
* saying "try again" — which M365's own refusals do — and any mention of a rate
|
|
12170
|
+
* limit. Type `invalid_request_error` switches off the "try again" rule; the rate
|
|
12171
|
+
* limit wording is reworded, since that rule ignores the type.
|
|
12172
|
+
*/
|
|
12173
|
+
function refuse(response, streaming, code, message) {
|
|
12174
|
+
const reworded = message.replace(/rate increased too quickly/gi, "sent too fast").replace(/rate[-_\s]?limit/gi, "throttle").replace(/too[_\s]?many[_\s]?requests/gi, "too many turns");
|
|
12175
|
+
finishWithError(response, streaming, NON_RETRYABLE, code, reworded, "invalid_request_error");
|
|
12176
|
+
}
|
|
11301
12177
|
/** Report an error, in whichever shape the client is already reading. */
|
|
11302
|
-
function finishWithError(response, streaming, status, code, message) {
|
|
12178
|
+
function finishWithError(response, streaming, status, code, message, type = code) {
|
|
11303
12179
|
if (!streaming) {
|
|
11304
|
-
|
|
12180
|
+
if (!response.writableEnded) sendJson(response, status, { error: {
|
|
12181
|
+
message,
|
|
12182
|
+
type,
|
|
12183
|
+
code
|
|
12184
|
+
} });
|
|
11305
12185
|
return;
|
|
11306
12186
|
}
|
|
11307
12187
|
if (!response.writableEnded) {
|
|
11308
12188
|
response.write(`data: ${JSON.stringify({ error: {
|
|
11309
12189
|
message,
|
|
11310
12190
|
code,
|
|
11311
|
-
type
|
|
12191
|
+
type
|
|
11312
12192
|
} })}\n\n`);
|
|
11313
12193
|
response.write(streamDone());
|
|
11314
12194
|
response.end();
|
|
@@ -11373,4 +12253,4 @@ async function readBody(request, limit) {
|
|
|
11373
12253
|
}
|
|
11374
12254
|
return Buffer.concat(chunks).toString("utf8");
|
|
11375
12255
|
}
|
|
11376
|
-
export {
|
|
12256
|
+
export { buildModelInfos as A, __toESM as B, writePrivateFile as C, SECRETS_FILE as D, CONFIG_DIR as E, LOCAL_TITLE_MODEL as F, MODELS as I, isLocalModel as L, mergeOpencodeConfig as M, resolveOptions as N, PLUGIN_ID as O, DEFAULT_MODEL as P, __commonJSMin as R, ensurePrivateDir as S, CACHE_FILE as T, SYDNEY_SCOPES as _, generateApiKey as a, createTokenClient as b, stripMcpCalls as c, CopilotSession as d, AUTHORITY as f, REDIRECT_URI as g, POWERPLATFORM_SCOPE as h, SESSION_ID_HEADER as i, buildProviderInfo as j, PROVIDER_ID as k, object as l, CLIENT_ID as m, DEFAULT_MAX_BODY_BYTES as n, noteAbout as o, BAP_SCOPE as p, MAX_MCP_SEARCHES as r, startServer as s, AUX_REQUEST_KIND_HEADER as t, string as u, authCodeFromUrl as v, AGENT_FILE as w, createLogger as x, createCachePlugin as y, __require as z };
|