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.
@@ -1,5 +1,5 @@
1
- import { C as SECRETS_FILE, S as CONFIG_DIR, _ as createCachePlugin, f as CLIENT_ID, g as authCodeFromUrl, h as SYDNEY_SCOPES, m as REDIRECT_URI, n as object, r as string, u as AUTHORITY, y as createLogger } from "./server-B_2RPeJD.mjs";
2
- import { existsSync, mkdirSync, readFileSync } from "node:fs";
1
+ import { C as SECRETS_FILE, S as CONFIG_DIR, _ as createLogger, c as AUTHORITY, f as REDIRECT_URI, h as createCachePlugin, m as authCodeFromUrl, o as object, p as SYDNEY_SCOPES, s as string, u as CLIENT_ID, v as ensurePrivateDir } from "./server-DO0_u884.mjs";
2
+ import { chmodSync, existsSync, readFileSync, statSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  //#region src/login.ts
5
5
  /**
@@ -29,9 +29,15 @@ const SecretsSchema = object({
29
29
  */
30
30
  mfaSecret: string().optional()
31
31
  });
32
- /** Read stored credentials, if any. Returns undefined when the file is absent. */
33
- function loadSecrets(file = SECRETS_FILE) {
32
+ /**
33
+ * Read stored credentials, if any. Returns undefined when the file is absent.
34
+ *
35
+ * The file holds both sign-in factors, so a copy other local users can read is
36
+ * tightened to 0600 on the spot, with a warning. A file we cannot tighten is refused.
37
+ */
38
+ function loadSecrets(file = SECRETS_FILE, { warn = (message) => console.warn(message) } = {}) {
34
39
  if (!existsSync(file)) return void 0;
40
+ guardSecretsMode(file, warn);
35
41
  let parsed;
36
42
  try {
37
43
  parsed = JSON.parse(readFileSync(file, "utf8"));
@@ -42,6 +48,17 @@ function loadSecrets(file = SECRETS_FILE) {
42
48
  if (!result.success) throw new Error(`${file} is missing required fields: ${result.error.issues.map((i) => i.path.join(".")).join(", ")}`);
43
49
  return result.data;
44
50
  }
51
+ function guardSecretsMode(file, warn) {
52
+ if (process.platform === "win32") return;
53
+ const mode = statSync(file).mode & 511;
54
+ if ((mode & 63) === 0) return;
55
+ try {
56
+ chmodSync(file, 384);
57
+ } catch (error) {
58
+ throw new Error(`${file} is readable by other users (mode ${mode.toString(8)}) and could not be tightened: ${String(error)}. Run \`chmod 600 ${file}\`.`);
59
+ }
60
+ warn(`${file} was readable by other users (mode ${mode.toString(8)}); it holds your password and TOTP seed, so it has been changed to 0600.`);
61
+ }
45
62
  /**
46
63
  * Validate a TOTP seed before we try to use it.
47
64
  *
@@ -62,7 +79,7 @@ function normaliseTotpSecret(raw) {
62
79
  }
63
80
  /** Current 6-digit code for a base32 seed. */
64
81
  async function totpCode(secret) {
65
- const { TOTP, Secret } = await import("./otpauth.node-klD_z4Tx.mjs");
82
+ const { TOTP, Secret } = await import("./otpauth.node-CBOz_1IZ.mjs");
66
83
  return new TOTP({
67
84
  secret: Secret.fromBase32(normaliseTotpSecret(secret)),
68
85
  digits: 6,
@@ -79,7 +96,7 @@ async function login(options = {}) {
79
96
  const secrets = loadSecrets(options.secretsFile);
80
97
  const interactive = options.interactive ?? !secrets?.mfaSecret;
81
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.`);
82
- const { PublicClientApplication, CryptoProvider } = await import("./dist-JS8R_Thl.mjs");
99
+ const { PublicClientApplication, CryptoProvider } = await import("./dist-CBYT-Zyt.mjs");
83
100
  const app = new PublicClientApplication({
84
101
  auth: {
85
102
  clientId: CLIENT_ID,
@@ -112,8 +129,9 @@ async function login(options = {}) {
112
129
  async function captureAuthCode(authUrl, options) {
113
130
  const playwright = await importPlaywright();
114
131
  const timeout = options.timeoutMs ?? (options.interactive ? 6e5 : 12e4);
115
- mkdirSync(CONFIG_DIR, { recursive: true });
132
+ ensurePrivateDir(CONFIG_DIR);
116
133
  const profileDir = process.env.M365_BROWSER_PROFILE || join(CONFIG_DIR, "browser-profile");
134
+ ensurePrivateDir(profileDir);
117
135
  const context = await playwright.chromium.launchPersistentContext(profileDir, {
118
136
  headless: !options.interactive,
119
137
  executablePath: process.env.CHROMIUM_PATH || void 0,
@@ -1,6 +1,6 @@
1
1
  import * as crypto from "node:crypto";
2
2
  //#region node_modules/otpauth/dist/otpauth.node.mjs
3
- //! otpauth 9.5.1 | (c) Héctor Molinero Fernández | MIT | https://github.com/hectorm/otpauth
3
+ //! otpauth 9.5.2 | (c) Héctor Molinero Fernández | MIT | https://github.com/hectorm/otpauth
4
4
  /**
5
5
  * Converts an integer to an Uint8Array.
6
6
  * @param {number} num Integer.
@@ -73,24 +73,24 @@ import * as crypto from "node:crypto";
73
73
  /**
74
74
  * RFC 4648 base32 alphabet without pad.
75
75
  * @type {string}
76
- */ const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
76
+ */ const ALPHABET$1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
77
77
  /**
78
78
  * Converts a base32 string to an Uint8Array (RFC 4648).
79
79
  * @see [LinusU/base32-decode](https://github.com/LinusU/base32-decode)
80
80
  * @param {string} str Base32 string.
81
81
  * @returns {Uint8Array} Uint8Array.
82
82
  */ const base32Decode = (str) => {
83
- str = str.replace(/ /g, "");
83
+ str = str.replace(/ /g, "").toUpperCase();
84
84
  let end = str.length;
85
85
  while (str[end - 1] === "=") --end;
86
- str = (end < str.length ? str.substring(0, end) : str).toUpperCase();
86
+ if (end < str.length) str = str.substring(0, end);
87
87
  const buf = /* @__PURE__ */ new ArrayBuffer(str.length * 5 / 8 | 0);
88
88
  const arr = new Uint8Array(buf);
89
89
  let bits = 0;
90
90
  let value = 0;
91
91
  let index = 0;
92
92
  for (let i = 0; i < str.length; i++) {
93
- const idx = ALPHABET.indexOf(str[i]);
93
+ const idx = ALPHABET$1.indexOf(str[i]);
94
94
  if (idx === -1) throw new TypeError(`Invalid character found: ${str[i]}`);
95
95
  value = value << 5 | idx;
96
96
  bits += 5;
@@ -114,22 +114,31 @@ import * as crypto from "node:crypto";
114
114
  value = value << 8 | arr[i];
115
115
  bits += 8;
116
116
  while (bits >= 5) {
117
- str += ALPHABET[value >>> bits - 5 & 31];
117
+ str += ALPHABET$1[value >>> bits - 5 & 31];
118
118
  bits -= 5;
119
119
  }
120
120
  }
121
- if (bits > 0) str += ALPHABET[value << 5 - bits & 31];
121
+ if (bits > 0) str += ALPHABET$1[value << 5 - bits & 31];
122
122
  return str;
123
123
  };
124
124
  /**
125
+ * Hexadecimal alphabet.
126
+ * @type {string}
127
+ */ const ALPHABET = "0123456789ABCDEF";
128
+ /**
125
129
  * Converts a hexadecimal string to an Uint8Array.
126
130
  * @param {string} str Hexadecimal string.
127
131
  * @returns {Uint8Array} Uint8Array.
128
132
  */ const hexDecode = (str) => {
129
- str = str.replace(/ /g, "");
133
+ str = str.replace(/ /g, "").toUpperCase();
130
134
  const buf = /* @__PURE__ */ new ArrayBuffer(str.length / 2);
131
135
  const arr = new Uint8Array(buf);
132
- for (let i = 0; i < str.length; i += 2) arr[i / 2] = parseInt(str.substring(i, i + 2), 16);
136
+ for (let i = 0; i < str.length; i += 2) {
137
+ const hi = ALPHABET.indexOf(str[i]);
138
+ const lo = ALPHABET.indexOf(str[i + 1]);
139
+ if (hi === -1 || lo === -1) throw new TypeError(`Invalid character found: ${str.substring(i, i + 2)}`);
140
+ arr[i / 2] = hi << 4 | lo;
141
+ }
133
142
  return arr;
134
143
  };
135
144
  /**
@@ -192,7 +201,7 @@ import * as crypto from "node:crypto";
192
201
  * Returns random bytes.
193
202
  * @param {number} size Size.
194
203
  * @returns {Uint8Array} Random bytes.
195
- */ const randomBytes = (size) => {
204
+ */ const randomBytes$1 = (size) => {
196
205
  if (crypto?.randomBytes) return crypto.randomBytes(size);
197
206
  else if (globalScope.crypto?.getRandomValues) return globalScope.crypto.getRandomValues(new Uint8Array(size));
198
207
  else throw new Error("Cryptography API not available");
@@ -293,7 +302,7 @@ import * as crypto from "node:crypto";
293
302
  * Secret key.
294
303
  * @type {Uint8Array}
295
304
  * @readonly
296
- */ this.bytes = typeof buffer === "undefined" ? randomBytes(size) : new Uint8Array(buffer);
305
+ */ this.bytes = typeof buffer === "undefined" ? randomBytes$1(size) : new Uint8Array(buffer);
297
306
  Object.defineProperty(this, "bytes", {
298
307
  enumerable: true,
299
308
  writable: false,
@@ -307,7 +316,7 @@ import * as crypto from "node:crypto";
307
316
  * @param {string} a String a.
308
317
  * @param {string} b String b.
309
318
  * @returns {boolean} Equality result.
310
- */ const timingSafeEqual = (a, b) => {
319
+ */ const timingSafeEqual$1 = (a, b) => {
311
320
  if (crypto?.timingSafeEqual) return crypto.timingSafeEqual(globalScope.Buffer.from(a), globalScope.Buffer.from(b));
312
321
  else {
313
322
  if (a.length !== b.length) throw new TypeError("Input strings must have the same length");
@@ -395,7 +404,7 @@ import * as crypto from "node:crypto";
395
404
  counter: i,
396
405
  hmac
397
406
  });
398
- if (timingSafeEqual(token, generatedToken)) delta = i - counter;
407
+ if (timingSafeEqual$1(token, generatedToken)) delta = i - counter;
399
408
  };
400
409
  check(counter);
401
410
  for (let i = 1; i <= window && delta === null; ++i) {
package/dist/plugin.d.mts CHANGED
@@ -1,5 +1,13 @@
1
- import { Plugin } from "@opencode-ai/plugin";
1
+ import { Plugin } from "@opencode/plugin";
2
+ import { Hooks, PluginInput } from "@opencode-ai/plugin";
3
+ //#region src/plugin-v1.d.ts
4
+ declare function server(input: PluginInput, rawOptions?: Record<string, unknown>): Promise<Hooks>;
5
+ //#endregion
2
6
  //#region src/plugin.d.ts
3
- declare const M365CopilotPlugin: Plugin;
7
+ declare const _default: {
8
+ id: string;
9
+ setup: (context: Plugin.Context) => Promise<Plugin.Cleanup | void> | Plugin.Cleanup | void;
10
+ server: typeof server;
11
+ };
4
12
  //#endregion
5
- export { M365CopilotPlugin, M365CopilotPlugin as default };
13
+ export { _default as default };
package/dist/plugin.mjs CHANGED
@@ -1,7 +1,19 @@
1
- import { a as applyPluginConfig, s as resolveOptions, t as startServer, v as createTokenClient, y as createLogger } from "./server-B_2RPeJD.mjs";
2
- import { t as getOrCreateAgent } from "./agent-BXH7KR-e.mjs";
3
- //#region src/plugin.ts
4
- const log = createLogger("plugin");
1
+ import { A as resolveOptions, D as buildModelInfos, E as applyPluginConfig, N as isLocalModel, O as buildProviderInfo, T as PROVIDER_ID, _ as createLogger, a as startServer, g as createTokenClient, j as DEFAULT_MODEL, r as SESSION_ID_HEADER, t as AUX_REQUEST_KIND_HEADER, w as PLUGIN_ID } from "./server-DO0_u884.mjs";
2
+ import { t as getOrCreateAgent } from "./agent-C3DxtJPy.mjs";
3
+ //#region src/runtime.ts
4
+ /**
5
+ * The part of the plugin that is the same under both opencode plugin APIs.
6
+ *
7
+ * v1 and v2 disagree about almost everything — how a plugin is declared, how it is
8
+ * loaded, how it registers a provider — but they agree completely about what this
9
+ * plugin *does*: stand up the OpenAI-compatible proxy, and hand back the URL it is
10
+ * listening on. That is all this module is.
11
+ *
12
+ * Auth is deliberately not here: the plugin only refreshes silently, and tells the
13
+ * user to run `opencode-m365 login` if it cannot. Launching a browser underneath a
14
+ * TUI is not something a plugin should do.
15
+ */
16
+ const log$1 = createLogger("plugin");
5
17
  /**
6
18
  * The system prompt used for M365 models.
7
19
  *
@@ -16,6 +28,10 @@ const log = createLogger("plugin");
16
28
  * still carries the original prompt; setting `agent.<name>.prompt` from the `config`
17
29
  * hook is ignored the same way. Since our provider only ever serves our own models,
18
30
  * doing it proxy-side is also correctly scoped — no other provider is affected.
31
+ *
32
+ * opencode 2 offers `session.hook("context")` as a working replacement for that dead
33
+ * v1 hook. It has not been measured against a live tenant, and the proxy is the only
34
+ * layer that is true for every harness, so the logic stays here until it has been.
19
35
  */
20
36
  const LEAN_SYSTEM_PROMPT = [
21
37
  "You are a coding agent working in the user's real workspace on this machine.",
@@ -25,35 +41,96 @@ const LEAN_SYSTEM_PROMPT = [
25
41
  "Inspect before you change something, and check your change afterwards.",
26
42
  "Report what you actually did, not what you intended to do."
27
43
  ].join("\n");
28
- const M365CopilotPlugin = async (input, rawOptions) => {
44
+ /**
45
+ * Resolve options and bring the proxy up.
46
+ *
47
+ * With `baseUrl` set the caller already has a proxy running — `opencode-m365 serve`,
48
+ * or a test — and we attach to it rather than binding a second port. `close()` is
49
+ * then a no-op, because a runtime must not shut down a server it did not start.
50
+ */
51
+ async function startRuntime(rawOptions) {
29
52
  const options = resolveOptions(rawOptions);
30
- const tokens = createTokenClient();
31
- let proxy;
32
- let baseUrl = options.baseUrl;
33
- if (!baseUrl) {
34
- proxy = await startServer({
35
- getToken: () => tokens.getToken(),
36
- resolveAgent: () => getOrCreateAgent({ getTokenForScope: (scopes) => tokens.getTokenForScope(scopes) }),
37
- lean: options.lean,
38
- ...options.leanSystemPrompt ? { leanSystemPrompt: LEAN_SYSTEM_PROMPT } : {}
39
- });
40
- baseUrl = `${proxy.url}/v1`;
41
- log.info(`M365 Copilot proxy listening on ${proxy.url}`);
53
+ const sharedKey = process.env.M365_PROXY_KEY || void 0;
54
+ if (options.baseUrl) {
55
+ const apiKey = options.apiKey ?? sharedKey;
56
+ if (!apiKey) log$1.warn("baseUrl is set but no proxy secret is: pass the key `opencode-m365 serve` printed as the `apiKey` plugin option, or set M365_PROXY_KEY");
57
+ return {
58
+ baseUrl: options.baseUrl,
59
+ apiKey: apiKey ?? "missing-proxy-secret",
60
+ options,
61
+ close: async () => {}
62
+ };
42
63
  }
64
+ const tokens = createTokenClient();
65
+ const proxy = await startServer({
66
+ getToken: () => tokens.getToken(),
67
+ resolveAgent: () => getOrCreateAgent({ getTokenForScope: (scopes) => tokens.getTokenForScope(scopes) }),
68
+ lean: options.lean,
69
+ ...sharedKey ? { apiKey: sharedKey } : {},
70
+ ...options.leanSystemPrompt ? { leanSystemPrompt: LEAN_SYSTEM_PROMPT } : {}
71
+ });
72
+ log$1.info(`M365 Copilot proxy listening on ${proxy.url}`);
73
+ return {
74
+ baseUrl: `${proxy.url}/v1`,
75
+ apiKey: proxy.apiKey,
76
+ options,
77
+ close: () => proxy.close()
78
+ };
79
+ }
80
+ //#endregion
81
+ //#region src/plugin-v1.ts
82
+ async function server(input, rawOptions) {
83
+ const runtime = await startRuntime(rawOptions);
43
84
  await input.client.app.log({ body: {
44
85
  service: "m365-copilot",
45
86
  level: "info",
46
- message: `Microsoft 365 Copilot ready at ${baseUrl}`,
47
- extra: { lean: options.lean }
87
+ message: `Microsoft 365 Copilot ready at ${runtime.baseUrl}`,
88
+ extra: { lean: runtime.options.lean }
48
89
  } }).catch(() => {});
49
90
  return {
50
91
  async config(config) {
51
- applyPluginConfig(config, baseUrl, options);
92
+ applyPluginConfig(config, runtime, runtime.options);
52
93
  },
53
94
  async dispose() {
54
- await proxy?.close();
95
+ await runtime.close();
55
96
  }
56
97
  };
98
+ }
99
+ //#endregion
100
+ //#region src/plugin-v2.ts
101
+ const log = createLogger("plugin");
102
+ const setup = async (ctx) => {
103
+ const runtime = await startRuntime(ctx.options);
104
+ const info = buildProviderInfo(runtime.baseUrl, runtime.apiKey);
105
+ const models = buildModelInfos();
106
+ await ctx.provider.transform((editor) => {
107
+ editor.add({
108
+ info,
109
+ models
110
+ });
111
+ });
112
+ if (runtime.options.setDefaultModel) await ctx.model.transform((editor) => {
113
+ if (editor.default.get()) return;
114
+ editor.default.set(PROVIDER_ID, DEFAULT_MODEL);
115
+ });
116
+ await ctx.session.hook("model.request", (event) => {
117
+ if (event.model.providerID !== "m365") return;
118
+ if (event.kind === "primary" && event.sessionID) {
119
+ event.headers[SESSION_ID_HEADER] = String(event.sessionID);
120
+ return;
121
+ }
122
+ if (!runtime.options.setSmallModel) return;
123
+ if (event.kind !== "title") return;
124
+ if (isLocalModel(event.model.id)) return;
125
+ event.headers[AUX_REQUEST_KIND_HEADER] = event.kind;
126
+ });
127
+ log.info(`Microsoft 365 Copilot ready at ${runtime.baseUrl}`);
128
+ return () => runtime.close();
129
+ };
130
+ var plugin_default = {
131
+ id: PLUGIN_ID,
132
+ setup,
133
+ server
57
134
  };
58
135
  //#endregion
59
- export { M365CopilotPlugin, M365CopilotPlugin as default };
136
+ export { plugin_default as default };