opencode-m365-copilot 0.3.5 → 2.0.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,17 +1,17 @@
1
1
  import { createRequire } from "node:module";
2
- import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
3
- import { appendFileSync, chmodSync, closeSync, constants, mkdirSync, openSync, readFileSync, realpathSync, writeFileSync, writeSync } from "node:fs";
4
2
  import { homedir } from "node:os";
5
3
  import { dirname, join, parse, resolve, sep } from "node:path";
4
+ import { appendFileSync, chmodSync, closeSync, constants, mkdirSync, openSync, readFileSync, realpathSync, writeFileSync, writeSync } from "node:fs";
5
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
6
6
  import { createServer } from "node:http";
7
- //#region \0rolldown/runtime.js
7
+ // \0rolldown/runtime.js
8
8
  var __create = Object.create;
9
9
  var __defProp = Object.defineProperty;
10
10
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
11
11
  var __getOwnPropNames = Object.getOwnPropertyNames;
12
12
  var __getProtoOf = Object.getPrototypeOf;
13
13
  var __hasOwnProp = Object.prototype.hasOwnProperty;
14
- var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
14
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod, mod.exports), cb = null), mod.exports);
15
15
  var __copyProps = (to, from, except, desc) => {
16
16
  if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
17
17
  key = keys[i];
@@ -27,8 +27,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
27
27
  enumerable: true
28
28
  }) : target, mod));
29
29
  var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
30
- //#endregion
31
- //#region src/models.ts
30
+ // src/models.ts
32
31
  /**
33
32
  * Advertised context/output limits.
34
33
  *
@@ -43,10 +42,11 @@ const OUTPUT_TOKENS = 128e3;
43
42
  * A synthetic model served entirely by our own proxy — it never opens a WebSocket
44
43
  * to M365.
45
44
  *
46
- * This exists because opencode's `small_model` (session title generation) defaults
47
- * to the main model. That would open a *second* M365 conversation for every session,
45
+ * This exists because a harness titles each session with a model call, by default on
46
+ * the main model. That would open a *second* M365 conversation for every session,
48
47
  * which is precisely the thread-rate throttle signature: the limit tracks
49
- * conversations started, not messages. Pointing `small_model` here costs nothing.
48
+ * conversations started, not messages. Any client can select this model by id; the
49
+ * opencode plugin instead marks its title requests so the proxy answers them here.
50
50
  */
51
51
  const LOCAL_TITLE_MODEL = "local-title";
52
52
  /**
@@ -119,8 +119,7 @@ function isLocalModel(id) {
119
119
  function listModelIds() {
120
120
  return MODELS.map((model) => model.id);
121
121
  }
122
- //#endregion
123
- //#region src/fenced.ts
122
+ // src/fenced.ts
124
123
  /** Info strings we accept as "this is a shell block", beyond the tool's own name. */
