opencode-m365-copilot 2.2.1 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +109 -4
- package/dist/{agent-D3anZnuv.mjs → agent-DPNplWJY.mjs} +1 -1
- package/dist/cli.mjs +6 -4
- package/dist/{dist-CsSmycf9.mjs → dist-QjFnJhR3.mjs} +1 -1
- package/dist/{login-Dgv1sbgr.mjs → login-Cts_gng-.mjs} +2 -2
- package/dist/plugin.mjs +12 -2
- package/dist/{server-MqggZMCR.mjs → server-DXznAk1h.mjs} +737 -27
- package/dist/server.d.mts +23 -0
- package/dist/server.mjs +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -82,8 +82,10 @@ What gets dropped:
|
|
|
82
82
|
tools were unusable. That section, any line naming `execute`, and the skills
|
|
83
83
|
paragraph go with their tools, as do two harness lines that contradict the
|
|
84
84
|
contract ("prefer parallelizing tool calls", "prefer dedicated tools over shell
|
|
85
|
-
commands").
|
|
86
|
-
|
|
85
|
+
commands"). The whole Code Mode section is removed, catalogue included, even when a
|
|
86
|
+
tool's description in it holds a line that looks like a heading. On opencode 2.2.5
|
|
87
|
+
this takes the system prompt from about 8,000 characters to about 2,000. To reach
|
|
88
|
+
MCP tools anyway, see [MCP tools](#mcp-tools).
|
|
87
89
|
- **The harness's prose system prompt** — replaced with a short one, but **off by
|
|
88
90
|
default**. A long, polished assistant prompt measurably reduces M365's tool
|
|
89
91
|
compliance on another harness's numbers; that is a borrowed result we have not
|
|
@@ -123,7 +125,7 @@ warning and carries on.
|
|
|
123
125
|
Four things keep a turn on track:
|
|
124
126
|
|
|
125
127
|
- **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
|
|
128
|
+
`filePath:` for `path`, quoted values, a copied `$ ` prompt, a fence opened at the end of a sentence (`…first.```shell`), prose or an invented
|
|
127
129
|
`<tool_response>` after the block. These are read as the call the model meant.
|
|
128
130
|
- **One nudge after a give-up.** Chat tones sometimes answer a tool turn with "no tool
|
|
129
131
|
is available" without trying. The proxy then asks once more, softly, in the same
|
|
@@ -164,6 +166,94 @@ progress checks (grep for what was left, re-reading a file after editing it), no
|
|
|
164
166
|
These runs had the routing header, so they show it causes no harm. They don't show it
|
|
165
167
|
is needed, because no run without it was tried.
|
|
166
168
|
|
|
169
|
+
## MCP tools
|
|
170
|
+
|
|
171
|
+
opencode 2 does not offer MCP tools as ordinary tools. It lists them in a **Code Mode**
|
|
172
|
+
catalogue in the system prompt (`tools.github.create_issue({ … })` and so on, with
|
|
173
|
+
opencode's own `opencode` namespace among them), and they can be called only as
|
|
174
|
+
JavaScript inside its `execute` tool. The request's `tools` hold opencode's built-ins
|
|
175
|
+
plus `execute`, whose one parameter is a string of code. The lean trim drops `execute`
|
|
176
|
+
and the catalogue goes with it, so by default M365 reaches **no MCP tools** at all.
|
|
177
|
+
Offering the catalogue as it is would put a long list of TypeScript signatures in front
|
|
178
|
+
of M365 and push it back towards the Disengaged threshold.
|
|
179
|
+
|
|
180
|
+
With `{ "mcpProxy": true }` the proxy stands in for the catalogue. M365 never sees
|
|
181
|
+
`execute` or the catalogue, even with `lean` off: the catalogue is stripped from the
|
|
182
|
+
prompt, and the proxy adds **one** extra fenced tool, `mcp`, as the only way to reach
|
|
183
|
+
the MCP tools. Its one-line description summarises what is behind it, by server, so the
|
|
184
|
+
model knows a search is worth making and which words to use:
|
|
185
|
+
|
|
186
|
+
```
|
|
187
|
+
mcp — Use 14 tools from my MCP servers — github (create_issue, list_issues, search_code, get_file, +6 more), slack (post_message, list_channels) — by searching with a few words about what you want to do; …
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
The summary names up to four tools for each server and up to eight servers, and it is
|
|
191
|
+
prose, not tool blocks. A search looks like this:
|
|
192
|
+
|
|
193
|
+
````
|
|
194
|
+
```mcp
|
|
195
|
+
search: create a github issue
|
|
196
|
+
```
|
|
197
|
+
````
|
|
198
|
+
|
|
199
|
+
The proxy answers that search **itself**; it never reaches opencode. It ranks the
|
|
200
|
+
catalogue against the words (a hit in a tool's name counts more than one in its
|
|
201
|
+
description) and sends the best five back to M365 in the same conversation: each
|
|
202
|
+
match's signature as opencode wrote it, then how to call one. A search for a server's
|
|
203
|
+
prefix, such as `github.`, lists that server's tools, also up to five. The model then
|
|
204
|
+
calls a tool through `mcp` with `call:` and the path the search showed, and its
|
|
205
|
+
arguments as a JSON object:
|
|
206
|
+
|
|
207
|
+
````
|
|
208
|
+
```mcp
|
|
209
|
+
call: tools.github.create_issue
|
|
210
|
+
{"owner": "me", "repo": "project", "title": "The build fails on Node 22"}
|
|
211
|
+
```
|
|
212
|
+
````
|
|
213
|
+
|
|
214
|
+
Scalar arguments may instead be written as `key: value` lines, like any other fenced
|
|
215
|
+
tool; a value that reads as a JSON number, boolean or null is passed as one:
|
|
216
|
+
|
|
217
|
+
````
|
|
218
|
+
```mcp
|
|
219
|
+
call: tools.github.get_issue
|
|
220
|
+
owner: me
|
|
221
|
+
repo: project
|
|
222
|
+
issue_number: 42
|
|
223
|
+
```
|
|
224
|
+
````
|
|
225
|
+
|
|
226
|
+
The proxy turns that block into an `execute` call for opencode to run, with the code
|
|
227
|
+
`return await tools.github.create_issue({"owner":"me",…});`, and opencode's result comes
|
|
228
|
+
back to M365 as an ordinary tool result. In the history M365 is sent, those `execute`
|
|
229
|
+
calls are written back as the `mcp` blocks it wrote. A path that is not in the
|
|
230
|
+
catalogue, or a block the proxy cannot read, is answered in the proxy with a short note
|
|
231
|
+
on what to write instead; nothing reaches opencode. M365 sees the lean set plus one
|
|
232
|
+
tool however many MCP tools you have.
|
|
233
|
+
|
|
234
|
+
When opencode marks its catalogue as **partial** (it lists only some of its tools and
|
|
235
|
+
offers a `search(...)` function for the rest), a search that matches nothing in the
|
|
236
|
+
listed part goes to opencode's own search instead, as an `execute` call with the code
|
|
237
|
+
`return await search("…");`. Its result comes back as a tool result, and a
|
|
238
|
+
well-formed `tools.…` path it returns may then be called even though the catalogue does
|
|
239
|
+
not list it.
|
|
240
|
+
|
|
241
|
+
- **Opt-in.** `mcpProxy` is `false` by default. It takes effect when a request carries a
|
|
242
|
+
Code Mode catalogue and offers `execute`. A standalone `opencode-m365 serve` proxy
|
|
243
|
+
takes `M365_MCP_PROXY=1` instead.
|
|
244
|
+
- **Cost.** Each search answered in the proxy is one extra M365 message in the same
|
|
245
|
+
conversation, like the give-up nudge; it does not start a new conversation. So is the
|
|
246
|
+
note for an unknown path or an unreadable block.
|
|
247
|
+
- **Cap.** At most 3 searches per request, counting those notes. A reply that is still
|
|
248
|
+
an `mcp` block after the third is returned as its prose, and an `mcp` block never
|
|
249
|
+
reaches opencode as an `mcp` tool call.
|
|
250
|
+
- **Not yet measured on a live tenant.** The flow is covered against the offline stub
|
|
251
|
+
only; whether M365 searches and then calls reliably has not been measured.
|
|
252
|
+
|
|
253
|
+
With `M365_TURN_LOG` set, each search is a turn of its own in the log, marked with
|
|
254
|
+
`mcpSearch` and the query. A turn whose reply became an `execute` call is marked with
|
|
255
|
+
`mcpCall` and the tool's path, or `search` when it went to opencode's own search.
|
|
256
|
+
|
|
167
257
|
## opencode 2
|
|
168
258
|
|
|
169
259
|
This is an opencode 2 plugin (`@opencode/cli`, `@opencode/plugin`): its default export
|
|
@@ -188,7 +278,7 @@ any options you set on it, and leaves other plugins' entries alone.
|
|
|
188
278
|
### Verified how far
|
|
189
279
|
|
|
190
280
|
Against a real opencode 2.2.5, end to end, with the proxy running against the offline
|
|
191
|
-
stub rather than Microsoft: the plugin loads from a directory, registers
|
|
281
|
+
stub rather than Microsoft: the plugin loads from a directory, registers the whole model catalogue,
|
|
192
282
|
an attached image is uploaded and attached to the turn, and the session title is
|
|
193
283
|
answered locally — one chat turn reaches the backend, not two. The catalog records are
|
|
194
284
|
also checked against the real `@opencode/plugin` schema constructors in the test suite.
|
|
@@ -203,6 +293,7 @@ That stub run says nothing about Microsoft's side; see [Development](#developmen
|
|
|
203
293
|
"options": {
|
|
204
294
|
"lean": true, // trim the toolset (default: true)
|
|
205
295
|
"leanSystemPrompt": false, // replace opencode's prose prompt (default: false)
|
|
296
|
+
"mcpProxy": false, // reach MCP tools only through one `mcp` tool (default: false)
|
|
206
297
|
"setDefaultModel": true, // set `model` if you have not (default: true)
|
|
207
298
|
"setSmallModel": true, // answer session titles locally (default: true)
|
|
208
299
|
"baseUrl": null, // use an already-running proxy instead of an in-process one
|
|
@@ -257,6 +348,20 @@ on the real model — they are real work, and only titling opens the extra conve
|
|
|
257
348
|
|
|
258
349
|
Models are selected by an M365 *tone*, not a model id. `m365/quick` is the default.
|
|
259
350
|
|
|
351
|
+
Each model is listed once. Older short ids (`auto`, `claude`, `gpt-5.4`, `gpt-5.3` and
|
|
352
|
+
`gpt-5.2`) used to appear alongside their descriptive twins (`m365-copilot`, `claude-sonnet`,
|
|
353
|
+
`gpt-5.4-think-deeper`, `gpt-5.3-quick`, `gpt-5.2-quick`), so the picker showed them twice.
|
|
354
|
+
They are no longer listed, but they are still accepted, with or without the `m365/`
|
|
355
|
+
prefix, so a saved config that names one keeps working.
|
|
356
|
+
|
|
357
|
+
**GPT-6 Sol** (`m365/gpt-6.2-sol`, `m365/gpt-6.1-sol`, `m365/gpt-6-sol`) are reasoning
|
|
358
|
+
models that every account can reach. Their tool turns go **without** the Copilot Studio
|
|
359
|
+
agent: the reference project's notes find that Sol serves with the agent only on a
|
|
360
|
+
premium account, and on any other account that route returns nothing. Without the agent
|
|
361
|
+
the fenced tool contract still applies, but tool use is less reliable, and Sol has a
|
|
362
|
+
remote bash sandbox of its own (`/mnt/data`), so its tool turns use the relay framing
|
|
363
|
+
and ask it to use your terminal instead. Their tool calling has not been measured here.
|
|
364
|
+
|
|
260
365
|
Tool-calling on a live tenant (2026-11-09, one non-Premium account, a single file-read
|
|
261
366
|
task per run; small samples):
|
|
262
367
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { C as writePrivateFile, h as POWERPLATFORM_SCOPE, p as BAP_SCOPE, w as AGENT_FILE, x as createLogger } from "./server-DXznAk1h.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 {
|
|
3
|
-
import { t as getOrCreateAgent } from "./agent-
|
|
2
|
+
import { D as SECRETS_FILE, E as CONFIG_DIR, F as LOCAL_TITLE_MODEL, I as MODELS, M as mergeOpencodeConfig, P as DEFAULT_MODEL, T as CACHE_FILE, b as createTokenClient, d as CopilotSession, k as PROVIDER_ID, s as startServer, w as AGENT_FILE } from "./server-DXznAk1h.mjs";
|
|
3
|
+
import { t as getOrCreateAgent } from "./agent-DPNplWJY.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";
|
|
@@ -59,7 +59,8 @@ function printHelp() {
|
|
|
59
59
|
login [--interactive] Sign in to Microsoft 365 and store the token cache
|
|
60
60
|
setup [--local] Add the plugin to ~/.config/opencode/opencode.json
|
|
61
61
|
serve [--port <n>] Run the OpenAI-compatible proxy standalone
|
|
62
|
-
(key from M365_PROXY_KEY, else printed
|
|
62
|
+
(key from M365_PROXY_KEY, else printed;
|
|
63
|
+
M365_MCP_PROXY=1 enables the MCP proxy)
|
|
63
64
|
doctor [--live] Check auth, the agent, and the proxy
|
|
64
65
|
(--live also sends one short message per model tone)
|
|
65
66
|
|
|
@@ -70,7 +71,7 @@ to complete SSO/MFA by hand once — the only option on tenants with push-only
|
|
|
70
71
|
MFA, FIDO2, or a federated IdP.`);
|
|
71
72
|
}
|
|
72
73
|
async function doLogin(args) {
|
|
73
|
-
const { login } = await import("./login-
|
|
74
|
+
const { login } = await import("./login-Cts_gng-.mjs");
|
|
74
75
|
const interactive = args.includes("--interactive");
|
|
75
76
|
try {
|
|
76
77
|
const account = await login({
|
|
@@ -150,6 +151,7 @@ async function doServe(args) {
|
|
|
150
151
|
getToken: () => tokens.getToken(),
|
|
151
152
|
resolveAgent: () => getOrCreateAgent({ getTokenForScope: (scopes) => tokens.getTokenForScope(scopes) }),
|
|
152
153
|
port,
|
|
154
|
+
mcpProxy: process.env.M365_MCP_PROXY === "1",
|
|
153
155
|
...fixedKey ? { apiKey: fixedKey } : {}
|
|
154
156
|
});
|
|
155
157
|
console.log(`M365 Copilot proxy listening on ${proxy.url}`);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { B as __toESM, R as __commonJSMin, z as __require } from "./server-DXznAk1h.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 {
|
|
1
|
+
import { D as SECRETS_FILE, E as CONFIG_DIR, S as ensurePrivateDir, _ as SYDNEY_SCOPES, f as AUTHORITY, g as REDIRECT_URI, l as object, m as CLIENT_ID, u as string, v as authCodeFromUrl, x as createLogger, y as createCachePlugin } from "./server-DXznAk1h.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-
|
|
99
|
+
const { PublicClientApplication, CryptoProvider } = await import("./dist-QjFnJhR3.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 {
|
|
2
|
-
import { t as getOrCreateAgent } from "./agent-
|
|
1
|
+
import { A as buildModelInfos, L as isLocalModel, N as resolveOptions, O as PLUGIN_ID, P as DEFAULT_MODEL, b as createTokenClient, i as SESSION_ID_HEADER, j as buildProviderInfo, k as PROVIDER_ID, s as startServer, t as AUX_REQUEST_KIND_HEADER, x as createLogger } from "./server-DXznAk1h.mjs";
|
|
2
|
+
import { t as getOrCreateAgent } from "./agent-DPNplWJY.mjs";
|
|
3
3
|
// src/runtime.ts
|
|
4
4
|
/**
|
|
5
5
|
* What the plugin stands on: the OpenAI-compatible proxy, started in-process (or an
|
|
@@ -63,6 +63,7 @@ async function startRuntime(rawOptions) {
|
|
|
63
63
|
getToken: () => tokens.getToken(),
|
|
64
64
|
resolveAgent: () => getOrCreateAgent({ getTokenForScope: (scopes) => tokens.getTokenForScope(scopes) }),
|
|
65
65
|
lean: options.lean,
|
|
66
|
+
mcpProxy: options.mcpProxy,
|
|
66
67
|
...sharedKey ? { apiKey: sharedKey } : {},
|
|
67
68
|
...options.leanSystemPrompt ? { leanSystemPrompt: LEAN_SYSTEM_PROMPT } : {}
|
|
68
69
|
});
|
|
@@ -76,11 +77,20 @@ async function startRuntime(rawOptions) {
|
|
|
76
77
|
}
|
|
77
78
|
// src/plugin-v2.ts
|
|
78
79
|
const log = createLogger("plugin");
|
|
80
|
+
let warnedAboutDuplicate = false;
|
|
79
81
|
const setup = async (ctx) => {
|
|
80
82
|
const runtime = await startRuntime(ctx.options);
|
|
81
83
|
const info = buildProviderInfo(runtime.baseUrl, runtime.apiKey);
|
|
82
84
|
const models = buildModelInfos();
|
|
83
85
|
await ctx.provider.transform((editor) => {
|
|
86
|
+
const existing = editor.get?.(PROVIDER_ID);
|
|
87
|
+
if (existing && existing.provider.name === info.name) {
|
|
88
|
+
if (!warnedAboutDuplicate) {
|
|
89
|
+
warnedAboutDuplicate = true;
|
|
90
|
+
log.warn("opencode-m365-copilot is loaded more than once; keeping the first. Check your opencode config for a second plugin entry (an npm name and a checkout directory, or opencode.json and opencode.jsonc).");
|
|
91
|
+
}
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
84
94
|
editor.add({
|
|
85
95
|
info,
|
|
86
96
|
models
|
|
@@ -61,26 +61,24 @@ const DEFAULT_MODEL = "quick";
|
|
|
61
61
|
const MODELS = [
|
|
62
62
|
m("work", "Ask your mail, Teams & files", "magic", false, true),
|
|
63
63
|
m("work-think", "Ask your mail, Teams & files (Think Deeper)", "Gpt_5_5_Reasoning", true, true),
|
|
64
|
+
m("gpt-6.2-sol", "GPT-6.2 Sol", "Gpt_62_Sol_Reasoning", true),
|
|
65
|
+
m("gpt-6.1-sol", "GPT-6.1 Sol", "Gpt_61_Sol_Reasoning", true),
|
|
66
|
+
m("gpt-6-sol", "GPT-6 Sol", "Gpt_6_Sol_Reasoning", true),
|
|
64
67
|
m("gpt-5.6-think-deeper", "GPT-5.6 (Think Deeper)", "Gpt_5_6_Reasoning", true),
|
|
65
68
|
m("gpt-5.5-think-deeper", "GPT-5.5 (Think Deeper)", "Gpt_5_5_Reasoning", true),
|
|
66
69
|
m("gpt-5.5", "GPT-5.5", "Gpt_5_5_Chat", false),
|
|
67
70
|
m("gpt-5.5-quick", "GPT-5.5 (Quick)", "Gpt_5_5_Chat", false),
|
|
68
71
|
m("m365-copilot", "M365 Copilot (Auto)", "magic", false),
|
|
69
|
-
m("auto", "M365 Copilot (Auto)", "magic", false),
|
|
70
72
|
m("quick", "GPT (Quick)", "Gpt_5_5_Chat", false),
|
|
71
73
|
m("think-deeper", "GPT (Think Deeper)", "Gpt_5_5_Reasoning", true),
|
|
72
74
|
m("gpt-5.6", "GPT-5.6 (unreliable tool calls)", "Gpt_5_6_Chat", false),
|
|
73
75
|
m("gpt-5.6-quick", "GPT-5.6 (Quick, unreliable tool calls)", "Gpt_5_6_Chat", false),
|
|
74
76
|
m("claude-sonnet", "Claude Sonnet (via M365)", "Claude_Sonnet", false),
|
|
75
|
-
m("claude", "Claude Sonnet (via M365)", "Claude_Sonnet", false),
|
|
76
77
|
m("claude-sonnet-think-deeper", "Claude Sonnet (Think Deeper)", "Claude_Sonnet_Reasoning", true),
|
|
77
|
-
m("gpt-5.4", "GPT-5.4 (Think Deeper)", "Gpt_5_4_Reasoning", true),
|
|
78
78
|
m("gpt-5.4-think-deeper", "GPT-5.4 (Think Deeper)", "Gpt_5_4_Reasoning", true),
|
|
79
79
|
m("gpt-5.4-quick", "GPT-5.4 (Quick)", "Gpt_5_4_Chat", false),
|
|
80
|
-
m("gpt-5.3", "GPT-5.3 (Quick)", "Gpt_5_3_Chat", false),
|
|
81
80
|
m("gpt-5.3-quick", "GPT-5.3 (Quick)", "Gpt_5_3_Chat", false),
|
|
82
81
|
m("gpt-5.3-think-deeper", "GPT-5.3 (Think Deeper)", "Gpt_5_3_Reasoning", true),
|
|
83
|
-
m("gpt-5.2", "GPT-5.2 (Quick)", "Gpt_5_2_Chat", false),
|
|
84
82
|
m("gpt-5.2-quick", "GPT-5.2 (Quick)", "Gpt_5_2_Chat", false),
|
|
85
83
|
m("gpt-5.2-think-deeper", "GPT-5.2 (Think Deeper)", "Gpt_5_2_Reasoning", true),
|
|
86
84
|
m(LOCAL_TITLE_MODEL, "Local titler (no M365 call)", null, false)
|
|
@@ -107,11 +105,32 @@ function pickerName(name, tone, grounded) {
|
|
|
107
105
|
if (tone === null) return name;
|
|
108
106
|
return `${grounded ? "Work" : "Code"} · ${name}`;
|
|
109
107
|
}
|
|
108
|
+
/**
|
|
109
|
+
* Ids we accept but no longer advertise, each mapped to the canonical id it means.
|
|
110
|
+
*
|
|
111
|
+
* Each pair used to be advertised twice under one picker name, so opencode listed the
|
|
112
|
+
* model twice. The canonical id is the descriptive one: `m365-copilot` is the id the
|
|
113
|
+
* README documents and measured, and the GPT ids carry their tone suffix like their
|
|
114
|
+
* siblings (`-quick`, `-think-deeper`). The short forms stay accepted, with or without
|
|
115
|
+
* the `m365/` prefix, so saved configs keep working.
|
|
116
|
+
*/
|
|
117
|
+
const MODEL_ALIASES = {
|
|
118
|
+
auto: "m365-copilot",
|
|
119
|
+
claude: "claude-sonnet",
|
|
120
|
+
"gpt-5.4": "gpt-5.4-think-deeper",
|
|
121
|
+
"gpt-5.3": "gpt-5.3-quick",
|
|
122
|
+
"gpt-5.2": "gpt-5.2-quick"
|
|
123
|
+
};
|
|
110
124
|
const BY_ID = new Map(MODELS.map((model) => [model.id, model]));
|
|
125
|
+
for (const [alias, canonical] of Object.entries(MODEL_ALIASES)) {
|
|
126
|
+
const model = BY_ID.get(canonical);
|
|
127
|
+
if (!model) throw new Error(`model alias ${alias} points at unknown id ${canonical}`);
|
|
128
|
+
BY_ID.set(alias, model);
|
|
129
|
+
}
|
|
111
130
|
/**
|
|
112
131
|
* Look up a model, falling back to the default for anything we do not know.
|
|
113
132
|
*
|
|
114
|
-
* Harnesses routinely send ids we never advertised (
|
|
133
|
+
* Harnesses routinely send ids we never advertised (`MODEL_ALIASES`, stale config, a model
|
|
115
134
|
* string typed by hand). Answering on the default beats rejecting the request.
|
|
116
135
|
*/
|
|
117
136
|
function resolveModel(id) {
|
|
@@ -145,7 +164,22 @@ function listModelIds() {
|
|
|
145
164
|
* (`ClaudeUnavailableForLicense`), where today it quietly gets GPT. Unmeasured on a
|
|
146
165
|
* licensed account, so not adopted.
|
|
147
166
|
*/
|
|
167
|
+
/**
|
|
168
|
+
* GPT-6 Sol tones. With the declarative agent attached they serve only on a premium
|
|
169
|
+
* account; on any other account that is a dead route (`InternalError`, no content).
|
|
170
|
+
* Nothing on the token says which kind of account it is, so they always go agent-less.
|
|
171
|
+
* Agent-less, Sol runs commands in a remote bash sandbox of its own, so the relay note
|
|
172
|
+
* names it and asks for the user's terminal instead. From the reference project's
|
|
173
|
+
* protocol notes (`m365-copilot-api.md`, the Sol rows and quirk #21).
|
|
174
|
+
*/
|
|
175
|
+
const SOL_TONE = /^Gpt_\d+_Sol_Reasoning$/;
|
|
176
|
+
const SOL_SANDBOX = "the bash sandbox with /mnt/data and /home/oai";
|
|
148
177
|
function toolRouteFor(tone) {
|
|
178
|
+
if (tone && SOL_TONE.test(tone)) return {
|
|
179
|
+
framing: "relay",
|
|
180
|
+
agent: false,
|
|
181
|
+
sandbox: SOL_SANDBOX
|
|
182
|
+
};
|
|
149
183
|
if (tone?.startsWith("Gpt_") && tone.endsWith("_Reasoning")) return {
|
|
150
184
|
framing: "relay",
|
|
151
185
|
agent: true
|
|
@@ -398,6 +432,15 @@ function extractFences(source) {
|
|
|
398
432
|
}
|
|
399
433
|
return fences;
|
|
400
434
|
}
|
|
435
|
+
/**
|
|
436
|
+
* The body of the first closed fence whose info string names `name` (case-insensitive),
|
|
437
|
+
* or undefined. For a tool whose body the proxy reads itself rather than mapping it
|
|
438
|
+
* onto parameters.
|
|
439
|
+
*/
|
|
440
|
+
function firstFenceBody(source, name) {
|
|
441
|
+
const wanted = name.toLowerCase();
|
|
442
|
+
return extractFences(unglueFenceOpeners(source.replace(/\r\n?/g, "\n"))).find((fence) => (fence.info.split(/\s+/)[0] ?? "").toLowerCase() === wanted)?.body;
|
|
443
|
+
}
|
|
401
444
|
function charOffset(lines, lineIndex) {
|
|
402
445
|
let offset = 0;
|
|
403
446
|
for (let i = 0; i < lineIndex && i < lines.length; i += 1) offset += lines[i].length + 1;
|
|
@@ -444,9 +487,20 @@ function stripInventedJson(text) {
|
|
|
444
487
|
result = result.replace(/^\s*\{\s*"final"\s*:\s*(?:"(?:[^"\\]|\\.)*"|[^}]*)\}\s*$/gm, "");
|
|
445
488
|
return result.trim();
|
|
446
489
|
}
|
|
490
|
+
/**
|
|
491
|
+
* Move a fence opener glued to the end of a prose line onto its own line.
|
|
492
|
+
*
|
|
493
|
+
* M365 sometimes writes `…before drafting anything.```shell` with no line break, so the
|
|
494
|
+
* block rendered as text, nothing ran, and the user had to say "resume" (seen live,
|
|
495
|
+
* 2026-11-19). Only an opener with an info word ends the line; an inline ```bash```
|
|
496
|
+
* span does not match, and an unclosed fence is still ignored by `extractFences`.
|
|
497
|
+
*/
|
|
498
|
+
function unglueFenceOpeners(text) {
|
|
499
|
+
return text.replace(/^(.*[^`\s])(`{3,}[A-Za-z][\w-]*)[ \t]*$/gm, "$1\n$2");
|
|
500
|
+
}
|
|
447
501
|
/** Parse a raw M365 response into OpenAI-shaped tool calls plus any prose. */
|
|
448
502
|
function parseToolCalls(source, tools, options = {}) {
|
|
449
|
-
const cleaned = stripInventedJson(source.replace(/\r\n?/g, "\n"));
|
|
503
|
+
const cleaned = unglueFenceOpeners(stripInventedJson(source.replace(/\r\n?/g, "\n")));
|
|
450
504
|
const none = (text) => ({
|
|
451
505
|
toolCalls: [],
|
|
452
506
|
text,
|
|
@@ -708,6 +762,7 @@ function resolveOptions(raw) {
|
|
|
708
762
|
setDefaultModel: bool(options.setDefaultModel, true),
|
|
709
763
|
setSmallModel: bool(options.setSmallModel, true),
|
|
710
764
|
leanSystemPrompt: bool(options.leanSystemPrompt, false),
|
|
765
|
+
mcpProxy: bool(options.mcpProxy, false),
|
|
711
766
|
baseUrl: typeof options.baseUrl === "string" ? options.baseUrl : void 0,
|
|
712
767
|
apiKey: typeof options.apiKey === "string" && options.apiKey !== "" ? options.apiKey : void 0
|
|
713
768
|
};
|
|
@@ -779,6 +834,7 @@ const OUR_OPTION_KEYS = /* @__PURE__ */ new Set([
|
|
|
779
834
|
"setDefaultModel",
|
|
780
835
|
"setSmallModel",
|
|
781
836
|
"leanSystemPrompt",
|
|
837
|
+
"mcpProxy",
|
|
782
838
|
"baseUrl",
|
|
783
839
|
"apiKey"
|
|
784
840
|
]);
|
|
@@ -1111,7 +1167,7 @@ function createTokenClient(options = {}) {
|
|
|
1111
1167
|
const cache = /* @__PURE__ */ new Map();
|
|
1112
1168
|
async function client() {
|
|
1113
1169
|
if (app) return app;
|
|
1114
|
-
const { PublicClientApplication } = await import("./dist-
|
|
1170
|
+
const { PublicClientApplication } = await import("./dist-QjFnJhR3.mjs");
|
|
1115
1171
|
app = new PublicClientApplication({
|
|
1116
1172
|
auth: {
|
|
1117
1173
|
clientId: CLIENT_ID,
|
|
@@ -1174,6 +1230,533 @@ function authCodeFromUrl(rawUrl) {
|
|
|
1174
1230
|
}
|
|
1175
1231
|
return url.searchParams.get("code") ?? void 0;
|
|
1176
1232
|
}
|
|
1233
|
+
// src/codemode.ts
|
|
1234
|
+
const HEADING = /^# Code Mode[ \t]*$/m;
|
|
1235
|
+
const NAMESPACE_LINE = /^- \S+ \(\d+ tools?\)/;
|
|
1236
|
+
const ENTRY_LINE = /^ {2}(?:- )?(tools[.[].*)$/;
|
|
1237
|
+
const PATH_SEGMENT = /\.([A-Za-z_$][\w$]*)|\["([^"]+)"\]/y;
|
|
1238
|
+
/** Where the section ended before the catalogue was parsed by depth; the fallback when it has no entries. */
|
|
1239
|
+
const LEGACY_END = /^# |^Skills provide |^<[a-z_]+>/m;
|
|
1240
|
+
/** A structured block at column 0 always ends the catalogue, even mid-signature. */
|
|
1241
|
+
const BLOCK_LINE = /^<\/?[a-z_]+>/;
|
|
1242
|
+
function splitLines(text, from) {
|
|
1243
|
+
const lines = [];
|
|
1244
|
+
let start = from;
|
|
1245
|
+
while (start < text.length) {
|
|
1246
|
+
const newline = text.indexOf("\n", start);
|
|
1247
|
+
const end = newline === -1 ? text.length : newline + 1;
|
|
1248
|
+
lines.push({
|
|
1249
|
+
text: text.slice(start, newline === -1 ? text.length : newline),
|
|
1250
|
+
start,
|
|
1251
|
+
end
|
|
1252
|
+
});
|
|
1253
|
+
start = end;
|
|
1254
|
+
}
|
|
1255
|
+
return lines;
|
|
1256
|
+
}
|
|
1257
|
+
/**
|
|
1258
|
+
* Walk one line of a TypeScript signature, tracking bracket depth outside comments and
|
|
1259
|
+
* string literals. Returns the new state, plus where a ` // ` line comment starts at
|
|
1260
|
+
* depth 0 (the entry's description), if one does.
|
|
1261
|
+
*/
|
|
1262
|
+
function scanLine(line, state) {
|
|
1263
|
+
let quote;
|
|
1264
|
+
for (let i = 0; i < line.length; i++) {
|
|
1265
|
+
const char = line[i];
|
|
1266
|
+
if (state.inComment) {
|
|
1267
|
+
if (char === "*" && line[i + 1] === "/") {
|
|
1268
|
+
state.inComment = false;
|
|
1269
|
+
i++;
|
|
1270
|
+
}
|
|
1271
|
+
continue;
|
|
1272
|
+
}
|
|
1273
|
+
if (quote) {
|
|
1274
|
+
if (char === "\\") i++;
|
|
1275
|
+
else if (char === quote) quote = void 0;
|
|
1276
|
+
continue;
|
|
1277
|
+
}
|
|
1278
|
+
if (char === "/" && line[i + 1] === "*") {
|
|
1279
|
+
state.inComment = true;
|
|
1280
|
+
i++;
|
|
1281
|
+
} else if (char === "/" && line[i + 1] === "/") return state.depth <= 0 ? { descriptionAt: i + 2 } : {};
|
|
1282
|
+
else if (char === "\"" || char === "'" || char === "`") quote = char;
|
|
1283
|
+
else if ("({[".includes(char)) state.depth++;
|
|
1284
|
+
else if (")}]".includes(char)) state.depth--;
|
|
1285
|
+
}
|
|
1286
|
+
return {};
|
|
1287
|
+
}
|
|
1288
|
+
function splitPath(path) {
|
|
1289
|
+
if (!path.startsWith("tools")) return void 0;
|
|
1290
|
+
const segments = [];
|
|
1291
|
+
PATH_SEGMENT.lastIndex = 5;
|
|
1292
|
+
while (PATH_SEGMENT.lastIndex < path.length) {
|
|
1293
|
+
const match = PATH_SEGMENT.exec(path);
|
|
1294
|
+
if (!match) return void 0;
|
|
1295
|
+
segments.push(match[1] ?? match[2]);
|
|
1296
|
+
}
|
|
1297
|
+
if (segments.length < 2) return void 0;
|
|
1298
|
+
return {
|
|
1299
|
+
namespace: segments[0],
|
|
1300
|
+
name: segments.slice(1).join(".")
|
|
1301
|
+
};
|
|
1302
|
+
}
|
|
1303
|
+
/** Parse the Code Mode catalogue out of a system prompt, or undefined if there is none. */
|
|
1304
|
+
function parseCodeModeCatalog(systemText) {
|
|
1305
|
+
const heading = HEADING.exec(systemText);
|
|
1306
|
+
if (!heading) return void 0;
|
|
1307
|
+
const start = heading.index;
|
|
1308
|
+
const lines = splitLines(systemText, start + heading[0].length);
|
|
1309
|
+
const tools = [];
|
|
1310
|
+
let catalogueEnd;
|
|
1311
|
+
let preamble = "";
|
|
1312
|
+
let i = 0;
|
|
1313
|
+
for (; i < lines.length && !NAMESPACE_LINE.test(lines[i].text); i++) {
|
|
1314
|
+
if (/^# |^<[a-z_]+>/.test(lines[i].text)) break;
|
|
1315
|
+
preamble += `${lines[i].text}\n`;
|
|
1316
|
+
}
|
|
1317
|
+
const partial = /\bcatalog(?:ue)? is partial\b/i.test(preamble);
|
|
1318
|
+
while (i < lines.length) {
|
|
1319
|
+
const line = lines[i];
|
|
1320
|
+
if (NAMESPACE_LINE.test(line.text)) {
|
|
1321
|
+
catalogueEnd = line.end;
|
|
1322
|
+
i++;
|
|
1323
|
+
continue;
|
|
1324
|
+
}
|
|
1325
|
+
const entry = ENTRY_LINE.exec(line.text);
|
|
1326
|
+
if (entry) {
|
|
1327
|
+
const state = {
|
|
1328
|
+
depth: 0,
|
|
1329
|
+
inComment: false
|
|
1330
|
+
};
|
|
1331
|
+
const entryLines = [];
|
|
1332
|
+
let description = "";
|
|
1333
|
+
let j = i;
|
|
1334
|
+
for (; j < lines.length; j++) {
|
|
1335
|
+
const current = lines[j];
|
|
1336
|
+
if (j > i && !state.inComment && state.depth > 0 && BLOCK_LINE.test(current.text)) break;
|
|
1337
|
+
if (j > i && (NAMESPACE_LINE.test(current.text) || ENTRY_LINE.test(current.text)) && state.depth > 0 && !state.inComment) break;
|
|
1338
|
+
const text = j === i ? entry[1] : current.text;
|
|
1339
|
+
entryLines.push(text);
|
|
1340
|
+
const { descriptionAt } = scanLine(text, state);
|
|
1341
|
+
if (state.depth <= 0 && !state.inComment) {
|
|
1342
|
+
if (descriptionAt !== void 0) description = text.slice(descriptionAt).trim();
|
|
1343
|
+
j++;
|
|
1344
|
+
break;
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
const signature = entryLines.join("\n");
|
|
1348
|
+
const path = signature.slice(0, signature.indexOf("(")).trim();
|
|
1349
|
+
const parts = splitPath(path);
|
|
1350
|
+
if (parts) tools.push({
|
|
1351
|
+
path,
|
|
1352
|
+
...parts,
|
|
1353
|
+
signature,
|
|
1354
|
+
description
|
|
1355
|
+
});
|
|
1356
|
+
catalogueEnd = lines[j - 1].end;
|
|
1357
|
+
i = j;
|
|
1358
|
+
continue;
|
|
1359
|
+
}
|
|
1360
|
+
if (line.text.trim() === "") {
|
|
1361
|
+
i++;
|
|
1362
|
+
continue;
|
|
1363
|
+
}
|
|
1364
|
+
break;
|
|
1365
|
+
}
|
|
1366
|
+
let end;
|
|
1367
|
+
if (catalogueEnd === void 0) {
|
|
1368
|
+
const next = systemText.slice(start + heading[0].length).search(LEGACY_END);
|
|
1369
|
+
end = next === -1 ? systemText.length : start + heading[0].length + next;
|
|
1370
|
+
} else {
|
|
1371
|
+
end = catalogueEnd;
|
|
1372
|
+
while (end < systemText.length && systemText[end] === "\n") end++;
|
|
1373
|
+
}
|
|
1374
|
+
return {
|
|
1375
|
+
tools,
|
|
1376
|
+
partial,
|
|
1377
|
+
section: {
|
|
1378
|
+
start,
|
|
1379
|
+
end
|
|
1380
|
+
}
|
|
1381
|
+
};
|
|
1382
|
+
}
|
|
1383
|
+
/**
|
|
1384
|
+
* Remove opencode 2's whole `# Code Mode` section, from its heading to the end of the
|
|
1385
|
+
* catalogue. Text without one is returned unchanged.
|
|
1386
|
+
*/
|
|
1387
|
+
function stripCodeModeSection(systemText) {
|
|
1388
|
+
const catalog = parseCodeModeCatalog(systemText);
|
|
1389
|
+
if (!catalog) return systemText;
|
|
1390
|
+
return systemText.slice(0, catalog.section.start) + systemText.slice(catalog.section.end);
|
|
1391
|
+
}
|
|
1392
|
+
/** Score for a query that names a tool exactly, or a namespace's whole prefix. */
|
|
1393
|
+
const EXACT_SCORE = 1e3;
|
|
1394
|
+
const NAME_WEIGHT = 3;
|
|
1395
|
+
const DESCRIPTION_WEIGHT = 1;
|
|
1396
|
+
/** Tools named per server in the summary, and servers named, before "+N more". */
|
|
1397
|
+
const SUMMARY_TOOLS_PER_SERVER = 4;
|
|
1398
|
+
const SUMMARY_SERVERS = 8;
|
|
1399
|
+
/** A call path: `tools` then dotted identifiers or `["bracketed"]` names, nothing else. */
|
|
1400
|
+
const CALL_PATH = /^tools(?:\.[A-Za-z_$][\w$]*|\["[^"\\]+"\])+$/;
|
|
1401
|
+
const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
|
|
1402
|
+
/** Group `[key, value]` pairs by key, keeping first-seen order. */
|
|
1403
|
+
function groupBy(items, key, value) {
|
|
1404
|
+
const groups = /* @__PURE__ */ new Map();
|
|
1405
|
+
for (const item of items) {
|
|
1406
|
+
const group = groups.get(key(item)) ?? [];
|
|
1407
|
+
group.push(value(item));
|
|
1408
|
+
groups.set(key(item), group);
|
|
1409
|
+
}
|
|
1410
|
+
return groups;
|
|
1411
|
+
}
|
|
1412
|
+
/** `server (a, b, +3 more), other (c)`, at most eight servers, then how many more. */
|
|
1413
|
+
function summarise(servers) {
|
|
1414
|
+
const entries = [...servers].slice(0, SUMMARY_SERVERS).map(([server, tools]) => {
|
|
1415
|
+
if (tools.length === 0) return server;
|
|
1416
|
+
const shown = tools.slice(0, SUMMARY_TOOLS_PER_SERVER);
|
|
1417
|
+
const more = tools.length - shown.length;
|
|
1418
|
+
return `${server} (${[...shown, ...more > 0 ? [`+${more} more`] : []].join(", ")})`;
|
|
1419
|
+
});
|
|
1420
|
+
const hidden = servers.size - SUMMARY_SERVERS;
|
|
1421
|
+
return entries.join(", ") + (hidden > 0 ? `, and ${hidden} more servers` : "");
|
|
1422
|
+
}
|
|
1423
|
+
/** The catalogue grouped by namespace, as one line: `github (create_issue, +2 more), slack (post_message)`. */
|
|
1424
|
+
function summariseCatalog(catalog) {
|
|
1425
|
+
return summarise(groupBy(catalog, (tool) => tool.namespace, (tool) => tool.name));
|
|
1426
|
+
}
|
|
1427
|
+
/**
|
|
1428
|
+
* The virtual tool offered to M365 in place of the catalogue. Gentle wording on
|
|
1429
|
+
* purpose: see `buildToolPrompt` on why prompt shape matters more than size.
|
|
1430
|
+
*
|
|
1431
|
+
* The description stays on one line with no sentence break: the tool block shows only
|
|
1432
|
+
* a description's first sentence, and the summary is what tells the model a search is
|
|
1433
|
+
* worth making and which words to use.
|
|
1434
|
+
*/
|
|
1435
|
+
function mcpTool(catalog, partial) {
|
|
1436
|
+
const count = catalog.length;
|
|
1437
|
+
const noun = count === 1 ? "tool" : "tools";
|
|
1438
|
+
const summary = summariseCatalog(catalog) + (partial ? ", and more not listed" : "");
|
|
1439
|
+
return {
|
|
1440
|
+
type: "function",
|
|
1441
|
+
function: {
|
|
1442
|
+
name: "mcp",
|
|
1443
|
+
description: `Use ${count}${partial ? "+" : ""} ${noun} from my MCP servers — ${summary} — by searching with a few words about what you want to do; the result shows how to call each match.`,
|
|
1444
|
+
parameters: {
|
|
1445
|
+
type: "object",
|
|
1446
|
+
properties: {
|
|
1447
|
+
search: {
|
|
1448
|
+
type: "string",
|
|
1449
|
+
description: "A few words describing the tool you need"
|
|
1450
|
+
},
|
|
1451
|
+
call: {
|
|
1452
|
+
type: "string",
|
|
1453
|
+
description: "The path of a tool a search showed you, with its arguments below"
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
}
|
|
1458
|
+
};
|
|
1459
|
+
}
|
|
1460
|
+
/** Lowercase words of two or more characters. */
|
|
1461
|
+
function words(text) {
|
|
1462
|
+
return text.toLowerCase().split(/[^a-z0-9]+/).filter((word) => word.length >= 2);
|
|
1463
|
+
}
|
|
1464
|
+
/** A tool name's words: split on `_`, `-` and camelCase boundaries. */
|
|
1465
|
+
function nameWords(name) {
|
|
1466
|
+
return words(name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2"));
|
|
1467
|
+
}
|
|
1468
|
+
/** Every way a model might write a tool's full name. */
|
|
1469
|
+
function spellings(tool) {
|
|
1470
|
+
return [
|
|
1471
|
+
tool.path,
|
|
1472
|
+
`${tool.namespace}.${tool.name}`,
|
|
1473
|
+
`${tool.namespace}_${tool.name}`,
|
|
1474
|
+
`tools.${tool.namespace}.${tool.name}`
|
|
1475
|
+
].map((spelling) => spelling.toLowerCase());
|
|
1476
|
+
}
|
|
1477
|
+
function isNamespacePrefix(query, namespace) {
|
|
1478
|
+
const ns = namespace.toLowerCase();
|
|
1479
|
+
return [
|
|
1480
|
+
`${ns}_`,
|
|
1481
|
+
`${ns}.`,
|
|
1482
|
+
`tools.${ns}`,
|
|
1483
|
+
`tools.${ns}.`
|
|
1484
|
+
].includes(query);
|
|
1485
|
+
}
|
|
1486
|
+
function scoreTool(query, queryWords, tool) {
|
|
1487
|
+
if (query === tool.name.toLowerCase() || spellings(tool).includes(query)) return EXACT_SCORE;
|
|
1488
|
+
if (isNamespacePrefix(query, tool.namespace)) return EXACT_SCORE;
|
|
1489
|
+
const inName = /* @__PURE__ */ new Set([...nameWords(tool.namespace), ...nameWords(tool.name)]);
|
|
1490
|
+
const inDescription = new Set(words(tool.description));
|
|
1491
|
+
let score = 0;
|
|
1492
|
+
for (const word of queryWords) {
|
|
1493
|
+
if (inName.has(word)) score += NAME_WEIGHT;
|
|
1494
|
+
if (inDescription.has(word)) score += DESCRIPTION_WEIGHT;
|
|
1495
|
+
}
|
|
1496
|
+
return score;
|
|
1497
|
+
}
|
|
1498
|
+
/**
|
|
1499
|
+
* Rank the catalogue against a search. Name (and namespace) hits weigh 3, description
|
|
1500
|
+
* hits 1; an exact name or path, or a namespace prefix, scores top. Tools that score
|
|
1501
|
+
* zero are dropped; ties keep catalogue order.
|
|
1502
|
+
*/
|
|
1503
|
+
function searchCatalog(query, catalog, limit = 5) {
|
|
1504
|
+
const normalised = query.trim().toLowerCase();
|
|
1505
|
+
if (!normalised) return [];
|
|
1506
|
+
const queryWords = [...new Set(words(normalised))];
|
|
1507
|
+
return catalog.map((tool, index) => ({
|
|
1508
|
+
tool,
|
|
1509
|
+
index,
|
|
1510
|
+
score: scoreTool(normalised, queryWords, tool)
|
|
1511
|
+
})).filter((entry) => entry.score > 0).sort((a, b) => b.score - a.score || a.index - b.index).slice(0, Math.max(0, limit)).map((entry) => entry.tool);
|
|
1512
|
+
}
|
|
1513
|
+
/**
|
|
1514
|
+
* The top-level parameter names of a catalogue signature: the keys of its first
|
|
1515
|
+
* argument's object type, outside doc comments and nested types.
|
|
1516
|
+
*/
|
|
1517
|
+
function argumentNames(signature) {
|
|
1518
|
+
const open = signature.indexOf("(");
|
|
1519
|
+
if (open === -1) return [];
|
|
1520
|
+
const names = [];
|
|
1521
|
+
let depth = 0;
|
|
1522
|
+
let inComment = false;
|
|
1523
|
+
let token = "";
|
|
1524
|
+
for (let i = open; i < signature.length; i++) {
|
|
1525
|
+
const char = signature[i];
|
|
1526
|
+
if (inComment) {
|
|
1527
|
+
if (char === "*" && signature[i + 1] === "/") {
|
|
1528
|
+
inComment = false;
|
|
1529
|
+
i++;
|
|
1530
|
+
}
|
|
1531
|
+
continue;
|
|
1532
|
+
}
|
|
1533
|
+
if (char === "/" && signature[i + 1] === "*") {
|
|
1534
|
+
inComment = true;
|
|
1535
|
+
i++;
|
|
1536
|
+
continue;
|
|
1537
|
+
}
|
|
1538
|
+
if ("({[<".includes(char)) {
|
|
1539
|
+
depth++;
|
|
1540
|
+
token = "";
|
|
1541
|
+
} else if (")}]".includes(char) || char === ">" && signature[i - 1] !== "=") {
|
|
1542
|
+
depth--;
|
|
1543
|
+
if (depth === 0) break;
|
|
1544
|
+
token = "";
|
|
1545
|
+
} else if (depth === 2 && (char === ":" || char === "?" && signature[i + 1] === ":")) {
|
|
1546
|
+
const name = token.trim();
|
|
1547
|
+
if (IDENTIFIER.test(name) && !names.includes(name)) names.push(name);
|
|
1548
|
+
token = "";
|
|
1549
|
+
if (char === "?") i++;
|
|
1550
|
+
} else if (depth === 2 && (char === "," || char === "\n")) token = "";
|
|
1551
|
+
else token += char;
|
|
1552
|
+
}
|
|
1553
|
+
return names;
|
|
1554
|
+
}
|
|
1555
|
+
/** The fence that calls a tool, with a placeholder for each of its parameters. */
|
|
1556
|
+
function callExample(tool) {
|
|
1557
|
+
const names = argumentNames(tool.signature);
|
|
1558
|
+
const args = names.length === 0 ? "" : `\n{${names.map((name) => `"${name}": "..."`).join(", ")}}`;
|
|
1559
|
+
return `\`\`\`mcp\ncall: ${tool.path}` + args + "\n```";
|
|
1560
|
+
}
|
|
1561
|
+
/**
|
|
1562
|
+
* The message sent back to M365 with a search's matches. It reads as a tool result:
|
|
1563
|
+
* each match's signature as opencode wrote it, then how to call one.
|
|
1564
|
+
*/
|
|
1565
|
+
function renderSearchResult(query, matches, total) {
|
|
1566
|
+
if (matches.length === 0) return `No tool matched "${query}". Try other words: ${total} tools are available.`;
|
|
1567
|
+
const lines = [
|
|
1568
|
+
`<tool_response tool="mcp">`,
|
|
1569
|
+
`Tools matching "${query}":`,
|
|
1570
|
+
""
|
|
1571
|
+
];
|
|
1572
|
+
for (const tool of matches) lines.push(`- ${tool.signature}`, "");
|
|
1573
|
+
lines.push("To call one, reply with an mcp block: `call:` and its path, then its arguments as a JSON object. For example:", callExample(matches[0]), "</tool_response>");
|
|
1574
|
+
return lines.join("\n");
|
|
1575
|
+
}
|
|
1576
|
+
/** The JSON number grammar: no leading zeros, hex, `+`, bare `.5` or `Infinity`. */
|
|
1577
|
+
const JSON_NUMBER = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
|
|
1578
|
+
/** A header value's own type: a JSON number, boolean or null is coerced; quotes are unwrapped. */
|
|
1579
|
+
function headerValue(raw) {
|
|
1580
|
+
const value = raw.trim();
|
|
1581
|
+
if (/^"(?:[^"\\]|\\.)*"$/.test(value)) try {
|
|
1582
|
+
return JSON.parse(value);
|
|
1583
|
+
} catch {
|
|
1584
|
+
return value.slice(1, -1);
|
|
1585
|
+
}
|
|
1586
|
+
if (/^'.*'$|^`.*`$/.test(value)) return value.slice(1, -1);
|
|
1587
|
+
if (value === "true") return true;
|
|
1588
|
+
if (value === "false") return false;
|
|
1589
|
+
if (value === "null") return null;
|
|
1590
|
+
if (JSON_NUMBER.test(value)) return Number(value);
|
|
1591
|
+
return value;
|
|
1592
|
+
}
|
|
1593
|
+
function isPlainObject$1(value) {
|
|
1594
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1595
|
+
}
|
|
1596
|
+
/** Read a call's arguments: a JSON object, or `key: value` lines. Empty means none. */
|
|
1597
|
+
function parseArguments(body) {
|
|
1598
|
+
const text = body.trim();
|
|
1599
|
+
if (text === "") return { args: {} };
|
|
1600
|
+
if (text.startsWith("{") || text.startsWith("[")) {
|
|
1601
|
+
let value;
|
|
1602
|
+
try {
|
|
1603
|
+
value = JSON.parse(text);
|
|
1604
|
+
} catch {
|
|
1605
|
+
return { invalid: "the arguments are not valid JSON" };
|
|
1606
|
+
}
|
|
1607
|
+
return isPlainObject$1(value) ? { args: value } : { invalid: "the arguments must be a JSON object" };
|
|
1608
|
+
}
|
|
1609
|
+
const args = {};
|
|
1610
|
+
for (const line of text.split("\n")) {
|
|
1611
|
+
if (line.trim() === "") continue;
|
|
1612
|
+
const header = /^\s*([A-Za-z_$][\w$]*)\s*:\s?(.*)$/.exec(line);
|
|
1613
|
+
if (!header) return { invalid: `"${line.trim()}" is neither a JSON object nor a key: value line` };
|
|
1614
|
+
args[header[1]] = headerValue(header[2]);
|
|
1615
|
+
}
|
|
1616
|
+
return { args };
|
|
1617
|
+
}
|
|
1618
|
+
/** A path as written: unwrap quotes and backticks, and split off a JS-style `(args)`. */
|
|
1619
|
+
function splitCallValue(raw) {
|
|
1620
|
+
let value = raw.trim();
|
|
1621
|
+
const wrapped = /^([`'])(.*)\1;?$/.exec(value);
|
|
1622
|
+
if (wrapped) value = wrapped[2].trim();
|
|
1623
|
+
value = value.replace(/;$/, "").trim();
|
|
1624
|
+
const paren = value.indexOf("(");
|
|
1625
|
+
if (paren !== -1 && value.endsWith(")")) return {
|
|
1626
|
+
path: value.slice(0, paren).trim(),
|
|
1627
|
+
inline: value.slice(paren + 1, -1)
|
|
1628
|
+
};
|
|
1629
|
+
return { path: value };
|
|
1630
|
+
}
|
|
1631
|
+
/**
|
|
1632
|
+
* Read an `mcp` block's body: `search: <words>`, or `call: <path>` followed by the
|
|
1633
|
+
* arguments. A body with no header is a search.
|
|
1634
|
+
*/
|
|
1635
|
+
function parseMcpBlock(body) {
|
|
1636
|
+
const lines = body.replace(/\r\n?/g, "\n").split("\n");
|
|
1637
|
+
while (lines.length > 0 && lines[0].trim() === "") lines.shift();
|
|
1638
|
+
if (lines.length === 0) return {
|
|
1639
|
+
kind: "invalid",
|
|
1640
|
+
reason: "the block is empty"
|
|
1641
|
+
};
|
|
1642
|
+
const header = /^\s*(search|call)\s*:\s?(.*)$/i.exec(lines[0]);
|
|
1643
|
+
if (!header) {
|
|
1644
|
+
const text = lines.join("\n").trim();
|
|
1645
|
+
if (text.startsWith("{")) return {
|
|
1646
|
+
kind: "invalid",
|
|
1647
|
+
reason: "the arguments need a `call:` line naming the tool"
|
|
1648
|
+
};
|
|
1649
|
+
return {
|
|
1650
|
+
kind: "search",
|
|
1651
|
+
query: text
|
|
1652
|
+
};
|
|
1653
|
+
}
|
|
1654
|
+
const rest = lines.slice(1).join("\n");
|
|
1655
|
+
if (header[1].toLowerCase() === "search") {
|
|
1656
|
+
const query = [header[2].trim(), rest.trim()].filter(Boolean).join(" ");
|
|
1657
|
+
return query ? {
|
|
1658
|
+
kind: "search",
|
|
1659
|
+
query
|
|
1660
|
+
} : {
|
|
1661
|
+
kind: "invalid",
|
|
1662
|
+
reason: "the search is empty"
|
|
1663
|
+
};
|
|
1664
|
+
}
|
|
1665
|
+
const { path, inline } = splitCallValue(header[2]);
|
|
1666
|
+
if (!path) return {
|
|
1667
|
+
kind: "invalid",
|
|
1668
|
+
reason: "`call:` names no tool"
|
|
1669
|
+
};
|
|
1670
|
+
const parsed = parseArguments(inline !== void 0 && rest.trim() === "" ? inline : rest);
|
|
1671
|
+
if ("invalid" in parsed) return {
|
|
1672
|
+
kind: "invalid",
|
|
1673
|
+
reason: parsed.invalid
|
|
1674
|
+
};
|
|
1675
|
+
return {
|
|
1676
|
+
kind: "call",
|
|
1677
|
+
path,
|
|
1678
|
+
args: parsed.args
|
|
1679
|
+
};
|
|
1680
|
+
}
|
|
1681
|
+
/**
|
|
1682
|
+
* The exact path to call for what the model wrote, or undefined if it may not be
|
|
1683
|
+
* called. A catalogued tool is accepted however the model spelled it; when opencode
|
|
1684
|
+
* says the catalogue is partial, any well-formed `tools` path is too, because opencode's
|
|
1685
|
+
* own search can return tools the catalogue leaves out.
|
|
1686
|
+
*/
|
|
1687
|
+
function resolveCallPath(written, catalog, partial) {
|
|
1688
|
+
const wanted = written.trim().toLowerCase();
|
|
1689
|
+
const known = catalog.find((tool) => spellings(tool).includes(wanted));
|
|
1690
|
+
if (known) return known.path;
|
|
1691
|
+
if (partial && CALL_PATH.test(written.trim())) return written.trim();
|
|
1692
|
+
}
|
|
1693
|
+
/** A complete answer to M365 for a path that is not a tool. */
|
|
1694
|
+
function renderUnknownTool(path) {
|
|
1695
|
+
return [
|
|
1696
|
+
`<tool_response tool="mcp">`,
|
|
1697
|
+
`There is no tool ${path}. Search first, and call a path exactly as the search shows it:`,
|
|
1698
|
+
"```mcp\nsearch: a few words about what you want to do\n```",
|
|
1699
|
+
"</tool_response>"
|
|
1700
|
+
].join("\n");
|
|
1701
|
+
}
|
|
1702
|
+
/** A complete answer to M365 for an `mcp` block it could not read, with the expected shape. */
|
|
1703
|
+
function renderInvalidMcpBlock(reason) {
|
|
1704
|
+
return [
|
|
1705
|
+
`<tool_response tool="mcp">`,
|
|
1706
|
+
`That mcp block could not be read: ${reason}. Search with:`,
|
|
1707
|
+
"```mcp\nsearch: a few words about what you want to do\n```",
|
|
1708
|
+
"or call a tool a search showed you, with its arguments as a JSON object:",
|
|
1709
|
+
"```mcp\ncall: tools.<server>.<tool>\n{\"<argument>\": \"<value>\"}\n```",
|
|
1710
|
+
"</tool_response>"
|
|
1711
|
+
].join("\n");
|
|
1712
|
+
}
|
|
1713
|
+
/** The code opencode's `execute` runs for a call. */
|
|
1714
|
+
function callCode(path, args) {
|
|
1715
|
+
return "return await " + path + "(" + JSON.stringify(args) + ");";
|
|
1716
|
+
}
|
|
1717
|
+
/** The code opencode's `execute` runs for a search of its own (a partial catalogue). */
|
|
1718
|
+
function searchCode(query) {
|
|
1719
|
+
return "return await search(" + JSON.stringify(query) + ");";
|
|
1720
|
+
}
|
|
1721
|
+
const CALL_CODE = /^return await (tools(?:\.[A-Za-z_$][\w$]*|\["[^"\\]+"\])+)\((\{[\s\S]*\})\);$/;
|
|
1722
|
+
const SEARCH_CODE = /^return await search\(("(?:[^"\\]|\\[\s\S])*")\);$/;
|
|
1723
|
+
/**
|
|
1724
|
+
* The inverse of `callCode` and `searchCode`: the `mcp` request an `execute` call's code
|
|
1725
|
+
* came from, or undefined for code the proxy did not write.
|
|
1726
|
+
*/
|
|
1727
|
+
function executeCodeToMcp(code) {
|
|
1728
|
+
if (typeof code !== "string") return void 0;
|
|
1729
|
+
const call = CALL_CODE.exec(code);
|
|
1730
|
+
if (call) {
|
|
1731
|
+
try {
|
|
1732
|
+
const args = JSON.parse(call[2]);
|
|
1733
|
+
if (isPlainObject$1(args) && callCode(call[1], args) === code) return {
|
|
1734
|
+
kind: "call",
|
|
1735
|
+
path: call[1],
|
|
1736
|
+
args
|
|
1737
|
+
};
|
|
1738
|
+
} catch {
|
|
1739
|
+
return;
|
|
1740
|
+
}
|
|
1741
|
+
return;
|
|
1742
|
+
}
|
|
1743
|
+
const search = SEARCH_CODE.exec(code);
|
|
1744
|
+
if (search) try {
|
|
1745
|
+
const query = JSON.parse(search[1]);
|
|
1746
|
+
if (typeof query === "string") return {
|
|
1747
|
+
kind: "search",
|
|
1748
|
+
query
|
|
1749
|
+
};
|
|
1750
|
+
} catch {
|
|
1751
|
+
return;
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
/** Write a request back as the `mcp` fence the model wrote, for history replay. */
|
|
1755
|
+
function renderMcpFence(request) {
|
|
1756
|
+
if (request.kind === "search") return `\`\`\`mcp\nsearch: ${request.query}\n\`\`\``;
|
|
1757
|
+
const args = Object.keys(request.args).length === 0 ? "" : `\n${JSON.stringify(request.args)}`;
|
|
1758
|
+
return `\`\`\`mcp\ncall: ${request.path}` + args + "\n```";
|
|
1759
|
+
}
|
|
1177
1760
|
// node_modules/ws/lib/constants.js
|
|
1178
1761
|
var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
1179
1762
|
const BINARY_TYPES = [
|
|
@@ -10794,7 +11377,7 @@ function condenseSystemPrompt(text, tools, options = {}) {
|
|
|
10794
11377
|
result = outsideUserRules(result, (harness) => {
|
|
10795
11378
|
let text = harness;
|
|
10796
11379
|
if (!toolNames.has("execute")) {
|
|
10797
|
-
text = text
|
|
11380
|
+
text = stripCodeModeSection(text);
|
|
10798
11381
|
text = dropLines(text, /`execute`/);
|
|
10799
11382
|
}
|
|
10800
11383
|
if (!toolNames.has("skill")) text = dropLines(text, /^Skills provide |\bskill tool\b|invoke a skill directly/);
|
|
@@ -10911,7 +11494,7 @@ function buildTurnPrompt(messages, tools, sentMessageCount, options = {}) {
|
|
|
10911
11494
|
if (message.role === "assistant") {
|
|
10912
11495
|
const text = contentOf(message);
|
|
10913
11496
|
if (text) parts.push(text);
|
|
10914
|
-
for (const call of message.tool_calls ?? []) parts.push(renderToolCall(call.function.name, call.function.arguments, tools));
|
|
11497
|
+
for (const call of message.tool_calls ?? []) parts.push(options.renderCall?.(call.function.name, call.function.arguments) ?? renderToolCall(call.function.name, call.function.arguments, options.historyTools ?? tools));
|
|
10915
11498
|
continue;
|
|
10916
11499
|
}
|
|
10917
11500
|
const text = contentOf(message) || (hasImagePart(message) ? "(See the attached image.)" : "");
|
|
@@ -10963,7 +11546,10 @@ function escapeAttribute(value) {
|
|
|
10963
11546
|
return value.replace(/"/g, """).replace(/\n/g, " ");
|
|
10964
11547
|
}
|
|
10965
11548
|
function buildCompletion(result, options) {
|
|
10966
|
-
const { toolCalls, text } =
|
|
11549
|
+
const { toolCalls, text } = options.toolCalls ? {
|
|
11550
|
+
toolCalls: options.toolCalls,
|
|
11551
|
+
text: ""
|
|
11552
|
+
} : parseToolCalls(result.text, options.tools, { allowMultiple: options.allowMultiple ?? false });
|
|
10967
11553
|
const hasCalls = toolCalls.length > 0;
|
|
10968
11554
|
return {
|
|
10969
11555
|
id: `chatcmpl-${randomUUID()}`,
|
|
@@ -11139,6 +11725,14 @@ const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
|
|
|
11139
11725
|
function generateApiKey() {
|
|
11140
11726
|
return randomBytes(32).toString("base64url");
|
|
11141
11727
|
}
|
|
11728
|
+
/**
|
|
11729
|
+
* `mcp` blocks the proxy answers itself per request — searches, unknown paths and
|
|
11730
|
+
* unreadable blocks — before the reply goes back to the client as it is.
|
|
11731
|
+
*/
|
|
11732
|
+
const MAX_MCP_SEARCHES = 3;
|
|
11733
|
+
/** opencode 2's tool that runs Code Mode JavaScript: the proxy emits it, M365 never sees it. */
|
|
11734
|
+
const EXECUTE_TOOL_NAME = "execute";
|
|
11735
|
+
const isExecute = (tool) => tool.function.name.toLowerCase() === EXECUTE_TOOL_NAME;
|
|
11142
11736
|
async function startServer(deps) {
|
|
11143
11737
|
const pool = new ConversationPool();
|
|
11144
11738
|
const host = deps.host ?? "127.0.0.1";
|
|
@@ -11268,15 +11862,18 @@ async function handleChatCompletion(request, response, context) {
|
|
|
11268
11862
|
}
|
|
11269
11863
|
const model = resolveModel(body.model);
|
|
11270
11864
|
const requested = body.tools ?? [];
|
|
11271
|
-
const
|
|
11272
|
-
if (
|
|
11273
|
-
log.info(`trimmed toolset ${requested.length} -> ${
|
|
11865
|
+
const kept = context.deps.lean !== false ? selectLeanTools(requested) : requested;
|
|
11866
|
+
if (kept.length !== requested.length) {
|
|
11867
|
+
log.info(`trimmed toolset ${requested.length} -> ${kept.length}`, kept.map((t) => t.function.name).join(","));
|
|
11274
11868
|
const concern = describeToolSelection(requested);
|
|
11275
11869
|
if (concern && !warnedAboutToolSelection) {
|
|
11276
11870
|
warnedAboutToolSelection = true;
|
|
11277
11871
|
log.warn(concern);
|
|
11278
11872
|
}
|
|
11279
11873
|
}
|
|
11874
|
+
const catalog = context.deps.mcpProxy === true ? mcpCatalogFor(body, requested) : void 0;
|
|
11875
|
+
const tools = catalog ? [...kept.filter((tool) => !isExecute(tool)), mcpTool(catalog.tools, catalog.partial)] : kept;
|
|
11876
|
+
if (catalog) log.info(`offering mcp over ${catalog.tools.length}${catalog.partial ? "+" : ""} Code Mode tools`, catalog.tools.map((tool) => tool.path).join(","));
|
|
11280
11877
|
if (isLocalModel(model.id) || request.headers["x-m365-request-kind"] === "title") {
|
|
11281
11878
|
respondWithTitle(response, body, model.id);
|
|
11282
11879
|
return;
|
|
@@ -11290,7 +11887,7 @@ async function handleChatCompletion(request, response, context) {
|
|
|
11290
11887
|
conversation.turn = previous.then(() => current);
|
|
11291
11888
|
await previous;
|
|
11292
11889
|
try {
|
|
11293
|
-
await runTurn(request, response, context, body, conversation, model, tools);
|
|
11890
|
+
await runTurn(request, response, context, body, conversation, model, tools, catalog, requested);
|
|
11294
11891
|
} finally {
|
|
11295
11892
|
release();
|
|
11296
11893
|
}
|
|
@@ -11305,22 +11902,27 @@ function defaultTurnLog() {
|
|
|
11305
11902
|
}
|
|
11306
11903
|
return envTurnLog;
|
|
11307
11904
|
}
|
|
11308
|
-
async function runTurn(request, response, context, body, conversation, model, tools) {
|
|
11905
|
+
async function runTurn(request, response, context, body, conversation, model, tools, catalog, requested = tools) {
|
|
11309
11906
|
if (body.messages.length < conversation.sentMessageCount) conversation.sentMessageCount = 0;
|
|
11310
11907
|
conversation.session ??= new CopilotSession({
|
|
11311
11908
|
getToken: context.deps.getToken,
|
|
11312
11909
|
...context.deps.endpoint ? { endpoint: context.deps.endpoint } : {}
|
|
11313
11910
|
});
|
|
11314
11911
|
const effectiveTools = model.grounded ? [] : tools;
|
|
11912
|
+
const mcp = model.grounded ? void 0 : catalog;
|
|
11913
|
+
const clientTools = mcp ? effectiveTools.filter((tool) => tool.function.name !== "mcp") : effectiveTools;
|
|
11914
|
+
const executeName = requested.find(isExecute)?.function.name ?? EXECUTE_TOOL_NAME;
|
|
11315
11915
|
const images = collectImages(body.messages, conversation.sentMessageCount);
|
|
11316
11916
|
const note = effectiveTools.length > 0 && conversation.sentMessageCount > 0 ? conversation.note : void 0;
|
|
11317
11917
|
conversation.note = void 0;
|
|
11318
11918
|
const route = toolRouteFor(model.tone);
|
|
11319
|
-
const prompt = buildTurnPrompt(body.messages, effectiveTools, conversation.sentMessageCount, {
|
|
11919
|
+
const prompt = buildTurnPrompt(mcp ? relabelProxyCalls(body.messages) : body.messages, effectiveTools, conversation.sentMessageCount, {
|
|
11320
11920
|
framing: route.framing,
|
|
11321
11921
|
...route.sandbox ? { sandbox: route.sandbox } : {},
|
|
11322
11922
|
...context.deps.leanSystemPrompt !== void 0 ? { leanSystemPrompt: context.deps.leanSystemPrompt } : {},
|
|
11323
|
-
...note ? { note } : {}
|
|
11923
|
+
...note ? { note } : {},
|
|
11924
|
+
...effectiveTools.length > 0 ? { historyTools: [...effectiveTools, ...requested] } : {},
|
|
11925
|
+
...mcp ? { renderCall: renderProxyCall } : {}
|
|
11324
11926
|
});
|
|
11325
11927
|
const agent = effectiveTools.length > 0 && route.agent ? await context.agentId() : null;
|
|
11326
11928
|
const abort = new AbortController();
|
|
@@ -11357,6 +11959,7 @@ async function runTurn(request, response, context, body, conversation, model, to
|
|
|
11357
11959
|
...result.resultValue ? { resultValue: result.resultValue } : {},
|
|
11358
11960
|
...extra
|
|
11359
11961
|
});
|
|
11962
|
+
let logged = {};
|
|
11360
11963
|
try {
|
|
11361
11964
|
let result = await conversation.session.run(prompt, {
|
|
11362
11965
|
...turnOptions,
|
|
@@ -11367,20 +11970,74 @@ async function runTurn(request, response, context, body, conversation, model, to
|
|
|
11367
11970
|
recordTurn(result);
|
|
11368
11971
|
const midTask = body.messages.some((message) => message.role === "tool");
|
|
11369
11972
|
result = await conversation.session.run(nudgeFor(midTask, route.framing), turnOptions);
|
|
11370
|
-
|
|
11371
|
-
}
|
|
11973
|
+
logged = { nudged: true };
|
|
11974
|
+
}
|
|
11975
|
+
let proxyCall;
|
|
11976
|
+
for (let answered = 0; mcp;) {
|
|
11977
|
+
if (parseToolCalls(result.text, effectiveTools).toolCalls[0]?.name !== "mcp") break;
|
|
11978
|
+
const ask = parseMcpBlock(firstFenceBody(result.text, "mcp") ?? "");
|
|
11979
|
+
let answer;
|
|
11980
|
+
let next = {};
|
|
11981
|
+
if (ask.kind === "call") {
|
|
11982
|
+
const path = resolveCallPath(ask.path, mcp.tools, mcp.partial);
|
|
11983
|
+
if (path) {
|
|
11984
|
+
proxyCall = {
|
|
11985
|
+
name: executeName,
|
|
11986
|
+
arguments: { code: callCode(path, ask.args) }
|
|
11987
|
+
};
|
|
11988
|
+
logged = {
|
|
11989
|
+
...logged,
|
|
11990
|
+
mcpCall: path
|
|
11991
|
+
};
|
|
11992
|
+
break;
|
|
11993
|
+
}
|
|
11994
|
+
answer = renderUnknownTool(ask.path);
|
|
11995
|
+
} else if (ask.kind === "search") {
|
|
11996
|
+
const matches = searchCatalog(ask.query, mcp.tools);
|
|
11997
|
+
if (matches.length === 0 && mcp.partial) {
|
|
11998
|
+
proxyCall = {
|
|
11999
|
+
name: executeName,
|
|
12000
|
+
arguments: { code: searchCode(ask.query) }
|
|
12001
|
+
};
|
|
12002
|
+
logged = {
|
|
12003
|
+
...logged,
|
|
12004
|
+
mcpCall: "search"
|
|
12005
|
+
};
|
|
12006
|
+
break;
|
|
12007
|
+
}
|
|
12008
|
+
answer = renderSearchResult(ask.query, matches, mcp.tools.length);
|
|
12009
|
+
next = { mcpSearch: ask.query };
|
|
12010
|
+
} else answer = renderInvalidMcpBlock(ask.reason);
|
|
12011
|
+
if (answered >= 3) break;
|
|
12012
|
+
answered += 1;
|
|
12013
|
+
recordTurn(result, logged);
|
|
12014
|
+
result = await conversation.session.run(answer, turnOptions);
|
|
12015
|
+
logged = next;
|
|
12016
|
+
}
|
|
12017
|
+
recordTurn(result, logged);
|
|
12018
|
+
if (mcp && !proxyCall) result = {
|
|
12019
|
+
...result,
|
|
12020
|
+
text: stripMcpCalls(result.text)
|
|
12021
|
+
};
|
|
11372
12022
|
conversation.sentMessageCount = body.messages.length + 1;
|
|
11373
12023
|
const allowMultiple = context.deps.allowMultiTool ?? false;
|
|
11374
|
-
|
|
12024
|
+
const parsed = proxyCall ? {
|
|
12025
|
+
toolCalls: [proxyCall],
|
|
12026
|
+
text: "",
|
|
12027
|
+
skippedCalls: 0,
|
|
12028
|
+
inventedResult: false
|
|
12029
|
+
} : parseToolCalls(result.text, clientTools, { allowMultiple });
|
|
12030
|
+
conversation.note = noteAbout(parsed);
|
|
11375
12031
|
if (!streaming) {
|
|
11376
12032
|
sendJson(response, 200, buildCompletion(result, {
|
|
11377
12033
|
model: model.id,
|
|
11378
|
-
tools:
|
|
11379
|
-
allowMultiple
|
|
12034
|
+
tools: clientTools,
|
|
12035
|
+
allowMultiple,
|
|
12036
|
+
...proxyCall ? { toolCalls: [proxyCall] } : {}
|
|
11380
12037
|
}));
|
|
11381
12038
|
return;
|
|
11382
12039
|
}
|
|
11383
|
-
finishStream(response, streamId, model.id,
|
|
12040
|
+
finishStream(response, streamId, model.id, parsed, canStreamText);
|
|
11384
12041
|
} catch (error) {
|
|
11385
12042
|
logTurn({ error: error instanceof Error ? `${error.name}: ${error.message}` : String(error) });
|
|
11386
12043
|
if (error instanceof DisengagedError) {
|
|
@@ -11407,9 +12064,62 @@ function noteAbout(parsed) {
|
|
|
11407
12064
|
if (parsed.inventedResult) lines.push("The result you predicted after your call was set aside; the real one is below.");
|
|
11408
12065
|
return lines.length > 0 ? lines.join(" ") : void 0;
|
|
11409
12066
|
}
|
|
12067
|
+
/**
|
|
12068
|
+
* Drop every `mcp` block from a reply. Past the search cap the client gets the
|
|
12069
|
+
* reply's prose (and any real call in it), never a call to the proxy's own tool.
|
|
12070
|
+
*/
|
|
12071
|
+
function stripMcpCalls(text) {
|
|
12072
|
+
const stripped = text.replace(MCP_FENCE, "");
|
|
12073
|
+
return stripped === text ? text : stripped.replace(/\n{3,}/g, "\n\n").trim();
|
|
12074
|
+
}
|
|
12075
|
+
const MCP_FENCE = /^[ \t]*(`{3,}|~{3,})[ \t]*mcp(?![\w-])[^\n]*\n[\s\S]*?^[ \t]*\1[ \t]*$\n?/gim;
|
|
12076
|
+
/**
|
|
12077
|
+
* opencode 2's Code Mode catalogue for a request, when the proxy should stand in for
|
|
12078
|
+
* it: the system prompt carries one, and the request offers `execute` to run calls.
|
|
12079
|
+
*/
|
|
12080
|
+
function mcpCatalogFor(body, requested) {
|
|
12081
|
+
if (!requested.some(isExecute)) return void 0;
|
|
12082
|
+
const catalog = parseCodeModeCatalog(body.messages.filter((message) => message.role === "system" || message.role === "developer").map(contentOf).join("\n\n"));
|
|
12083
|
+
return catalog && (catalog.tools.length > 0 || catalog.partial) ? catalog : void 0;
|
|
12084
|
+
}
|
|
12085
|
+
/** The code of an `execute` call's raw arguments, if it has one. */
|
|
12086
|
+
function executeCode(rawArguments) {
|
|
12087
|
+
try {
|
|
12088
|
+
const code = JSON.parse(rawArguments || "{}")?.code;
|
|
12089
|
+
return typeof code === "string" ? code : void 0;
|
|
12090
|
+
} catch {
|
|
12091
|
+
return;
|
|
12092
|
+
}
|
|
12093
|
+
}
|
|
12094
|
+
/**
|
|
12095
|
+
* Name the proxy's own `execute` calls `mcp` in the history, so they replay as the
|
|
12096
|
+
* `mcp` blocks the model wrote and their results are labelled as the `mcp` tool's.
|
|
12097
|
+
* Any other `execute` call is left as it is.
|
|
12098
|
+
*/
|
|
12099
|
+
function relabelProxyCalls(messages) {
|
|
12100
|
+
return messages.map((message) => {
|
|
12101
|
+
if (!message.tool_calls?.some((call) => call.function.name.toLowerCase() === EXECUTE_TOOL_NAME)) return message;
|
|
12102
|
+
return {
|
|
12103
|
+
...message,
|
|
12104
|
+
tool_calls: message.tool_calls.map((call) => call.function.name.toLowerCase() === EXECUTE_TOOL_NAME && executeCodeToMcp(executeCode(call.function.arguments)) ? {
|
|
12105
|
+
...call,
|
|
12106
|
+
function: {
|
|
12107
|
+
...call.function,
|
|
12108
|
+
name: "mcp"
|
|
12109
|
+
}
|
|
12110
|
+
} : call)
|
|
12111
|
+
};
|
|
12112
|
+
});
|
|
12113
|
+
}
|
|
12114
|
+
/** A relabelled call, written back as its `mcp` block. */
|
|
12115
|
+
function renderProxyCall(name, rawArguments) {
|
|
12116
|
+
if (name !== "mcp") return void 0;
|
|
12117
|
+
const request = executeCodeToMcp(executeCode(rawArguments));
|
|
12118
|
+
return request ? renderMcpFence(request) : void 0;
|
|
12119
|
+
}
|
|
11410
12120
|
/** Emit the closing frames of a streamed turn. */
|
|
11411
|
-
function finishStream(response, streamId, model,
|
|
11412
|
-
const { toolCalls, text } =
|
|
12121
|
+
function finishStream(response, streamId, model, parsed, alreadyStreamedText) {
|
|
12122
|
+
const { toolCalls, text } = parsed;
|
|
11413
12123
|
if (toolCalls.length > 0) {
|
|
11414
12124
|
response.write(streamChunk(streamId, model, { toolCalls: toolCalls.map(toOpenAiToolCall) }));
|
|
11415
12125
|
response.write(streamChunk(streamId, model, { finishReason: "tool_calls" }));
|
|
@@ -11543,4 +12253,4 @@ async function readBody(request, limit) {
|
|
|
11543
12253
|
}
|
|
11544
12254
|
return Buffer.concat(chunks).toString("utf8");
|
|
11545
12255
|
}
|
|
11546
|
-
export {
|
|
12256
|
+
export { buildModelInfos as A, __toESM as B, writePrivateFile as C, SECRETS_FILE as D, CONFIG_DIR as E, LOCAL_TITLE_MODEL as F, MODELS as I, isLocalModel as L, mergeOpencodeConfig as M, resolveOptions as N, PLUGIN_ID as O, DEFAULT_MODEL as P, __commonJSMin as R, ensurePrivateDir as S, CACHE_FILE as T, SYDNEY_SCOPES as _, generateApiKey as a, createTokenClient as b, stripMcpCalls as c, CopilotSession as d, AUTHORITY as f, REDIRECT_URI as g, POWERPLATFORM_SCOPE as h, SESSION_ID_HEADER as i, buildProviderInfo as j, PROVIDER_ID as k, object as l, CLIENT_ID as m, DEFAULT_MAX_BODY_BYTES as n, noteAbout as o, BAP_SCOPE as p, MAX_MCP_SEARCHES as r, startServer as s, AUX_REQUEST_KIND_HEADER as t, string as u, authCodeFromUrl as v, AGENT_FILE as w, createLogger as x, createCachePlugin as y, __require as z };
|
package/dist/server.d.mts
CHANGED
|
@@ -79,6 +79,12 @@ export interface ServerDeps {
|
|
|
79
79
|
* does not affect the outgoing request — see `condenseSystemPrompt`.
|
|
80
80
|
*/
|
|
81
81
|
leanSystemPrompt?: string;
|
|
82
|
+
/**
|
|
83
|
+
* Reach opencode 2's MCP tools only through the proxy's `mcp` tool: the Code Mode
|
|
84
|
+
* catalogue and `execute` never reach M365, a search is answered here, and a call
|
|
85
|
+
* becomes an `execute` call for opencode to run. Off unless set.
|
|
86
|
+
*/
|
|
87
|
+
mcpProxy?: boolean;
|
|
82
88
|
/**
|
|
83
89
|
* Receives one entry per M365 turn: the raw reply, what was parsed from it, and
|
|
84
90
|
* M365's diagnostics. Defaults to a JSONL file at `M365_TURN_LOG` when that is set,
|
|
@@ -116,6 +122,11 @@ export interface ProxyHandle {
|
|
|
116
122
|
export declare const DEFAULT_MAX_BODY_BYTES: number;
|
|
117
123
|
/** A fresh per-launch secret: 32 random bytes, base64url. */
|
|
118
124
|
export declare function generateApiKey(): string;
|
|
125
|
+
/**
|
|
126
|
+
* `mcp` blocks the proxy answers itself per request — searches, unknown paths and
|
|
127
|
+
* unreadable blocks — before the reply goes back to the client as it is.
|
|
128
|
+
*/
|
|
129
|
+
export declare const MAX_MCP_SEARCHES = 3;
|
|
119
130
|
export declare function startServer(deps: ServerDeps): Promise<ProxyHandle>;
|
|
120
131
|
export interface TurnLogEntry {
|
|
121
132
|
time: string;
|
|
@@ -134,6 +145,13 @@ export interface TurnLogEntry {
|
|
|
134
145
|
resultValue?: string;
|
|
135
146
|
/** This turn was the follow-up sent after a give-up. */
|
|
136
147
|
nudged?: boolean;
|
|
148
|
+
/** This turn was the reply to an `mcp` search the proxy answered; the query. */
|
|
149
|
+
mcpSearch?: string;
|
|
150
|
+
/**
|
|
151
|
+
* This turn's reply was an `mcp` call the proxy sent to opencode as an `execute`
|
|
152
|
+
* call: the tool's path, or `search` for opencode's own search.
|
|
153
|
+
*/
|
|
154
|
+
mcpCall?: string;
|
|
137
155
|
error?: string;
|
|
138
156
|
}
|
|
139
157
|
/**
|
|
@@ -149,4 +167,9 @@ export declare function noteAbout(parsed: {
|
|
|
149
167
|
skippedCalls: number;
|
|
150
168
|
inventedResult: boolean;
|
|
151
169
|
}): string | undefined;
|
|
170
|
+
/**
|
|
171
|
+
* Drop every `mcp` block from a reply. Past the search cap the client gets the
|
|
172
|
+
* reply's prose (and any real call in it), never a call to the proxy's own tool.
|
|
173
|
+
*/
|
|
174
|
+
export declare function stripMcpCalls(text: string): string;
|
|
152
175
|
export {};
|
package/dist/server.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as AUX_REQUEST_KIND_HEADER, n as DEFAULT_MAX_BODY_BYTES,
|
|
1
|
+
export { t as AUX_REQUEST_KIND_HEADER, n as DEFAULT_MAX_BODY_BYTES, P as DEFAULT_MODEL, r as MAX_MCP_SEARCHES, i as SESSION_ID_HEADER, a as generateApiKey, o as noteAbout, s as startServer, c as stripMcpCalls } from "./server-DXznAk1h.mjs";
|