opencode-m365-copilot 2.1.1 → 2.2.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 CHANGED
@@ -70,12 +70,20 @@ The proxy sees the final request, so it is the one place the trim reliably lands
70
70
 
71
71
  What gets dropped:
72
72
 
73
- - **Tools** — keeps `bash`, `read`, `grep`, and whichever editing tool is present
74
- (`apply_patch` in 1.18.18, `edit`/`write` in others). Drops `glob`, `skill`, `task`,
75
- `todowrite`, `webfetch`, `websearch`, `lsp`, `question`.
73
+ - **Tools** — keeps the shell tool under whatever name the harness gives it (`shell`
74
+ in opencode 2, `bash` before), `read`, `grep`, and the editing tools (`edit`/`write`,
75
+ or `apply_patch`). On opencode 2.2.5 that is five of thirteen; `execute`, `glob`,
76
+ `skill`, `subagent`, `webfetch`, `websearch` and `question` are dropped.
76
77
  - **Capability catalogues** — `<available_skills>` is removed when no `skill` tool
77
78
  survives the trim, because it advertises capabilities nothing can invoke. `<env>` and
78
79
  other structured context are kept.
80
+ - **Text about dropped tools** — opencode 2's "Code Mode" section says the listed tools
81
+ only work inside `execute`, which the trim removes, so the model was being told its
82
+ tools were unusable. That section, any line naming `execute`, and the skills
83
+ paragraph go with their tools, as do two harness lines that contradict the
84
+ contract ("prefer parallelizing tool calls", "prefer dedicated tools over shell
85
+ commands"). On opencode 2.2.5 this takes the system prompt from about 8,000
86
+ characters to about 2,000.
79
87
  - **The harness's prose system prompt** — replaced with a short one, but **off by
80
88
  default**. A long, polished assistant prompt measurably reduces M365's tool
81
89
  compliance on another harness's numbers; that is a borrowed result we have not
@@ -83,7 +91,7 @@ What gets dropped:
83
91
  never dropped either way: opencode injects `AGENTS.md` and global rules as prose
84
92
  inside the system message, and those sections are preserved verbatim.
85
93
 
86
- `bash` is never dropped. M365's chat-tuned model will not "act as an agent" on request,
94
+ The shell tool is never dropped. M365's chat-tuned model will not "act as an agent" on request,
87
95
  but it *will* reflexively write a ```` ```bash ```` block — routing that block to the
88
96
  shell tool is the single lever that makes tool calling work at all.
89
97
 
@@ -112,6 +120,34 @@ deleted — another host may be mid-conversation with it.
112
120
  Without Copilot Studio access the plugin still works, just less reliably; it logs a
113
121
  warning and carries on.
114
122
 
123
+ Three things keep a turn on track:
124
+
125
+ - **A tolerant parser.** M365 writes calls loosely: the command as a `command:` header,
126
+ `filePath:` for `path`, quoted values, a copied `$ ` prompt, prose or an invented
127
+ `<tool_response>` after the block. These are read as the call the model meant.
128
+ - **One nudge after a give-up.** Chat tones sometimes answer a tool turn with "no tool
129
+ is available" without trying. The proxy then asks once more, softly, in the same
130
+ conversation (one extra message, no new conversation), worded differently once
131
+ tools have already run.
132
+ - **A pinned backend.** Every turn's connection carries
133
+ `X-RoutingParameter-SessionKey`, which the reference project found stops long
134
+ sessions running on a forked copy of the conversation.
135
+
136
+ Measured on one tenant on 2026-11-09 (`m365/quick`, opencode 2.2.5, 36 conversations,
137
+ alternating builds), with and without the prompt trimming, nudge and routing header.
138
+ Both builds had the tolerant parser:
139
+
140
+ | Task | Without | With |
141
+ |---|---|---|
142
+ | Fix a bug, then rerun its test | 6/6, 5.3 turns | 6/6, 5.0 turns |
143
+ | Find a value across six files | 6/6, 2.7 turns | 6/6, 2.0 turns |
144
+ | 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
+
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.
150
+
115
151
  ## opencode 2
116
152
 
117
153
  This is an opencode 2 plugin (`@opencode/cli`, `@opencode/plugin`): its default export
@@ -140,7 +176,7 @@ stub rather than Microsoft: the plugin loads from a directory, registers all 21
140
176
  an attached image is uploaded and attached to the turn, and the session title is
141
177
  answered locally — one chat turn reaches the backend, not two. The catalog records are
142
178
  also checked against the real `@opencode/plugin` schema constructors in the test suite.
143
- Nothing here has been run against a live M365 tenant.
179
+ That stub run says nothing about Microsoft's side; see [Development](#development) for what has been run live.
144
180
 
145
181
  ## Configuration
146
182
 
@@ -165,6 +201,24 @@ hands it to opencode itself. Only a standalone `opencode-m365 serve` proxy needs
165
201
  `serve` prints its key, or takes a fixed one from `M365_PROXY_KEY`. Either put that key
166
202
  in `apiKey`, or export the same `M365_PROXY_KEY` to opencode and leave `apiKey` out.
167
203
 
204
+ ### Errors and the turn log
205
+
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:
209
+
210
+ | Code | Meaning |
211
+ |---|---|
212
+ | `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 |
214
+ | `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 |
216
+
217
+ Set `M365_TURN_LOG=/path/to/turns.jsonl` before starting opencode to record one line
218
+ per M365 turn: the raw reply, the tool calls parsed from it, and M365's diagnostics
219
+ (`contentOrigin`, `turnCount`, throttle and classifier scores). The file is
220
+ owner-only, and off by default because a reply can quote anything from the workspace.
221
+
168
222
  ### Why session titles are answered locally
169
223
 
170
224
  opencode titles every new session with a model call on your main model, which on M365
@@ -180,16 +234,22 @@ on the real model — they are real work, and only titling opens the extra conve
180
234
 
181
235
  ## Models
182
236
 
183
- Models are selected by an M365 *tone*, not a model id. `m365/gpt-5.5-think-deeper` is the
184
- default.
237
+ Models are selected by an M365 *tone*, not a model id. `m365/quick` is the default.
238
+
239
+ Tool-calling on a live tenant (2026-11-09, one non-Premium account, a single file-read
240
+ task per run; small samples):
241
+
242
+ | Model | Made the tool call |
243
+ |---|---|
244
+ | `m365/quick` | 5/5 |
245
+ | `m365/m365-copilot` | 1/1 |
246
+ | `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 |
185
249
 
186
- > **A conflict worth knowing about.** The reference project's README recommends
187
- > `gpt-5.5-think-deeper` and reports 100% tool compliance with the agent plus
188
- > fenced/shell-routing. Its own protocol notes (`m365-copilot-api.md`, quirk #13) say the
189
- > opposite — that reasoning tones meta-analyse the injected prompt and disengage, and
190
- > only `magic`/`*_Quick` work with an agent attached. The README is the newer
191
- > measurement, so it is the default here; if you see disengagement on tool turns, try
192
- > `m365/quick` or `m365/m365-copilot`.
250
+ The reference project's README reports 100% tool compliance for `gpt-5.5-think-deeper`;
251
+ its protocol notes (`m365-copilot-api.md`, quirk #13) say reasoning tones disengage with
252
+ an agent attached. Our runs agree with the notes. Reasoning tones still serve plain chat.
193
253
 
194
254
  A non-default tone (Claude, the reasoning tones) only takes effect when **no** agent is
195
255
  attached — with one, M365 silently routes to GPT regardless. The proxy therefore attaches
@@ -217,7 +277,8 @@ What `WorkSearch` reaches (all verified against a live tenant, except where note
217
277
  | Third-party **Graph connectors** (Jira, ServiceNow, …) | ✅ *if your admin configured them* |
218
278
 
219
279
  Select one in opencode (the model picker, or pin a `work` sub-agent to it) when you want
220
- this context; every other model stays coding/web-only and never reaches your account. A
280
+ this context; they are listed as `Work · …`. Every other model is listed as `Code · …`,
281
+ stays coding/web-only and never reaches your account. A
221
282
  grounded turn switches the request to the Outlook side-pane scenario, sends that surface's
222
283
  feature variants, and attaches the built-in agent with the `WorkSearch` capability — the
223
284
  combination that actually grounds on the signed-in account — then strips Copilot's inline
@@ -268,7 +329,8 @@ opencode-m365 login [--interactive] # sign in
268
329
  opencode-m365 setup [--local] # register the plugin with opencode
269
330
  opencode-m365 serve [--port 4141] # run the proxy standalone, for any OpenAI client
270
331
  # (send its key as `Authorization: Bearer`)
271
- opencode-m365 doctor # check auth, agent, proxy and opencode wiring
332
+ opencode-m365 doctor [--live] # check auth, agent, proxy and opencode wiring
333
+ # (--live sends one short message per model tone)
272
334
  ```
273
335
 
274
336
  ## Images
@@ -316,12 +378,12 @@ Tests run against a stub SignalR server (`test/stub-copilot.ts`) that speaks the
316
378
  framing, so a full turn — including the mandatory `Metrics` frame, ping handling,
317
379
  Disengaged detection and the stop-on-abort frame — is exercised offline.
318
380
 
319
- **No live M365 traffic has been run against this implementation.** Everything above about
320
- opencode's behaviour is measured; everything about M365's behaviour is implemented from
321
- the protocol notes in
381
+ Chat, tool calling and agent provisioning have been run against one live tenant, through
382
+ opencode 2.2.5. Image upload has not, and file edits, shell commands and multi-step tasks
383
+ have not been exercised there. Other M365 behaviour is implemented from the protocol notes in
322
384
  [cramt/m365-copilot-proxy](https://github.com/cramt/m365-copilot-proxy) (MIT), whose
323
- `docs/` are the source of truth for this surface. Run `opencode-m365 doctor` against your
324
- own tenant before trusting it.
385
+ `docs/` are the source of truth for this surface. Run `opencode-m365 doctor --live`
386
+ against your own tenant before trusting it.
325
387
 
326
388
  ## Credit
327
389
 
@@ -1,4 +1,4 @@
1
- import { _ as createLogger, b as AGENT_FILE, d as POWERPLATFORM_SCOPE, l as BAP_SCOPE, y as writePrivateFile } from "./server-MaGKSmnd.mjs";
1
+ import { b as writePrivateFile, f as POWERPLATFORM_SCOPE, u as BAP_SCOPE, v as createLogger, x as AGENT_FILE } from "./server-BRXlKFEJ.mjs";
2
2
  import { readFileSync } from "node:fs";
3
3
  import { createHash } from "node:crypto";
4
4
  // src/agent.ts
@@ -28,6 +28,16 @@ import { createHash } from "node:crypto";
28
28
  const log = createLogger("agent");
29
29
  const BAP_ENVIRONMENT_URL = "https://api.bap.microsoft.com/providers/Microsoft.BusinessAppPlatform/environments/~default?api-version=2023-06-01";
30
30
  const COPILOT_STUDIO_API_VERSION = "2022-03-01-preview";
31
+ /** A plain 48×48 square: the portal always sends an icon, so we do too. */
32
+ const BOT_ICON_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAIAAADYYG7QAAAAOklEQVR42u3OQQ0AAAgEoCtjMuNbwhbOBxsBSPW8EiEhISEhISEhISEhISEhISEhISEhISEhISGhOwsQ7wvEcqrbYwAAAABJRU5ErkJggg==";
33
+ const EMPTY_GUID = "00000000-0000-0000-0000-000000000000";
34
+ function studioHeaders(token) {
35
+ return {
36
+ Authorization: `Bearer ${token}`,
37
+ "Content-Type": "application/json",
38
+ "x-ms-user-agent": "PVA-Portal/1.0.0 (Web; ReactNative: false)"
39
+ };
40
+ }
31
41
  /**
32
42
  * The agent's server-side instructions.
33
43
  *
@@ -52,28 +62,24 @@ function agentInstructions() {
52
62
  function agentNameFor(instructions) {
53
63
  return `m365-tool-agent-${createHash("sha256").update(instructions).digest("hex").slice(0, 8)}`;
54
64
  }
55
- /** The id M365 expects in `threadLevelGptId` / `gpts`. */
65
+ /** The id M365 expects in `threadLevelGptId` / `gpts`. `titleId` arrives already `T_`-prefixed. */
56
66
  function buildAgentId(titleId, botId) {
57
- return `T_${titleId}.${botId}.gpt.default`;
67
+ return `${titleId}.${botId}.gpt.default`;
58
68
  }
59
69
  /**
60
- * Power Platform hosts to try for this environment.
70
+ * The Power Platform host for this environment.
61
71
  *
62
- * The obvious full-length label frequently does not resolve; the host that works has
63
- * the last two characters trimmed. Rather than pick one, probe both.
72
+ * The id is split across two DNS labels: all but its last two characters, then those
73
+ * two. It looks like a fixed `.df.` on any tenant whose id happens to end in `df`.
64
74
  */
65
- function environmentHostCandidates(envId) {
66
- const suffix = "df.environment.api.powerplatform.com";
67
- return [
68
- `default${envId}.${suffix}`,
69
- `default${envId.slice(0, -1)}.${suffix}`,
70
- `default${envId.slice(0, -2)}.${suffix}`
71
- ];
75
+ function environmentHost(envId) {
76
+ return `default${envId.slice(0, -2)}.${envId.slice(-2)}.environment.api.powerplatform.com`;
72
77
  }
73
- /** First candidate host that actually resolves. */
78
+ /** The environment's host, checked in DNS so a wrong one fails with a usable message. */
74
79
  async function resolveEnvironmentHost(envId, resolveDns, override) {
75
80
  if (override) return override;
76
- for (const candidate of environmentHostCandidates(envId)) if (await resolveDns(candidate)) return candidate;
81
+ const host = environmentHost(envId);
82
+ if (await resolveDns(host)) return host;
77
83
  throw new Error(`Could not resolve a Power Platform host for environment ${envId}. Set M365_POWERPLATFORM_HOST to override.`);
78
84
  }
79
85
  /** Default resolver: a DNS lookup, treating any failure as "does not resolve". */
@@ -89,7 +95,8 @@ const dnsResolver = async (host) => {
89
95
  /**
90
96
  * Resolve the declarative agent id, provisioning one if the tenant has none.
91
97
  *
92
- * Order: local cache → the tenant's existing bots → create + publish.
98
+ * Order: local cache → the tenant's existing bot, else create → publish (which is also
99
+ * the only way to learn an existing bot's title id).
93
100
  */
94
101
  async function getOrCreateAgent(deps) {
95
102
  const cacheFile = deps.cacheFile ?? AGENT_FILE;
@@ -103,17 +110,7 @@ async function getOrCreateAgent(deps) {
103
110
  const resolveDns = deps.resolveDns ?? dnsResolver;
104
111
  const host = await resolveEnvironmentHost(await discoverEnvironmentId(doFetch, deps.getTokenForScope), resolveDns, deps.hostOverride ?? process.env.M365_POWERPLATFORM_HOST);
105
112
  const token = await deps.getTokenForScope([POWERPLATFORM_SCOPE]);
106
- const existing = await findBot(doFetch, host, token, wantedName);
107
- if (existing) {
108
- const agentId = buildAgentId(existing.titleId, existing.botId);
109
- writeCache(cacheFile, {
110
- agentId,
111
- instructionsHash: wantedName
112
- });
113
- log.info("reusing existing agent", agentId);
114
- return agentId;
115
- }
116
- const botId = await createBot(doFetch, host, token, wantedName);
113
+ const botId = await findBot(doFetch, host, token, wantedName) ?? await createBot(doFetch, host, token, wantedName);
117
114
  const agentId = buildAgentId(await publishBot(doFetch, host, token, botId), botId);
118
115
  writeCache(cacheFile, {
119
116
  agentId,
@@ -136,55 +133,111 @@ async function discoverEnvironmentId(doFetch, getTokenForScope) {
136
133
  * Find a bot by name.
137
134
  *
138
135
  * Name lookup is reliable because Copilot Studio reflects the display name we set
139
- * into `shortBotName` byte for byte — hyphens, length and case all survive.
136
+ * into `shortBotName` byte for byte — hyphens, length and case all survive. The list
137
+ * carries no title id.
140
138
  */
141
139
  async function findBot(doFetch, host, token, name) {
142
- const response = await doFetch(`https://${host}/copilotstudio/minimalBots/api/botlist?api-version=${COPILOT_STUDIO_API_VERSION}`, { headers: { Authorization: `Bearer ${token}` } });
140
+ const response = await doFetch(`https://${host}/copilotstudio/minimalBots/api?api-version=${COPILOT_STUDIO_API_VERSION}`, { headers: studioHeaders(token) });
143
141
  if (!response.ok) throw new AgentHttpError(await describeFailure("listing agents", response), response.status);
144
- const body = await response.json();
145
- const match = (body?.value ?? body?.bots ?? []).find((bot) => bot?.shortBotName === name || bot?.displayName === name);
146
- if (!match) return void 0;
147
- if (!match.titleId || !match.botId) return void 0;
142
+ const bots = await response.json();
143
+ if (!Array.isArray(bots)) throw new Error("Copilot Studio returned an unexpected agent list");
144
+ return bots.find((bot) => bot?.shortBotName === name)?.botId;
145
+ }
146
+ /** The change set the Copilot Studio portal posts to create a GPT-template bot. */
147
+ function createBotBody(name) {
148
+ const noDiagnostics = { diagnostics: [] };
148
149
  return {
149
- botId: match.botId,
150
- titleId: match.titleId
150
+ botComponentChanges: [{
151
+ $kind: "BotComponentInsert",
152
+ component: {
153
+ ...noDiagnostics,
154
+ $kind: "GptComponent",
155
+ id: EMPTY_GUID,
156
+ displayName: name,
157
+ description: "Tool-calling format instructions for an OpenAI-compatible bridge.",
158
+ schemaName: `${EMPTY_GUID}.gpt.default`,
159
+ metadata: {
160
+ ...noDiagnostics,
161
+ $kind: "GptComponentMetadata",
162
+ tools: [],
163
+ conversationStarters: [],
164
+ instructions: {
165
+ ...noDiagnostics,
166
+ $kind: "TemplateLine",
167
+ segments: [{
168
+ ...noDiagnostics,
169
+ $kind: "TextSegment",
170
+ value: agentInstructions()
171
+ }]
172
+ },
173
+ knowledgeSources: {
174
+ ...noDiagnostics,
175
+ $kind: "SearchAllKnowledgeSources"
176
+ },
177
+ gptCapabilities: {
178
+ ...noDiagnostics,
179
+ $kind: "GptCapabilities",
180
+ codeInterpreter: false,
181
+ generateImages: false,
182
+ webBrowsing: false,
183
+ searchOneDriveAndSharePoint: false,
184
+ searchTeams: false,
185
+ searchMeetings: false,
186
+ searchEmails: false,
187
+ searchPeople: false
188
+ },
189
+ aISettings: {
190
+ ...noDiagnostics,
191
+ $kind: "AISettings",
192
+ useModelKnowledge: true
193
+ }
194
+ }
195
+ }
196
+ }],
197
+ cloudFlowDefinitionChanges: [],
198
+ connectorDefinitionChanges: [],
199
+ environmentVariableChanges: [],
200
+ connectionReferenceChanges: [],
201
+ aIPluginOperationChanges: [],
202
+ componentCollectionChanges: [],
203
+ dataverseTableSearchChanges: [],
204
+ dataverseTableSearchEntityConfigurationChanges: [],
205
+ dataverseTableSearchGlossaryConfigurationChanges: [],
206
+ dataverseTableSearchEntityColumnSynonymChanges: [],
207
+ aIModelChanges: [],
208
+ connectedAgentDefinitionChanges: [],
209
+ bot: {
210
+ $kind: "BotEntity",
211
+ authorizedSecurityGroupIds: [],
212
+ supportedLanguages: [],
213
+ diagnostics: [],
214
+ displayName: name,
215
+ language: 1033,
216
+ schemaName: EMPTY_GUID,
217
+ template: "gpt-1.1.0",
218
+ iconBase64: BOT_ICON_BASE64
219
+ }
151
220
  };
152
221
  }
153
222
  async function createBot(doFetch, host, token, name) {
154
223
  const response = await doFetch(`https://${host}/copilotstudio/minimalBots/api?api-version=${COPILOT_STUDIO_API_VERSION}`, {
155
224
  method: "POST",
156
- headers: {
157
- Authorization: `Bearer ${token}`,
158
- "Content-Type": "application/json"
159
- },
160
- body: JSON.stringify({
161
- displayName: name,
162
- description: "Tool-calling format instructions for an OpenAI-compatible bridge.",
163
- gptComponent: {
164
- instructions: agentInstructions(),
165
- conversationStarters: [],
166
- aISettings: { useModelKnowledge: true }
167
- }
168
- })
225
+ headers: studioHeaders(token),
226
+ body: JSON.stringify(createBotBody(name))
169
227
  });
170
228
  if (!response.ok) throw new AgentHttpError(await describeFailure("creating the agent", response), response.status);
171
229
  const body = await response.json();
172
- const botId = body?.botId ?? body?.id;
230
+ const botId = body?.bot?.schemaName ?? body?.bot?.cdsBotId;
173
231
  if (!botId) throw new Error("Copilot Studio created an agent but returned no bot id");
174
232
  return botId;
175
233
  }
176
234
  async function publishBot(doFetch, host, token, botId) {
177
- const response = await doFetch(`https://${host}/copilotstudio/minimalBots/api/publish?api-version=${COPILOT_STUDIO_API_VERSION}&botId=${encodeURIComponent(botId)}`, {
235
+ const response = await doFetch(`https://${host}/copilotstudio/minimalBots/api/${encodeURIComponent(botId)}/publish?api-version=${COPILOT_STUDIO_API_VERSION}`, {
178
236
  method: "POST",
179
- headers: {
180
- Authorization: `Bearer ${token}`,
181
- "Content-Type": "application/json"
182
- },
183
- body: JSON.stringify({ botId })
237
+ headers: studioHeaders(token)
184
238
  });
185
239
  if (!response.ok) throw new AgentHttpError(await describeFailure("publishing the agent", response), response.status);
186
- const body = await response.json();
187
- const titleId = body?.titleId ?? body?.TitleId;
240
+ const titleId = (await response.json())?.TitleId;
188
241
  if (!titleId) throw new Error("Copilot Studio published the agent but returned no title id");
189
242
  return titleId;
190
243
  }
package/dist/cli.mjs CHANGED
@@ -1,10 +1,33 @@
1
1
  #!/usr/bin/env node
2
- import { A as DEFAULT_MODEL, C as SECRETS_FILE, O as mergeOpencodeConfig, S as CONFIG_DIR, T as PROVIDER_ID, a as startServer, b as AGENT_FILE, g as createTokenClient, j as LOCAL_TITLE_MODEL, x as CACHE_FILE } from "./server-MaGKSmnd.mjs";
3
- import { t as getOrCreateAgent } from "./agent-Do_zx7Ev.mjs";
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";
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";
7
7
  import { fileURLToPath } from "node:url";
8
+ // src/live-check.ts
9
+ function distinctTones(models) {
10
+ return [...new Set(models.flatMap((model) => model.tone ? [model.tone] : []))];
11
+ }
12
+ async function checkTones(session, tones) {
13
+ const results = [];
14
+ for (const tone of tones) try {
15
+ const { text, contentOrigin } = await session.run("Please reply with the word ok.", { tone });
16
+ const ok = text.trim() !== "" && contentOrigin !== "BotConnection";
17
+ results.push({
18
+ tone,
19
+ ok,
20
+ detail: text.trim() === "" ? "empty reply" : contentOrigin ?? "replied"
21
+ });
22
+ } catch (error) {
23
+ results.push({
24
+ tone,
25
+ ok: false,
26
+ detail: error.message
27
+ });
28
+ }
29
+ return results;
30
+ }
8
31
  // src/cli.ts
9
32
  /**
10
33
  * `opencode-m365` — sign in, wire up opencode, and check the plumbing.
@@ -20,7 +43,7 @@ async function main() {
20
43
  case "login": return doLogin(rest);
21
44
  case "setup": return doSetup(rest);
22
45
  case "serve": return doServe(rest);
23
- case "doctor": return doDoctor();
46
+ case "doctor": return doDoctor(rest);
24
47
  case "help":
25
48
  case "--help":
26
49
  case "-h": return printHelp();
@@ -37,7 +60,8 @@ function printHelp() {
37
60
  setup [--local] Add the plugin to ~/.config/opencode/opencode.json
38
61
  serve [--port <n>] Run the OpenAI-compatible proxy standalone
39
62
  (key from M365_PROXY_KEY, else printed)
40
- doctor Check auth, the agent, and the proxy
63
+ doctor [--live] Check auth, the agent, and the proxy
64
+ (--live also sends one short message per model tone)
41
65
 
42
66
  Config lives in ${CONFIG_DIR}
43
67
 
@@ -46,7 +70,7 @@ to complete SSO/MFA by hand once — the only option on tenants with push-only
46
70
  MFA, FIDO2, or a federated IdP.`);
47
71
  }
48
72
  async function doLogin(args) {
49
- const { login } = await import("./login--nn76uPy.mjs");
73
+ const { login } = await import("./login-B-1yNcEb.mjs");
50
74
  const interactive = args.includes("--interactive");
51
75
  try {
52
76
  const account = await login({
@@ -145,7 +169,7 @@ async function doServe(args) {
145
169
  proxy.close().then(() => process.exit(0));
146
170
  });
147
171
  }
148
- async function doDoctor() {
172
+ async function doDoctor(args) {
149
173
  let failures = 0;
150
174
  const check = (label, ok, detail = "") => {
151
175
  console.log(` ${ok ? "ok " : "FAIL"} ${label}${detail ? ` — ${detail}` : ""}`);
@@ -189,6 +213,14 @@ async function doDoctor() {
189
213
  } catch (error) {
190
214
  check("starts", false, error.message);
191
215
  }
216
+ if (args.includes("--live")) {
217
+ console.log("\nLive turns (one conversation, one short message per tone)");
218
+ if (!signedIn) console.log(" skip needs a signed-in account");
219
+ else {
220
+ const session = new CopilotSession({ getToken: () => tokens.getToken() });
221
+ for (const { tone, ok, detail } of await checkTones(session, distinctTones(MODELS))) check(tone, ok, detail);
222
+ }
223
+ }
192
224
  console.log("\nopencode");
193
225
  const configured = existsSync(OPENCODE_CONFIG) && readFileSync(OPENCODE_CONFIG, "utf8").includes("m365");
194
226
  check("plugin registered", configured, configured ? OPENCODE_CONFIG : "run `opencode-m365 setup`");
@@ -1,4 +1,4 @@
1
- import { F as __toESM, N as __commonJSMin, P as __require } from "./server-MaGKSmnd.mjs";
1
+ import { F as __commonJSMin, I as __require, L as __toESM } from "./server-BRXlKFEJ.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 SECRETS_FILE, S as CONFIG_DIR, _ as createLogger, c as AUTHORITY, f as REDIRECT_URI, h as createCachePlugin, m as authCodeFromUrl, o as object, p as SYDNEY_SCOPES, s as string, u as CLIENT_ID, v as ensurePrivateDir } from "./server-MaGKSmnd.mjs";
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";
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-DoXU8l_x.mjs");
99
+ const { PublicClientApplication, CryptoProvider } = await import("./dist-CcVQZgN5.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 DEFAULT_MODEL, D as buildProviderInfo, E as buildModelInfos, M as isLocalModel, T as PROVIDER_ID, _ as createLogger, a as startServer, g as createTokenClient, k as resolveOptions, r as SESSION_ID_HEADER, t as AUX_REQUEST_KIND_HEADER, w as PLUGIN_ID } from "./server-MaGKSmnd.mjs";
2
- import { t as getOrCreateAgent } from "./agent-Do_zx7Ev.mjs";
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";
3
3
  // src/runtime.ts
4
4
  /**
5
5
  * What the plugin stands on: the OpenAI-compatible proxy, started in-process (or an
@@ -52,42 +52,43 @@ const LOCAL_TITLE_MODEL = "local-title";
52
52
  /**
53
53
  * Default when a request carries no model.
54
54
  *
55
- * Their README measures `gpt-5.5-think-deeper` at 100% tool compliance with the
56
- * declarative agent + fenced/shell-routing path, and a request with no model already
57
- * defaults to it there. Note this conflicts with `m365-copilot-api.md` quirk #13,
58
- * which says reasoning tones meta-analyse the injected prompt and disengage — that
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 = "gpt-5.5-think-deeper";
60
+ const DEFAULT_MODEL = "quick";
62
61
  const MODELS = [
63
- m("work", "M365 Copilot (Work — reads your mailbox)", "magic", false, true),
64
- m("work-think", "M365 Copilot (Work, Think Deeper)", "Gpt_5_5_Reasoning", true, true),
62
+ m("work", "Ask your mail, Teams & files", "magic", false, true),
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),
65
66
  m("gpt-5.6-think-deeper", "GPT-5.6 (Think Deeper)", "Gpt_5_6_Reasoning", true),
66
67
  m("gpt-5.5-think-deeper", "GPT-5.5 (Think Deeper)", "Gpt_5_5_Reasoning", true),
67
68
  m("gpt-5.5", "GPT-5.5", "Gpt_5_5_Chat", false),
68
69
  m("gpt-5.5-quick", "GPT-5.5 (Quick)", "Gpt_5_5_Chat", false),
69
70
  m("m365-copilot", "M365 Copilot (Auto)", "magic", false),
70
71
  m("auto", "M365 Copilot (Auto)", "magic", false),
71
- m("quick", "GPT (Quick)", "Gpt_Quick", false),
72
- m("think-deeper", "GPT (Think Deeper)", "Gpt_Reasoning", true),
72
+ m("quick", "GPT (Quick)", "Gpt_5_5_Chat", false),
73
+ m("think-deeper", "GPT (Think Deeper)", "Gpt_5_5_Reasoning", true),
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)", "Gpt_5_4_Quick", false),
79
- m("gpt-5.3", "GPT-5.3 (Quick)", "Gpt_5_3_Quick", false),
80
- m("gpt-5.3-quick", "GPT-5.3 (Quick)", "Gpt_5_3_Quick", false),
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)", "Gpt_5_2_Quick", false),
83
- m("gpt-5.2-quick", "GPT-5.2 (Quick)", "Gpt_5_2_Quick", false),
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
  ];
87
88
  function m(id, name, tone, reasoning, grounded = false) {
88
89
  return {
89
90
  id,
90
- name,
91
+ name: pickerName(name, tone, grounded),
91
92
  tone,
92
93
  reasoning,
93
94
  grounded,
@@ -97,6 +98,15 @@ function m(id, name, tone, reasoning, grounded = false) {
97
98
  }
98
99
  };
99
100
  }
101
+ /**
102
+ * Lead with what the model is for. opencode 2's `Model.Info` has no description, so
103
+ * the name is the only thing that separates reading your account from writing code.
104
+ * The local titler is neither.
105
+ */
106
+ function pickerName(name, tone, grounded) {
107
+ if (tone === null) return name;
108
+ return `${grounded ? "Work" : "Code"} · ${name}`;
109
+ }
100
110
  const BY_ID = new Map(MODELS.map((model) => [model.id, model]));
101
111
  /**
102
112
  * Look up a model, falling back to the default for anything we do not know.
@@ -186,9 +196,17 @@ const EDIT_PARAM_PAIRS = [
186
196
  const SEARCH_MARKER = "<<<<<<< SEARCH";
187
197
  const DIVIDER_MARKER = "=======";
188
198
  const REPLACE_MARKER = ">>>>>>> REPLACE";
189
- /** The shell tool in this toolset, whatever the harness named it. */
199
+ /**
200
+ * The shell tool in this toolset, whatever the harness named it.
201
+ *
202
+ * Chosen by name priority, not the harness's order: opencode 2 offers both `shell`
203
+ * and `execute`, and its `execute` runs JavaScript.
204
+ */
190
205
  function findShellTool(tools) {
191
- return tools.find((tool) => SHELL_TOOL_NAMES.includes(tool.function.name.toLowerCase()));
206
+ for (const name of SHELL_TOOL_NAMES) {
207
+ const match = tools.find((tool) => tool.function.name.toLowerCase() === name);
208
+ if (match) return match;
209
+ }
192
210
  }
193
211
  /**
194
212
  * Decide how a tool's arguments map onto the fence.
@@ -250,8 +268,9 @@ function buildToolPrompt(tools, options = {}) {
250
268
  lines.push("");
251
269
  }
252
270
  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.`);
253
- 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.");
254
- lines.push("Only say the work is done once a tool result above this line proves it. When you have the final answer, give it plainly with no preamble.");
271
+ 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
+ else lines.push("Read each tool result before deciding the next step, rather than guessing what a command returned.");
273
+ 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.");
255
274
  lines.push("</tools>");
256
275
  return lines.join("\n");
257
276
  }
@@ -355,23 +374,28 @@ function stripInventedJson(text) {
355
374
  }
356
375
  /** Parse a raw M365 response into OpenAI-shaped tool calls plus any prose. */
357
376
  function parseToolCalls(source, tools, options = {}) {
358
- const cleaned = stripInventedJson(source);
377
+ const cleaned = stripInventedJson(source.replace(/\r\n?/g, "\n"));
359
378
  if (tools.length === 0) return {
360
379
  toolCalls: [],
361
380
  text: cleaned
362
381
  };
363
- if (isProseDocument(cleaned)) return {
382
+ const shell = findShellTool(tools);
383
+ const byName = new Map(tools.map((tool) => [tool.function.name.toLowerCase(), tool]));
384
+ const toolFor = (fence) => {
385
+ const info = fence.info.split(/\s+/)[0]?.toLowerCase() ?? "";
386
+ return byName.get(info) ?? (shell && SHELL_FENCE_INFOS.has(info) ? shell : void 0);
387
+ };
388
+ const invented = cleaned.search(/<tool_(?:response|result)\b/i);
389
+ const actionable = invented === -1 ? cleaned : cleaned.slice(0, invented);
390
+ const fences = extractFences(actionable);
391
+ if (!(fences.length > 0 && actionable.slice(0, fences[0].start).trim() === "" && Boolean(toolFor(fences[0]))) && isProseDocument(actionable)) return {
364
392
  toolCalls: [],
365
393
  text: cleaned
366
394
  };
367
- const shell = findShellTool(tools);
368
- const byName = new Map(tools.map((tool) => [tool.function.name.toLowerCase(), tool]));
369
395
  const calls = [];
370
396
  const consumed = [];
371
- for (const fence of extractFences(cleaned)) {
372
- const info = fence.info.split(/\s+/)[0]?.toLowerCase() ?? "";
373
- let tool = byName.get(info);
374
- if (!tool && shell && SHELL_FENCE_INFOS.has(info)) tool = shell;
397
+ for (const fence of fences) {
398
+ const tool = toolFor(fence);
375
399
  if (!tool) continue;
376
400
  calls.push({
377
401
  name: tool.function.name,
@@ -389,33 +413,93 @@ function parseToolCalls(source, tools, options = {}) {
389
413
  text: ""
390
414
  };
391
415
  }
416
+ /** Names models use for a file path, compared without case or underscores. */
417
+ const PATH_ALIASES = /* @__PURE__ */ new Set([
418
+ "path",
419
+ "filepath",
420
+ "file",
421
+ "filename"
422
+ ]);
423
+ const squash = (name) => name.toLowerCase().replace(/_/g, "");
424
+ /** The parameter a header key means, tolerating case, snake_case and path aliases. */
425
+ function resolveKey(key, candidates) {
426
+ const wanted = squash(key);
427
+ const exact = candidates.find((name) => squash(name) === wanted);
428
+ if (exact) return exact;
429
+ if (!PATH_ALIASES.has(wanted)) return void 0;
430
+ return candidates.find((name) => PATH_ALIASES.has(squash(name)));
431
+ }
432
+ /**
433
+ * Clean a header value the way models write it: wrapped in quotes or backticks, with
434
+ * the template's `(optional)` marker echoed. An echoed `<type>` placeholder is no value.
435
+ */
436
+ function cleanValue(raw) {
437
+ let value = raw.replace(/\s*\(optional\)\s*$/i, "").trim();
438
+ const wrapped = /^(["'`])(.*)\1$/.exec(value);
439
+ if (wrapped) value = wrapped[2];
440
+ return /^<[A-Za-z]+>$/.test(value) ? void 0 : value;
441
+ }
392
442
  /** Split a fence body into header args, a SEARCH/REPLACE pair, and/or a body arg. */
393
443
  function parseFenceBody(body, tool) {
394
444
  const shape = shapeOf(tool);
395
445
  const props = tool.function.parameters?.properties ?? {};
446
+ const isShell = SHELL_TOOL_NAMES.includes(tool.function.name.toLowerCase());
396
447
  const args = {};
448
+ const seen = /* @__PURE__ */ new Set();
449
+ let bodyHeader;
450
+ const editHeaders = {};
397
451
  const lines = body.split("\n");
398
452
  let cursor = 0;
453
+ const headerish = [
454
+ ...shape.headers,
455
+ ...shape.bodyParam ? [shape.bodyParam] : [],
456
+ ...shape.editPair ?? []
457
+ ];
399
458
  while (cursor < lines.length) {
400
459
  const match = /^([A-Za-z_][A-Za-z0-9_]*)\s*:\s?(.*)$/.exec(lines[cursor]);
401
460
  if (!match) break;
402
- const key = match[1];
403
- if (!shape.headers.includes(key)) break;
404
- args[key] = coerce(match[2].trim(), props[key]?.type);
461
+ const key = resolveKey(match[1], headerish);
462
+ if (!key || seen.has(key)) break;
463
+ seen.add(key);
464
+ if (key === shape.bodyParam) bodyHeader = {
465
+ value: match[2].trim(),
466
+ line: lines[cursor]
467
+ };
468
+ else if (shape.editPair?.includes(key)) editHeaders[key] = match[2];
469
+ else {
470
+ const value = cleanValue(match[2]);
471
+ if (value !== void 0) args[key] = coerce(value, props[key]?.type);
472
+ }
405
473
  cursor += 1;
406
474
  }
407
- const rest = lines.slice(cursor).join("\n").replace(/^\n+/, "");
475
+ const rest = lines.slice(cursor).join("\n").replace(/^\n+/, "").trimEnd();
408
476
  if (shape.editPair) {
477
+ const [search, replace] = shape.editPair;
409
478
  const diff = parseSearchReplace(rest);
410
479
  if (diff) {
411
- args[shape.editPair[0]] = diff.search;
412
- args[shape.editPair[1]] = diff.replace;
480
+ args[search] = diff.search;
481
+ args[replace] = diff.replace;
482
+ } else if (search in editHeaders && replace in editHeaders) {
483
+ args[search] = editHeaders[search];
484
+ args[replace] = editHeaders[replace];
413
485
  }
414
486
  return args;
415
487
  }
416
488
  if (shape.bodyParam) {
417
- const trimmed = rest.trim();
418
- if (trimmed !== "") args[shape.bodyParam] = trimmed;
489
+ let value = rest;
490
+ if (bodyHeader) {
491
+ if (isShell) value = [bodyHeader.value, rest].filter((part) => part !== "").join("\n");
492
+ else value = rest === "" ? bodyHeader.value : `${bodyHeader.line}\n${rest}`;
493
+ }
494
+ if (isShell && value.split("\n").every((line) => line.trim() === "" || line.startsWith("$ "))) value = value.replace(/^\$ /gm, "");
495
+ if (value.trim() !== "") args[shape.bodyParam] = value;
496
+ return args;
497
+ }
498
+ const required = tool.function.parameters?.required ?? [];
499
+ const missing = shape.headers.filter((name) => required.includes(name) && !(name in args));
500
+ if (missing.length === 1 && rest !== "" && !rest.includes("\n")) {
501
+ const value = cleanValue(rest);
502
+ if (value !== void 0) args[missing[0]] = coerce(value, props[missing[0]]?.type);
419
503
  }
420
504
  return args;
421
505
  }
@@ -477,6 +561,7 @@ const PLUGIN_ID = "m365-copilot";
477
561
  */
478
562
  const LEAN_TOOLS = [
479
563
  "bash",
564
+ "shell",
480
565
  "read",
481
566
  "edit",
482
567
  "write",
@@ -493,16 +578,18 @@ const LEAN_TOOLS = [
493
578
  * final request whatever the harness does, so the trim lives here.
494
579
  *
495
580
  * Two rules, in order:
496
- * 1. Keep the tools we recognise as load-bearing for a coding loop.
581
+ * 1. Keep the tools we recognise as load-bearing for a coding loop, plus the shell
582
+ * tool under whatever name the harness gives it — opencode 2 renamed `bash` to
583
+ * `shell`, and an allowlist alone silently dropped it.
497
584
  * 2. If we recognise none of them — a harness with its own vocabulary — fall back
498
585
  * to a hard cap, keeping any shell tool first.
499
586
  */
500
587
  function selectLeanTools(tools) {
501
588
  if (tools.length === 0) return [...tools];
502
589
  const wanted = new Set(LEAN_TOOLS);
503
- const kept = tools.filter((tool) => wanted.has(tool.function.name.toLowerCase()));
504
- if (kept.length > 0) return kept;
505
590
  const shell = findShellTool(tools);
591
+ const kept = tools.filter((tool) => tool === shell || wanted.has(tool.function.name.toLowerCase()));
592
+ if (kept.some((tool) => tool !== shell)) return kept;
506
593
  const rest = tools.filter((tool) => tool !== shell);
507
594
  const remaining = shell ? 4 : 5;
508
595
  return [...shell ? [shell] : [], ...rest.slice(0, remaining)];
@@ -949,7 +1036,7 @@ function createTokenClient(options = {}) {
949
1036
  const cache = /* @__PURE__ */ new Map();
950
1037
  async function client() {
951
1038
  if (app) return app;
952
- const { PublicClientApplication } = await import("./dist-DoXU8l_x.mjs");
1039
+ const { PublicClientApplication } = await import("./dist-CcVQZgN5.mjs");
953
1040
  app = new PublicClientApplication({
954
1041
  auth: {
955
1042
  clientId: CLIENT_ID,
@@ -4789,6 +4876,30 @@ var DisengagedError = class extends Error {
4789
4876
  this.name = "DisengagedError";
4790
4877
  }
4791
4878
  };
4879
+ /** The server refused the invocation outright — a retired tone, typically. Retrying cannot help. */
4880
+ var TurnRejectedError = class extends Error {
4881
+ constructor(detail) {
4882
+ super(`M365 rejected the turn: ${detail}`);
4883
+ this.name = "TurnRejectedError";
4884
+ }
4885
+ };
4886
+ /** M365 throttled the account. Every retry extends the lull it needs to recover. */
4887
+ var M365ThrottledError = class extends Error {
4888
+ constructor(detail) {
4889
+ super(`M365 is throttling this account (${detail}). It recovers after a lull; retrying now extends it.`);
4890
+ this.name = "M365ThrottledError";
4891
+ }
4892
+ };
4893
+ /**
4894
+ * M365 answered with its own refusal instead of the model: no credits left, a model
4895
+ * this account's licence does not cover, or a tone that is registered but dead.
4896
+ */
4897
+ var M365UnavailableError = class extends Error {
4898
+ constructor(detail) {
4899
+ super(`M365 could not serve this model: ${detail}`);
4900
+ this.name = "M365UnavailableError";
4901
+ }
4902
+ };
4792
4903
  /**
4793
4904
  * Strip Copilot's inline citation control tokens from a GROUNDED answer.
4794
4905
  *
@@ -4839,7 +4950,10 @@ var CopilotSession = class {
4839
4950
  text: note ? `${text}\n\n${note}` : text,
4840
4951
  annotations
4841
4952
  };
4842
- const socket = new import_websocket.default(url, { headers: BROWSER_HEADERS });
4953
+ const socket = new import_websocket.default(url, { headers: {
4954
+ ...BROWSER_HEADERS,
4955
+ "X-RoutingParameter-SessionKey": this.conversationId
4956
+ } });
4843
4957
  try {
4844
4958
  const result = await this.pump(socket, message, turn);
4845
4959
  this.turnIndex += 1;
@@ -4916,6 +5030,11 @@ var CopilotSession = class {
4916
5030
  return;
4917
5031
  }
4918
5032
  const raw = deltaText.length >= snapshotText.length ? deltaText : snapshotText;
5033
+ const refusal = refusalOf(result, raw);
5034
+ if (refusal) {
5035
+ reject(refusal);
5036
+ return;
5037
+ }
4919
5038
  result.text = turn.grounded ? cleanAnswer(raw) : raw;
4920
5039
  resolve(result);
4921
5040
  };
@@ -4967,7 +5086,7 @@ var CopilotSession = class {
4967
5086
  break;
4968
5087
  case 3:
4969
5088
  if (frame.error) {
4970
- finish(/* @__PURE__ */ new Error(`M365 rejected the turn: ${frame.error}`));
5089
+ finish(new TurnRejectedError(frame.error));
4971
5090
  return;
4972
5091
  }
4973
5092
  finish();
@@ -5106,6 +5225,8 @@ var CopilotSession = class {
5106
5225
  }
5107
5226
  applyStreamItem(item, result) {
5108
5227
  if (!item) return;
5228
+ if (typeof item.result?.value === "string") result.resultValue = item.result.value;
5229
+ if (typeof item.result?.errorCode === "string") result.errorCode = item.result.errorCode;
5109
5230
  if (item.throttling) result.throttle = {
5110
5231
  current: item.throttling.numUserMessagesInConversation,
5111
5232
  max: item.throttling.maxNumUserMessagesInConversation
@@ -5113,6 +5234,16 @@ var CopilotSession = class {
5113
5234
  for (const message of item.messages ?? []) if (message?.author === "bot" && !message.messageType) absorbMetadata(message, result);
5114
5235
  }
5115
5236
  };
5237
+ /**
5238
+ * M365's own refusal, when that is what arrived instead of an answer. Its text reads
5239
+ * like a reply, so returned as one it would end opencode's loop on an apology.
5240
+ */
5241
+ function refusalOf(result, text) {
5242
+ const detail = [result.errorCode, text.trim()].filter(Boolean).join(": ") || result.resultValue || "no reason given";
5243
+ if (result.resultValue === "Throttled") return new M365ThrottledError(detail);
5244
+ if (result.resultValue && result.resultValue !== "Success") return new M365UnavailableError(detail);
5245
+ if (result.contentOrigin === "BotConnection") return new M365UnavailableError(`registered but dead (BotConnection): ${detail}`);
5246
+ }
5116
5247
  /** Pull the diagnostic fields off a final bot message. */
5117
5248
  function absorbMetadata(message, result) {
5118
5249
  if (typeof message.contentOrigin === "string") result.contentOrigin = message.contentOrigin;
@@ -10585,6 +10716,12 @@ function condenseSystemPrompt(text, tools, options = {}) {
10585
10716
  if (requires.some((name) => toolNames.has(name))) continue;
10586
10717
  result = result.replace(new RegExp(`<${tag}>[\\s\\S]*?</${tag}>`, "g"), "");
10587
10718
  }
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/);
10588
10725
  if (options.replaceProseWith !== void 0) {
10589
10726
  const { leadingBlocks, instructions, blocks } = splitSystemPrompt(result);
10590
10727
  result = [
@@ -10596,6 +10733,10 @@ function condenseSystemPrompt(text, tools, options = {}) {
10596
10733
  }
10597
10734
  return result.replace(/\n{3,}/g, "\n\n").trim();
10598
10735
  }
10736
+ /** Remove every line matching `pattern`. */
10737
+ function dropLines(text, pattern) {
10738
+ return text.split("\n").filter((line) => !pattern.test(line)).join("\n");
10739
+ }
10599
10740
  const BLOCK_PATTERN = /<([a-z_][a-z0-9_-]*)>[\s\S]*?<\/\1>/gi;
10600
10741
  /**
10601
10742
  * Split a harness system prompt into: leading prose, the user's own instructions,
@@ -10648,11 +10789,12 @@ function trailingBlockStart(text) {
10648
10789
  */
10649
10790
  function buildTurnPrompt(messages, tools, sentMessageCount, options = {}) {
10650
10791
  const parts = [];
10651
- if (sentMessageCount === 0) {
10792
+ const isFirstTurn = sentMessageCount === 0;
10793
+ if (isFirstTurn) {
10652
10794
  const systemText = messages.filter((message) => message.role === "system" || message.role === "developer").map(contentOf).filter(Boolean).join("\n\n");
10653
10795
  if (systemText) parts.push(condenseSystemPrompt(systemText, tools, { ...options.leanSystemPrompt !== void 0 ? { replaceProseWith: options.leanSystemPrompt } : {} }));
10654
10796
  }
10655
- if (tools.length > 0) parts.push(buildToolPrompt(tools));
10797
+ if (tools.length > 0) parts.push(buildToolPrompt(tools, { firstTurn: isFirstTurn }));
10656
10798
  const callsById = /* @__PURE__ */ new Map();
10657
10799
  for (const message of messages) for (const call of message.tool_calls ?? []) callsById.set(call.id, call.function);
10658
10800
  for (const message of messages.slice(sentMessageCount)) {
@@ -10803,6 +10945,37 @@ function generateTitle(messages) {
10803
10945
  function firstLine(text) {
10804
10946
  return text.split("\n", 1)[0] ?? "";
10805
10947
  }
10948
+ // src/giveup.ts
10949
+ /**
10950
+ * Spotting a tool turn where the model gave up instead of acting.
10951
+ *
10952
+ * M365's chat tones sometimes answer a tool turn by claiming they have no tools or
10953
+ * cannot reach the files, without trying. It is stochastic: the same tone acts on the
10954
+ * next try. Returned to opencode as-is, that prose ends the agent loop, so the proxy
10955
+ * asks once more in the same conversation instead. The reference project measured
10956
+ * that recovering roughly 16/30 → 25/30 tasks on `Gpt_5_5_Chat`.
10957
+ */
10958
+ const GIVE_UP_PATTERNS = [
10959
+ /\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,
10960
+ /\bdon.?t\s+have\s+(?:access|any\s+(?:way|tool)|a\s+(?:way|tool))\b/i,
10961
+ /\bno\s+(?:[\w-]+\s+){0,3}tools?\s+(?:is|are)\s+(?:currently\s+)?(?:available|accessible|executable)\b/i,
10962
+ /\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,
10963
+ /\b(?:does\s+not|doesn.?t)\s+(?:provide|have|expose)\s+(?:a|any)\s+[\w\s-]{0,30}\btool\b/i,
10964
+ /\bpaste\s+(?:the\s+|its\s+)?(?:contents?|files?|code|output)\b/i,
10965
+ /\b(?:different|another|new)\s+(?:session|environment|conversation)\b/i
10966
+ ];
10967
+ function looksLikeGiveUp(reply) {
10968
+ const text = reply.trim();
10969
+ return text.length >= 12 && GIVE_UP_PATTERNS.some((pattern) => pattern.test(text));
10970
+ }
10971
+ /**
10972
+ * The follow-up. Soft on purpose: shouted absolutes read as manipulation to the
10973
+ * Disengaged filter. Once tools have run it must not say nothing has — a prompt that
10974
+ * contradicts the transcript is one the model stops trusting.
10975
+ */
10976
+ function nudgeFor(midTask) {
10977
+ 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
+ }
10806
10979
  // src/server.ts
10807
10980
  /**
10808
10981
  * The OpenAI-compatible HTTP surface.
@@ -11001,6 +11174,16 @@ async function handleChatCompletion(request, response, context) {
11001
11174
  release();
11002
11175
  }
11003
11176
  }
11177
+ let envTurnLog;
11178
+ /** The `M365_TURN_LOG` file writer, created on first use. */
11179
+ function defaultTurnLog() {
11180
+ if (envTurnLog === void 0) {
11181
+ const file = process.env.M365_TURN_LOG;
11182
+ const append = file ? createPrivateAppender(file) : null;
11183
+ envTurnLog = append ? (entry) => append(`${JSON.stringify(entry)}\n`) : null;
11184
+ }
11185
+ return envTurnLog;
11186
+ }
11004
11187
  async function runTurn(request, response, context, body, conversation, model, tools) {
11005
11188
  if (body.messages.length < conversation.sentMessageCount) conversation.sentMessageCount = 0;
11006
11189
  conversation.session ??= new CopilotSession({
@@ -11019,15 +11202,43 @@ async function runTurn(request, response, context, body, conversation, model, to
11019
11202
  const streamId = `chatcmpl-${randomUUID()}`;
11020
11203
  const canStreamText = streaming && effectiveTools.length === 0 && !model.grounded;
11021
11204
  if (streaming) startSse(response);
11205
+ const turnLog = context.deps.turnLog ?? defaultTurnLog();
11206
+ const logTurn = (fields) => turnLog?.({
11207
+ time: (/* @__PURE__ */ new Date()).toISOString(),
11208
+ model: model.id,
11209
+ tone: model.tone,
11210
+ agent: Boolean(agent),
11211
+ tools: effectiveTools.map((tool) => tool.function.name),
11212
+ ...fields
11213
+ });
11214
+ const turnOptions = {
11215
+ ...model.tone ? { tone: model.tone } : {},
11216
+ agentId: agent,
11217
+ ...model.grounded ? { grounded: true } : {},
11218
+ signal: abort.signal
11219
+ };
11220
+ const recordTurn = (result, extra = {}) => logTurn({
11221
+ reply: result.text,
11222
+ toolCalls: parseToolCalls(result.text, effectiveTools).toolCalls.map((call) => call.name),
11223
+ ...result.contentOrigin ? { contentOrigin: result.contentOrigin } : {},
11224
+ ...result.turnCount !== void 0 ? { turnCount: result.turnCount } : {},
11225
+ ...result.throttle ? { throttle: result.throttle } : {},
11226
+ ...result.scores ? { scores: result.scores } : {},
11227
+ ...result.resultValue ? { resultValue: result.resultValue } : {},
11228
+ ...extra
11229
+ });
11022
11230
  try {
11023
- const result = await conversation.session.run(prompt, {
11024
- ...model.tone ? { tone: model.tone } : {},
11025
- agentId: agent,
11026
- ...model.grounded ? { grounded: true } : {},
11027
- signal: abort.signal,
11231
+ let result = await conversation.session.run(prompt, {
11232
+ ...turnOptions,
11028
11233
  ...images.length > 0 ? { images } : {},
11029
11234
  ...canStreamText ? { onDelta: (chunk) => response.write(streamChunk(streamId, model.id, { content: chunk })) } : {}
11030
11235
  });
11236
+ if (effectiveTools.length > 0 && parseToolCalls(result.text, effectiveTools).toolCalls.length === 0 && looksLikeGiveUp(result.text)) {
11237
+ recordTurn(result);
11238
+ const midTask = body.messages.some((message) => message.role === "tool");
11239
+ result = await conversation.session.run(nudgeFor(midTask), turnOptions);
11240
+ recordTurn(result, { nudged: true });
11241
+ } else recordTurn(result);
11031
11242
  conversation.sentMessageCount = body.messages.length + 1;
11032
11243
  if (!streaming) {
11033
11244
  sendJson(response, 200, buildCompletion(result, {
@@ -11039,6 +11250,7 @@ async function runTurn(request, response, context, body, conversation, model, to
11039
11250
  }
11040
11251
  finishStream(response, streamId, model.id, result, effectiveTools, canStreamText, context.deps.allowMultiTool ?? false);
11041
11252
  } catch (error) {
11253
+ logTurn({ error: error instanceof Error ? `${error.name}: ${error.message}` : String(error) });
11042
11254
  handleTurnFailure(response, error, streaming, effectiveTools.length);
11043
11255
  }
11044
11256
  }
@@ -11055,13 +11267,28 @@ function finishStream(response, streamId, model, result, tools, alreadyStreamedT
11055
11267
  response.write(streamDone());
11056
11268
  response.end();
11057
11269
  }
11270
+ /** opencode retries a 5xx several times and a 4xx not at all (measured on 2.2.5). */
11271
+ const NON_RETRYABLE = 422;
11058
11272
  function handleTurnFailure(response, error, streaming, toolCount) {
11059
11273
  if (error instanceof AuthRequiredError) {
11060
11274
  finishWithError(response, streaming, 401, "authentication_required", error.message);
11061
11275
  return;
11062
11276
  }
11063
11277
  if (error instanceof DisengagedError) {
11064
- finishWithError(response, streaming, 502, "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. Retrying will not help; reduce the toolset or simplify the prompt."}`);
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}`);
11280
+ return;
11281
+ }
11282
+ if (error instanceof M365ThrottledError) {
11283
+ finishWithError(response, streaming, NON_RETRYABLE, "m365_throttled", error.message);
11284
+ return;
11285
+ }
11286
+ if (error instanceof M365UnavailableError) {
11287
+ finishWithError(response, streaming, NON_RETRYABLE, "m365_unavailable", error.message);
11288
+ return;
11289
+ }
11290
+ if (error instanceof TurnRejectedError) {
11291
+ finishWithError(response, streaming, NON_RETRYABLE, "m365_turn_rejected", error.message);
11065
11292
  return;
11066
11293
  }
11067
11294
  const message = error instanceof Error ? error.message : String(error);
@@ -11146,4 +11373,4 @@ async function readBody(request, limit) {
11146
11373
  }
11147
11374
  return Buffer.concat(chunks).toString("utf8");
11148
11375
  }
11149
- export { DEFAULT_MODEL as A, SECRETS_FILE as C, buildProviderInfo as D, buildModelInfos as E, __toESM as F, isLocalModel as M, __commonJSMin as N, mergeOpencodeConfig as O, __require as P, CONFIG_DIR as S, PROVIDER_ID as T, createLogger as _, startServer as a, AGENT_FILE as b, AUTHORITY as c, POWERPLATFORM_SCOPE as d, REDIRECT_URI as f, createTokenClient as g, createCachePlugin as h, generateApiKey as i, LOCAL_TITLE_MODEL as j, resolveOptions as k, BAP_SCOPE as l, authCodeFromUrl as m, DEFAULT_MAX_BODY_BYTES as n, object as o, SYDNEY_SCOPES as p, SESSION_ID_HEADER as r, string as s, AUX_REQUEST_KIND_HEADER as t, CLIENT_ID as u, ensurePrivateDir as v, PLUGIN_ID as w, CACHE_FILE as x, writePrivateFile as y };
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 };
package/dist/server.d.mts CHANGED
@@ -12,13 +12,30 @@
12
12
  /**
13
13
  * Default when a request carries no model.
14
14
  *
15
- * Their README measures `gpt-5.5-think-deeper` at 100% tool compliance with the
16
- * declarative agent + fenced/shell-routing path, and a request with no model already
17
- * defaults to it there. Note this conflicts with `m365-copilot-api.md` quirk #13,
18
- * which says reasoning tones meta-analyse the injected prompt and disengage — that
19
- * note predates the GPT-5.5 measurements. See README for the full story.
15
+ * A chat tone, because a coding backend has to call tools. Measured on a live tenant
16
+ * (2026-11-09): `quick` made real tool calls 4/4, while `gpt-5.5-think-deeper` claimed
17
+ * to have no tools 3/3 — matching `m365-copilot-api.md` quirk #13, and contradicting
18
+ * the 100% that project's README reports for it.
20
19
  */
21
- export declare const DEFAULT_MODEL = "gpt-5.5-think-deeper";
20
+ export declare const DEFAULT_MODEL = "quick";
21
+ interface ThrottleState {
22
+ current: number;
23
+ max: number;
24
+ }
25
+ interface TurnResult {
26
+ text: string;
27
+ /** Per-conversation quota, when the server reported it. */
28
+ throttle?: ThrottleState;
29
+ /** Which backend answered — `DeepLeo` is the reasoning pipeline. */
30
+ contentOrigin?: string;
31
+ /** Server-side turn count for this conversation. */
32
+ turnCount?: number;
33
+ /** Classifier scores. `dea_violation` rises before Disengaged fires. */
34
+ scores?: Record<string, number>;
35
+ /** The final item's verdict: `Success`, or why M365 did not serve the turn. */
36
+ resultValue?: string;
37
+ errorCode?: string;
38
+ }
22
39
  /**
23
40
  * Header a harness uses to declare what an auxiliary request is *for*.
24
41
  *
@@ -62,6 +79,12 @@ export interface ServerDeps {
62
79
  * does not affect the outgoing request — see `condenseSystemPrompt`.
63
80
  */
64
81
  leanSystemPrompt?: string;
82
+ /**
83
+ * Receives one entry per M365 turn: the raw reply, what was parsed from it, and
84
+ * M365's diagnostics. Defaults to a JSONL file at `M365_TURN_LOG` when that is set,
85
+ * and to nothing otherwise — the raw reply can hold anything from the workspace.
86
+ */
87
+ turnLog?: (entry: TurnLogEntry) => void;
65
88
  port?: number;
66
89
  /** Loopback only: `127.0.0.1` (the default), `::1` or `localhost`. Anything else throws. */
67
90
  host?: string;
@@ -93,4 +116,22 @@ export interface ProxyHandle {
93
116
  export declare const DEFAULT_MAX_BODY_BYTES: number;
94
117
  /** A fresh per-launch secret: 32 random bytes, base64url. */
95
118
  export declare function generateApiKey(): string;
96
- export declare function startServer(deps: ServerDeps): Promise<ProxyHandle>;
119
+ export declare function startServer(deps: ServerDeps): Promise<ProxyHandle>;
120
+ export interface TurnLogEntry {
121
+ time: string;
122
+ model: string;
123
+ tone: string | null;
124
+ agent: boolean;
125
+ tools: string[];
126
+ reply?: string;
127
+ toolCalls?: string[];
128
+ contentOrigin?: string;
129
+ turnCount?: number;
130
+ throttle?: TurnResult["throttle"];
131
+ scores?: Record<string, number>;
132
+ resultValue?: string;
133
+ /** This turn was the follow-up sent after a give-up. */
134
+ nudged?: boolean;
135
+ error?: string;
136
+ }
137
+ export {};
package/dist/server.mjs CHANGED
@@ -1 +1 @@
1
- export { t as AUX_REQUEST_KIND_HEADER, n as DEFAULT_MAX_BODY_BYTES, A as DEFAULT_MODEL, r as SESSION_ID_HEADER, i as generateApiKey, a as startServer } from "./server-MaGKSmnd.mjs";
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";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-m365-copilot",
3
- "version": "2.1.1",
3
+ "version": "2.2.0",
4
4
  "description": "Use your org's Microsoft 365 Copilot as the model backend for opencode",
5
5
  "license": "MIT",
6
6
  "type": "module",