125
124
  const SHELL_FENCE_INFOS = /* @__PURE__ */ new Set([
126
125
  "bash",
@@ -445,8 +444,7 @@ function coerce(value, type) {
445
444
  default: return value;
446
445
  }
447
446
  }
448
- //#endregion
449
- //#region src/config.ts
447
+ // src/config.ts
450
448
  /**
451
449
  * opencode configuration: the provider entry, and the lean tool profile that makes
452
450
  * M365 willing to engage at all.
@@ -460,10 +458,8 @@ const PROVIDER_ID = "m365";
460
458
  * The plugin's own id.
461
459
  *
462
460
  * opencode 2 requires one, scopes the plugin's storage by it, and names the plugin
463
- * by it in `plugin list` and diagnostics. opencode 1 from 1.18.29 registers an object
464
- * entrypoint under it too, so the two APIs must agree — `plugin-entry.test.ts` checks
465
- * that they do. Changing it is not cosmetic: it orphans anything stored under the old
466
- * one.
461
+ * by it in `plugin list` and diagnostics. Changing it is not cosmetic: it orphans
462
+ * anything stored under the old one.
467
463
  */
468
464
  const PLUGIN_ID = "m365-copilot";
469
465
  /**
@@ -485,33 +481,13 @@ const LEAN_TOOLS = [
485
481
  "grep"
486
482
  ];
487
483
  /**
488
- * opencode built-ins we switch off in lean mode.
489
- *
490
- * Each one is a tool block in the injected prompt, and the count is what trips the
491
- * filter. `glob`/`grep` overlap and `bash` can do both; `webfetch`/`websearch` are
492
- * rarely load-bearing for a coding turn; `todowrite`/`question`/`skill` are harness
493
- * ergonomics rather than capability.
494
- */
495
- const DISABLED_TOOLS = [
496
- "glob",
497
- "lsp",
498
- "patch",
499
- "skill",
500
- "todowrite",
501
- "todoread",
502
- "webfetch",
503
- "websearch",
504
- "question",
505
- "task"
506
- ];
507
- /**
508
484
  * Cut a harness's toolset down to something M365 will engage with.
509
485
  *
510
- * This is the enforcement point, and it has to be. opencode's own `tools` config —
511
- * which the plugin also sets — is resolved into the config but **not applied to the
512
- * request**: verified against 1.18.18, where a config disabling eight tools still
513
- * produced a request offering all nine. The proxy sees the final request, so it is
514
- * the only place the trim reliably happens.
486
+ * This is the enforcement point. opencode 1's own `tools` config was resolved into the
487
+ * config but **not applied to the request** (verified against 1.18.18: a config
488
+ * disabling eight tools still produced a request offering all nine). opencode 2's
489
+ * `tool.transform` has not been measured against a live tenant. The proxy sees the
490
+ * final request whatever the harness does, so the trim lives here.
515
491
  *
516
492
  * Two rules, in order:
517
493
  * 1. Keep the tools we recognise as load-bearing for a coding loop.
@@ -571,40 +547,6 @@ function resolveOptions(raw) {
571
547
  apiKey: typeof options.apiKey === "string" && options.apiKey !== "" ? options.apiKey : void 0
572
548
  };
573
549
  }
574
- /** `{ bash: true, ..., webfetch: false, ... }` — opencode's `tools` config shape. */
575
- function buildToolProfile() {
576
- const profile = {};
577
- for (const tool of LEAN_TOOLS) profile[tool] = true;
578
- for (const tool of DISABLED_TOOLS) profile[tool] = false;
579
- return profile;
580
- }
581
- /** The `provider.m365` entry pointing opencode at our local OpenAI-compatible proxy. */
582
- function buildProviderConfig(baseUrl, apiKey) {
583
- const models = {};
584
- for (const model of MODELS) models[model.id] = {
585
- name: model.name,
586
- tool_call: !isLocalModel(model.id),
587
- reasoning: model.reasoning,
588
- attachment: false,
589
- limit: model.limit,
590
- cost: {
591
- input: 0,
592
- output: 0,
593
- cache_read: 0,
594
- cache_write: 0
595
- }
596
- };
597
- return {
598
- npm: "@ai-sdk/openai-compatible",
599
- name: "Microsoft 365 Copilot",
600
- options: {
601
- baseURL: baseUrl,
602
- apiKey,
603
- timeout: 9e5
604
- },
605
- models
606
- };
607
- }
608
550
  /** The opencode 2 provider record pointing at our local OpenAI-compatible proxy. */
609
551
  function buildProviderInfo(baseUrl, apiKey) {
610
552
  return {
@@ -642,7 +584,7 @@ function buildModelInfos() {
642
584
  name: model.name,
643
585
  capabilities: {
644
586
  tools: !isLocalModel(model.id),
645
- input: ["text"],
587
+ input: inputModalities(model.id),
646
588
  output: ["text"]
647
589
  },
648
590
  variants: [],
@@ -660,24 +602,9 @@ function buildModelInfos() {
660
602
  limit: model.limit
661
603
  }));
662
604
  }
663
- /**
664
- * Mutate opencode's in-memory config during the plugin's `config` hook.
665
- *
666
- * Deliberately additive: anything the user set explicitly wins. We are a plugin
667
- * making someone else's config work, not the owner of it.
668
- */
669
- function applyPluginConfig(config, endpoint, options) {
670
- config.provider ??= {};
671
- config.provider[PROVIDER_ID] = buildProviderConfig(endpoint.baseUrl, endpoint.apiKey);
672
- if (options.setDefaultModel && !config.model) config.model = `${PROVIDER_ID}/${DEFAULT_MODEL}`;
673
- if (options.setSmallModel && !config.small_model) config.small_model = `${PROVIDER_ID}/${LOCAL_TITLE_MODEL}`;
674
- if (options.lean && usesOurProvider(config)) config.tools = {
675
- ...buildToolProfile(),
676
- ...config.tools ?? {}
677
- };
678
- }
679
- function usesOurProvider(config) {
680
- return typeof config.model === "string" && config.model.startsWith(`m365/`);
605
+ /** Image input on every model that reaches M365; the local titler takes text only. */
606
+ function inputModalities(modelId) {
607
+ return isLocalModel(modelId) ? ["text"] : ["text", "image"];
681
608
  }
682
609
  /** The npm name this package publishes under — what a checkout's package.json says. */
683
610
  const PACKAGE_NAME = "opencode-m365-copilot";
@@ -690,17 +617,36 @@ const OUR_OPTION_KEYS = /* @__PURE__ */ new Set([
690
617
  "baseUrl",
691
618
  "apiKey"
692
619
  ]);
620
+ /**
621
+ * Merge our plugin reference into an on-disk `opencode.json`, non-destructively.
622
+ *
623
+ * Writes opencode 2's `plugins` key. For an npm install the reference is the package
624
+ * name. For a local checkout it is `pluginDir`, the checkout directory: opencode 2
625
+ * drops a file path with `configured plugin path must be a directory` (measured
626
+ * against 2.0.11), and since it swallows plugin load failures nothing else says so.
627
+ *
628
+ * `pluginRef` is how older versions of setup referenced us in opencode 1's `plugin`
629
+ * key — the package name, or the built `dist/plugin.mjs`. It is used only to find
630
+ * that entry and take it out: this version no longer loads under opencode 1, which
631
+ * would throw on it. Options on it carry over when the `plugins` entry has none, so
632
+ * a `{ "lean": false }` set for opencode 1 is not lost. Other plugins' entries in
633
+ * `plugin` stay, and the key is removed only if we emptied it.
634
+ */
693
635
  function mergeOpencodeConfig(existing, opts) {
694
636
  const merged = { ...existing };
695
637
  merged.$schema ??= "https://opencode.ai/config.json";
696
638
  const pluginDir = opts.pluginDir ?? opts.pluginRef;
697
639
  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);
700
- merged.plugin = [...v1.kept, v1.options ? [opts.pluginRef, v1.options] : opts.pluginRef];
701
- merged.plugins = [...v2.kept, v2.options ? {
640
+ const legacy = withOurRef(merged.plugin, opts.pluginRef, inspect);
641
+ const current = withOurRef(merged.plugins, pluginDir, inspect, legacy.dropped);
642
+ if (legacy.dropped.length > 0) {
643
+ if (legacy.kept.length > 0) merged.plugin = legacy.kept;
644
+ else delete merged.plugin;
645
+ }
646
+ const options = current.options ?? legacy.options;
647
+ merged.plugins = [...current.kept, options ? {
702
648
  package: pluginDir,
703
- options: v2.options
649
+ options
704
650
  } : pluginDir];
705
651
  return merged;
706
652
  }
@@ -731,7 +677,7 @@ function withOurRef(existing, pluginRef, inspect, containing = []) {
731
677
  ...options ? { options } : {}
732
678
  };
733
679
  }
734
- /** The options out of any entry form either version accepts, if it carries some. */
680
+ /** The options out of any entry form — `[spec, options]` or `{ package, options }`. */
735
681
  function optionsOf(entry) {
736
682
  const raw = Array.isArray(entry) ? entry[1] : entry && typeof entry === "object" && "options" in entry ? entry.options : void 0;
737
683
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
@@ -744,7 +690,7 @@ function isWithin(dir, path) {
744
690
  const prefix = dir.endsWith("/") ? dir : `${dir}/`;
745
691
  return path.startsWith(prefix);
746
692
  }
747
- /** The package-or-path out of any entry form either version accepts. */
693
+ /** The package-or-path out of any entry form, including opencode 1's. */
748
694
  function specifierOf(entry) {
749
695
  if (typeof entry === "string") return entry;
750
696
  if (Array.isArray(entry)) return String(entry[0] ?? "");
@@ -778,8 +724,7 @@ function tail(ref) {
778
724
  if (!ref.includes("/")) return "";
779
725
  return ref.split("/").slice(-2).join("/");
780
726
  }
781
- //#endregion
782
- //#region src/paths.ts
727
+ // src/paths.ts
783
728
  /**
784
729
  * Where we keep auth state.
785
730
  *
@@ -792,8 +737,7 @@ const CACHE_FILE = process.env.M365_CACHE_FILE || join(CONFIG_DIR, "msal-cache.j
792
737
  const SECRETS_FILE = process.env.M365_SECRETS_FILE || join(CONFIG_DIR, "secrets.json");
793
738
  const AGENT_FILE = process.env.M365_AGENT_FILE || join(CONFIG_DIR, "agent-id.json");
794
739
  const LOG_FILE = join(CONFIG_DIR, "debug.log");
795
- //#endregion
796
- //#region src/private-fs.ts
740
+ // src/private-fs.ts
797
741
  /**
798
742
  * Owner-only filesystem writes for everything under the config directory.
799
743
  *
@@ -901,8 +845,7 @@ function createPrivateAppender(file) {
901
845
  ready = true;
902
846
  };
903
847
  }
904
- //#endregion
905
- //#region src/log.ts
848
+ // src/log.ts
906
849
  const DEBUG = process.env.M365_DEBUG === "1" || process.env.M365_TRACE === "1";
907
850
  const TRACE = process.env.M365_TRACE === "1";
908
851
  const TO_STDOUT = process.env.M365_LOG_STDOUT === "1";
@@ -939,8 +882,7 @@ function createLogger(scope) {
939
882
  error: (...parts) => write("error", parts)
940
883
  };
941
884
  }
942
- //#endregion
943
- //#region src/auth.ts
885
+ // src/auth.ts
944
886
  /**
945
887
  * Authentication against the Office web Copilot client.
946
888
  *
@@ -955,7 +897,7 @@ function createLogger(scope) {
955
897
  * a client secret only Microsoft holds (`AADSTS7000218`). The `nativeclient` redirect
956
898
  * is the only door, which is why `login.ts` has to drive a real browser.
957
899
  */
958
- const log$2 = createLogger("auth");
900
+ const log$3 = createLogger("auth");
959
901
  /** Microsoft's Office web Copilot client. Not ours, and not replaceable. */
960
902
  const CLIENT_ID = "c0ab8ce9-e9a0-42e7-b064-33d422df41f1";
961
903
  const AUTHORITY = "https://login.microsoftonline.com/common";
@@ -994,7 +936,7 @@ function createCachePlugin(file = CACHE_FILE) {
994
936
  try {
995
937
  writePrivateFile(file, context.tokenCache.serialize());
996
938
  } catch (error) {
997
- log$2.warn("could not persist the token cache", String(error));
939
+ log$3.warn("could not persist the token cache", String(error));
998
940
  }
999
941
  }
1000
942
  };
@@ -1004,7 +946,7 @@ function createTokenClient(options = {}) {
1004
946
  const cache = /* @__PURE__ */ new Map();
1005
947
  async function client() {
1006
948
  if (app) return app;
1007
- const { PublicClientApplication } = await import("./dist-CQqDXRJD.mjs");
949
+ const { PublicClientApplication } = await import("./dist-BNzsla4k.mjs");
1008
950
  app = new PublicClientApplication({
1009
951
  auth: {
1010
952
  clientId: CLIENT_ID,
@@ -1028,7 +970,7 @@ function createTokenClient(options = {}) {
1028
970
  scopes
1029
971
  });
1030
972
  } catch (error) {
1031
- log$2.warn("silent token acquisition failed", String(error));
973
+ log$3.warn("silent token acquisition failed", String(error));
1032
974
  throw new AuthRequiredError("Could not refresh the Microsoft 365 token silently");
1033
975
  }
1034
976
  if (!result?.accessToken) throw new AuthRequiredError("Microsoft 365 returned no access token");
@@ -1067,8 +1009,7 @@ function authCodeFromUrl(rawUrl) {
1067
1009
  }
1068
1010
  return url.searchParams.get("code") ?? void 0;
1069
1011
  }
1070
- //#endregion
1071
- //#region node_modules/ws/lib/constants.js
1012
+ // node_modules/ws/lib/constants.js
1072
1013
  var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1073
1014
  const BINARY_TYPES = [
1074
1015
  "nodebuffer",
@@ -1090,9 +1031,9 @@ var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1090
1031
  NOOP: () => {}
1091
1032
  };
1092
1033
  }));
1093
- //#endregion
1094
- //#region node_modules/ws/lib/buffer-util.js
1034
+ // node_modules/ws/lib/buffer-util.js
1095
1035
  var require_buffer_util = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1036
+ const { websocketMask, websocketUnmask } = __require("http");
1096
1037
  const { EMPTY_BUFFER } = require_constants();
1097
1038
  const FastBuffer = Buffer[Symbol.species];
1098
1039
  /**
@@ -1177,8 +1118,16 @@ var require_buffer_util = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1177
1118
  toBuffer,
1178
1119
  unmask: _unmask
1179
1120
  };
1180
- /* istanbul ignore else */
1181
- if (!process.env.WS_NO_BUFFER_UTIL) try {
1121
+ if (websocketMask) {
1122
+ module.exports.mask = function(source, mask, output, offset, length) {
1123
+ if (length < 24) _mask(source, mask, output, offset, length);
1124
+ else websocketMask(source, mask, output, offset, length);
1125
+ };
1126
+ module.exports.unmask = function(buffer, mask) {
1127
+ if (buffer.length < 24) _unmask(buffer, mask);
1128
+ else websocketUnmask(buffer, mask);
1129
+ };
1130
+ } else if (!process.env.WS_NO_BUFFER_UTIL) try {
1182
1131
  const bufferUtil = __require("bufferutil");
1183
1132
  module.exports.mask = function(source, mask, output, offset, length) {
1184
1133
  if (length < 48) _mask(source, mask, output, offset, length);
@@ -1190,8 +1139,7 @@ var require_buffer_util = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1190
1139
  };
1191
1140
  } catch (e) {}
1192
1141
  }));
