opencode-m365-copilot 0.3.0 → 0.3.2

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
@@ -162,11 +162,17 @@ records are checked against the real `@opencode/plugin` schema constructors. It
162
162
  "leanSystemPrompt": false, // replace opencode's prose prompt (default: false)
163
163
  "setDefaultModel": true, // set `model` if you have not (default: true)
164
164
  "setSmallModel": true, // route title generation to the local titler (default: true)
165
- "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)
166
167
  }]]
167
168
  }
168
169
  ```
169
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
+
170
176
  On opencode 2 the same block goes under `plugins`, as `{ "package": ..., "options": ... }`.
171
177
 
172
178
  ### Why `small_model` is redirected
@@ -211,6 +217,10 @@ Two ways to sign in:
211
217
  `~/.config/opencode-copilot/secrets.json`. `mfaSecret` is the **base32 seed** your
212
218
  authenticator derives codes from (`JBSWY3DPEHPK3PXP`), not a 6-digit code. Most password
213
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.
214
224
  - **Interactive** — `opencode-m365 login --interactive` opens a window and you complete
215
225
  SSO/MFA by hand once. Required for tenants with push-only MFA, FIDO2, or a federated IdP
216
226
  (Okta/Ping/Duo), where no seed exists to extract.
@@ -231,14 +241,17 @@ which belongs to the m365-copilot-proxy project.
231
241
  opencode-m365 login [--interactive] # sign in
232
242
  opencode-m365 setup [--local] # register the plugin with opencode
233
243
  opencode-m365 serve [--port 4141] # run the proxy standalone, for any OpenAI client
244
+ # (send its key as `Authorization: Bearer`)
234
245
  opencode-m365 doctor # check auth, agent, proxy and opencode wiring
235
246
  ```
236
247
 
237
248
  ## Limits
238
249
 
239
- - **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,
240
251
  sends only new messages, and reports the remaining budget in
241
- `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.
242
255
  - **Account-level throttling** exists and is keyed to your identity, so re-authenticating
243
256
  does not clear it. It self-heals after a lull.
244
257
  - **Streaming** works for tool-less turns. A tool turn is buffered, because a fenced call
@@ -1,7 +1,6 @@
1
- import { c as POWERPLATFORM_SCOPE, h as AGENT_FILE, m as createLogger, o as BAP_SCOPE } from "./server-DuHBfcPQ.mjs";
1
+ import { _ as createLogger, b as AGENT_FILE, d as POWERPLATFORM_SCOPE, l as BAP_SCOPE, y as writePrivateFile } from "./server-Buz1ZIg5.mjs";
2
2
  import { createHash } from "node:crypto";
3
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
- import { dirname } from "node:path";
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 { D as LOCAL_TITLE_MODEL, E as DEFAULT_MODEL, _ as CONFIG_DIR, b as PROVIDER_ID, g as CACHE_FILE, h as AGENT_FILE, n as startServer, p as createTokenClient, v as SECRETS_FILE, w as mergeOpencodeConfig } from "./server-DuHBfcPQ.mjs";
3
- import { t as getOrCreateAgent } from "./agent-BDA00x1V.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-Buz1ZIg5.mjs";
3
+ import { t as getOrCreateAgent } from "./agent-C28PfLXM.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-Cb_rQQHO.mjs");
49
+ const { login } = await import("./login-Y2igNqfw.mjs");
49
50
  const interactive = args.includes("--interactive");
50
51
  try {
51
52
  const account = await login({
@@ -84,11 +85,16 @@ async function doSetup(args) {
84
85
  }
85
86
  const merged = mergeOpencodeConfig(existing, {
86
87
  pluginRef,
87
- pluginDir
88
+ pluginDir,
89
+ inspect: inspectPluginPath
88
90
  });
89
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);
90
95
  writeFileSync(OPENCODE_CONFIG, `${JSON.stringify(merged, null, 2)}\n`);
91
96
  console.log(`Added ${pluginRef} to ${OPENCODE_CONFIG}`);
97
+ if (hadConfig) console.log(`(previous version saved as ${backup})`);
92
98
  console.log(`\nThe plugin registers the provider itself on startup, so there is nothing`);
93
99
  console.log(`else to configure. Models appear as ${PROVIDER_ID}/<model>, defaulting to`);
94
100
  console.log(`${PROVIDER_ID}/${DEFAULT_MODEL}.`);
@@ -97,19 +103,43 @@ async function doSetup(args) {
97
103
  console.log(`README. Pass { "lean": false } in the plugin options to opt out.`);
98
104
  console.log(`\nCheck it with: opencode models | grep ${PROVIDER_ID}`);
99
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
+ }
100
119
  async function doServe(args) {
101
120
  const portIndex = args.indexOf("--port");
102
121
  const port = portIndex >= 0 ? Number(args[portIndex + 1]) : 4141;
103
122
  const tokens = createTokenClient();
123
+ const fixedKey = process.env.M365_PROXY_KEY || void 0;
104
124
  const proxy = await startServer({
105
125
  getToken: () => tokens.getToken(),
106
126
  resolveAgent: () => getOrCreateAgent({ getTokenForScope: (scopes) => tokens.getTokenForScope(scopes) }),
107
- port
127
+ port,
128
+ ...fixedKey ? { apiKey: fixedKey } : {}
108
129
  });
109
130
  console.log(`M365 Copilot proxy listening on ${proxy.url}`);
110
131
  console.log(` models: ${proxy.url}/v1/models`);
111
132
  console.log(` completions: ${proxy.url}/v1/chat/completions`);
112
- 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.");
113
143
  process.on("SIGINT", () => {
114
144
  proxy.close().then(() => process.exit(0));
115
145
  });
@@ -150,7 +180,8 @@ async function doDoctor() {
150
180
  port: 0
151
181
  });
152
182
  check("starts and serves /health", (await fetch(`${proxy.url}/health`)).ok, proxy.url);
153
- 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();
154
185
  check("advertises models", models.data?.length > 0, `${models.data?.length ?? 0} models`);
155
186
  check("local titler present", models.data?.some((m) => m.id === LOCAL_TITLE_MODEL));
156
187
  await proxy.close();