opencode-m365-copilot 2.2.0 → 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 CHANGED
@@ -120,7 +120,7 @@ deleted — another host may be mid-conversation with it.
120
120
  Without Copilot Studio access the plugin still works, just less reliably; it logs a
121
121
  warning and carries on.
122
122
 
123
- Three things keep a turn on track:
123
+ Four things keep a turn on track:
124
124
 
125
125
  - **A tolerant parser.** M365 writes calls loosely: the command as a `command:` header,
126
126
  `filePath:` for `path`, quoted values, a copied `$ ` prompt, prose or an invented
@@ -132,6 +132,11 @@ Three things keep a turn on track:
132
132
  - **A pinned backend.** Every turn's connection carries
133
133
  `X-RoutingParameter-SessionKey`, which the reference project found stops long
134
134
  sessions running on a forked copy of the conversation.
135
+ - **Telling the model what ran.** Only the first tool block in a reply runs. When a
136
+ reply holds more, or goes on to predict its own result, the next turn starts with
137
+ one line saying so, so the model does not assume the rest ran. opencode's tool
138
+ errors arrive as plain text (`Error: …`) rather than a JSON envelope. In the 237
139
+ `quick` turns measured so far, no reply needed the note.
135
140
 
136
141
  Measured on one tenant on 2026-11-09 (`m365/quick`, opencode 2.2.5, 36 conversations,
137
142
  alternating builds), with and without the prompt trimming, nudge and routing header.
@@ -143,10 +148,21 @@ Both builds had the tolerant parser:
143
148
  | Find a value across six files | 6/6, 2.7 turns | 6/6, 2.0 turns |
144
149
  | Edit one config value, leave the rest | 6/6, 3.5 turns | 6/6, 4.5 turns (re-read the file to check, 3 of 6) |
145
150
 
146
- Every run made its tool call on the first turn, so the nudge never fired; that it
147
- recovers a give-up is tested offline only. No turn disengaged, and none ran on a
148
- forked conversation (`turnCount` rose by one each turn). Long sessions and the
149
- reasoning tones are not yet measured.
151
+ Every run made its tool call on the first turn, so the nudge never fired. No turn
152
+ disengaged, and none ran on a forked conversation (`turnCount` rose by one each turn).
153
+
154
+ Long sessions (2026-11-10, `m365/quick`, with all three): 4/4 solved, no nudges, no
155
+ forks.
156
+
157
+ | Task | Runs | Turns |
158
+ |---|---|---|
159
+ | Rename a function across ten modules, one edit at a time, then run the test | 2/2 | 37, 25 |
160
+ | Fix a 1,500-line file whose test fails, then fails again on a second bug | 2/2 | 8, 8 |
161
+
162
+ `turnCount` rose by one on every turn of the 37-turn session. Repeated calls were
163
+ progress checks (grep for what was left, re-reading a file after editing it), not loops.
164
+ These runs had the routing header, so they show it causes no harm. They don't show it
165
+ is needed, because no run without it was tried.
150
166
 
151
167
  ## opencode 2
152
168
 
@@ -203,16 +219,21 @@ in `apiKey`, or export the same `M365_PROXY_KEY` to opencode and leave `apiKey`
203
219
 
204
220
  ### Errors and the turn log
205
221
 