1193
- //#endregion
1194
- //#region node_modules/ws/lib/limiter.js
1142
+ // node_modules/ws/lib/limiter.js
1195
1143
  var require_limiter = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1196
1144
  const kDone = Symbol("kDone");
1197
1145
  const kRun = Symbol("kRun");
@@ -1241,8 +1189,7 @@ var require_limiter = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1241
1189
  };
1242
1190
  module.exports = Limiter;
1243
1191
  }));
1244
- //#endregion
1245
- //#region node_modules/ws/lib/permessage-deflate.js
1192
+ // node_modules/ws/lib/permessage-deflate.js
1246
1193
  var require_permessage_deflate = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1247
1194
  const zlib = __require("zlib");
1248
1195
  const bufferUtil = require_buffer_util();
@@ -1577,8 +1524,7 @@ var require_permessage_deflate = /* @__PURE__ */ __commonJSMin(((exports, module
1577
1524
  this[kCallback](err);
1578
1525
  }
1579
1526
  }));
1580
- //#endregion
1581
- //#region node_modules/ws/lib/validation.js
1527
+ // node_modules/ws/lib/validation.js
1582
1528
  var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1583
1529
  const { isUtf8 } = __require("buffer");
1584
1530
  const { hasBlob } = require_constants();
@@ -1773,8 +1719,7 @@ var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1773
1719
  };
1774
1720
  } catch (e) {}
1775
1721
  }));
1776
- //#endregion
1777
- //#region node_modules/ws/lib/receiver.js
1722
+ // node_modules/ws/lib/receiver.js
1778
1723
  var require_receiver = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1779
1724
  const { Writable } = __require("stream");
