@otium-team/negotium 0.23.14 → 0.24.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.
Files changed (43) hide show
  1. package/dist/agent-helpers.js +956 -243
  2. package/dist/agent-helpers.js.map +12 -9
  3. package/dist/{chunk-3v58ejrk.js → chunk-3r4xfhkx.js} +3 -3
  4. package/dist/{chunk-3v58ejrk.js.map → chunk-3r4xfhkx.js.map} +2 -2
  5. package/dist/{chunk-ng13grfj.js → chunk-fzfzskjq.js} +18 -2
  6. package/dist/{chunk-ng13grfj.js.map → chunk-fzfzskjq.js.map} +4 -4
  7. package/dist/{chunk-m1ngkjdd.js → chunk-hn2cqdd0.js} +1 -1
  8. package/dist/hosted-agent.js +19 -3
  9. package/dist/hosted-agent.js.map +5 -5
  10. package/dist/main.js +38697 -37819
  11. package/dist/main.js.map +89 -85
  12. package/dist/mcp-factories.js +946 -227
  13. package/dist/mcp-factories.js.map +13 -10
  14. package/dist/prompts.js +221 -1
  15. package/dist/prompts.js.map +7 -5
  16. package/dist/registry.js +3 -3
  17. package/dist/rollout.js +2 -2
  18. package/dist/runtime/src/mcp/wiki-server.ts +8 -0
  19. package/dist/runtime/src/platform/mcp-config.ts +26 -0
  20. package/dist/runtime/src/prompts/builders.ts +5 -0
  21. package/dist/runtime/src/runtime/turn-runner.ts +104 -1
  22. package/dist/runtime/src/storage/api-topics.ts +29 -0
  23. package/dist/runtime/src/topics/agent-plugins/mcp.schema.json +120 -0
  24. package/dist/runtime/src/topics/agent-plugins/plugin.schema.json +65 -0
  25. package/dist/runtime/src/topics/plugin-server-instructions.ts +201 -0
  26. package/dist/runtime/src/topics/plugin-turn.ts +37 -0
  27. package/dist/runtime/src/topics/plugins.ts +445 -0
  28. package/dist/runtime/src/topics/update.ts +34 -0
  29. package/dist/runtime/src/types/api.ts +5 -0
  30. package/dist/runtime/src/version.ts +1 -1
  31. package/dist/storage.js +23 -2
  32. package/dist/storage.js.map +3 -3
  33. package/dist/types/packages/core/src/platform/mcp-config.d.ts +6 -0
  34. package/dist/types/packages/core/src/prompts/builders.d.ts +3 -0
  35. package/dist/types/packages/core/src/runtime/turn-runner.d.ts +14 -1
  36. package/dist/types/packages/core/src/storage/api-topics.d.ts +3 -0
  37. package/dist/types/packages/core/src/topics/plugin-server-instructions.d.ts +55 -0
  38. package/dist/types/packages/core/src/topics/plugin-turn.d.ts +17 -0
  39. package/dist/types/packages/core/src/topics/plugins.d.ts +66 -0
  40. package/dist/types/packages/core/src/types/api.d.ts +5 -0
  41. package/dist/types/packages/core/src/version.d.ts +1 -1
  42. package/package.json +1 -1
  43. /package/dist/{chunk-m1ngkjdd.js.map → chunk-hn2cqdd0.js.map} +0 -0
