opencode-m365-copilot 0.2.1 → 0.3.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.
@@ -1,4 +1,4 @@
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-DDD-Hlhx.mjs";
1
+ import { _ as CONFIG_DIR, a as AUTHORITY, d as authCodeFromUrl, f as createCachePlugin, i as string, l as REDIRECT_URI, m as createLogger, r as object, s as CLIENT_ID, u as SYDNEY_SCOPES, v as SECRETS_FILE } from "./server-DuHBfcPQ.mjs";
2
2
  import { existsSync, mkdirSync, readFileSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  //#region src/login.ts
@@ -62,7 +62,7 @@ function normaliseTotpSecret(raw) {
62
62
  }
63
63
  /** Current 6-digit code for a base32 seed. */
64
64
  async function totpCode(secret) {
65
- const { TOTP, Secret } = await import("./otpauth.node-klD_z4Tx.mjs");
65
+ const { TOTP, Secret } = await import("./otpauth.node-BaAHzqxj.mjs");
66
66
  return new TOTP({
67
67
  secret: Secret.fromBase32(normaliseTotpSecret(secret)),
68
68
  digits: 6,
@@ -79,7 +79,7 @@ async function login(options = {}) {
79
79
  const secrets = loadSecrets(options.secretsFile);
80
80
  const interactive = options.interactive ?? !secrets?.mfaSecret;
81
81
  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-CX5bv-4h.mjs");
82
+ const { PublicClientApplication, CryptoProvider } = await import("./dist-C8jy_NH0.mjs");
83
83
  const app = new PublicClientApplication({
84
84
  auth: {
85
85
  clientId: CLIENT_ID,
@@ -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
  /**
package/dist/plugin.d.mts CHANGED
@@ -1,9 +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;
4
7
  declare const _default: {
5
8
  id: string;
6
- server: Plugin;
9
+ setup: (context: Plugin.Context) => Promise<Plugin.Cleanup | void> | Plugin.Cleanup | void;
10
+ server: typeof server;
7
11
  };
8
12
  //#endregion
9
- export { M365CopilotPlugin, _default 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-DDD-Hlhx.mjs";
2
- import { t as getOrCreateAgent } from "./agent-BF67A0cd.mjs";
3
- //#region src/plugin.ts
4
- const log = createLogger("plugin");
1
+ import { C as buildProviderInfo, E as DEFAULT_MODEL, O as isLocalModel, S as buildModelInfos, T as resolveOptions, b as PROVIDER_ID, m as createLogger, n as startServer, p as createTokenClient, t as AUX_REQUEST_KIND_HEADER, x as applyPluginConfig, y as PLUGIN_ID } from "./server-DuHBfcPQ.mjs";
2
+ import { t as getOrCreateAgent } from "./agent-BDA00x1V.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,39 +41,83 @@ 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);
53
+ if (options.baseUrl) return {
54
+ baseUrl: options.baseUrl,
55
+ options,
56
+ close: async () => {}
57
+ };
30
58
  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}`);
42
- }
59
+ const proxy = await startServer({
60
+ getToken: () => tokens.getToken(),
61
+ resolveAgent: () => getOrCreateAgent({ getTokenForScope: (scopes) => tokens.getTokenForScope(scopes) }),
62
+ lean: options.lean,
63
+ ...options.leanSystemPrompt ? { leanSystemPrompt: LEAN_SYSTEM_PROMPT } : {}
64
+ });
65
+ log$1.info(`M365 Copilot proxy listening on ${proxy.url}`);
66
+ return {
67
+ baseUrl: `${proxy.url}/v1`,
68
+ options,
69
+ close: () => proxy.close()
70
+ };
71
+ }
72
+ //#endregion
73
+ //#region src/plugin-v1.ts
74
+ async function server(input, rawOptions) {
75
+ const runtime = await startRuntime(rawOptions);
43
76
  await input.client.app.log({ body: {
44
77
  service: "m365-copilot",
45
78
  level: "info",
46
- message: `Microsoft 365 Copilot ready at ${baseUrl}`,
47
- extra: { lean: options.lean }
79
+ message: `Microsoft 365 Copilot ready at ${runtime.baseUrl}`,
80
+ extra: { lean: runtime.options.lean }
48
81
  } }).catch(() => {});
49
82
  return {
50
83
  async config(config) {
51
- applyPluginConfig(config, baseUrl, options);
84
+ applyPluginConfig(config, runtime.baseUrl, runtime.options);
52
85
  },
53
86
  async dispose() {
54
- await proxy?.close();
87
+ await runtime.close();
55
88
  }
56
89
  };
90
+ }
91
+ //#endregion
92
+ //#region src/plugin-v2.ts
93
+ const log = createLogger("plugin");
94
+ const setup = async (ctx) => {
95
+ const runtime = await startRuntime(ctx.options);
96
+ const info = buildProviderInfo(runtime.baseUrl);
97
+ const models = buildModelInfos();
98
+ await ctx.provider.transform((editor) => {
99
+ editor.add({
100
+ info,
101
+ models
102
+ });
103
+ });
104
+ if (runtime.options.setDefaultModel) await ctx.model.transform((editor) => {
105
+ if (editor.default.get()) return;
106
+ editor.default.set(PROVIDER_ID, DEFAULT_MODEL);
107
+ });
108
+ if (runtime.options.setSmallModel) await ctx.session.hook("model.request", (event) => {
109
+ if (event.kind !== "title") return;
110
+ if (event.model.providerID !== "m365") return;
111
+ if (isLocalModel(event.model.id)) return;
112
+ event.headers[AUX_REQUEST_KIND_HEADER] = event.kind;
113
+ });
114
+ log.info(`Microsoft 365 Copilot ready at ${runtime.baseUrl}`);
115
+ return () => runtime.close();
57
116
  };
58
117
  var plugin_default = {
59
- id: "opencode-m365-copilot",
60
- server: M365CopilotPlugin
118
+ id: PLUGIN_ID,
119
+ setup,
120
+ server
61
121
  };
62
122
  //#endregion
63
- export { M365CopilotPlugin, plugin_default as default };
123
+ export { plugin_default as default };