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 +16 -3
- package/dist/{agent-BDA00x1V.mjs → agent-C28PfLXM.mjs} +3 -5
- package/dist/cli.mjs +40 -9
- package/dist/{dist-C8jy_NH0.mjs → dist-BGVW-hOf.mjs} +127 -122
- package/dist/{login-Cb_rQQHO.mjs → login-Y2igNqfw.mjs} +25 -7
- package/dist/{otpauth.node-BaAHzqxj.mjs → otpauth.node-CBOz_1IZ.mjs} +4 -4
- package/dist/plugin.mjs +24 -11
- package/dist/{server-DuHBfcPQ.mjs → server-Buz1ZIg5.mjs} +281 -84
- package/dist/server.d.mts +29 -0
- package/dist/server.mjs +2 -2
- package/package.json +8 -6
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { createRequire } from "node:module";
|
|
2
|
-
import { randomUUID } from "node:crypto";
|
|
3
|
-
import { appendFileSync, chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
4
|
-
import { dirname, join } from "node:path";
|
|
2
|
+
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
3
|
+
import { appendFileSync, chmodSync, closeSync, constants, mkdirSync, openSync, readFileSync, realpathSync, writeFileSync, writeSync } from "node:fs";
|
|
5
4
|
import { homedir } from "node:os";
|
|
5
|
+
import { dirname, join, parse, resolve, sep } from "node:path";
|
|
6
6
|
import { createServer } from "node:http";
|
|
7
7
|
//#region \0rolldown/runtime.js
|
|
8
8
|
var __create = Object.create;
|
|
@@ -567,7 +567,8 @@ function resolveOptions(raw) {
|
|
|
567
567
|
setDefaultModel: bool(options.setDefaultModel, true),
|
|
568
568
|
setSmallModel: bool(options.setSmallModel, true),
|
|
569
569
|
leanSystemPrompt: bool(options.leanSystemPrompt, false),
|
|
570
|
-
baseUrl: typeof options.baseUrl === "string" ? options.baseUrl : void 0
|
|
570
|
+
baseUrl: typeof options.baseUrl === "string" ? options.baseUrl : void 0,
|
|
571
|
+
apiKey: typeof options.apiKey === "string" && options.apiKey !== "" ? options.apiKey : void 0
|
|
571
572
|
};
|
|
572
573
|
}
|
|
573
574
|
/** `{ bash: true, ..., webfetch: false, ... }` — opencode's `tools` config shape. */
|
|
@@ -578,7 +579,7 @@ function buildToolProfile() {
|
|
|
578
579
|
return profile;
|
|
579
580
|
}
|
|
580
581
|
/** The `provider.m365` entry pointing opencode at our local OpenAI-compatible proxy. */
|
|
581
|
-
function buildProviderConfig(baseUrl) {
|
|
582
|
+
function buildProviderConfig(baseUrl, apiKey) {
|
|
582
583
|
const models = {};
|
|
583
584
|
for (const model of MODELS) models[model.id] = {
|
|
584
585
|
name: model.name,
|
|
@@ -598,14 +599,14 @@ function buildProviderConfig(baseUrl) {
|
|
|
598
599
|
name: "Microsoft 365 Copilot",
|
|
599
600
|
options: {
|
|
600
601
|
baseURL: baseUrl,
|
|
601
|
-
apiKey
|
|
602
|
+
apiKey,
|
|
602
603
|
timeout: 9e5
|
|
603
604
|
},
|
|
604
605
|
models
|
|
605
606
|
};
|
|
606
607
|
}
|
|
607
608
|
/** The opencode 2 provider record pointing at our local OpenAI-compatible proxy. */
|
|
608
|
-
function buildProviderInfo(baseUrl) {
|
|
609
|
+
function buildProviderInfo(baseUrl, apiKey) {
|
|
609
610
|
return {
|
|
610
611
|
id: PROVIDER_ID,
|
|
611
612
|
name: "Microsoft 365 Copilot",
|
|
@@ -613,7 +614,7 @@ function buildProviderInfo(baseUrl) {
|
|
|
613
614
|
package: "@opencode/ai/providers/openai-compatible",
|
|
614
615
|
settings: {
|
|
615
616
|
baseURL: baseUrl,
|
|
616
|
-
apiKey
|
|
617
|
+
apiKey,
|
|
617
618
|
timeout: 9e5
|
|
618
619
|
}
|
|
619
620
|
};
|
|
@@ -665,9 +666,9 @@ function buildModelInfos() {
|
|
|
665
666
|
* Deliberately additive: anything the user set explicitly wins. We are a plugin
|
|
666
667
|
* making someone else's config work, not the owner of it.
|
|
667
668
|
*/
|
|
668
|
-
function applyPluginConfig(config,
|
|
669
|
+
function applyPluginConfig(config, endpoint, options) {
|
|
669
670
|
config.provider ??= {};
|
|
670
|
-
config.provider[PROVIDER_ID] = buildProviderConfig(baseUrl);
|
|
671
|
+
config.provider[PROVIDER_ID] = buildProviderConfig(endpoint.baseUrl, endpoint.apiKey);
|
|
671
672
|
if (options.setDefaultModel && !config.model) config.model = `${PROVIDER_ID}/${DEFAULT_MODEL}`;
|
|
672
673
|
if (options.setSmallModel && !config.small_model) config.small_model = `${PROVIDER_ID}/${LOCAL_TITLE_MODEL}`;
|
|
673
674
|
if (options.lean && usesOurProvider(config)) config.tools = {
|
|
@@ -678,31 +679,24 @@ function applyPluginConfig(config, baseUrl, options) {
|
|
|
678
679
|
function usesOurProvider(config) {
|
|
679
680
|
return typeof config.model === "string" && config.model.startsWith(`m365/`);
|
|
680
681
|
}
|
|
681
|
-
/**
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
* one file can serve both, which is the whole point of the dual entry in `plugin.ts`.
|
|
693
|
-
*
|
|
694
|
-
* They also need different *references* for a local checkout. opencode 1 wants the
|
|
695
|
-
* built entrypoint; opencode 2 insists on a directory and drops a file path with
|
|
696
|
-
* `configured plugin path must be a directory` — measured against 2.0.11, and since
|
|
697
|
-
* v2 swallows plugin load failures nothing else reports it. `pluginDir` is that
|
|
698
|
-
* directory. An npm install needs neither, because the package name serves both.
|
|
699
|
-
*/
|
|
682
|
+
/** The npm name this package publishes under — what a checkout's package.json says. */
|
|
683
|
+
const PACKAGE_NAME = "opencode-m365-copilot";
|
|
684
|
+
/** Every option key this plugin reads; anything else belongs to another plugin. */
|
|
685
|
+
const OUR_OPTION_KEYS = /* @__PURE__ */ new Set([
|
|
686
|
+
"lean",
|
|
687
|
+
"setDefaultModel",
|
|
688
|
+
"setSmallModel",
|
|
689
|
+
"leanSystemPrompt",
|
|
690
|
+
"baseUrl",
|
|
691
|
+
"apiKey"
|
|
692
|
+
]);
|
|
700
693
|
function mergeOpencodeConfig(existing, opts) {
|
|
701
694
|
const merged = { ...existing };
|
|
702
695
|
merged.$schema ??= "https://opencode.ai/config.json";
|
|
703
696
|
const pluginDir = opts.pluginDir ?? opts.pluginRef;
|
|
704
|
-
const
|
|
705
|
-
const
|
|
697
|
+
const inspect = opts.inspect ?? (() => ({ exists: false }));
|
|
698
|
+
const v1 = withOurRef(merged.plugin, opts.pluginRef, inspect);
|
|
699
|
+
const v2 = withOurRef(merged.plugins, pluginDir, inspect, v1.dropped);
|
|
706
700
|
merged.plugin = [...v1.kept, v1.options ? [opts.pluginRef, v1.options] : opts.pluginRef];
|
|
707
701
|
merged.plugins = [...v2.kept, v2.options ? {
|
|
708
702
|
package: pluginDir,
|
|
@@ -717,14 +711,14 @@ function mergeOpencodeConfig(existing, opts) {
|
|
|
717
711
|
* build path — is what stops a re-run of setup, after the checkout moved, from
|
|
718
712
|
* leaving opencode trying to load a file that no longer exists.
|
|
719
713
|
*/
|
|
720
|
-
function withOurRef(existing, pluginRef, containing = []) {
|
|
714
|
+
function withOurRef(existing, pluginRef, inspect, containing = []) {
|
|
721
715
|
const entries = Array.isArray(existing) ? [...existing] : [];
|
|
722
716
|
const kept = [];
|
|
723
717
|
const dropped = [];
|
|
724
718
|
let options;
|
|
725
719
|
for (const entry of entries) {
|
|
726
720
|
const spec = specifierOf(entry);
|
|
727
|
-
if (!(isOurPluginRef(spec, pluginRef) || containing.some((path) => isWithin(spec, path)))) {
|
|
721
|
+
if (!(isOurPluginRef(spec, pluginRef, optionsOf(entry), inspect) || containing.some((path) => isWithin(spec, path)))) {
|
|
728
722
|
kept.push(entry);
|
|
729
723
|
continue;
|
|
730
724
|
}
|
|
@@ -760,14 +754,24 @@ function specifierOf(entry) {
|
|
|
760
754
|
/**
|
|
761
755
|
* Does `ref` point at this plugin?
|
|
762
756
|
*
|
|
763
|
-
*
|
|
764
|
-
*
|
|
765
|
-
*
|
|
757
|
+
* Certain when it is the npm package name or this repo's directory name. A local
|
|
758
|
+
* install is an absolute path to `.../dist/plugin.mjs`, but that layout is common to
|
|
759
|
+
* many plugins, so a shared path tail alone proves nothing:
|
|
760
|
+
*
|
|
761
|
+
* - a path that exists is ours only if its package.json names this package;
|
|
762
|
+
* - a path that no longer exists (the usual moved-checkout case) is taken as a stale
|
|
763
|
+
* copy of us when it carries no options, or only ours — so another plugin's options
|
|
764
|
+
* are never swallowed. An option-less vanished entry is taken even if it was someone
|
|
765
|
+
* else's: setup writes a bare entry by default, so that is what a moved checkout of
|
|
766
|
+
* ours usually leaves, and a foreign one was already failing to load.
|
|
766
767
|
*/
|
|
767
|
-
function isOurPluginRef(ref, incoming) {
|
|
768
|
+
function isOurPluginRef(ref, incoming, options, inspect) {
|
|
768
769
|
if (ref === incoming) return true;
|
|
769
770
|
if (ref.includes("opencode-m365-copilot") || ref.includes("opencode-copilot-plugin")) return true;
|
|
770
|
-
|
|
771
|
+
if (tail(ref) === "" || tail(ref) !== tail(incoming)) return false;
|
|
772
|
+
const info = inspect(ref);
|
|
773
|
+
if (info.exists) return info.packageName === PACKAGE_NAME;
|
|
774
|
+
return Object.keys(options ?? {}).every((key) => OUR_OPTION_KEYS.has(key));
|
|
771
775
|
}
|
|
772
776
|
/** The last two path segments, which for a local install are `dist/plugin.mjs`. */
|
|
773
777
|
function tail(ref) {
|
|
@@ -789,11 +793,125 @@ const SECRETS_FILE = process.env.M365_SECRETS_FILE || join(CONFIG_DIR, "secrets.
|
|
|
789
793
|
const AGENT_FILE = process.env.M365_AGENT_FILE || join(CONFIG_DIR, "agent-id.json");
|
|
790
794
|
const LOG_FILE = join(CONFIG_DIR, "debug.log");
|
|
791
795
|
//#endregion
|
|
796
|
+
//#region src/private-fs.ts
|
|
797
|
+
/**
|
|
798
|
+
* Owner-only filesystem writes for everything under the config directory.
|
|
799
|
+
*
|
|
800
|
+
* That directory holds the SSO browser profile, the MSAL cache, optional stored
|
|
801
|
+
* credentials (password *and* TOTP seed) and a debug log that under `M365_TRACE`
|
|
802
|
+
* contains the access token. None of it should be readable by other local users,
|
|
803
|
+
* whatever the umask was when it was first created — so each helper also tightens
|
|
804
|
+
* a file or directory that already exists with looser permissions.
|
|
805
|
+
*/
|
|
806
|
+
const DIR_MODE = 448;
|
|
807
|
+
const FILE_MODE = 384;
|
|
808
|
+
/** Best effort: Windows ignores POSIX modes, and a file we do not own cannot be changed. */
|
|
809
|
+
function tighten(path, mode) {
|
|
810
|
+
if (process.platform === "win32") return;
|
|
811
|
+
try {
|
|
812
|
+
chmodSync(path, mode);
|
|
813
|
+
} catch {}
|
|
814
|
+
}
|
|
815
|
+
/** The canonical path, following symlinks — or the plain resolved one if it does not exist. */
|
|
816
|
+
function canonical(path) {
|
|
817
|
+
try {
|
|
818
|
+
return realpathSync(path);
|
|
819
|
+
} catch {
|
|
820
|
+
return resolve(path);
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
/**
|
|
824
|
+
* Is `dir` the user's home directory, one of its ancestors, or the filesystem root?
|
|
825
|
+
*
|
|
826
|
+
* Those are shared with every other tool the user runs, so they are never ours to
|
|
827
|
+
* chmod — even when `M365_CONFIG_DIR=$HOME` makes one of them our config directory.
|
|
828
|
+
* Compared by real path, so a symlink on either side cannot slip past.
|
|
829
|
+
*/
|
|
830
|
+
function isHomeOrAbove(dir) {
|
|
831
|
+
const target = canonical(dir);
|
|
832
|
+
if (target === parse(target).root) return true;
|
|
833
|
+
const home = canonical(homedir());
|
|
834
|
+
return home === target || home.startsWith(target.endsWith(sep) ? target : `${target}${sep}`);
|
|
835
|
+
}
|
|
836
|
+
/**
|
|
837
|
+
* Create `dir` (and parents) owner-only, and tighten `dir` itself if it already
|
|
838
|
+
* existed — unless it is the home directory or above, which stays as it is.
|
|
839
|
+
*/
|
|
840
|
+
function ensurePrivateDir(dir) {
|
|
841
|
+
mkdirSync(dir, {
|
|
842
|
+
recursive: true,
|
|
843
|
+
mode: DIR_MODE
|
|
844
|
+
});
|
|
845
|
+
if (!isHomeOrAbove(dir)) tighten(dir, DIR_MODE);
|
|
846
|
+
}
|
|
847
|
+
/**
|
|
848
|
+
* Make sure `file`'s directory exists. A directory we create is owner-only; an
|
|
849
|
+
* existing one is tightened only when it is our config directory — a path
|
|
850
|
+
* overridden to `~/cache.json` must not chmod the user's home.
|
|
851
|
+
*/
|
|
852
|
+
function preparePrivateParent(file) {
|
|
853
|
+
const dir = dirname(file);
|
|
854
|
+
if (resolve(dir) === resolve(CONFIG_DIR)) ensurePrivateDir(dir);
|
|
855
|
+
else mkdirSync(dir, {
|
|
856
|
+
recursive: true,
|
|
857
|
+
mode: DIR_MODE
|
|
858
|
+
});
|
|
859
|
+
}
|
|
860
|
+
/** Write `file` owner-only, creating its directory owner-only too. */
|
|
861
|
+
function writePrivateFile(file, contents) {
|
|
862
|
+
preparePrivateParent(file);
|
|
863
|
+
writeFileSync(file, contents, { mode: FILE_MODE });
|
|
864
|
+
tighten(file, FILE_MODE);
|
|
865
|
+
}
|
|
866
|
+
/** Append to `file` owner-only, creating its directory owner-only too. */
|
|
867
|
+
function appendPrivateFile(file, contents) {
|
|
868
|
+
preparePrivateParent(file);
|
|
869
|
+
appendFileSync(file, contents, { mode: FILE_MODE });
|
|
870
|
+
tighten(file, FILE_MODE);
|
|
871
|
+
}
|
|
872
|
+
/**
|
|
873
|
+
* An appender for a file written often, like the debug log.
|
|
874
|
+
*
|
|
875
|
+
* The first write goes through `appendPrivateFile` — directory created, both
|
|
876
|
+
* tightened. Later writes only append, so a log line per stream delta does not pay
|
|
877
|
+
* for a mkdir and two chmods each time on opencode's event loop. If the file has
|
|
878
|
+
* disappeared since (a user clearing the log), the next write does the full setup
|
|
879
|
+
* again rather than recreating it with whatever the umask allows.
|
|
880
|
+
*/
|
|
881
|
+
function createPrivateAppender(file) {
|
|
882
|
+
let ready = false;
|
|
883
|
+
return (contents) => {
|
|
884
|
+
if (ready) {
|
|
885
|
+
let fd;
|
|
886
|
+
try {
|
|
887
|
+
fd = openSync(file, constants.O_WRONLY | constants.O_APPEND);
|
|
888
|
+
} catch {
|
|
889
|
+
ready = false;
|
|
890
|
+
}
|
|
891
|
+
if (fd !== void 0) {
|
|
892
|
+
try {
|
|
893
|
+
writeSync(fd, contents);
|
|
894
|
+
} finally {
|
|
895
|
+
closeSync(fd);
|
|
896
|
+
}
|
|
897
|
+
return;
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
appendPrivateFile(file, contents);
|
|
901
|
+
ready = true;
|
|
902
|
+
};
|
|
903
|
+
}
|
|
904
|
+
//#endregion
|
|
792
905
|
//#region src/log.ts
|
|
793
906
|
const DEBUG = process.env.M365_DEBUG === "1" || process.env.M365_TRACE === "1";
|
|
794
907
|
const TRACE = process.env.M365_TRACE === "1";
|
|
795
908
|
const TO_STDOUT = process.env.M365_LOG_STDOUT === "1";
|
|
796
|
-
|
|
909
|
+
/**
|
|
910
|
+
* One appender for every scope, since they all share the file. Owner-only (under
|
|
911
|
+
* M365_TRACE this log carries the access token), with the mkdir and chmods paid on
|
|
912
|
+
* the first line only — this runs per stream delta on opencode's event loop.
|
|
913
|
+
*/
|
|
914
|
+
const appendLog = createPrivateAppender(LOG_FILE);
|
|
797
915
|
/** Truncate a payload for the log unless full tracing is on. */
|
|
798
916
|
function trunc(value, max = 400) {
|
|
799
917
|
const text = typeof value === "string" ? value : JSON.stringify(value);
|
|
@@ -812,11 +930,7 @@ function createLogger(scope) {
|
|
|
812
930
|
const line = `${(/* @__PURE__ */ new Date()).toISOString()} [${level}] [${scope}] ${parts.map((p) => trunc(p)).join(" ")}`;
|
|
813
931
|
if (TO_STDOUT) process.stdout.write(`${line}\n`);
|
|
814
932
|
try {
|
|
815
|
-
|
|
816
|
-
mkdirSync(dirname(LOG_FILE) || CONFIG_DIR, { recursive: true });
|
|
817
|
-
ready = true;
|
|
818
|
-
}
|
|
819
|
-
appendFileSync(LOG_FILE, `${line}\n`);
|
|
933
|
+
appendLog(`${line}\n`);
|
|
820
934
|
} catch {}
|
|
821
935
|
};
|
|
822
936
|
return {
|
|
@@ -878,9 +992,7 @@ function createCachePlugin(file = CACHE_FILE) {
|
|
|
878
992
|
async afterCacheAccess(context) {
|
|
879
993
|
if (!context.cacheHasChanged) return;
|
|
880
994
|
try {
|
|
881
|
-
|
|
882
|
-
writeFileSync(file, context.tokenCache.serialize(), { mode: 384 });
|
|
883
|
-
chmodSync(file, 384);
|
|
995
|
+
writePrivateFile(file, context.tokenCache.serialize());
|
|
884
996
|
} catch (error) {
|
|
885
997
|
log$2.warn("could not persist the token cache", String(error));
|
|
886
998
|
}
|
|
@@ -892,7 +1004,7 @@ function createTokenClient(options = {}) {
|
|
|
892
1004
|
const cache = /* @__PURE__ */ new Map();
|
|
893
1005
|
async function client() {
|
|
894
1006
|
if (app) return app;
|
|
895
|
-
const { PublicClientApplication } = await import("./dist-
|
|
1007
|
+
const { PublicClientApplication } = await import("./dist-BGVW-hOf.mjs");
|
|
896
1008
|
app = new PublicClientApplication({
|
|
897
1009
|
auth: {
|
|
898
1010
|
clientId: CLIENT_ID,
|
|
@@ -3007,7 +3119,7 @@ var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
3007
3119
|
const http$1 = __require("http");
|
|
3008
3120
|
const net = __require("net");
|
|
3009
3121
|
const tls = __require("tls");
|
|
3010
|
-
const { randomBytes, createHash: createHash$2 } = __require("crypto");
|
|
3122
|
+
const { randomBytes: randomBytes$1, createHash: createHash$2 } = __require("crypto");
|
|
3011
3123
|
const { Duplex: Duplex$2, Readable } = __require("stream");
|
|
3012
3124
|
const { URL: URL$1 } = __require("url");
|
|
3013
3125
|
const PerMessageDeflate = require_permessage_deflate();
|
|
@@ -3576,7 +3688,7 @@ var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
3576
3688
|
}
|
|
3577
3689
|
}
|
|
3578
3690
|
const defaultPort = isSecure ? 443 : 80;
|
|
3579
|
-
const key = randomBytes(16).toString("base64");
|
|
3691
|
+
const key = randomBytes$1(16).toString("base64");
|
|
3580
3692
|
const request = isSecure ? https.request : http$1.request;
|
|
3581
3693
|
const protocolSet = /* @__PURE__ */ new Set();
|
|
3582
3694
|
let perMessageDeflate;
|
|
@@ -9299,7 +9411,7 @@ const initializer = (inst, issues) => {
|
|
|
9299
9411
|
const ZodRealError = /*@__PURE__*/ $constructor("ZodError", initializer, void 0, { Parent: Error });
|
|
9300
9412
|
//#endregion
|
|
9301
9413
|
//#region node_modules/zod/v4/classic/parse.js
|
|
9302
|
-
const parse = /* @__PURE__ */ _parse(ZodRealError);
|
|
9414
|
+
const parse$1 = /* @__PURE__ */ _parse(ZodRealError);
|
|
9303
9415
|
const parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
|
|
9304
9416
|
const safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
|
|
9305
9417
|
const safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
|
|
@@ -9431,7 +9543,7 @@ const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => {
|
|
|
9431
9543
|
own(this, "~standard", value);
|
|
9432
9544
|
},
|
|
9433
9545
|
parse: function _parse(data, params) {
|
|
9434
|
-
return parse(this, data, params, { callee: _parse });
|
|
9546
|
+
return parse$1(this, data, params, { callee: _parse });
|
|
9435
9547
|
},
|
|
9436
9548
|
parseAsync: async function _parseAsync(data, params) {
|
|
9437
9549
|
return await parseAsync(this, data, params, { callee: _parseAsync });
|
|
@@ -10232,8 +10344,11 @@ const ChatCompletionRequest = object({
|
|
|
10232
10344
|
/**
|
|
10233
10345
|
* Maps an OpenAI client's stateless history onto stateful M365 conversations.
|
|
10234
10346
|
*
|
|
10235
|
-
* Identity is the
|
|
10236
|
-
*
|
|
10347
|
+
* Identity is the harness's session id when it names one (the opencode 2 plugin
|
|
10348
|
+
* does). Otherwise it is a sha256 of the system prompt plus the first user message:
|
|
10349
|
+
* an agent loop keeps resending both, so together they are a stable handle for "this
|
|
10350
|
+
* is still the same task" — and the system prompt carries the working directory, so
|
|
10351
|
+
* the same opener in two repos stays apart.
|
|
10237
10352
|
*/
|
|
10238
10353
|
var ConversationPool = class {
|
|
10239
10354
|
conversations = /* @__PURE__ */ new Map();
|
|
@@ -10241,9 +10356,9 @@ var ConversationPool = class {
|
|
|
10241
10356
|
constructor(options = {}) {
|
|
10242
10357
|
this.maxIdleMs = options.maxIdleMs ?? 36e5;
|
|
10243
10358
|
}
|
|
10244
|
-
resolve(messages) {
|
|
10359
|
+
resolve(messages, options = {}) {
|
|
10245
10360
|
this.evictStale();
|
|
10246
|
-
const key = fingerprint(messages);
|
|
10361
|
+
const key = options.sessionId ? `s:${createHash("sha256").update(options.sessionId).digest("hex")}` : fingerprint(messages);
|
|
10247
10362
|
const existing = this.conversations.get(key);
|
|
10248
10363
|
if (existing) {
|
|
10249
10364
|
if (messages.length < existing.sentMessageCount) existing.sentMessageCount = 0;
|
|
@@ -10267,11 +10382,11 @@ var ConversationPool = class {
|
|
|
10267
10382
|
}
|
|
10268
10383
|
};
|
|
10269
10384
|
function fingerprint(messages) {
|
|
10385
|
+
const system = messages.filter((message) => message.role === "system" || message.role === "developer").map(contentOf).join("\n");
|
|
10270
10386
|
const firstUser = messages.find((message) => message.role === "user");
|
|
10271
|
-
const
|
|
10272
|
-
|
|
10273
|
-
|
|
10274
|
-
return `c${hash}`;
|
|
10387
|
+
const hash = createHash("sha256");
|
|
10388
|
+
for (const part of [system, firstUser ? contentOf(firstUser) : ""]) hash.update(`${part.length}:${part}`);
|
|
10389
|
+
return `c:${hash.digest("hex")}`;
|
|
10275
10390
|
}
|
|
10276
10391
|
/** Message content as plain text, flattening the array-of-parts form. */
|
|
10277
10392
|
function contentOf(message) {
|
|
@@ -10537,8 +10652,11 @@ function firstLine(text) {
|
|
|
10537
10652
|
*
|
|
10538
10653
|
* Small on purpose: `node:http` rather than a framework, because this runs inside
|
|
10539
10654
|
* opencode's own process and every dependency here is one opencode has to install.
|
|
10540
|
-
* It binds loopback only
|
|
10541
|
-
*
|
|
10655
|
+
* It binds loopback only, and loopback is not a trust boundary: every browser tab on
|
|
10656
|
+
* the machine can reach it too. So every request must also carry a per-launch secret
|
|
10657
|
+
* (`Authorization: Bearer <apiKey>`), must name a loopback `Host` (DNS rebinding), and
|
|
10658
|
+
* must not come from a browser `Origin` the caller did not allow. No CORS headers are
|
|
10659
|
+
* ever sent — opencode is a server-side client and needs none.
|
|
10542
10660
|
*/
|
|
10543
10661
|
const log = createLogger("server");
|
|
10544
10662
|
/** See the warning in `handleChatCompletion`; this keeps it to once per process. */
|
|
@@ -10553,9 +10671,33 @@ let warnedAboutToolSelection = false;
|
|
|
10553
10671
|
* M365 conversation per session, which is precisely the throttle signature.
|
|
10554
10672
|
*/
|
|
10555
10673
|
const AUX_REQUEST_KIND_HEADER = "x-m365-request-kind";
|
|
10674
|
+
/**
|
|
10675
|
+
* Header a harness uses to name the session a request belongs to, so two sessions
|
|
10676
|
+
* that happen to open with the same message never share an M365 conversation.
|
|
10677
|
+
* Lowercase for the same reason as {@link AUX_REQUEST_KIND_HEADER}.
|
|
10678
|
+
*/
|
|
10679
|
+
const SESSION_ID_HEADER = "x-m365-session-id";
|
|
10680
|
+
/** Generous: a long agent history is a few MB of JSON; this only stops abuse. */
|
|
10681
|
+
const DEFAULT_MAX_BODY_BYTES = 33554432;
|
|
10682
|
+
const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
|
|
10683
|
+
"127.0.0.1",
|
|
10684
|
+
"::1",
|
|
10685
|
+
"localhost"
|
|
10686
|
+
]);
|
|
10687
|
+
/** A fresh per-launch secret: 32 random bytes, base64url. */
|
|
10688
|
+
function generateApiKey() {
|
|
10689
|
+
return randomBytes(32).toString("base64url");
|
|
10690
|
+
}
|
|
10556
10691
|
async function startServer(deps) {
|
|
10557
10692
|
const pool = new ConversationPool();
|
|
10558
10693
|
const host = deps.host ?? "127.0.0.1";
|
|
10694
|
+
if (!LOOPBACK_HOSTS.has(host)) throw new Error(`Refusing to bind ${host}: the proxy only listens on loopback (127.0.0.1, ::1, localhost)`);
|
|
10695
|
+
const apiKey = deps.apiKey || generateApiKey();
|
|
10696
|
+
if (deps.allowedOrigins !== void 0) process.emitWarning("startServer's allowedOrigins option is ignored: the proxy refuses every request carrying an Origin, since browsers cannot use it.", {
|
|
10697
|
+
type: "DeprecationWarning",
|
|
10698
|
+
code: "M365_ALLOWED_ORIGINS"
|
|
10699
|
+
});
|
|
10700
|
+
const maxBodyBytes = deps.maxBodyBytes ?? 33554432;
|
|
10559
10701
|
let agentPromise;
|
|
10560
10702
|
const agentId = async () => {
|
|
10561
10703
|
if (!deps.resolveAgent) return null;
|
|
@@ -10565,11 +10707,15 @@ async function startServer(deps) {
|
|
|
10565
10707
|
});
|
|
10566
10708
|
return agentPromise;
|
|
10567
10709
|
};
|
|
10710
|
+
const portOf = () => server.address().port;
|
|
10568
10711
|
const server = createServer((request, response) => {
|
|
10569
10712
|
handle(request, response, {
|
|
10570
10713
|
deps,
|
|
10571
10714
|
pool,
|
|
10572
|
-
agentId
|
|
10715
|
+
agentId,
|
|
10716
|
+
apiKey,
|
|
10717
|
+
maxBodyBytes,
|
|
10718
|
+
port: portOf()
|
|
10573
10719
|
}).catch((error) => {
|
|
10574
10720
|
log.error("unhandled request failure", String(error));
|
|
10575
10721
|
sendError(response, 500, "internal_error", String(error));
|
|
@@ -10581,25 +10727,60 @@ async function startServer(deps) {
|
|
|
10581
10727
|
});
|
|
10582
10728
|
const { port } = server.address();
|
|
10583
10729
|
return {
|
|
10584
|
-
url: `http://${host}:${port}`,
|
|
10730
|
+
url: `http://${host.includes(":") ? `[${host}]` : host}:${port}`,
|
|
10585
10731
|
port,
|
|
10732
|
+
apiKey,
|
|
10586
10733
|
close: () => new Promise((resolve) => {
|
|
10587
10734
|
server.closeAllConnections?.();
|
|
10588
10735
|
server.close(() => resolve());
|
|
10589
10736
|
})
|
|
10590
10737
|
};
|
|
10591
10738
|
}
|
|
10739
|
+
var PayloadTooLargeError = class extends Error {};
|
|
10740
|
+
/**
|
|
10741
|
+
* Is `Host` one of the names this listener is actually reachable by?
|
|
10742
|
+
*
|
|
10743
|
+
* A DNS-rebound page talks to 127.0.0.1 while its `Host` still names the attacker's
|
|
10744
|
+
* domain, so anything but a loopback name on our own port is refused.
|
|
10745
|
+
*/
|
|
10746
|
+
function isLoopbackHost(header, port) {
|
|
10747
|
+
if (!header) return false;
|
|
10748
|
+
const match = /^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/.exec(header.trim().toLowerCase());
|
|
10749
|
+
if (!match) return false;
|
|
10750
|
+
const name = match[1].replace(/^\[|\]$/g, "");
|
|
10751
|
+
return LOOPBACK_HOSTS.has(name) && Number(match[2] ?? 80) === port;
|
|
10752
|
+
}
|
|
10753
|
+
/** Constant-time check of `Authorization: Bearer <key>`. */
|
|
10754
|
+
function hasApiKey(header, apiKey) {
|
|
10755
|
+
const match = /^Bearer\s+(.+)$/i.exec(header ?? "");
|
|
10756
|
+
if (!match) return false;
|
|
10757
|
+
const given = Buffer.from(match[1].trim());
|
|
10758
|
+
const expected = Buffer.from(apiKey);
|
|
10759
|
+
return given.length === expected.length && timingSafeEqual(given, expected);
|
|
10760
|
+
}
|
|
10592
10761
|
async function handle(request, response, context) {
|
|
10593
10762
|
const url = new URL(request.url ?? "/", "http://localhost");
|
|
10594
10763
|
const method = (request.method ?? "GET").toUpperCase();
|
|
10764
|
+
if (!isLoopbackHost(request.headers.host, context.port)) {
|
|
10765
|
+
sendError(response, 403, "forbidden", "Host must be a loopback address");
|
|
10766
|
+
return;
|
|
10767
|
+
}
|
|
10768
|
+
if (request.headers.origin !== void 0) {
|
|
10769
|
+
sendError(response, 403, "forbidden", "Browser origins may not use this proxy");
|
|
10770
|
+
return;
|
|
10771
|
+
}
|
|
10595
10772
|
if (method === "OPTIONS") {
|
|
10596
|
-
response
|
|
10773
|
+
sendError(response, 403, "forbidden", "CORS is not supported");
|
|
10597
10774
|
return;
|
|
10598
10775
|
}
|
|
10599
10776
|
if (method === "GET" && url.pathname === "/health") {
|
|
10600
10777
|
sendJson(response, 200, { status: "ok" });
|
|
10601
10778
|
return;
|
|
10602
10779
|
}
|
|
10780
|
+
if (!hasApiKey(request.headers.authorization, context.apiKey)) {
|
|
10781
|
+
sendError(response, 401, "invalid_api_key", "Missing or wrong proxy secret. Send `Authorization: Bearer <key>` with the key the proxy printed or was given (M365_PROXY_KEY).");
|
|
10782
|
+
return;
|
|
10783
|
+
}
|
|
10603
10784
|
if (method === "GET" && url.pathname === "/v1/models") {
|
|
10604
10785
|
sendJson(response, 200, {
|
|
10605
10786
|
object: "list",
|
|
@@ -10621,8 +10802,13 @@ async function handle(request, response, context) {
|
|
|
10621
10802
|
async function handleChatCompletion(request, response, context) {
|
|
10622
10803
|
let body;
|
|
10623
10804
|
try {
|
|
10624
|
-
body = ChatCompletionRequest.parse(JSON.parse(await readBody(request)));
|
|
10805
|
+
body = ChatCompletionRequest.parse(JSON.parse(await readBody(request, context.maxBodyBytes)));
|
|
10625
10806
|
} catch (error) {
|
|
10807
|
+
if (error instanceof PayloadTooLargeError) {
|
|
10808
|
+
sendError(response, 413, "request_too_large", error.message);
|
|
10809
|
+
request.resume();
|
|
10810
|
+
return;
|
|
10811
|
+
}
|
|
10626
10812
|
sendError(response, 400, "invalid_request_error", String(error?.message ?? error));
|
|
10627
10813
|
return;
|
|
10628
10814
|
}
|
|
@@ -10641,7 +10827,22 @@ async function handleChatCompletion(request, response, context) {
|
|
|
10641
10827
|
respondWithTitle(response, body, model.id);
|
|
10642
10828
|
return;
|
|
10643
10829
|
}
|
|
10644
|
-
const
|
|
10830
|
+
const sessionHeader = request.headers[SESSION_ID_HEADER];
|
|
10831
|
+
const sessionId = typeof sessionHeader === "string" && sessionHeader !== "" ? sessionHeader : void 0;
|
|
10832
|
+
const conversation = context.pool.resolve(body.messages, sessionId ? { sessionId } : {});
|
|
10833
|
+
const previous = conversation.turn ?? Promise.resolve();
|
|
10834
|
+
let release;
|
|
10835
|
+
const current = new Promise((resolve) => release = resolve);
|
|
10836
|
+
conversation.turn = previous.then(() => current);
|
|
10837
|
+
await previous;
|
|
10838
|
+
try {
|
|
10839
|
+
await runTurn(request, response, context, body, conversation, model, tools);
|
|
10840
|
+
} finally {
|
|
10841
|
+
release();
|
|
10842
|
+
}
|
|
10843
|
+
}
|
|
10844
|
+
async function runTurn(request, response, context, body, conversation, model, tools) {
|
|
10845
|
+
if (body.messages.length < conversation.sentMessageCount) conversation.sentMessageCount = 0;
|
|
10645
10846
|
conversation.session ??= new CopilotSession({
|
|
10646
10847
|
getToken: context.deps.getToken,
|
|
10647
10848
|
...context.deps.endpoint ? { endpoint: context.deps.endpoint } : {}
|
|
@@ -10663,7 +10864,7 @@ async function handleChatCompletion(request, response, context) {
|
|
|
10663
10864
|
signal: abort.signal,
|
|
10664
10865
|
...canStreamText ? { onDelta: (chunk) => response.write(streamChunk(streamId, model.id, { content: chunk })) } : {}
|
|
10665
10866
|
});
|
|
10666
|
-
conversation.sentMessageCount = body.messages.length;
|
|
10867
|
+
conversation.sentMessageCount = body.messages.length + 1;
|
|
10667
10868
|
if (!streaming) {
|
|
10668
10869
|
sendJson(response, 200, buildCompletion(result, {
|
|
10669
10870
|
model: model.id,
|
|
@@ -10753,23 +10954,12 @@ function startSse(response) {
|
|
|
10753
10954
|
response.writeHead(200, {
|
|
10754
10955
|
"Content-Type": "text/event-stream",
|
|
10755
10956
|
"Cache-Control": "no-cache",
|
|
10756
|
-
Connection: "keep-alive"
|
|
10757
|
-
...corsHeaders()
|
|
10957
|
+
Connection: "keep-alive"
|
|
10758
10958
|
});
|
|
10759
10959
|
}
|
|
10760
|
-
function corsHeaders() {
|
|
10761
|
-
return {
|
|
10762
|
-
"Access-Control-Allow-Origin": "*",
|
|
10763
|
-
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
|
10764
|
-
"Access-Control-Allow-Headers": "Content-Type, Authorization"
|
|
10765
|
-
};
|
|
10766
|
-
}
|
|
10767
10960
|
function sendJson(response, status, body) {
|
|
10768
10961
|
const payload = JSON.stringify(body);
|
|
10769
|
-
response.writeHead(status, {
|
|
10770
|
-
"Content-Type": "application/json",
|
|
10771
|
-
...corsHeaders()
|
|
10772
|
-
});
|
|
10962
|
+
response.writeHead(status, { "Content-Type": "application/json" });
|
|
10773
10963
|
response.end(payload);
|
|
10774
10964
|
}
|
|
10775
10965
|
function sendError(response, status, code, message) {
|
|
@@ -10780,10 +10970,17 @@ function sendError(response, status, code, message) {
|
|
|
10780
10970
|
code
|
|
10781
10971
|
} });
|
|
10782
10972
|
}
|
|
10783
|
-
async function readBody(request) {
|
|
10973
|
+
async function readBody(request, limit) {
|
|
10974
|
+
const declared = Number(request.headers["content-length"]);
|
|
10975
|
+
if (Number.isFinite(declared) && declared > limit) throw new PayloadTooLargeError(`Request body exceeds ${limit} bytes`);
|
|
10784
10976
|
const chunks = [];
|
|
10785
|
-
|
|
10977
|
+
let size = 0;
|
|
10978
|
+
for await (const chunk of request) {
|
|
10979
|
+
size += chunk.length;
|
|
10980
|
+
if (size > limit) throw new PayloadTooLargeError(`Request body exceeds ${limit} bytes`);
|
|
10981
|
+
chunks.push(chunk);
|
|
10982
|
+
}
|
|
10786
10983
|
return Buffer.concat(chunks).toString("utf8");
|
|
10787
10984
|
}
|
|
10788
10985
|
//#endregion
|
|
10789
|
-
export {
|
|
10986
|
+
export { resolveOptions as A, SECRETS_FILE as C, buildModelInfos as D, applyPluginConfig as E, __require as F, __toESM as I, LOCAL_TITLE_MODEL as M, isLocalModel as N, buildProviderInfo as O, __commonJSMin as P, CONFIG_DIR as S, PROVIDER_ID as T, createLogger as _, startServer as a, AGENT_FILE as b, AUTHORITY as c, POWERPLATFORM_SCOPE as d, REDIRECT_URI as f, createTokenClient as g, createCachePlugin as h, generateApiKey as i, DEFAULT_MODEL as j, mergeOpencodeConfig as k, BAP_SCOPE as l, authCodeFromUrl as m, DEFAULT_MAX_BODY_BYTES as n, object as o, SYDNEY_SCOPES as p, SESSION_ID_HEADER as r, string as s, AUX_REQUEST_KIND_HEADER as t, CLIENT_ID as u, ensurePrivateDir as v, PLUGIN_ID as w, CACHE_FILE as x, writePrivateFile as y };
|
package/dist/server.d.mts
CHANGED
|
@@ -21,6 +21,12 @@ export declare const DEFAULT_MODEL = "gpt-5.5-think-deeper";
|
|
|
21
21
|
* M365 conversation per session, which is precisely the throttle signature.
|
|
22
22
|
*/
|
|
23
23
|
export declare const AUX_REQUEST_KIND_HEADER = "x-m365-request-kind";
|
|
24
|
+
/**
|
|
25
|
+
* Header a harness uses to name the session a request belongs to, so two sessions
|
|
26
|
+
* that happen to open with the same message never share an M365 conversation.
|
|
27
|
+
* Lowercase for the same reason as {@link AUX_REQUEST_KIND_HEADER}.
|
|
28
|
+
*/
|
|
29
|
+
export declare const SESSION_ID_HEADER = "x-m365-session-id";
|
|
24
30
|
export interface ServerDeps {
|
|
25
31
|
/** Supplies a Sydney chat token. */
|
|
26
32
|
getToken: () => Promise<string>;
|
|
@@ -49,12 +55,35 @@ export interface ServerDeps {
|
|
|
49
55
|
*/
|
|
50
56
|
leanSystemPrompt?: string;
|
|
51
57
|
port?: number;
|
|
58
|
+
/** Loopback only: `127.0.0.1` (the default), `::1` or `localhost`. Anything else throws. */
|
|
52
59
|
host?: string;
|
|
60
|
+
/**
|
|
61
|
+
* The bearer secret every request must carry. Omit it and a fresh 32-byte random
|
|
62
|
+
* one is generated per launch, which is what the in-process plugin wants: it hands
|
|
63
|
+
* the key straight to opencode's provider config and nobody else ever sees it.
|
|
64
|
+
*/
|
|
65
|
+
apiKey?: string;
|
|
66
|
+
/**
|
|
67
|
+
* @deprecated Ignored, with a warning. Every request carrying an `Origin` is refused:
|
|
68
|
+
* opencode sends none, so one means a web page — and no allowlist could have made
|
|
69
|
+
* the proxy usable from a page anyway, since the bearer header forces a CORS
|
|
70
|
+
* preflight and preflights are always refused. Kept only so an old caller that
|
|
71
|
+
* still passes it keeps starting.
|
|
72
|
+
*/
|
|
73
|
+
allowedOrigins?: readonly string[];
|
|
74
|
+
/** Largest request body accepted, in bytes. */
|
|
75
|
+
maxBodyBytes?: number;
|
|
53
76
|
}
|
|
54
77
|
export interface ProxyHandle {
|
|
55
78
|
url: string;
|
|
56
79
|
port: number;
|
|
80
|
+
/** The bearer secret a client must send. */
|
|
81
|
+
apiKey: string;
|
|
57
82
|
close(): Promise<void>;
|
|
58
83
|
}
|
|
84
|
+
/** Generous: a long agent history is a few MB of JSON; this only stops abuse. */
|
|
85
|
+
export declare const DEFAULT_MAX_BODY_BYTES: number;
|
|
86
|
+
/** A fresh per-launch secret: 32 random bytes, base64url. */
|
|
87
|
+
export declare function generateApiKey(): string;
|
|
59
88
|
export declare function startServer(deps: ServerDeps): Promise<ProxyHandle>;
|
|
60
89
|
//#endregion
|
package/dist/server.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { AUX_REQUEST_KIND_HEADER, DEFAULT_MODEL, startServer };
|
|
1
|
+
import { a as startServer, i as generateApiKey, j as DEFAULT_MODEL, n as DEFAULT_MAX_BODY_BYTES, r as SESSION_ID_HEADER, t as AUX_REQUEST_KIND_HEADER } from "./server-Buz1ZIg5.mjs";
|
|
2
|
+
export { AUX_REQUEST_KIND_HEADER, DEFAULT_MAX_BODY_BYTES, DEFAULT_MODEL, SESSION_ID_HEADER, generateApiKey, startServer };
|