@@ -2441,6 +2441,7 @@ function initializeApiTopicsSchema() {
2441
2441
  browser_profile TEXT NOT NULL DEFAULT 'default',
2442
2442
  browser_profile_owner TEXT,
2443
2443
  browser_connect_port INTEGER,
2444
+ plugins_json TEXT,
2444
2445
  session_id TEXT,
2445
2446
  CHECK (
2446
2447
  (kind = 'channel' AND response_policy = 'off' AND agent IS NULL) OR
@@ -2561,6 +2562,10 @@ function initializeApiTopicsSchema() {
2561
2562
  if (!tableColumns("api_topics").has("browser_connect_port")) {
2562
2563
  db.exec("ALTER TABLE api_topics ADD COLUMN browser_connect_port INTEGER");
2563
2564
  }
2565
+ if (!tableColumns("api_topics").has("plugins_json")) {
2566
+ db.exec("ALTER TABLE api_topics ADD COLUMN plugins_json TEXT");
2567
+ }
2568
+ db.exec("DROP TABLE IF EXISTS api_topic_plugin_variables");
2564
2569
  if (!tableColumns("api_topics").has("subagent_report_mode")) {
2565
2570
  db.exec("ALTER TABLE api_topics ADD COLUMN subagent_report_mode TEXT NOT NULL DEFAULT 'auto'");
2566
2571
  }
@@ -2799,9 +2804,20 @@ function rowToDto2(r, participants = getTopicParticipants(r.id), tellTargets) {
2799
2804
  visibility: normalizeTopicVisibility(r.visibility),
2800
2805
  surface: normalizeTopicSurface(r.surface),
2801
2806
  surfaceScope: normalizeSurfaceScope(r.surface_scope),
2802
- ...r.browser_connect_port != null ? { browserConnectPort: r.browser_connect_port } : {}
2807
+ ...r.browser_connect_port != null ? { browserConnectPort: r.browser_connect_port } : {},
2808
+ ...pluginsField(r.plugins_json)
2803
2809
  };
2804
2810
  }
2811
+ function pluginsField(json) {
2812
+ if (!json)
2813
+ return {};
2814
+ try {
2815
+ const plugins = JSON.parse(json);
2816
+ return Array.isArray(plugins) && plugins.every((dir) => typeof dir === "string") ? { plugins } : {};
2817
+ } catch {
2818
+ return {};
2819
+ }
2820
+ }
2805
2821
  function normalizeTopicVisibility(value) {
2806
2822
  return value === "hidden" ? "hidden" : "visible";
2807
2823
  }
@@ -3203,6 +3219,22 @@ function refreshForumCatalogViews() {
3203
3219
  function isReservedRuntimeMcpServerName(name) {
3204
3220
  return Object.hasOwn(MCP_CATALOG, name) || nodeMcpEntries.some((entry) => entry.key === name);
3205
3221
  }
3222
+ function pluginMcpRefusal(topic, names, hostNames = []) {
3223
+ if (names.length > 0 && topic.isSubagent)
3224
+ return "plugin servers are not allowed for subagent topics";
3225
+ for (const name of names) {
3226
+ if (isReservedRuntimeMcpServerName(name)) {
3227
+ return `plugin MCP server name conflicts with node catalog: ${name}`;
3228
+ }
3229
+ if (topic.kind !== "manager" && MANAGER_ONLY_HOST_MCP_NAMES.has(name)) {
3230
+ return `${name} is only allowed for manager topics`;
3231
+ }
3232
+ if (hostNames.includes(name)) {
3233
+ return `plugin MCP server name conflicts with a host MCP server: ${name}`;
3234
+ }
3235
+ }
3236
+ return null;
3237
+ }
3206
3238
  function withoutManagerOnlyHostMcpServers(hostMcpServers) {
3207
3239
  if (!hostMcpServers)
3208
3240
  return;
@@ -5270,7 +5302,7 @@ var init_codex = __esm(async () => {
5270
5302
  });
5271
5303
 
5272
5304
  // ../../packages/core/src/version.ts
5273
- var NEGOTIUM_VERSION = "0.23.14";
5305
+ var NEGOTIUM_VERSION = "0.24.0";
5274
5306
 
5275
5307
  // ../../packages/core/src/agents/codex-native-multi-agent.ts
5276
5308
  import { spawn as spawn2 } from "child_process";
@@ -9649,11 +9681,578 @@ var init_bus = __esm(async () => {
9649
9681
  };
9650
9682
  });
9651
9683
 
9684
+ // ../../packages/core/src/runtime-gateway.ts
9685
+ function parseHostMcpServers(value) {
9686
+ if (value === undefined)
9687
+ return;
9688
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
9689
+ throw new TypeError("hostMcpServers must be an object");
9690
+ }
9691
+ const parsedEntries = [];
9692
+ for (const [name, raw] of Object.entries(value)) {
9693
+ if (!HOST_MCP_SERVER_NAME.test(name)) {
9694
+ throw new TypeError(`invalid host MCP server name: ${name}`);
9695
+ }
9696
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
9697
+ throw new TypeError(`hostMcpServers.${name} must be an object`);
9698
+ }
9699
+ const spec = raw;
9700
+ const unsupported = Object.keys(spec).find((key) => !HOST_MCP_SERVER_KEYS.has(key));
9701
+ if (unsupported) {
9702
+ throw new TypeError(`hostMcpServers.${name}.${unsupported} is not allowed`);
9703
+ }
9704
+ if (spec.type !== "sse" && spec.type !== "http") {
9705
+ throw new TypeError(`hostMcpServers.${name}.type must be sse or http`);
9706
+ }
9707
+ if (typeof spec.url !== "string") {
9708
+ throw new TypeError(`hostMcpServers.${name}.url must be a string`);
9709
+ }
9710
+ let url;
9711
+ try {
9712
+ url = new URL(spec.url);
9713
+ } catch {
9714
+ throw new TypeError(`hostMcpServers.${name}.url must be a valid URL`);
9715
+ }
9716
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
9717
+ throw new TypeError(`hostMcpServers.${name}.url must use http or https`);
9718
+ }
9719
+ let headers;
9720
+ if (spec.headers !== undefined) {
9721
+ if (!spec.headers || typeof spec.headers !== "object" || Array.isArray(spec.headers)) {
9722
+ throw new TypeError(`hostMcpServers.${name}.headers must be an object`);
9723
+ }
9724
+ const headerEntries = [];
9725
+ for (const [key, headerValue] of Object.entries(spec.headers)) {
9726
+ if (!HTTP_HEADER_NAME.test(key) || typeof headerValue !== "string") {
9727
+ throw new TypeError(`hostMcpServers.${name}.headers must contain string values`);
9728
+ }
9729
+ try {
9730
+ new Headers([[key, headerValue]]);
9731
+ } catch {
9732
+ throw new TypeError(`hostMcpServers.${name}.headers contains an invalid header`);
9733
+ }
9734
+ headerEntries.push([key, headerValue]);
9735
+ }
9736
+ headers = Object.fromEntries(headerEntries);
9737
+ }
9738
+ if (spec.timeout !== undefined && (typeof spec.timeout !== "number" || !Number.isFinite(spec.timeout) || spec.timeout <= 0)) {
9739
+ throw new TypeError(`hostMcpServers.${name}.timeout must be a positive number`);
9740
+ }
9741
+ parsedEntries.push([
9742
+ name,
9743
+ {
9744
+ type: spec.type,
9745
+ url: url.toString(),
9746
+ ...headers ? { headers } : {},
9747
+ ...spec.timeout !== undefined ? { timeout: spec.timeout } : {}
9748
+ }
9749
+ ]);
9750
+ }
9751
+ return Object.fromEntries(parsedEntries);
9752
+ }
9753
+ var HOST_MCP_SERVER_NAME, HOST_MCP_SERVER_KEYS, HTTP_HEADER_NAME;
9754
+ var init_runtime_gateway = __esm(() => {
9755
+ HOST_MCP_SERVER_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
9756
+ HOST_MCP_SERVER_KEYS = new Set(["type", "url", "headers", "timeout"]);
9757
+ HTTP_HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
9758
+ });
9759
+
9760
+ // ../../packages/core/src/topics/agent-plugins/mcp.schema.json
9761
+ var mcp_schema_default;
9762
+ var init_mcp_schema = __esm(() => {
9763
+ mcp_schema_default = {
9764
+ $schema: "https://json-schema.org/draft/2020-12/schema",
9765
+ $id: "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
9766
+ title: "Agent Plugins MCP Configuration",
9767
+ description: "Machine-readable schema for mcp.json in Agent Plugins 1.0.0. The Agent Plugins specification defines additional semantic and operational requirements.",
9768
+ type: "object",
9769
+ properties: {
9770
+ $schema: {
9771
+ const: "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
9772
+ description: "Canonical identifier of the MCP configuration schema for the Agent Plugins version targeted by this document."
9773
+ },
9774
+ mcpServers: {
9775
+ type: "object",
9776
+ additionalProperties: {
9777
+ $ref: "#/$defs/server"
9778
+ }
9779
+ }
9780
+ },
9781
+ required: ["$schema", "mcpServers"],
9782
+ additionalProperties: false,
9783
+ $defs: {
9784
+ server: {
9785
+ title: "MCP server",
9786
+ oneOf: [
9787
+ {
9788
+ $ref: "#/$defs/stdioServer"
9789
+ },
9790
+ {
9791
+ $ref: "#/$defs/streamableHttpServer"
9792
+ },
9793
+ {
9794
+ $ref: "#/$defs/sseServer"
9795
+ }
9796
+ ]
9797
+ },
9798
+ stdioServer: {
9799
+ title: "stdio MCP server",
9800
+ type: "object",
9801
+ properties: {
9802
+ type: {
9803
+ const: "stdio"
9804
+ },
9805
+ command: {
9806
+ type: "string",
9807
+ minLength: 1,
9808
+ description: "Executable token. Resolution rules are defined by the Agent Plugins specification."
9809
+ },
9810
+ args: {
9811
+ type: "array",
9812
+ items: {
9813
+ type: "string"
9814
+ }
9815
+ },
9816
+ env: {
9817
+ type: "object",
9818
+ propertyNames: {
9819
+ not: {
9820
+ enum: ["PLUGIN_ROOT", "PLUGIN_DATA"]
9821
+ }
9822
+ },
9823
+ additionalProperties: {
9824
+ type: "string"
9825
+ }
9826
+ },
9827
+ cwd: {
9828
+ type: "string",
9829
+ pattern: "^(?:\\./|\\$\\{PLUGIN_ROOT\\}(?:/|$)|\\$\\{PLUGIN_DATA\\}(?:/|$))",
9830
+ description: "Plugin-relative, PLUGIN_ROOT-rooted, or PLUGIN_DATA-rooted working directory. Filesystem containment is validated separately."
9831
+ }
9832
+ },
9833
+ required: ["type", "command"],
9834
+ additionalProperties: false
9835
+ },
9836
+ streamableHttpServer: {
9837
+ title: "Streamable HTTP MCP server",
9838
+ type: "object",
9839
+ properties: {
9840
+ type: {
9841
+ const: "streamable-http"
9842
+ },
9843
+ url: {
9844
+ type: "string",
9845
+ minLength: 1,
9846
+ description: "MCP endpoint URL. URL semantics are defined by the Agent Plugins specification."
9847
+ },
9848
+ headers: {
9849
+ $ref: "#/$defs/headers"
9850
+ }
9851
+ },
9852
+ required: ["type", "url"],
9853
+ additionalProperties: false
9854
+ },
9855
+ sseServer: {
9856
+ title: "Legacy HTTP+SSE MCP server",
9857
+ type: "object",
9858
+ properties: {
9859
+ type: {
9860
+ const: "sse"
9861
+ },
9862
+ url: {
9863
+ type: "string",
9864
+ minLength: 1,
9865
+ description: "MCP endpoint URL. URL semantics are defined by the Agent Plugins specification."
9866
+ },
9867
+ headers: {
9868
+ $ref: "#/$defs/headers"
9869
+ }
9870
+ },
9871
+ required: ["type", "url"],
9872
+ additionalProperties: false
9873
+ },
9874
+ headers: {
9875
+ title: "HTTP headers",
9876
+ type: "object",
9877
+ additionalProperties: {
9878
+ type: "string"
9879
+ }
9880
+ }
9881
+ }
9882
+ };
9883
+ });
9884
+
9885
+ // ../../packages/core/src/topics/agent-plugins/plugin.schema.json
9886
+ var plugin_schema_default;
9887
+ var init_plugin_schema = __esm(() => {
9888
+ plugin_schema_default = {
9889
+ $schema: "https://json-schema.org/draft/2020-12/schema",
9890
+ $id: "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
9891
+ title: "Agent Plugins Manifest",
9892
+ description: "Machine-readable schema for plugin.json in Agent Plugins 1.0.0. The Agent Plugins specification defines additional semantic and operational requirements.",
9893
+ type: "object",
9894
+ properties: {
9895
+ $schema: {
9896
+ const: "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
9897
+ description: "Canonical identifier of the plugin manifest schema for the Agent Plugins version targeted by this document."
9898
+ },
9899
+ name: {
9900
+ type: "string",
9901
+ minLength: 1,
9902
+ maxLength: 64,
9903
+ pattern: "^(?!.*(?:--|\\.\\.))[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$",
9904
+ description: "Human-readable plugin name."
9905
+ },
9906
+ version: {
9907
+ type: "string"
9908
+ },
9909
+ description: {
9910
+ type: "string"
9911
+ },
9912
+ author: {
9913
+ type: "object",
9914
+ properties: {
9915
+ name: {
9916
+ type: "string"
9917
+ },
9918
+ email: {
9919
+ type: "string"
9920
+ },
9921
+ url: {
9922
+ type: "string"
9923
+ }
9924
+ },
9925
+ additionalProperties: false
9926
+ },
9927
+ homepage: {
9928
+ type: "string"
9929
+ },
9930
+ repository: {
9931
+ type: "string"
9932
+ },
9933
+ license: {
9934
+ type: "string"
9935
+ },
9936
+ keywords: {
9937
+ type: "array",
9938
+ items: {
9939
+ type: "string"
9940
+ }
9941
+ },
9942
+ extensions: {
9943
+ type: "object",
9944
+ description: "Client-specific manifest data keyed by reverse-domain extension namespace. Agent Plugins assigns no semantics to namespace object contents.",
9945
+ additionalProperties: {
9946
+ type: "object"
9947
+ }
9948
+ }
9949
+ },
9950
+ required: ["$schema", "name"],
9951
+ additionalProperties: false
9952
+ };
9953
+ });
9954
+
9955
+ // ../../packages/core/src/topics/plugins.ts
9956
+ import { existsSync as existsSync16, readdirSync as readdirSync2, readFileSync as readFileSync12, realpathSync as realpathSync5, statSync as statSync7 } from "fs";
9957
+ import { isAbsolute as isAbsolute5, join as join17, relative as relative3 } from "path";
9958
+ import { z } from "zod";
9959
+ function readText(path) {
9960
+ return readFileSync12(path, "utf-8").replace(/^\uFEFF/, "").replace(/\r\n/g, `
9961
+ `);
9962
+ }
9963
+ function pathKind(root, path) {
9964
+ if (!existsSync16(path))
9965
+ return "missing";
9966
+ const real = realpathSync5(path);
9967
+ const fromRoot = relative3(root, real);
9968
+ if (fromRoot.startsWith("..") || isAbsolute5(fromRoot))
9969
+ return "outside";
9970
+ const stat = statSync7(real);
9971
+ return stat.isFile() ? "file" : stat.isDirectory() ? "dir" : "other";
9972
+ }
9973
+ function parseFrontmatter(raw) {
9974
+ const match = raw.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
9975
+ if (!match)
9976
+ return { ok: false, problem: "missing the --- frontmatter block" };
9977
+ let meta;
9978
+ try {
9979
+ meta = Bun.YAML.parse(match[1]);
9980
+ } catch (error) {
9981
+ const reason = error instanceof Error ? error.message : String(error);
9982
+ return { ok: false, problem: `frontmatter is not valid YAML (${reason})` };
9983
+ }
9984
+ if (!isObject(meta))
9985
+ return { ok: false, problem: "frontmatter must be a YAML mapping" };
9986
+ return { ok: true, meta, body: match[2] };
9987
+ }
9988
+ function readJson(path, fail) {
9989
+ try {
9990
+ return JSON.parse(readText(path));
9991
+ } catch (error) {
9992
+ fail(`not valid JSON (${error instanceof Error ? error.message : String(error)})`);
9993
+ return;
9994
+ }
9995
+ }
9996
+ function manifestSchema() {
9997
+ manifestValidator ??= z.fromJSONSchema(plugin_schema_default);
9998
+ return manifestValidator;
9999
+ }
10000
+ function readManifest(root, fail) {
10001
+ const path = join17(root, MANIFEST_FILE);
10002
+ const kind = pathKind(root, path);
10003
+ if (kind !== "file") {
10004
+ fail(kind === "outside" ? "resolves outside the plugin folder" : "missing");
10005
+ return null;
10006
+ }
10007
+ const raw = readJson(path, fail);
10008
+ if (raw === undefined)
10009
+ return null;
10010
+ if (!isObject(raw)) {
10011
+ fail("must be a JSON object");
10012
+ return null;
10013
+ }
10014
+ const manifest = {};
10015
+ for (const [field, value] of Object.entries(raw)) {
10016
+ if (!MANIFEST_FIELDS.has(field))
10017
+ fail(`unknown field "${field}" is ignored`);
10018
+ else if (field === "extensions" && !isObject(value)) {
10019
+ fail('"extensions" is not an object and is ignored');
10020
+ } else
10021
+ manifest[field] = value;
10022
+ }
10023
+ if (typeof manifest.$schema === "string" && manifest.$schema !== MANIFEST_SCHEMA_ID) {
10024
+ fail(`unsupported Agent Plugins version: $schema "${manifest.$schema}"`);
10025
+ return null;
10026
+ }
10027
+ const checked = manifestSchema().safeParse(manifest);
10028
+ if (!checked.success) {
10029
+ for (const issue of checked.error.issues) {
10030
+ fail(`${issue.path.length > 0 ? `${issue.path.join(".")}: ` : ""}${issue.message}`);
10031
+ }
10032
+ return null;
10033
+ }
10034
+ return { id: String(manifest.name) };
10035
+ }
10036
+ function readSkill(root, dir, name, fail) {
10037
+ const where = `${SKILLS_DIR}/${name}/${SKILL_FILE}`;
10038
+ const path = join17(dir, SKILLS_DIR, name, SKILL_FILE);
10039
+ const kind = pathKind(root, path);
10040
+ if (kind === "outside") {
10041
+ fail(where, "resolves outside the plugin folder; skipped");
10042
+ return null;
10043
+ }
10044
+ if (kind !== "file")
10045
+ return null;
10046
+ const parsed = parseFrontmatter(readText(path));
10047
+ if (!parsed.ok) {
10048
+ fail(where, `${parsed.problem}; skipped`);
10049
+ return null;
10050
+ }
10051
+ const problems = [];
10052
+ const skillName = parsed.meta.name;
10053
+ const description = typeof parsed.meta.description === "string" ? parsed.meta.description.trim() : "";
10054
+ if (skillName !== name)
10055
+ problems.push(`name must be the folder's name "${name}"`);
10056
+ else if (!SKILL_NAME.test(name) || name.length > MAX_SKILL_NAME_CHARS) {
10057
+ problems.push("name must be 1-64 lowercase letters, digits and single inner hyphens");
10058
+ }
10059
+ if (!description)
10060
+ problems.push("description (when to read it) is missing");
10061
+ else if (description.length > MAX_SKILL_DESCRIPTION_CHARS) {
10062
+ problems.push(`description is over ${MAX_SKILL_DESCRIPTION_CHARS} characters`);
10063
+ }
10064
+ if (problems.length > 0) {
10065
+ fail(where, `${problems.join("; ")}; skipped`);
10066
+ return null;
10067
+ }
10068
+ return { name, description, path };
10069
+ }
10070
+ function readSkills(root, dir, fail) {
10071
+ const skillsDir = join17(root, SKILLS_DIR);
10072
+ const kind = pathKind(root, skillsDir);
10073
+ if (kind === "missing")
10074
+ return [];
10075
+ if (kind !== "dir") {
10076
+ fail(SKILLS_DIR, kind === "outside" ? "resolves outside the plugin folder" : "not a folder");
10077
+ return [];
10078
+ }
10079
+ return readdirSync2(skillsDir).filter(visible).sort(byName).flatMap((name) => readSkill(root, dir, name, fail) ?? []);
10080
+ }
10081
+ function remoteUrlProblem(raw) {
10082
+ let url;
10083
+ try {
10084
+ url = new URL(raw);
10085
+ } catch {
10086
+ return "url must be an absolute http or https URL";
10087
+ }
10088
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
10089
+ return "url must be an absolute http or https URL";
10090
+ }
10091
+ if (url.username || url.password)
10092
+ return "url must not contain user information";
10093
+ if (url.hash || raw.includes("#"))
10094
+ return "url must not contain a fragment";
10095
+ if (url.protocol === "http:" && !isLoopbackHost(url.hostname)) {
10096
+ return "a non-loopback url must use https";
10097
+ }
10098
+ return null;
10099
+ }
10100
+ function isLoopbackHost(hostname) {
10101
+ if (hostname === "localhost" || hostname === "[::1]")
10102
+ return true;
10103
+ const parts = hostname.split(".");
10104
+ return parts.length === 4 && parts[0] === "127" && parts.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255);
10105
+ }
10106
+ function readServer(name, spec, fail) {
10107
+ if (!isObject(spec) || typeof spec.type !== "string") {
10108
+ fail(`"${name}": a server is an object with a "type"; skipped`);
10109
+ return null;
10110
+ }
10111
+ if (spec.type === "stdio") {
10112
+ fail(`"${name}": stdio servers are not supported here (remote servers only); skipped`);
10113
+ return null;
10114
+ }
10115
+ const variant = REMOTE_SERVERS[spec.type];
10116
+ if (!variant) {
10117
+ fail(`"${name}": unknown type "${spec.type}"; skipped`);
10118
+ return null;
10119
+ }
10120
+ const allowed = new Set(Object.keys(variant.properties));
10121
+ const unknown = Object.keys(spec).find((key) => !allowed.has(key));
10122
+ if (unknown) {
10123
+ fail(`"${name}": field "${unknown}" does not belong to a ${spec.type} server; skipped`);
10124
+ return null;
10125
+ }
10126
+ if (typeof spec.url !== "string" || !spec.url) {
10127
+ fail(`"${name}": url is required; skipped`);
10128
+ return null;
10129
+ }
10130
+ const headers = spec.headers;
10131
+ if (headers !== undefined) {
10132
+ const values = isObject(headers) ? Object.entries(headers) : null;
10133
+ const lower = values?.map(([key]) => key.toLowerCase()) ?? [];
10134
+ if (!values || values.some(([, value]) => typeof value !== "string") || new Set(lower).size !== lower.length) {
10135
+ fail(`"${name}": headers must be distinct header names with string values; skipped`);
10136
+ return null;
10137
+ }
10138
+ }
10139
+ const server = {
10140
+ type: NODE_TRANSPORT[spec.type],
10141
+ url: spec.url,
10142
+ ...headers ? { headers } : {}
10143
+ };
10144
+ const urlProblem = remoteUrlProblem(spec.url);
10145
+ if (urlProblem) {
10146
+ fail(`"${name}": ${urlProblem}; skipped`);
10147
+ return null;
10148
+ }
10149
+ try {
10150
+ parseHostMcpServers({ [name]: server });
10151
+ } catch (error) {
10152
+ fail(`"${name}": ${error instanceof Error ? error.message : String(error)}; skipped`);
10153
+ return null;
10154
+ }
10155
+ return server;
10156
+ }
10157
+ function readMcpFile(root, fail) {
10158
+ const path = join17(root, MCP_FILE);
10159
+ const kind = pathKind(root, path);
10160
+ if (kind === "missing")
10161
+ return {};
10162
+ if (kind !== "file") {
10163
+ fail(`${kind === "outside" ? "resolves outside the plugin folder" : "not a file"}; no servers`);
10164
+ return {};
10165
+ }
10166
+ const raw = readJson(path, fail);
10167
+ if (raw === undefined)
10168
+ return {};
10169
+ const extra = isObject(raw) ? Object.keys(raw).find((key) => key !== "$schema" && key !== "mcpServers") : undefined;
10170
+ if (!isObject(raw) || raw.$schema !== MCP_SCHEMA_ID || !isObject(raw.mcpServers) || extra) {
10171
+ fail(`must be {"$schema": "${MCP_SCHEMA_ID}", "mcpServers": {\u2026}} and nothing else; no servers`);
10172
+ return {};
10173
+ }
10174
+ const servers = {};
10175
+ for (const [name, spec] of Object.entries(raw.mcpServers)) {
10176
+ const server = readServer(name, spec, fail);
10177
+ if (server)
10178
+ servers[name] = server;
10179
+ }
10180
+ return servers;
10181
+ }
10182
+ function loadTopicPlugins(dirs) {
10183
+ const problems = [];
10184
+ const plugins = [];
10185
+ const pluginOwner = new Map;
10186
+ const skillOwner = new Map;
10187
+ const serverOwner = new Map;
10188
+ for (const dir of dirs) {
10189
+ if (!isAbsolute5(dir)) {
10190
+ problems.push(`${dir}: a plugin is given by its folder's absolute path`);
10191
+ continue;
10192
+ }
10193
+ if (!existsSync16(dir) || !statSync7(dir).isDirectory()) {
10194
+ problems.push(`${dir}: not a folder`);
10195
+ continue;
10196
+ }
10197
+ const root = realpathSync5(dir);
10198
+ const failIn = (file, problem) => problems.push(`${dir}/${file}: ${problem}`);
10199
+ const manifest = readManifest(root, (problem) => failIn(MANIFEST_FILE, problem));
10200
+ if (!manifest)
10201
+ continue;
10202
+ const owner = pluginOwner.get(manifest.id);
10203
+ if (owner) {
10204
+ failIn(MANIFEST_FILE, `plugin name "${manifest.id}" is already used by ${owner}; skipped`);
10205
+ continue;
10206
+ }
10207
+ pluginOwner.set(manifest.id, dir);
10208
+ const unique = (owners, key, what, file) => {
10209
+ const other = owners.get(key);
10210
+ if (other)
10211
+ failIn(file, `${what} "${key}" is already used by ${other}; skipped`);
10212
+ else
10213
+ owners.set(key, dir);
10214
+ return !other;
10215
+ };
10216
+ const skills = readSkills(root, dir, failIn).filter((skill) => unique(skillOwner, skill.name, "skill name", SKILLS_DIR));
10217
+ const mcpServers = Object.fromEntries(Object.entries(readMcpFile(root, (problem) => failIn(MCP_FILE, problem))).filter(([name]) => unique(serverOwner, name, "server name", MCP_FILE)));
10218
+ plugins.push({ ...manifest, dir, skills, mcpServers });
10219
+ }
10220
+ return { plugins, problems };
10221
+ }
10222
+ function renderTopicPluginsPrompt(plugins) {
10223
+ const skills = plugins.flatMap((plugin) => plugin.skills);
10224
+ if (skills.length === 0)
10225
+ return "";
10226
+ return [
10227
+ "## Skills",
10228
+ "",
10229
+ "Each skill below is a guide for one kind of task. When a skill's description fits what you are about to do, first open its SKILL.md with your file-read tool and follow it. Other files of a skill sit in its folder and are linked from its SKILL.md.",
10230
+ "",
10231
+ ...skills.map((skill) => `- \`${skill.name}\`: ${skill.description} (file: ${skill.path})`)
10232
+ ].join(`
10233
+ `);
10234
+ }
10235
+ var MANIFEST_FILE = "plugin.json", SKILLS_DIR = "skills", SKILL_FILE = "SKILL.md", MCP_FILE = "mcp.json", MANIFEST_SCHEMA_ID, MCP_SCHEMA_ID, MANIFEST_FIELDS, REMOTE_SERVERS, NODE_TRANSPORT, SKILL_NAME, MAX_SKILL_NAME_CHARS = 64, MAX_SKILL_DESCRIPTION_CHARS = 1024, visible = (name) => !name.startsWith("."), byName = (a, b) => a < b ? -1 : a > b ? 1 : 0, isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value), manifestValidator = null;
10236
+ var init_plugins = __esm(() => {
10237
+ init_runtime_gateway();
10238
+ init_mcp_schema();
10239
+ init_plugin_schema();
10240
+ MANIFEST_SCHEMA_ID = plugin_schema_default.properties.$schema.const;
10241
+ MCP_SCHEMA_ID = mcp_schema_default.properties.$schema.const;
10242
+ MANIFEST_FIELDS = new Set(Object.keys(plugin_schema_default.properties));
10243
+ REMOTE_SERVERS = {
10244
+ "streamable-http": mcp_schema_default.$defs.streamableHttpServer,
10245
+ sse: mcp_schema_default.$defs.sseServer
10246
+ };
10247
+ NODE_TRANSPORT = { "streamable-http": "http", sse: "sse" };
10248
+ SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
10249
+ });
10250
+
9652
10251
  // ../../packages/core/src/prompts/builders.ts
