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