opencode-m365-copilot 0.2.2 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -31,6 +31,9 @@ opencode # models appear as m365/*
31
31
  `setup` writes only a plugin reference. The provider, the model list, the default model
32
32
  and the small model are all registered by the plugin at startup.
33
33
 
34
+ Works on **opencode 1 and opencode 2** from the one install — see
35
+ [opencode 2](#opencode-2) for what differs.
36
+
34
37
  ## The thing you need to know first
35
38
 
36
39
  **M365 refuses to work with a full coding-agent toolset.** Its "Disengaged" filter
@@ -111,6 +114,45 @@ deleted — another host may be mid-conversation with it.
111
114
  Without Copilot Studio access the plugin still works, just less reliably; it logs a
112
115
  warning and carries on.
113
116
 
117
+ ## opencode 2
118
+
119
+ opencode 2 is a separate package family (`@opencode/cli`, `@opencode/plugin`) with a
120
+ different plugin API. This package serves both from a single default export: opencode 1
121
+ calls its `server()`, opencode 2 calls its `setup()`. There is nothing to choose and no
122
+ second install.
123
+
124
+ What differs, and why:
125
+
126
+ | | opencode 1 | opencode 2 |
127
+ |---|---|---|
128
+ | config key | `plugin` | `plugins` |
129
+ | entry form | `[spec, options]` | `{ package, options }` |
130
+ | local reference | the built entrypoint | **a directory** — 2.0.11 drops a file path with `configured plugin path must be a directory`, and since it swallows plugin load failures, nothing else tells you |
131
+ | provider registration | `config.provider.m365` | `ctx.provider.transform` → `editor.add` |
132
+ | openai-compatible driver | installs `@ai-sdk/openai-compatible` | bundled as `@opencode/ai/providers/openai-compatible` |
133
+ | title generation | `small_model` | no such setting — see below |
134
+
135
+ `opencode-m365 setup` writes **both** keys, with the right reference for each. Each
136
+ version silently drops the key it does not know, so the one file serves either.
137
+
138
+ Everything in [Where the trimming happens](#where-the-trimming-happens-and-why) is
139
+ unchanged, because it all lives in the proxy. opencode 2 does offer working equivalents
140
+ for the two dead v1 hooks (`ctx.tool.transform`, `session.hook("context")`); neither has
141
+ been measured against a live tenant, so the proxy stays the enforcement point.
142
+
143
+ ### Verified how far
144
+
145
+ The opencode 1 path is verified end to end against a real 1.18.31: the plugin loads, the
146
+ provider registers with all 21 models, and the default and small models are set. The
147
+ dual entry shape is also asserted against decompiled loader logic from 1.18.0, 1.18.18,
148
+ 1.18.28 and 1.18.31 in `src/plugin-entry.test.ts` — opencode's docs say the object entry
149
+ form arrived in 1.18.29, but 1.18.0 already has the identical detect path, so the peer
150
+ floor did not move.
151
+
152
+ The opencode 2 path is covered by unit tests against a stand-in context, and its catalog
153
+ records are checked against the real `@opencode/plugin` schema constructors. It has
154
+ **not** yet been exercised against a live opencode 2 end to end.
155
+
114
156
  ## Configuration
115
157
 
116
158
  ```jsonc
@@ -120,11 +162,19 @@ warning and carries on.
120
162
  "leanSystemPrompt": false, // replace opencode's prose prompt (default: false)
121
163
  "setDefaultModel": true, // set `model` if you have not (default: true)
122
164
  "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
165
+ "baseUrl": null, // use an already-running proxy instead of an in-process one
166
+ "apiKey": null // that proxy's secret (or export M365_PROXY_KEY instead)
124
167
  }]]
125
168
  }
126
169
  ```
127
170
 
171
+ The in-process proxy needs no key configured: it mints a random secret each launch and
172
+ hands it to opencode itself. Only a standalone `opencode-m365 serve` proxy needs one —
173
+ `serve` prints its key, or takes a fixed one from `M365_PROXY_KEY`. Either put that key
174
+ in `apiKey`, or export the same `M365_PROXY_KEY` to opencode and leave `apiKey` out.
175
+
176
+ On opencode 2 the same block goes under `plugins`, as `{ "package": ..., "options": ... }`.
177
+
128
178
  ### Why `small_model` is redirected
129
179
 
130
180
  opencode's `small_model` defaults to your main model, so every new session would generate
@@ -132,6 +182,12 @@ its title on M365 — opening a **second conversation**. The account-level throt
132
182
  conversations started, not messages, so that is the fastest way to get throttled. The
133
183
  `m365/local-title` model is answered by the proxy itself and never opens a connection.
134
184
 
185
+ opencode 2 has no `small_model`, and its title hook exposes the model read-only, so the
186
+ same guarantee is reached differently: the plugin marks the title request on a header
187
+ (`x-m365-request-kind: title`) and the proxy answers it locally. Compaction and
188
+ generation are left on the real model — they are real work, and only titling opens the
189
+ extra conversation. `setSmallModel` controls both mechanisms.
190
+
135
191
  ## Models
136
192
 
137
193
  Models are selected by an M365 *tone*, not a model id. `m365/gpt-5.5-think-deeper` is the
@@ -161,6 +217,10 @@ Two ways to sign in:
161
217
  `~/.config/opencode-copilot/secrets.json`. `mfaSecret` is the **base32 seed** your
162
218
  authenticator derives codes from (`JBSWY3DPEHPK3PXP`), not a 6-digit code. Most password
163
219
  managers will show it; an `otpauth://` URI is accepted and the seed extracted.
220
+ That file holds **both** sign-in factors — anyone who can read it can pass MFA as you —
221
+ so keep it `chmod 600` (the CLI tightens a looser file itself and warns), keep it off
222
+ backups and synced folders, and prefer interactive sign-in if you can. It is only read
223
+ by `opencode-m365 login`; you can delete it once you have signed in.
164
224
  - **Interactive** — `opencode-m365 login --interactive` opens a window and you complete
165
225
  SSO/MFA by hand once. Required for tenants with push-only MFA, FIDO2, or a federated IdP
166
226
  (Okta/Ping/Duo), where no seed exists to extract.
@@ -181,14 +241,17 @@ which belongs to the m365-copilot-proxy project.
181
241
  opencode-m365 login [--interactive] # sign in
182
242
  opencode-m365 setup [--local] # register the plugin with opencode
183
243
  opencode-m365 serve [--port 4141] # run the proxy standalone, for any OpenAI client
244
+ # (send its key as `Authorization: Bearer`)
184
245
  opencode-m365 doctor # check auth, agent, proxy and opencode wiring
185
246
  ```
186
247
 
187
248
  ## Limits
188
249
 
189
- - **600 user messages per conversation.** The proxy reuses one conversation per task and
250
+ - **600 user messages per conversation.** The proxy reuses one conversation per task,
190
251
  sends only new messages, and reports the remaining budget in
191
- `usage.x_m365_conversation_remaining`.
252
+ `usage.x_m365_conversation_remaining`. A task is the opencode session on opencode 2,
253
+ or the system prompt plus the first user message otherwise; turns within one task run
254
+ one at a time.
192
255
  - **Account-level throttling** exists and is keyed to your identity, so re-authenticating
193
256
  does not clear it. It self-heals after a lull.
194
257
  - **Streaming** works for tool-less turns. A tool turn is buffered, because a fenced call
@@ -1,7 +1,6 @@
1
- import { b as AGENT_FILE, d as BAP_SCOPE, p as POWERPLATFORM_SCOPE, y as createLogger } from "./server-B_2RPeJD.mjs";
2
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
- import { dirname } from "node:path";
1
+ import { _ as createLogger, b as AGENT_FILE, d as POWERPLATFORM_SCOPE, l as BAP_SCOPE, y as writePrivateFile } from "./server-DO0_u884.mjs";
4
2
  import { createHash } from "node:crypto";
3
+ import { readFileSync } from "node:fs";
5
4
  //#region src/agent.ts
6
5
  /**
7
6
  * The Copilot Studio declarative agent.
@@ -205,8 +204,7 @@ function readCache(file) {
205
204
  }
206
205
  function writeCache(file, cache) {
207
206
  try {
208
- mkdirSync(dirname(file), { recursive: true });
209
- writeFileSync(file, `${JSON.stringify(cache, null, 2)}\n`);
207
+ writePrivateFile(file, `${JSON.stringify(cache, null, 2)}\n`);
210
208
  } catch (error) {
211
209
  log.warn("could not write the agent cache", String(error));
212
210
  }
package/dist/cli.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
- import { C as SECRETS_FILE, S as CONFIG_DIR, b as AGENT_FILE, c as DEFAULT_MODEL, i as PROVIDER_ID, l as LOCAL_TITLE_MODEL, o as mergeOpencodeConfig, t as startServer, v as createTokenClient, x as CACHE_FILE } from "./server-B_2RPeJD.mjs";
3
- import { t as getOrCreateAgent } from "./agent-BXH7KR-e.mjs";
4
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
- import { dirname, join, resolve } from "node:path";
2
+ import { C as SECRETS_FILE, M as LOCAL_TITLE_MODEL, S as CONFIG_DIR, T as PROVIDER_ID, a as startServer, b as AGENT_FILE, g as createTokenClient, j as DEFAULT_MODEL, k as mergeOpencodeConfig, x as CACHE_FILE } from "./server-DO0_u884.mjs";
3
+ import { t as getOrCreateAgent } from "./agent-C3DxtJPy.mjs";
4
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
5
  import { homedir } from "node:os";
6
+ import { dirname, join, resolve } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
8
  //#region src/cli.ts
9
9
  /**
@@ -36,6 +36,7 @@ function printHelp() {
36
36
  login [--interactive] Sign in to Microsoft 365 and store the token cache
37
37
  setup [--local] Add the plugin to ~/.config/opencode/opencode.json
38
38
  serve [--port <n>] Run the OpenAI-compatible proxy standalone
39
+ (key from M365_PROXY_KEY, else printed)
39
40
  doctor Check auth, the agent, and the proxy
40
41
 
41
42
  Config lives in ${CONFIG_DIR}
@@ -45,7 +46,7 @@ to complete SSO/MFA by hand once — the only option on tenants with push-only
45
46
  MFA, FIDO2, or a federated IdP.`);
46
47
  }
