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
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { _ as createLogger, b as CONFIG_DIR, c as AUTHORITY, f as REDIRECT_URI, h as createCachePlugin, m as authCodeFromUrl, p as SYDNEY_SCOPES, u as CLIENT_ID, x as SECRETS_FILE } from "./server-CeGQPDdE.mjs";
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
//#region src/login.ts
|
|
6
|
+
/**
|
|
7
|
+
* Interactive / automated sign-in. Loaded only by the CLI, never by the plugin.
|
|
8
|
+
*
|
|
9
|
+
* Why a browser at all: the Sydney scopes are granted exclusively to Microsoft's own
|
|
10
|
+
* Office web Copilot client, so we cannot register a loopback redirect
|
|
11
|
+
* (`AADSTS50011`) and the device-code grant is refused for that client
|
|
12
|
+
* (`AADSTS7000218` — it wants a client secret only Microsoft has). The `nativeclient`
|
|
13
|
+
* redirect is the only remaining door, and driving it needs a real browser.
|
|
14
|
+
*
|
|
15
|
+
* Two modes:
|
|
16
|
+
* - automated: stored credentials plus a TOTP seed, headless. Needs the seed
|
|
17
|
+
* itself, not a code from a phone.
|
|
18
|
+
* - interactive: a visible window where you complete SSO/MFA by hand. The only
|
|
19
|
+
* option for push-only MFA, FIDO2, or a federated IdP (Okta/Ping/Duo).
|
|
20
|
+
*
|
|
21
|
+
* Either way it is a one-time cost — afterwards `auth.ts` refreshes silently.
|
|
22
|
+
*/
|
|
23
|
+
const log = createLogger("login");
|
|
24
|
+
const SecretsSchema = z.object({
|
|
25
|
+
email: z.string().min(3),
|
|
26
|
+
password: z.string().min(1),
|
|
27
|
+
/**
|
|
28
|
+
* The base32 TOTP seed — what your authenticator derives its 6-digit codes from,
|
|
29
|
+
* not a code. Optional: without it, only interactive sign-in is possible.
|
|
30
|
+
*/
|
|
31
|
+
mfaSecret: z.string().optional()
|
|
32
|
+
});
|
|
33
|
+
/** Read stored credentials, if any. Returns undefined when the file is absent. */
|
|
34
|
+
function loadSecrets(file = SECRETS_FILE) {
|
|
35
|
+
if (!existsSync(file)) return void 0;
|
|
36
|
+
let parsed;
|
|
37
|
+
try {
|
|
38
|
+
parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
39
|
+
} catch (error) {
|
|
40
|
+
throw new Error(`${file} is not valid JSON: ${String(error)}`);
|
|
41
|
+
}
|
|
42
|
+
const result = SecretsSchema.safeParse(parsed);
|
|
43
|
+
if (!result.success) throw new Error(`${file} is missing required fields: ${result.error.issues.map((i) => i.path.join(".")).join(", ")}`);
|
|
44
|
+
return result.data;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Validate a TOTP seed before we try to use it.
|
|
48
|
+
*
|
|
49
|
+
* A common failure is pasting the whole `otpauth://` URI, or a 6-digit code, instead
|
|
50
|
+
* of the seed. Both fail deep inside the login with an unhelpful message.
|
|
51
|
+
*/
|
|
52
|
+
function normaliseTotpSecret(raw) {
|
|
53
|
+
let secret = raw.trim();
|
|
54
|
+
if (secret.startsWith("otpauth://")) {
|
|
55
|
+
const fromUri = new URL(secret).searchParams.get("secret");
|
|
56
|
+
if (!fromUri) throw new Error("That otpauth:// URI has no `secret` parameter");
|
|
57
|
+
secret = fromUri;
|
|
58
|
+
}
|
|
59
|
+
secret = secret.replace(/\s+/g, "").toUpperCase();
|
|
60
|
+
if (/^\d{6}$/.test(secret)) throw new Error("That looks like a 6-digit code, not the base32 seed it is generated from");
|
|
61
|
+
if (!/^[A-Z2-7]+=*$/.test(secret) || secret.length < 16) throw new Error("mfaSecret must be a base32 seed (A-Z and 2-7, 16+ characters)");
|
|
62
|
+
return secret;
|
|
63
|
+
}
|
|
64
|
+
/** Current 6-digit code for a base32 seed. */
|
|
65
|
+
async function totpCode(secret) {
|
|
66
|
+
const { TOTP, Secret } = await import("otpauth");
|
|
67
|
+
return new TOTP({
|
|
68
|
+
secret: Secret.fromBase32(normaliseTotpSecret(secret)),
|
|
69
|
+
digits: 6,
|
|
70
|
+
period: 30
|
|
71
|
+
}).generate();
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Sign in and populate the MSAL cache.
|
|
75
|
+
*
|
|
76
|
+
* Returns the account username on success. Everything afterwards is silent refresh.
|
|
77
|
+
*/
|
|
78
|
+
async function login(options = {}) {
|
|
79
|
+
const status = options.onStatus ?? (() => {});
|
|
80
|
+
const secrets = loadSecrets(options.secretsFile);
|
|
81
|
+
const interactive = options.interactive ?? !secrets?.mfaSecret;
|
|
82
|
+
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.`);
|
|
83
|
+
const { PublicClientApplication, CryptoProvider } = await import("@azure/msal-node");
|
|
84
|
+
const app = new PublicClientApplication({
|
|
85
|
+
auth: {
|
|
86
|
+
clientId: CLIENT_ID,
|
|
87
|
+
authority: AUTHORITY
|
|
88
|
+
},
|
|
89
|
+
cache: { cachePlugin: createCachePlugin(options.cacheFile) }
|
|
90
|
+
});
|
|
91
|
+
const { verifier, challenge } = await new CryptoProvider().generatePkceCodes();
|
|
92
|
+
const authUrl = await app.getAuthCodeUrl({
|
|
93
|
+
scopes: SYDNEY_SCOPES,
|
|
94
|
+
redirectUri: REDIRECT_URI,
|
|
95
|
+
codeChallenge: challenge,
|
|
96
|
+
codeChallengeMethod: "S256",
|
|
97
|
+
prompt: interactive ? "select_account" : void 0
|
|
98
|
+
});
|
|
99
|
+
status(interactive ? "Opening a browser window — complete sign-in there." : "Signing in…");
|
|
100
|
+
const code = await captureAuthCode(authUrl, {
|
|
101
|
+
...options,
|
|
102
|
+
interactive,
|
|
103
|
+
secrets
|
|
104
|
+
});
|
|
105
|
+
return (await app.acquireTokenByCode({
|
|
106
|
+
code,
|
|
107
|
+
scopes: SYDNEY_SCOPES,
|
|
108
|
+
redirectUri: "https://login.microsoftonline.com/common/oauth2/nativeclient",
|
|
109
|
+
codeVerifier: verifier
|
|
110
|
+
}))?.account?.username ?? "signed in";
|
|
111
|
+
}
|
|
112
|
+
/** Drive a browser to the authorize endpoint and pull the code off the redirect. */
|
|
113
|
+
async function captureAuthCode(authUrl, options) {
|
|
114
|
+
const playwright = await importPlaywright();
|
|
115
|
+
const timeout = options.timeoutMs ?? (options.interactive ? 6e5 : 12e4);
|
|
116
|
+
mkdirSync(CONFIG_DIR, { recursive: true });
|
|
117
|
+
const profileDir = process.env.M365_BROWSER_PROFILE || join(CONFIG_DIR, "browser-profile");
|
|
118
|
+
const context = await playwright.chromium.launchPersistentContext(profileDir, {
|
|
119
|
+
headless: !options.interactive,
|
|
120
|
+
executablePath: process.env.CHROMIUM_PATH || void 0,
|
|
121
|
+
locale: process.env.M365_LOGIN_LOCALE || "en-GB",
|
|
122
|
+
timezoneId: process.env.M365_LOGIN_TIMEZONE || void 0,
|
|
123
|
+
...process.env.M365_LOGIN_UA ? { userAgent: process.env.M365_LOGIN_UA } : {}
|
|
124
|
+
});
|
|
125
|
+
try {
|
|
126
|
+
const page = context.pages()[0] ?? await context.newPage();
|
|
127
|
+
const code = new Promise((resolve, reject) => {
|
|
128
|
+
const timer = setTimeout(() => reject(/* @__PURE__ */ new Error("Timed out waiting for sign-in to complete")), timeout);
|
|
129
|
+
page.on("request", (request) => {
|
|
130
|
+
try {
|
|
131
|
+
const found = authCodeFromUrl(request.url());
|
|
132
|
+
if (found) {
|
|
133
|
+
clearTimeout(timer);
|
|
134
|
+
resolve(found);
|
|
135
|
+
}
|
|
136
|
+
} catch (error) {
|
|
137
|
+
clearTimeout(timer);
|
|
138
|
+
reject(error);
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
await page.goto(authUrl, { waitUntil: "domcontentloaded" }).catch(() => {});
|
|
143
|
+
if (!options.interactive && options.secrets) await fillCredentials(page, options.secrets, options.onStatus ?? (() => {}));
|
|
144
|
+
return await code;
|
|
145
|
+
} finally {
|
|
146
|
+
await context.close().catch(() => {});
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
/** Walk the converged AAD form: email, password, then the TOTP code. */
|
|
150
|
+
async function fillCredentials(page, secrets, status) {
|
|
151
|
+
status("Entering credentials…");
|
|
152
|
+
await fillVerified(page, "input[name=\"loginfmt\"]", secrets.email);
|
|
153
|
+
await page.click("#idSIButton9").catch(() => page.keyboard.press("Enter"));
|
|
154
|
+
await page.waitForSelector("input[name=\"passwd\"]", { timeout: 3e4 });
|
|
155
|
+
await fillVerified(page, "input[name=\"passwd\"]", secrets.password);
|
|
156
|
+
await page.click("#idSIButton9").catch(() => page.keyboard.press("Enter"));
|
|
157
|
+
if (!secrets.mfaSecret) return;
|
|
158
|
+
if (!await page.waitForSelector("input[name=\"otc\"]", { timeout: 3e4 }).catch(() => null)) return;
|
|
159
|
+
status("Entering the MFA code…");
|
|
160
|
+
await fillVerified(page, "input[name=\"otc\"]", await totpCode(secrets.mfaSecret));
|
|
161
|
+
await page.click("#idSubmit_SAOTCC_Continue").catch(() => page.keyboard.press("Enter"));
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Fill a field and check the value actually landed.
|
|
165
|
+
*
|
|
166
|
+
* The converged login page keeps hidden duplicate `<input type=password>` nodes, and
|
|
167
|
+
* a naive fill can target a stale hidden one and submit an empty password — which
|
|
168
|
+
* AAD reports as bad credentials.
|
|
169
|
+
*/
|
|
170
|
+
async function fillVerified(page, selector, value) {
|
|
171
|
+
const field = page.locator(`${selector}:visible`).first();
|
|
172
|
+
await field.waitFor({
|
|
173
|
+
state: "visible",
|
|
174
|
+
timeout: 3e4
|
|
175
|
+
});
|
|
176
|
+
await field.fill(value);
|
|
177
|
+
if (await field.inputValue() !== value) {
|
|
178
|
+
log.warn(`value did not land in ${selector}, retrying`);
|
|
179
|
+
await field.fill("");
|
|
180
|
+
await field.type(value, { delay: 20 });
|
|
181
|
+
if (await field.inputValue() !== value) throw new Error(`Could not fill ${selector} on the sign-in page`);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
async function importPlaywright() {
|
|
185
|
+
try {
|
|
186
|
+
return await import("playwright");
|
|
187
|
+
} catch {
|
|
188
|
+
throw new Error("Playwright is not installed. It ships as an optional dependency — run `npm i playwright && npx playwright install chromium`, or set CHROMIUM_PATH to an existing browser.");
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
//#endregion
|
|
192
|
+
export { login };
|
package/dist/plugin.mjs
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { _ as createLogger, a as resolveOptions, g as createTokenClient, r as applyPluginConfig, t as startServer } from "./server-CeGQPDdE.mjs";
|
|
2
|
+
import { t as getOrCreateAgent } from "./agent-t3MgztgU.mjs";
|
|
3
|
+
//#region src/plugin.ts
|
|
4
|
+
const log = createLogger("plugin");
|
|
5
|
+
/**
|
|
6
|
+
* The system prompt used for M365 models.
|
|
7
|
+
*
|
|
8
|
+
* opencode's own prompt is long and carefully worded for frontier models. Measured
|
|
9
|
+
* against M365, a shorter and blunter prompt produced markedly better tool
|
|
10
|
+
* compliance — the same model confabulates ("I can't access the files, paste them")
|
|
11
|
+
* under a longer, more polished assistant prompt.
|
|
12
|
+
*
|
|
13
|
+
* This is applied in the **proxy**, not through opencode's own hook. Verified
|
|
14
|
+
* against opencode 1.18.18: `experimental.chat.system.transform` fires and happily
|
|
15
|
+
* accepts a replacement `system` array, but the request that reaches the provider
|
|
16
|
+
* still carries the original prompt; setting `agent.<name>.prompt` from the `config`
|
|
17
|
+
* hook is ignored the same way. Since our provider only ever serves our own models,
|
|
18
|
+
* doing it proxy-side is also correctly scoped — no other provider is affected.
|
|
19
|
+
*/
|
|
20
|
+
const LEAN_SYSTEM_PROMPT = [
|
|
21
|
+
"You are a coding agent working in the user's real workspace on this machine.",
|
|
22
|
+
"The files and commands are real, and anything you run actually runs.",
|
|
23
|
+
"",
|
|
24
|
+
"Work one step at a time: take an action, read the result, then decide the next step.",
|
|
25
|
+
"Inspect before you change something, and check your change afterwards.",
|
|
26
|
+
"Report what you actually did, not what you intended to do."
|
|
27
|
+
].join("\n");
|
|
28
|
+
const M365CopilotPlugin = async (input, rawOptions) => {
|
|
29
|
+
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}`);
|
|
42
|
+
}
|
|
43
|
+
await input.client.app.log({ body: {
|
|
44
|
+
service: "m365-copilot",
|
|
45
|
+
level: "info",
|
|
46
|
+
message: `Microsoft 365 Copilot ready at ${baseUrl}`,
|
|
47
|
+
extra: { lean: options.lean }
|
|
48
|
+
} }).catch(() => {});
|
|
49
|
+
return {
|
|
50
|
+
async config(config) {
|
|
51
|
+
applyPluginConfig(config, baseUrl, options);
|
|
52
|
+
},
|
|
53
|
+
async dispose() {
|
|
54
|
+
await proxy?.close();
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
var plugin_default = {
|
|
59
|
+
id: "opencode-m365-copilot",
|
|
60
|
+
server: M365CopilotPlugin
|
|
61
|
+
};
|
|
62
|
+
//#endregion
|
|
63
|
+
export { M365CopilotPlugin, plugin_default as default };
|