opencode-m365-copilot 0.1.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/LICENSE +21 -0
- package/README.md +232 -0
- package/dist/agent-t3MgztgU.mjs +215 -0
- package/dist/cli.d.mts +1 -0
- package/dist/cli.mjs +165 -0
- package/dist/login-Dj9Ss7K_.mjs +192 -0
- package/dist/plugin.d.mts +9 -0
- package/dist/plugin.mjs +63 -0
- package/dist/server-CeGQPDdE.mjs +1772 -0
- package/dist/server.d.mts +51 -0
- package/dist/server.mjs +2 -0
- package/package.json +75 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Chris Hall
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
# opencode-m365-copilot
|
|
2
|
+
|
|
3
|
+
[](https://github.com/chrischall/opencode-copilot-plugin/actions/workflows/ci.yml)
|
|
4
|
+
[](https://www.npmjs.com/package/opencode-m365-copilot)
|
|
5
|
+
[](https://www.npmjs.com/package/opencode-m365-copilot)
|
|
6
|
+
[](LICENSE)
|
|
7
|
+
|
|
8
|
+
Use your organisation's **Microsoft 365 Copilot** as the model backend for
|
|
9
|
+
[opencode](https://opencode.ai).
|
|
10
|
+
|
|
11
|
+
M365 Copilot has no developer API. It is an undocumented SignalR-over-WebSocket service
|
|
12
|
+
(`substrate.office.com`) that Microsoft intends only its own clients to speak to. This
|
|
13
|
+
package implements that protocol, wraps it in an OpenAI-compatible proxy, and ships an
|
|
14
|
+
opencode plugin that starts the proxy in-process and registers it as a provider.
|
|
15
|
+
|
|
16
|
+
```
|
|
17
|
+
opencode ──OpenAI /v1──▶ in-process proxy ──SignalR/WS──▶ M365 Copilot
|
|
18
|
+
│
|
|
19
|
+
└── local-title model, answered without any M365 call
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Install
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
npm install -g opencode-m365-copilot
|
|
26
|
+
opencode-m365 login # one-time browser sign-in
|
|
27
|
+
opencode-m365 setup # adds the plugin to ~/.config/opencode/opencode.json
|
|
28
|
+
opencode # models appear as m365/*
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
`setup` writes only a plugin reference. The provider, the model list, the default model
|
|
32
|
+
and the small model are all registered by the plugin at startup.
|
|
33
|
+
|
|
34
|
+
## The thing you need to know first
|
|
35
|
+
|
|
36
|
+
**M365 refuses to work with a full coding-agent toolset.** Its "Disengaged" filter
|
|
37
|
+
returns an empty reply — indistinguishable from rate limiting unless you look for
|
|
38
|
+
`messageType: "Disengaged"` — and the reference reverse-engineering notes measure the
|
|
39
|
+
threshold at roughly 12 tools, naming opencode specifically as the harness that
|
|
40
|
+
disengages *persistently*.
|
|
41
|
+
|
|
42
|
+
So this plugin's main job is not wiring. It is **cutting opencode down to something M365
|
|
43
|
+
will engage with**. Measured against opencode 1.18.18 on a single agentic turn:
|
|
44
|
+
|
|
45
|
+
| | stock | with this plugin |
|
|
46
|
+
|---|---|---|
|
|
47
|
+
| tools offered | 9 | 4 |
|
|
48
|
+
| prompt sent to M365 | 53,676 chars | 9,701 chars |
|
|
49
|
+
| `<available_skills>` catalogue | 34,263 chars | removed |
|
|
50
|
+
|
|
51
|
+
The trimming is on by default. Turn it off with `{ "lean": false }` and expect empty
|
|
52
|
+
replies.
|
|
53
|
+
|
|
54
|
+
## Where the trimming happens, and why
|
|
55
|
+
|
|
56
|
+
Not in opencode's config — **in the proxy**. Two opencode levers look like they should
|
|
57
|
+
work and do not (verified against 1.18.18, and the reason the architecture is what it is):
|
|
58
|
+
|
|
59
|
+
- **`config.tools`** is resolved into the config — `opencode debug config` shows it
|
|
60
|
+
correctly — but the request still offers every tool. A config disabling eight tools
|
|
61
|
+
produced a request offering all nine.
|
|
62
|
+
- **`experimental.chat.system.transform`** fires, and accepts a replacement `system`
|
|
63
|
+
array, but the request that reaches the provider still carries the original prompt.
|
|
64
|
+
Setting `agent.<name>.prompt` from the `config` hook is ignored the same way.
|
|
65
|
+
|
|
66
|
+
The proxy sees the final request, so it is the one place the trim reliably lands. The
|
|
67
|
+
plugin still sets `config.tools` as a declaration of intent, in case a future version
|
|
68
|
+
honours it.
|
|
69
|
+
|
|
70
|
+
What gets dropped:
|
|
71
|
+
|
|
72
|
+
- **Tools** — keeps `bash`, `read`, `grep`, and whichever editing tool is present
|
|
73
|
+
(`apply_patch` in 1.18.18, `edit`/`write` in others). Drops `glob`, `skill`, `task`,
|
|
74
|
+
`todowrite`, `webfetch`, `websearch`, `lsp`, `question`.
|
|
75
|
+
- **Capability catalogues** — `<available_skills>` is removed when no `skill` tool
|
|
76
|
+
survives the trim, because it advertises capabilities nothing can invoke. `<env>` and
|
|
77
|
+
other structured context are kept.
|
|
78
|
+
- **The harness's prose system prompt** — replaced with a short one, but **off by
|
|
79
|
+
default**. A long, polished assistant prompt measurably reduces M365's tool
|
|
80
|
+
compliance on another harness's numbers; that is a borrowed result we have not
|
|
81
|
+
reproduced, so it is opt-in via `{ "leanSystemPrompt": true }`. Your own rules are
|
|
82
|
+
never dropped either way: opencode injects `AGENTS.md` and global rules as prose
|
|
83
|
+
inside the system message, and those sections are preserved verbatim.
|
|
84
|
+
|
|
85
|
+
`bash` is never dropped. M365's chat-tuned model will not "act as an agent" on request,
|
|
86
|
+
but it *will* reflexively write a ```` ```bash ```` block — routing that block to the
|
|
87
|
+
shell tool is the single lever that makes tool calling work at all.
|
|
88
|
+
|
|
89
|
+
## How tool calling works
|
|
90
|
+
|
|
91
|
+
M365 has no native `tool_calls`. Tools go out as a fenced contract and come back as
|
|
92
|
+
fenced blocks:
|
|
93
|
+
|
|
94
|
+
````
|
|
95
|
+
```read
|
|
96
|
+
filePath: /etc/hostname
|
|
97
|
+
```
|
|
98
|
+
````
|
|
99
|
+
|
|
100
|
+
Scalar arguments are `key: value` header lines, one free-form argument is the fence body,
|
|
101
|
+
and an old/new pair is written as a SEARCH/REPLACE diff. A JSON `{"tool": …}` contract
|
|
102
|
+
was tried in the reference project and scored 0/5 on real agentic tasks.
|
|
103
|
+
|
|
104
|
+
The other half is a **Copilot Studio declarative agent**, provisioned automatically on
|
|
105
|
+
the first turn that carries tools. Microsoft's server-side prompt outranks anything we
|
|
106
|
+
send, so per-request instructions get answered in prose; instructions delivered through
|
|
107
|
+
an agent land in the server-side system prompt and are obeyed. The agent is named after
|
|
108
|
+
a hash of its instructions, so hosts on a tenant converge on one, and it is never
|
|
109
|
+
deleted — another host may be mid-conversation with it.
|
|
110
|
+
|
|
111
|
+
Without Copilot Studio access the plugin still works, just less reliably; it logs a
|
|
112
|
+
warning and carries on.
|
|
113
|
+
|
|
114
|
+
## Configuration
|
|
115
|
+
|
|
116
|
+
```jsonc
|
|
117
|
+
{
|
|
118
|
+
"plugin": [["opencode-m365-copilot", {
|
|
119
|
+
"lean": true, // trim the toolset (default: true)
|
|
120
|
+
"leanSystemPrompt": false, // replace opencode's prose prompt (default: false)
|
|
121
|
+
"setDefaultModel": true, // set `model` if you have not (default: true)
|
|
122
|
+
"setSmallModel": true, // route title generation to the local titler (default: true)
|
|
123
|
+
"baseUrl": null // use an already-running proxy instead of an in-process one
|
|
124
|
+
}]]
|
|
125
|
+
}
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
### Why `small_model` is redirected
|
|
129
|
+
|
|
130
|
+
opencode's `small_model` defaults to your main model, so every new session would generate
|
|
131
|
+
its title on M365 — opening a **second conversation**. The account-level throttle counts
|
|
132
|
+
conversations started, not messages, so that is the fastest way to get throttled. The
|
|
133
|
+
`m365/local-title` model is answered by the proxy itself and never opens a connection.
|
|
134
|
+
|
|
135
|
+
## Models
|
|
136
|
+
|
|
137
|
+
Models are selected by an M365 *tone*, not a model id. `m365/gpt-5.5-think-deeper` is the
|
|
138
|
+
default.
|
|
139
|
+
|
|
140
|
+
> **A conflict worth knowing about.** The reference project's README recommends
|
|
141
|
+
> `gpt-5.5-think-deeper` and reports 100% tool compliance with the agent plus
|
|
142
|
+
> fenced/shell-routing. Its own protocol notes (`m365-copilot-api.md`, quirk #13) say the
|
|
143
|
+
> opposite — that reasoning tones meta-analyse the injected prompt and disengage, and
|
|
144
|
+
> only `magic`/`*_Quick` work with an agent attached. The README is the newer
|
|
145
|
+
> measurement, so it is the default here; if you see disengagement on tool turns, try
|
|
146
|
+
> `m365/quick` or `m365/m365-copilot`.
|
|
147
|
+
|
|
148
|
+
A non-default tone (Claude, the reasoning tones) only takes effect when **no** agent is
|
|
149
|
+
attached — with one, M365 silently routes to GPT regardless. The proxy therefore attaches
|
|
150
|
+
the agent only on turns that carry tools, so plain chat reaches the model the tone selects.
|
|
151
|
+
|
|
152
|
+
## Authentication
|
|
153
|
+
|
|
154
|
+
Sign-in is a CLI concern, never the plugin's: the plugin only refreshes silently and asks
|
|
155
|
+
you to run `opencode-m365 login` if it cannot. A plugin running underneath a TUI has no
|
|
156
|
+
business opening a browser.
|
|
157
|
+
|
|
158
|
+
Two ways to sign in:
|
|
159
|
+
|
|
160
|
+
- **Automated (headless)** — put `{ "email", "password", "mfaSecret" }` in
|
|
161
|
+
`~/.config/opencode-copilot/secrets.json`. `mfaSecret` is the **base32 seed** your
|
|
162
|
+
authenticator derives codes from (`JBSWY3DPEHPK3PXP`), not a 6-digit code. Most password
|
|
163
|
+
managers will show it; an `otpauth://` URI is accepted and the seed extracted.
|
|
164
|
+
- **Interactive** — `opencode-m365 login --interactive` opens a window and you complete
|
|
165
|
+
SSO/MFA by hand once. Required for tenants with push-only MFA, FIDO2, or a federated IdP
|
|
166
|
+
(Okta/Ping/Duo), where no seed exists to extract.
|
|
167
|
+
|
|
168
|
+
Either way it is one-time; afterwards tokens refresh from the MSAL cache.
|
|
169
|
+
|
|
170
|
+
The client id is Microsoft's own Office web Copilot application. That is not a shortcut —
|
|
171
|
+
the Sydney scopes are granted to no other client, so a loopback redirect is rejected
|
|
172
|
+
(`AADSTS50011`) and the device-code grant demands a client secret only Microsoft holds
|
|
173
|
+
(`AADSTS7000218`). Driving a browser is the only door.
|
|
174
|
+
|
|
175
|
+
State lives in `~/.config/opencode-copilot/` — deliberately not `~/.config/opencode-m365/`,
|
|
176
|
+
which belongs to the m365-copilot-proxy project.
|
|
177
|
+
|
|
178
|
+
## CLI
|
|
179
|
+
|
|
180
|
+
```sh
|
|
181
|
+
opencode-m365 login [--interactive] # sign in
|
|
182
|
+
opencode-m365 setup [--local] # register the plugin with opencode
|
|
183
|
+
opencode-m365 serve [--port 4141] # run the proxy standalone, for any OpenAI client
|
|
184
|
+
opencode-m365 doctor # check auth, agent, proxy and opencode wiring
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
## Limits
|
|
188
|
+
|
|
189
|
+
- **600 user messages per conversation.** The proxy reuses one conversation per task and
|
|
190
|
+
sends only new messages, and reports the remaining budget in
|
|
191
|
+
`usage.x_m365_conversation_remaining`.
|
|
192
|
+
- **Account-level throttling** exists and is keyed to your identity, so re-authenticating
|
|
193
|
+
does not clear it. It self-heals after a lull.
|
|
194
|
+
- **Streaming** works for tool-less turns. A tool turn is buffered, because a fenced call
|
|
195
|
+
cannot be parsed until the fence closes.
|
|
196
|
+
- **Tool calling is emulated**, not native, and one call per turn is kept by default —
|
|
197
|
+
M365 batches its whole plan into one response, and later steps run on guessed state.
|
|
198
|
+
- `usage` reports zero tokens. M365 never exposes token counts; the `x_m365_*` extension
|
|
199
|
+
fields carry what it does report, including `x_m365_dea_score`, the classifier score
|
|
200
|
+
that rises before the Disengaged filter fires.
|
|
201
|
+
|
|
202
|
+
## Development
|
|
203
|
+
|
|
204
|
+
```sh
|
|
205
|
+
pnpm install
|
|
206
|
+
pnpm test # 237 tests, no network and no credentials required
|
|
207
|
+
pnpm typecheck
|
|
208
|
+
pnpm build
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
Tests run against a stub SignalR server (`test/stub-copilot.ts`) that speaks the real
|
|
212
|
+
framing, so a full turn — including the mandatory `Metrics` frame, ping handling,
|
|
213
|
+
Disengaged detection and the stop-on-abort frame — is exercised offline.
|
|
214
|
+
|
|
215
|
+
**No live M365 traffic has been run against this implementation.** Everything above about
|
|
216
|
+
opencode's behaviour is measured; everything about M365's behaviour is implemented from
|
|
217
|
+
the protocol notes in
|
|
218
|
+
[cramt/m365-copilot-proxy](https://github.com/cramt/m365-copilot-proxy) (MIT), whose
|
|
219
|
+
`docs/` are the source of truth for this surface. Run `opencode-m365 doctor` against your
|
|
220
|
+
own tenant before trusting it.
|
|
221
|
+
|
|
222
|
+
## Credit
|
|
223
|
+
|
|
224
|
+
The protocol this implements was reverse-engineered by
|
|
225
|
+
[cramt/m365-copilot-proxy](https://github.com/cramt/m365-copilot-proxy). This is an
|
|
226
|
+
independent implementation written against that project's documentation, not a fork of
|
|
227
|
+
its code.
|
|
228
|
+
|
|
229
|
+
## Licence
|
|
230
|
+
|
|
231
|
+
MIT. This speaks to Microsoft's API with your own credentials on your own account —
|
|
232
|
+
whether that is acceptable is between you and your tenant's acceptable-use policy.
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { _ as createLogger, d as POWERPLATFORM_SCOPE, l as BAP_SCOPE, v as AGENT_FILE } from "./server-CeGQPDdE.mjs";
|
|
2
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
//#region src/agent.ts
|
|
6
|
+
/**
|
|
7
|
+
* The Copilot Studio declarative agent.
|
|
8
|
+
*
|
|
9
|
+
* This is the lever that makes tool calling work at all. Microsoft's server-side
|
|
10
|
+
* BizChat prompt sits above ours and defines the model as a retrieval chat assistant,
|
|
11
|
+
* so per-request instructions to "emit a tool call" get answered in prose or
|
|
12
|
+
* meta-analysed away. Instructions delivered through a declarative agent land in the
|
|
13
|
+
* *server-side* system prompt instead, and the model obeys them.
|
|
14
|
+
*
|
|
15
|
+
* Two design constraints shape everything here:
|
|
16
|
+
*
|
|
17
|
+
* 1. **Instructions are baked in at creation** — the update API needs a change token
|
|
18
|
+
* only returned by create. So the agent is versioned by *name*: a short hash of
|
|
19
|
+
* the instructions. Change the instructions and the next request provisions a new
|
|
20
|
+
* agent.
|
|
21
|
+
* 2. **Nothing is ever deleted.** Another host on the same tenant may be mid
|
|
22
|
+
* conversation with an agent we consider stale, and pulling it out from under them
|
|
23
|
+
* produces an instant empty reply that looks exactly like rate limiting. A few
|
|
24
|
+
* orphaned lightweight bots are the cheaper problem.
|
|
25
|
+
*
|
|
26
|
+
* Hosts sharing a tenant derive the same name from the same instructions, so they
|
|
27
|
+
* converge on one agent with no coordination.
|
|
28
|
+
*/
|
|
29
|
+
const log = createLogger("agent");
|
|
30
|
+
const BAP_ENVIRONMENT_URL = "https://api.bap.microsoft.com/providers/Microsoft.BusinessAppPlatform/environments/~default?api-version=2023-06-01";
|
|
31
|
+
const COPILOT_STUDIO_API_VERSION = "2022-03-01-preview";
|
|
32
|
+
/**
|
|
33
|
+
* The agent's server-side instructions.
|
|
34
|
+
*
|
|
35
|
+
* Kept short and purely about *format*. Heavy behavioural framing here backfired
|
|
36
|
+
* badly in the reference project's measurements — it suppressed tool calls to zero.
|
|
37
|
+
* Behaviour (first-move framing, anti-confabulation) lives in the per-request
|
|
38
|
+
* `<tools>` block, where changing it does not cost a re-provision.
|
|
39
|
+
*/
|
|
40
|
+
function agentInstructions() {
|
|
41
|
+
return [
|
|
42
|
+
"You help with software tasks in a real workspace.",
|
|
43
|
+
"",
|
|
44
|
+
"When a request lists tools, act by writing a fenced code block whose info string is the tool name.",
|
|
45
|
+
"Argument lines of the form `name: value` come first, and any free-form content is the body of the block.",
|
|
46
|
+
"An edit is written as a SEARCH/REPLACE diff inside the block.",
|
|
47
|
+
"",
|
|
48
|
+
"A fenced block of that shape is executed for you, and its result comes back before you continue.",
|
|
49
|
+
"Write one block at a time and wait for the result before deciding the next step."
|
|
50
|
+
].join("\n");
|
|
51
|
+
}
|
|
52
|
+
/** `m365-tool-agent-<8 hex>` — the same instructions always yield the same name. */
|
|
53
|
+
function agentNameFor(instructions) {
|
|
54
|
+
return `m365-tool-agent-${createHash("sha256").update(instructions).digest("hex").slice(0, 8)}`;
|
|
55
|
+
}
|
|
56
|
+
/** The id M365 expects in `threadLevelGptId` / `gpts`. */
|
|
57
|
+
function buildAgentId(titleId, botId) {
|
|
58
|
+
return `T_${titleId}.${botId}.gpt.default`;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Power Platform hosts to try for this environment.
|
|
62
|
+
*
|
|
63
|
+
* The obvious full-length label frequently does not resolve; the host that works has
|
|
64
|
+
* the last two characters trimmed. Rather than pick one, probe both.
|
|
65
|
+
*/
|
|
66
|
+
function environmentHostCandidates(envId) {
|
|
67
|
+
const suffix = "df.environment.api.powerplatform.com";
|
|
68
|
+
return [
|
|
69
|
+
`default${envId}.${suffix}`,
|
|
70
|
+
`default${envId.slice(0, -1)}.${suffix}`,
|
|
71
|
+
`default${envId.slice(0, -2)}.${suffix}`
|
|
72
|
+
];
|
|
73
|
+
}
|
|
74
|
+
/** First candidate host that actually resolves. */
|
|
75
|
+
async function resolveEnvironmentHost(envId, resolveDns, override) {
|
|
76
|
+
if (override) return override;
|
|
77
|
+
for (const candidate of environmentHostCandidates(envId)) if (await resolveDns(candidate)) return candidate;
|
|
78
|
+
throw new Error(`Could not resolve a Power Platform host for environment ${envId}. Set M365_POWERPLATFORM_HOST to override.`);
|
|
79
|
+
}
|
|
80
|
+
/** Default resolver: a DNS lookup, treating any failure as "does not resolve". */
|
|
81
|
+
const dnsResolver = async (host) => {
|
|
82
|
+
try {
|
|
83
|
+
const { lookup } = await import("node:dns/promises");
|
|
84
|
+
await lookup(host);
|
|
85
|
+
return true;
|
|
86
|
+
} catch {
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* Resolve the declarative agent id, provisioning one if the tenant has none.
|
|
92
|
+
*
|
|
93
|
+
* Order: local cache → the tenant's existing bots → create + publish.
|
|
94
|
+
*/
|
|
95
|
+
async function getOrCreateAgent(deps) {
|
|
96
|
+
const cacheFile = deps.cacheFile ?? AGENT_FILE;
|
|
97
|
+
const wantedName = agentNameFor(agentInstructions());
|
|
98
|
+
const cached = readCache(cacheFile);
|
|
99
|
+
if (cached?.instructionsHash === wantedName && cached.agentId) {
|
|
100
|
+
log.info("using cached agent", cached.agentId);
|
|
101
|
+
return cached.agentId;
|
|
102
|
+
}
|
|
103
|
+
const doFetch = deps.fetch ?? globalThis.fetch;
|
|
104
|
+
const resolveDns = deps.resolveDns ?? dnsResolver;
|
|
105
|
+
const host = await resolveEnvironmentHost(await discoverEnvironmentId(doFetch, deps.getTokenForScope), resolveDns, deps.hostOverride ?? process.env.M365_POWERPLATFORM_HOST);
|
|
106
|
+
const token = await deps.getTokenForScope([POWERPLATFORM_SCOPE]);
|
|
107
|
+
const existing = await findBot(doFetch, host, token, wantedName);
|
|
108
|
+
if (existing) {
|
|
109
|
+
const agentId = buildAgentId(existing.titleId, existing.botId);
|
|
110
|
+
writeCache(cacheFile, {
|
|
111
|
+
agentId,
|
|
112
|
+
instructionsHash: wantedName
|
|
113
|
+
});
|
|
114
|
+
log.info("reusing existing agent", agentId);
|
|
115
|
+
return agentId;
|
|
116
|
+
}
|
|
117
|
+
const botId = await createBot(doFetch, host, token, wantedName);
|
|
118
|
+
const agentId = buildAgentId(await publishBot(doFetch, host, token, botId), botId);
|
|
119
|
+
writeCache(cacheFile, {
|
|
120
|
+
agentId,
|
|
121
|
+
instructionsHash: wantedName
|
|
122
|
+
});
|
|
123
|
+
log.info("provisioned agent", agentId);
|
|
124
|
+
return agentId;
|
|
125
|
+
}
|
|
126
|
+
/** The environment id: the tenant GUID from BAP, dashes stripped. */
|
|
127
|
+
async function discoverEnvironmentId(doFetch, getTokenForScope) {
|
|
128
|
+
const token = await getTokenForScope([BAP_SCOPE]);
|
|
129
|
+
const response = await doFetch(BAP_ENVIRONMENT_URL, { headers: { Authorization: `Bearer ${token}` } });
|
|
130
|
+
if (!response.ok) throw new Error(await describeFailure("environment discovery", response));
|
|
131
|
+
const name = (await response.json())?.name ?? "";
|
|
132
|
+
const guid = name.replace(/^Default-/i, "");
|
|
133
|
+
if (!guid) throw new Error(`Power Platform returned an unexpected environment name: ${JSON.stringify(name)}`);
|
|
134
|
+
return guid.replace(/-/g, "");
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Find a bot by name.
|
|
138
|
+
*
|
|
139
|
+
* Name lookup is reliable because Copilot Studio reflects the display name we set
|
|
140
|
+
* into `shortBotName` byte for byte — hyphens, length and case all survive.
|
|
141
|
+
*/
|
|
142
|
+
async function findBot(doFetch, host, token, name) {
|
|
143
|
+
const response = await doFetch(`https://${host}/copilotstudio/minimalBots/api/botlist?api-version=${COPILOT_STUDIO_API_VERSION}`, { headers: { Authorization: `Bearer ${token}` } });
|
|
144
|
+
if (!response.ok) throw new Error(await describeFailure("listing agents", response));
|
|
145
|
+
const body = await response.json();
|
|
146
|
+
const match = (body?.value ?? body?.bots ?? []).find((bot) => bot?.shortBotName === name || bot?.displayName === name);
|
|
147
|
+
if (!match) return void 0;
|
|
148
|
+
if (!match.titleId || !match.botId) return void 0;
|
|
149
|
+
return {
|
|
150
|
+
botId: match.botId,
|
|
151
|
+
titleId: match.titleId
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
async function createBot(doFetch, host, token, name) {
|
|
155
|
+
const response = await doFetch(`https://${host}/copilotstudio/minimalBots/api?api-version=${COPILOT_STUDIO_API_VERSION}`, {
|
|
156
|
+
method: "POST",
|
|
157
|
+
headers: {
|
|
158
|
+
Authorization: `Bearer ${token}`,
|
|
159
|
+
"Content-Type": "application/json"
|
|
160
|
+
},
|
|
161
|
+
body: JSON.stringify({
|
|
162
|
+
displayName: name,
|
|
163
|
+
description: "Tool-calling format instructions for an OpenAI-compatible bridge.",
|
|
164
|
+
gptComponent: {
|
|
165
|
+
instructions: agentInstructions(),
|
|
166
|
+
conversationStarters: [],
|
|
167
|
+
aISettings: { useModelKnowledge: true }
|
|
168
|
+
}
|
|
169
|
+
})
|
|
170
|
+
});
|
|
171
|
+
if (!response.ok) throw new Error(await describeFailure("creating the agent", response));
|
|
172
|
+
const body = await response.json();
|
|
173
|
+
const botId = body?.botId ?? body?.id;
|
|
174
|
+
if (!botId) throw new Error("Copilot Studio created an agent but returned no bot id");
|
|
175
|
+
return botId;
|
|
176
|
+
}
|
|
177
|
+
async function publishBot(doFetch, host, token, botId) {
|
|
178
|
+
const response = await doFetch(`https://${host}/copilotstudio/minimalBots/api/publish?api-version=${COPILOT_STUDIO_API_VERSION}&botId=${encodeURIComponent(botId)}`, {
|
|
179
|
+
method: "POST",
|
|
180
|
+
headers: {
|
|
181
|
+
Authorization: `Bearer ${token}`,
|
|
182
|
+
"Content-Type": "application/json"
|
|
183
|
+
},
|
|
184
|
+
body: JSON.stringify({ botId })
|
|
185
|
+
});
|
|
186
|
+
if (!response.ok) throw new Error(await describeFailure("publishing the agent", response));
|
|
187
|
+
const body = await response.json();
|
|
188
|
+
const titleId = body?.titleId ?? body?.TitleId;
|
|
189
|
+
if (!titleId) throw new Error("Copilot Studio published the agent but returned no title id");
|
|
190
|
+
return titleId;
|
|
191
|
+
}
|
|
192
|
+
async function describeFailure(what, response) {
|
|
193
|
+
let detail = "";
|
|
194
|
+
try {
|
|
195
|
+
detail = await response.text?.() ?? "";
|
|
196
|
+
} catch {}
|
|
197
|
+
const hint = response.status === 401 || response.status === 403 ? " — this usually means the account lacks Copilot Studio / Power Platform access" : "";
|
|
198
|
+
return `M365 rejected ${what} (HTTP ${response.status})${hint}${detail ? `: ${detail.slice(0, 300)}` : ""}`;
|
|
199
|
+
}
|
|
200
|
+
function readCache(file) {
|
|
201
|
+
try {
|
|
202
|
+
const parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
203
|
+
if (parsed && typeof parsed.agentId === "string") return parsed;
|
|
204
|
+
} catch {}
|
|
205
|
+
}
|
|
206
|
+
function writeCache(file, cache) {
|
|
207
|
+
try {
|
|
208
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
209
|
+
writeFileSync(file, `${JSON.stringify(cache, null, 2)}\n`);
|
|
210
|
+
} catch (error) {
|
|
211
|
+
log.warn("could not write the agent cache", String(error));
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
//#endregion
|
|
215
|
+
export { getOrCreateAgent as t };
|
package/dist/cli.d.mts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {}
|
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { b as CONFIG_DIR, g as createTokenClient, i as mergeOpencodeConfig, n as PROVIDER_ID, o as DEFAULT_MODEL, s as LOCAL_TITLE_MODEL, t as startServer, v as AGENT_FILE, x as SECRETS_FILE, y as CACHE_FILE } from "./server-CeGQPDdE.mjs";
|
|
3
|
+
import { t as getOrCreateAgent } from "./agent-t3MgztgU.mjs";
|
|
4
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { dirname, join, resolve } from "node:path";
|
|
6
|
+
import { homedir } from "node:os";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
//#region src/cli.ts
|
|
9
|
+
/**
|
|
10
|
+
* `opencode-m365` — sign in, wire up opencode, and check the plumbing.
|
|
11
|
+
*
|
|
12
|
+
* The plugin can do everything except sign in, because signing in means opening a
|
|
13
|
+
* browser and a plugin running under a TUI must not do that. This is where that
|
|
14
|
+
* happens, plus the one-time config write.
|
|
15
|
+
*/
|
|
16
|
+
const OPENCODE_CONFIG = join(homedir(), ".config", "opencode", "opencode.json");
|
|
17
|
+
async function main() {
|
|
18
|
+
const [command = "help", ...rest] = process.argv.slice(2);
|
|
19
|
+
switch (command) {
|
|
20
|
+
case "login": return doLogin(rest);
|
|
21
|
+
case "setup": return doSetup(rest);
|
|
22
|
+
case "serve": return doServe(rest);
|
|
23
|
+
case "doctor": return doDoctor();
|
|
24
|
+
case "help":
|
|
25
|
+
case "--help":
|
|
26
|
+
case "-h": return printHelp();
|
|
27
|
+
default:
|
|
28
|
+
console.error(`Unknown command: ${command}\n`);
|
|
29
|
+
printHelp();
|
|
30
|
+
process.exitCode = 1;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function printHelp() {
|
|
34
|
+
console.log(`opencode-m365 — use Microsoft 365 Copilot as opencode's model backend
|
|
35
|
+
|
|
36
|
+
login [--interactive] Sign in to Microsoft 365 and store the token cache
|
|
37
|
+
setup [--local] Add the plugin to ~/.config/opencode/opencode.json
|
|
38
|
+
serve [--port <n>] Run the OpenAI-compatible proxy standalone
|
|
39
|
+
doctor Check auth, the agent, and the proxy
|
|
40
|
+
|
|
41
|
+
Config lives in ${CONFIG_DIR}
|
|
42
|
+
|
|
43
|
+
Sign-in needs either a TOTP seed in secrets.json (headless), or --interactive
|
|
44
|
+
to complete SSO/MFA by hand once — the only option on tenants with push-only
|
|
45
|
+
MFA, FIDO2, or a federated IdP.`);
|
|
46
|
+
}
|
|
47
|
+
async function doLogin(args) {
|
|
48
|
+
const { login } = await import("./login-Dj9Ss7K_.mjs");
|
|
49
|
+
const interactive = args.includes("--interactive");
|
|
50
|
+
try {
|
|
51
|
+
const account = await login({
|
|
52
|
+
interactive,
|
|
53
|
+
onStatus: (message) => console.log(` ${message}`)
|
|
54
|
+
});
|
|
55
|
+
console.log(`\nSigned in as ${account}.`);
|
|
56
|
+
console.log(`Token cache written to ${CACHE_FILE}`);
|
|
57
|
+
console.log("\nNext: opencode-m365 setup");
|
|
58
|
+
} catch (error) {
|
|
59
|
+
console.error(`\nSign-in failed: ${error.message}`);
|
|
60
|
+
if (!interactive) {
|
|
61
|
+
console.error("\nIf your tenant has no TOTP option (push-only MFA, FIDO2, Okta/Ping/Duo),");
|
|
62
|
+
console.error("try: opencode-m365 login --interactive");
|
|
63
|
+
}
|
|
64
|
+
process.exitCode = 1;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
async function doSetup(args) {
|
|
68
|
+
const local = args.includes("--local");
|
|
69
|
+
const pluginRef = local ? resolve(dirname(fileURLToPath(import.meta.url)), "plugin.mjs") : "opencode-m365-copilot";
|
|
70
|
+
if (local && !existsSync(pluginRef)) {
|
|
71
|
+
console.error(`No build at ${pluginRef}. Run \`pnpm build\` first.`);
|
|
72
|
+
process.exitCode = 1;
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
let existing = {};
|
|
76
|
+
if (existsSync(OPENCODE_CONFIG)) try {
|
|
77
|
+
existing = JSON.parse(readFileSync(OPENCODE_CONFIG, "utf8"));
|
|
78
|
+
} catch (error) {
|
|
79
|
+
console.error(`${OPENCODE_CONFIG} is not valid JSON — fix or move it first.\n ${String(error)}`);
|
|
80
|
+
process.exitCode = 1;
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
const merged = mergeOpencodeConfig(existing, { pluginRef });
|
|
84
|
+
mkdirSync(dirname(OPENCODE_CONFIG), { recursive: true });
|
|
85
|
+
writeFileSync(OPENCODE_CONFIG, `${JSON.stringify(merged, null, 2)}\n`);
|
|
86
|
+
console.log(`Added ${pluginRef} to ${OPENCODE_CONFIG}`);
|
|
87
|
+
console.log(`\nThe plugin registers the provider itself on startup, so there is nothing`);
|
|
88
|
+
console.log(`else to configure. Models appear as ${PROVIDER_ID}/<model>, defaulting to`);
|
|
89
|
+
console.log(`${PROVIDER_ID}/${DEFAULT_MODEL}.`);
|
|
90
|
+
console.log(`\nNote: it also trims opencode's toolset when an ${PROVIDER_ID} model is`);
|
|
91
|
+
console.log(`selected. M365 refuses to engage with a full coding-agent toolset — see the`);
|
|
92
|
+
console.log(`README. Pass { "lean": false } in the plugin options to opt out.`);
|
|
93
|
+
console.log(`\nCheck it with: opencode models | grep ${PROVIDER_ID}`);
|
|
94
|
+
}
|
|
95
|
+
async function doServe(args) {
|
|
96
|
+
const portIndex = args.indexOf("--port");
|
|
97
|
+
const port = portIndex >= 0 ? Number(args[portIndex + 1]) : 4141;
|
|
98
|
+
const tokens = createTokenClient();
|
|
99
|
+
const proxy = await startServer({
|
|
100
|
+
getToken: () => tokens.getToken(),
|
|
101
|
+
resolveAgent: () => getOrCreateAgent({ getTokenForScope: (scopes) => tokens.getTokenForScope(scopes) }),
|
|
102
|
+
port
|
|
103
|
+
});
|
|
104
|
+
console.log(`M365 Copilot proxy listening on ${proxy.url}`);
|
|
105
|
+
console.log(` models: ${proxy.url}/v1/models`);
|
|
106
|
+
console.log(` completions: ${proxy.url}/v1/chat/completions`);
|
|
107
|
+
console.log("\nUnauthenticated and loopback-only. Ctrl+C to stop.");
|
|
108
|
+
process.on("SIGINT", () => {
|
|
109
|
+
proxy.close().then(() => process.exit(0));
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
async function doDoctor() {
|
|
113
|
+
let failures = 0;
|
|
114
|
+
const check = (label, ok, detail = "") => {
|
|
115
|
+
console.log(` ${ok ? "ok " : "FAIL"} ${label}${detail ? ` — ${detail}` : ""}`);
|
|
116
|
+
if (!ok) failures += 1;
|
|
117
|
+
};
|
|
118
|
+
console.log("Config");
|
|
119
|
+
check("config directory", existsSync(CONFIG_DIR), CONFIG_DIR);
|
|
120
|
+
check("token cache", existsSync(CACHE_FILE), existsSync(CACHE_FILE) ? CACHE_FILE : "run `opencode-m365 login`");
|
|
121
|
+
console.log(` .. stored credentials — ${existsSync(SECRETS_FILE) ? "present" : "absent (interactive login only)"}`);
|
|
122
|
+
console.log("\nAuthentication");
|
|
123
|
+
const tokens = createTokenClient();
|
|
124
|
+
let signedIn = false;
|
|
125
|
+
try {
|
|
126
|
+
const token = await tokens.getToken();
|
|
127
|
+
signedIn = true;
|
|
128
|
+
check("chat token", true, `${token.length} chars`);
|
|
129
|
+
} catch (error) {
|
|
130
|
+
check("chat token", false, error.message);
|
|
131
|
+
}
|
|
132
|
+
console.log("\nDeclarative agent");
|
|
133
|
+
if (!signedIn) console.log(" skip needs a signed-in account");
|
|
134
|
+
else try {
|
|
135
|
+
check("agent", true, await getOrCreateAgent({ getTokenForScope: (scopes) => tokens.getTokenForScope(scopes) }));
|
|
136
|
+
} catch (error) {
|
|
137
|
+
console.log(` warn agent unavailable — ${error.message}`);
|
|
138
|
+
console.log(" Tool calling will be markedly less reliable without it.");
|
|
139
|
+
}
|
|
140
|
+
console.log(` .. cache — ${existsSync(AGENT_FILE) ? AGENT_FILE : "not yet provisioned"}`);
|
|
141
|
+
console.log("\nProxy");
|
|
142
|
+
try {
|
|
143
|
+
const proxy = await startServer({
|
|
144
|
+
getToken: () => tokens.getToken(),
|
|
145
|
+
port: 0
|
|
146
|
+
});
|
|
147
|
+
check("starts and serves /health", (await fetch(`${proxy.url}/health`)).ok, proxy.url);
|
|
148
|
+
const models = await (await fetch(`${proxy.url}/v1/models`)).json();
|
|
149
|
+
check("advertises models", models.data?.length > 0, `${models.data?.length ?? 0} models`);
|
|
150
|
+
check("local titler present", models.data?.some((m) => m.id === LOCAL_TITLE_MODEL));
|
|
151
|
+
await proxy.close();
|
|
152
|
+
} catch (error) {
|
|
153
|
+
check("starts", false, error.message);
|
|
154
|
+
}
|
|
155
|
+
console.log("\nopencode");
|
|
156
|
+
const configured = existsSync(OPENCODE_CONFIG) && readFileSync(OPENCODE_CONFIG, "utf8").includes("m365");
|
|
157
|
+
check("plugin registered", configured, configured ? OPENCODE_CONFIG : "run `opencode-m365 setup`");
|
|
158
|
+
process.exitCode = failures > 0 ? 1 : 0;
|
|
159
|
+
}
|
|
160
|
+
main().catch((error) => {
|
|
161
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
162
|
+
process.exit(1);
|
|
163
|
+
});
|
|
164
|
+
//#endregion
|
|
165
|
+
export {};
|