1780
1725
  const PerMessageDeflate = require_permessage_deflate();
@@ -2236,10 +2181,9 @@ var require_receiver = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2236
2181
  };
2237
2182
  module.exports = Receiver;
2238
2183
  }));
2239
- //#endregion
2240
- //#region node_modules/ws/lib/sender.js
2184
+ // node_modules/ws/lib/sender.js
2241
2185
  var require_sender = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2242
- const { Duplex: Duplex$3 } = __require("stream");
2186
+ const { Duplex } = __require("stream");
2243
2187
  const { randomFillSync } = __require("crypto");
2244
2188
  const { types: { isUint8Array } } = __require("util");
2245
2189
  const PerMessageDeflate = require_permessage_deflate();
@@ -2350,12 +2294,13 @@ var require_sender = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2350
2294
  target[2] = target[3] = 0;
2351
2295
  target.writeUIntBE(dataLength, 4, 6);
2352
2296
  }
2353
- if (!options.mask) return [target, data];
2297
+ if (!options.mask) return dataLength ? [target, data] : [target];
2354
2298
  target[1] |= 128;
2355
2299
  target[offset - 4] = mask[0];
2356
2300
  target[offset - 3] = mask[1];
2357
2301
  target[offset - 2] = mask[2];
2358
2302
  target[offset - 1] = mask[3];
2303
+ if (!dataLength) return [target];
2359
2304
  if (skipMasking) return [target, data];
2360
2305
  if (merge) {
2361
2306
  applyMask(data, mask, target, offset, dataLength);
@@ -2734,8 +2679,7 @@ var require_sender = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2734
2679
  sender.onerror(err);
2735
2680
  }
2736
2681
  }));
2737
- //#endregion
2738
- //#region node_modules/ws/lib/event-target.js
2682
+ // node_modules/ws/lib/event-target.js
2739
2683
  var require_event_target = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2740
2684
  const { kForOnEventAttribute, kListener } = require_constants();
2741
2685
  const kCode = Symbol("kCode");
@@ -2965,8 +2909,7 @@ var require_event_target = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2965
2909
  else listener.call(thisArg, event);
2966
2910
  }
2967
2911
  }));
2968
- //#endregion
2969
- //#region node_modules/ws/lib/extension.js
2912
+ // node_modules/ws/lib/extension.js
2970
2913
  var require_extension = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2971
2914
  const { tokenChars } = require_validation();
2972
2915
  /**
@@ -3111,17 +3054,16 @@ var require_extension = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3111
3054
  parse
3112
3055
  };
3113
3056
  }));
3114
- //#endregion
3115
- //#region node_modules/ws/lib/websocket.js
3057
+ // node_modules/ws/lib/websocket.js
3116
3058
  var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3117
- const EventEmitter$1 = __require("events");
3059
+ const EventEmitter = __require("events");
3118
3060
  const https = __require("https");
3119
- const http$1 = __require("http");
3061
+ const http = __require("http");
3120
3062
  const net = __require("net");
3121
3063
  const tls = __require("tls");
3122
- const { randomBytes: randomBytes$1, createHash: createHash$2 } = __require("crypto");
3123
- const { Duplex: Duplex$2, Readable } = __require("stream");
3124
- const { URL: URL$1 } = __require("url");
3064
+ const { randomBytes, createHash } = __require("crypto");
3065
+ const { Duplex, Readable } = __require("stream");
3066
+ const { URL } = __require("url");
3125
3067
  const PerMessageDeflate = require_permessage_deflate();
3126
3068
  const Receiver = require_receiver();
3127
3069
  const Sender = require_sender();
@@ -3144,7 +3086,7 @@ var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3144
3086
  *
3145
3087
  * @extends EventEmitter
3146
3088
  */
3147
- var WebSocket = class WebSocket extends EventEmitter$1 {
3089
+ var WebSocket = class WebSocket extends EventEmitter {
3148
3090
  /**
3149
3091
  * Create a new `WebSocket`.
3150
3092
  *
@@ -3670,9 +3612,9 @@ var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3670
3612
  websocket._closeTimeout = opts.closeTimeout;
3671
3613
  if (!protocolVersions.includes(opts.protocolVersion)) throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`);
3672
3614
  let parsedUrl;
3673
- if (address instanceof URL$1) parsedUrl = address;
3615
+ if (address instanceof URL) parsedUrl = address;
3674
3616
  else try {
3675
- parsedUrl = new URL$1(address);
3617
+ parsedUrl = new URL(address);
3676
3618
  } catch {
3677
3619
  throw new SyntaxError(`Invalid URL: ${address}`);
3678
3620
  }
@@ -3694,8 +3636,8 @@ var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3694
3636
  }
3695
3637
  }
3696
3638
  const defaultPort = isSecure ? 443 : 80;
3697
- const key = randomBytes$1(16).toString("base64");
3698
- const request = isSecure ? https.request : http$1.request;
3639
+ const key = randomBytes(16).toString("base64");
3640
+ const request = isSecure ? https.request : http.request;
3699
3641
  const protocolSet = /* @__PURE__ */ new Set();
3700
3642
  let perMessageDeflate;
3701
3643
  opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
@@ -3732,9 +3674,14 @@ var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3732
3674
  }
3733
3675
  if (parsedUrl.username || parsedUrl.password) opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
3734
3676
  if (isIpcUrl) {
3735
- const parts = opts.path.split(":");
3736
- opts.socketPath = parts[0];
3737
- opts.path = parts[1];
3677
+ const i = opts.path.indexOf(":");
3678
+ if (i === -1) {
3679
+ opts.socketPath = opts.path;
3680
+ opts.path = "";
3681
+ } else {
3682
+ opts.socketPath = opts.path.slice(0, i);
3683
+ opts.path = opts.path.slice(i + 1);
3684
+ }
3738
3685
  }
3739
3686
  let req;
3740
3687
  if (opts.followRedirects) {
@@ -3780,7 +3727,7 @@ var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3780
3727
  req.abort();
3781
3728
  let addr;
3782
3729
  try {
3783
- addr = new URL$1(location, address);
3730
+ addr = new URL(location, address);
3784
3731
  } catch (e) {
3785
3732
  emitErrorAndClose(websocket, /* @__PURE__ */ new SyntaxError(`Invalid URL: ${location}`));
3786
3733
  return;
@@ -3797,7 +3744,7 @@ var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3797
3744
  abortHandshake(websocket, socket, "Invalid Upgrade header");
3798
3745
  return;
3799
3746
  }
3800
- const digest = createHash$2("sha1").update(key + GUID).digest("base64");
3747
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
3801
3748
  if (res.headers["sec-websocket-accept"] !== digest) {
3802
3749
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
3803
3750
  return;
@@ -4110,11 +4057,10 @@ var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4110
4057
  }
4111
4058
  }
4112
4059
  }));
