opencode-m365-copilot 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-t3MgztgU.mjs → agent-BF67A0cd.mjs} +1 -1
- package/dist/cli.mjs +3 -3
- package/dist/dist-CX5bv-4h.mjs +12668 -0
- package/dist/{login-Dj9Ss7K_.mjs → login-Bjybi2AZ.mjs} +8 -9
- package/dist/otpauth.node-klD_z4Tx.mjs +682 -0
- package/dist/plugin.mjs +2 -2
- package/dist/server-DDD-Hlhx.mjs +9488 -0
- package/dist/server.mjs +1 -1
- package/package.json +12 -12
- package/dist/server-CeGQPDdE.mjs +0 -1772
package/dist/server-CeGQPDdE.mjs
DELETED
|
@@ -1,1772 +0,0 @@
|
|
|
1
|
-
import { appendFileSync, chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
-
import { dirname, join } from "node:path";
|
|
3
|
-
import { homedir } from "node:os";
|
|
4
|
-
import { randomUUID } from "node:crypto";
|
|
5
|
-
import { createServer } from "node:http";
|
|
6
|
-
import { WebSocket } from "ws";
|
|
7
|
-
import { z } from "zod";
|
|
8
|
-
//#region src/paths.ts
|
|
9
|
-
/**
|
|
10
|
-
* Where we keep auth state.
|
|
11
|
-
*
|
|
12
|
-
* Deliberately NOT `~/.config/opencode-m365/` — that belongs to the
|
|
13
|
-
* m365-copilot-proxy project, and sharing it would mean two independent tools
|
|
14
|
-
* writing the same MSAL cache and agent-id file.
|
|
15
|
-
*/
|
|
16
|
-
const CONFIG_DIR = process.env.M365_CONFIG_DIR || join(homedir(), ".config", "opencode-copilot");
|
|
17
|
-
const CACHE_FILE = process.env.M365_CACHE_FILE || join(CONFIG_DIR, "msal-cache.json");
|
|
18
|
-
const SECRETS_FILE = process.env.M365_SECRETS_FILE || join(CONFIG_DIR, "secrets.json");
|
|
19
|
-
const AGENT_FILE = process.env.M365_AGENT_FILE || join(CONFIG_DIR, "agent-id.json");
|
|
20
|
-
const LOG_FILE = join(CONFIG_DIR, "debug.log");
|
|
21
|
-
//#endregion
|
|
22
|
-
//#region src/log.ts
|
|
23
|
-
const DEBUG = process.env.M365_DEBUG === "1" || process.env.M365_TRACE === "1";
|
|
24
|
-
const TRACE = process.env.M365_TRACE === "1";
|
|
25
|
-
const TO_STDOUT = process.env.M365_LOG_STDOUT === "1";
|
|
26
|
-
let ready = false;
|
|
27
|
-
/** Truncate a payload for the log unless full tracing is on. */
|
|
28
|
-
function trunc(value, max = 400) {
|
|
29
|
-
const text = typeof value === "string" ? value : JSON.stringify(value);
|
|
30
|
-
if (TRACE || text == null) return String(text);
|
|
31
|
-
return text.length > max ? `${text.slice(0, max)}… (${text.length} chars)` : text;
|
|
32
|
-
}
|
|
33
|
-
/**
|
|
34
|
-
* A file logger, off unless `M365_DEBUG=1`.
|
|
35
|
-
*
|
|
36
|
-
* The plugin runs inside opencode's server process, so writing to stdout would
|
|
37
|
-
* corrupt the TUI. Everything goes to a file unless explicitly asked otherwise.
|
|
38
|
-
*/
|
|
39
|
-
function createLogger(scope) {
|
|
40
|
-
const write = (level, parts) => {
|
|
41
|
-
if (!DEBUG) return;
|
|
42
|
-
const line = `${(/* @__PURE__ */ new Date()).toISOString()} [${level}] [${scope}] ${parts.map((p) => trunc(p)).join(" ")}`;
|
|
43
|
-
if (TO_STDOUT) process.stdout.write(`${line}\n`);
|
|
44
|
-
try {
|
|
45
|
-
if (!ready) {
|
|
46
|
-
mkdirSync(dirname(LOG_FILE) || CONFIG_DIR, { recursive: true });
|
|
47
|
-
ready = true;
|
|
48
|
-
}
|
|
49
|
-
appendFileSync(LOG_FILE, `${line}\n`);
|
|
50
|
-
} catch {}
|
|
51
|
-
};
|
|
52
|
-
return {
|
|
53
|
-
info: (...parts) => write("info", parts),
|
|
54
|
-
warn: (...parts) => write("warn", parts),
|
|
55
|
-
error: (...parts) => write("error", parts)
|
|
56
|
-
};
|
|
57
|
-
}
|
|
58
|
-
//#endregion
|
|
59
|
-
//#region src/auth.ts
|
|
60
|
-
/**
|
|
61
|
-
* Authentication against the Office web Copilot client.
|
|
62
|
-
*
|
|
63
|
-
* This module is deliberately **silent-only**. It runs inside opencode's server
|
|
64
|
-
* process, where launching a browser would be hostile — so when the cache cannot
|
|
65
|
-
* produce a token it raises `AuthRequiredError` telling the user to run the CLI.
|
|
66
|
-
* The interactive path lives in `login.ts`, which the CLI loads on demand.
|
|
67
|
-
*
|
|
68
|
-
* The client id below is Microsoft's own Office web Copilot application. We did not
|
|
69
|
-
* register it, and no one can: the Sydney scopes are granted to no other client, so a
|
|
70
|
-
* loopback redirect URI is rejected (`AADSTS50011`) and the device-code grant demands
|
|
71
|
-
* a client secret only Microsoft holds (`AADSTS7000218`). The `nativeclient` redirect
|
|
72
|
-
* is the only door, which is why `login.ts` has to drive a real browser.
|
|
73
|
-
*/
|
|
74
|
-
const log$2 = createLogger("auth");
|
|
75
|
-
/** Microsoft's Office web Copilot client. Not ours, and not replaceable. */
|
|
76
|
-
const CLIENT_ID = "c0ab8ce9-e9a0-42e7-b064-33d422df41f1";
|
|
77
|
-
const AUTHORITY = "https://login.microsoftonline.com/common";
|
|
78
|
-
const REDIRECT_URI = "https://login.microsoftonline.com/common/oauth2/nativeclient";
|
|
79
|
-
/** Scopes for the chat backend. The resulting token's audience is Sydney. */
|
|
80
|
-
const SYDNEY_SCOPES = ["https://substrate.office.com/sydney/M365Chat.Read", "https://substrate.office.com/sydney/sydney.readwrite"];
|
|
81
|
-
/** Copilot Studio agent management — acquired separately from the chat token. */
|
|
82
|
-
const POWERPLATFORM_SCOPE = "https://api.powerplatform.com/.default";
|
|
83
|
-
/** Power Platform environment discovery. */
|
|
84
|
-
const BAP_SCOPE = "https://api.bap.microsoft.com/.default";
|
|
85
|
-
/** Re-acquire this far ahead of expiry rather than racing the clock mid-turn. */
|
|
86
|
-
const EXPIRY_MARGIN_MS = 12e4;
|
|
87
|
-
/** No usable cached credential. The user has to sign in; we cannot do it for them. */
|
|
88
|
-
var AuthRequiredError = class extends Error {
|
|
89
|
-
authRequired = true;
|
|
90
|
-
constructor(reason) {
|
|
91
|
-
super(`${reason}. Run \`opencode-m365 login\` to sign in.`);
|
|
92
|
-
this.name = "AuthRequiredError";
|
|
93
|
-
}
|
|
94
|
-
};
|
|
95
|
-
/**
|
|
96
|
-
* Persist MSAL's token cache to disk.
|
|
97
|
-
*
|
|
98
|
-
* The cache is disposable: delete it and the next login rebuilds an equivalent one.
|
|
99
|
-
* It still holds refresh tokens, so it is written owner-only.
|
|
100
|
-
*/
|
|
101
|
-
function createCachePlugin(file = CACHE_FILE) {
|
|
102
|
-
return {
|
|
103
|
-
async beforeCacheAccess(context) {
|
|
104
|
-
try {
|
|
105
|
-
context.tokenCache.deserialize(readFileSync(file, "utf8"));
|
|
106
|
-
} catch {}
|
|
107
|
-
},
|
|
108
|
-
async afterCacheAccess(context) {
|
|
109
|
-
if (!context.cacheHasChanged) return;
|
|
110
|
-
try {
|
|
111
|
-
mkdirSync(dirname(file), { recursive: true });
|
|
112
|
-
writeFileSync(file, context.tokenCache.serialize(), { mode: 384 });
|
|
113
|
-
chmodSync(file, 384);
|
|
114
|
-
} catch (error) {
|
|
115
|
-
log$2.warn("could not persist the token cache", String(error));
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
};
|
|
119
|
-
}
|
|
120
|
-
function createTokenClient(options = {}) {
|
|
121
|
-
let app = options.app;
|
|
122
|
-
const cache = /* @__PURE__ */ new Map();
|
|
123
|
-
async function client() {
|
|
124
|
-
if (app) return app;
|
|
125
|
-
const { PublicClientApplication } = await import("@azure/msal-node");
|
|
126
|
-
app = new PublicClientApplication({
|
|
127
|
-
auth: {
|
|
128
|
-
clientId: CLIENT_ID,
|
|
129
|
-
authority: AUTHORITY
|
|
130
|
-
},
|
|
131
|
-
cache: { cachePlugin: createCachePlugin(options.cacheFile) }
|
|
132
|
-
});
|
|
133
|
-
return app;
|
|
134
|
-
}
|
|
135
|
-
async function acquire(scopes) {
|
|
136
|
-
const key = scopes.join(" ");
|
|
137
|
-
const cached = cache.get(key);
|
|
138
|
-
if (cached && cached.expiresAt - EXPIRY_MARGIN_MS > Date.now()) return cached.token;
|
|
139
|
-
const msal = await client();
|
|
140
|
-
const account = (await msal.getTokenCache().getAllAccounts())[0];
|
|
141
|
-
if (!account) throw new AuthRequiredError("No signed-in Microsoft 365 account");
|
|
142
|
-
let result;
|
|
143
|
-
try {
|
|
144
|
-
result = await msal.acquireTokenSilent({
|
|
145
|
-
account,
|
|
146
|
-
scopes
|
|
147
|
-
});
|
|
148
|
-
} catch (error) {
|
|
149
|
-
log$2.warn("silent token acquisition failed", String(error));
|
|
150
|
-
throw new AuthRequiredError("Could not refresh the Microsoft 365 token silently");
|
|
151
|
-
}
|
|
152
|
-
if (!result?.accessToken) throw new AuthRequiredError("Microsoft 365 returned no access token");
|
|
153
|
-
cache.set(key, {
|
|
154
|
-
token: result.accessToken,
|
|
155
|
-
expiresAt: result.expiresOn ? new Date(result.expiresOn).getTime() : Date.now() + 3e5
|
|
156
|
-
});
|
|
157
|
-
return result.accessToken;
|
|
158
|
-
}
|
|
159
|
-
return {
|
|
160
|
-
getToken: () => acquire(SYDNEY_SCOPES),
|
|
161
|
-
getTokenForScope: (scopes) => acquire(scopes),
|
|
162
|
-
invalidate: () => cache.clear()
|
|
163
|
-
};
|
|
164
|
-
}
|
|
165
|
-
/**
|
|
166
|
-
* Pull the authorization code out of a navigation URL.
|
|
167
|
-
*
|
|
168
|
-
* The `nativeclient` redirect is designed to be intercepted by an embedded native
|
|
169
|
-
* host before the page loads. A real browser instead follows it one hop further and
|
|
170
|
-
* lands on `/common/wrongplace`, so waiting for the redirect to *land* misses the
|
|
171
|
-
* code entirely — it only ever exists on the in-flight navigation request.
|
|
172
|
-
*/
|
|
173
|
-
function authCodeFromUrl(rawUrl) {
|
|
174
|
-
let url;
|
|
175
|
-
try {
|
|
176
|
-
url = new URL(rawUrl);
|
|
177
|
-
} catch {
|
|
178
|
-
return;
|
|
179
|
-
}
|
|
180
|
-
if (!url.pathname.includes("/oauth2/nativeclient")) return void 0;
|
|
181
|
-
const error = url.searchParams.get("error");
|
|
182
|
-
if (error) {
|
|
183
|
-
const description = url.searchParams.get("error_description");
|
|
184
|
-
throw new Error(`Sign-in failed: ${error}${description ? ` — ${description}` : ""}`);
|
|
185
|
-
}
|
|
186
|
-
return url.searchParams.get("code") ?? void 0;
|
|
187
|
-
}
|
|
188
|
-
//#endregion
|
|
189
|
-
//#region src/models.ts
|
|
190
|
-
/**
|
|
191
|
-
* Advertised context/output limits.
|
|
192
|
-
*
|
|
193
|
-
* Input is retrieval-backed and enormous — benign payloads of ~500k tokens never
|
|
194
|
-
* tripped anything. Output soft-caps far lower, but M365 signals that by *concluding
|
|
195
|
-
* early* rather than truncating, so a small advertised output limit only causes
|
|
196
|
-
* harnesses to clip our prompts. Advertise roomy numbers and let the server decide.
|
|
197
|
-
*/
|
|
198
|
-
const CONTEXT_TOKENS = 1e6;
|
|
199
|
-
const OUTPUT_TOKENS = 128e3;
|
|
200
|
-
/**
|
|
201
|
-
* A synthetic model served entirely by our own proxy — it never opens a WebSocket
|
|
202
|
-
* to M365.
|
|
203
|
-
*
|
|
204
|
-
* This exists because opencode's `small_model` (session title generation) defaults
|
|
205
|
-
* to the main model. That would open a *second* M365 conversation for every session,
|
|
206
|
-
* which is precisely the thread-rate throttle signature: the limit tracks
|
|
207
|
-
* conversations started, not messages. Pointing `small_model` here costs nothing.
|
|
208
|
-
*/
|
|
209
|
-
const LOCAL_TITLE_MODEL = "local-title";
|
|
210
|
-
/**
|
|
211
|
-
* Default when a request carries no model.
|
|
212
|
-
*
|
|
213
|
-
* Their README measures `gpt-5.5-think-deeper` at 100% tool compliance with the
|
|
214
|
-
* declarative agent + fenced/shell-routing path, and a request with no model already
|
|
215
|
-
* defaults to it there. Note this conflicts with `m365-copilot-api.md` quirk #13,
|
|
216
|
-
* which says reasoning tones meta-analyse the injected prompt and disengage — that
|
|
217
|
-
* note predates the GPT-5.5 measurements. See README for the full story.
|
|
218
|
-
*/
|
|
219
|
-
const DEFAULT_MODEL = "gpt-5.5-think-deeper";
|
|
220
|
-
const MODELS = [
|
|
221
|
-
m("gpt-5.6-think-deeper", "GPT-5.6 (Think Deeper)", "Gpt_5_6_Reasoning", true),
|
|
222
|
-
m("gpt-5.5-think-deeper", "GPT-5.5 (Think Deeper)", "Gpt_5_5_Reasoning", true),
|
|
223
|
-
m("gpt-5.5", "GPT-5.5", "Gpt_5_5_Chat", false),
|
|
224
|
-
m("gpt-5.5-quick", "GPT-5.5 (Quick)", "Gpt_5_5_Chat", false),
|
|
225
|
-
m("m365-copilot", "M365 Copilot (Auto)", "magic", false),
|
|
226
|
-
m("auto", "M365 Copilot (Auto)", "magic", false),
|
|
227
|
-
m("quick", "GPT (Quick)", "Gpt_Quick", false),
|
|
228
|
-
m("think-deeper", "GPT (Think Deeper)", "Gpt_Reasoning", true),
|
|
229
|
-
m("claude-sonnet", "Claude Sonnet (via M365)", "Claude_Sonnet", false),
|
|
230
|
-
m("claude", "Claude Sonnet (via M365)", "Claude_Sonnet", false),
|
|
231
|
-
m("claude-sonnet-think-deeper", "Claude Sonnet (Think Deeper)", "Claude_Sonnet_Reasoning", true),
|
|
232
|
-
m("gpt-5.4", "GPT-5.4 (Think Deeper)", "Gpt_5_4_Reasoning", true),
|
|
233
|
-
m("gpt-5.4-think-deeper", "GPT-5.4 (Think Deeper)", "Gpt_5_4_Reasoning", true),
|
|
234
|
-
m("gpt-5.4-quick", "GPT-5.4 (Quick)", "Gpt_5_4_Quick", false),
|
|
235
|
-
m("gpt-5.3", "GPT-5.3 (Quick)", "Gpt_5_3_Quick", false),
|
|
236
|
-
m("gpt-5.3-quick", "GPT-5.3 (Quick)", "Gpt_5_3_Quick", false),
|
|
237
|
-
m("gpt-5.3-think-deeper", "GPT-5.3 (Think Deeper)", "Gpt_5_3_Reasoning", true),
|
|
238
|
-
m("gpt-5.2", "GPT-5.2 (Quick)", "Gpt_5_2_Quick", false),
|
|
239
|
-
m("gpt-5.2-quick", "GPT-5.2 (Quick)", "Gpt_5_2_Quick", false),
|
|
240
|
-
m("gpt-5.2-think-deeper", "GPT-5.2 (Think Deeper)", "Gpt_5_2_Reasoning", true),
|
|
241
|
-
m(LOCAL_TITLE_MODEL, "Local titler (no M365 call)", null, false)
|
|
242
|
-
];
|
|
243
|
-
function m(id, name, tone, reasoning) {
|
|
244
|
-
return {
|
|
245
|
-
id,
|
|
246
|
-
name,
|
|
247
|
-
tone,
|
|
248
|
-
reasoning,
|
|
249
|
-
limit: {
|
|
250
|
-
context: CONTEXT_TOKENS,
|
|
251
|
-
output: OUTPUT_TOKENS
|
|
252
|
-
}
|
|
253
|
-
};
|
|
254
|
-
}
|
|
255
|
-
const BY_ID = new Map(MODELS.map((model) => [model.id, model]));
|
|
256
|
-
/**
|
|
257
|
-
* Look up a model, falling back to the default for anything we do not know.
|
|
258
|
-
*
|
|
259
|
-
* Harnesses routinely send ids we never advertised (aliases, stale config, a model
|
|
260
|
-
* string typed by hand). Answering on the default beats rejecting the request.
|
|
261
|
-
*/
|
|
262
|
-
function resolveModel(id) {
|
|
263
|
-
if (id) {
|
|
264
|
-
const exact = BY_ID.get(id);
|
|
265
|
-
if (exact) return exact;
|
|
266
|
-
const suffix = id.slice(id.lastIndexOf("/") + 1);
|
|
267
|
-
const stripped = BY_ID.get(suffix);
|
|
268
|
-
if (stripped) return stripped;
|
|
269
|
-
}
|
|
270
|
-
return BY_ID.get(DEFAULT_MODEL);
|
|
271
|
-
}
|
|
272
|
-
/** True when the model is served locally and must never open an M365 conversation. */
|
|
273
|
-
function isLocalModel(id) {
|
|
274
|
-
return resolveModel(id).tone === null;
|
|
275
|
-
}
|
|
276
|
-
/** Every advertised model id, in catalog order. */
|
|
277
|
-
function listModelIds() {
|
|
278
|
-
return MODELS.map((model) => model.id);
|
|
279
|
-
}
|
|
280
|
-
//#endregion
|
|
281
|
-
//#region src/fenced.ts
|
|
282
|
-
/** Info strings we accept as "this is a shell block", beyond the tool's own name. */
|
|
283
|
-
const SHELL_FENCE_INFOS = /* @__PURE__ */ new Set([
|
|
284
|
-
"bash",
|
|
285
|
-
"sh",
|
|
286
|
-
"shell",
|
|
287
|
-
"zsh",
|
|
288
|
-
"console",
|
|
289
|
-
"shellsession",
|
|
290
|
-
"shellscript",
|
|
291
|
-
"terminal"
|
|
292
|
-
]);
|
|
293
|
-
/** Tool names that mean "run a command", whatever the harness calls it. */
|
|
294
|
-
const SHELL_TOOL_NAMES = [
|
|
295
|
-
"bash",
|
|
296
|
-
"shell",
|
|
297
|
-
"sh",
|
|
298
|
-
"run",
|
|
299
|
-
"run_command",
|
|
300
|
-
"runcommand",
|
|
301
|
-
"execute",
|
|
302
|
-
"execute_command",
|
|
303
|
-
"exec",
|
|
304
|
-
"terminal",
|
|
305
|
-
"command"
|
|
306
|
-
];
|
|
307
|
-
/**
|
|
308
|
-
* Parameter names that are conventionally free-form, multi-line bodies.
|
|
309
|
-
*
|
|
310
|
-
* Membership here is the *only* way a parameter becomes the fence body when a tool
|
|
311
|
-
* has more than one argument. A name-based rule is blunt, but it is symmetric: the
|
|
312
|
-
* prompt and the parser derive the same shape from the same list, so a call we
|
|
313
|
-
* described is always a call we can read back. Guessing from JSON-schema types is
|
|
314
|
-
* not symmetric — `read(filePath, offset)` and `t(n, b, s)` both have exactly one
|
|
315
|
-
* string parameter, and it is a body in neither.
|
|
316
|
-
*/
|
|
317
|
-
const BODY_PARAM_NAMES = [
|
|
318
|
-
"command",
|
|
319
|
-
"content",
|
|
320
|
-
"body",
|
|
321
|
-
"text",
|
|
322
|
-
"code",
|
|
323
|
-
"script",
|
|
324
|
-
"patch",
|
|
325
|
-
"diff",
|
|
326
|
-
"input",
|
|
327
|
-
"prompt",
|
|
328
|
-
"query",
|
|
329
|
-
"pattern",
|
|
330
|
-
"thought",
|
|
331
|
-
"message",
|
|
332
|
-
"sql",
|
|
333
|
-
"expression"
|
|
334
|
-
];
|
|
335
|
-
/** Pairs of parameter names that together mean "a search/replace edit". */
|
|
336
|
-
const EDIT_PARAM_PAIRS = [
|
|
337
|
-
["oldString", "newString"],
|
|
338
|
-
["old_string", "new_string"],
|
|
339
|
-
["old", "new"],
|
|
340
|
-
["search", "replace"]
|
|
341
|
-
];
|
|
342
|
-
const SEARCH_MARKER = "<<<<<<< SEARCH";
|
|
343
|
-
const DIVIDER_MARKER = "=======";
|
|
344
|
-
const REPLACE_MARKER = ">>>>>>> REPLACE";
|
|
345
|
-
/** The shell tool in this toolset, whatever the harness named it. */
|
|
346
|
-
function findShellTool(tools) {
|
|
347
|
-
return tools.find((tool) => SHELL_TOOL_NAMES.includes(tool.function.name.toLowerCase()));
|
|
348
|
-
}
|
|
349
|
-
/**
|
|
350
|
-
* Decide how a tool's arguments map onto the fence.
|
|
351
|
-
*
|
|
352
|
-
* The split has to be deterministic in both directions: whatever we describe in the
|
|
353
|
-
* prompt is exactly what the parser expects back.
|
|
354
|
-
*/
|
|
355
|
-
function shapeOf(tool) {
|
|
356
|
-
const props = tool.function.parameters?.properties ?? {};
|
|
357
|
-
const names = Object.keys(props);
|
|
358
|
-
const editPair = EDIT_PARAM_PAIRS.find(([a, b]) => names.includes(a) && names.includes(b));
|
|
359
|
-
let bodyParam;
|
|
360
|
-
if (!editPair) {
|
|
361
|
-
bodyParam = names.find((name) => BODY_PARAM_NAMES.includes(name.toLowerCase()));
|
|
362
|
-
if (!bodyParam && names.length === 1) {
|
|
363
|
-
const only = names[0];
|
|
364
|
-
if ((props[only]?.type ?? "string") === "string" && !props[only]?.enum) bodyParam = only;
|
|
365
|
-
}
|
|
366
|
-
}
|
|
367
|
-
const consumed = /* @__PURE__ */ new Set([...editPair ?? [], ...bodyParam ? [bodyParam] : []]);
|
|
368
|
-
return {
|
|
369
|
-
tool,
|
|
370
|
-
headers: names.filter((name) => !consumed.has(name)),
|
|
371
|
-
bodyParam,
|
|
372
|
-
editPair
|
|
373
|
-
};
|
|
374
|
-
}
|
|
375
|
-
/**
|
|
376
|
-
* Build the `<tools>` block injected into the user turn.
|
|
377
|
-
*
|
|
378
|
-
* Kept deliberately gentle. The Disengaged filter tracks prompt *shape* rather than
|
|
379
|
-
* size — fake `<system>` turns, shouted absolutes and "output ONLY JSON" all read as
|
|
380
|
-
* manipulation and get the conversation disengaged, so a leaner prompt can outscore a
|
|
381
|
-
* more forceful one. Behavioural framing lives here rather than in the agent's
|
|
382
|
-
* server-side instructions, where heavy framing measurably backfired.
|
|
383
|
-
*/
|
|
384
|
-
function buildToolPrompt(tools, options = {}) {
|
|
385
|
-
if (tools.length === 0) return "";
|
|
386
|
-
const shell = findShellTool(tools);
|
|
387
|
-
const useShellFraming = options.shellFraming ?? Boolean(shell);
|
|
388
|
-
const lines = [];
|
|
389
|
-
lines.push("<tools>");
|
|
390
|
-
lines.push("You are working in a real workspace with real files. These tools are available, and a fenced block is an action the runtime executes for you — not an illustration.");
|
|
391
|
-
lines.push("");
|
|
392
|
-
for (const tool of tools) {
|
|
393
|
-
const shape = shapeOf(tool);
|
|
394
|
-
const description = tool.function.description?.trim();
|
|
395
|
-
if (description) lines.push(`${tool.function.name} — ${firstSentence(description)}`);
|
|
396
|
-
lines.push("```" + tool.function.name);
|
|
397
|
-
for (const header of shape.headers) lines.push(`${header}: ${placeholderFor(header, shape.tool)}`);
|
|
398
|
-
if (shape.editPair) {
|
|
399
|
-
lines.push(SEARCH_MARKER);
|
|
400
|
-
lines.push("the exact existing text");
|
|
401
|
-
lines.push(DIVIDER_MARKER);
|
|
402
|
-
lines.push("the replacement text");
|
|
403
|
-
lines.push(REPLACE_MARKER);
|
|
404
|
-
} else if (shape.bodyParam) lines.push(`<${shape.bodyParam}>`);
|
|
405
|
-
lines.push("```");
|
|
406
|
-
lines.push("");
|
|
407
|
-
}
|
|
408
|
-
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.`);
|
|
409
|
-
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.");
|
|
410
|
-
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.");
|
|
411
|
-
lines.push("</tools>");
|
|
412
|
-
return lines.join("\n");
|
|
413
|
-
}
|
|
414
|
-
function firstSentence(text) {
|
|
415
|
-
const cleaned = (text.split("\n").find((candidate) => candidate.trim() !== "") ?? text).replace(/^\s*[-*•]\s*/, "");
|
|
416
|
-
const stop = cleaned.indexOf(". ");
|
|
417
|
-
return (stop > 0 ? cleaned.slice(0, stop) : cleaned).trim();
|
|
418
|
-
}
|
|
419
|
-
function placeholderFor(name, tool) {
|
|
420
|
-
const schema = tool.function.parameters?.properties?.[name];
|
|
421
|
-
if (schema?.enum?.length) return schema.enum.map(String).join(" | ");
|
|
422
|
-
const required = tool.function.parameters?.required?.includes(name);
|
|
423
|
-
return `<${schema?.type ?? "string"}>${required ? "" : " (optional)"}`;
|
|
424
|
-
}
|
|
425
|
-
/**
|
|
426
|
-
* Extract fenced blocks, honouring the CommonMark rule that a fence is closed only by
|
|
427
|
-
* a run of at least as many backticks as opened it.
|
|
428
|
-
*
|
|
429
|
-
* That rule matters here: the model writes heredocs containing ``` all the time, and
|
|
430
|
-
* a naive split would truncate the command halfway through.
|
|
431
|
-
*/
|
|
432
|
-
function extractFences(source) {
|
|
433
|
-
const fences = [];
|
|
434
|
-
const lines = source.split("\n");
|
|
435
|
-
let index = 0;
|
|
436
|
-
while (index < lines.length) {
|
|
437
|
-
const open = /^(\s*)(`{3,})(.*)$/.exec(lines[index]);
|
|
438
|
-
if (!open) {
|
|
439
|
-
index += 1;
|
|
440
|
-
continue;
|
|
441
|
-
}
|
|
442
|
-
const ticks = open[2];
|
|
443
|
-
const info = open[3].trim();
|
|
444
|
-
const bodyLines = [];
|
|
445
|
-
let cursor = index + 1;
|
|
446
|
-
let closed = false;
|
|
447
|
-
while (cursor < lines.length) {
|
|
448
|
-
const close = /^\s*(`{3,})\s*$/.exec(lines[cursor]);
|
|
449
|
-
if (close && close[1].length >= ticks.length) {
|
|
450
|
-
closed = true;
|
|
451
|
-
break;
|
|
452
|
-
}
|
|
453
|
-
bodyLines.push(lines[cursor]);
|
|
454
|
-
cursor += 1;
|
|
455
|
-
}
|
|
456
|
-
if (closed) fences.push({
|
|
457
|
-
info,
|
|
458
|
-
body: bodyLines.join("\n"),
|
|
459
|
-
start: charOffset(lines, index),
|
|
460
|
-
end: charOffset(lines, cursor + 1)
|
|
461
|
-
});
|
|
462
|
-
index = cursor + 1;
|
|
463
|
-
}
|
|
464
|
-
return fences;
|
|
465
|
-
}
|
|
466
|
-
function charOffset(lines, lineIndex) {
|
|
467
|
-
let offset = 0;
|
|
468
|
-
for (let i = 0; i < lineIndex && i < lines.length; i += 1) offset += lines[i].length + 1;
|
|
469
|
-
return offset;
|
|
470
|
-
}
|
|
471
|
-
/**
|
|
472
|
-
* Does this response look like a document the model wrote *as its answer*, rather
|
|
473
|
-
* than an action it wants executed?
|
|
474
|
-
*
|
|
475
|
-
* Shell-routing means every ```bash block becomes a tool call, so a model answering
|
|
476
|
-
* "here's a suggested README" would get its own answer run as shell. A single action
|
|
477
|
-
* is never reclassified — only genuinely document-shaped output is.
|
|
478
|
-
*/
|
|
479
|
-
function isProseDocument(source) {
|
|
480
|
-
const fences = extractFences(source);
|
|
481
|
-
if (fences.length <= 1) return false;
|
|
482
|
-
if (fences.length >= 4) return true;
|
|
483
|
-
return proseAround(source, fences).length >= 120;
|
|
484
|
-
}
|
|
485
|
-
function proseAround(source, fences) {
|
|
486
|
-
let prose = "";
|
|
487
|
-
let cursor = 0;
|
|
488
|
-
for (const fence of fences) {
|
|
489
|
-
prose += source.slice(cursor, fence.start);
|
|
490
|
-
cursor = fence.end;
|
|
491
|
-
}
|
|
492
|
-
prose += source.slice(cursor);
|
|
493
|
-
return prose.trim();
|
|
494
|
-
}
|
|
495
|
-
/**
|
|
496
|
-
* Remove JSON objects the model invents around its answer.
|
|
497
|
-
*
|
|
498
|
-
* M365 likes to append `{"confidence": 0.9}` and to wrap answers in `{"final": ...}`.
|
|
499
|
-
* A lone `{"final": ...}` is unwrapped into its text; one riding alongside a real
|
|
500
|
-
* tool call is a premature victory claim and gets dropped by the caller.
|
|
501
|
-
*/
|
|
502
|
-
function stripInventedJson(text) {
|
|
503
|
-
let result = text;
|
|
504
|
-
result = result.replace(/^\s*\{\s*"confidence"\s*:\s*[^}]*\}\s*$/gm, "");
|
|
505
|
-
const lone = /^\s*\{\s*"final"\s*:\s*("(?:[^"\\]|\\.)*")\s*\}\s*$/.exec(result.trim());
|
|
506
|
-
if (lone) try {
|
|
507
|
-
return JSON.parse(lone[1]);
|
|
508
|
-
} catch {}
|
|
509
|
-
result = result.replace(/^\s*\{\s*"final"\s*:\s*(?:"(?:[^"\\]|\\.)*"|[^}]*)\}\s*$/gm, "");
|
|
510
|
-
return result.trim();
|
|
511
|
-
}
|
|
512
|
-
/** Parse a raw M365 response into OpenAI-shaped tool calls plus any prose. */
|
|
513
|
-
function parseToolCalls(source, tools, options = {}) {
|
|
514
|
-
const cleaned = stripInventedJson(source);
|
|
515
|
-
if (tools.length === 0) return {
|
|
516
|
-
toolCalls: [],
|
|
517
|
-
text: cleaned
|
|
518
|
-
};
|
|
519
|
-
if (isProseDocument(cleaned)) return {
|
|
520
|
-
toolCalls: [],
|
|
521
|
-
text: cleaned
|
|
522
|
-
};
|
|
523
|
-
const shell = findShellTool(tools);
|
|
524
|
-
const byName = new Map(tools.map((tool) => [tool.function.name.toLowerCase(), tool]));
|
|
525
|
-
const calls = [];
|
|
526
|
-
const consumed = [];
|
|
527
|
-
for (const fence of extractFences(cleaned)) {
|
|
528
|
-
const info = fence.info.split(/\s+/)[0]?.toLowerCase() ?? "";
|
|
529
|
-
let tool = byName.get(info);
|
|
530
|
-
if (!tool && shell && SHELL_FENCE_INFOS.has(info)) tool = shell;
|
|
531
|
-
if (!tool) continue;
|
|
532
|
-
calls.push({
|
|
533
|
-
name: tool.function.name,
|
|
534
|
-
arguments: parseFenceBody(fence.body, tool)
|
|
535
|
-
});
|
|
536
|
-
consumed.push(fence);
|
|
537
|
-
if (!options.allowMultiple) break;
|
|
538
|
-
}
|
|
539
|
-
if (calls.length === 0) return {
|
|
540
|
-
toolCalls: [],
|
|
541
|
-
text: cleaned
|
|
542
|
-
};
|
|
543
|
-
return {
|
|
544
|
-
toolCalls: calls,
|
|
545
|
-
text: ""
|
|
546
|
-
};
|
|
547
|
-
}
|
|
548
|
-
/** Split a fence body into header args, a SEARCH/REPLACE pair, and/or a body arg. */
|
|
549
|
-
function parseFenceBody(body, tool) {
|
|
550
|
-
const shape = shapeOf(tool);
|
|
551
|
-
const props = tool.function.parameters?.properties ?? {};
|
|
552
|
-
const args = {};
|
|
553
|
-
const lines = body.split("\n");
|
|
554
|
-
let cursor = 0;
|
|
555
|
-
while (cursor < lines.length) {
|
|
556
|
-
const match = /^([A-Za-z_][A-Za-z0-9_]*)\s*:\s?(.*)$/.exec(lines[cursor]);
|
|
557
|
-
if (!match) break;
|
|
558
|
-
const key = match[1];
|
|
559
|
-
if (!shape.headers.includes(key)) break;
|
|
560
|
-
args[key] = coerce(match[2].trim(), props[key]?.type);
|
|
561
|
-
cursor += 1;
|
|
562
|
-
}
|
|
563
|
-
const rest = lines.slice(cursor).join("\n").replace(/^\n+/, "");
|
|
564
|
-
if (shape.editPair) {
|
|
565
|
-
const diff = parseSearchReplace(rest);
|
|
566
|
-
if (diff) {
|
|
567
|
-
args[shape.editPair[0]] = diff.search;
|
|
568
|
-
args[shape.editPair[1]] = diff.replace;
|
|
569
|
-
}
|
|
570
|
-
return args;
|
|
571
|
-
}
|
|
572
|
-
if (shape.bodyParam) {
|
|
573
|
-
const trimmed = rest.trim();
|
|
574
|
-
if (trimmed !== "") args[shape.bodyParam] = trimmed;
|
|
575
|
-
}
|
|
576
|
-
return args;
|
|
577
|
-
}
|
|
578
|
-
function parseSearchReplace(body) {
|
|
579
|
-
const lines = body.split("\n");
|
|
580
|
-
const start = lines.findIndex((line) => line.trim().startsWith(SEARCH_MARKER));
|
|
581
|
-
if (start === -1) return void 0;
|
|
582
|
-
const divider = lines.findIndex((line, i) => i > start && line.trim() === DIVIDER_MARKER);
|
|
583
|
-
if (divider === -1) return void 0;
|
|
584
|
-
const end = lines.findIndex((line, i) => i > divider && line.trim().startsWith(REPLACE_MARKER));
|
|
585
|
-
if (end === -1) return void 0;
|
|
586
|
-
return {
|
|
587
|
-
search: lines.slice(start + 1, divider).join("\n"),
|
|
588
|
-
replace: lines.slice(divider + 1, end).join("\n")
|
|
589
|
-
};
|
|
590
|
-
}
|
|
591
|
-
/** Coerce a header value to the type the schema declares. */
|
|
592
|
-
function coerce(value, type) {
|
|
593
|
-
switch (type) {
|
|
594
|
-
case "number":
|
|
595
|
-
case "integer": {
|
|
596
|
-
const parsed = Number(value);
|
|
597
|
-
return Number.isFinite(parsed) ? parsed : value;
|
|
598
|
-
}
|
|
599
|
-
case "boolean":
|
|
600
|
-
if (value === "true") return true;
|
|
601
|
-
if (value === "false") return false;
|
|
602
|
-
return value;
|
|
603
|
-
default: return value;
|
|
604
|
-
}
|
|
605
|
-
}
|
|
606
|
-
//#endregion
|
|
607
|
-
//#region src/config.ts
|
|
608
|
-
/**
|
|
609
|
-
* opencode configuration: the provider entry, and the lean tool profile that makes
|
|
610
|
-
* M365 willing to engage at all.
|
|
611
|
-
*
|
|
612
|
-
* Everything here is pure — it takes a base URL and returns/mutates plain objects —
|
|
613
|
-
* so the interesting decisions are testable without opencode, a network, or a tenant.
|
|
614
|
-
*/
|
|
615
|
-
/** The provider id opencode addresses models by: `m365/<model>`. */
|
|
616
|
-
const PROVIDER_ID = "m365";
|
|
617
|
-
/**
|
|
618
|
-
* The tools we leave enabled.
|
|
619
|
-
*
|
|
620
|
-
* `bash` is not optional. M365's chat-tuned model refuses to "act as an agent" on
|
|
621
|
-
* demand, but reflexively writes a ```bash block — routing that block to the shell
|
|
622
|
-
* tool is the single lever that took the reference implementation's benchmark from
|
|
623
|
-
* 0/5 to real multi-turn loops. Remove bash and tool calling largely stops working.
|
|
624
|
-
*
|
|
625
|
-
* The rest is the minimum needed to read and change code.
|
|
626
|
-
*/
|
|
627
|
-
const LEAN_TOOLS = [
|
|
628
|
-
"bash",
|
|
629
|
-
"read",
|
|
630
|
-
"edit",
|
|
631
|
-
"write",
|
|
632
|
-
"apply_patch",
|
|
633
|
-
"grep"
|
|
634
|
-
];
|
|
635
|
-
/**
|
|
636
|
-
* opencode built-ins we switch off in lean mode.
|
|
637
|
-
*
|
|
638
|
-
* Each one is a tool block in the injected prompt, and the count is what trips the
|
|
639
|
-
* filter. `glob`/`grep` overlap and `bash` can do both; `webfetch`/`websearch` are
|
|
640
|
-
* rarely load-bearing for a coding turn; `todowrite`/`question`/`skill` are harness
|
|
641
|
-
* ergonomics rather than capability.
|
|
642
|
-
*/
|
|
643
|
-
const DISABLED_TOOLS = [
|
|
644
|
-
"glob",
|
|
645
|
-
"lsp",
|
|
646
|
-
"patch",
|
|
647
|
-
"skill",
|
|
648
|
-
"todowrite",
|
|
649
|
-
"todoread",
|
|
650
|
-
"webfetch",
|
|
651
|
-
"websearch",
|
|
652
|
-
"question",
|
|
653
|
-
"task"
|
|
654
|
-
];
|
|
655
|
-
/**
|
|
656
|
-
* Cut a harness's toolset down to something M365 will engage with.
|
|
657
|
-
*
|
|
658
|
-
* This is the enforcement point, and it has to be. opencode's own `tools` config —
|
|
659
|
-
* which the plugin also sets — is resolved into the config but **not applied to the
|
|
660
|
-
* request**: verified against 1.18.18, where a config disabling eight tools still
|
|
661
|
-
* produced a request offering all nine. The proxy sees the final request, so it is
|
|
662
|
-
* the only place the trim reliably happens.
|
|
663
|
-
*
|
|
664
|
-
* Two rules, in order:
|
|
665
|
-
* 1. Keep the tools we recognise as load-bearing for a coding loop.
|
|
666
|
-
* 2. If we recognise none of them — a harness with its own vocabulary — fall back
|
|
667
|
-
* to a hard cap, keeping any shell tool first.
|
|
668
|
-
*/
|
|
669
|
-
function selectLeanTools(tools) {
|
|
670
|
-
if (tools.length === 0) return [...tools];
|
|
671
|
-
const wanted = new Set(LEAN_TOOLS);
|
|
672
|
-
const kept = tools.filter((tool) => wanted.has(tool.function.name.toLowerCase()));
|
|
673
|
-
if (kept.length > 0) return kept;
|
|
674
|
-
const shell = findShellTool(tools);
|
|
675
|
-
const rest = tools.filter((tool) => tool !== shell);
|
|
676
|
-
const remaining = shell ? 4 : 5;
|
|
677
|
-
return [...shell ? [shell] : [], ...rest.slice(0, remaining)];
|
|
678
|
-
}
|
|
679
|
-
/** Tool names that mean "change a file", across opencode versions and harnesses. */
|
|
680
|
-
const EDITING_TOOLS = [
|
|
681
|
-
"edit",
|
|
682
|
-
"write",
|
|
683
|
-
"apply_patch",
|
|
684
|
-
"patch",
|
|
685
|
-
"str_replace",
|
|
686
|
-
"create"
|
|
687
|
-
];
|
|
688
|
-
/**
|
|
689
|
-
* Describe anything worrying about the trimmed toolset, or undefined if it is fine.
|
|
690
|
-
*
|
|
691
|
-
* The allowlist in `LEAN_TOOLS` is coupled to what the harness calls its tools, and
|
|
692
|
-
* that has already changed once. When the trim silently removes the ability to edit
|
|
693
|
-
* or to run a command, the model degrades quietly — worth a line in the log rather
|
|
694
|
-
* than a mystery.
|
|
695
|
-
*/
|
|
696
|
-
function describeToolSelection(requested) {
|
|
697
|
-
if (requested.length === 0) return void 0;
|
|
698
|
-
const kept = selectLeanTools(requested);
|
|
699
|
-
const names = kept.map((tool) => tool.function.name.toLowerCase());
|
|
700
|
-
if (!findShellTool(kept)) return "the trimmed toolset has no shell tool, so shell-routing is unavailable and tool calling will be markedly less reliable";
|
|
701
|
-
if (!names.some((name) => EDITING_TOOLS.includes(name))) return "the trimmed toolset has no editing tool — the model can only change files through the shell. The harness may have renamed its tools; check LEAN_TOOLS.";
|
|
702
|
-
}
|
|
703
|
-
/**
|
|
704
|
-
* Normalise the options object opencode hands us.
|
|
705
|
-
*
|
|
706
|
-
* These come straight out of user-authored JSON, so anything can be anything. A bad
|
|
707
|
-
* value falls back to the default rather than throwing — a plugin that throws during
|
|
708
|
-
* load takes opencode's whole config with it.
|
|
709
|
-
*/
|
|
710
|
-
function resolveOptions(raw) {
|
|
711
|
-
const bool = (value, fallback) => typeof value === "boolean" ? value : fallback;
|
|
712
|
-
const options = raw ?? {};
|
|
713
|
-
return {
|
|
714
|
-
lean: bool(options.lean, true),
|
|
715
|
-
setDefaultModel: bool(options.setDefaultModel, true),
|
|
716
|
-
setSmallModel: bool(options.setSmallModel, true),
|
|
717
|
-
leanSystemPrompt: bool(options.leanSystemPrompt, false),
|
|
718
|
-
baseUrl: typeof options.baseUrl === "string" ? options.baseUrl : void 0
|
|
719
|
-
};
|
|
720
|
-
}
|
|
721
|
-
/** `{ bash: true, ..., webfetch: false, ... }` — opencode's `tools` config shape. */
|
|
722
|
-
function buildToolProfile() {
|
|
723
|
-
const profile = {};
|
|
724
|
-
for (const tool of LEAN_TOOLS) profile[tool] = true;
|
|
725
|
-
for (const tool of DISABLED_TOOLS) profile[tool] = false;
|
|
726
|
-
return profile;
|
|
727
|
-
}
|
|
728
|
-
/** The `provider.m365` entry pointing opencode at our local OpenAI-compatible proxy. */
|
|
729
|
-
function buildProviderConfig(baseUrl) {
|
|
730
|
-
const models = {};
|
|
731
|
-
for (const model of MODELS) models[model.id] = {
|
|
732
|
-
name: model.name,
|
|
733
|
-
tool_call: !isLocalModel(model.id),
|
|
734
|
-
reasoning: model.reasoning,
|
|
735
|
-
attachment: false,
|
|
736
|
-
limit: model.limit,
|
|
737
|
-
cost: {
|
|
738
|
-
input: 0,
|
|
739
|
-
output: 0,
|
|
740
|
-
cache_read: 0,
|
|
741
|
-
cache_write: 0
|
|
742
|
-
}
|
|
743
|
-
};
|
|
744
|
-
return {
|
|
745
|
-
npm: "@ai-sdk/openai-compatible",
|
|
746
|
-
name: "Microsoft 365 Copilot",
|
|
747
|
-
options: {
|
|
748
|
-
baseURL: baseUrl,
|
|
749
|
-
apiKey: "m365-local",
|
|
750
|
-
timeout: 9e5
|
|
751
|
-
},
|
|
752
|
-
models
|
|
753
|
-
};
|
|
754
|
-
}
|
|
755
|
-
/**
|
|
756
|
-
* Mutate opencode's in-memory config during the plugin's `config` hook.
|
|
757
|
-
*
|
|
758
|
-
* Deliberately additive: anything the user set explicitly wins. We are a plugin
|
|
759
|
-
* making someone else's config work, not the owner of it.
|
|
760
|
-
*/
|
|
761
|
-
function applyPluginConfig(config, baseUrl, options) {
|
|
762
|
-
config.provider ??= {};
|
|
763
|
-
config.provider[PROVIDER_ID] = buildProviderConfig(baseUrl);
|
|
764
|
-
if (options.setDefaultModel && !config.model) config.model = `${PROVIDER_ID}/${DEFAULT_MODEL}`;
|
|
765
|
-
if (options.setSmallModel && !config.small_model) config.small_model = `${PROVIDER_ID}/${LOCAL_TITLE_MODEL}`;
|
|
766
|
-
if (options.lean && usesOurProvider(config)) config.tools = {
|
|
767
|
-
...buildToolProfile(),
|
|
768
|
-
...config.tools ?? {}
|
|
769
|
-
};
|
|
770
|
-
}
|
|
771
|
-
function usesOurProvider(config) {
|
|
772
|
-
return typeof config.model === "string" && config.model.startsWith(`m365/`);
|
|
773
|
-
}
|
|
774
|
-
/**
|
|
775
|
-
* Merge our plugin reference into an on-disk `opencode.json`, non-destructively.
|
|
776
|
-
*
|
|
777
|
-
* `pluginRef` is either the npm package name or an absolute path to the built
|
|
778
|
-
* plugin — the CLI uses the latter for a local checkout.
|
|
779
|
-
*/
|
|
780
|
-
function mergeOpencodeConfig(existing, opts) {
|
|
781
|
-
const merged = { ...existing };
|
|
782
|
-
merged.$schema ??= "https://opencode.ai/config.json";
|
|
783
|
-
const kept = (Array.isArray(merged.plugin) ? [...merged.plugin] : []).filter((entry) => {
|
|
784
|
-
return !isOurPluginRef(typeof entry === "string" ? entry : Array.isArray(entry) ? String(entry[0]) : "", opts.pluginRef);
|
|
785
|
-
});
|
|
786
|
-
kept.push(opts.pluginRef);
|
|
787
|
-
merged.plugin = kept;
|
|
788
|
-
return merged;
|
|
789
|
-
}
|
|
790
|
-
/**
|
|
791
|
-
* Does `ref` point at this plugin?
|
|
792
|
-
*
|
|
793
|
-
* Three ways it can: the npm package name, this repo's directory name, or the same
|
|
794
|
-
* build artifact at a different location — a local install is an absolute path to
|
|
795
|
-
* `.../dist/plugin.mjs`, and only the directory changes when the checkout moves.
|
|
796
|
-
*/
|
|
797
|
-
function isOurPluginRef(ref, incoming) {
|
|
798
|
-
if (ref === incoming) return true;
|
|
799
|
-
if (ref.includes("opencode-m365-copilot") || ref.includes("opencode-copilot-plugin")) return true;
|
|
800
|
-
return tail(ref) !== "" && tail(ref) === tail(incoming);
|
|
801
|
-
}
|
|
802
|
-
/** The last two path segments, which for a local install are `dist/plugin.mjs`. */
|
|
803
|
-
function tail(ref) {
|
|
804
|
-
if (!ref.includes("/")) return "";
|
|
805
|
-
return ref.split("/").slice(-2).join("/");
|
|
806
|
-
}
|
|
807
|
-
//#endregion
|
|
808
|
-
//#region src/session.ts
|
|
809
|
-
/**
|
|
810
|
-
* The M365 Copilot transport: SignalR over WebSocket.
|
|
811
|
-
*
|
|
812
|
-
* Things that are load-bearing and non-obvious, all of which fail *silently* when
|
|
813
|
-
* you get them wrong:
|
|
814
|
-
*
|
|
815
|
-
* - The access token goes in the WebSocket URL **query string**, not a header.
|
|
816
|
-
* - Node's built-in WebSocket is refused. The `ws` package plus a browser-shaped
|
|
817
|
-
* `Origin`/`User-Agent` is what the server accepts.
|
|
818
|
-
* - Frames are JSON terminated by `0x1E` (record separator), and one WebSocket
|
|
819
|
-
* message can carry several of them.
|
|
820
|
-
* - A `Metrics` frame must ride in the **same send** as the chat frame. Omit it and
|
|
821
|
-
* the turn simply never produces output — no error, just silence.
|
|
822
|
-
* - Only bot messages with **no** `messageType` carry the answer. Everything with one
|
|
823
|
-
* is control traffic.
|
|
824
|
-
* - `messageType: "Disengaged"` is a refusal with empty content. It looks exactly
|
|
825
|
-
* like rate limiting and must not be retried into.
|
|
826
|
-
*
|
|
827
|
-
* Each turn opens a fresh socket but reuses the conversation id, so the server keeps
|
|
828
|
-
* threading context. The 600-message cap is per conversation, which is why we reuse.
|
|
829
|
-
*/
|
|
830
|
-
const log$1 = createLogger("session");
|
|
831
|
-
/** Record separator: every SignalR frame ends with this byte. */
|
|
832
|
-
const RS = "";
|
|
833
|
-
const DEFAULT_ENDPOINT = "wss://substrate.office.com";
|
|
834
|
-
/** The upgrade is rejected without browser-shaped headers. */
|
|
835
|
-
const BROWSER_HEADERS = {
|
|
836
|
-
Origin: "https://m365.cloud.microsoft",
|
|
837
|
-
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:148.0) Gecko/20100101 Firefox/148.0"
|
|
838
|
-
};
|
|
839
|
-
/**
|
|
840
|
-
* Feature flags copied from a captured first-party session.
|
|
841
|
-
*
|
|
842
|
-
* Cargo-culted on purpose: these are the values the real Office web client sends, and
|
|
843
|
-
* which subset actually matters has never been established. Removing them is untested.
|
|
844
|
-
*/
|
|
845
|
-
const VARIANTS = [
|
|
846
|
-
"feature.EnableWebSearch",
|
|
847
|
-
"feature.EnableCodeInterpreter",
|
|
848
|
-
"feature.EnableSydneyClientCompliance",
|
|
849
|
-
"feature.EnableStreaming"
|
|
850
|
-
].join(",");
|
|
851
|
-
/** The message types we tell the server we are able to render. */
|
|
852
|
-
const ALLOWED_MESSAGE_TYPES = [
|
|
853
|
-
"Chat",
|
|
854
|
-
"Suggestion",
|
|
855
|
-
"Progress",
|
|
856
|
-
"EndOfRequest",
|
|
857
|
-
"Disengaged",
|
|
858
|
-
"InternalSearchQuery",
|
|
859
|
-
"InternalSearchResult",
|
|
860
|
-
"RenderCardRequest",
|
|
861
|
-
"ReferencesListComplete",
|
|
862
|
-
"GeneratedCode"
|
|
863
|
-
];
|
|
864
|
-
/** Read the object id and tenant id out of a Sydney token — they address the hub. */
|
|
865
|
-
function decodeJwt(token) {
|
|
866
|
-
const parts = token.split(".");
|
|
867
|
-
if (parts.length < 2) throw new Error("Malformed JWT: expected three dot-separated segments");
|
|
868
|
-
let claims;
|
|
869
|
-
try {
|
|
870
|
-
claims = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
|
|
871
|
-
} catch {
|
|
872
|
-
throw new Error("Malformed JWT: payload is not valid base64url JSON");
|
|
873
|
-
}
|
|
874
|
-
if (!claims || typeof claims !== "object") throw new Error("Malformed JWT: payload is not an object");
|
|
875
|
-
return claims;
|
|
876
|
-
}
|
|
877
|
-
/** M365 refused to engage with the prompt. Not a rate limit — do not retry into it. */
|
|
878
|
-
var DisengagedError = class extends Error {
|
|
879
|
-
disengaged = true;
|
|
880
|
-
constructor(message = "M365 Copilot disengaged from this conversation") {
|
|
881
|
-
super(message);
|
|
882
|
-
this.name = "DisengagedError";
|
|
883
|
-
}
|
|
884
|
-
};
|
|
885
|
-
/**
|
|
886
|
-
* One M365 conversation.
|
|
887
|
-
*
|
|
888
|
-
* Stateful across turns: the conversation and session ids persist so the server keeps
|
|
889
|
-
* its own context, and follow-up turns only need to carry new messages.
|
|
890
|
-
*/
|
|
891
|
-
var CopilotSession = class {
|
|
892
|
-
conversationId;
|
|
893
|
-
sessionId;
|
|
894
|
-
turnIndex = 0;
|
|
895
|
-
options;
|
|
896
|
-
constructor(options) {
|
|
897
|
-
this.options = options;
|
|
898
|
-
this.conversationId = options.conversationId ?? randomUUID();
|
|
899
|
-
this.sessionId = options.sessionId ?? randomUUID();
|
|
900
|
-
}
|
|
901
|
-
/** Abandon the server-side context and start a fresh conversation. */
|
|
902
|
-
reset() {
|
|
903
|
-
this.conversationId = randomUUID();
|
|
904
|
-
this.sessionId = randomUUID();
|
|
905
|
-
this.turnIndex = 0;
|
|
906
|
-
}
|
|
907
|
-
async run(text, turn = {}) {
|
|
908
|
-
if (turn.signal?.aborted) throw abortError();
|
|
909
|
-
const token = await this.options.getToken();
|
|
910
|
-
const { oid, tid } = decodeJwt(token);
|
|
911
|
-
const url = this.buildUrl(token, oid, tid);
|
|
912
|
-
const socket = new WebSocket(url, { headers: BROWSER_HEADERS });
|
|
913
|
-
try {
|
|
914
|
-
const result = await this.pump(socket, text, turn);
|
|
915
|
-
this.turnIndex += 1;
|
|
916
|
-
return result;
|
|
917
|
-
} finally {
|
|
918
|
-
closeSocket(socket);
|
|
919
|
-
}
|
|
920
|
-
}
|
|
921
|
-
buildUrl(token, oid, tid) {
|
|
922
|
-
return `${this.options.endpoint ?? DEFAULT_ENDPOINT}/m365Copilot/Chathub/${oid}@${tid}?${new URLSearchParams({
|
|
923
|
-
access_token: token,
|
|
924
|
-
ConversationId: this.conversationId,
|
|
925
|
-
chatsessionid: this.sessionId,
|
|
926
|
-
"X-SessionId": this.sessionId,
|
|
927
|
-
clientrequestid: randomUUID(),
|
|
928
|
-
source: "\"officeweb\"",
|
|
929
|
-
product: "Office",
|
|
930
|
-
agentHost: "Bizchat.FullScreen",
|
|
931
|
-
scenario: "OfficeWebIncludedCopilot",
|
|
932
|
-
variants: VARIANTS
|
|
933
|
-
}).toString()}`;
|
|
934
|
-
}
|
|
935
|
-
/** Drive one turn to completion. */
|
|
936
|
-
pump(socket, text, turn) {
|
|
937
|
-
return new Promise((resolve, reject) => {
|
|
938
|
-
let deltaText = "";
|
|
939
|
-
let snapshotText = "";
|
|
940
|
-
let handshakeDone = false;
|
|
941
|
-
let settled = false;
|
|
942
|
-
const result = { text: "" };
|
|
943
|
-
const finish = (error) => {
|
|
944
|
-
if (settled) return;
|
|
945
|
-
settled = true;
|
|
946
|
-
turn.signal?.removeEventListener("abort", onAbort);
|
|
947
|
-
if (error) {
|
|
948
|
-
reject(error);
|
|
949
|
-
return;
|
|
950
|
-
}
|
|
951
|
-
result.text = deltaText.length >= snapshotText.length ? deltaText : snapshotText;
|
|
952
|
-
resolve(result);
|
|
953
|
-
};
|
|
954
|
-
const onAbort = () => {
|
|
955
|
-
try {
|
|
956
|
-
socket.send(`${JSON.stringify({
|
|
957
|
-
arguments: [{}],
|
|
958
|
-
invocationId: "1",
|
|
959
|
-
target: "stop",
|
|
960
|
-
type: 1
|
|
961
|
-
})}${RS}`);
|
|
962
|
-
} catch {}
|
|
963
|
-
finish(abortError());
|
|
964
|
-
};
|
|
965
|
-
turn.signal?.addEventListener("abort", onAbort, { once: true });
|
|
966
|
-
socket.on("error", (error) => finish(error instanceof Error ? error : new Error(String(error))));
|
|
967
|
-
socket.on("close", () => finish());
|
|
968
|
-
socket.on("open", () => {
|
|
969
|
-
socket.send(`${JSON.stringify({
|
|
970
|
-
protocol: "json",
|
|
971
|
-
version: 1
|
|
972
|
-
})}${RS}`);
|
|
973
|
-
});
|
|
974
|
-
socket.on("message", (raw) => {
|
|
975
|
-
for (const frame of splitFrames(raw.toString())) {
|
|
976
|
-
if (!handshakeDone) {
|
|
977
|
-
handshakeDone = true;
|
|
978
|
-
this.sendChat(socket, text, turn);
|
|
979
|
-
if (Object.keys(frame).length === 0) continue;
|
|
980
|
-
}
|
|
981
|
-
switch (frame.type) {
|
|
982
|
-
case 1:
|
|
983
|
-
if (frame.target === "update") for (const argument of frame.arguments ?? []) {
|
|
984
|
-
const applied = this.applyUpdate(argument, result, turn);
|
|
985
|
-
if (applied.disengaged) {
|
|
986
|
-
finish(new DisengagedError());
|
|
987
|
-
return;
|
|
988
|
-
}
|
|
989
|
-
deltaText += applied.delta;
|
|
990
|
-
if (applied.snapshot.length > snapshotText.length) snapshotText = applied.snapshot;
|
|
991
|
-
}
|
|
992
|
-
break;
|
|
993
|
-
case 2:
|
|
994
|
-
this.applyStreamItem(frame.item, result);
|
|
995
|
-
if (frame.item?.result?.message && frame.item.result.message.length > snapshotText.length) snapshotText = frame.item.result.message;
|
|
996
|
-
break;
|
|
997
|
-
case 3:
|
|
998
|
-
if (frame.error) {
|
|
999
|
-
finish(/* @__PURE__ */ new Error(`M365 rejected the turn: ${frame.error}`));
|
|
1000
|
-
return;
|
|
1001
|
-
}
|
|
1002
|
-
finish();
|
|
1003
|
-
return;
|
|
1004
|
-
case 6:
|
|
1005
|
-
socket.send(`${JSON.stringify({ type: 6 })}${RS}`);
|
|
1006
|
-
break;
|
|
1007
|
-
case 7:
|
|
1008
|
-
if (frame.error) {
|
|
1009
|
-
finish(/* @__PURE__ */ new Error(`M365 closed the connection: ${frame.error}`));
|
|
1010
|
-
return;
|
|
1011
|
-
}
|
|
1012
|
-
finish();
|
|
1013
|
-
return;
|
|
1014
|
-
}
|
|
1015
|
-
}
|
|
1016
|
-
});
|
|
1017
|
-
});
|
|
1018
|
-
}
|
|
1019
|
-
/** The chat invocation and its mandatory Metrics companion, in one send. */
|
|
1020
|
-
sendChat(socket, text, turn) {
|
|
1021
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1022
|
-
const argument = {
|
|
1023
|
-
message: {
|
|
1024
|
-
text,
|
|
1025
|
-
author: "user",
|
|
1026
|
-
inputMethod: "Keyboard",
|
|
1027
|
-
messageType: "Chat",
|
|
1028
|
-
locale: "en-US",
|
|
1029
|
-
timestamp: now,
|
|
1030
|
-
messageId: randomUUID()
|
|
1031
|
-
},
|
|
1032
|
-
tone: turn.tone ?? "magic",
|
|
1033
|
-
source: "officeweb",
|
|
1034
|
-
streamingMode: "ConciseWithPadding",
|
|
1035
|
-
isStartOfSession: this.turnIndex === 0,
|
|
1036
|
-
conversationId: this.conversationId,
|
|
1037
|
-
allowedMessageTypes: ALLOWED_MESSAGE_TYPES,
|
|
1038
|
-
optionsSets: [],
|
|
1039
|
-
clientInfo: {
|
|
1040
|
-
clientPlatform: "mcmcopilot-web",
|
|
1041
|
-
clientAppName: "Office",
|
|
1042
|
-
clientAppVersion: "1.0.0"
|
|
1043
|
-
},
|
|
1044
|
-
traceId: randomUUID()
|
|
1045
|
-
};
|
|
1046
|
-
if (turn.agentId) {
|
|
1047
|
-
argument.threadLevelGptId = {
|
|
1048
|
-
id: turn.agentId,
|
|
1049
|
-
source: "MOS3"
|
|
1050
|
-
};
|
|
1051
|
-
argument.gpts = [{
|
|
1052
|
-
id: turn.agentId,
|
|
1053
|
-
source: "MOS3",
|
|
1054
|
-
version: "1.0.0",
|
|
1055
|
-
clientOverrides: {
|
|
1056
|
-
capabilities: [],
|
|
1057
|
-
"deepResearchModels@odata.type": "Collection(String)"
|
|
1058
|
-
}
|
|
1059
|
-
}];
|
|
1060
|
-
} else argument.plugins = [{
|
|
1061
|
-
Id: "BingWebSearch",
|
|
1062
|
-
Source: "BuiltIn"
|
|
1063
|
-
}];
|
|
1064
|
-
const chat = {
|
|
1065
|
-
arguments: [argument],
|
|
1066
|
-
invocationId: "0",
|
|
1067
|
-
target: "chat",
|
|
1068
|
-
type: 4
|
|
1069
|
-
};
|
|
1070
|
-
const metrics = {
|
|
1071
|
-
arguments: [{ Timestamps: {
|
|
1072
|
-
ConnectionStart: now,
|
|
1073
|
-
UserInputStart: now,
|
|
1074
|
-
ConnectionEstablished: now,
|
|
1075
|
-
UserInputSubmit: now
|
|
1076
|
-
} }],
|
|
1077
|
-
target: "Metrics",
|
|
1078
|
-
type: 1
|
|
1079
|
-
};
|
|
1080
|
-
log$1.info("sending turn", trunc({
|
|
1081
|
-
tone: argument.tone,
|
|
1082
|
-
agent: Boolean(turn.agentId),
|
|
1083
|
-
text
|
|
1084
|
-
}));
|
|
1085
|
-
socket.send(`${JSON.stringify(chat)}${RS}${JSON.stringify(metrics)}${RS}`);
|
|
1086
|
-
}
|
|
1087
|
-
/** Fold one `update` argument into the accumulating result. */
|
|
1088
|
-
applyUpdate(argument, result, turn) {
|
|
1089
|
-
let deltaChunk = "";
|
|
1090
|
-
let snapshot = "";
|
|
1091
|
-
if (typeof argument?.writeAtCursor === "string") {
|
|
1092
|
-
deltaChunk = argument.writeAtCursor;
|
|
1093
|
-
turn.onDelta?.(deltaChunk);
|
|
1094
|
-
}
|
|
1095
|
-
if (argument?.throttling) result.throttle = {
|
|
1096
|
-
current: argument.throttling.numUserMessagesInConversation,
|
|
1097
|
-
max: argument.throttling.maxNumUserMessagesInConversation
|
|
1098
|
-
};
|
|
1099
|
-
for (const message of argument?.messages ?? []) {
|
|
1100
|
-
if (message?.author !== "bot") continue;
|
|
1101
|
-
if (message.messageType === "Disengaged") return {
|
|
1102
|
-
delta: deltaChunk,
|
|
1103
|
-
snapshot,
|
|
1104
|
-
disengaged: true
|
|
1105
|
-
};
|
|
1106
|
-
if (message.messageType) continue;
|
|
1107
|
-
if (typeof message.text === "string" && message.text.length > snapshot.length) snapshot = message.text;
|
|
1108
|
-
absorbMetadata(message, result);
|
|
1109
|
-
}
|
|
1110
|
-
return {
|
|
1111
|
-
delta: deltaChunk,
|
|
1112
|
-
snapshot,
|
|
1113
|
-
disengaged: false
|
|
1114
|
-
};
|
|
1115
|
-
}
|
|
1116
|
-
applyStreamItem(item, result) {
|
|
1117
|
-
if (!item) return;
|
|
1118
|
-
if (item.throttling) result.throttle = {
|
|
1119
|
-
current: item.throttling.numUserMessagesInConversation,
|
|
1120
|
-
max: item.throttling.maxNumUserMessagesInConversation
|
|
1121
|
-
};
|
|
1122
|
-
for (const message of item.messages ?? []) if (message?.author === "bot" && !message.messageType) absorbMetadata(message, result);
|
|
1123
|
-
}
|
|
1124
|
-
};
|
|
1125
|
-
/** Pull the diagnostic fields off a final bot message. */
|
|
1126
|
-
function absorbMetadata(message, result) {
|
|
1127
|
-
if (typeof message.contentOrigin === "string") result.contentOrigin = message.contentOrigin;
|
|
1128
|
-
if (typeof message.turnCount === "number") result.turnCount = message.turnCount;
|
|
1129
|
-
if (Array.isArray(message.scores)) {
|
|
1130
|
-
result.scores ??= {};
|
|
1131
|
-
for (const score of message.scores) if (typeof score?.component === "string") result.scores[score.component] = score.score;
|
|
1132
|
-
}
|
|
1133
|
-
}
|
|
1134
|
-
/** One WebSocket message can carry several `0x1E`-terminated frames. */
|
|
1135
|
-
function splitFrames(raw) {
|
|
1136
|
-
const frames = [];
|
|
1137
|
-
for (const chunk of raw.split(RS)) {
|
|
1138
|
-
if (chunk.trim() === "") continue;
|
|
1139
|
-
try {
|
|
1140
|
-
frames.push(JSON.parse(chunk));
|
|
1141
|
-
} catch {
|
|
1142
|
-
log$1.warn("unparseable frame", trunc(chunk));
|
|
1143
|
-
}
|
|
1144
|
-
}
|
|
1145
|
-
return frames;
|
|
1146
|
-
}
|
|
1147
|
-
/**
|
|
1148
|
-
* Shut a turn's socket down without losing anything still buffered.
|
|
1149
|
-
*
|
|
1150
|
-
* `terminate()` destroys the socket immediately and drops queued frames — which is
|
|
1151
|
-
* how a pong or the stop frame can be sent and still never arrive. `close()` flushes
|
|
1152
|
-
* first; the timer is the backstop for a server that never completes the handshake.
|
|
1153
|
-
*/
|
|
1154
|
-
function closeSocket(socket) {
|
|
1155
|
-
if (socket.readyState === WebSocket.CLOSED || socket.readyState === WebSocket.CLOSING) return;
|
|
1156
|
-
try {
|
|
1157
|
-
socket.close();
|
|
1158
|
-
} catch {
|
|
1159
|
-
socket.terminate();
|
|
1160
|
-
return;
|
|
1161
|
-
}
|
|
1162
|
-
const timer = setTimeout(() => socket.terminate(), 1e3);
|
|
1163
|
-
timer.unref?.();
|
|
1164
|
-
socket.once("close", () => clearTimeout(timer));
|
|
1165
|
-
}
|
|
1166
|
-
function abortError() {
|
|
1167
|
-
const error = /* @__PURE__ */ new Error("The M365 turn was aborted");
|
|
1168
|
-
error.name = "AbortError";
|
|
1169
|
-
return error;
|
|
1170
|
-
}
|
|
1171
|
-
//#endregion
|
|
1172
|
-
//#region src/translate.ts
|
|
1173
|
-
/**
|
|
1174
|
-
* OpenAI ⇄ M365 translation.
|
|
1175
|
-
*
|
|
1176
|
-
* Two asymmetries drive the design:
|
|
1177
|
-
*
|
|
1178
|
-
* - **M365 is stateful, OpenAI is not.** An OpenAI client resends the whole history
|
|
1179
|
-
* every turn; M365 keeps its own server-side context and charges 600 user messages
|
|
1180
|
-
* per *conversation*. So we key conversations on the first user message and send
|
|
1181
|
-
* only what is new.
|
|
1182
|
-
* - **M365 has no tool calls.** Tools go out as a fenced contract in the prompt and
|
|
1183
|
-
* come back as fenced blocks, which `fenced.ts` converts in both directions.
|
|
1184
|
-
*/
|
|
1185
|
-
const ContentPart = z.object({
|
|
1186
|
-
type: z.string(),
|
|
1187
|
-
text: z.string().optional()
|
|
1188
|
-
}).passthrough();
|
|
1189
|
-
const Message = z.object({
|
|
1190
|
-
role: z.string(),
|
|
1191
|
-
content: z.union([
|
|
1192
|
-
z.string(),
|
|
1193
|
-
z.array(ContentPart),
|
|
1194
|
-
z.null()
|
|
1195
|
-
]).optional(),
|
|
1196
|
-
name: z.string().optional(),
|
|
1197
|
-
tool_call_id: z.string().optional(),
|
|
1198
|
-
tool_calls: z.array(z.object({
|
|
1199
|
-
id: z.string(),
|
|
1200
|
-
type: z.literal("function").optional(),
|
|
1201
|
-
function: z.object({
|
|
1202
|
-
name: z.string(),
|
|
1203
|
-
arguments: z.string()
|
|
1204
|
-
})
|
|
1205
|
-
})).optional()
|
|
1206
|
-
}).passthrough();
|
|
1207
|
-
const Tool = z.object({
|
|
1208
|
-
type: z.literal("function"),
|
|
1209
|
-
function: z.object({
|
|
1210
|
-
name: z.string(),
|
|
1211
|
-
description: z.string().optional(),
|
|
1212
|
-
parameters: z.any().optional()
|
|
1213
|
-
})
|
|
1214
|
-
});
|
|
1215
|
-
const ChatCompletionRequest = z.object({
|
|
1216
|
-
model: z.string().optional(),
|
|
1217
|
-
messages: z.array(Message).min(1),
|
|
1218
|
-
tools: z.array(Tool).optional(),
|
|
1219
|
-
tool_choice: z.any().optional(),
|
|
1220
|
-
stream: z.boolean().optional(),
|
|
1221
|
-
temperature: z.number().optional(),
|
|
1222
|
-
top_p: z.number().optional(),
|
|
1223
|
-
max_tokens: z.number().optional()
|
|
1224
|
-
});
|
|
1225
|
-
/**
|
|
1226
|
-
* Maps an OpenAI client's stateless history onto stateful M365 conversations.
|
|
1227
|
-
*
|
|
1228
|
-
* Identity is the first user message: an agent loop keeps resending the same opening
|
|
1229
|
-
* turn, so it is a stable handle for "this is still the same task".
|
|
1230
|
-
*/
|
|
1231
|
-
var ConversationPool = class {
|
|
1232
|
-
conversations = /* @__PURE__ */ new Map();
|
|
1233
|
-
maxIdleMs;
|
|
1234
|
-
constructor(options = {}) {
|
|
1235
|
-
this.maxIdleMs = options.maxIdleMs ?? 36e5;
|
|
1236
|
-
}
|
|
1237
|
-
resolve(messages) {
|
|
1238
|
-
this.evictStale();
|
|
1239
|
-
const key = fingerprint(messages);
|
|
1240
|
-
const existing = this.conversations.get(key);
|
|
1241
|
-
if (existing) {
|
|
1242
|
-
if (messages.length < existing.sentMessageCount) existing.sentMessageCount = 0;
|
|
1243
|
-
existing.lastAccessedAt = Date.now();
|
|
1244
|
-
return existing;
|
|
1245
|
-
}
|
|
1246
|
-
const state = {
|
|
1247
|
-
key,
|
|
1248
|
-
sentMessageCount: 0,
|
|
1249
|
-
lastAccessedAt: Date.now()
|
|
1250
|
-
};
|
|
1251
|
-
this.conversations.set(key, state);
|
|
1252
|
-
return state;
|
|
1253
|
-
}
|
|
1254
|
-
get size() {
|
|
1255
|
-
return this.conversations.size;
|
|
1256
|
-
}
|
|
1257
|
-
evictStale() {
|
|
1258
|
-
const now = Date.now();
|
|
1259
|
-
for (const [key, state] of this.conversations) if (now - state.lastAccessedAt >= this.maxIdleMs) this.conversations.delete(key);
|
|
1260
|
-
}
|
|
1261
|
-
};
|
|
1262
|
-
function fingerprint(messages) {
|
|
1263
|
-
const firstUser = messages.find((message) => message.role === "user");
|
|
1264
|
-
const text = firstUser ? contentOf(firstUser) : "";
|
|
1265
|
-
let hash = 0;
|
|
1266
|
-
for (let i = 0; i < text.length; i += 1) hash = (hash << 5) - hash + text.charCodeAt(i) | 0;
|
|
1267
|
-
return `c${hash}`;
|
|
1268
|
-
}
|
|
1269
|
-
/** Message content as plain text, flattening the array-of-parts form. */
|
|
1270
|
-
function contentOf(message) {
|
|
1271
|
-
const { content } = message;
|
|
1272
|
-
if (typeof content === "string") return content;
|
|
1273
|
-
if (Array.isArray(content)) return content.map((part) => typeof part.text === "string" ? part.text : "").filter(Boolean).join("\n");
|
|
1274
|
-
return "";
|
|
1275
|
-
}
|
|
1276
|
-
/**
|
|
1277
|
-
* Capability catalogues a harness injects into its system prompt, and the tool each
|
|
1278
|
-
* one needs in order to be actionable.
|
|
1279
|
-
*
|
|
1280
|
-
* Measured against opencode 1.18: `<available_skills>` alone was 34k of a 53k-char
|
|
1281
|
-
* system prompt — and lean mode disables the `skill` tool, so every entry in it named
|
|
1282
|
-
* something the model had no way to invoke. Advertising unusable capabilities is
|
|
1283
|
-
* worse than saying nothing: it invites the model to claim it did something it cannot.
|
|
1284
|
-
*/
|
|
1285
|
-
const CAPABILITY_CATALOGUES = [{
|
|
1286
|
-
tag: "available_skills",
|
|
1287
|
-
requires: ["skill"]
|
|
1288
|
-
}, {
|
|
1289
|
-
tag: "available_agents",
|
|
1290
|
-
requires: ["task", "agent"]
|
|
1291
|
-
}];
|
|
1292
|
-
/**
|
|
1293
|
-
* Trim a harness system prompt down to what this toolset can actually act on.
|
|
1294
|
-
*
|
|
1295
|
-
* This happens here rather than in the plugin because opencode's own hooks cannot do
|
|
1296
|
-
* it: `experimental.chat.system.transform` fires and accepts a new `system` array,
|
|
1297
|
-
* but the request still carries the original prompt (verified against 1.18.18), and
|
|
1298
|
-
* `agent.<name>.prompt` set from the config hook is ignored the same way. The proxy
|
|
1299
|
-
* sees the final request, so it is the one place the change reliably lands.
|
|
1300
|
-
*/
|
|
1301
|
-
function condenseSystemPrompt(text, tools, options = {}) {
|
|
1302
|
-
const toolNames = new Set(tools.map((tool) => tool.function.name.toLowerCase()));
|
|
1303
|
-
let result = text;
|
|
1304
|
-
for (const { tag, requires } of CAPABILITY_CATALOGUES) {
|
|
1305
|
-
if (requires.some((name) => toolNames.has(name))) continue;
|
|
1306
|
-
result = result.replace(new RegExp(`<${tag}>[\\s\\S]*?</${tag}>`, "g"), "");
|
|
1307
|
-
}
|
|
1308
|
-
if (options.replaceProseWith !== void 0) {
|
|
1309
|
-
const { leadingBlocks, instructions, blocks } = splitSystemPrompt(result);
|
|
1310
|
-
result = [
|
|
1311
|
-
options.replaceProseWith,
|
|
1312
|
-
...leadingBlocks,
|
|
1313
|
-
instructions,
|
|
1314
|
-
blocks
|
|
1315
|
-
].filter(Boolean).join("\n\n");
|
|
1316
|
-
}
|
|
1317
|
-
return result.replace(/\n{3,}/g, "\n\n").trim();
|
|
1318
|
-
}
|
|
1319
|
-
const BLOCK_PATTERN = /<([a-z_][a-z0-9_-]*)>[\s\S]*?<\/\1>/gi;
|
|
1320
|
-
/**
|
|
1321
|
-
* Split a harness system prompt into: leading prose, the user's own instructions,
|
|
1322
|
-
* and the structured blocks the harness appends at the end.
|
|
1323
|
-
*
|
|
1324
|
-
* The boundary that matters is the **trailing** run of structured blocks, not the
|
|
1325
|
-
* first tag-like line. A rules file is Markdown and routinely contains HTML or JSX —
|
|
1326
|
-
* cutting at the first `<something>` would drop every rule after it, which is exactly
|
|
1327
|
-
* the silent deletion this logic exists to prevent.
|
|
1328
|
-
*
|
|
1329
|
-
* Everything from the first `Instructions from:` line up to that trailing run is
|
|
1330
|
-
* treated as the user's, verbatim, whatever it contains.
|
|
1331
|
-
*/
|
|
1332
|
-
function splitSystemPrompt(text) {
|
|
1333
|
-
const tailStart = trailingBlockStart(text);
|
|
1334
|
-
const head = text.slice(0, tailStart);
|
|
1335
|
-
const blocks = text.slice(tailStart).trim();
|
|
1336
|
-
const marker = head.search(/^Instructions from:[ \t]*\S/m);
|
|
1337
|
-
const proseEnd = marker === -1 ? head.length : marker;
|
|
1338
|
-
return {
|
|
1339
|
-
leadingBlocks: [...head.slice(0, proseEnd).matchAll(BLOCK_PATTERN)].map((match) => match[0]),
|
|
1340
|
-
instructions: marker === -1 ? "" : head.slice(marker).trim(),
|
|
1341
|
-
blocks
|
|
1342
|
-
};
|
|
1343
|
-
}
|
|
1344
|
-
/**
|
|
1345
|
-
* Offset at which the closing run of structured blocks begins.
|
|
1346
|
-
*
|
|
1347
|
-
* Walks matched `<tag>…</tag>` pairs from the end, extending backwards while nothing
|
|
1348
|
-
* but whitespace separates them, so only blocks that genuinely trail the prompt are
|
|
1349
|
-
* treated as the harness's own. Returns `text.length` when there are none.
|
|
1350
|
-
*/
|
|
1351
|
-
function trailingBlockStart(text) {
|
|
1352
|
-
const matches = [...text.matchAll(BLOCK_PATTERN)];
|
|
1353
|
-
let start = text.length;
|
|
1354
|
-
for (let i = matches.length - 1; i >= 0; i -= 1) {
|
|
1355
|
-
const match = matches[i];
|
|
1356
|
-
const end = match.index + match[0].length;
|
|
1357
|
-
if (text.slice(end, start).trim() !== "") break;
|
|
1358
|
-
start = match.index;
|
|
1359
|
-
}
|
|
1360
|
-
return start;
|
|
1361
|
-
}
|
|
1362
|
-
/**
|
|
1363
|
-
* Build the single prompt string for this turn.
|
|
1364
|
-
*
|
|
1365
|
-
* Only messages beyond `sentMessageCount` are included — the server already has the
|
|
1366
|
-
* rest. The tool block is repeated every turn: it is the contract, and the model
|
|
1367
|
-
* drifts away from it if it falls out of view.
|
|
1368
|
-
*/
|
|
1369
|
-
function buildTurnPrompt(messages, tools, sentMessageCount, options = {}) {
|
|
1370
|
-
const parts = [];
|
|
1371
|
-
if (sentMessageCount === 0) {
|
|
1372
|
-
const systemText = messages.filter((message) => message.role === "system" || message.role === "developer").map(contentOf).filter(Boolean).join("\n\n");
|
|
1373
|
-
if (systemText) parts.push(condenseSystemPrompt(systemText, tools, { ...options.leanSystemPrompt !== void 0 ? { replaceProseWith: options.leanSystemPrompt } : {} }));
|
|
1374
|
-
}
|
|
1375
|
-
if (tools.length > 0) parts.push(buildToolPrompt(tools));
|
|
1376
|
-
const callsById = /* @__PURE__ */ new Map();
|
|
1377
|
-
for (const message of messages) for (const call of message.tool_calls ?? []) callsById.set(call.id, call.function);
|
|
1378
|
-
for (const message of messages.slice(sentMessageCount)) {
|
|
1379
|
-
if (message.role === "system" || message.role === "developer") continue;
|
|
1380
|
-
if (message.role === "tool") {
|
|
1381
|
-
parts.push(renderToolResult(message, callsById));
|
|
1382
|
-
continue;
|
|
1383
|
-
}
|
|
1384
|
-
if (message.role === "assistant") {
|
|
1385
|
-
const text = contentOf(message);
|
|
1386
|
-
if (text) parts.push(text);
|
|
1387
|
-
continue;
|
|
1388
|
-
}
|
|
1389
|
-
const text = contentOf(message);
|
|
1390
|
-
if (text) parts.push(text);
|
|
1391
|
-
}
|
|
1392
|
-
return parts.filter(Boolean).join("\n\n");
|
|
1393
|
-
}
|
|
1394
|
-
/**
|
|
1395
|
-
* Wrap a tool result so the model can tell what it is looking at.
|
|
1396
|
-
*
|
|
1397
|
-
* An unlabelled blob is routinely misread — an `ls` listing taken for file contents,
|
|
1398
|
-
* an empty stdout taken for an empty file.
|
|
1399
|
-
*/
|
|
1400
|
-
function renderToolResult(message, callsById) {
|
|
1401
|
-
const call = message.tool_call_id ? callsById.get(message.tool_call_id) : void 0;
|
|
1402
|
-
const attributes = [];
|
|
1403
|
-
if (call?.name) attributes.push(`tool="${escapeAttribute(call.name)}"`);
|
|
1404
|
-
const summary = summariseArguments(call?.arguments);
|
|
1405
|
-
if (summary) attributes.push(`command="${escapeAttribute(summary)}"`);
|
|
1406
|
-
return `${attributes.length > 0 ? `<tool_response ${attributes.join(" ")}>` : "<tool_response>"}\n${contentOf(message)}\n</tool_response>`;
|
|
1407
|
-
}
|
|
1408
|
-
/** The most identifying argument value, for the label. */
|
|
1409
|
-
function summariseArguments(raw) {
|
|
1410
|
-
if (!raw) return void 0;
|
|
1411
|
-
try {
|
|
1412
|
-
const parsed = JSON.parse(raw);
|
|
1413
|
-
const value = parsed.command ?? parsed.filePath ?? parsed.path ?? parsed.pattern ?? parsed.query;
|
|
1414
|
-
if (typeof value !== "string") return void 0;
|
|
1415
|
-
return value.length > 120 ? `${value.slice(0, 117)}…` : value;
|
|
1416
|
-
} catch {
|
|
1417
|
-
return;
|
|
1418
|
-
}
|
|
1419
|
-
}
|
|
1420
|
-
function escapeAttribute(value) {
|
|
1421
|
-
return value.replace(/"/g, """).replace(/\n/g, " ");
|
|
1422
|
-
}
|
|
1423
|
-
function buildCompletion(result, options) {
|
|
1424
|
-
const { toolCalls, text } = parseToolCalls(result.text, options.tools, { allowMultiple: options.allowMultiple ?? false });
|
|
1425
|
-
const hasCalls = toolCalls.length > 0;
|
|
1426
|
-
return {
|
|
1427
|
-
id: `chatcmpl-${randomUUID()}`,
|
|
1428
|
-
object: "chat.completion",
|
|
1429
|
-
created: Math.floor(Date.now() / 1e3),
|
|
1430
|
-
model: options.model,
|
|
1431
|
-
choices: [{
|
|
1432
|
-
index: 0,
|
|
1433
|
-
message: {
|
|
1434
|
-
role: "assistant",
|
|
1435
|
-
content: hasCalls ? null : text,
|
|
1436
|
-
...hasCalls ? { tool_calls: toolCalls.map(toOpenAiToolCall) } : {}
|
|
1437
|
-
},
|
|
1438
|
-
finish_reason: hasCalls ? "tool_calls" : "stop"
|
|
1439
|
-
}],
|
|
1440
|
-
usage: buildUsage(result)
|
|
1441
|
-
};
|
|
1442
|
-
}
|
|
1443
|
-
function toOpenAiToolCall(call) {
|
|
1444
|
-
return {
|
|
1445
|
-
id: `call_${randomUUID().replace(/-/g, "").slice(0, 24)}`,
|
|
1446
|
-
type: "function",
|
|
1447
|
-
function: {
|
|
1448
|
-
name: call.name,
|
|
1449
|
-
arguments: JSON.stringify(call.arguments)
|
|
1450
|
-
}
|
|
1451
|
-
};
|
|
1452
|
-
}
|
|
1453
|
-
/**
|
|
1454
|
-
* Usage, plus M365-specific extensions.
|
|
1455
|
-
*
|
|
1456
|
-
* M365 never reports token counts, so the standard fields are zero. The extensions
|
|
1457
|
-
* carry what it *does* report: the per-conversation message quota — the closest thing
|
|
1458
|
-
* to context-window utilisation available — and the classifier score that rises
|
|
1459
|
-
* before the Disengaged filter fires. Clients that ignore unknown fields are fine.
|
|
1460
|
-
*/
|
|
1461
|
-
function buildUsage(result) {
|
|
1462
|
-
const usage = {
|
|
1463
|
-
prompt_tokens: 0,
|
|
1464
|
-
completion_tokens: 0,
|
|
1465
|
-
total_tokens: 0
|
|
1466
|
-
};
|
|
1467
|
-
if (result.throttle) {
|
|
1468
|
-
const { current, max } = result.throttle;
|
|
1469
|
-
usage.x_m365_conversation_messages = current;
|
|
1470
|
-
usage.x_m365_conversation_max = max;
|
|
1471
|
-
usage.x_m365_conversation_remaining = Math.max(0, max - current);
|
|
1472
|
-
usage.x_m365_conversation_pct = max > 0 ? Math.round(current / max * 100) : 0;
|
|
1473
|
-
}
|
|
1474
|
-
if (result.contentOrigin) usage.x_m365_content_origin = result.contentOrigin;
|
|
1475
|
-
if (typeof result.turnCount === "number") usage.x_m365_turn_count = result.turnCount;
|
|
1476
|
-
if (result.scores) {
|
|
1477
|
-
usage.x_m365_classifier_scores = result.scores;
|
|
1478
|
-
if (typeof result.scores.dea_violation === "number") usage.x_m365_dea_score = result.scores.dea_violation;
|
|
1479
|
-
}
|
|
1480
|
-
return usage;
|
|
1481
|
-
}
|
|
1482
|
-
/** One `chat.completion.chunk` as a server-sent event frame. */
|
|
1483
|
-
function streamChunk(id, model, delta) {
|
|
1484
|
-
const payload = {
|
|
1485
|
-
id,
|
|
1486
|
-
object: "chat.completion.chunk",
|
|
1487
|
-
created: Math.floor(Date.now() / 1e3),
|
|
1488
|
-
model,
|
|
1489
|
-
choices: [{
|
|
1490
|
-
index: 0,
|
|
1491
|
-
delta: {
|
|
1492
|
-
...delta.content !== void 0 ? { content: delta.content } : {},
|
|
1493
|
-
...delta.toolCalls ? { tool_calls: delta.toolCalls.map((call, index) => ({
|
|
1494
|
-
index,
|
|
1495
|
-
...call
|
|
1496
|
-
})) } : {}
|
|
1497
|
-
},
|
|
1498
|
-
finish_reason: delta.finishReason ?? null
|
|
1499
|
-
}]
|
|
1500
|
-
};
|
|
1501
|
-
return `data: ${JSON.stringify(payload)}\n\n`;
|
|
1502
|
-
}
|
|
1503
|
-
function streamDone() {
|
|
1504
|
-
return "data: [DONE]\n\n";
|
|
1505
|
-
}
|
|
1506
|
-
/** Instruction wrappers a harness puts around a title request, which are not the subject. */
|
|
1507
|
-
const TITLE_INSTRUCTION = /generate|summar|title|respond with|in a few words|short phrase/i;
|
|
1508
|
-
/**
|
|
1509
|
-
* Name a session without spending an M365 conversation on it.
|
|
1510
|
-
*
|
|
1511
|
-
* opencode's `small_model` defaults to the main model, so titling would open a second
|
|
1512
|
-
* conversation for every session — and the throttle counts conversations started, not
|
|
1513
|
-
* messages. This is not as good as a model-written title; it is free, and it keeps
|
|
1514
|
-
* the account out of the throttle.
|
|
1515
|
-
*/
|
|
1516
|
-
function generateTitle(messages) {
|
|
1517
|
-
const cleaned = (messages.filter((message) => message.role === "user").map(contentOf).filter((text) => text.trim() !== "" && !TITLE_INSTRUCTION.test(firstLine(text))).join("\n") || messages.map(contentOf).join("\n")).replace(/```[\s\S]*?```/g, " ").replace(/`[^`]*`/g, " ").replace(/<tool_response[\s\S]*?<\/tool_response>/g, " ").replace(/[#*_>]/g, " ").replace(/\s+/g, " ").trim();
|
|
1518
|
-
if (cleaned === "") return "New session";
|
|
1519
|
-
const words = cleaned.split(" ").slice(0, 8).join(" ");
|
|
1520
|
-
const title = words.length > 50 ? `${words.slice(0, 47).trimEnd()}…` : words;
|
|
1521
|
-
return title.charAt(0).toUpperCase() + title.slice(1);
|
|
1522
|
-
}
|
|
1523
|
-
function firstLine(text) {
|
|
1524
|
-
return text.split("\n", 1)[0] ?? "";
|
|
1525
|
-
}
|
|
1526
|
-
//#endregion
|
|
1527
|
-
//#region src/server.ts
|
|
1528
|
-
/**
|
|
1529
|
-
* The OpenAI-compatible HTTP surface.
|
|
1530
|
-
*
|
|
1531
|
-
* Small on purpose: `node:http` rather than a framework, because this runs inside
|
|
1532
|
-
* opencode's own process and every dependency here is one opencode has to install.
|
|
1533
|
-
* It binds loopback only — the proxy is unauthenticated and speaks to a paid account
|
|
1534
|
-
* with your credentials.
|
|
1535
|
-
*/
|
|
1536
|
-
const log = createLogger("server");
|
|
1537
|
-
/** See the warning in `handleChatCompletion`; this keeps it to once per process. */
|
|
1538
|
-
let warnedAboutToolSelection = false;
|
|
1539
|
-
async function startServer(deps) {
|
|
1540
|
-
const pool = new ConversationPool();
|
|
1541
|
-
const host = deps.host ?? "127.0.0.1";
|
|
1542
|
-
let agentPromise;
|
|
1543
|
-
const agentId = async () => {
|
|
1544
|
-
if (!deps.resolveAgent) return null;
|
|
1545
|
-
agentPromise ??= deps.resolveAgent().catch((error) => {
|
|
1546
|
-
log.warn("could not resolve a declarative agent; continuing without one", String(error));
|
|
1547
|
-
return null;
|
|
1548
|
-
});
|
|
1549
|
-
return agentPromise;
|
|
1550
|
-
};
|
|
1551
|
-
const server = createServer((request, response) => {
|
|
1552
|
-
handle(request, response, {
|
|
1553
|
-
deps,
|
|
1554
|
-
pool,
|
|
1555
|
-
agentId
|
|
1556
|
-
}).catch((error) => {
|
|
1557
|
-
log.error("unhandled request failure", String(error));
|
|
1558
|
-
sendError(response, 500, "internal_error", String(error));
|
|
1559
|
-
});
|
|
1560
|
-
});
|
|
1561
|
-
await new Promise((resolve, reject) => {
|
|
1562
|
-
server.once("error", reject);
|
|
1563
|
-
server.listen(deps.port ?? 0, host, resolve);
|
|
1564
|
-
});
|
|
1565
|
-
const { port } = server.address();
|
|
1566
|
-
return {
|
|
1567
|
-
url: `http://${host}:${port}`,
|
|
1568
|
-
port,
|
|
1569
|
-
close: () => new Promise((resolve) => {
|
|
1570
|
-
server.closeAllConnections?.();
|
|
1571
|
-
server.close(() => resolve());
|
|
1572
|
-
})
|
|
1573
|
-
};
|
|
1574
|
-
}
|
|
1575
|
-
async function handle(request, response, context) {
|
|
1576
|
-
const url = new URL(request.url ?? "/", "http://localhost");
|
|
1577
|
-
const method = (request.method ?? "GET").toUpperCase();
|
|
1578
|
-
if (method === "OPTIONS") {
|
|
1579
|
-
response.writeHead(204, corsHeaders()).end();
|
|
1580
|
-
return;
|
|
1581
|
-
}
|
|
1582
|
-
if (method === "GET" && url.pathname === "/health") {
|
|
1583
|
-
sendJson(response, 200, { status: "ok" });
|
|
1584
|
-
return;
|
|
1585
|
-
}
|
|
1586
|
-
if (method === "GET" && url.pathname === "/v1/models") {
|
|
1587
|
-
sendJson(response, 200, {
|
|
1588
|
-
object: "list",
|
|
1589
|
-
data: listModelIds().map((id) => ({
|
|
1590
|
-
id,
|
|
1591
|
-
object: "model",
|
|
1592
|
-
created: Math.floor(Date.now() / 1e3),
|
|
1593
|
-
owned_by: "microsoft"
|
|
1594
|
-
}))
|
|
1595
|
-
});
|
|
1596
|
-
return;
|
|
1597
|
-
}
|
|
1598
|
-
if (method === "POST" && url.pathname === "/v1/chat/completions") {
|
|
1599
|
-
await handleChatCompletion(request, response, context);
|
|
1600
|
-
return;
|
|
1601
|
-
}
|
|
1602
|
-
sendError(response, 404, "not_found", `No route for ${method} ${url.pathname}`);
|
|
1603
|
-
}
|
|
1604
|
-
async function handleChatCompletion(request, response, context) {
|
|
1605
|
-
let body;
|
|
1606
|
-
try {
|
|
1607
|
-
body = ChatCompletionRequest.parse(JSON.parse(await readBody(request)));
|
|
1608
|
-
} catch (error) {
|
|
1609
|
-
sendError(response, 400, "invalid_request_error", String(error?.message ?? error));
|
|
1610
|
-
return;
|
|
1611
|
-
}
|
|
1612
|
-
const model = resolveModel(body.model);
|
|
1613
|
-
const requested = body.tools ?? [];
|
|
1614
|
-
const tools = context.deps.lean === false ? requested : selectLeanTools(requested);
|
|
1615
|
-
if (tools.length !== requested.length) {
|
|
1616
|
-
log.info(`trimmed toolset ${requested.length} -> ${tools.length}`, tools.map((t) => t.function.name).join(","));
|
|
1617
|
-
const concern = describeToolSelection(requested);
|
|
1618
|
-
if (concern && !warnedAboutToolSelection) {
|
|
1619
|
-
warnedAboutToolSelection = true;
|
|
1620
|
-
log.warn(concern);
|
|
1621
|
-
}
|
|
1622
|
-
}
|
|
1623
|
-
if (isLocalModel(model.id)) {
|
|
1624
|
-
respondWithTitle(response, body, model.id);
|
|
1625
|
-
return;
|
|
1626
|
-
}
|
|
1627
|
-
const conversation = context.pool.resolve(body.messages);
|
|
1628
|
-
conversation.session ??= new CopilotSession({
|
|
1629
|
-
getToken: context.deps.getToken,
|
|
1630
|
-
...context.deps.endpoint ? { endpoint: context.deps.endpoint } : {}
|
|
1631
|
-
});
|
|
1632
|
-
const prompt = buildTurnPrompt(body.messages, tools, conversation.sentMessageCount, { ...context.deps.leanSystemPrompt !== void 0 ? { leanSystemPrompt: context.deps.leanSystemPrompt } : {} });
|
|
1633
|
-
const agent = tools.length > 0 ? await context.agentId() : null;
|
|
1634
|
-
const abort = new AbortController();
|
|
1635
|
-
request.on("close", () => {
|
|
1636
|
-
if (!response.writableEnded) abort.abort();
|
|
1637
|
-
});
|
|
1638
|
-
const streaming = body.stream === true;
|
|
1639
|
-
const streamId = `chatcmpl-${randomUUID()}`;
|
|
1640
|
-
const canStreamText = streaming && tools.length === 0;
|
|
1641
|
-
if (streaming) startSse(response);
|
|
1642
|
-
try {
|
|
1643
|
-
const result = await conversation.session.run(prompt, {
|
|
1644
|
-
...model.tone ? { tone: model.tone } : {},
|
|
1645
|
-
agentId: agent,
|
|
1646
|
-
signal: abort.signal,
|
|
1647
|
-
...canStreamText ? { onDelta: (chunk) => response.write(streamChunk(streamId, model.id, { content: chunk })) } : {}
|
|
1648
|
-
});
|
|
1649
|
-
conversation.sentMessageCount = body.messages.length;
|
|
1650
|
-
if (!streaming) {
|
|
1651
|
-
sendJson(response, 200, buildCompletion(result, {
|
|
1652
|
-
model: model.id,
|
|
1653
|
-
tools,
|
|
1654
|
-
allowMultiple: context.deps.allowMultiTool ?? false
|
|
1655
|
-
}));
|
|
1656
|
-
return;
|
|
1657
|
-
}
|
|
1658
|
-
finishStream(response, streamId, model.id, result, tools, canStreamText, context.deps.allowMultiTool ?? false);
|
|
1659
|
-
} catch (error) {
|
|
1660
|
-
handleTurnFailure(response, error, streaming, tools.length);
|
|
1661
|
-
}
|
|
1662
|
-
}
|
|
1663
|
-
/** Emit the closing frames of a streamed turn. */
|
|
1664
|
-
function finishStream(response, streamId, model, result, tools, alreadyStreamedText, allowMultiple) {
|
|
1665
|
-
const { toolCalls, text } = parseToolCalls(result.text, tools, { allowMultiple });
|
|
1666
|
-
if (toolCalls.length > 0) {
|
|
1667
|
-
response.write(streamChunk(streamId, model, { toolCalls: toolCalls.map(toOpenAiToolCall) }));
|
|
1668
|
-
response.write(streamChunk(streamId, model, { finishReason: "tool_calls" }));
|
|
1669
|
-
} else {
|
|
1670
|
-
if (!alreadyStreamedText && text) response.write(streamChunk(streamId, model, { content: text }));
|
|
1671
|
-
response.write(streamChunk(streamId, model, { finishReason: "stop" }));
|
|
1672
|
-
}
|
|
1673
|
-
response.write(streamDone());
|
|
1674
|
-
response.end();
|
|
1675
|
-
}
|
|
1676
|
-
function handleTurnFailure(response, error, streaming, toolCount) {
|
|
1677
|
-
if (error instanceof AuthRequiredError) {
|
|
1678
|
-
finishWithError(response, streaming, 401, "authentication_required", error.message);
|
|
1679
|
-
return;
|
|
1680
|
-
}
|
|
1681
|
-
if (error instanceof DisengagedError) {
|
|
1682
|
-
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."}`);
|
|
1683
|
-
return;
|
|
1684
|
-
}
|
|
1685
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
1686
|
-
if (error?.name === "AbortError") {
|
|
1687
|
-
if (!response.writableEnded) response.end();
|
|
1688
|
-
return;
|
|
1689
|
-
}
|
|
1690
|
-
finishWithError(response, streaming, 502, "upstream_error", message);
|
|
1691
|
-
}
|
|
1692
|
-
/** Report an error, in whichever shape the client is already reading. */
|
|
1693
|
-
function finishWithError(response, streaming, status, code, message) {
|
|
1694
|
-
if (!streaming) {
|
|
1695
|
-
sendError(response, status, code, message);
|
|
1696
|
-
return;
|
|
1697
|
-
}
|
|
1698
|
-
if (!response.writableEnded) {
|
|
1699
|
-
response.write(`data: ${JSON.stringify({ error: {
|
|
1700
|
-
message,
|
|
1701
|
-
code,
|
|
1702
|
-
type: code
|
|
1703
|
-
} })}\n\n`);
|
|
1704
|
-
response.write(streamDone());
|
|
1705
|
-
response.end();
|
|
1706
|
-
}
|
|
1707
|
-
}
|
|
1708
|
-
function respondWithTitle(response, body, model) {
|
|
1709
|
-
const title = generateTitle(body.messages);
|
|
1710
|
-
if (body.stream !== true) {
|
|
1711
|
-
sendJson(response, 200, {
|
|
1712
|
-
id: `chatcmpl-${randomUUID()}`,
|
|
1713
|
-
object: "chat.completion",
|
|
1714
|
-
created: Math.floor(Date.now() / 1e3),
|
|
1715
|
-
model,
|
|
1716
|
-
choices: [{
|
|
1717
|
-
index: 0,
|
|
1718
|
-
message: {
|
|
1719
|
-
role: "assistant",
|
|
1720
|
-
content: title
|
|
1721
|
-
},
|
|
1722
|
-
finish_reason: "stop"
|
|
1723
|
-
}],
|
|
1724
|
-
usage: buildUsage({ text: title })
|
|
1725
|
-
});
|
|
1726
|
-
return;
|
|
1727
|
-
}
|
|
1728
|
-
const streamId = `chatcmpl-${randomUUID()}`;
|
|
1729
|
-
startSse(response);
|
|
1730
|
-
response.write(streamChunk(streamId, model, { content: title }));
|
|
1731
|
-
response.write(streamChunk(streamId, model, { finishReason: "stop" }));
|
|
1732
|
-
response.write(streamDone());
|
|
1733
|
-
response.end();
|
|
1734
|
-
}
|
|
1735
|
-
function startSse(response) {
|
|
1736
|
-
response.writeHead(200, {
|
|
1737
|
-
"Content-Type": "text/event-stream",
|
|
1738
|
-
"Cache-Control": "no-cache",
|
|
1739
|
-
Connection: "keep-alive",
|
|
1740
|
-
...corsHeaders()
|
|
1741
|
-
});
|
|
1742
|
-
}
|
|
1743
|
-
function corsHeaders() {
|
|
1744
|
-
return {
|
|
1745
|
-
"Access-Control-Allow-Origin": "*",
|
|
1746
|
-
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
|
1747
|
-
"Access-Control-Allow-Headers": "Content-Type, Authorization"
|
|
1748
|
-
};
|
|
1749
|
-
}
|
|
1750
|
-
function sendJson(response, status, body) {
|
|
1751
|
-
const payload = JSON.stringify(body);
|
|
1752
|
-
response.writeHead(status, {
|
|
1753
|
-
"Content-Type": "application/json",
|
|
1754
|
-
...corsHeaders()
|
|
1755
|
-
});
|
|
1756
|
-
response.end(payload);
|
|
1757
|
-
}
|
|
1758
|
-
function sendError(response, status, code, message) {
|
|
1759
|
-
if (response.writableEnded) return;
|
|
1760
|
-
sendJson(response, status, { error: {
|
|
1761
|
-
message,
|
|
1762
|
-
type: code,
|
|
1763
|
-
code
|
|
1764
|
-
} });
|
|
1765
|
-
}
|
|
1766
|
-
async function readBody(request) {
|
|
1767
|
-
const chunks = [];
|
|
1768
|
-
for await (const chunk of request) chunks.push(chunk);
|
|
1769
|
-
return Buffer.concat(chunks).toString("utf8");
|
|
1770
|
-
}
|
|
1771
|
-
//#endregion
|
|
1772
|
-
export { createLogger as _, resolveOptions as a, CONFIG_DIR as b, AUTHORITY as c, POWERPLATFORM_SCOPE as d, REDIRECT_URI as f, createTokenClient as g, createCachePlugin as h, mergeOpencodeConfig as i, BAP_SCOPE as l, authCodeFromUrl as m, PROVIDER_ID as n, DEFAULT_MODEL as o, SYDNEY_SCOPES as p, applyPluginConfig as r, LOCAL_TITLE_MODEL as s, startServer as t, CLIENT_ID as u, AGENT_FILE as v, SECRETS_FILE as x, CACHE_FILE as y };
|