47
48
  async function doLogin(args) {
48
- const { login } = await import("./login-BD6JAsn7.mjs");
49
+ const { login } = await import("./login-_9JzoRK8.mjs");
49
50
  const interactive = args.includes("--interactive");
50
51
  try {
51
52
  const account = await login({
@@ -66,7 +67,9 @@ async function doLogin(args) {
66
67
  }
67
68
  async function doSetup(args) {
68
69
  const local = args.includes("--local");
69
- const pluginRef = local ? resolve(dirname(fileURLToPath(import.meta.url)), "plugin.mjs") : "opencode-m365-copilot";
70
+ const dist = dirname(fileURLToPath(import.meta.url));
71
+ const pluginRef = local ? resolve(dist, "plugin.mjs") : "opencode-m365-copilot";
72
+ const pluginDir = local ? resolve(dist, "..") : pluginRef;
70
73
  if (local && !existsSync(pluginRef)) {
71
74
  console.error(`No build at ${pluginRef}. Run \`pnpm build\` first.`);
72
75
  process.exitCode = 1;
@@ -80,10 +83,18 @@ async function doSetup(args) {
80
83
  process.exitCode = 1;
81
84
  return;
82
85
  }
83
- const merged = mergeOpencodeConfig(existing, { pluginRef });
86
+ const merged = mergeOpencodeConfig(existing, {
87
+ pluginRef,
88
+ pluginDir,
89
+ inspect: inspectPluginPath
90
+ });
84
91
  mkdirSync(dirname(OPENCODE_CONFIG), { recursive: true });
92
+ const backup = `${OPENCODE_CONFIG}.bak`;
93
+ const hadConfig = existsSync(OPENCODE_CONFIG);
94
+ if (hadConfig) copyFileSync(OPENCODE_CONFIG, backup);
85
95
  writeFileSync(OPENCODE_CONFIG, `${JSON.stringify(merged, null, 2)}\n`);
86
96
  console.log(`Added ${pluginRef} to ${OPENCODE_CONFIG}`);
97
+ if (hadConfig) console.log(`(previous version saved as ${backup})`);
87
98
  console.log(`\nThe plugin registers the provider itself on startup, so there is nothing`);
88
99
  console.log(`else to configure. Models appear as ${PROVIDER_ID}/<model>, defaulting to`);
89
100
  console.log(`${PROVIDER_ID}/${DEFAULT_MODEL}.`);
@@ -92,19 +103,43 @@ async function doSetup(args) {
92
103
  console.log(`README. Pass { "lean": false } in the plugin options to opt out.`);
93
104
  console.log(`\nCheck it with: opencode models | grep ${PROVIDER_ID}`);
94
105
  }
106
+ /** Which package owns a local plugin path: its own dir or the one above (`dist/`). */
107
+ function inspectPluginPath(path) {
108
+ if (!existsSync(path)) return { exists: false };
109
+ const start = path.endsWith(".mjs") || path.endsWith(".js") ? dirname(path) : path;
110
+ for (const dir of [start, dirname(start)]) try {
111
+ const name = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"))?.name;
112
+ if (typeof name === "string") return {
113
+ exists: true,
114
+ packageName: name
115
+ };
116
+ } catch {}
117
+ return { exists: true };
118
+ }
95
119
  async function doServe(args) {
96
120
  const portIndex = args.indexOf("--port");
97
121
  const port = portIndex >= 0 ? Number(args[portIndex + 1]) : 4141;
98
122
  const tokens = createTokenClient();
123
+ const fixedKey = process.env.M365_PROXY_KEY || void 0;
99
124
  const proxy = await startServer({
100
125
  getToken: () => tokens.getToken(),
101
126
  resolveAgent: () => getOrCreateAgent({ getTokenForScope: (scopes) => tokens.getTokenForScope(scopes) }),
102
- port
127
+ port,
128
+ ...fixedKey ? { apiKey: fixedKey } : {}
103
129
  });
104
130
  console.log(`M365 Copilot proxy listening on ${proxy.url}`);
105
131
  console.log(` models: ${proxy.url}/v1/models`);
106
132
  console.log(` completions: ${proxy.url}/v1/chat/completions`);
107
- console.log("\nUnauthenticated and loopback-only. Ctrl+C to stop.");
133
+ console.log("\nLoopback-only. Every request must send `Authorization: Bearer <key>`;");
134
+ console.log("browser origins and CORS are refused.");
135
+ if (fixedKey) console.log(" key: from M365_PROXY_KEY");
136
+ else {
137
+ console.log(` key: ${proxy.apiKey}`);
138
+ console.log(" (new every launch — set M365_PROXY_KEY to keep one)");
139
+ }
140
+ console.log(`\nPoint the plugin here with { "baseUrl": "${proxy.url}/v1", "apiKey": "<key>" },`);
141
+ console.log("or leave apiKey out and export the same M365_PROXY_KEY to opencode.");
142
+ console.log("Ctrl+C to stop.");
108
143
  process.on("SIGINT", () => {
109
144
  proxy.close().then(() => process.exit(0));
110
145
  });
@@ -145,7 +180,8 @@ async function doDoctor() {
145
180
  port: 0
146
181
  });
147
182
  check("starts and serves /health", (await fetch(`${proxy.url}/health`)).ok, proxy.url);
148
- const models = await (await fetch(`${proxy.url}/v1/models`)).json();
183
+ check("refuses a request without the secret", (await fetch(`${proxy.url}/v1/models`)).status === 401);
184
+ const models = await (await fetch(`${proxy.url}/v1/models`, { headers: { Authorization: `Bearer ${proxy.apiKey}` } })).json();
149
185
  check("advertises models", models.data?.length > 0, `${models.data?.length ?? 0} models`);
150
186
  check("local titler present", models.data?.some((m) => m.id === LOCAL_TITLE_MODEL));
151
187
  await proxy.close();