4113
- //#endregion
4114
- //#region node_modules/ws/lib/stream.js
4060
+ // node_modules/ws/lib/stream.js
4115
4061
  var require_stream = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4116
4062
  require_websocket();
4117
- const { Duplex: Duplex$1 } = __require("stream");
4063
+ const { Duplex } = __require("stream");
4118
4064
  /**
4119
4065
  * Emits the `'close'` event on a stream.
4120
4066
  *
@@ -4153,7 +4099,7 @@ var require_stream = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4153
4099
  */
4154
4100
  function createWebSocketStream(ws, options) {
4155
4101
  let terminateOnDestroy = true;
4156
- const duplex = new Duplex$1({
4102
+ const duplex = new Duplex({
4157
4103
  ...options,
4158
4104
  autoDestroy: false,
4159
4105
  emitClose: false,
@@ -4226,8 +4172,7 @@ var require_stream = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4226
4172
  }
4227
4173
  module.exports = createWebSocketStream;
4228
4174
  }));
4229
- //#endregion
4230
- //#region node_modules/ws/lib/subprotocol.js
4175
+ // node_modules/ws/lib/subprotocol.js
4231
4176
  var require_subprotocol = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4232
4177
  const { tokenChars } = require_validation();
4233
4178
  /**
@@ -4265,13 +4210,12 @@ var require_subprotocol = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4265
4210
  }
4266
4211
  module.exports = { parse };
4267
4212
  }));
4268
- //#endregion
4269
- //#region node_modules/ws/lib/websocket-server.js
4213
+ // node_modules/ws/lib/websocket-server.js
4270
4214
  var require_websocket_server = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4271
4215
  const EventEmitter = __require("events");
4272
4216
  const http = __require("http");
4273
4217
  const { Duplex } = __require("stream");
4274
- const { createHash: createHash$1 } = __require("crypto");
4218
+ const { createHash } = __require("crypto");
4275
4219
  const extension = require_extension();
4276
4220
  const PerMessageDeflate = require_permessage_deflate();
4277
4221
  const subprotocol = require_subprotocol();
@@ -4541,7 +4485,7 @@ var require_websocket_server = /* @__PURE__ */ __commonJSMin(((exports, module)
4541
4485
  "HTTP/1.1 101 Switching Protocols",
4542
4486
  "Upgrade: websocket",
4543
4487
  "Connection: Upgrade",
4544
- `Sec-WebSocket-Accept: ${createHash$1("sha1").update(key + GUID).digest("base64")}`
4488
+ `Sec-WebSocket-Accept: ${createHash("sha1").update(key + GUID).digest("base64")}`
4545
4489
  ];
4546
4490
  const ws = new this.options.WebSocket(null, void 0, this.options);
4547
4491
  if (protocols.size) {
@@ -4660,8 +4604,91 @@ require_sender();
4660
4604
  require_subprotocol();
4661
4605
  var import_websocket = /* @__PURE__ */ __toESM(require_websocket(), 1);
4662
4606
  require_websocket_server();
4663
- //#endregion
4664
- //#region src/session.ts
4607
+ // src/image.ts
4608
+ /**
4609
+ * Image input: getting a pasted image in front of the model.
4610
+ *
4611
+ * M365 does not take image bytes on the chat socket. The web client uploads the
4612
+ * image over HTTP first, gets a `docId` back, and the chat frame points at it with an
4613
+ * `ImageFile` message annotation. That flow is measured to work with the plain chat
4614
+ * token, with or without the declarative agent, and without any GPT-V `optionsSets`
4615
+ * on the turn itself (cramt/m365-copilot-proxy, hypotheses §33 F86).
4616
+ */
4617
+ const log$2 = createLogger("image");
4618
+ /**
4619
+ * The image URLs in the messages from `fromIndex` on.
4620
+ *
4621
+ * Only what the turn carries: M365 keeps its own context, so an image from an earlier
4622
+ * turn is already there, and uploading it again would show it to the model twice.
4623
+ */
4624
+ function collectImages(messages, fromIndex) {
4625
+ const urls = [];
4626
+ for (const message of messages.slice(fromIndex)) {
4627
+ if (message.role === "system" || message.role === "developer") continue;
4628
+ if (!Array.isArray(message.content)) continue;
4629
+ for (const part of message.content) {
4630
+ if (part.type !== "image_url") continue;
4631
+ const raw = part.image_url;
4632
+ const url = typeof raw === "string" ? raw : raw?.url;
4633
+ if (typeof url === "string" && url !== "") urls.push(url);
4634
+ }
4635
+ }
4636
+ return urls;
4637
+ }
4638
+ /** `png`, `jpg`, `svg`… for a base64 image data URL; null for anything else. */
4639
+ function imageFileType(url) {
4640
+ const match = /^data:image\/([a-z0-9.+-]+);base64,/i.exec(url);
4641
+ if (!match) return null;
4642
+ const subtype = match[1].toLowerCase().replace(/\+.*$/, "");
4643
+ return subtype === "jpeg" ? "jpg" : subtype;
4644
+ }
4645
+ /** Upload one image and return the annotation that points a chat turn at it. */
4646
+ async function uploadImage(dataUrl, options) {
4647
+ const fileType = imageFileType(dataUrl);
4648
+ if (!fileType) throw new Error("only base64 image data URLs can be uploaded");
4649
+ const form = new URLSearchParams();
4650
+ form.append("scenario", "UploadImage");
4651
+ form.append("conversationId", options.conversationId);
4652
+ form.append("FileBase64", dataUrl);
4653
+ form.append("optionsSets", "cwcgptvsan");
4654
+ form.append("optionsSets", "flux_v3_gptv_enable_upload_multi_image_in_turn_wo_ch");
4655
+ const response = await fetch(`${options.origin}/m365Copilot/UploadFile`, {
4656
+ method: "POST",
4657
+ headers: {
4658
+ Authorization: `Bearer ${options.token}`,
4659
+ "Content-Type": "application/x-www-form-urlencoded",
4660
+ "X-Scenario": "OfficeWebIncludedCopilot",
4661
+ "X-Variants": "feature.EnableImageSupportInUploadFile",
4662
+ Origin: "https://m365.cloud.microsoft",
4663
+ Referer: "https://m365.cloud.microsoft/"
4664
+ },
4665
+ body: form.toString(),
4666
+ ...options.signal ? { signal: options.signal } : {}
4667
+ });
4668
+ const body = await response.text();
4669
+ if (!response.ok) throw new Error(`image upload failed: HTTP ${response.status}`);
4670
+ let docId;
4671
+ try {
4672
+ docId = JSON.parse(body)?.docId;
4673
+ } catch {}
4674
+ if (typeof docId !== "string" || docId === "") throw new Error("image upload returned no docId");
4675
+ log$2.info("uploaded image", {
4676
+ fileType,
4677
+ chars: dataUrl.length,
4678
+ docId
4679
+ });
4680
+ return {
4681
+ id: docId,
4682
+ messageAnnotationType: "ImageFile",
4683
+ messageAnnotationMetadata: {
4684
+ "@type": "File",
4685
+ annotationType: "File",
4686
+ fileType,
4687
+ fileName: `image-${randomUUID().slice(0, 8)}.${fileType}`
4688
+ }
4689
+ };
4690
+ }
4691
+ // src/session.ts
4665
4692
  /**
4666
4693
  * The M365 Copilot transport: SignalR over WebSocket.
4667
4694
  *
@@ -4765,15 +4792,47 @@ var CopilotSession = class {
4765
4792
  const token = await this.options.getToken();
4766
4793
  const { oid, tid } = decodeJwt(token);
4767
4794
  const url = this.buildUrl(token, oid, tid);
4795
+ const { annotations, note } = await this.uploadImages(token, turn);
4796
+ const message = {
4797
+ text: note ? `${text}\n\n${note}` : text,
4798
+ annotations
4799
+ };
4768
4800
  const socket = new import_websocket.default(url, { headers: BROWSER_HEADERS });
4769
4801
  try {
4770
- const result = await this.pump(socket, text, turn);
4802
+ const result = await this.pump(socket, message, turn);
4771
4803
  this.turnIndex += 1;
4772
4804
  return result;
4773
4805
  } finally {
4774
4806
  closeSocket(socket);
4775
4807
  }
4776
4808
  }
4809
+ /**
4810
+ * Upload the turn's images. A failure costs that image, not the turn: the model is
4811
+ * told what did not arrive, so it says so instead of describing a picture it never
4812
+ * received.
4813
+ */
4814
+ async uploadImages(token, turn) {
4815
+ const images = turn.images ?? [];
4816
+ const annotations = [];
4817
+ const origin = (this.options.endpoint ?? DEFAULT_ENDPOINT).replace(/^ws/, "http");
4818
+ for (const image of images) try {
4819
+ annotations.push(await uploadImage(image, {
4820
+ token,
4821
+ conversationId: this.conversationId,
4822
+ origin,
4823
+ ...turn.signal ? { signal: turn.signal } : {}
4824
+ }));
4825
+ } catch (error) {
4826
+ if (turn.signal?.aborted) throw abortError();
4827
+ log$1.warn("image not attached", error instanceof Error ? error.message : String(error));
4828
+ }
4829
+ const missing = images.length - annotations.length;
4830
+ if (missing === 0) return { annotations };
4831
+ return {
4832
+ annotations,
4833
+ note: images.length === 1 ? "(The user attached an image, but it could not be uploaded, so it is not visible to you. If it matters, let them know.)" : `(${missing} of the ${images.length} attached images could not be uploaded, so they are not visible to you. If they matter, let the user know.)`
4834
+ };
4835
+ }
4777
4836
  buildUrl(token, oid, tid) {
4778
4837
  return `${this.options.endpoint ?? DEFAULT_ENDPOINT}/m365Copilot/Chathub/${oid}@${tid}?${new URLSearchParams({
4779
4838
  access_token: token,
@@ -4789,7 +4848,7 @@ var CopilotSession = class {
4789
4848
  }).toString()}`;
4790
4849
  }
4791
4850
  /** Drive one turn to completion. */
4792
- pump(socket, text, turn) {
4851
+ pump(socket, outgoing, turn) {
4793
4852
  return new Promise((resolve, reject) => {
4794
4853
  let deltaText = "";
4795
4854
  let snapshotText = "";
@@ -4834,7 +4893,7 @@ var CopilotSession = class {
4834
4893
  for (const frame of splitFrames(raw.toString())) {
4835
4894
  if (!handshakeDone) {
4836
4895
  handshakeDone = true;
4837
- this.sendChat(socket, text, turn);
4896
+ this.sendChat(socket, outgoing, turn);
4838
4897
  if (Object.keys(frame).length === 0) continue;
4839
4898
  }
4840
4899
  switch (frame.type) {
@@ -4876,18 +4935,21 @@ var CopilotSession = class {
4876
4935
  });
4877
4936
  }
4878
4937
  /** The chat invocation and its mandatory Metrics companion, in one send. */
4879
- sendChat(socket, text, turn) {
4938
+ sendChat(socket, outgoing, turn) {
4880
4939
  const now = (/* @__PURE__ */ new Date()).toISOString();
4940
+ const { text } = outgoing;
4941
+ const message = {
4942
+ text,
4943
+ author: "user",
4944
+ inputMethod: "Keyboard",
4945
+ messageType: "Chat",
4946
+ locale: "en-US",
4947
+ timestamp: now,
4948
+ messageId: randomUUID()
4949
+ };
4950
+ if (outgoing.annotations.length > 0) message.messageAnnotations = outgoing.annotations;
4881
4951
  const argument = {
4882
- message: {
4883
- text,
4884
- author: "user",
4885
- inputMethod: "Keyboard",
4886
- messageType: "Chat",
4887
- locale: "en-US",
4888
- timestamp: now,
4889
- messageId: randomUUID()
4890
- },
4952
+ message,
4891
4953
  tone: turn.tone ?? "magic",
4892
4954
  source: "officeweb",
4893
4955
  streamingMode: "ConciseWithPadding",
@@ -4939,6 +5001,7 @@ var CopilotSession = class {
4939
5001
  log$1.info("sending turn", trunc({
4940
5002
  tone: argument.tone,
4941
5003
  agent: Boolean(turn.agentId),
5004
+ images: outgoing.annotations.length,
4942
5005
  text
4943
5006
  }));
4944
5007
  socket.send(`${JSON.stringify(chat)}${RS}${JSON.stringify(metrics)}${RS}`);
@@ -5027,8 +5090,7 @@ function abortError() {
5027
5090
  error.name = "AbortError";
5028
5091
  return error;
5029
5092
  }
5030
- //#endregion
5031
- //#region node_modules/zod/v4/core/util.js
5093
+ // node_modules/zod/v4/core/util.js
5032
5094
  function getEnumValues(entries) {
5033
5095
  const numericValues = Object.values(entries).filter((v) => typeof v === "number");
5034
5096
  return Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
@@ -5438,6 +5500,7 @@ function hide(inst, key, value) {
5438
5500
  return own(inst, key, value, false);
5439
5501
  }
5440
5502
  /** Adds members a table derives from the instance: each builds on first read and shadows as own data, and assignment shadows the same way, as when these were own properties. */
5503
+ /* @__NO_SIDE_EFFECTS__ */
5441
5504
  function derived(computes, table) {
5442
5505
  for (const key in computes) {
5443
5506
  const compute = computes[key];
@@ -5561,8 +5624,7 @@ function constantCatch(value) {
5561
5624
  fn[CONSTANT_CATCH] = true;
5562
5625
  return fn;
5563
5626
  }
5564
- //#endregion
5565
- //#region node_modules/zod/v4/core/core.js
5627
+ // node_modules/zod/v4/core/core.js
5566
5628
  var _a$1;
5567
5629
  const _zodDesc = {
5568
5630
  value: void 0,
@@ -5589,6 +5651,7 @@ function newError(Definition) {
5589
5651
  }
5590
5652
  return new Definition();
5591
5653
  }
5654
+ /* @__NO_SIDE_EFFECTS__ */
5592
5655
  function $constructor(name, initializer, proto, params) {
5593
5656
  const zodProto = {};
5594
5657
  function Internals(def) {
@@ -5667,8 +5730,7 @@ function config(newConfig) {
5667
5730
  if (newConfig) Object.assign(globalConfig, newConfig);
5668
5731
  return globalConfig;
5669
5732
  }
5670
- //#endregion
5671
- //#region node_modules/zod/v4/core/errors.js
5733
+ // node_modules/zod/v4/core/errors.js
5672
5734
  function _getMessage() {
5673
5735
  const internals = this._zod;
5674
5736
  internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2));
@@ -5719,8 +5781,7 @@ const initializer$1 = (inst, def) => {
5719
5781
  });
5720
5782
  }
5721
5783
  };
5722
- const $ZodError = $constructor("$ZodError", initializer$1);
5723
- $constructor("$ZodError", initializer$1, void 0, { Parent: Error });
5784
+ const $ZodError = /* @__PURE__ */ $constructor("$ZodError", initializer$1);
5724
5785
  /** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member
5725
5786
  * ("toString", "constructor") would otherwise read through to the prototype, and assigning
5726
5787
  * "__proto__" would hit the setter instead of creating a key. */
@@ -5783,8 +5844,7 @@ function formatError(error, mapper = (issue) => issue.message) {
5783
5844
  processError(error);
5784
5845
  return fieldErrors;
5785
5846
  }
5786
- //#endregion
5787
- //#region node_modules/zod/v4/core/parse.js
5847
+ // node_modules/zod/v4/core/parse.js
5788
5848
  function finalizeParams(callee, params) {
5789
5849
  return {
5790
5850
  callee: params?.callee ?? callee,
@@ -5986,8 +6046,7 @@ const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
5986
6046
  const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
5987
6047
  return _safeParseAsync(_Err)(schema, value, _ctx);
5988
6048
  };
5989
- //#endregion
5990
- //#region node_modules/zod/v4/core/regexes.js
6049
+ // node_modules/zod/v4/core/regexes.js
5991
6050
  /**
5992
6051
  * @deprecated CUID v1 is deprecated by its authors due to information leakage
5993
6052
  * (timestamps embedded in the id). Use {@link cuid2} instead.
@@ -6058,8 +6117,7 @@ const boolean$1 = /^(?:true|false)$/i;
6058
6117
  const _null$2 = /^null$/i;
6059
6118
  const lowercase = /^[^A-Z]*$/;
6060
6119
  const uppercase = /^[^a-z]*$/;
6061
- //#endregion
6062
- //#region node_modules/zod/v4/core/checks.js
6120
+ // node_modules/zod/v4/core/checks.js
6063
6121
  const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => {
6064
6122
  var _a;
6065
6123
  inst._zod ?? (inst._zod = {});
@@ -6354,8 +6412,7 @@ const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (ins
6354
6412
  payload.value = def.tx(payload.value);
6355
6413
  };
6356
6414
  });
6357
- //#endregion
6358
- //#region node_modules/zod/v4/core/doc.js
6415
+ // node_modules/zod/v4/core/doc.js
6359
6416
  var Doc = class {
6360
6417
  constructor(args = [], closed = {}) {
6361
6418
  this.content = [];
@@ -6388,15 +6445,13 @@ var Doc = class {
6388
6445
  return new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) {\n${content.join("\n")}\n};`)(...Object.values(this.closed));
6389
6446
  }
6390
6447
  };
6391
- //#endregion
6392
- //#region node_modules/zod/v4/core/versions.js
6448
+ // node_modules/zod/v4/core/versions.js
6393
6449
  const version = {
6394
6450
  major: 4,
6395
6451
  minor: 6,
6396
6452
  patch: 7
6397
6453
  };
6398
- //#endregion
6399
- //#region node_modules/zod/v4/core/schemas.js
6454
+ // node_modules/zod/v4/core/schemas.js
6400
6455
  const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => {
6401
6456
  var _a;
6402
6457
  inst ?? (inst = {});
@@ -7674,8 +7729,7 @@ function handleRefineResult(result, payload, input, inst) {
7674
7729
  payload.issues.push(issue(_iss));
7675
7730
  }
7676
7731
  }
7677
- //#endregion
7678
- //#region node_modules/zod/v4/core/memoizer.js
7732
+ // node_modules/zod/v4/core/memoizer.js
7679
7733
  var $ZodCyclicError = class extends Error {
7680
7734
  constructor() {
7681
7735
  super(`Cannot parse a reference cycle that closes through a transform`);
@@ -7927,8 +7981,7 @@ function isBackEdge(ctx, value) {
7927
7981
  const backEdges = ctx[STATE]?.backEdges;
7928
7982
  return backEdges !== void 0 && isRef(value) && backEdges.has(value);
7929
7983
  }
7930
- //#endregion
7931
- //#region node_modules/zod/v4/locales/en.js
7984
+ // node_modules/zod/v4/locales/en.js
7932
7985
  const error = () => {
7933
7986
  const Sizable = {
7934
7987
  string: {
@@ -8035,8 +8088,7 @@ const error = () => {
8035
8088
  function en_default() {
8036
8089
  return { localeError: error() };
8037
8090
  }
8038
- //#endregion
8039
- //#region node_modules/zod/v4/core/registries.js
8091
+ // node_modules/zod/v4/core/registries.js
8040
8092
  var _a;
8041
8093
  var $ZodRegistry = class {
8042
8094
  constructor() {
@@ -8082,8 +8134,7 @@ function registry() {
8082
8134
  }
8083
8135
  (_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());
8084
8136
  const globalRegistry = globalThis.__zod_globalRegistry;
8085
- //#endregion
8086
- //#region node_modules/zod/v4/core/api.js
8137
+ // node_modules/zod/v4/core/api.js
8087
8138
  function snapshotChecks(def) {
8088
8139
  if (def.checks) def.checks = [...def.checks];
8089
8140
  return def;
@@ -8602,8 +8653,7 @@ function _check(fn, params) {
8602
8653
  ch._zod.check = fn;
8603
8654
  return ch;
8604
8655
  }
8605
- //#endregion
8606
- //#region node_modules/zod/v4/core/to-json-schema.js
8656
+ // node_modules/zod/v4/core/to-json-schema.js
8607
8657
  function assignProps(target, ...sources) {
8608
8658
  for (const source of sources) for (const key of Reflect.ownKeys(source)) if (Object.prototype.propertyIsEnumerable.call(source, key)) assignProp(target, key, source[key]);
8609
8659
  return target;
@@ -9046,8 +9096,7 @@ const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params)
9046
9096
  extractDefs(ctx, schema);
9047
9097
  return finalize(ctx, schema);
9048
9098
  };
9049
- //#endregion
9050
- //#region node_modules/zod/v4/core/json-schema-processors.js
9099
+ // node_modules/zod/v4/core/json-schema-processors.js
9051
9100
  const narrowMin = (agg, key, value) => {
9052
9101
  if (agg[key] === void 0 || value > agg[key]) agg[key] = value;
9053
9102
  };
@@ -9400,8 +9449,7 @@ const optionalProcessor = (schema, ctx, _json, params) => {
9400
9449
  const seen = ctx.seen.get(schema);
9401
9450
  seen.ref = def.innerType;
9402
9451
  };
9403
- //#endregion
9404
- //#region node_modules/zod/v4/classic/errors.js
9452
+ // node_modules/zod/v4/classic/errors.js
9405
9453
  const _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);
9406
9454
  function _lazyMethod(proto, key, make) {
9407
9455
  Object.defineProperty(proto, key, {
@@ -9450,8 +9498,7 @@ const initializer = (inst, issues) => {
9450
9498
  });
9451
9499
  };
9452
9500
  const ZodRealError = /*@__PURE__*/ $constructor("ZodError", initializer, void 0, { Parent: Error });
9453
- //#endregion
9454
- //#region node_modules/zod/v4/classic/parse.js
9501
+ // node_modules/zod/v4/classic/parse.js
9455
9502
  const parse$1 = /* @__PURE__ */ _parse(ZodRealError);
9456
9503
  const parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
9457
9504
  const safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
@@ -9464,8 +9511,7 @@ const safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError);
9464
9511
  const safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError);
9465
9512
  const safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError);
9466
9513
  const safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
9467
- //#endregion
9468
- //#region node_modules/zod/v4/classic/schemas.js
9514
+ // node_modules/zod/v4/classic/schemas.js
9469
9515
  function _ensureDefaultLocale() {
9470
9516
  if (!globalConfig.localeError) config(en_default());
9471
9517
  }
@@ -10328,8 +10374,7 @@ function refine(fn, _params = {}) {
10328
10374
  function superRefine(fn, params) {
10329
10375
  return /* @__PURE__ */ _superRefine(fn, params);
10330
10376
  }
10331
- //#endregion
10332
- //#region src/translate.ts
10377
+ // src/translate.ts
10333
10378
  /**
10334
10379
  * OpenAI ⇄ M365 translation.
10335
10380
  *
@@ -10436,6 +10481,9 @@ function contentOf(message) {
10436
10481
  if (Array.isArray(content)) return content.map((part) => typeof part.text === "string" ? part.text : "").filter(Boolean).join("\n");
10437
10482
  return "";
10438
10483
  }
10484
+ function hasImagePart(message) {
10485
+ return Array.isArray(message.content) && message.content.some((part) => part.type === "image_url");
10486
+ }
10439
10487
  /**
10440
10488
  * Capability catalogues a harness injects into its system prompt, and the tool each
10441
10489
  * one needs in order to be actionable.
@@ -10549,7 +10597,7 @@ function buildTurnPrompt(messages, tools, sentMessageCount, options = {}) {
10549
10597
  if (text) parts.push(text);
10550
10598
  continue;
10551
10599
  }
10552
- const text = contentOf(message);
10600
+ const text = contentOf(message) || (hasImagePart(message) ? "(See the attached image.)" : "");
10553
10601
  if (text) parts.push(text);
10554
10602
  }
10555
10603
  return parts.filter(Boolean).join("\n\n");
@@ -10671,7 +10719,7 @@ const TITLE_INSTRUCTION = /generate|summar|title|respond with|in a few words|sho
10671
10719
  /**
10672
10720
  * Name a session without spending an M365 conversation on it.
10673
10721
  *
10674
- * opencode's `small_model` defaults to the main model, so titling would open a second
10722
+ * A harness titles each session on the main model by default, which would open a second
10675
10723
  * conversation for every session — and the throttle counts conversations started, not
10676
10724
  * messages. This is not as good as a model-written title; it is free, and it keeps
10677
10725
  * the account out of the throttle.
@@ -10686,8 +10734,7 @@ function generateTitle(messages) {
10686
10734
  function firstLine(text) {
10687
10735
  return text.split("\n", 1)[0] ?? "";
10688
10736
  }
10689
- //#endregion
10690
- //#region src/server.ts
10737
+ // src/server.ts
10691
10738
  /**
10692
10739
  * The OpenAI-compatible HTTP surface.
10693
10740
  *
@@ -10891,6 +10938,7 @@ async function runTurn(request, response, context, body, conversation, model, to
10891
10938
  getToken: context.deps.getToken,
10892
10939
  ...context.deps.endpoint ? { endpoint: context.deps.endpoint } : {}
10893
10940
  });
10941
+ const images = collectImages(body.messages, conversation.sentMessageCount);
10894
10942
  const prompt = buildTurnPrompt(body.messages, tools, conversation.sentMessageCount, { ...context.deps.leanSystemPrompt !== void 0 ? { leanSystemPrompt: context.deps.leanSystemPrompt } : {} });
10895
10943
  const agent = tools.length > 0 ? await context.agentId() : null;
10896
10944
  const abort = new AbortController();
@@ -10906,6 +10954,7 @@ async function runTurn(request, response, context, body, conversation, model, to
10906
10954
  ...model.tone ? { tone: model.tone } : {},
10907
10955
  agentId: agent,
10908
10956
  signal: abort.signal,
10957
+ ...images.length > 0 ? { images } : {},
10909
10958
  ...canStreamText ? { onDelta: (chunk) => response.write(streamChunk(streamId, model.id, { content: chunk })) } : {}
10910
10959
  });
10911
10960
  conversation.sentMessageCount = body.messages.length + 1;
@@ -11026,5 +11075,4 @@ async function readBody(request, limit) {
11026
11075
  }
11027
11076
  return Buffer.concat(chunks).toString("utf8");
11028
11077
  }
11029
- //#endregion
11030
- 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 };
11078
+ export { DEFAULT_MODEL as A, SECRETS_FILE as C, buildProviderInfo as D, buildModelInfos as E, __toESM as F, isLocalModel as M, __commonJSMin as N, mergeOpencodeConfig as O, __require 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, LOCAL_TITLE_MODEL as j, resolveOptions 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 };