9653
- import { readFileSync as readFileSync12 } from "fs";
10252
+ import { readFileSync as readFileSync13 } from "fs";
9654
10253
  import { resolve as resolve12 } from "path";
9655
10254
  function loadPrompt(filename, dir = SESSIONS_DIR) {
9656
- const raw = readFileSync12(resolve12(dir, filename), "utf-8");
10255
+ const raw = readFileSync13(resolve12(dir, filename), "utf-8");
9657
10256
  return raw.replace(/\{\{RESOURCES_DIR\}\}/g, RESOURCES_DIR);
9658
10257
  }
9659
10258
  function replaceVars(template, vars) {
@@ -9716,7 +10315,7 @@ function visualDesignGuide() {
9716
10315
  return _visualDesignGuide;
9717
10316
  }
9718
10317
  function loadAgentPrompt(filename) {
9719
- const raw = readFileSync12(resolve12(AGENTS_PROMPTS_DIR, filename), "utf-8");
10318
+ const raw = readFileSync13(resolve12(AGENTS_PROMPTS_DIR, filename), "utf-8");
9720
10319
  const match = raw.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
9721
10320
  if (!match)
9722
10321
  throw new Error(`Agent prompt ${filename} is missing frontmatter`);
@@ -9964,6 +10563,11 @@ function createPromptBuilders(host = {}) {
9964
10563
  ## Topic-Specific Instructions
9965
10564
  ${opts.description.trim()}`;
9966
10565
  }
10566
+ const plugins = renderTopicPluginsPrompt(opts.plugins ?? []);
10567
+ if (plugins)
10568
+ prompt += `
10569
+
10570
+ ${plugins}`;
9967
10571
  if (sessionKind === "manager") {
9968
10572
  const managerTemplate = replaceVars(template(opts.surface === "otium" ? {
9969
10573
  kind: "surface-profile",
@@ -10053,6 +10657,7 @@ var init_builders = __esm(() => {
10053
10657
  init_browser_backend();
10054
10658
  init_config();
10055
10659
  init_logger();
10660
+ init_plugins();
10056
10661
  PROMPTS_DIR = resolve12(PROJECT_ROOT, "src/prompts");
10057
10662
  SESSIONS_DIR = resolve12(PROMPTS_DIR, "sessions");
10058
10663
  SURFACE_PROFILE_FILES = {
@@ -10176,9 +10781,9 @@ var init_api_topic_brief = __esm(async () => {
10176
10781
  });
10177
10782
 
10178
10783
  // ../../packages/core/src/storage/wiki.ts
10179
- import { basename as basename3, dirname as dirname12, join as join17 } from "path";
10784
+ import { basename as basename3, dirname as dirname12, join as join18 } from "path";
10180
10785
  function getSharedWikiDir(workspaceDir = resolveStorageWorkspaceDir()) {
10181
- return workspaceDir === resolveStorageWorkspaceDir() ? resolveStorageSharedWikiDir() : join17(workspaceDir, "wiki");
10786
+ return workspaceDir === resolveStorageWorkspaceDir() ? resolveStorageSharedWikiDir() : join18(workspaceDir, "wiki");
10182
10787
  }
10183
10788
  var init_wiki = __esm(async () => {
10184
10789
  await init_storage_host();
@@ -10358,8 +10963,8 @@ var init_personal_general = __esm(async () => {
10358
10963
 
10359
10964
  // ../../packages/core/src/agents/archiver.ts
10360
10965
  import { randomUUID as randomUUID9 } from "crypto";
10361
- import { existsSync as existsSync16, readdirSync as readdirSync2, readFileSync as readFileSync13, statSync as statSync7 } from "fs";
10362
- import { join as join18 } from "path";
10966
+ import { existsSync as existsSync17, readdirSync as readdirSync3, readFileSync as readFileSync14, statSync as statSync8 } from "fs";
10967
+ import { join as join19 } from "path";
10363
10968
  function resolveMemoryLanguage() {
10364
10969
  const override = process.env.NEGOTIUM_MEMORY_LANG?.trim();
10365
10970
  return override && override.length > 0 ? override : resolveOutputLanguage();
@@ -10617,10 +11222,10 @@ function distillOneLine(summaryMd) {
10617
11222
  return "";
10618
11223
  }
10619
11224
  function findSummaryFile(storage, topicTitle, date, sinceMs, topicId) {
10620
- const dir = join18(storage.getWikiDir(), "summaries");
11225
+ const dir = join19(storage.getWikiDir(), "summaries");
10621
11226
  if (!storage.fileExists(dir))
10622
11227
  return null;
10623
- const predicted = join18(dir, wikiSummaryFilename(date, topicTitle, topicId));
11228
+ const predicted = join19(dir, wikiSummaryFilename(date, topicTitle, topicId));
10624
11229
  if (storage.fileExists(predicted) && storage.fileModifiedAt(predicted) >= sinceMs)
10625
11230
  return predicted;
10626
11231
  let best = null;
@@ -10628,7 +11233,7 @@ function findSummaryFile(storage, topicTitle, date, sinceMs, topicId) {
10628
11233
  if (!f.startsWith(`${date}-`) || !isTopicSummaryFile(f, topicId ?? "", topicTitle)) {
10629
11234
  continue;
10630
11235
  }
10631
- const p = join18(dir, f);
11236
+ const p = join19(dir, f);
10632
11237
  try {
10633
11238
  const m = storage.fileModifiedAt(p);
10634
11239
  if (m >= sinceMs && (!best || m > best.mtime))
@@ -10714,11 +11319,11 @@ var init_archiver = __esm(async () => {
10714
11319
  defaultArchiverRuntime = createArchiverRuntime({
10715
11320
  storage: {
10716
11321
  getWikiDir: getSharedWikiDir,
10717
- fileExists: existsSync16,
10718
- listDirectory: readdirSync2,
10719
- readTextFile: (path) => readFileSync13(path, "utf-8"),
10720
- fileSize: (path) => statSync7(path).size,
10721
- fileModifiedAt: (path) => statSync7(path).mtimeMs,
11322
+ fileExists: existsSync17,
11323
+ listDirectory: readdirSync3,
11324
+ readTextFile: (path) => readFileSync14(path, "utf-8"),
11325
+ fileSize: (path) => statSync8(path).size,
11326
+ fileModifiedAt: (path) => statSync8(path).mtimeMs,
10722
11327
  getGeneralTopicId: (userId, sourceTopicId) => {
10723
11328
  const source = sourceTopicId ? getTopic(sourceTopicId) : null;
10724
11329
  return source ? ensurePersonalGeneral(userId, source.surface, {
@@ -10759,9 +11364,9 @@ var init_archiver = __esm(async () => {
10759
11364
 
10760
11365
  // ../../packages/core/src/agents/auth-check.ts
10761
11366
  import { execFileSync as execFileSync5 } from "child_process";
10762
- import { existsSync as existsSync17 } from "fs";
11367
+ import { existsSync as existsSync18 } from "fs";
10763
11368
  import { homedir as homedir9, platform } from "os";
10764
- import { join as join19 } from "path";
11369
+ import { join as join20 } from "path";
10765
11370
  function hasMaestroCredential(host, key, userId) {
10766
11371
  if (userId && host.getVaultValue(userId, key)?.trim())
10767
11372
  return true;
@@ -10781,7 +11386,7 @@ function checkAgentAuth(agent, host = defaultAgentAuthHost, userId) {
10781
11386
  case "claude": {
10782
11387
  if (host.environment.ANTHROPIC_API_KEY)
10783
11388
  return { ok: true };
10784
- const path = join19(host.homeDirectory(), ".claude", ".credentials.json");
11389
+ const path = join20(host.homeDirectory(), ".claude", ".credentials.json");
10785
11390
  if (host.operatingSystem() === "darwin") {
10786
11391
  if (host.hasMacOsCredential("Claude Code-credentials") || host.exists(path)) {
10787
11392
  return { ok: true };
@@ -10838,7 +11443,7 @@ var init_auth_check = __esm(async () => {
10838
11443
  await init_vault();
10839
11444
  defaultAgentAuthHost = {
10840
11445
  codexAuthFilePath,
10841
- exists: existsSync17,
11446
+ exists: existsSync18,
10842
11447
  environment: process.env,
10843
11448
  homeDirectory: homedir9,
10844
11449
  operatingSystem: platform,
@@ -10855,7 +11460,7 @@ var init_auth_check = __esm(async () => {
10855
11460
  });
10856
11461
 
10857
11462
  // ../../packages/core/src/agents/fork.ts
10858
- import { existsSync as existsSync18, unlinkSync as unlinkSync8 } from "fs";
11463
+ import { existsSync as existsSync19, unlinkSync as unlinkSync8 } from "fs";
10859
11464
  function createAgentForkHelpers(host) {
10860
11465
  return {
10861
11466
  async forkAgentSession(options) {
@@ -10892,7 +11497,7 @@ var init_fork = __esm(async () => {
10892
11497
  await init_registry();
10893
11498
  defaultForkHelpers = createAgentForkHelpers({
10894
11499
  forkSession: (agent, options) => getRegistryOperations(agent).forkSession(options),
10895
- exists: existsSync18,
11500
+ exists: existsSync19,
10896
11501
  unlink: unlinkSync8,
10897
11502
  warn: (details, message) => logger.warn(details, message)
10898
11503
  });
@@ -11438,13 +12043,13 @@ function formatTopicArchiveTranscriptRecord(row, topicTitle, index) {
11438
12043
 
11439
12044
  // ../../packages/core/src/storage/topic-archive.ts
11440
12045
  import { mkdirSync as mkdirSync10, writeFileSync as writeFileSync8 } from "fs";
11441
- import { join as join20 } from "path";
12046
+ import { join as join21 } from "path";
11442
12047
  function archiveTopicMessages(topicId, topicTitle, options = {}) {
11443
12048
  const rows = options.afterRowid !== undefined ? getMessagesForTopicAfterRowid(topicId, options.afterRowid) : getAllMessagesForTopic(topicId);
11444
12049
  if (rows.length === 0)
11445
12050
  return null;
11446
12051
  const safeTopic = sanitizeTopicName(topicTitle, true);
11447
- const archiveDir = join20(getSharedWikiDir(), "archive");
12052
+ const archiveDir = join21(getSharedWikiDir(), "archive");
11448
12053
  mkdirSync10(archiveDir, { recursive: true });
11449
12054
  const date = new Date().toISOString().slice(0, 10);
11450
12055
  const reasonSuffix = options.reason && options.reason !== "delete" ? `_${options.reason}` : "";
@@ -11457,7 +12062,7 @@ function archiveTopicMessages(topicId, topicTitle, options = {}) {
11457
12062
  let path;
11458
12063
  while (true) {
11459
12064
  filename = `${safeTopic}_${date}${reasonSuffix}${counter === 1 ? "" : `_${counter}`}.jsonl`;
11460
- path = join20(archiveDir, filename);
12065
+ path = join21(archiveDir, filename);
11461
12066
  try {
11462
12067
  writeFileSync8(path, body, { flag: "wx" });
11463
12068
  break;
@@ -11502,7 +12107,7 @@ function archiveConversationEvents(topicId, topicTitle, userId, options = {}) {
11502
12107
  const entries = readRawConversation(userId, topicTitle);
11503
12108
  if (entries.length === 0)
11504
12109
  return null;
11505
- const archiveDir = join20(getSharedWikiDir(), "archive");
12110
+ const archiveDir = join21(getSharedWikiDir(), "archive");
11506
12111
  mkdirSync10(archiveDir, { recursive: true });
11507
12112
  const safeTopic = sanitizeTopicName(topicTitle, true);
11508
12113
  const date = new Date().toISOString().slice(0, 10);
@@ -11530,7 +12135,7 @@ function archiveConversationEvents(topicId, topicTitle, userId, options = {}) {
11530
12135
  let counter = 1;
11531
12136
  while (true) {
11532
12137
  const suffix = counter === 1 ? "" : `_${counter}`;
11533
- const path = join20(archiveDir, `${safeTopic}_${date}${reasonSuffix}_events${suffix}.jsonl`);
12138
+ const path = join21(archiveDir, `${safeTopic}_${date}${reasonSuffix}_events${suffix}.jsonl`);
11534
12139
  try {
11535
12140
  writeFileSync8(path, body, { flag: "wx" });
11536
12141
  logger.info({ topicId, topicTitle, archive: path, eventCount: entries.length }, "archiveConversationEvents: archived raw conversation events");
@@ -12228,7 +12833,7 @@ var init_runtime_process_leases = __esm(async () => {
12228
12833
 
12229
12834
  // ../../packages/core/src/agents/mcp-tools/ask-user.ts
12230
12835
  import { createHash as createHash5, randomUUID as randomUUID11 } from "crypto";
12231
- import { z } from "zod";
12836
+ import { z as z2 } from "zod";
12232
12837
  function normalizeAskText(value, maxChars) {
12233
12838
  if (typeof value !== "string")
12234
12839
  return;
@@ -12521,12 +13126,12 @@ function createAskUserRuntime(host) {
12521
13126
  name: "ask_user_question",
12522
13127
  description: "Ask the user a blocking multiple-choice question in the chat and wait for their selection. Use this instead of provider built-in AskUserQuestion. Use only when you cannot proceed safely without the user's choice.",
12523
13128
  schema: {
12524
- question: z.string().describe("The concise question to show to the user."),
12525
- choices: z.array(z.object({
12526
- label: z.string().describe("Choice label shown on the button."),
12527
- description: z.string().optional().describe("Optional one-sentence consequence.")
13129
+ question: z2.string().describe("The concise question to show to the user."),
13130
+ choices: z2.array(z2.object({
13131
+ label: z2.string().describe("Choice label shown on the button."),
13132
+ description: z2.string().optional().describe("Optional one-sentence consequence.")
12528
13133
  })).min(1).max(MAX_CHOICES).describe("Choices the user can select."),
12529
- idempotency_key: z.string().max(MAX_IDEMPOTENCY_KEY_CHARS).optional().describe("Optional retry key. Reusing it with the same question replays the existing result; reusing it with different content fails.")
13134
+ idempotency_key: z2.string().max(MAX_IDEMPOTENCY_KEY_CHARS).optional().describe("Optional retry key. Reusing it with the same question replays the existing result; reusing it with different content fails.")
12530
13135
  },
12531
13136
  async handler(input) {
12532
13137
  return askUserQuestion(ctx, input);
@@ -12760,7 +13365,7 @@ var init_manager_utils = () => {};
12760
13365
 
12761
13366
  // ../../packages/core/src/platform/playwright/browser-processes.ts
12762
13367
  import { execFileSync as execFileSync6 } from "child_process";
12763
- import { readdirSync as readdirSync3, unlinkSync as unlinkSync10 } from "fs";
13368
+ import { readdirSync as readdirSync4, unlinkSync as unlinkSync10 } from "fs";
12764
13369
  import { createServer as createServer2 } from "net";
12765
13370
  import { resolve as resolve14, sep as sep2 } from "path";
12766
13371
  function isPortInUse(port) {
@@ -12885,7 +13490,7 @@ function reapOrphanBrowsers(liveUserDataDirs) {
12885
13490
  }
12886
13491
  function cleanSingletonFiles(userDataDir) {
12887
13492
  try {
12888
- const files = readdirSync3(userDataDir);
13493
+ const files = readdirSync4(userDataDir);
12889
13494
  for (const f of files) {
12890
13495
  if (f.startsWith("Singleton")) {
12891
13496
  try {
@@ -12929,9 +13534,9 @@ var init_browser_processes = __esm(async () => {
12929
13534
 
12930
13535
  // ../../packages/core/src/platform/playwright/headed-launch.ts
12931
13536
  import { accessSync as accessSync3, constants as constants3 } from "fs";
12932
- import { delimiter as delimiter2, isAbsolute as isAbsolute6, resolve as resolve15 } from "path";
13537
+ import { delimiter as delimiter2, isAbsolute as isAbsolute7, resolve as resolve15 } from "path";
12933
13538
  function findExecutableOnPath(command, environment = process.env) {
12934
- const candidates = isAbsolute6(command) ? [command] : (environment.PATH ?? "").split(delimiter2).filter(Boolean).map((directory) => resolve15(directory, command));
13539
+ const candidates = isAbsolute7(command) ? [command] : (environment.PATH ?? "").split(delimiter2).filter(Boolean).map((directory) => resolve15(directory, command));
12935
13540
  for (const candidate of candidates) {
12936
13541
  try {
12937
13542
  accessSync3(candidate, constants3.X_OK);
@@ -13032,7 +13637,7 @@ var init_vault_public = __esm(async () => {
13032
13637
  import { randomBytes as randomBytes6, timingSafeEqual as timingSafeEqual2 } from "crypto";
13033
13638
  import { createServer as createServer3 } from "net";
13034
13639
  import { tmpdir as tmpdir3 } from "os";
13035
- import { join as join21 } from "path";
13640
+ import { join as join22 } from "path";
13036
13641
  function deepMapStrings2(value, transform) {
13037
13642
  if (typeof value === "string")
13038
13643
  return transform(value);
@@ -13119,7 +13724,7 @@ function authorized(actual, expected) {
13119
13724
  }
13120
13725
  async function createBrowserVaultBroker(userId) {
13121
13726
  const token = randomBytes6(32).toString("hex");
13122
- const socketPath = ipcEndpoint(join21(process.platform === "win32" ? tmpdir3() : "/tmp", `negotium-browser-vault-${process.pid}-${randomBytes6(8).toString("hex")}.sock`));
13727
+ const socketPath = ipcEndpoint(join22(process.platform === "win32" ? tmpdir3() : "/tmp", `negotium-browser-vault-${process.pid}-${randomBytes6(8).toString("hex")}.sock`));
13123
13728
  const retainedForms = new Map;
13124
13729
  const leases = new Map;
13125
13730
  const sockets = new Set;
@@ -13334,21 +13939,21 @@ import { execFileSync as execFileSync7, spawn as spawn5 } from "child_process";
13334
13939
  import { createHash as createHash6, randomBytes as randomBytes7, timingSafeEqual as timingSafeEqual3 } from "crypto";
13335
13940
  import {
13336
13941
  cpSync,
13337
- existsSync as existsSync20,
13942
+ existsSync as existsSync21,
13338
13943
  mkdirSync as mkdirSync11,
13339
- readFileSync as readFileSync15,
13944
+ readFileSync as readFileSync16,
13340
13945
  rmSync as rmSync3,
13341
13946
  unlinkSync as unlinkSync11,
13342
13947
  writeFileSync as writeFileSync9
13343
13948
  } from "fs";
13344
- import { dirname as dirname13, join as join22, resolve as resolve16 } from "path";
13949
+ import { dirname as dirname13, join as join23, resolve as resolve16 } from "path";
13345
13950
  function removeDefaultProfileDataDir(userDataDir) {
13346
13951
  const root = resolve16(BROWSER_PROFILES_DIR);
13347
13952
  const target = resolve16(userDataDir);
13348
13953
  if (dirname13(target) !== root) {
13349
13954
  throw new Error(`Refusing to delete browser profile outside managed root: ${target}`);
13350
13955
  }
13351
- const existed = existsSync20(target);
13956
+ const existed = existsSync21(target);
13352
13957
  rmSync3(target, { recursive: true, force: true });
13353
13958
  return existed;
13354
13959
  }
@@ -13437,14 +14042,14 @@ function portFileName(instanceKey) {
13437
14042
  function writePortFile(instanceKey, port) {
13438
14043
  try {
13439
14044
  mkdirSync11(managerHost.portsDir, { recursive: true });
13440
- writeFileSync9(join22(managerHost.portsDir, portFileName(instanceKey)), String(port));
14045
+ writeFileSync9(join23(managerHost.portsDir, portFileName(instanceKey)), String(port));
13441
14046
  } catch (e) {
13442
14047
  logger.warn({ err: e, instanceKey, port }, "Failed to save playwright port file");
13443
14048
  }
13444
14049
  }
13445
14050
  function deletePortFile(instanceKey) {
13446
14051
  try {
13447
- unlinkSync11(join22(managerHost.portsDir, portFileName(instanceKey)));
14052
+ unlinkSync11(join23(managerHost.portsDir, portFileName(instanceKey)));
13448
14053
  } catch (e) {
13449
14054
  if (e.code === "ENOENT")
13450
14055
  return;
@@ -13944,11 +14549,11 @@ async function cloneProfileForChild(opts) {
13944
14549
  killInstance(dstKey);
13945
14550
  await delay(500);
13946
14551
  }
13947
- if (!existsSync20(srcDir)) {
14552
+ if (!existsSync21(srcDir)) {
13948
14553
  return { copied: false, srcDir, dstDir, reason: "src-missing" };
13949
14554
  }
13950
14555
  try {
13951
- if (existsSync20(dstDir)) {
14556
+ if (existsSync21(dstDir)) {
13952
14557
  rmSync3(dstDir, { recursive: true, force: true });
13953
14558
  }
13954
14559
  mkdirSync11(dirname13(dstDir), { recursive: true });
@@ -14247,7 +14852,7 @@ var init_compaction_tool_projection = __esm(() => {
14247
14852
  // ../../packages/core/src/storage/token-stats.ts
14248
14853
  import { createHash as createHash8 } from "crypto";
14249
14854
  import { mkdirSync as mkdirSync12, writeFileSync as writeFileSync10 } from "fs";
14250
- import { join as join23 } from "path";
14855
+ import { join as join24 } from "path";
14251
14856
  function emptyBucket() {
14252
14857
  return {
14253
14858
  inputTokens: 0,
@@ -14266,7 +14871,7 @@ function queriesPath(userId) {
14266
14871
  const fileId = tokenStatsFileId(userId);
14267
14872
  const logDir = resolveStorageLogDir();
14268
14873
  mkdirSync12(logDir, { recursive: true });
14269
- return join23(logDir, `token-queries-${fileId}.jsonl`);
14874
+ return join24(logDir, `token-queries-${fileId}.jsonl`);
14270
14875
  }
14271
14876
  function loadRecords(userId) {
14272
14877
  try {
@@ -15108,7 +15713,7 @@ var init_runtime_turn_requests = __esm(async () => {
15108
15713
  import { randomUUID as randomUUID13 } from "crypto";
15109
15714
  import { mkdtempSync as mkdtempSync2, rmSync as rmSync4, writeFileSync as writeFileSync12 } from "fs";
15110
15715
  import { tmpdir as tmpdir4 } from "os";
15111
- import { join as join24 } from "path";
15716
+ import { join as join25 } from "path";
15112
15717
  async function fenceTopicWork(topicId, maintenance) {
15113
15718
  for (const queryId of cancelRuntimeUserTurnRequestsBeforeEpoch(topicId, maintenance.epoch)) {
15114
15719
  WsHub.get().broadcastAborted(topicId, queryId, "stopped");
@@ -15317,7 +15922,7 @@ function formatCompactElapsed(startedAt) {
15317
15922
  async function summarizeTopicContext(request) {
15318
15923
  const startedAt = Date.now();
15319
15924
  const sessionIds = [];
15320
- const compactCwd = mkdtempSync2(join24(tmpdir4(), "negotium-compact-"));
15925
+ const compactCwd = mkdtempSync2(join25(tmpdir4(), "negotium-compact-"));
15321
15926
  const abortController = new AbortController;
15322
15927
  const relayAbort = () => abortController.abort(request.signal?.reason);
15323
15928
  if (request.signal?.aborted)
@@ -15344,7 +15949,7 @@ async function summarizeTopicContext(request) {
15344
15949
  let error = "";
15345
15950
  let toolViolation = false;
15346
15951
  let compactionLogCalls = 0;
15347
- const compactionLogPath = join24(compactCwd, "conversation.log");
15952
+ const compactionLogPath = join25(compactCwd, "conversation.log");
15348
15953
  try {
15349
15954
  const compactionMcp = useCompactionLog ? {
15350
15955
  compact_log: {
@@ -16104,16 +16709,16 @@ var init_derive = __esm(async () => {
16104
16709
 
16105
16710
  // ../../packages/core/src/query/state.ts
16106
16711
  import { mkdirSync as mkdirSync15, renameSync as renameSync7, unlinkSync as unlinkSync14, writeFileSync as writeFileSync13 } from "fs";
16107
- import { basename as basename4, join as join25 } from "path";
16712
+ import { basename as basename4, join as join26 } from "path";
16108
16713
  function createQueryStateStore(options) {
16109
16714
  const sanitize = options.sanitizeTopicId ?? sanitizeId;
16110
- const queryStateDirPath = (userId) => join25(options.usersLogDir, String(userId), "active-queries");
16111
- const queryStateFile = (userId, topicId) => join25(queryStateDirPath(userId), `${sanitize(topicId)}.json`);
16715
+ const queryStateDirPath = (userId) => join26(options.usersLogDir, String(userId), "active-queries");
16716
+ const queryStateFile = (userId, topicId) => join26(queryStateDirPath(userId), `${sanitize(topicId)}.json`);
16112
16717
  const legacyQueryStateFile = (userId, topicName) => {
16113
16718
  if (!topicName || topicName === "." || topicName === ".." || basename4(topicName) !== topicName) {
16114
16719
  return null;
16115
16720
  }
16116
- return join25(queryStateDirPath(userId), `${topicName}.json`);
16721
+ return join26(queryStateDirPath(userId), `${topicName}.json`);
16117
16722
  };
16118
16723
  return {
16119
16724
  write(userId, topicId, topicName, task) {
@@ -16234,14 +16839,14 @@ var init_actor_topic_reach = __esm(async () => {
16234
16839
  });
16235
16840
 
16236
16841
  // ../../packages/core/src/query/session-inbox-path.ts
16237
- import { join as join26 } from "path";
16842
+ import { join as join27 } from "path";
16238
16843
  function sessionInboxPath(userId, topicId) {
16239
16844
  const key = Buffer.from(topicId, "utf8").toString("base64url");
16240
- return join26(SESSION_INBOX_DIR, userId, `${TOPIC_ID_FILE_PREFIX}${key}${JSONL_SUFFIX}`);
16845
+ return join27(SESSION_INBOX_DIR, userId, `${TOPIC_ID_FILE_PREFIX}${key}${JSONL_SUFFIX}`);
16241
16846
  }
16242
16847
  function scheduledSessionInboxPath(userId, topicId) {
16243
16848
  const key = Buffer.from(topicId, "utf8").toString("base64url");
16244
- return join26(SESSION_INBOX_DIR, userId, `${TOPIC_ID_FILE_PREFIX}${key}${SCHEDULE_SUFFIX}`);
16849
+ return join27(SESSION_INBOX_DIR, userId, `${TOPIC_ID_FILE_PREFIX}${key}${SCHEDULE_SUFFIX}`);
16245
16850
  }
16246
16851
  var TOPIC_ID_FILE_PREFIX = "topic-id-", JSONL_SUFFIX = ".jsonl", SCHEDULE_SUFFIX = ".schedule";
16247
16852
  var init_session_inbox_path = __esm(() => {
@@ -16249,12 +16854,12 @@ var init_session_inbox_path = __esm(() => {
16249
16854
  });
16250
16855
 
16251
16856
  // ../../packages/core/src/storage/session-inbox-signal.ts
16252
- import { join as join27 } from "path";
16857
+ import { join as join28 } from "path";
16253
16858
  var SESSION_INBOX_WAKE_FILE, listeners;
16254
16859
  var init_session_inbox_signal = __esm(() => {
16255
16860
  init_config();
16256
16861
  init_logger();
16257
- SESSION_INBOX_WAKE_FILE = join27(SESSION_INBOX_DIR, ".wake");
16862
+ SESSION_INBOX_WAKE_FILE = join28(SESSION_INBOX_DIR, ".wake");
16258
16863
  listeners = new Set;
16259
16864
  });
16260
16865
 
@@ -16292,13 +16897,13 @@ var init_session_inbox = __esm(async () => {
16292
16897
 
16293
16898
  // ../../packages/core/src/query/session-inbox-cleanup.ts
16294
16899
  import { unlinkSync as unlinkSync15 } from "fs";
16295
- import { basename as basename5, join as join28 } from "path";
16900
+ import { basename as basename5, join as join29 } from "path";
16296
16901
  function cleanupSessionInboxFiles(userId, topicId, legacyTopicTitle) {
16297
16902
  const live = sessionInboxPath(userId, topicId);
16298
16903
  const scheduled = scheduledSessionInboxPath(userId, topicId);
16299
16904
  const candidates = new Set([live, `${live}.processing`, scheduled, `${scheduled}.processing`]);
16300
16905
  if (legacyTopicTitle && legacyTopicTitle !== "." && legacyTopicTitle !== ".." && basename5(legacyTopicTitle) === legacyTopicTitle) {
16301
- const legacyBase = join28(SESSION_INBOX_DIR, userId, legacyTopicTitle);
16906
+ const legacyBase = join29(SESSION_INBOX_DIR, userId, legacyTopicTitle);
16302
16907
  for (const suffix of [".jsonl", ".jsonl.processing", ".schedule", ".schedule.processing"]) {
16303
16908
  candidates.add(`${legacyBase}${suffix}`);
16304
16909
  }
@@ -16538,35 +17143,35 @@ import {
16538
17143
  closeSync as closeSync2,
16539
17144
  mkdirSync as mkdirSync16,
16540
17145
  openSync as openSync2,
16541
- readdirSync as readdirSync4,
16542
- readFileSync as readFileSync16,
16543
- statSync as statSync9,
17146
+ readdirSync as readdirSync5,
17147
+ readFileSync as readFileSync17,
17148
+ statSync as statSync10,
16544
17149
  unlinkSync as unlinkSync16,
16545
17150
  writeFileSync as writeFileSync14
16546
17151
  } from "fs";
16547
- import { dirname as dirname15, join as join29 } from "path";
17152
+ import { dirname as dirname15, join as join30 } from "path";
16548
17153
  function pendingAskDir(userId) {
16549
17154
  const rawUserId = String(userId);
16550
17155
  const safeUserId = /^[A-Za-z0-9][A-Za-z0-9_.@-]{0,255}$/.test(rawUserId) && !rawUserId.includes("..") ? rawUserId : `sha256-${createHash10("sha256").update(rawUserId).digest("hex")}`;
16551
- return join29(resolveStorageSessionAsksDir(), safeUserId);
17156
+ return join30(resolveStorageSessionAsksDir(), safeUserId);
16552
17157
  }
16553
17158
  function encodeAskKey(key) {
16554
17159
  return JSON.stringify([key.from, key.to]);
16555
17160
  }
16556
17161
  function pendingAskPath(key) {
16557
17162
  const digest = createHash10("sha256").update(encodeAskKey(key)).digest("hex");
16558
- return join29(pendingAskDir(key.userId), `${ASK_FILENAME_PREFIX}${digest}.pending`);
17163
+ return join30(pendingAskDir(key.userId), `${ASK_FILENAME_PREFIX}${digest}.pending`);
16559
17164
  }
16560
17165
  function v2PendingAskPath(key) {
16561
17166
  const encoded = Buffer.from(encodeAskKey(key), "utf8").toString("base64url");
16562
- return join29(pendingAskDir(key.userId), `${V2_ASK_FILENAME_PREFIX}${encoded}.pending`);
17167
+ return join30(pendingAskDir(key.userId), `${V2_ASK_FILENAME_PREFIX}${encoded}.pending`);
16563
17168
  }
16564
17169
  function legacyPendingAskPath(key) {
16565
17170
  if (key.from.includes("/") || key.from.includes("\\") || key.to.includes("/") || key.to.includes("\\") || key.from.includes("\x00") || key.to.includes("\x00")) {
16566
17171
  return null;
16567
17172
  }
16568
17173
  const dir = pendingAskDir(key.userId);
16569
- const candidate = join29(dir, `${key.from}___${key.to}.pending`);
17174
+ const candidate = join30(dir, `${key.from}___${key.to}.pending`);
16570
17175
  return dirname15(candidate) === dir ? candidate : null;
16571
17176
  }
16572
17177
  function parsePendingAskFilename(fileName) {
@@ -16588,11 +17193,11 @@ function parsePendingAskFilename(fileName) {
16588
17193
  }
16589
17194
  function readPendingAskFile(path, fallback) {
16590
17195
  try {
16591
- const raw = readFileSync16(path, "utf8").trim();
17196
+ const raw = readFileSync17(path, "utf8").trim();
16592
17197
  if (!raw)
16593
17198
  return null;
16594
17199
  if (!raw.startsWith("{")) {
16595
- const ts = new Date(statSync9(path).mtimeMs).toISOString();
17200
+ const ts = new Date(statSync10(path).mtimeMs).toISOString();
16596
17201
  return {
16597
17202
  userId: fallback.userId,
16598
17203
  from: fallback.from,
@@ -16712,13 +17317,13 @@ function deletePendingAsksForTopic(args) {
16712
17317
  const dir = pendingAskDir(args.userId);
16713
17318
  let files;
16714
17319
  try {
16715
- files = readdirSync4(dir);
17320
+ files = readdirSync5(dir);
16716
17321
  } catch {
16717
17322
  return 0;
16718
17323
  }
16719
17324
  let deleted = 0;
16720
17325
  for (const fileName of files) {
16721
- const path = join29(dir, fileName);
17326
+ const path = join30(dir, fileName);
16722
17327
  const parsed = parsePendingAskFilename(fileName);
16723
17328
  const record = readPendingAskFile(path, {
16724
17329
  userId: args.userId,
@@ -17394,82 +17999,6 @@ body{font-family:system-ui,-apple-system,"Segoe UI",sans-serif;background:var(--
17394
17999
  </style>`;
17395
18000
  });
17396
18001
 
17397
- // ../../packages/core/src/runtime-gateway.ts
17398
- function parseHostMcpServers(value) {
17399
- if (value === undefined)
17400
- return;
17401
- if (!value || typeof value !== "object" || Array.isArray(value)) {
17402
- throw new TypeError("hostMcpServers must be an object");
17403
- }
17404
- const parsedEntries = [];
17405
- for (const [name, raw] of Object.entries(value)) {
17406
- if (!HOST_MCP_SERVER_NAME.test(name)) {
17407
- throw new TypeError(`invalid host MCP server name: ${name}`);
17408
- }
17409
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
17410
- throw new TypeError(`hostMcpServers.${name} must be an object`);
17411
- }
17412
- const spec = raw;
17413
- const unsupported = Object.keys(spec).find((key) => !HOST_MCP_SERVER_KEYS.has(key));
17414
- if (unsupported) {
17415
- throw new TypeError(`hostMcpServers.${name}.${unsupported} is not allowed`);
17416
- }
17417
- if (spec.type !== "sse" && spec.type !== "http") {
17418
- throw new TypeError(`hostMcpServers.${name}.type must be sse or http`);
17419
- }
17420
- if (typeof spec.url !== "string") {
17421
- throw new TypeError(`hostMcpServers.${name}.url must be a string`);
17422
- }
17423
- let url;
17424
- try {
17425
- url = new URL(spec.url);
17426
- } catch {
17427
- throw new TypeError(`hostMcpServers.${name}.url must be a valid URL`);
17428
- }
17429
- if (url.protocol !== "http:" && url.protocol !== "https:") {
17430
- throw new TypeError(`hostMcpServers.${name}.url must use http or https`);
17431
- }
17432
- let headers;
17433
- if (spec.headers !== undefined) {
17434
- if (!spec.headers || typeof spec.headers !== "object" || Array.isArray(spec.headers)) {
17435
- throw new TypeError(`hostMcpServers.${name}.headers must be an object`);
17436
- }
17437
- const headerEntries = [];
17438
- for (const [key, headerValue] of Object.entries(spec.headers)) {
17439
- if (!HTTP_HEADER_NAME.test(key) || typeof headerValue !== "string") {
17440
- throw new TypeError(`hostMcpServers.${name}.headers must contain string values`);
17441
- }
17442
- try {
17443
- new Headers([[key, headerValue]]);
17444
- } catch {
17445
- throw new TypeError(`hostMcpServers.${name}.headers contains an invalid header`);
17446
- }
17447
- headerEntries.push([key, headerValue]);
17448
- }
17449
- headers = Object.fromEntries(headerEntries);
17450
- }
17451
- if (spec.timeout !== undefined && (typeof spec.timeout !== "number" || !Number.isFinite(spec.timeout) || spec.timeout <= 0)) {
17452
- throw new TypeError(`hostMcpServers.${name}.timeout must be a positive number`);
17453
- }
17454
- parsedEntries.push([
17455
- name,
17456
- {
17457
- type: spec.type,
17458
- url: url.toString(),
17459
- ...headers ? { headers } : {},
17460
- ...spec.timeout !== undefined ? { timeout: spec.timeout } : {}
17461
- }
17462
- ]);
17463
- }
17464
- return Object.fromEntries(parsedEntries);
17465
- }
17466
- var HOST_MCP_SERVER_NAME, HOST_MCP_SERVER_KEYS, HTTP_HEADER_NAME;
17467
- var init_runtime_gateway = __esm(() => {
17468
- HOST_MCP_SERVER_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
17469
- HOST_MCP_SERVER_KEYS = new Set(["type", "url", "headers", "timeout"]);
17470
- HTTP_HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
17471
- });
17472
-
17473
18002
  // ../../packages/core/src/storage/topic-host-mcp-grants.ts
