opencode-m365-copilot 2.1.2 → 2.2.1
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 +118 -20
- package/dist/{agent-DDZ4B7E6.mjs → agent-D3anZnuv.mjs} +110 -57
- package/dist/cli.mjs +38 -6
- package/dist/{dist-CN4xwvMF.mjs → dist-CsSmycf9.mjs} +1 -1
- package/dist/{login-DAXgPgtX.mjs → login-Dgv1sbgr.mjs} +2 -2
- package/dist/plugin.mjs +2 -2
- package/dist/{server-Dhpnsh1N.mjs → server-MqggZMCR.mjs} +468 -80
- package/dist/server.d.mts +63 -7
- package/dist/server.mjs +1 -1
- package/package.json +1 -1
|
@@ -52,13 +52,12 @@ const LOCAL_TITLE_MODEL = "local-title";
|
|
|
52
52
|
/**
|
|
53
53
|
* Default when a request carries no model.
|
|
54
54
|
*
|
|
55
|
-
*
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
* note predates the GPT-5.5 measurements. See README for the full story.
|
|
55
|
+
* A chat tone, because a coding backend has to call tools. Measured on a live tenant
|
|
56
|
+
* (2026-11-09): `quick` made real tool calls 4/4, while `gpt-5.5-think-deeper` claimed
|
|
57
|
+
* to have no tools 3/3 — matching `m365-copilot-api.md` quirk #13, and contradicting
|
|
58
|
+
* the 100% that project's README reports for it.
|
|
60
59
|
*/
|
|
61
|
-
const DEFAULT_MODEL = "
|
|
60
|
+
const DEFAULT_MODEL = "quick";
|
|
62
61
|
const MODELS = [
|
|
63
62
|
m("work", "Ask your mail, Teams & files", "magic", false, true),
|
|
64
63
|
m("work-think", "Ask your mail, Teams & files (Think Deeper)", "Gpt_5_5_Reasoning", true, true),
|
|
@@ -68,19 +67,21 @@ const MODELS = [
|
|
|
68
67
|
m("gpt-5.5-quick", "GPT-5.5 (Quick)", "Gpt_5_5_Chat", false),
|
|
69
68
|
m("m365-copilot", "M365 Copilot (Auto)", "magic", false),
|
|
70
69
|
m("auto", "M365 Copilot (Auto)", "magic", false),
|
|
71
|
-
m("quick", "GPT (Quick)", "
|
|
72
|
-
m("think-deeper", "GPT (Think Deeper)", "
|
|
70
|
+
m("quick", "GPT (Quick)", "Gpt_5_5_Chat", false),
|
|
71
|
+
m("think-deeper", "GPT (Think Deeper)", "Gpt_5_5_Reasoning", true),
|
|
72
|
+
m("gpt-5.6", "GPT-5.6 (unreliable tool calls)", "Gpt_5_6_Chat", false),
|
|
73
|
+
m("gpt-5.6-quick", "GPT-5.6 (Quick, unreliable tool calls)", "Gpt_5_6_Chat", false),
|
|
73
74
|
m("claude-sonnet", "Claude Sonnet (via M365)", "Claude_Sonnet", false),
|
|
74
75
|
m("claude", "Claude Sonnet (via M365)", "Claude_Sonnet", false),
|
|
75
76
|
m("claude-sonnet-think-deeper", "Claude Sonnet (Think Deeper)", "Claude_Sonnet_Reasoning", true),
|
|
76
77
|
m("gpt-5.4", "GPT-5.4 (Think Deeper)", "Gpt_5_4_Reasoning", true),
|
|
77
78
|
m("gpt-5.4-think-deeper", "GPT-5.4 (Think Deeper)", "Gpt_5_4_Reasoning", true),
|
|
78
|
-
m("gpt-5.4-quick", "GPT-5.4 (Quick)", "
|
|
79
|
-
m("gpt-5.3", "GPT-5.3 (Quick)", "
|
|
80
|
-
m("gpt-5.3-quick", "GPT-5.3 (Quick)", "
|
|
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
|
+
m("gpt-5.3-quick", "GPT-5.3 (Quick)", "Gpt_5_3_Chat", false),
|
|
81
82
|
m("gpt-5.3-think-deeper", "GPT-5.3 (Think Deeper)", "Gpt_5_3_Reasoning", true),
|
|
82
|
-
m("gpt-5.2", "GPT-5.2 (Quick)", "
|
|
83
|
-
m("gpt-5.2-quick", "GPT-5.2 (Quick)", "
|
|
83
|
+
m("gpt-5.2", "GPT-5.2 (Quick)", "Gpt_5_2_Chat", false),
|
|
84
|
+
m("gpt-5.2-quick", "GPT-5.2 (Quick)", "Gpt_5_2_Chat", false),
|
|
84
85
|
m("gpt-5.2-think-deeper", "GPT-5.2 (Think Deeper)", "Gpt_5_2_Reasoning", true),
|
|
85
86
|
m(LOCAL_TITLE_MODEL, "Local titler (no M365 call)", null, false)
|
|
86
87
|
];
|
|
@@ -131,6 +132,29 @@ function isLocalModel(id) {
|
|
|
131
132
|
function listModelIds() {
|
|
132
133
|
return MODELS.map((model) => model.id);
|
|
133
134
|
}
|
|
135
|
+
/**
|
|
136
|
+
* - Reasoning GPT tones keep the agent (agent-less GPT-5.x made no tool calls in the
|
|
137
|
+
* reference project, 0/4), but under the default framing they say they cannot reach
|
|
138
|
+
* the workspace, even after a command succeeded. The reference project's `relay`
|
|
139
|
+
* framing, where the user asks to be guided through their own terminal, took that to
|
|
140
|
+
* 30/30. Ours said it on the first reply in 8 of 8 runs.
|
|
141
|
+
* - Chat GPT tones work as they are.
|
|
142
|
+
* - Claude stays as it was: with the agent, which M365 answers on GPT. The reference
|
|
143
|
+
* project ran Claude without the agent and with `relay` (193/200), but without the
|
|
144
|
+
* agent an account with no Claude licence refuses every tool turn
|
|
145
|
+
* (`ClaudeUnavailableForLicense`), where today it quietly gets GPT. Unmeasured on a
|
|
146
|
+
* licensed account, so not adopted.
|
|
147
|
+
*/
|
|
148
|
+
function toolRouteFor(tone) {
|
|
149
|
+
if (tone?.startsWith("Gpt_") && tone.endsWith("_Reasoning")) return {
|
|
150
|
+
framing: "relay",
|
|
151
|
+
agent: true
|
|
152
|
+
};
|
|
153
|
+
return {
|
|
154
|
+
framing: "default",
|
|
155
|
+
agent: true
|
|
156
|
+
};
|
|
157
|
+
}
|
|
134
158
|
// src/fenced.ts
|
|
135
159
|
/** Info strings we accept as "this is a shell block", beyond the tool's own name. */
|
|
136
160
|
const SHELL_FENCE_INFOS = /* @__PURE__ */ new Set([
|
|
@@ -195,9 +219,17 @@ const EDIT_PARAM_PAIRS = [
|
|
|
195
219
|
const SEARCH_MARKER = "<<<<<<< SEARCH";
|
|
196
220
|
const DIVIDER_MARKER = "=======";
|
|
197
221
|
const REPLACE_MARKER = ">>>>>>> REPLACE";
|
|
198
|
-
/**
|
|
222
|
+
/**
|
|
223
|
+
* The shell tool in this toolset, whatever the harness named it.
|
|
224
|
+
*
|
|
225
|
+
* Chosen by name priority, not the harness's order: opencode 2 offers both `shell`
|
|
226
|
+
* and `execute`, and its `execute` runs JavaScript.
|
|
227
|
+
*/
|
|
199
228
|
function findShellTool(tools) {
|
|
200
|
-
|
|
229
|
+
for (const name of SHELL_TOOL_NAMES) {
|
|
230
|
+
const match = tools.find((tool) => tool.function.name.toLowerCase() === name);
|
|
231
|
+
if (match) return match;
|
|
232
|
+
}
|
|
201
233
|
}
|
|
202
234
|
/**
|
|
203
235
|
* Decide how a tool's arguments map onto the fence.
|
|
@@ -237,33 +269,52 @@ function shapeOf(tool) {
|
|
|
237
269
|
function buildToolPrompt(tools, options = {}) {
|
|
238
270
|
if (tools.length === 0) return "";
|
|
239
271
|
const shell = findShellTool(tools);
|
|
272
|
+
if (options.framing === "relay") return buildRelayPrompt(tools, shell, options.sandbox);
|
|
240
273
|
const useShellFraming = options.shellFraming ?? Boolean(shell);
|
|
241
274
|
const lines = [];
|
|
242
275
|
lines.push("<tools>");
|
|
243
276
|
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.");
|
|
244
277
|
lines.push("");
|
|
245
|
-
for (const tool of tools)
|
|
246
|
-
const shape = shapeOf(tool);
|
|
247
|
-
const description = tool.function.description?.trim();
|
|
248
|
-
if (description) lines.push(`${tool.function.name} — ${firstSentence(description)}`);
|
|
249
|
-
lines.push("```" + tool.function.name);
|
|
250
|
-
for (const header of shape.headers) lines.push(`${header}: ${placeholderFor(header, shape.tool)}`);
|
|
251
|
-
if (shape.editPair) {
|
|
252
|
-
lines.push(SEARCH_MARKER);
|
|
253
|
-
lines.push("the exact existing text");
|
|
254
|
-
lines.push(DIVIDER_MARKER);
|
|
255
|
-
lines.push("the replacement text");
|
|
256
|
-
lines.push(REPLACE_MARKER);
|
|
257
|
-
} else if (shape.bodyParam) lines.push(`<${shape.bodyParam}>`);
|
|
258
|
-
lines.push("```");
|
|
259
|
-
lines.push("");
|
|
260
|
-
}
|
|
278
|
+
for (const tool of tools) lines.push(...describeTool(tool), "");
|
|
261
279
|
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.`);
|
|
262
|
-
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.");
|
|
263
|
-
lines.push("
|
|
280
|
+
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.");
|
|
281
|
+
else lines.push("Read each tool result before deciding the next step, rather than guessing what a command returned.");
|
|
282
|
+
lines.push("Only say the work is done once a tool result proves it. When you have the final answer, give it plainly with no preamble.");
|
|
264
283
|
lines.push("</tools>");
|
|
265
284
|
return lines.join("\n");
|
|
266
285
|
}
|
|
286
|
+
/** One tool's one-line description and fence template. */
|
|
287
|
+
function describeTool(tool) {
|
|
288
|
+
const shape = shapeOf(tool);
|
|
289
|
+
const lines = [];
|
|
290
|
+
const description = tool.function.description?.trim();
|
|
291
|
+
if (description) lines.push(`${tool.function.name} — ${firstSentence(description)}`);
|
|
292
|
+
lines.push("```" + tool.function.name);
|
|
293
|
+
for (const header of shape.headers) lines.push(`${header}: ${placeholderFor(header, shape.tool)}`);
|
|
294
|
+
if (shape.editPair) lines.push(SEARCH_MARKER, "the exact existing text", DIVIDER_MARKER, "the replacement text", REPLACE_MARKER);
|
|
295
|
+
else if (shape.bodyParam) lines.push(`<${shape.bodyParam}>`);
|
|
296
|
+
lines.push("```");
|
|
297
|
+
return lines;
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* The relay framing: not an agent with a shell, but a pair-programmer telling the
|
|
301
|
+
* user what to run next. A model that doubts it can reach the workspace has nothing
|
|
302
|
+
* to doubt here, because the user runs the commands. From the reference project's
|
|
303
|
+
* `relay` variant, unchanged in substance; it is repeated every turn, as there.
|
|
304
|
+
*/
|
|
305
|
+
function buildRelayPrompt(tools, shell, sandbox) {
|
|
306
|
+
const block = shell ? shell.function.name : "<tool name>";
|
|
307
|
+
const lines = [
|
|
308
|
+
`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."}`,
|
|
309
|
+
"",
|
|
310
|
+
`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.`,
|
|
311
|
+
"",
|
|
312
|
+
"The blocks I can run:",
|
|
313
|
+
""
|
|
314
|
+
];
|
|
315
|
+
for (const tool of tools) lines.push(...describeTool(tool), "");
|
|
316
|
+
return lines.join("\n").trimEnd();
|
|
317
|
+
}
|
|
267
318
|
function firstSentence(text) {
|
|
268
319
|
const cleaned = (text.split("\n").find((candidate) => candidate.trim() !== "") ?? text).replace(/^\s*[-*•]\s*/, "");
|
|
269
320
|
const stop = cleaned.indexOf(". ");
|
|
@@ -276,6 +327,37 @@ function placeholderFor(name, tool) {
|
|
|
276
327
|
return `<${schema?.type ?? "string"}>${required ? "" : " (optional)"}`;
|
|
277
328
|
}
|
|
278
329
|
/**
|
|
330
|
+
* Write a call the client already ran back as the fence the model would have
|
|
331
|
+
* written, so a history replayed into a fresh conversation shows the call next to
|
|
332
|
+
* its result. The inverse of `parseFenceBody`; falls back to JSON when a value
|
|
333
|
+
* cannot be written as a header line.
|
|
334
|
+
*/
|
|
335
|
+
function renderToolCall(name, rawArguments, tools) {
|
|
336
|
+
const tool = tools.find((candidate) => candidate.function.name === name);
|
|
337
|
+
let args;
|
|
338
|
+
try {
|
|
339
|
+
args = JSON.parse(rawArguments || "{}");
|
|
340
|
+
} catch {
|
|
341
|
+
args = {};
|
|
342
|
+
}
|
|
343
|
+
const json = () => "```" + name + "\n" + (rawArguments || "{}") + "\n```";
|
|
344
|
+
if (!tool || typeof args !== "object" || args === null) return json();
|
|
345
|
+
const shape = shapeOf(tool);
|
|
346
|
+
const lines = [];
|
|
347
|
+
for (const key of Object.keys(args)) {
|
|
348
|
+
if (key === shape.bodyParam || shape.editPair?.includes(key)) continue;
|
|
349
|
+
const value = args[key];
|
|
350
|
+
if (value === void 0 || value === null) continue;
|
|
351
|
+
if (typeof value === "object" || String(value).includes("\n")) return json();
|
|
352
|
+
lines.push(`${key}: ${String(value)}`);
|
|
353
|
+
}
|
|
354
|
+
if (shape.editPair) {
|
|
355
|
+
const [from, to] = shape.editPair;
|
|
356
|
+
if (typeof args[from] === "string" && typeof args[to] === "string") lines.push(SEARCH_MARKER, args[from], DIVIDER_MARKER, args[to], REPLACE_MARKER);
|
|
357
|
+
} else if (shape.bodyParam && typeof args[shape.bodyParam] === "string") lines.push(args[shape.bodyParam]);
|
|
358
|
+
return "```" + name + "\n" + lines.join("\n") + "\n```";
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
279
361
|
* Extract fenced blocks, honouring the CommonMark rule that a fence is closed only by
|
|
280
362
|
* a run of at least as many backticks as opened it.
|
|
281
363
|
*
|
|
@@ -364,67 +446,135 @@ function stripInventedJson(text) {
|
|
|
364
446
|
}
|
|
365
447
|
/** Parse a raw M365 response into OpenAI-shaped tool calls plus any prose. */
|
|
366
448
|
function parseToolCalls(source, tools, options = {}) {
|
|
367
|
-
const cleaned = stripInventedJson(source);
|
|
368
|
-
|
|
449
|
+
const cleaned = stripInventedJson(source.replace(/\r\n?/g, "\n"));
|
|
450
|
+
const none = (text) => ({
|
|
369
451
|
toolCalls: [],
|
|
370
|
-
text
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
};
|
|
452
|
+
text,
|
|
453
|
+
skippedCalls: 0,
|
|
454
|
+
inventedResult: false
|
|
455
|
+
});
|
|
456
|
+
if (tools.length === 0) return none(cleaned);
|
|
376
457
|
const shell = findShellTool(tools);
|
|
377
458
|
const byName = new Map(tools.map((tool) => [tool.function.name.toLowerCase(), tool]));
|
|
459
|
+
const toolFor = (fence) => {
|
|
460
|
+
const info = fence.info.split(/\s+/)[0]?.toLowerCase() ?? "";
|
|
461
|
+
return byName.get(info) ?? (shell && SHELL_FENCE_INFOS.has(info) ? shell : void 0);
|
|
462
|
+
};
|
|
463
|
+
const invented = cleaned.search(/<tool_(?:response|result)\b/i);
|
|
464
|
+
const actionable = invented === -1 ? cleaned : cleaned.slice(0, invented);
|
|
465
|
+
const fences = extractFences(actionable);
|
|
466
|
+
if (!(fences.length > 0 && actionable.slice(0, fences[0].start).trim() === "" && Boolean(toolFor(fences[0]))) && isProseDocument(actionable)) return none(cleaned);
|
|
378
467
|
const calls = [];
|
|
379
468
|
const consumed = [];
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
if (!tool && shell && SHELL_FENCE_INFOS.has(info)) tool = shell;
|
|
469
|
+
let skippedCalls = 0;
|
|
470
|
+
for (const fence of fences) {
|
|
471
|
+
const tool = toolFor(fence);
|
|
384
472
|
if (!tool) continue;
|
|
473
|
+
if (calls.length > 0 && !options.allowMultiple) {
|
|
474
|
+
skippedCalls += 1;
|
|
475
|
+
continue;
|
|
476
|
+
}
|
|
385
477
|
calls.push({
|
|
386
478
|
name: tool.function.name,
|
|
387
479
|
arguments: parseFenceBody(fence.body, tool)
|
|
388
480
|
});
|
|
389
481
|
consumed.push(fence);
|
|
390
|
-
if (!options.allowMultiple) break;
|
|
391
482
|
}
|
|
392
|
-
if (calls.length === 0) return
|
|
393
|
-
toolCalls: [],
|
|
394
|
-
text: cleaned
|
|
395
|
-
};
|
|
483
|
+
if (calls.length === 0) return none(cleaned);
|
|
396
484
|
return {
|
|
397
485
|
toolCalls: calls,
|
|
398
|
-
text: ""
|
|
486
|
+
text: "",
|
|
487
|
+
skippedCalls,
|
|
488
|
+
inventedResult: invented !== -1
|
|
399
489
|
};
|
|
400
490
|
}
|
|
491
|
+
/** Names models use for a file path, compared without case or underscores. */
|
|
492
|
+
const PATH_ALIASES = /* @__PURE__ */ new Set([
|
|
493
|
+
"path",
|
|
494
|
+
"filepath",
|
|
495
|
+
"file",
|
|
496
|
+
"filename"
|
|
497
|
+
]);
|
|
498
|
+
const squash = (name) => name.toLowerCase().replace(/_/g, "");
|
|
499
|
+
/** The parameter a header key means, tolerating case, snake_case and path aliases. */
|
|
500
|
+
function resolveKey(key, candidates) {
|
|
501
|
+
const wanted = squash(key);
|
|
502
|
+
const exact = candidates.find((name) => squash(name) === wanted);
|
|
503
|
+
if (exact) return exact;
|
|
504
|
+
if (!PATH_ALIASES.has(wanted)) return void 0;
|
|
505
|
+
return candidates.find((name) => PATH_ALIASES.has(squash(name)));
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* Clean a header value the way models write it: wrapped in quotes or backticks, with
|
|
509
|
+
* the template's `(optional)` marker echoed. An echoed `<type>` placeholder is no value.
|
|
510
|
+
*/
|
|
511
|
+
function cleanValue(raw) {
|
|
512
|
+
let value = raw.replace(/\s*\(optional\)\s*$/i, "").trim();
|
|
513
|
+
const wrapped = /^(["'`])(.*)\1$/.exec(value);
|
|
514
|
+
if (wrapped) value = wrapped[2];
|
|
515
|
+
return /^<[A-Za-z]+>$/.test(value) ? void 0 : value;
|
|
516
|
+
}
|
|
401
517
|
/** Split a fence body into header args, a SEARCH/REPLACE pair, and/or a body arg. */
|
|
402
518
|
function parseFenceBody(body, tool) {
|
|
403
519
|
const shape = shapeOf(tool);
|
|
404
520
|
const props = tool.function.parameters?.properties ?? {};
|
|
521
|
+
const isShell = SHELL_TOOL_NAMES.includes(tool.function.name.toLowerCase());
|
|
405
522
|
const args = {};
|
|
523
|
+
const seen = /* @__PURE__ */ new Set();
|
|
524
|
+
let bodyHeader;
|
|
525
|
+
const editHeaders = {};
|
|
406
526
|
const lines = body.split("\n");
|
|
407
527
|
let cursor = 0;
|
|
528
|
+
const headerish = [
|
|
529
|
+
...shape.headers,
|
|
530
|
+
...shape.bodyParam ? [shape.bodyParam] : [],
|
|
531
|
+
...shape.editPair ?? []
|
|
532
|
+
];
|
|
408
533
|
while (cursor < lines.length) {
|
|
409
534
|
const match = /^([A-Za-z_][A-Za-z0-9_]*)\s*:\s?(.*)$/.exec(lines[cursor]);
|
|
410
535
|
if (!match) break;
|
|
411
|
-
const key = match[1];
|
|
412
|
-
if (!
|
|
413
|
-
|
|
536
|
+
const key = resolveKey(match[1], headerish);
|
|
537
|
+
if (!key || seen.has(key)) break;
|
|
538
|
+
seen.add(key);
|
|
539
|
+
if (key === shape.bodyParam) bodyHeader = {
|
|
540
|
+
value: match[2].trim(),
|
|
541
|
+
line: lines[cursor]
|
|
542
|
+
};
|
|
543
|
+
else if (shape.editPair?.includes(key)) editHeaders[key] = match[2];
|
|
544
|
+
else {
|
|
545
|
+
const value = cleanValue(match[2]);
|
|
546
|
+
if (value !== void 0) args[key] = coerce(value, props[key]?.type);
|
|
547
|
+
}
|
|
414
548
|
cursor += 1;
|
|
415
549
|
}
|
|
416
|
-
const rest = lines.slice(cursor).join("\n").replace(/^\n+/, "");
|
|
550
|
+
const rest = lines.slice(cursor).join("\n").replace(/^\n+/, "").trimEnd();
|
|
417
551
|
if (shape.editPair) {
|
|
552
|
+
const [search, replace] = shape.editPair;
|
|
418
553
|
const diff = parseSearchReplace(rest);
|
|
419
554
|
if (diff) {
|
|
420
|
-
args[
|
|
421
|
-
args[
|
|
555
|
+
args[search] = diff.search;
|
|
556
|
+
args[replace] = diff.replace;
|
|
557
|
+
} else if (search in editHeaders && replace in editHeaders) {
|
|
558
|
+
args[search] = editHeaders[search];
|
|
559
|
+
args[replace] = editHeaders[replace];
|
|
422
560
|
}
|
|
423
561
|
return args;
|
|
424
562
|
}
|
|
425
563
|
if (shape.bodyParam) {
|
|
426
|
-
|
|
427
|
-
if (
|
|
564
|
+
let value = rest;
|
|
565
|
+
if (bodyHeader) {
|
|
566
|
+
if (isShell) value = [bodyHeader.value, rest].filter((part) => part !== "").join("\n");
|
|
567
|
+
else value = rest === "" ? bodyHeader.value : `${bodyHeader.line}\n${rest}`;
|
|
568
|
+
}
|
|
569
|
+
if (isShell && value.split("\n").every((line) => line.trim() === "" || line.startsWith("$ "))) value = value.replace(/^\$ /gm, "");
|
|
570
|
+
if (value.trim() !== "") args[shape.bodyParam] = value;
|
|
571
|
+
return args;
|
|
572
|
+
}
|
|
573
|
+
const required = tool.function.parameters?.required ?? [];
|
|
574
|
+
const missing = shape.headers.filter((name) => required.includes(name) && !(name in args));
|
|
575
|
+
if (missing.length === 1 && rest !== "" && !rest.includes("\n")) {
|
|
576
|
+
const value = cleanValue(rest);
|
|
577
|
+
if (value !== void 0) args[missing[0]] = coerce(value, props[missing[0]]?.type);
|
|
428
578
|
}
|
|
429
579
|
return args;
|
|
430
580
|
}
|
|
@@ -486,6 +636,7 @@ const PLUGIN_ID = "m365-copilot";
|
|
|
486
636
|
*/
|
|
487
637
|
const LEAN_TOOLS = [
|
|
488
638
|
"bash",
|
|
639
|
+
"shell",
|
|
489
640
|
"read",
|
|
490
641
|
"edit",
|
|
491
642
|
"write",
|
|
@@ -502,16 +653,18 @@ const LEAN_TOOLS = [
|
|
|
502
653
|
* final request whatever the harness does, so the trim lives here.
|
|
503
654
|
*
|
|
504
655
|
* Two rules, in order:
|
|
505
|
-
* 1. Keep the tools we recognise as load-bearing for a coding loop
|
|
656
|
+
* 1. Keep the tools we recognise as load-bearing for a coding loop, plus the shell
|
|
657
|
+
* tool under whatever name the harness gives it — opencode 2 renamed `bash` to
|
|
658
|
+
* `shell`, and an allowlist alone silently dropped it.
|
|
506
659
|
* 2. If we recognise none of them — a harness with its own vocabulary — fall back
|
|
507
660
|
* to a hard cap, keeping any shell tool first.
|
|
508
661
|
*/
|
|
509
662
|
function selectLeanTools(tools) {
|
|
510
663
|
if (tools.length === 0) return [...tools];
|
|
511
664
|
const wanted = new Set(LEAN_TOOLS);
|
|
512
|
-
const kept = tools.filter((tool) => wanted.has(tool.function.name.toLowerCase()));
|
|
513
|
-
if (kept.length > 0) return kept;
|
|
514
665
|
const shell = findShellTool(tools);
|
|
666
|
+
const kept = tools.filter((tool) => tool === shell || wanted.has(tool.function.name.toLowerCase()));
|
|
667
|
+
if (kept.some((tool) => tool !== shell)) return kept;
|
|
515
668
|
const rest = tools.filter((tool) => tool !== shell);
|
|
516
669
|
const remaining = shell ? 4 : 5;
|
|
517
670
|
return [...shell ? [shell] : [], ...rest.slice(0, remaining)];
|
|
@@ -958,7 +1111,7 @@ function createTokenClient(options = {}) {
|
|
|
958
1111
|
const cache = /* @__PURE__ */ new Map();
|
|
959
1112
|
async function client() {
|
|
960
1113
|
if (app) return app;
|
|
961
|
-
const { PublicClientApplication } = await import("./dist-
|
|
1114
|
+
const { PublicClientApplication } = await import("./dist-CsSmycf9.mjs");
|
|
962
1115
|
app = new PublicClientApplication({
|
|
963
1116
|
auth: {
|
|
964
1117
|
clientId: CLIENT_ID,
|
|
@@ -4798,6 +4951,30 @@ var DisengagedError = class extends Error {
|
|
|
4798
4951
|
this.name = "DisengagedError";
|
|
4799
4952
|
}
|
|
4800
4953
|
};
|
|
4954
|
+
/** The server refused the invocation outright — a retired tone, typically. Retrying cannot help. */
|
|
4955
|
+
var TurnRejectedError = class extends Error {
|
|
4956
|
+
constructor(detail) {
|
|
4957
|
+
super(`M365 rejected the turn: ${detail}`);
|
|
4958
|
+
this.name = "TurnRejectedError";
|
|
4959
|
+
}
|
|
4960
|
+
};
|
|
4961
|
+
/** M365 throttled the account. Every retry extends the lull it needs to recover. */
|
|
4962
|
+
var M365ThrottledError = class extends Error {
|
|
4963
|
+
constructor(detail) {
|
|
4964
|
+
super(`M365 is throttling this account (${detail}). It recovers after a lull; retrying now extends it.`);
|
|
4965
|
+
this.name = "M365ThrottledError";
|
|
4966
|
+
}
|
|
4967
|
+
};
|
|
4968
|
+
/**
|
|
4969
|
+
* M365 answered with its own refusal instead of the model: no credits left, a model
|
|
4970
|
+
* this account's licence does not cover, or a tone that is registered but dead.
|
|
4971
|
+
*/
|
|
4972
|
+
var M365UnavailableError = class extends Error {
|
|
4973
|
+
constructor(detail) {
|
|
4974
|
+
super(`M365 could not serve this model: ${detail}`);
|
|
4975
|
+
this.name = "M365UnavailableError";
|
|
4976
|
+
}
|
|
4977
|
+
};
|
|
4801
4978
|
/**
|
|
4802
4979
|
* Strip Copilot's inline citation control tokens from a GROUNDED answer.
|
|
4803
4980
|
*
|
|
@@ -4848,7 +5025,10 @@ var CopilotSession = class {
|
|
|
4848
5025
|
text: note ? `${text}\n\n${note}` : text,
|
|
4849
5026
|
annotations
|
|
4850
5027
|
};
|
|
4851
|
-
const socket = new import_websocket.default(url, { headers:
|
|
5028
|
+
const socket = new import_websocket.default(url, { headers: {
|
|
5029
|
+
...BROWSER_HEADERS,
|
|
5030
|
+
"X-RoutingParameter-SessionKey": this.conversationId
|
|
5031
|
+
} });
|
|
4852
5032
|
try {
|
|
4853
5033
|
const result = await this.pump(socket, message, turn);
|
|
4854
5034
|
this.turnIndex += 1;
|
|
@@ -4925,6 +5105,11 @@ var CopilotSession = class {
|
|
|
4925
5105
|
return;
|
|
4926
5106
|
}
|
|
4927
5107
|
const raw = deltaText.length >= snapshotText.length ? deltaText : snapshotText;
|
|
5108
|
+
const refusal = refusalOf(result, raw);
|
|
5109
|
+
if (refusal) {
|
|
5110
|
+
reject(refusal);
|
|
5111
|
+
return;
|
|
5112
|
+
}
|
|
4928
5113
|
result.text = turn.grounded ? cleanAnswer(raw) : raw;
|
|
4929
5114
|
resolve(result);
|
|
4930
5115
|
};
|
|
@@ -4976,7 +5161,7 @@ var CopilotSession = class {
|
|
|
4976
5161
|
break;
|
|
4977
5162
|
case 3:
|
|
4978
5163
|
if (frame.error) {
|
|
4979
|
-
finish(
|
|
5164
|
+
finish(new TurnRejectedError(frame.error));
|
|
4980
5165
|
return;
|
|
4981
5166
|
}
|
|
4982
5167
|
finish();
|
|
@@ -5115,6 +5300,8 @@ var CopilotSession = class {
|
|
|
5115
5300
|
}
|
|
5116
5301
|
applyStreamItem(item, result) {
|
|
5117
5302
|
if (!item) return;
|
|
5303
|
+
if (typeof item.result?.value === "string") result.resultValue = item.result.value;
|
|
5304
|
+
if (typeof item.result?.errorCode === "string") result.errorCode = item.result.errorCode;
|
|
5118
5305
|
if (item.throttling) result.throttle = {
|
|
5119
5306
|
current: item.throttling.numUserMessagesInConversation,
|
|
5120
5307
|
max: item.throttling.maxNumUserMessagesInConversation
|
|
@@ -5122,6 +5309,16 @@ var CopilotSession = class {
|
|
|
5122
5309
|
for (const message of item.messages ?? []) if (message?.author === "bot" && !message.messageType) absorbMetadata(message, result);
|
|
5123
5310
|
}
|
|
5124
5311
|
};
|
|
5312
|
+
/**
|
|
5313
|
+
* M365's own refusal, when that is what arrived instead of an answer. Its text reads
|
|
5314
|
+
* like a reply, so returned as one it would end opencode's loop on an apology.
|
|
5315
|
+
*/
|
|
5316
|
+
function refusalOf(result, text) {
|
|
5317
|
+
const detail = [result.errorCode, text.trim()].filter(Boolean).join(": ") || result.resultValue || "no reason given";
|
|
5318
|
+
if (result.resultValue === "Throttled") return new M365ThrottledError(detail);
|
|
5319
|
+
if (result.resultValue && result.resultValue !== "Success") return new M365UnavailableError(detail);
|
|
5320
|
+
if (result.contentOrigin === "BotConnection") return new M365UnavailableError(`registered but dead (BotConnection): ${detail}`);
|
|
5321
|
+
}
|
|
5125
5322
|
/** Pull the diagnostic fields off a final bot message. */
|
|
5126
5323
|
function absorbMetadata(message, result) {
|
|
5127
5324
|
if (typeof message.contentOrigin === "string") result.contentOrigin = message.contentOrigin;
|
|
@@ -10594,6 +10791,15 @@ function condenseSystemPrompt(text, tools, options = {}) {
|
|
|
10594
10791
|
if (requires.some((name) => toolNames.has(name))) continue;
|
|
10595
10792
|
result = result.replace(new RegExp(`<${tag}>[\\s\\S]*?</${tag}>`, "g"), "");
|
|
10596
10793
|
}
|
|
10794
|
+
result = outsideUserRules(result, (harness) => {
|
|
10795
|
+
let text = harness;
|
|
10796
|
+
if (!toolNames.has("execute")) {
|
|
10797
|
+
text = text.replace(/^# Code Mode\n[\s\S]*?(?=^# |^Skills provide |^<[a-z_]+>|(?![\s\S]))/m, "");
|
|
10798
|
+
text = dropLines(text, /`execute`/);
|
|
10799
|
+
}
|
|
10800
|
+
if (!toolNames.has("skill")) text = dropLines(text, /^Skills provide |\bskill tool\b|invoke a skill directly/);
|
|
10801
|
+
return dropLines(text, /^- Prefer parallelizing independent tool calls|^- Prefer dedicated tools over shell commands/);
|
|
10802
|
+
});
|
|
10597
10803
|
if (options.replaceProseWith !== void 0) {
|
|
10598
10804
|
const { leadingBlocks, instructions, blocks } = splitSystemPrompt(result);
|
|
10599
10805
|
result = [
|
|
@@ -10605,6 +10811,32 @@ function condenseSystemPrompt(text, tools, options = {}) {
|
|
|
10605
10811
|
}
|
|
10606
10812
|
return result.replace(/\n{3,}/g, "\n\n").trim();
|
|
10607
10813
|
}
|
|
10814
|
+
/**
|
|
10815
|
+
* Apply `trim` to everything except the user's rules files.
|
|
10816
|
+
*
|
|
10817
|
+
* opencode puts each rules file under an `Instructions from: <path>` line, and follows
|
|
10818
|
+
* the last with its own `Today's date:` line and `<env>`. A rules section runs until the
|
|
10819
|
+
* next of those. Rules files are Markdown with blank lines of their own, so a blank
|
|
10820
|
+
* line is not a boundary.
|
|
10821
|
+
*/
|
|
10822
|
+
function outsideUserRules(text, trim) {
|
|
10823
|
+
const out = [];
|
|
10824
|
+
let cursor = 0;
|
|
10825
|
+
for (const start of text.matchAll(/^Instructions from:[ \t]*\S.*$/gm)) {
|
|
10826
|
+
if (start.index < cursor) continue;
|
|
10827
|
+
out.push(trim(text.slice(cursor, start.index)));
|
|
10828
|
+
const after = start.index + start[0].length;
|
|
10829
|
+
const next = text.slice(after).search(/^(?:Instructions from:|Today's date:|<[a-z_]+>)/m);
|
|
10830
|
+
cursor = next === -1 ? text.length : after + next;
|
|
10831
|
+
out.push(text.slice(start.index, cursor));
|
|
10832
|
+
}
|
|
10833
|
+
out.push(trim(text.slice(cursor)));
|
|
10834
|
+
return out.join("");
|
|
10835
|
+
}
|
|
10836
|
+
/** Remove every line matching `pattern`. */
|
|
10837
|
+
function dropLines(text, pattern) {
|
|
10838
|
+
return text.split("\n").filter((line) => !pattern.test(line)).join("\n");
|
|
10839
|
+
}
|
|
10608
10840
|
const BLOCK_PATTERN = /<([a-z_][a-z0-9_-]*)>[\s\S]*?<\/\1>/gi;
|
|
10609
10841
|
/**
|
|
10610
10842
|
* Split a harness system prompt into: leading prose, the user's own instructions,
|
|
@@ -10657,13 +10889,19 @@ function trailingBlockStart(text) {
|
|
|
10657
10889
|
*/
|
|
10658
10890
|
function buildTurnPrompt(messages, tools, sentMessageCount, options = {}) {
|
|
10659
10891
|
const parts = [];
|
|
10660
|
-
|
|
10892
|
+
const isFirstTurn = sentMessageCount === 0;
|
|
10893
|
+
if (isFirstTurn) {
|
|
10661
10894
|
const systemText = messages.filter((message) => message.role === "system" || message.role === "developer").map(contentOf).filter(Boolean).join("\n\n");
|
|
10662
10895
|
if (systemText) parts.push(condenseSystemPrompt(systemText, tools, { ...options.leanSystemPrompt !== void 0 ? { replaceProseWith: options.leanSystemPrompt } : {} }));
|
|
10663
10896
|
}
|
|
10664
|
-
if (tools.length > 0) parts.push(buildToolPrompt(tools
|
|
10897
|
+
if (tools.length > 0) parts.push(buildToolPrompt(tools, {
|
|
10898
|
+
firstTurn: isFirstTurn,
|
|
10899
|
+
...options.framing ? { framing: options.framing } : {},
|
|
10900
|
+
...options.sandbox ? { sandbox: options.sandbox } : {}
|
|
10901
|
+
}));
|
|
10665
10902
|
const callsById = /* @__PURE__ */ new Map();
|
|
10666
10903
|
for (const message of messages) for (const call of message.tool_calls ?? []) callsById.set(call.id, call.function);
|
|
10904
|
+
if (options.note) parts.push(options.note);
|
|
10667
10905
|
for (const message of messages.slice(sentMessageCount)) {
|
|
10668
10906
|
if (message.role === "system" || message.role === "developer") continue;
|
|
10669
10907
|
if (message.role === "tool") {
|
|
@@ -10673,6 +10911,7 @@ function buildTurnPrompt(messages, tools, sentMessageCount, options = {}) {
|
|
|
10673
10911
|
if (message.role === "assistant") {
|
|
10674
10912
|
const text = contentOf(message);
|
|
10675
10913
|
if (text) parts.push(text);
|
|
10914
|
+
for (const call of message.tool_calls ?? []) parts.push(renderToolCall(call.function.name, call.function.arguments, tools));
|
|
10676
10915
|
continue;
|
|
10677
10916
|
}
|
|
10678
10917
|
const text = contentOf(message) || (hasImagePart(message) ? "(See the attached image.)" : "");
|
|
@@ -10692,7 +10931,21 @@ function renderToolResult(message, callsById) {
|
|
|
10692
10931
|
if (call?.name) attributes.push(`tool="${escapeAttribute(call.name)}"`);
|
|
10693
10932
|
const summary = summariseArguments(call?.arguments);
|
|
10694
10933
|
if (summary) attributes.push(`command="${escapeAttribute(summary)}"`);
|
|
10695
|
-
return `${attributes.length > 0 ? `<tool_response ${attributes.join(" ")}>` : "<tool_response>"}\n${contentOf(message)}\n</tool_response>`;
|
|
10934
|
+
return `${attributes.length > 0 ? `<tool_response ${attributes.join(" ")}>` : "<tool_response>"}\n${unwrapToolError(contentOf(message))}\n</tool_response>`;
|
|
10935
|
+
}
|
|
10936
|
+
/**
|
|
10937
|
+
* opencode reports a failed tool as `{"error":{"type":"tool.execution","message":"…"},"content":[]}`,
|
|
10938
|
+
* with the message's newlines escaped. Its messages are good ("Update the arguments
|
|
10939
|
+
* and call the tool again"); the envelope just hides them.
|
|
10940
|
+
*/
|
|
10941
|
+
function unwrapToolError(content) {
|
|
10942
|
+
if (!content.startsWith("{\"error\"")) return content;
|
|
10943
|
+
try {
|
|
10944
|
+
const message = JSON.parse(content)?.error?.message;
|
|
10945
|
+
return typeof message === "string" ? `Error: ${message}` : content;
|
|
10946
|
+
} catch {
|
|
10947
|
+
return content;
|
|
10948
|
+
}
|
|
10696
10949
|
}
|
|
10697
10950
|
/** The most identifying argument value, for the label. */
|
|
10698
10951
|
function summariseArguments(raw) {
|
|
@@ -10812,6 +11065,38 @@ function generateTitle(messages) {
|
|
|
10812
11065
|
function firstLine(text) {
|
|
10813
11066
|
return text.split("\n", 1)[0] ?? "";
|
|
10814
11067
|
}
|
|
11068
|
+
// src/giveup.ts
|
|
11069
|
+
/**
|
|
11070
|
+
* Spotting a tool turn where the model gave up instead of acting.
|
|
11071
|
+
*
|
|
11072
|
+
* M365's chat tones sometimes answer a tool turn by claiming they have no tools or
|
|
11073
|
+
* cannot reach the files, without trying. It is stochastic: the same tone acts on the
|
|
11074
|
+
* next try. Returned to opencode as-is, that prose ends the agent loop, so the proxy
|
|
11075
|
+
* asks once more in the same conversation instead. The reference project measured
|
|
11076
|
+
* that recovering roughly 16/30 → 25/30 tasks on `Gpt_5_5_Chat`.
|
|
11077
|
+
*/
|
|
11078
|
+
const GIVE_UP_PATTERNS = [
|
|
11079
|
+
/\b(?:unable|not able|can.?t|cannot)\s+(?:to\s+)?(?:directly\s+)?(?:access|inspect|list|read|run|execute|retrieve|fetch|open|see|edit|modify|write|create|change)\b/i,
|
|
11080
|
+
/\bdon.?t\s+have\s+(?:access|any\s+(?:way|tool)|a\s+(?:way|tool))\b/i,
|
|
11081
|
+
/\bno\s+(?:[\w-]+\s+){0,3}tools?\s+(?:is|are)\s+(?:currently\s+)?(?:available|accessible|executable)\b/i,
|
|
11082
|
+
/\btools?\b[^.\n]{0,40}\b(?:(?:is|are)\s+not\s+(?:currently\s+)?(?:available|executable|accessible)|unavailable|no\s+longer\s+available|did\s*n.?o?t\s+execute)\b/i,
|
|
11083
|
+
/\b(?:does\s+not|doesn.?t)\s+(?:provide|have|expose)\s+(?:a|any)\s+[\w\s-]{0,30}\btool\b/i,
|
|
11084
|
+
/\bpaste\s+(?:the\s+|its\s+)?(?:contents?|files?|code|output)\b/i,
|
|
11085
|
+
/\b(?:different|another|new)\s+(?:session|environment|conversation)\b/i
|
|
11086
|
+
];
|
|
11087
|
+
function looksLikeGiveUp(reply) {
|
|
11088
|
+
const text = reply.trim();
|
|
11089
|
+
return text.length >= 12 && GIVE_UP_PATTERNS.some((pattern) => pattern.test(text));
|
|
11090
|
+
}
|
|
11091
|
+
/**
|
|
11092
|
+
* The follow-up. Soft on purpose: shouted absolutes read as manipulation to the
|
|
11093
|
+
* Disengaged filter. Once tools have run it must not say nothing has — a prompt that
|
|
11094
|
+
* contradicts the transcript is one the model stops trusting.
|
|
11095
|
+
*/
|
|
11096
|
+
function nudgeFor(midTask, framing = "default") {
|
|
11097
|
+
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.";
|
|
11098
|
+
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.";
|
|
11099
|
+
}
|
|
10815
11100
|
// src/server.ts
|
|
10816
11101
|
/**
|
|
10817
11102
|
* The OpenAI-compatible HTTP surface.
|
|
@@ -11010,6 +11295,16 @@ async function handleChatCompletion(request, response, context) {
|
|
|
11010
11295
|
release();
|
|
11011
11296
|
}
|
|
11012
11297
|
}
|
|
11298
|
+
let envTurnLog;
|
|
11299
|
+
/** The `M365_TURN_LOG` file writer, created on first use. */
|
|
11300
|
+
function defaultTurnLog() {
|
|
11301
|
+
if (envTurnLog === void 0) {
|
|
11302
|
+
const file = process.env.M365_TURN_LOG;
|
|
11303
|
+
const append = file ? createPrivateAppender(file) : null;
|
|
11304
|
+
envTurnLog = append ? (entry) => append(`${JSON.stringify(entry)}\n`) : null;
|
|
11305
|
+
}
|
|
11306
|
+
return envTurnLog;
|
|
11307
|
+
}
|
|
11013
11308
|
async function runTurn(request, response, context, body, conversation, model, tools) {
|
|
11014
11309
|
if (body.messages.length < conversation.sentMessageCount) conversation.sentMessageCount = 0;
|
|
11015
11310
|
conversation.session ??= new CopilotSession({
|
|
@@ -11018,8 +11313,16 @@ async function runTurn(request, response, context, body, conversation, model, to
|
|
|
11018
11313
|
});
|
|
11019
11314
|
const effectiveTools = model.grounded ? [] : tools;
|
|
11020
11315
|
const images = collectImages(body.messages, conversation.sentMessageCount);
|
|
11021
|
-
const
|
|
11022
|
-
|
|
11316
|
+
const note = effectiveTools.length > 0 && conversation.sentMessageCount > 0 ? conversation.note : void 0;
|
|
11317
|
+
conversation.note = void 0;
|
|
11318
|
+
const route = toolRouteFor(model.tone);
|
|
11319
|
+
const prompt = buildTurnPrompt(body.messages, effectiveTools, conversation.sentMessageCount, {
|
|
11320
|
+
framing: route.framing,
|
|
11321
|
+
...route.sandbox ? { sandbox: route.sandbox } : {},
|
|
11322
|
+
...context.deps.leanSystemPrompt !== void 0 ? { leanSystemPrompt: context.deps.leanSystemPrompt } : {},
|
|
11323
|
+
...note ? { note } : {}
|
|
11324
|
+
});
|
|
11325
|
+
const agent = effectiveTools.length > 0 && route.agent ? await context.agentId() : null;
|
|
11023
11326
|
const abort = new AbortController();
|
|
11024
11327
|
request.on("close", () => {
|
|
11025
11328
|
if (!response.writableEnded) abort.abort();
|
|
@@ -11028,16 +11331,47 @@ async function runTurn(request, response, context, body, conversation, model, to
|
|
|
11028
11331
|
const streamId = `chatcmpl-${randomUUID()}`;
|
|
11029
11332
|
const canStreamText = streaming && effectiveTools.length === 0 && !model.grounded;
|
|
11030
11333
|
if (streaming) startSse(response);
|
|
11334
|
+
const turnLog = context.deps.turnLog ?? defaultTurnLog();
|
|
11335
|
+
const logTurn = (fields) => turnLog?.({
|
|
11336
|
+
time: (/* @__PURE__ */ new Date()).toISOString(),
|
|
11337
|
+
model: model.id,
|
|
11338
|
+
tone: model.tone,
|
|
11339
|
+
agent: Boolean(agent),
|
|
11340
|
+
...effectiveTools.length > 0 ? { framing: route.framing } : {},
|
|
11341
|
+
tools: effectiveTools.map((tool) => tool.function.name),
|
|
11342
|
+
...fields
|
|
11343
|
+
});
|
|
11344
|
+
const turnOptions = {
|
|
11345
|
+
...model.tone ? { tone: model.tone } : {},
|
|
11346
|
+
agentId: agent,
|
|
11347
|
+
...model.grounded ? { grounded: true } : {},
|
|
11348
|
+
signal: abort.signal
|
|
11349
|
+
};
|
|
11350
|
+
const recordTurn = (result, extra = {}) => logTurn({
|
|
11351
|
+
reply: result.text,
|
|
11352
|
+
toolCalls: parseToolCalls(result.text, effectiveTools).toolCalls.map((call) => call.name),
|
|
11353
|
+
...result.contentOrigin ? { contentOrigin: result.contentOrigin } : {},
|
|
11354
|
+
...result.turnCount !== void 0 ? { turnCount: result.turnCount } : {},
|
|
11355
|
+
...result.throttle ? { throttle: result.throttle } : {},
|
|
11356
|
+
...result.scores ? { scores: result.scores } : {},
|
|
11357
|
+
...result.resultValue ? { resultValue: result.resultValue } : {},
|
|
11358
|
+
...extra
|
|
11359
|
+
});
|
|
11031
11360
|
try {
|
|
11032
|
-
|
|
11033
|
-
...
|
|
11034
|
-
agentId: agent,
|
|
11035
|
-
...model.grounded ? { grounded: true } : {},
|
|
11036
|
-
signal: abort.signal,
|
|
11361
|
+
let result = await conversation.session.run(prompt, {
|
|
11362
|
+
...turnOptions,
|
|
11037
11363
|
...images.length > 0 ? { images } : {},
|
|
11038
11364
|
...canStreamText ? { onDelta: (chunk) => response.write(streamChunk(streamId, model.id, { content: chunk })) } : {}
|
|
11039
11365
|
});
|
|
11366
|
+
if (effectiveTools.length > 0 && parseToolCalls(result.text, effectiveTools).toolCalls.length === 0 && looksLikeGiveUp(result.text)) {
|
|
11367
|
+
recordTurn(result);
|
|
11368
|
+
const midTask = body.messages.some((message) => message.role === "tool");
|
|
11369
|
+
result = await conversation.session.run(nudgeFor(midTask, route.framing), turnOptions);
|
|
11370
|
+
recordTurn(result, { nudged: true });
|
|
11371
|
+
} else recordTurn(result);
|
|
11040
11372
|
conversation.sentMessageCount = body.messages.length + 1;
|
|
11373
|
+
const allowMultiple = context.deps.allowMultiTool ?? false;
|
|
11374
|
+
conversation.note = noteAbout(parseToolCalls(result.text, effectiveTools, { allowMultiple }));
|
|
11041
11375
|
if (!streaming) {
|
|
11042
11376
|
sendJson(response, 200, buildCompletion(result, {
|
|
11043
11377
|
model: model.id,
|
|
@@ -11048,9 +11382,31 @@ async function runTurn(request, response, context, body, conversation, model, to
|
|
|
11048
11382
|
}
|
|
11049
11383
|
finishStream(response, streamId, model.id, result, effectiveTools, canStreamText, context.deps.allowMultiTool ?? false);
|
|
11050
11384
|
} catch (error) {
|
|
11385
|
+
logTurn({ error: error instanceof Error ? `${error.name}: ${error.message}` : String(error) });
|
|
11386
|
+
if (error instanceof DisengagedError) {
|
|
11387
|
+
conversation.session.reset();
|
|
11388
|
+
conversation.sentMessageCount = 0;
|
|
11389
|
+
}
|
|
11051
11390
|
handleTurnFailure(response, error, streaming, effectiveTools.length);
|
|
11052
11391
|
}
|
|
11053
11392
|
}
|
|
11393
|
+
/**
|
|
11394
|
+
* One line for the next turn when the last reply was not run as written. Without
|
|
11395
|
+
* it the model assumes every block it wrote ran, and the reference project measured
|
|
11396
|
+
* early "task already complete" endings falling from 9 in 56 runs to 0 in 70 once
|
|
11397
|
+
* it was told.
|
|
11398
|
+
*/
|
|
11399
|
+
function noteAbout(parsed) {
|
|
11400
|
+
const first = parsed.toolCalls[0];
|
|
11401
|
+
if (!first) return void 0;
|
|
11402
|
+
const lines = [];
|
|
11403
|
+
if (parsed.skippedCalls > 0) {
|
|
11404
|
+
const others = parsed.skippedCalls === 1 ? "1 other" : `${parsed.skippedCalls} others`;
|
|
11405
|
+
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.`);
|
|
11406
|
+
}
|
|
11407
|
+
if (parsed.inventedResult) lines.push("The result you predicted after your call was set aside; the real one is below.");
|
|
11408
|
+
return lines.length > 0 ? lines.join(" ") : void 0;
|
|
11409
|
+
}
|
|
11054
11410
|
/** Emit the closing frames of a streamed turn. */
|
|
11055
11411
|
function finishStream(response, streamId, model, result, tools, alreadyStreamedText, allowMultiple) {
|
|
11056
11412
|
const { toolCalls, text } = parseToolCalls(result.text, tools, { allowMultiple });
|
|
@@ -11064,13 +11420,27 @@ function finishStream(response, streamId, model, result, tools, alreadyStreamedT
|
|
|
11064
11420
|
response.write(streamDone());
|
|
11065
11421
|
response.end();
|
|
11066
11422
|
}
|
|
11423
|
+
/** opencode retries a 5xx several times and a 4xx not at all (measured on 2.2.5). */
|
|
11424
|
+
const NON_RETRYABLE = 422;
|
|
11067
11425
|
function handleTurnFailure(response, error, streaming, toolCount) {
|
|
11068
11426
|
if (error instanceof AuthRequiredError) {
|
|
11069
11427
|
finishWithError(response, streaming, 401, "authentication_required", error.message);
|
|
11070
11428
|
return;
|
|
11071
11429
|
}
|
|
11072
11430
|
if (error instanceof DisengagedError) {
|
|
11073
|
-
|
|
11431
|
+
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."}`);
|
|
11432
|
+
return;
|
|
11433
|
+
}
|
|
11434
|
+
if (error instanceof M365ThrottledError) {
|
|
11435
|
+
refuse(response, streaming, "m365_throttled", error.message);
|
|
11436
|
+
return;
|
|
11437
|
+
}
|
|
11438
|
+
if (error instanceof M365UnavailableError) {
|
|
11439
|
+
refuse(response, streaming, "m365_not_served", error.message);
|
|
11440
|
+
return;
|
|
11441
|
+
}
|
|
11442
|
+
if (error instanceof TurnRejectedError) {
|
|
11443
|
+
refuse(response, streaming, "m365_turn_rejected", error.message);
|
|
11074
11444
|
return;
|
|
11075
11445
|
}
|
|
11076
11446
|
const message = error instanceof Error ? error.message : String(error);
|
|
@@ -11080,17 +11450,35 @@ function handleTurnFailure(response, error, streaming, toolCount) {
|
|
|
11080
11450
|
}
|
|
11081
11451
|
finishWithError(response, streaming, 502, "upstream_error", message);
|
|
11082
11452
|
}
|
|
11453
|
+
/**
|
|
11454
|
+
* Report an M365 refusal so that opencode does not retry it.
|
|
11455
|
+
*
|
|
11456
|
+
* opencode streams, so the refusal reaches it inside a stream that already answered
|
|
11457
|
+
* 200, and it decides from the body alone (measured against 2.2.5's classifier, see
|
|
11458
|
+
* test/opencode-retry.ts). It retries a code containing "unavailable", a message
|
|
11459
|
+
* saying "try again" — which M365's own refusals do — and any mention of a rate
|
|
11460
|
+
* limit. Type `invalid_request_error` switches off the "try again" rule; the rate
|
|
11461
|
+
* limit wording is reworded, since that rule ignores the type.
|
|
11462
|
+
*/
|
|
11463
|
+
function refuse(response, streaming, code, message) {
|
|
11464
|
+
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");
|
|
11465
|
+
finishWithError(response, streaming, NON_RETRYABLE, code, reworded, "invalid_request_error");
|
|
11466
|
+
}
|
|
11083
11467
|
/** Report an error, in whichever shape the client is already reading. */
|
|
11084
|
-
function finishWithError(response, streaming, status, code, message) {
|
|
11468
|
+
function finishWithError(response, streaming, status, code, message, type = code) {
|
|
11085
11469
|
if (!streaming) {
|
|
11086
|
-
|
|
11470
|
+
if (!response.writableEnded) sendJson(response, status, { error: {
|
|
11471
|
+
message,
|
|
11472
|
+
type,
|
|
11473
|
+
code
|
|
11474
|
+
} });
|
|
11087
11475
|
return;
|
|
11088
11476
|
}
|
|
11089
11477
|
if (!response.writableEnded) {
|
|
11090
11478
|
response.write(`data: ${JSON.stringify({ error: {
|
|
11091
11479
|
message,
|
|
11092
11480
|
code,
|
|
11093
|
-
type
|
|
11481
|
+
type
|
|
11094
11482
|
} })}\n\n`);
|
|
11095
11483
|
response.write(streamDone());
|
|
11096
11484
|
response.end();
|
|
@@ -11155,4 +11543,4 @@ async function readBody(request, limit) {
|
|
|
11155
11543
|
}
|
|
11156
11544
|
return Buffer.concat(chunks).toString("utf8");
|
|
11157
11545
|
}
|
|
11158
|
-
export {
|
|
11546
|
+
export { mergeOpencodeConfig as A, CACHE_FILE as C, PROVIDER_ID as D, PLUGIN_ID as E, isLocalModel as F, __commonJSMin as I, __require as L, DEFAULT_MODEL as M, LOCAL_TITLE_MODEL as N, buildModelInfos as O, MODELS as P, __toESM as R, AGENT_FILE as S, SECRETS_FILE as T, createCachePlugin as _, noteAbout as a, ensurePrivateDir as b, string as c, BAP_SCOPE as d, CLIENT_ID as f, authCodeFromUrl as g, SYDNEY_SCOPES as h, generateApiKey as i, resolveOptions as j, buildProviderInfo as k, CopilotSession as l, REDIRECT_URI as m, DEFAULT_MAX_BODY_BYTES as n, startServer as o, POWERPLATFORM_SCOPE as p, SESSION_ID_HEADER as r, object as s, AUX_REQUEST_KIND_HEADER as t, AUTHORITY as u, createTokenClient as v, CONFIG_DIR as w, writePrivateFile as x, createLogger as y };
|