206
- When M365 refuses a turn, the proxy answers with an HTTP 422 so opencode does not
207
- retry it: opencode retries a 5xx or a 429 several times, which against a throttle only
208
- extends it. The error `code` says which refusal it was:
222
+ When M365 refuses a turn, the proxy reports it so that opencode does not retry it.
223
+ Retrying a throttle only extends it, and a refusal like a missing licence never changes.
224
+ opencode streams, so the refusal usually arrives inside a stream that already answered
225
+ 200. opencode then decides from the error body alone: it retries an error whose code
226
+ contains "unavailable", whose message says "try again" (M365's own refusals do), or
227
+ which mentions a rate limit. The proxy therefore sends type `invalid_request_error`,
228
+ avoids those words, and uses HTTP 422 when nothing has been streamed yet. In 2.2.0 a
229
+ licence refusal was retried ten times. The error `code` says which refusal it was:
209
230
 
210
231
  | Code | Meaning |
211
232
  |---|---|
212
233
  | `m365_throttled` | The account is throttled. Wait for a lull. |
213
- | `m365_unavailable` | M365 answered with its own refusal: no credits, a model this licence does not cover, or a dead tone |
234
+ | `m365_not_served` | M365 answered with its own refusal: no credits, a model this licence does not cover, or a dead tone. Called `m365_unavailable` up to 2.2.0 |
214
235
  | `m365_turn_rejected` | The server refused the request outright, typically a retired tone |
215
- | `m365_disengaged` | M365's filter refused to engage with the prompt |
236
+ | `m365_disengaged` | M365's filter refused to engage with the prompt. A disengaged conversation stays that way, so the proxy drops it: the next request opens a fresh conversation and replays the whole history |
216
237
 
217
238
  Set `M365_TURN_LOG=/path/to/turns.jsonl` before starting opencode to record one line
218
239
  per M365 turn: the raw reply, the tool calls parsed from it, and M365's diagnostics
@@ -244,13 +265,29 @@ task per run; small samples):
244
265
  | `m365/quick` | 5/5 |
245
266
  | `m365/m365-copilot` | 1/1 |
246
267
  | `m365/gpt-5.5` (same tone as `quick`) | 0/1 |
247
- | `m365/gpt-5.6` | 0/1 |
248
- | `m365/gpt-5.5-think-deeper` | 0/3 — says it has no file tool |
268
+ | `m365/gpt-5.6` | 0/1 (the reference project: 7/30), so its picker name says "unreliable tool calls" |
269
+ | `m365/gpt-5.5-think-deeper` | 0/3 — said it had no file tool; 4/4 with the relay framing, below |
249
270
 
250
271
  The reference project's README reports 100% tool compliance for `gpt-5.5-think-deeper`;