17474
18003
  function getTopicHostMcpGrant(topicId) {
17475
18004
  const row = db.query("SELECT servers_json FROM api_topic_host_mcp_grants WHERE topic_id = ?").get(topicId);
@@ -17778,7 +18307,7 @@ var init_lifecycle = __esm(async () => {
17778
18307
 
17779
18308
  // ../../packages/core/src/runtime/attachments.ts
17780
18309
  import { copyFileSync as copyFileSync2, mkdirSync as mkdirSync17, writeFileSync as writeFileSync15 } from "fs";
17781
- import { basename as basename6, join as join30 } from "path";
18310
+ import { basename as basename6, join as join31 } from "path";
17782
18311
  function workspaceCwdFor(topicId) {
17783
18312
  return resolveTopicWorkspaceDir(topicId);
17784
18313
  }
@@ -17791,7 +18320,7 @@ function materializePromptAttachments(topicId, queryId, attachmentIds) {
17791
18320
  if (!attachmentIds?.length)
17792
18321
  return [];
17793
18322
  const out = [];
17794
- const destDir = join30(workspaceCwdFor(topicId), "attachments", queryId);
18323
+ const destDir = join31(workspaceCwdFor(topicId), "attachments", queryId);
17795
18324
  for (const rawId of attachmentIds) {
17796
18325
  if (typeof rawId !== "string")
17797
18326
  continue;
@@ -17808,7 +18337,7 @@ function materializePromptAttachments(topicId, queryId, attachmentIds) {
17808
18337
  mkdirSync17(destDir, { recursive: true });
17809
18338
  const index = String(out.length + 1).padStart(2, "0");
17810
18339
  const safeName = safeAttachmentFilename(attachment.filename, fileId);
17811
- const destPath = join30(destDir, `${index}-${fileId.slice(0, 8)}-${safeName}`);
18340
+ const destPath = join31(destDir, `${index}-${fileId.slice(0, 8)}-${safeName}`);
17812
18341
  copyFileSync2(sourcePath, destPath);
17813
18342
  out.push({
17814
18343
  id: attachment.id,
@@ -18292,7 +18821,7 @@ var init_vault_request_gates = __esm(async () => {
18292
18821
 
18293
18822
  // ../../packages/core/src/agents/mcp-tools/request-vault.ts
18294
18823
  import { createHash as createHash12, randomUUID as randomUUID17 } from "crypto";
18295
- import { z as z4 } from "zod";
18824
+ import { z as z5 } from "zod";
18296
18825
  function requestBodyHash(key, description) {
18297
18826
  return createHash12("sha256").update(JSON.stringify({ key, description })).digest("hex");
18298
18827
  }
@@ -18559,10 +19088,10 @@ function createRequestVaultRuntime(host) {
18559
19088
  name: "request_vault_secret",
18560
19089
  description: "Ask the user to store a secret value in their Vault. You choose the key name and a short description of what to paste; the user types only the value on a surface that can mask it, and you never see the raw value. Use this instead of asking the user to paste a secret directly into chat. After it succeeds, reference the value as {{KEY}} in supported transient tool inputs. Fails if the key already exists unless you pass overwrite: true.",
18561
19090
  schema: {
18562
- key: z4.string().describe("Vault key name, e.g. STRIPE_API_KEY. Letters/digits/underscores, must start with a letter."),
18563
- description: z4.string().max(MAX_DESCRIPTION_CHARS).describe("One sentence telling the user what value to paste and where it's from."),
18564
- overwrite: z4.boolean().optional().describe("Set true to replace the value of a key that already exists. Defaults to false, which fails instead of silently clobbering an existing secret."),
18565
- idempotency_key: z4.string().max(MAX_IDEMPOTENCY_KEY_CHARS2).optional().describe("Optional retry key. Reusing it with the same key/description replays the existing result; reusing it with different content fails.")
19091
+ key: z5.string().describe("Vault key name, e.g. STRIPE_API_KEY. Letters/digits/underscores, must start with a letter."),
19092
+ description: z5.string().max(MAX_DESCRIPTION_CHARS).describe("One sentence telling the user what value to paste and where it's from."),
19093
+ overwrite: z5.boolean().optional().describe("Set true to replace the value of a key that already exists. Defaults to false, which fails instead of silently clobbering an existing secret."),
19094
+ idempotency_key: z5.string().max(MAX_IDEMPOTENCY_KEY_CHARS2).optional().describe("Optional retry key. Reusing it with the same key/description replays the existing result; reusing it with different content fails.")
18566
19095
  },
18567
19096
  async handler(input) {
18568
19097
  return requestVaultSecret(ctx, input);
@@ -18599,7 +19128,7 @@ function createRequestVaultRuntime(host) {
18599
19128
  name: "delete_vault_secret",
18600
19129
  description: "Permanently delete a key from the user's Vault. This removes the stored value outright \u2014 there is no confirmation step and no undo. Use request_vault_secret with overwrite: true instead if the goal is just to replace a value.",
18601
19130
  schema: {
18602
- key: z4.string().describe("Vault key name to delete, e.g. STRIPE_API_KEY.")
19131
+ key: z5.string().describe("Vault key name to delete, e.g. STRIPE_API_KEY.")
18603
19132
  },
18604
19133
  async handler(input) {
18605
19134
  return deleteVaultSecret(ctx, input);
@@ -18905,8 +19434,8 @@ var init_visual_html = __esm(() => {
18905
19434
  });
18906
19435
 
18907
19436
  // ../../packages/core/src/runtime/visuals.ts
18908
- import { realpathSync as realpathSync5 } from "fs";
18909
- import { isAbsolute as isAbsolute7, resolve as resolve17 } from "path";
19437
+ import { realpathSync as realpathSync6 } from "fs";
19438
+ import { isAbsolute as isAbsolute8, resolve as resolve17 } from "path";
18910
19439
  function activeVisualHtmlForPrompt(html) {
18911
19440
  if (html.length <= ACTIVE_VISUAL_PROMPT_MAX_CHARS) {
18912
19441
  return { html, omittedChars: 0 };
@@ -18955,8 +19484,8 @@ function topicAllowsVisualFileId(topicId, fileId) {
18955
19484
  }
18956
19485
  function isPathInside(baseDir, filePath) {
18957
19486
  try {
18958
- const realBase = realpathSync5(resolve17(baseDir));
18959
- const real = realpathSync5(resolve17(filePath));
19487
+ const realBase = realpathSync6(resolve17(baseDir));
19488
+ const real = realpathSync6(resolve17(filePath));
18960
19489
  return isInsideDir(real, realBase);
18961
19490
  } catch {
18962
19491
  return false;
@@ -19011,10 +19540,10 @@ function locateVisualMediaInput(topicId, input) {
19011
19540
  }
19012
19541
  const rawPath = input.file_path.trim();
19013
19542
  const cwd = workspaceCwdFor(topicId);
19014
- const candidate = isAbsolute7(rawPath) ? rawPath : resolve17(cwd, rawPath);
19543
+ const candidate = isAbsolute8(rawPath) ? rawPath : resolve17(cwd, rawPath);
19015
19544
  let realCandidate;
19016
19545
  try {
19017
- realCandidate = realpathSync5(candidate);
19546
+ realCandidate = realpathSync6(candidate);
19018
19547
  } catch {
19019
19548
  return { error: `file not found: ${rawPath}` };
19020
19549
  }
@@ -19067,8 +19596,8 @@ var init_visuals = __esm(async () => {
19067
19596
 
19068
19597
  // ../../packages/core/src/runtime/turn-event-stream.ts
19069
19598
  import { randomUUID as randomUUID18 } from "crypto";
19070
- import { realpathSync as realpathSync6, statSync as statSync10 } from "fs";
19071
- import { isAbsolute as isAbsolute8, resolve as resolve18 } from "path";
19599
+ import { realpathSync as realpathSync7, statSync as statSync11 } from "fs";
19600
+ import { isAbsolute as isAbsolute9, resolve as resolve18 } from "path";
19072
19601
  function sessionEventMatchesCurrentExecution(topicId, queryId, agent, model) {
19073
19602
  if (getRoomQuery(topicId)?.queryId !== queryId)
19074
19603
  return false;
@@ -19493,15 +20022,15 @@ ${JSON.stringify(event.input ?? {})}`);
19493
20022
  case "file":
19494
20023
  if (!silent && peerBridge) {
19495
20024
  const cwd = workspaceCwdFor(topicId);
19496
- const path = isAbsolute8(event.path) ? event.path : resolve18(cwd, event.path);
20025
+ const path = isAbsolute9(event.path) ? event.path : resolve18(cwd, event.path);
19497
20026
  if (!isPathInside(cwd, path)) {
19498
20027
  logger.warn({ topicId, path }, "peer output file is outside the topic workspace");
19499
20028
  break;
19500
20029
  }
19501
20030
  let safePath;
19502
20031
  try {
19503
- safePath = realpathSync6(path);
19504
- if (!statSync10(safePath).isFile()) {
20032
+ safePath = realpathSync7(path);
20033
+ if (!statSync11(safePath).isFile()) {
19505
20034
  logger.warn({ topicId, path }, "peer output path is not a regular file");
19506
20035
  break;
19507
20036
  }
@@ -19830,16 +20359,16 @@ var init_turn_session = __esm(async () => {
19830
20359
  });
19831
20360
 
19832
20361
  // ../../packages/core/src/storage/app-settings.ts
19833
- import { existsSync as existsSync21, mkdirSync as mkdirSync18, readFileSync as readFileSync17, writeFileSync as writeFileSync16 } from "fs";
19834
- import { dirname as dirname16, join as join31 } from "path";
20362
+ import { existsSync as existsSync22, mkdirSync as mkdirSync18, readFileSync as readFileSync18, writeFileSync as writeFileSync16 } from "fs";
20363
+ import { dirname as dirname16, join as join32 } from "path";
19835
20364
  function settingsFile() {
19836
- return join31(resolveStorageDataDir(), "otium-settings.json");
20365
+ return join32(resolveStorageDataDir(), "otium-settings.json");
19837
20366
  }
19838
20367
  function getGlobalAiName() {
19839
20368
  const path = settingsFile();
19840
20369
  try {
19841
- if (existsSync21(path)) {
19842
- const data = JSON.parse(readFileSync17(path, "utf8"));
20370
+ if (existsSync22(path)) {
20371
+ const data = JSON.parse(readFileSync18(path, "utf8"));
19843
20372
  if (typeof data.aiName === "string" && data.aiName.trim()) {
19844
20373
  return data.aiName.trim();
19845
20374
  }
@@ -19852,10 +20381,154 @@ var init_app_settings = __esm(async () => {
19852
20381
  await init_storage_host();
19853
20382
  });
19854
20383
 
20384
+ // ../../packages/core/src/topics/plugin-server-instructions.ts
20385
+ import { Client as Client2 } from "@modelcontextprotocol/sdk/client/index.js";
20386
+ import { SSEClientTransport as SSEClientTransport2 } from "@modelcontextprotocol/sdk/client/sse.js";
20387
+ import { StreamableHTTPClientTransport as StreamableHTTPClientTransport2 } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
20388
+ function cacheKey(server, spec) {
20389
+ const headers = Object.entries(spec.headers ?? {}).map(([name, value]) => [name.toLowerCase(), value]).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
20390
+ return JSON.stringify([server, spec.type, spec.url, headers]);
20391
+ }
20392
+ function transportFor(spec, signal) {
20393
+ const url = new URL(spec.url);
20394
+ const requestInit = spec.headers ? { headers: spec.headers } : undefined;
20395
+ const noRedirect = (input, init) => fetch(input, {
20396
+ ...init,
20397
+ redirect: "error",
20398
+ signal: init?.signal ? AbortSignal.any([init.signal, signal]) : signal
20399
+ });
20400
+ return spec.type === "sse" ? new SSEClientTransport2(url, { requestInit, fetch: noRedirect }) : new StreamableHTTPClientTransport2(url, { requestInit, fetch: noRedirect });
20401
+ }
20402
+ async function readInstructions(spec, timeoutMs, stop) {
20403
+ const ended = new AbortController;
20404
+ const timer = setTimeout(() => ended.abort(new Error(`no answer in ${timeoutMs} ms`)), timeoutMs);
20405
+ timer.unref?.();
20406
+ const onStop = () => ended.abort(new Error("the turn was stopped"));
20407
+ if (stop?.aborted)
20408
+ onStop();
20409
+ else
20410
+ stop?.addEventListener("abort", onStop, { once: true });
20411
+ const client = new Client2({ name: "negotium-plugin-instructions", version: "1.0.0" });
20412
+ const transport = transportFor(spec, ended.signal);
20413
+ try {
20414
+ return await Promise.race([
20415
+ client.connect(transport).then(() => client.getInstructions() ?? ""),
20416
+ new Promise((_, reject) => {
20417
+ if (ended.signal.aborted)
20418
+ reject(ended.signal.reason);
20419
+ ended.signal.addEventListener("abort", () => reject(ended.signal.reason), { once: true });
20420
+ })
20421
+ ]);
20422
+ } finally {
20423
+ clearTimeout(timer);
20424
+ stop?.removeEventListener("abort", onStop);
20425
+ const ending = !ended.signal.aborted && transport instanceof StreamableHTTPClientTransport2 ? transport.terminateSession() : Promise.resolve();
20426
+ ending.catch(() => {}).finally(() => client.close().catch(() => {}));
20427
+ }
20428
+ }
20429
+ async function fetchMcpServerInstructions(servers, options = {}) {
20430
+ const timeoutMs = options.timeoutMs ?? SERVER_INSTRUCTIONS_TIMEOUT_MS;
20431
+ const entries = Object.entries(servers);
20432
+ const results = await Promise.allSettled(entries.map(async ([server, spec]) => {
20433
+ const key = cacheKey(server, spec);
20434
+ const hit = cache.get(key);
20435
+ if (hit && hit.expires > Date.now())
20436
+ return hit.text;
20437
+ const text = await readInstructions(spec, timeoutMs, options.signal);
20438
+ cache.set(key, { text, expires: Date.now() + SERVER_INSTRUCTIONS_TTL_MS });
20439
+ return text;
20440
+ }));
20441
+ const fetched = { instructions: [], problems: [] };
20442
+ results.forEach((result, index) => {
20443
+ const server = entries[index][0];
20444
+ if (result.status === "rejected") {
20445
+ const reason = result.reason instanceof Error ? result.reason.message : String(result.reason);
20446
+ fetched.problems.push(`plugin server "${server}": instructions not read (${reason})`);
20447
+ } else if (result.value.trim()) {
20448
+ fetched.instructions.push({ server, text: result.value });
20449
+ }
20450
+ });
20451
+ return fetched;
20452
+ }
20453
+ function cutToBytes(text, maxBytes) {
20454
+ const encoded = encoder.encode(text);
20455
+ let end = Math.max(0, maxBytes);
20456
+ while (end > 0 && (encoded[end] & 192) === 128)
20457
+ end--;
20458
+ return new TextDecoder().decode(encoded.subarray(0, end));
20459
+ }
20460
+ function renderMcpServerInstructions(instructions) {
20461
+ const head = [
20462
+ "## MCP Server Instructions",
20463
+ "",
20464
+ "The following MCP servers have provided instructions for how to use their tools and resources:"
20465
+ ].join(`
20466
+ `);
20467
+ const blocks = [];
20468
+ const problems = [];
20469
+ let left = INSTRUCTIONS_SECTION_MAX_BYTES - byteLength(head);
20470
+ for (const { server, text: sent } of instructions) {
20471
+ const heading = `
20472
+
20473
+ ### ${server}
20474
+
20475
+ `;
20476
+ const text = sent.trim();
20477
+ const size = byteLength(text);
20478
+ const room = Math.min(SERVER_INSTRUCTIONS_MAX_BYTES, left - byteLength(heading));
20479
+ if (size <= room) {
20480
+ blocks.push(`${heading}${text}`);
20481
+ left -= byteLength(heading) + size;
20482
+ continue;
20483
+ }
20484
+ const marker = cutMarker(server, size);
20485
+ if (room <= byteLength(marker)) {
20486
+ problems.push(`plugin server "${server}": instructions left out (the section is full)`);
20487
+ continue;
20488
+ }
20489
+ const shown = `${cutToBytes(text, room - byteLength(marker))}${marker}`;
20490
+ blocks.push(`${heading}${shown}`);
20491
+ left -= byteLength(heading) + byteLength(shown);
20492
+ problems.push(`plugin server "${server}": instructions cut from ${size} bytes`);
20493
+ }
20494
+ return { section: blocks.length > 0 ? `${head}${blocks.join("")}` : "", problems };
20495
+ }
20496
+ var SERVER_INSTRUCTIONS_TIMEOUT_MS = 3000, SERVER_INSTRUCTIONS_TTL_MS, SERVER_INSTRUCTIONS_MAX_BYTES, INSTRUCTIONS_SECTION_MAX_BYTES, cache, encoder, byteLength = (text) => encoder.encode(text).length, cutMarker = (server, sent) => `
20497
+
20498
+ [negotium cut the instructions of "${server}" here; the server sent ${sent} bytes]`;
20499
+ var init_plugin_server_instructions = __esm(() => {
20500
+ SERVER_INSTRUCTIONS_TTL_MS = 5 * 60 * 1000;
20501
+ SERVER_INSTRUCTIONS_MAX_BYTES = 8 * 1024;
20502
+ INSTRUCTIONS_SECTION_MAX_BYTES = 32 * 1024;
20503
+ cache = new Map;
20504
+ encoder = new TextEncoder;
20505
+ });
20506
+
20507
+ // ../../packages/core/src/topics/plugin-turn.ts
20508
+ function resolveTopicPluginTurn(topic, hostServerNames) {
20509
+ if (!topic.plugins?.length)
20510
+ return NONE;
20511
+ const { plugins, problems: loadProblems } = loadTopicPlugins(topic.plugins);
20512
+ const servers = Object.assign({}, ...plugins.map((plugin) => plugin.mcpServers));
20513
+ const refusal = pluginMcpRefusal(topic, Object.keys(servers), hostServerNames);
20514
+ return {
20515
+ plugins,
20516
+ mcpServers: refusal ? {} : servers,
20517
+ loadProblems,
20518
+ serverProblems: refusal ? [refusal] : []
20519
+ };
20520
+ }
20521
+ var NONE;
20522
+ var init_plugin_turn = __esm(async () => {
20523
+ init_plugins();
20524
+ await init_mcp_config();
20525
+ NONE = { plugins: [], mcpServers: {}, loadProblems: [], serverProblems: [] };
20526
+ });
20527
+
19855
20528
  // ../../packages/core/src/runtime/turn-runner.ts
19856
20529
  import { randomUUID as randomUUID19 } from "crypto";
19857
- import { existsSync as existsSync22, mkdirSync as mkdirSync19, readdirSync as readdirSync5, statSync as statSync11 } from "fs";
19858
- import { join as join32 } from "path";
20530
+ import { existsSync as existsSync23, mkdirSync as mkdirSync19, readdirSync as readdirSync6, statSync as statSync12 } from "fs";
20531
+ import { join as join33 } from "path";
19859
20532
  function withDefaultPlaywright(configuredMcp, isManager) {
19860
20533
  if (isManager)
19861
20534
  return configuredMcp;
@@ -19919,19 +20592,19 @@ function appendAskReplyMessage(topicId, text, sourceLabel, body, kind, agentType
19919
20592
  return message;
19920
20593
  }
19921
20594
  function resolveWikiMirrorPath(directory, preferredFilename, matchesLegacyId, matchesTitle, preferExact = true) {
19922
- const preferred = join32(directory, preferredFilename);
19923
- if (preferExact && existsSync22(preferred))
20595
+ const preferred = join33(directory, preferredFilename);
20596
+ if (preferExact && existsSync23(preferred))
19924
20597
  return preferred;
19925
20598
  let newestLegacyId = null;
19926
20599
  let newestTitle = null;
19927
20600
  try {
19928
- for (const filename of readdirSync5(directory)) {
20601
+ for (const filename of readdirSync6(directory)) {
19929
20602
  const titleMatch = matchesTitle(filename);
19930
20603
  const legacyIdMatch = !titleMatch && matchesLegacyId(filename);
19931
20604
  if (!titleMatch && !legacyIdMatch)
19932
20605
  continue;
19933
- const path = join32(directory, filename);
19934
- const mtimeMs = statSync11(path).mtimeMs;
20606
+ const path = join33(directory, filename);
20607
+ const mtimeMs = statSync12(path).mtimeMs;
19935
20608
  if (titleMatch) {
19936
20609
  if (!newestTitle || mtimeMs > newestTitle.mtimeMs) {
19937
20610
  newestTitle = { path, mtimeMs };
@@ -19944,10 +20617,10 @@ function resolveWikiMirrorPath(directory, preferredFilename, matchesLegacyId, ma
19944
20617
  return newestTitle?.path ?? newestLegacyId?.path ?? preferred;
19945
20618
  }
19946
20619
  function resolveWikiMemoryMirror(wikiDir, topicId, topicTitle) {
19947
- const briefFile = resolveWikiMirrorPath(join32(wikiDir, "topic"), `${wikiBriefStorageKey(topicTitle, topicId)}.md`, (filename) => isTopicBriefFile(filename, topicId), (filename) => isTopicBriefFile(filename, topicId, topicTitle));
19948
- const hasBriefFile = existsSync22(briefFile) && statSync11(briefFile).isFile();
19949
- const latestSummaryCandidate = resolveWikiMirrorPath(join32(wikiDir, "summaries"), `__missing__-${wikiSummaryFilename("0000-00-00", topicTitle, topicId)}`, (filename) => isTopicSummaryFile(filename, topicId), (filename) => isTopicSummaryFile(filename, topicId, topicTitle), false);
19950
- const latestSummaryFile = existsSync22(latestSummaryCandidate) && statSync11(latestSummaryCandidate).isFile() ? latestSummaryCandidate : null;
20620
+ const briefFile = resolveWikiMirrorPath(join33(wikiDir, "topic"), `${wikiBriefStorageKey(topicTitle, topicId)}.md`, (filename) => isTopicBriefFile(filename, topicId), (filename) => isTopicBriefFile(filename, topicId, topicTitle));
20621
+ const hasBriefFile = existsSync23(briefFile) && statSync12(briefFile).isFile();
20622
+ const latestSummaryCandidate = resolveWikiMirrorPath(join33(wikiDir, "summaries"), `__missing__-${wikiSummaryFilename("0000-00-00", topicTitle, topicId)}`, (filename) => isTopicSummaryFile(filename, topicId), (filename) => isTopicSummaryFile(filename, topicId, topicTitle), false);
20623
+ const latestSummaryFile = existsSync23(latestSummaryCandidate) && statSync12(latestSummaryCandidate).isFile() ? latestSummaryCandidate : null;
19951
20624
  return { briefFile, hasBriefFile, latestSummaryFile };
19952
20625
  }
19953
20626
  async function streamAgentEvents(topicId, topicTitle, queryId, events, control, agentType, model, effort, userId, retryableSessionExpired = true, onSessionId, execution) {
@@ -20182,6 +20855,23 @@ function resolveTurnHostMcpServers(topic, sessionType) {
20182
20855
  return;
20183
20856
  return getTopicHostMcpGrant(topic.id) ?? undefined;
20184
20857
  }
20858
+ function resolveTurnPlugins(topic, sessionType, hostMcpServers) {
20859
+ const ownScope = topic.kind === "manager" ? "manager" : "forum";
20860
+ const stored = getTopic(topic.id);
20861
+ if (!stored?.plugins?.length || (sessionType ?? ownScope) !== ownScope) {
20862
+ return { plugins: [], pluginMcpServers: {}, hostMcpServers };
20863
+ }
20864
+ const turn = resolveTopicPluginTurn(stored, Object.keys(hostMcpServers ?? {}));
20865
+ const problems = [...turn.loadProblems, ...turn.serverProblems];
20866
+ if (problems.length > 0) {
20867
+ logger.warn({ topicId: topic.id, problems }, "ai: topic plugins partly or wholly left out of the turn");
20868
+ }
20869
+ return {
20870
+ plugins: turn.plugins,
20871
+ pluginMcpServers: turn.mcpServers,
20872
+ hostMcpServers: Object.keys(turn.mcpServers).length > 0 ? { ...hostMcpServers, ...turn.mcpServers } : hostMcpServers
20873
+ };
20874
+ }
20185
20875
  function sameTurnActor(runningActorUserId, incomingActorUserId) {
20186
20876
  return (runningActorUserId ?? null) === (incomingActorUserId ?? null);
20187
20877
  }
@@ -20339,7 +21029,7 @@ function startAiTurn(params) {
20339
21029
  const sessionName = params.sessionName ?? topic.title;
20340
21030
  const sessionType = params.sessionType;
20341
21031
  const { visualTools, fileDeliveryTools } = resolveTurnToolCapabilities(topicId, params);
20342
- const hostMcpServers = resolveTurnHostMcpServers(topic, sessionType);
21032
+ const { plugins, pluginMcpServers, hostMcpServers } = resolveTurnPlugins(topic, sessionType, resolveTurnHostMcpServers(topic, sessionType));
20343
21033
  const onSessionId = params.onSessionId;
20344
21034
  const onSessionReset = params.onSessionReset;
20345
21035
  const bridgeSessionFromHistory = params.bridgeSessionFromHistory === true;
@@ -20458,6 +21148,11 @@ function startAiTurn(params) {
20458
21148
  }
20459
21149
  if (decision.action === "abort-replace") {
20460
21150
  const running = decision.running;
21151
+ const runningRequestIds = new Set(running.durableRequestIds ?? []);
21152
+ if (durableRequestIds.length > 0 && durableRequestIds.every((requestId) => runningRequestIds.has(requestId))) {
21153
+ logger.warn({ topicId, queryId: running.queryId, durableRequestIds }, "ai: ignored a replay of the durable request this room is already running");
21154
+ return running.queryId;
21155
+ }
20461
21156
  if (isUserOrigin(running.origin) && !sameTurnActor(running.actorUserId, params.actorUserId)) {
20462
21157
  const queuedQueryId = waitToStartRemoteUserTurn({
20463
21158
  ...params,
@@ -20715,7 +21410,8 @@ function startAiTurn(params) {
20715
21410
  subagentParentTitle: topicRecord?.isSubagent && topicRecord.parentTopicId ? getTopic(topicRecord.parentTopicId)?.title : undefined,
20716
21411
  subagentReportMode: topicRecord?.isSubagent ? subagentReportMode(topicId) : undefined,
20717
21412
  visualTools,
20718
- fileDeliveryTools
21413
+ fileDeliveryTools,
21414
+ plugins
20719
21415
  };
20720
21416
  const isManager = topicRecord?.kind === "manager";
20721
21417
  const isMentionOnlyChannel = topic.aiMode === "mention" && !isManager;
@@ -20861,6 +21557,21 @@ function startAiTurn(params) {
20861
21557
  if (consumePlaywrightUnavailable(userId, topic.title)) {
20862
21558
  turnReminders.push("<system-reminder>Playwright browser tools are UNAVAILABLE this turn. The `mcp__playwright__*` tools have been removed from this turn's catalog because the long-lived browser MCP could not be prepared. Do not attempt to call browser tools. If browser interaction is required, ask the user to retry shortly or use a non-browser alternative.</system-reminder>");
20863
21559
  }
21560
+ if (Object.keys(pluginMcpServers).length > 0) {
21561
+ const fetched = await fetchMcpServerInstructions(pluginMcpServers, {
21562
+ signal: abortController.signal
21563
+ });
21564
+ if (abortController.signal.aborted)
21565
+ return;
21566
+ const { section, problems } = renderMcpServerInstructions(fetched.instructions);
21567
+ if (fetched.problems.length + problems.length > 0) {
21568
+ logger.warn({ topicId, problems: [...fetched.problems, ...problems] }, "ai: plugin server instructions cut or left out of the turn");
21569
+ }
21570
+ if (section)
21571
+ systemPrompt += `
21572
+
21573
+ ${section}`;
21574
+ }
20864
21575
  const reminderQuery = buildTurnReminderQuery(agentKind, agentPrompt, turnReminders);
20865
21576
  try {
20866
21577
  yield* runAgent({
@@ -21223,6 +21934,7 @@ var init_turn_runner = __esm(async () => {
21223
21934
  init_remote_session_grant();
21224
21935
  init_user_turn_envelope();
21225
21936
  init_wiki_summary_names();
21937
+ init_plugin_server_instructions();
21226
21938
  init_user_turn_envelope();
21227
21939
  await __promiseAll([
21228
21940
  init_fork(),
@@ -21253,7 +21965,8 @@ var init_turn_runner = __esm(async () => {
21253
21965
  init_topic_host_mcp_grants(),
21254
21966
  init_topic_tool_capabilities(),
21255
21967
  init_wiki(),
21256
- init_derive()
21968
+ init_derive(),
21969
+ init_plugin_turn()
21257
21970
  ]);
21258
21971
  init_model_catalog();
21259
21972
  init_attachments();
@@ -21274,7 +21987,7 @@ var init_turn_runner = __esm(async () => {
21274
21987
  });
21275
21988
 
21276
21989
  // ../../packages/core/src/agents/mcp-tools/spawn-subagent.ts
21277
- import { z as z5 } from "zod";
21990
+ import { z as z6 } from "zod";
21278
21991
  function activeQueryUserId(topic) {
21279
21992
  return topic?.participants.find((participant) => hasActiveQuery(participant.userId, topic.id))?.userId;
21280
21993
  }
@@ -21841,7 +22554,7 @@ ${card.task}${reportInstruction}`;
21841
22554
  name: "start_subagent",
21842
22555
  description: "Start a prepared descendant subagent task.",
21843
22556
  schema: {
21844
- topic_id: z5.string().describe("Prepared subagent room id.")
22557
+ topic_id: z6.string().describe("Prepared subagent room id.")
21845
22558
  },
21846
22559
  async handler(input) {
21847
22560
  const result = ownedSubagentTree(ctx);
@@ -21861,7 +22574,7 @@ ${card.task}${reportInstruction}`;
21861
22574
  name: "delete_subagent",
21862
22575
  description: "Permanently delete one descendant subagent room managed by the current room. " + "This removes its conversation, workspace, runtime state, and topic. Keep it when follow-up work is likely.",
21863
22576
  schema: {
21864
- topic_id: z5.string().describe("Exact subagent room id returned by list_subagents; names are not accepted.")
22577
+ topic_id: z6.string().describe("Exact subagent room id returned by list_subagents; names are not accepted.")
21865
22578
  },
21866
22579
  async handler(input) {
21867
22580
  const result = ownedSubagentTree(ctx);
@@ -21885,8 +22598,8 @@ ${card.task}${reportInstruction}`;
21885
22598
  name: "grant_subagent_tell",
21886
22599
  description: "Allow one descendant subagent to tell_session another topic in this managed subagent tree. " + "Direct-parent reporting is always allowed and does not need a grant.",
21887
22600
  schema: {
21888
- subagent_topic_id: z5.string().describe("Source descendant subagent topic id."),
21889
- target_topic_id: z5.string().describe("Target topic id: this manager room or another descendant in its tree.")
22601
+ subagent_topic_id: z6.string().describe("Source descendant subagent topic id."),
22602
+ target_topic_id: z6.string().describe("Target topic id: this manager room or another descendant in its tree.")
21890
22603
  },
21891
22604
  async handler(input) {
21892
22605
  const result = ownedSubagentTree(ctx);
@@ -21911,8 +22624,8 @@ ${card.task}${reportInstruction}`;
21911
22624
  name: "revoke_subagent_tell",
21912
22625
  description: "Remove an extra tell_session connection previously granted to a descendant subagent.",
21913
22626
  schema: {
21914
- subagent_topic_id: z5.string().describe("Source descendant subagent topic id."),
21915
- target_topic_id: z5.string().describe("Granted target topic id.")
22627
+ subagent_topic_id: z6.string().describe("Source descendant subagent topic id."),
22628
+ target_topic_id: z6.string().describe("Granted target topic id.")
21916
22629
  },
21917
22630
  async handler(input) {
21918
22631
  const result = ownedSubagentTree(ctx);
@@ -21934,18 +22647,18 @@ ${card.task}${reportInstruction}`;
21934
22647
  }
21935
22648
  function createSpawnSubagentToolDefinition(ctx, options = {}) {
21936
22649
  const executionOverrideSchema = options.executionOverrides === false ? {} : {
21937
- agent: z5.enum(["claude", "codex", "maestro"]).optional().describe("Agent backend override. Defaults to this room's agent."),
21938
- model: z5.string().optional().describe(`Best-fit model override from the system prompt catalog. Omit agent+model to inherit ${ctx.agent}/${ctx.model ?? "default"}; overriding agent without model uses that agent's default.`)
22650
+ agent: z6.enum(["claude", "codex", "maestro"]).optional().describe("Agent backend override. Defaults to this room's agent."),
22651
+ model: z6.string().optional().describe(`Best-fit model override from the system prompt catalog. Omit agent+model to inherit ${ctx.agent}/${ctx.model ?? "default"}; overriding agent without model uses that agent's default.`)
21939
22652
  };
21940
22653
  return {
21941
22654
  name: "spawn_subagent",
21942
22655
  description: "Delegate a self-contained task to a subagent that works in its own new agent room. " + "Returns immediately; the subagent runs in the background and reports according to report_mode. " + "The fresh room has no parent conversation history; it receives the task plus the selected or inherited topic memory. " + "Use for parallelizable or long-running side work. Do not use provider built-in Task/Agent subagents.",
21943
22656
  schema: {
21944
- task: z5.string().describe("Self-contained task brief. The worker has topic memory but no parent conversation history, so include all task-specific context."),
21945
- name: z5.string().optional().describe("Short name for the subagent room. Auto-generated when omitted."),
22657
+ task: z6.string().describe("Self-contained task brief. The worker has topic memory but no parent conversation history, so include all task-specific context."),
22658
+ name: z6.string().optional().describe("Short name for the subagent room. Auto-generated when omitted."),
21946
22659
  ...executionOverrideSchema,
21947
- memory_topic: z5.string().optional().describe("Optional knowledge source: an accessible topic id/title or topic/*.md brief. Defaults to the parent room's effective topic brief."),
21948
- report_mode: z5.enum(["auto", "tell", "status-only"]).optional().describe("Completion reporting: auto injects the final result, tell requires tell_session, status-only updates only the lifecycle card.")
22660
+ memory_topic: z6.string().optional().describe("Optional knowledge source: an accessible topic id/title or topic/*.md brief. Defaults to the parent room's effective topic brief."),
22661
+ report_mode: z6.enum(["auto", "tell", "status-only"]).optional().describe("Completion reporting: auto injects the final result, tell requires tell_session, status-only updates only the lifecycle card.")
21949
22662
  },
21950
22663
  async handler(input) {
21951
22664
  return createSubagent(ctx, input, true);
@@ -21957,14 +22670,14 @@ ${card.task}${reportInstruction}`;
21957
22670
  name: "create_subagent",
21958
22671
  description: "Create a prepared subagent room and task definition without starting its AI turn. " + "Use start_subagent when the team is ready to run it.",
21959
22672
  schema: {
21960
- task: z5.string().describe("Self-contained task brief for the subagent."),
21961
- name: z5.string().optional().describe("Short room name. Auto-generated when omitted."),
22673
+ task: z6.string().describe("Self-contained task brief for the subagent."),
22674
+ name: z6.string().optional().describe("Short room name. Auto-generated when omitted."),
21962
22675
  ...options.executionOverrides === false ? {} : {
21963
- agent: z5.enum(["claude", "codex", "maestro"]).optional(),
21964
- model: z5.string().optional()
22676
+ agent: z6.enum(["claude", "codex", "maestro"]).optional(),
22677
+ model: z6.string().optional()
21965
22678
  },
21966
- memory_topic: z5.string().optional().describe("Optional accessible topic id/title or topic/*.md brief to use as this worker's knowledge source. Defaults to the parent."),
21967
- report_mode: z5.enum(["auto", "tell", "status-only"]).optional()
22679
+ memory_topic: z6.string().optional().describe("Optional accessible topic id/title or topic/*.md brief to use as this worker's knowledge source. Defaults to the parent."),
22680
+ report_mode: z6.enum(["auto", "tell", "status-only"]).optional()
21968
22681
  },
21969
22682
  async handler(input) {
21970
22683
  return createSubagent(ctx, input, false);
@@ -22159,11 +22872,11 @@ await __promiseAll([
22159
22872
 
22160
22873
  // ../../packages/core/src/agents/mcp-tools/publish-html.ts
22161
22874
  init_common();
22162
- import { z as z2 } from "zod";
22875
+ import { z as z3 } from "zod";
22163
22876
 
22164
22877
  // ../../packages/core/src/agents/mcp-tools/inline-assets.ts
22165
- import { existsSync as existsSync19, readFileSync as readFileSync14, statSync as statSync8 } from "fs";
22166
- import { extname, isAbsolute as isAbsolute5, resolve as resolve13 } from "path";
22878
+ import { existsSync as existsSync20, readFileSync as readFileSync15, statSync as statSync9 } from "fs";
22879
+ import { extname, isAbsolute as isAbsolute6, resolve as resolve13 } from "path";
22167
22880
  var MIME_BY_EXT = {
22168
22881
  ".apng": "image/apng",
22169
22882
  ".avif": "image/avif",
@@ -22212,15 +22925,15 @@ function inlineLocalAssets(html, options) {
22212
22925
  const relPath = stripSuffix(ref);
22213
22926
  if (!relPath)
22214
22927
  return null;
22215
- const abs = isAbsolute5(relPath) ? relPath : resolve13(baseDir, relPath);
22928
+ const abs = isAbsolute6(relPath) ? relPath : resolve13(baseDir, relPath);
22216
22929
  let bytes;
22217
22930
  try {
22218
- if (!existsSync19(abs) || !statSync8(abs).isFile()) {
22931
+ if (!existsSync20(abs) || !statSync9(abs).isFile()) {
22219
22932
  unresolved.push(ref);
22220
22933
  cache.set(ref, null);
22221
22934
  return null;
22222
22935
  }
22223
- bytes = statSync8(abs).size;
22936
+ bytes = statSync9(abs).size;
22224
22937
  } catch {
22225
22938
  unresolved.push(ref);
22226
22939
  cache.set(ref, null);
@@ -22240,7 +22953,7 @@ function inlineLocalAssets(html, options) {
22240
22953
  let uri;
22241
22954
  try {
22242
22955
  const mime = MIME_BY_EXT[extname(abs).toLowerCase()] ?? "application/octet-stream";
22243
- uri = `data:${mime};base64,${readFileSync14(abs).toString("base64")}`;
22956
+ uri = `data:${mime};base64,${readFileSync15(abs).toString("base64")}`;
22244
22957
  } catch {
22245
22958
  unresolved.push(ref);
22246
22959
  cache.set(ref, null);
@@ -22337,8 +23050,8 @@ function createPublishHtmlToolDefinitions(ctx, options = {}) {
22337
23050
  "working after your workspace is gone."
22338
23051
  ].join(" "),
22339
23052
  schema: {
22340
- html: z2.string().describe("Complete standalone HTML document to publish. Inline the CSS and JS."),
22341
- base_dir: z2.string().optional().describe("Directory that relative image paths resolve against. Defaults to the working directory.")
23053
+ html: z3.string().describe("Complete standalone HTML document to publish. Inline the CSS and JS."),
23054
+ base_dir: z3.string().optional().describe("Directory that relative image paths resolve against. Defaults to the working directory.")
22342
23055
  },
22343
23056
  async handler(input) {
22344
23057
  const html = input?.html ?? "";
@@ -22389,7 +23102,7 @@ function createPublishHtmlToolDefinitions(ctx, options = {}) {
22389
23102
  name: "unpublish_html",
22390
23103
  description: "Delete a previously published HTML document before its 72-hour expiry. Accepts the URL returned by publish_html, or its id.",
22391
23104
  schema: {
22392
- snippet: z2.string().describe("URL returned by publish_html, or the bare id.")
23105
+ snippet: z3.string().describe("URL returned by publish_html, or the bare id.")
22393
23106
  },
22394
23107
  async handler(input) {
22395
23108
  const id = parseSnippetId(input?.snippet ?? "");
@@ -22405,7 +23118,7 @@ function createPublishHtmlToolDefinitions(ctx, options = {}) {
22405
23118
  }
22406
23119
  // ../../packages/core/src/agents/mcp-tools/self-config.ts
22407
23120
  init_common();
22408
- import { z as z3 } from "zod";
23121
+ import { z as z4 } from "zod";
22409
23122
 
22410
23123
  // ../../packages/core/src/agents/api-topic-agent-switch.ts
22411
23124
  init_model_catalog();
@@ -22945,7 +23658,7 @@ function createSelfConfigToolDefinitionsForCore(core, ctx, capabilities) {
22945
23658
  {
22946
23659
  name: "set_model",
22947
23660
  description: toolDescription(core, "set_model", "Set the model for THIS topic; it persists and applies from the NEXT turn. Use a model from the system prompt's same-agent catalog. Cross-agent changes require an explicit user-requested set_agent first. Fails if the user locked this setting. NEVER use 'fable' or 'fable-5.2' unless explicitly requested."),
22948
- schema: { model: z3.string().describe("Model id valid for the topic's current agent.") },
23661
+ schema: { model: z4.string().describe("Model id valid for the topic's current agent.") },
22949
23662
  async handler({ model }) {
22950
23663
  return mcpResult(core.setModel(getCtx(), model));
22951
23664
  }
@@ -22961,7 +23674,7 @@ function createSelfConfigToolDefinitionsForCore(core, ctx, capabilities) {
22961
23674
  {
22962
23675
  name: "set_agent",
22963
23676
  description: toolDescription(core, "set_agent", "Switch the agent backend for THIS topic between 'claude', 'codex', and 'maestro'. Clears the topic's model/effort override so the new agent starts at its defaults. Fails if the user locked this setting. Use only when the user explicitly asks to switch the runtime itself."),
22964
- schema: { agent: z3.enum(AGENT_VALUES) },
23677
+ schema: { agent: z4.enum(AGENT_VALUES) },
22965
23678
  async handler({ agent }) {
22966
23679
  return mcpResult(core.setAgent(getCtx(), agent));
22967
23680
  }
@@ -22978,7 +23691,7 @@ function createSelfConfigToolDefinitionsForCore(core, ctx, capabilities) {
22978
23691
  name: "set_effort",
22979
23692
  description: toolDescription(core, "set_effort", "Set the reasoning effort for THIS topic. Claude: low/medium/high/xhigh/max. Codex: low/medium/high/xhigh. Maestro: low/medium/high/xhigh/max. Higher effort costs more and is slower. Fails if the user locked this setting."),
22980
23693
  schema: {
22981
- effort: z3.enum(EFFORT_VALUES).describe("Reasoning effort level valid for the topic's current agent.")
23694
+ effort: z4.enum(EFFORT_VALUES).describe("Reasoning effort level valid for the topic's current agent.")
22982
23695
  },
22983
23696
  async handler({ effort }) {
22984
23697
  return mcpResult(core.setEffort(getCtx(), effort));
@@ -22998,8 +23711,8 @@ function createSelfConfigToolDefinitionsForCore(core, ctx, capabilities) {
22998
23711
  name: "schedule_self",
22999
23712
  description: toolDescription(core, "schedule_self", "Create the one pending durable delayed continuation allowed for THIS topic without blocking the current turn. Use it to check a long-running operation or resume work later. The future message must be self-contained. If one already exists, use get_self_schedule then update_self_schedule or cancel_self_schedule. For recurring or longer-lived schedules, use cron-manager instead."),
23000
23713
  schema: {
23001
- delay_seconds: z3.number().int().min(1).max(core.product.scheduleMaxDelaySeconds).describe(`Seconds before this topic resumes, from 1 through ${core.product.scheduleMaxDelaySeconds}${core.product.scheduleMaxDelaySeconds === 86400 ? " (24 hours)" : ""}.`),
23002
- message: z3.string().min(1).max(core.product.scheduleMaxMessageLength).describe("Self-contained instruction delivered to your future turn.")
23714
+ delay_seconds: z4.number().int().min(1).max(core.product.scheduleMaxDelaySeconds).describe(`Seconds before this topic resumes, from 1 through ${core.product.scheduleMaxDelaySeconds}${core.product.scheduleMaxDelaySeconds === 86400 ? " (24 hours)" : ""}.`),
23715
+ message: z4.string().min(1).max(core.product.scheduleMaxMessageLength).describe("Self-contained instruction delivered to your future turn.")
23003
23716
  },
23004
23717
  async handler({ delay_seconds, message }) {
23005
23718
  return mcpResult(core.scheduleContinue(getCtx(), delay_seconds, message));
@@ -23017,9 +23730,9 @@ function createSelfConfigToolDefinitionsForCore(core, ctx, capabilities) {
23017
23730
  name: "update_self_schedule",
23018
23731
  description: toolDescription(core, "update_self_schedule", "Edit THIS topic's pending self-schedule. Provide its schedule_id from schedule_self/get_self_schedule and change delay_seconds, message, or both. delay_seconds is measured from this update. A schedule that already started cannot be edited."),
23019
23732
  schema: {
23020
- schedule_id: z3.string().min(1).describe("Exact ID of the pending self-schedule."),
23021
- delay_seconds: z3.number().int().min(1).max(core.product.scheduleMaxDelaySeconds).optional().describe(`New delay from now, from 1 through ${core.product.scheduleMaxDelaySeconds} seconds.`),
23022
- message: z3.string().min(1).max(core.product.scheduleMaxMessageLength).optional().describe("Replacement self-contained future instruction.")
23733
+ schedule_id: z4.string().min(1).describe("Exact ID of the pending self-schedule."),
23734
+ delay_seconds: z4.number().int().min(1).max(core.product.scheduleMaxDelaySeconds).optional().describe(`New delay from now, from 1 through ${core.product.scheduleMaxDelaySeconds} seconds.`),
23735
+ message: z4.string().min(1).max(core.product.scheduleMaxMessageLength).optional().describe("Replacement self-contained future instruction.")
23023
23736
  },
23024
23737
  async handler({
23025
23738
  schedule_id,
@@ -23036,7 +23749,7 @@ function createSelfConfigToolDefinitionsForCore(core, ctx, capabilities) {
23036
23749
  name: "cancel_self_schedule",
23037
23750
  description: toolDescription(core, "cancel_self_schedule", "Cancel THIS topic's pending self-schedule by its exact schedule_id. A schedule that already started cannot be cancelled with this tool."),
23038
23751
  schema: {
23039
- schedule_id: z3.string().min(1).describe("Exact ID of the pending self-schedule.")
23752
+ schedule_id: z4.string().min(1).describe("Exact ID of the pending self-schedule.")
23040
23753
  },
23041
23754
  async handler({ schedule_id }) {
23042
23755
  return mcpResult(core.cancelSchedule(getCtx(), schedule_id));
@@ -23048,7 +23761,7 @@ function createSelfConfigToolDefinitionsForCore(core, ctx, capabilities) {
23048
23761
  name: "spawn_topic",
23049
23762
  description: toolDescription(core, "spawn_topic", `Create a new forum topic that inherits all settings from THIS topic but starts with a fresh session. Limited to ${core.product.derivedTopicLimit} calls per conversation turn.`),
23050
23763
  schema: {
23051
- name: z3.string().optional().describe("New topic name. Auto-generated if omitted.")
23764
+ name: z4.string().optional().describe("New topic name. Auto-generated if omitted.")
23052
23765
  },
23053
23766
  async handler({ name }) {
23054
23767
  if (derivedCount >= core.product.derivedTopicLimit) {
@@ -23065,7 +23778,7 @@ function createSelfConfigToolDefinitionsForCore(core, ctx, capabilities) {
23065
23778
  name: "fork_topic",
23066
23779
  description: toolDescription(core, "fork_topic", `Fork THIS topic by creating a new topic that inherits both settings AND conversation history. Limited to ${core.product.derivedTopicLimit} calls per conversation turn.`),
23067
23780
  schema: {
23068
- name: z3.string().optional().describe("New topic name. Auto-generated if omitted.")
23781
+ name: z4.string().optional().describe("New topic name. Auto-generated if omitted.")
23069
23782
  },
23070
23783
  async handler({ name }) {
23071
23784
  if (derivedCount >= core.product.derivedTopicLimit) {
@@ -23087,14 +23800,14 @@ await init_spawn_subagent();
23087
23800
 
23088
23801
  // ../../packages/core/src/agents/mcp-tools/visuals.ts
23089
23802
  init_common();
23090
- import { z as z6 } from "zod";
23803
+ import { z as z7 } from "zod";
23091
23804
  var VISUALS_MCP_KEY = "visuals";
23092
23805
  var showHtmlTool = {
23093
23806
  name: "show_html",
23094
23807
  description: "Display charts, tables, or interactive HTML to the user in a sandboxed WebView side panel. Pass a complete, self-contained HTML string with inline CSS/JS. Local DOM interactions are supported. Links (<a href> to http/https URLs) are safe to include: a click opens the URL in the user's system browser. Network requests, external scripts, form posts, popups, and parent-window access are blocked.",
23095
23808
  schema: {
23096
- html: z6.string().describe("Complete, self-contained HTML document or fragment to render."),
23097
- title: z6.string().optional().describe("Optional title shown above the rendered card.")
23809
+ html: z7.string().describe("Complete, self-contained HTML document or fragment to render."),
23810
+ title: z7.string().optional().describe("Optional title shown above the rendered card.")
23098
23811
  },
23099
23812
  async handler() {
23100
23813
  return textResult("HTML card displayed to the user.");
@@ -23104,9 +23817,9 @@ var showMermaidTool = {
23104
23817
  name: "show_mermaid",
23105
23818
  description: "Render a Mermaid diagram in the user's visual side panel. Pass Mermaid DSL only, not markdown fences. Use this for flowcharts, sequence diagrams, class diagrams, state diagrams, ER diagrams, timelines, and architecture diagrams.",
23106
23819
  schema: {
23107
- code: z6.string().describe("Mermaid diagram source without markdown code fences."),
23108
- title: z6.string().optional().describe("Optional title shown above the rendered card."),
23109
- theme: z6.enum(["default", "neutral", "dark", "forest"]).optional().describe("Optional Mermaid theme. Defaults to neutral.")
23820
+ code: z7.string().describe("Mermaid diagram source without markdown code fences."),
23821
+ title: z7.string().optional().describe("Optional title shown above the rendered card."),
23822
+ theme: z7.enum(["default", "neutral", "dark", "forest"]).optional().describe("Optional Mermaid theme. Defaults to neutral.")
23110
23823
  },
23111
23824
  async handler() {
23112
23825
  return textResult("Mermaid diagram displayed to the user.");
@@ -23116,10 +23829,10 @@ var showImageTool = {
23116
23829
  name: "show_image",
23117
23830
  description: "Display an image in the user's visual side panel. Provide either file_path for an image in the topic workspace, or file_id for an uploaded file already attached in this topic.",
23118
23831
  schema: {
23119
- file_path: z6.string().optional().describe("Absolute or workspace-relative path to an image file."),
23120
- file_id: z6.string().optional().describe("Full Otium uploaded file UUID for an image attached in this topic."),
23121
- title: z6.string().optional().describe("Optional title shown above the rendered card."),
23122
- alt: z6.string().optional().describe("Optional alt text for the image.")
23832
+ file_path: z7.string().optional().describe("Absolute or workspace-relative path to an image file."),
23833
+ file_id: z7.string().optional().describe("Full Otium uploaded file UUID for an image attached in this topic."),
23834
+ title: z7.string().optional().describe("Optional title shown above the rendered card."),
23835
+ alt: z7.string().optional().describe("Optional alt text for the image.")
23123
23836
  },
23124
23837
  async handler(input) {
23125
23838
  if (!input?.file_path && !input?.file_id) {
@@ -23205,4 +23918,4 @@ export {
23205
23918
  withTaskSnapshots
23206
23919
  };
23207
23920
 
23208
- //# debugId=7836A053B43D717A64756E2164756E21
23921
+ //# debugId=B3A759B1E39CB45464756E2164756E21