251
272
  its protocol notes (`m365-copilot-api.md`, quirk #13) say reasoning tones disengage with
252
273
  an agent attached. Our runs agree with the notes. Reasoning tones still serve plain chat.
253
274
 
275
+ The reasoning tones now get a different framing on tool turns. The tool block is
276
+ worded as the user asking to be guided through their own terminal, one command at a
277
+ time, pasting back the real output (the reference project's `relay`). A model that
278
+ doubts it can reach the workspace has nothing to doubt, because the user runs the
279
+ commands. Measured on `gpt-5.5-think-deeper` on 2026-11-10, 16 conversations:
280
+
281
+ | Framing | First reply said the tools were unavailable | Solved |
282
+ |---|---|---|
283
+ | Default, before the give-up nudge | 4/4 | 1/4 |
284
+ | Default, with the nudge | 8/8 | 5/8 |
285
+ | Relay, with the nudge | 0/4 | 4/4, with no nudge needed |
286
+
287
+ Claude tones stay on the agent, which M365 answers on GPT. The reference project ran
288
+ Claude without the agent and with `relay`, but an account with no Claude licence then
289
+ refuses every tool turn, and that could not be measured on a licensed account here.
290
+
254
291
  A non-default tone (Claude, the reasoning tones) only takes effect when **no** agent is
255
292
  attached — with one, M365 silently routes to GPT regardless. The proxy therefore attaches
256
293
  the agent only on turns that carry tools, so plain chat reaches the model the tone selects.
@@ -1,4 +1,4 @@
1
- import { b as writePrivateFile, f as POWERPLATFORM_SCOPE, u as BAP_SCOPE, v as createLogger, x as AGENT_FILE } from "./server-BRXlKFEJ.mjs";
1
+ import { S as AGENT_FILE, d as BAP_SCOPE, p as POWERPLATFORM_SCOPE, x as writePrivateFile, y as createLogger } from "./server-MqggZMCR.mjs";
2
2
  import { readFileSync } from "node:fs";
3
3
  import { createHash } from "node:crypto";
4
4
  // src/agent.ts
package/dist/cli.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { C as CONFIG_DIR, E as PROVIDER_ID, M as LOCAL_TITLE_MODEL, N as MODELS, S as CACHE_FILE, _ as createTokenClient, a as startServer, c as CopilotSession, j as DEFAULT_MODEL, k as mergeOpencodeConfig, w as SECRETS_FILE, x as AGENT_FILE } from "./server-BRXlKFEJ.mjs";
3
- import { t as getOrCreateAgent } from "./agent-CRSlpTfS.mjs";
2
+ import { A as mergeOpencodeConfig, C as CACHE_FILE, D as PROVIDER_ID, M as DEFAULT_MODEL, N as LOCAL_TITLE_MODEL, P as MODELS, S as AGENT_FILE, T as SECRETS_FILE, l as CopilotSession, o as startServer, v as createTokenClient, w as CONFIG_DIR } from "./server-MqggZMCR.mjs";
3
+ import { t as getOrCreateAgent } from "./agent-D3anZnuv.mjs";
4
4
  import { homedir } from "node:os";
5
5
  import { dirname, join, resolve } from "node:path";
6
6
  import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
@@ -70,7 +70,7 @@ to complete SSO/MFA by hand once — the only option on tenants with push-only
70
70
  MFA, FIDO2, or a federated IdP.`);
71
71
  }
72
72
  async function doLogin(args) {
73
- const { login } = await import("./login-B-1yNcEb.mjs");
73
+ const { login } = await import("./login-Dgv1sbgr.mjs");
74
74
  const interactive = args.includes("--interactive");
75
75
  try {
76
76
  const account = await login({
@@ -1,4 +1,4 @@
1
- import { F as __commonJSMin, I as __require, L as __toESM } from "./server-BRXlKFEJ.mjs";
1
+ import { I as __commonJSMin, L as __require, R as __toESM } from "./server-MqggZMCR.mjs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import http from "http";
4
4
  import crypto, { createHash as createHash$1 } from "crypto";
@@ -1,4 +1,4 @@
1
- import { C as CONFIG_DIR, d as CLIENT_ID, g as createCachePlugin, h as authCodeFromUrl, l as AUTHORITY, m as SYDNEY_SCOPES, o as object, p as REDIRECT_URI, s as string, v as createLogger, w as SECRETS_FILE, y as ensurePrivateDir } from "./server-BRXlKFEJ.mjs";
1
+ import { T as SECRETS_FILE, _ as createCachePlugin, b as ensurePrivateDir, c as string, f as CLIENT_ID, g as authCodeFromUrl, h as SYDNEY_SCOPES, m as REDIRECT_URI, s as object, u as AUTHORITY, w as CONFIG_DIR, y as createLogger } from "./server-MqggZMCR.mjs";
2
2
  import { join } from "node:path";
3
3
  import { chmodSync, existsSync, readFileSync, statSync } from "node:fs";
4
4
  // src/login.ts
@@ -96,7 +96,7 @@ async function login(options = {}) {
96
96
  const secrets = loadSecrets(options.secretsFile);
97
97
  const interactive = options.interactive ?? !secrets?.mfaSecret;
98
98
  if (!interactive && !secrets) throw new Error(`No credentials at ${options.secretsFile ?? SECRETS_FILE}. Create it with { "email", "password", "mfaSecret" }, or sign in interactively with --interactive.`);
99
- const { PublicClientApplication, CryptoProvider } = await import("./dist-CcVQZgN5.mjs");
99
+ const { PublicClientApplication, CryptoProvider } = await import("./dist-CsSmycf9.mjs");
100
100
  const app = new PublicClientApplication({
101
101
  auth: {
102
102
  clientId: CLIENT_ID,
package/dist/plugin.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { A as resolveOptions, D as buildModelInfos, E as PROVIDER_ID, O as buildProviderInfo, P as isLocalModel, T as PLUGIN_ID, _ as createTokenClient, a as startServer, j as DEFAULT_MODEL, r as SESSION_ID_HEADER, t as AUX_REQUEST_KIND_HEADER, v as createLogger } from "./server-BRXlKFEJ.mjs";
2
- import { t as getOrCreateAgent } from "./agent-CRSlpTfS.mjs";
1
+ import { D as PROVIDER_ID, E as PLUGIN_ID, F as isLocalModel, M as DEFAULT_MODEL, O as buildModelInfos, j as resolveOptions, k as buildProviderInfo, o as startServer, r as SESSION_ID_HEADER, t as AUX_REQUEST_KIND_HEADER, v as createTokenClient, y as createLogger } from "./server-MqggZMCR.mjs";
2
+ import { t as getOrCreateAgent } from "./agent-D3anZnuv.mjs";
3
3
  // src/runtime.ts
4
4
  /**
5
5
  * What the plugin stands on: the OpenAI-compatible proxy, started in-process (or an
@@ -61,8 +61,6 @@ 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-5.6", "GPT-5.6", "Gpt_5_6_Chat", false),
65
- m("gpt-5.6-quick", "GPT-5.6 (Quick)", "Gpt_5_6_Chat", false),
66
64
  m("gpt-5.6-think-deeper", "GPT-5.6 (Think Deeper)", "Gpt_5_6_Reasoning", true),
67
65
  m("gpt-5.5-think-deeper", "GPT-5.5 (Think Deeper)", "Gpt_5_5_Reasoning", true),
68
66
  m("gpt-5.5", "GPT-5.5", "Gpt_5_5_Chat", false),
@@ -71,6 +69,8 @@ const MODELS = [
71
69
  m("auto", "M365 Copilot (Auto)", "magic", false),
72
70
  m("quick", "GPT (Quick)", "Gpt_5_5_Chat", false),
73
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),
74
74
  m("claude-sonnet", "Claude Sonnet (via M365)", "Claude_Sonnet", false),
75
75
  m("claude", "Claude Sonnet (via M365)", "Claude_Sonnet", false),
76
76
  m("claude-sonnet-think-deeper", "Claude Sonnet (Think Deeper)", "Claude_Sonnet_Reasoning", true),
@@ -132,6 +132,29 @@ function isLocalModel(id) {
132
132
  function listModelIds() {
133
133
  return MODELS.map((model) => model.id);
134
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
+ }
135
158
  // src/fenced.ts
136
159
  /** Info strings we accept as "this is a shell block", beyond the tool's own name. */
137
160
  const SHELL_FENCE_INFOS = /* @__PURE__ */ new Set([
@@ -246,27 +269,13 @@ function shapeOf(tool) {
246
269
  function buildToolPrompt(tools, options = {}) {
247
270
  if (tools.length === 0) return "";
248
271
  const shell = findShellTool(tools);
272
+ if (options.framing === "relay") return buildRelayPrompt(tools, shell, options.sandbox);
249
273
  const useShellFraming = options.shellFraming ?? Boolean(shell);
250
274
  const lines = [];
251
275
  lines.push("<tools>");
252
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.");
253
277
  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
- }
278
+ for (const tool of tools) lines.push(...describeTool(tool), "");
270
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.`);
271
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.");
272
281
  else lines.push("Read each tool result before deciding the next step, rather than guessing what a command returned.");
@@ -274,6 +283,38 @@ function buildToolPrompt(tools, options = {}) {
274
283
  lines.push("</tools>");
275
284
  return lines.join("\n");
276
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
+ }
277
318
  function firstSentence(text) {
278
319
  const cleaned = (text.split("\n").find((candidate) => candidate.trim() !== "") ?? text).replace(/^\s*[-*•]\s*/, "");
279
320
  const stop = cleaned.indexOf(". ");
@@ -286,6 +327,37 @@ function placeholderFor(name, tool) {
286
327
  return `<${schema?.type ?? "string"}>${required ? "" : " (optional)"}`;
287
328
  }
288
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
+ /**
289
361
  * Extract fenced blocks, honouring the CommonMark rule that a fence is closed only by
290
362
  * a run of at least as many backticks as opened it.
291
363
  *
@@ -375,10 +447,13 @@ function stripInventedJson(text) {
375
447
  /** Parse a raw M365 response into OpenAI-shaped tool calls plus any prose. */
376
448
  function parseToolCalls(source, tools, options = {}) {
377
449
  const cleaned = stripInventedJson(source.replace(/\r\n?/g, "\n"));
378
- if (tools.length === 0) return {
450
+ const none = (text) => ({
379
451
  toolCalls: [],
380
- text: cleaned
381
- };
452
+ text,
453
+ skippedCalls: 0,
454
+ inventedResult: false
455
+ });
456
+ if (tools.length === 0) return none(cleaned);
382
457
  const shell = findShellTool(tools);
383
458
  const byName = new Map(tools.map((tool) => [tool.function.name.toLowerCase(), tool]));
384
459
  const toolFor = (fence) => {
@@ -388,29 +463,29 @@ function parseToolCalls(source, tools, options = {}) {
388
463
  const invented = cleaned.search(/<tool_(?:response|result)\b/i);
389
464
  const actionable = invented === -1 ? cleaned : cleaned.slice(0, invented);
390
465
  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
- };
466
+ if (!(fences.length > 0 && actionable.slice(0, fences[0].start).trim() === "" && Boolean(toolFor(fences[0]))) && isProseDocument(actionable)) return none(cleaned);
395
467
  const calls = [];
396
468
  const consumed = [];
469
+ let skippedCalls = 0;
397
470
  for (const fence of fences) {
398
471
  const tool = toolFor(fence);
399
472
  if (!tool) continue;
473
+ if (calls.length > 0 && !options.allowMultiple) {
474
+ skippedCalls += 1;
475
+ continue;
476
+ }
400
477
  calls.push({
401
478
  name: tool.function.name,
402
479
  arguments: parseFenceBody(fence.body, tool)
403
480
  });
404
481
  consumed.push(fence);
405
- if (!options.allowMultiple) break;
406
482
  }
407
- if (calls.length === 0) return {
408
- toolCalls: [],
409
- text: cleaned
410
- };
483
+ if (calls.length === 0) return none(cleaned);
411
484
  return {
412
485
  toolCalls: calls,
413
- text: ""
486
+ text: "",
487
+ skippedCalls,
488
+ inventedResult: invented !== -1
414
489
  };
415
490
  }
416
491
  /** Names models use for a file path, compared without case or underscores. */
@@ -1036,7 +1111,7 @@ function createTokenClient(options = {}) {
1036
1111
  const cache = /* @__PURE__ */ new Map();
1037
1112
  async function client() {
1038
1113
  if (app) return app;
1039
- const { PublicClientApplication } = await import("./dist-CcVQZgN5.mjs");
1114
+ const { PublicClientApplication } = await import("./dist-CsSmycf9.mjs");
1040
1115
  app = new PublicClientApplication({
1041
1116
  auth: {
1042
1117
  clientId: CLIENT_ID,
@@ -10716,12 +10791,15 @@ function condenseSystemPrompt(text, tools, options = {}) {
10716
10791
  if (requires.some((name) => toolNames.has(name))) continue;
10717
10792
  result = result.replace(new RegExp(`<${tag}>[\\s\\S]*?</${tag}>`, "g"), "");
10718
10793
  }
10719
- if (!toolNames.has("execute")) {
10720
- result = result.replace(/^# Code Mode\n[\s\S]*?(?=^# |^Skills provide |^<[a-z_]+>|(?![\s\S]))/m, "");
10721
- result = dropLines(result, /`execute`/);
10722
- }
10723
- if (!toolNames.has("skill")) result = dropLines(result, /^Skills provide |\bskill tool\b|invoke a skill directly/);
10724
- result = dropLines(result, /^- Prefer parallelizing independent tool calls|^- Prefer dedicated tools over shell commands/);
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
+ });
10725
10803
  if (options.replaceProseWith !== void 0) {
10726
10804
  const { leadingBlocks, instructions, blocks } = splitSystemPrompt(result);
10727
10805
  result = [
@@ -10733,6 +10811,28 @@ function condenseSystemPrompt(text, tools, options = {}) {
10733
10811
  }
10734
10812
  return result.replace(/\n{3,}/g, "\n\n").trim();
10735
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
+ }
10736
10836
  /** Remove every line matching `pattern`. */
10737
10837
  function dropLines(text, pattern) {
10738
10838
  return text.split("\n").filter((line) => !pattern.test(line)).join("\n");
@@ -10794,9 +10894,14 @@ function buildTurnPrompt(messages, tools, sentMessageCount, options = {}) {
10794
10894
  const systemText = messages.filter((message) => message.role === "system" || message.role === "developer").map(contentOf).filter(Boolean).join("\n\n");
10795
10895
  if (systemText) parts.push(condenseSystemPrompt(systemText, tools, { ...options.leanSystemPrompt !== void 0 ? { replaceProseWith: options.leanSystemPrompt } : {} }));
10796
10896
  }
10797
- if (tools.length > 0) parts.push(buildToolPrompt(tools, { firstTurn: isFirstTurn }));
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
+ }));
10798
10902
  const callsById = /* @__PURE__ */ new Map();
10799
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);
10800
10905
  for (const message of messages.slice(sentMessageCount)) {
10801
10906
  if (message.role === "system" || message.role === "developer") continue;
10802
10907
  if (message.role === "tool") {
@@ -10806,6 +10911,7 @@ function buildTurnPrompt(messages, tools, sentMessageCount, options = {}) {
10806
10911
  if (message.role === "assistant") {
10807
10912
  const text = contentOf(message);
10808
10913
  if (text) parts.push(text);
10914
+ for (const call of message.tool_calls ?? []) parts.push(renderToolCall(call.function.name, call.function.arguments, tools));
10809
10915
  continue;
10810
10916
  }
10811
10917
  const text = contentOf(message) || (hasImagePart(message) ? "(See the attached image.)" : "");
@@ -10825,7 +10931,21 @@ function renderToolResult(message, callsById) {
10825
10931
  if (call?.name) attributes.push(`tool="${escapeAttribute(call.name)}"`);
10826
10932
  const summary = summariseArguments(call?.arguments);
10827
10933
  if (summary) attributes.push(`command="${escapeAttribute(summary)}"`);
10828
- 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
+ }
10829
10949
  }
10830
10950
  /** The most identifying argument value, for the label. */
10831
10951
  function summariseArguments(raw) {
@@ -10973,7 +11093,8 @@ function looksLikeGiveUp(reply) {
10973
11093
  * Disengaged filter. Once tools have run it must not say nothing has — a prompt that
10974
11094
  * contradicts the transcript is one the model stops trusting.
10975
11095
  */
10976
- function nudgeFor(midTask) {
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.";
10977
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.";
10978
11099
  }
10979
11100
  // src/server.ts
@@ -11192,8 +11313,16 @@ async function runTurn(request, response, context, body, conversation, model, to
11192
11313
  });
11193
11314
  const effectiveTools = model.grounded ? [] : tools;
11194
11315
  const images = collectImages(body.messages, conversation.sentMessageCount);
11195
- const prompt = buildTurnPrompt(body.messages, effectiveTools, conversation.sentMessageCount, { ...context.deps.leanSystemPrompt !== void 0 ? { leanSystemPrompt: context.deps.leanSystemPrompt } : {} });
11196
- const agent = effectiveTools.length > 0 ? await context.agentId() : null;
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;
11197
11326
  const abort = new AbortController();
11198
11327
  request.on("close", () => {
11199
11328
  if (!response.writableEnded) abort.abort();
@@ -11208,6 +11337,7 @@ async function runTurn(request, response, context, body, conversation, model, to
11208
11337
  model: model.id,
11209
11338
  tone: model.tone,
11210
11339
  agent: Boolean(agent),
11340
+ ...effectiveTools.length > 0 ? { framing: route.framing } : {},
11211
11341
  tools: effectiveTools.map((tool) => tool.function.name),
11212
11342
  ...fields
11213
11343
  });
@@ -11236,10 +11366,12 @@ async function runTurn(request, response, context, body, conversation, model, to
11236
11366
  if (effectiveTools.length > 0 && parseToolCalls(result.text, effectiveTools).toolCalls.length === 0 && looksLikeGiveUp(result.text)) {
11237
11367
  recordTurn(result);
11238
11368
  const midTask = body.messages.some((message) => message.role === "tool");
11239
- result = await conversation.session.run(nudgeFor(midTask), turnOptions);
11369
+ result = await conversation.session.run(nudgeFor(midTask, route.framing), turnOptions);
11240
11370
  recordTurn(result, { nudged: true });
11241
11371
  } else recordTurn(result);
11242
11372
  conversation.sentMessageCount = body.messages.length + 1;
11373
+ const allowMultiple = context.deps.allowMultiTool ?? false;
11374
+ conversation.note = noteAbout(parseToolCalls(result.text, effectiveTools, { allowMultiple }));
11243
11375
  if (!streaming) {
11244
11376
  sendJson(response, 200, buildCompletion(result, {
11245
11377
  model: model.id,
@@ -11251,9 +11383,30 @@ async function runTurn(request, response, context, body, conversation, model, to
11251
11383
  finishStream(response, streamId, model.id, result, effectiveTools, canStreamText, context.deps.allowMultiTool ?? false);
11252
11384
  } catch (error) {
11253
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
+ }
11254
11390
  handleTurnFailure(response, error, streaming, effectiveTools.length);
11255
11391
  }
11256
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
+ }
11257
11410
  /** Emit the closing frames of a streamed turn. */
11258
11411
  function finishStream(response, streamId, model, result, tools, alreadyStreamedText, allowMultiple) {
11259
11412
  const { toolCalls, text } = parseToolCalls(result.text, tools, { allowMultiple });
@@ -11275,20 +11428,19 @@ function handleTurnFailure(response, error, streaming, toolCount) {
11275
11428
  return;
11276
11429
  }
11277
11430
  if (error instanceof DisengagedError) {
11278
- const hint = 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. Retrying will not help; reduce the toolset or simplify the prompt.";
11279
- finishWithError(response, streaming, NON_RETRYABLE, "m365_disengaged", `M365 Copilot disengaged.${hint}`);
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."}`);
11280
11432
  return;
11281
11433
  }
11282
11434
  if (error instanceof M365ThrottledError) {
11283
- finishWithError(response, streaming, NON_RETRYABLE, "m365_throttled", error.message);
11435
+ refuse(response, streaming, "m365_throttled", error.message);
11284
11436
  return;
11285
11437
  }
11286
11438
  if (error instanceof M365UnavailableError) {
11287
- finishWithError(response, streaming, NON_RETRYABLE, "m365_unavailable", error.message);
11439
+ refuse(response, streaming, "m365_not_served", error.message);
11288
11440
  return;
11289
11441
  }
11290
11442
  if (error instanceof TurnRejectedError) {
11291
- finishWithError(response, streaming, NON_RETRYABLE, "m365_turn_rejected", error.message);
11443
+ refuse(response, streaming, "m365_turn_rejected", error.message);
11292
11444
  return;
11293
11445
  }
11294
11446
  const message = error instanceof Error ? error.message : String(error);
@@ -11298,17 +11450,35 @@ function handleTurnFailure(response, error, streaming, toolCount) {
11298
11450
  }
11299
11451
  finishWithError(response, streaming, 502, "upstream_error", message);
11300
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
+ }
11301
11467
  /** Report an error, in whichever shape the client is already reading. */
11302
- function finishWithError(response, streaming, status, code, message) {
11468
+ function finishWithError(response, streaming, status, code, message, type = code) {
11303
11469
  if (!streaming) {
11304
- sendError(response, status, code, message);
11470
+ if (!response.writableEnded) sendJson(response, status, { error: {
11471
+ message,
11472
+ type,
11473
+ code
11474
+ } });
11305
11475
  return;
11306
11476
  }
11307
11477
  if (!response.writableEnded) {
11308
11478
  response.write(`data: ${JSON.stringify({ error: {
11309
11479
  message,
11310
11480
  code,
11311
- type: code
11481
+ type
11312
11482
  } })}\n\n`);
11313
11483
  response.write(streamDone());
11314
11484
  response.end();
@@ -11373,4 +11543,4 @@ async function readBody(request, limit) {
11373
11543
  }
11374
11544
  return Buffer.concat(chunks).toString("utf8");
11375
11545
  }
11376
- export { resolveOptions as A, CONFIG_DIR as C, buildModelInfos as D, PROVIDER_ID as E, __commonJSMin as F, __require as I, __toESM as L, LOCAL_TITLE_MODEL as M, MODELS as N, buildProviderInfo as O, isLocalModel as P, CACHE_FILE as S, PLUGIN_ID as T, createTokenClient as _, startServer as a, writePrivateFile as b, CopilotSession as c, CLIENT_ID as d, POWERPLATFORM_SCOPE as f, createCachePlugin as g, authCodeFromUrl as h, generateApiKey as i, DEFAULT_MODEL as j, mergeOpencodeConfig as k, AUTHORITY as l, SYDNEY_SCOPES as m, DEFAULT_MAX_BODY_BYTES as n, object as o, REDIRECT_URI as p, SESSION_ID_HEADER as r, string as s, AUX_REQUEST_KIND_HEADER as t, BAP_SCOPE as u, createLogger as v, SECRETS_FILE as w, AGENT_FILE as x, ensurePrivateDir as y };
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 };
package/dist/server.d.mts CHANGED
@@ -122,6 +122,8 @@ export interface TurnLogEntry {
122
122
  model: string;
123
123
  tone: string | null;
124
124
  agent: boolean;
125
+ /** How the tool block was worded, on a tool turn. */
126
+ framing?: "default" | "relay";
125
127
  tools: string[];
126
128
  reply?: string;
127
129
  toolCalls?: string[];
@@ -134,4 +136,17 @@ export interface TurnLogEntry {
134
136
  nudged?: boolean;
135
137
  error?: string;
136
138
  }
139
+ /**
140
+ * One line for the next turn when the last reply was not run as written. Without
141
+ * it the model assumes every block it wrote ran, and the reference project measured
142
+ * early "task already complete" endings falling from 9 in 56 runs to 0 in 70 once
143
+ * it was told.
144
+ */
145
+ export declare function noteAbout(parsed: {
146
+ toolCalls: {
147
+ name: string;
148
+ }[];
149
+ skippedCalls: number;
150
+ inventedResult: boolean;
151
+ }): string | undefined;
137
152
  export {};
package/dist/server.mjs CHANGED
@@ -1 +1 @@
1
- export { t as AUX_REQUEST_KIND_HEADER, n as DEFAULT_MAX_BODY_BYTES, j as DEFAULT_MODEL, r as SESSION_ID_HEADER, i as generateApiKey, a as startServer } from "./server-BRXlKFEJ.mjs";
1
+ export { t as AUX_REQUEST_KIND_HEADER, n as DEFAULT_MAX_BODY_BYTES, M as DEFAULT_MODEL, r as SESSION_ID_HEADER, i as generateApiKey, a as noteAbout, o as startServer } from "./server-MqggZMCR.mjs";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-m365-copilot",
3
- "version": "2.2.0",
3
+ "version": "2.2.1",
4
4
  "description": "Use your org's Microsoft 365 Copilot as the model backend for opencode",
5
5
  "license": "MIT",
6
6
  "type": "module",