@otium-team/negotium 0.23.15 → 0.24.1

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 (47) hide show
  1. package/dist/agent-helpers.js +969 -245
  2. package/dist/agent-helpers.js.map +13 -10
  3. package/dist/{chunk-ng13grfj.js → chunk-fzfzskjq.js} +18 -2
  4. package/dist/{chunk-ng13grfj.js.map → chunk-fzfzskjq.js.map} +4 -4
  5. package/dist/{chunk-m1ngkjdd.js → chunk-hn2cqdd0.js} +1 -1
  6. package/dist/{chunk-3hf8y6bd.js → chunk-kfckfff2.js} +3 -3
  7. package/dist/{chunk-3hf8y6bd.js.map → chunk-kfckfff2.js.map} +2 -2
  8. package/dist/hosted-agent.js +19 -3
  9. package/dist/hosted-agent.js.map +5 -5
  10. package/dist/main.js +3744 -2928
  11. package/dist/main.js.map +18 -15
  12. package/dist/mcp-factories.js +959 -229
  13. package/dist/mcp-factories.js.map +14 -11
  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/agents/mcp-tools/ask-user.ts +56 -1
  19. package/dist/runtime/src/application/submit-runtime-gateway-turn.ts +71 -0
  20. package/dist/runtime/src/application/turn-follow-ups.ts +7 -0
  21. package/dist/runtime/src/mcp/wiki-server.ts +8 -0
  22. package/dist/runtime/src/platform/mcp-config.ts +26 -0
  23. package/dist/runtime/src/prompts/builders.ts +5 -0
  24. package/dist/runtime/src/runtime/turn-runner.ts +65 -1
  25. package/dist/runtime/src/storage/api-topics.ts +29 -0
  26. package/dist/runtime/src/topics/agent-plugins/mcp.schema.json +120 -0
  27. package/dist/runtime/src/topics/agent-plugins/plugin.schema.json +65 -0
  28. package/dist/runtime/src/topics/plugin-server-instructions.ts +201 -0
  29. package/dist/runtime/src/topics/plugin-turn.ts +37 -0
  30. package/dist/runtime/src/topics/plugins.ts +445 -0
  31. package/dist/runtime/src/topics/update.ts +34 -0
  32. package/dist/runtime/src/types/api.ts +5 -0
  33. package/dist/runtime/src/version.ts +1 -1
  34. package/dist/storage.js +23 -2
  35. package/dist/storage.js.map +3 -3
  36. package/dist/types/packages/core/src/agents/mcp-tools/ask-user.d.ts +14 -0
  37. package/dist/types/packages/core/src/platform/mcp-config.d.ts +6 -0
  38. package/dist/types/packages/core/src/prompts/builders.d.ts +3 -0
  39. package/dist/types/packages/core/src/runtime/turn-runner.d.ts +14 -1
  40. package/dist/types/packages/core/src/storage/api-topics.d.ts +3 -0
  41. package/dist/types/packages/core/src/topics/plugin-server-instructions.d.ts +55 -0
  42. package/dist/types/packages/core/src/topics/plugin-turn.d.ts +17 -0
  43. package/dist/types/packages/core/src/topics/plugins.d.ts +66 -0
  44. package/dist/types/packages/core/src/types/api.d.ts +5 -0
  45. package/dist/types/packages/core/src/version.d.ts +1 -1
  46. package/package.json +1 -1
  47. /package/dist/{chunk-m1ngkjdd.js.map → chunk-hn2cqdd0.js.map} +0 -0
@@ -3093,6 +3093,7 @@ function initializeApiTopicsSchema() {
3093
3093
  browser_profile TEXT NOT NULL DEFAULT 'default',
3094
3094
  browser_profile_owner TEXT,
3095
3095
  browser_connect_port INTEGER,
3096
+ plugins_json TEXT,
3096
3097
  session_id TEXT,
3097
3098
  CHECK (
3098
3099
  (kind = 'channel' AND response_policy = 'off' AND agent IS NULL) OR
@@ -3213,6 +3214,10 @@ function initializeApiTopicsSchema() {
3213
3214
  if (!tableColumns("api_topics").has("browser_connect_port")) {
3214
3215
  db.exec("ALTER TABLE api_topics ADD COLUMN browser_connect_port INTEGER");
3215
3216
  }
3217
+ if (!tableColumns("api_topics").has("plugins_json")) {
3218
+ db.exec("ALTER TABLE api_topics ADD COLUMN plugins_json TEXT");
3219
+ }
3220
+ db.exec("DROP TABLE IF EXISTS api_topic_plugin_variables");
3216
3221
  if (!tableColumns("api_topics").has("subagent_report_mode")) {
3217
3222
  db.exec("ALTER TABLE api_topics ADD COLUMN subagent_report_mode TEXT NOT NULL DEFAULT 'auto'");
3218
3223
  }
@@ -3451,9 +3456,20 @@ function rowToDto2(r, participants = getTopicParticipants(r.id), tellTargets) {
3451
3456
  visibility: normalizeTopicVisibility(r.visibility),
3452
3457
  surface: normalizeTopicSurface(r.surface),
3453
3458
  surfaceScope: normalizeSurfaceScope(r.surface_scope),
3454
- ...r.browser_connect_port != null ? { browserConnectPort: r.browser_connect_port } : {}
3459
+ ...r.browser_connect_port != null ? { browserConnectPort: r.browser_connect_port } : {},
3460
+ ...pluginsField(r.plugins_json)
3455
3461
  };
3456
3462
  }
3463
+ function pluginsField(json) {
3464
+ if (!json)
3465
+ return {};
3466
+ try {
3467
+ const plugins = JSON.parse(json);
3468
+ return Array.isArray(plugins) && plugins.every((dir) => typeof dir === "string") ? { plugins } : {};
3469
+ } catch {
3470
+ return {};
3471
+ }
3472
+ }
3457
3473
  function normalizeTopicVisibility(value) {
3458
3474
  return value === "hidden" ? "hidden" : "visible";
3459
3475
  }
@@ -3859,6 +3875,22 @@ function refreshForumCatalogViews() {
3859
3875
  function isReservedRuntimeMcpServerName(name) {
3860
3876
  return Object.hasOwn(MCP_CATALOG, name) || nodeMcpEntries.some((entry) => entry.key === name);
3861
3877
  }
3878
+ function pluginMcpRefusal(topic, names, hostNames = []) {
3879
+ if (names.length > 0 && topic.isSubagent)
3880
+ return "plugin servers are not allowed for subagent topics";
3881
+ for (const name of names) {
3882
+ if (isReservedRuntimeMcpServerName(name)) {
3883
+ return `plugin MCP server name conflicts with node catalog: ${name}`;
3884
+ }
3885
+ if (topic.kind !== "manager" && MANAGER_ONLY_HOST_MCP_NAMES.has(name)) {
3886
+ return `${name} is only allowed for manager topics`;
3887
+ }
3888
+ if (hostNames.includes(name)) {
3889
+ return `plugin MCP server name conflicts with a host MCP server: ${name}`;
3890
+ }
3891
+ }
3892
+ return null;
3893
+ }
3862
3894
  function withoutManagerOnlyHostMcpServers(hostMcpServers) {
3863
3895
  if (!hostMcpServers)
3864
3896
  return;
@@ -5316,7 +5348,7 @@ var init_codex = __esm(async () => {
5316
5348
  });
5317
5349
 
5318
5350
  // ../../packages/core/src/version.ts
5319
- var NEGOTIUM_VERSION = "0.23.15";
5351
+ var NEGOTIUM_VERSION = "0.24.1";
5320
5352
 
5321
5353
  // ../../packages/core/src/agents/codex-native-multi-agent.ts
5322
5354
  import { spawn as spawn2 } from "child_process";
@@ -12584,11 +12616,578 @@ var init_agents = __esm(async () => {
12584
12616
  loadMaestroProvider = memoizeImport(() => init_maestro_provider().then(() => exports_maestro_provider));
12585
12617
  });
12586
12618
 
12619
+ // ../../packages/core/src/runtime-gateway.ts
12620
+ function parseHostMcpServers(value) {
12621
+ if (value === undefined)
12622
+ return;
12623
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
12624
+ throw new TypeError("hostMcpServers must be an object");
12625
+ }
12626
+ const parsedEntries = [];
12627
+ for (const [name, raw] of Object.entries(value)) {
12628
+ if (!HOST_MCP_SERVER_NAME.test(name)) {
12629
+ throw new TypeError(`invalid host MCP server name: ${name}`);
12630
+ }
12631
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
12632
+ throw new TypeError(`hostMcpServers.${name} must be an object`);
12633
+ }
12634
+ const spec = raw;
12635
+ const unsupported = Object.keys(spec).find((key) => !HOST_MCP_SERVER_KEYS.has(key));
12636
+ if (unsupported) {
12637
+ throw new TypeError(`hostMcpServers.${name}.${unsupported} is not allowed`);
12638
+ }
12639
+ if (spec.type !== "sse" && spec.type !== "http") {
12640
+ throw new TypeError(`hostMcpServers.${name}.type must be sse or http`);
12641
+ }
12642
+ if (typeof spec.url !== "string") {
12643
+ throw new TypeError(`hostMcpServers.${name}.url must be a string`);
12644
+ }
12645
+ let url;
12646
+ try {
12647
+ url = new URL(spec.url);
12648
+ } catch {
12649
+ throw new TypeError(`hostMcpServers.${name}.url must be a valid URL`);
12650
+ }
12651
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
12652
+ throw new TypeError(`hostMcpServers.${name}.url must use http or https`);
12653
+ }
12654
+ let headers;
12655
+ if (spec.headers !== undefined) {
12656
+ if (!spec.headers || typeof spec.headers !== "object" || Array.isArray(spec.headers)) {
12657
+ throw new TypeError(`hostMcpServers.${name}.headers must be an object`);
12658
+ }
12659
+ const headerEntries = [];
12660
+ for (const [key, headerValue] of Object.entries(spec.headers)) {
12661
+ if (!HTTP_HEADER_NAME.test(key) || typeof headerValue !== "string") {
12662
+ throw new TypeError(`hostMcpServers.${name}.headers must contain string values`);
12663
+ }
12664
+ try {
12665
+ new Headers([[key, headerValue]]);
12666
+ } catch {
12667
+ throw new TypeError(`hostMcpServers.${name}.headers contains an invalid header`);
12668
+ }
12669
+ headerEntries.push([key, headerValue]);
12670
+ }
12671
+ headers = Object.fromEntries(headerEntries);
12672
+ }
12673
+ if (spec.timeout !== undefined && (typeof spec.timeout !== "number" || !Number.isFinite(spec.timeout) || spec.timeout <= 0)) {
12674
+ throw new TypeError(`hostMcpServers.${name}.timeout must be a positive number`);
12675
+ }
12676
+ parsedEntries.push([
12677
+ name,
12678
+ {
12679
+ type: spec.type,
12680
+ url: url.toString(),
12681
+ ...headers ? { headers } : {},
12682
+ ...spec.timeout !== undefined ? { timeout: spec.timeout } : {}
12683
+ }
12684
+ ]);
12685
+ }
12686
+ return Object.fromEntries(parsedEntries);
12687
+ }
12688
+ var HOST_MCP_SERVER_NAME, HOST_MCP_SERVER_KEYS, HTTP_HEADER_NAME;
12689
+ var init_runtime_gateway = __esm(() => {
12690
+ HOST_MCP_SERVER_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
12691
+ HOST_MCP_SERVER_KEYS = new Set(["type", "url", "headers", "timeout"]);
12692
+ HTTP_HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
12693
+ });
12694
+
12695
+ // ../../packages/core/src/topics/agent-plugins/mcp.schema.json
12696
+ var mcp_schema_default;
12697
+ var init_mcp_schema = __esm(() => {
12698
+ mcp_schema_default = {
12699
+ $schema: "https://json-schema.org/draft/2020-12/schema",
12700
+ $id: "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
12701
+ title: "Agent Plugins MCP Configuration",
12702
+ description: "Machine-readable schema for mcp.json in Agent Plugins 1.0.0. The Agent Plugins specification defines additional semantic and operational requirements.",
12703
+ type: "object",
12704
+ properties: {
12705
+ $schema: {
12706
+ const: "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
12707
+ description: "Canonical identifier of the MCP configuration schema for the Agent Plugins version targeted by this document."
12708
+ },
12709
+ mcpServers: {
12710
+ type: "object",
12711
+ additionalProperties: {
12712
+ $ref: "#/$defs/server"
12713
+ }
12714
+ }
12715
+ },
12716
+ required: ["$schema", "mcpServers"],
12717
+ additionalProperties: false,
12718
+ $defs: {
12719
+ server: {
12720
+ title: "MCP server",
12721
+ oneOf: [
12722
+ {
12723
+ $ref: "#/$defs/stdioServer"
12724
+ },
12725
+ {
12726
+ $ref: "#/$defs/streamableHttpServer"
12727
+ },
12728
+ {
12729
+ $ref: "#/$defs/sseServer"
12730
+ }
12731
+ ]
12732
+ },
12733
+ stdioServer: {
12734
+ title: "stdio MCP server",
12735
+ type: "object",
12736
+ properties: {
12737
+ type: {
12738
+ const: "stdio"
12739
+ },
12740
+ command: {
12741
+ type: "string",
12742
+ minLength: 1,
12743
+ description: "Executable token. Resolution rules are defined by the Agent Plugins specification."
12744
+ },
12745
+ args: {
12746
+ type: "array",
12747
+ items: {
12748
+ type: "string"
12749
+ }
12750
+ },
12751
+ env: {
12752
+ type: "object",
12753
+ propertyNames: {
12754
+ not: {
12755
+ enum: ["PLUGIN_ROOT", "PLUGIN_DATA"]
12756
+ }
12757
+ },
12758
+ additionalProperties: {
12759
+ type: "string"
12760
+ }
12761
+ },
12762
+ cwd: {
12763
+ type: "string",
12764
+ pattern: "^(?:\\./|\\$\\{PLUGIN_ROOT\\}(?:/|$)|\\$\\{PLUGIN_DATA\\}(?:/|$))",
12765
+ description: "Plugin-relative, PLUGIN_ROOT-rooted, or PLUGIN_DATA-rooted working directory. Filesystem containment is validated separately."
12766
+ }
12767
+ },
12768
+ required: ["type", "command"],
12769
+ additionalProperties: false
12770
+ },
12771
+ streamableHttpServer: {
12772
+ title: "Streamable HTTP MCP server",
12773
+ type: "object",
12774
+ properties: {
12775
+ type: {
12776
+ const: "streamable-http"
12777
+ },
12778
+ url: {
12779
+ type: "string",
12780
+ minLength: 1,
12781
+ description: "MCP endpoint URL. URL semantics are defined by the Agent Plugins specification."
12782
+ },
12783
+ headers: {
12784
+ $ref: "#/$defs/headers"
12785
+ }
12786
+ },
12787
+ required: ["type", "url"],
12788
+ additionalProperties: false
12789
+ },
12790
+ sseServer: {
12791
+ title: "Legacy HTTP+SSE MCP server",
12792
+ type: "object",
12793
+ properties: {
12794
+ type: {
12795
+ const: "sse"
12796
+ },
12797
+ url: {
12798
+ type: "string",
12799
+ minLength: 1,
12800
+ description: "MCP endpoint URL. URL semantics are defined by the Agent Plugins specification."
12801
+ },
12802
+ headers: {
12803
+ $ref: "#/$defs/headers"
12804
+ }
12805
+ },
12806
+ required: ["type", "url"],
12807
+ additionalProperties: false
12808
+ },
12809
+ headers: {
12810
+ title: "HTTP headers",
12811
+ type: "object",
12812
+ additionalProperties: {
12813
+ type: "string"
12814
+ }
12815
+ }
12816
+ }
12817
+ };
12818
+ });
12819
+
12820
+ // ../../packages/core/src/topics/agent-plugins/plugin.schema.json
12821
+ var plugin_schema_default;
12822
+ var init_plugin_schema = __esm(() => {
12823
+ plugin_schema_default = {
12824
+ $schema: "https://json-schema.org/draft/2020-12/schema",
12825
+ $id: "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
12826
+ title: "Agent Plugins Manifest",
12827
+ description: "Machine-readable schema for plugin.json in Agent Plugins 1.0.0. The Agent Plugins specification defines additional semantic and operational requirements.",
12828
+ type: "object",
12829
+ properties: {
12830
+ $schema: {
12831
+ const: "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
12832
+ description: "Canonical identifier of the plugin manifest schema for the Agent Plugins version targeted by this document."
12833
+ },
12834
+ name: {
12835
+ type: "string",
12836
+ minLength: 1,
12837
+ maxLength: 64,
12838
+ pattern: "^(?!.*(?:--|\\.\\.))[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$",
12839
+ description: "Human-readable plugin name."
12840
+ },
12841
+ version: {
12842
+ type: "string"
12843
+ },
12844
+ description: {
12845
+ type: "string"
12846
+ },
12847
+ author: {
12848
+ type: "object",
12849
+ properties: {
12850
+ name: {
12851
+ type: "string"
12852
+ },
12853
+ email: {
12854
+ type: "string"
12855
+ },
12856
+ url: {
12857
+ type: "string"
12858
+ }
12859
+ },
12860
+ additionalProperties: false
12861
+ },
12862
+ homepage: {
12863
+ type: "string"
12864
+ },
12865
+ repository: {
12866
+ type: "string"
12867
+ },
12868
+ license: {
12869
+ type: "string"
12870
+ },
12871
+ keywords: {
12872
+ type: "array",
12873
+ items: {
12874
+ type: "string"
12875
+ }
12876
+ },
12877
+ extensions: {
12878
+ type: "object",
12879
+ description: "Client-specific manifest data keyed by reverse-domain extension namespace. Agent Plugins assigns no semantics to namespace object contents.",
12880
+ additionalProperties: {
12881
+ type: "object"
12882
+ }
12883
+ }
12884
+ },
12885
+ required: ["$schema", "name"],
12886
+ additionalProperties: false
12887
+ };
12888
+ });
12889
+
12890
+ // ../../packages/core/src/topics/plugins.ts
12891
+ import { existsSync as existsSync22, readdirSync as readdirSync5, readFileSync as readFileSync17, realpathSync as realpathSync6, statSync as statSync8 } from "fs";
12892
+ import { isAbsolute as isAbsolute6, join as join23, relative as relative4 } from "path";
12893
+ import { z as z5 } from "zod";
12894
+ function readText(path) {
12895
+ return readFileSync17(path, "utf-8").replace(/^\uFEFF/, "").replace(/\r\n/g, `
12896
+ `);
12897
+ }
12898
+ function pathKind(root, path) {
12899
+ if (!existsSync22(path))
12900
+ return "missing";
12901
+ const real = realpathSync6(path);
12902
+ const fromRoot = relative4(root, real);
12903
+ if (fromRoot.startsWith("..") || isAbsolute6(fromRoot))
12904
+ return "outside";
12905
+ const stat = statSync8(real);
12906
+ return stat.isFile() ? "file" : stat.isDirectory() ? "dir" : "other";
12907
+ }
12908
+ function parseFrontmatter(raw) {
12909
+ const match = raw.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
12910
+ if (!match)
12911
+ return { ok: false, problem: "missing the --- frontmatter block" };
12912
+ let meta;
12913
+ try {
12914
+ meta = Bun.YAML.parse(match[1]);
12915
+ } catch (error) {
12916
+ const reason = error instanceof Error ? error.message : String(error);
12917
+ return { ok: false, problem: `frontmatter is not valid YAML (${reason})` };
12918
+ }
12919
+ if (!isObject(meta))
12920
+ return { ok: false, problem: "frontmatter must be a YAML mapping" };
12921
+ return { ok: true, meta, body: match[2] };
12922
+ }
12923
+ function readJson(path, fail) {
12924
+ try {
12925
+ return JSON.parse(readText(path));
12926
+ } catch (error) {
12927
+ fail(`not valid JSON (${error instanceof Error ? error.message : String(error)})`);
12928
+ return;
12929
+ }
12930
+ }
12931
+ function manifestSchema() {
12932
+ manifestValidator ??= z5.fromJSONSchema(plugin_schema_default);
12933
+ return manifestValidator;
12934
+ }
12935
+ function readManifest(root, fail) {
12936
+ const path = join23(root, MANIFEST_FILE);
12937
+ const kind = pathKind(root, path);
12938
+ if (kind !== "file") {
12939
+ fail(kind === "outside" ? "resolves outside the plugin folder" : "missing");
12940
+ return null;
12941
+ }
12942
+ const raw = readJson(path, fail);
12943
+ if (raw === undefined)
12944
+ return null;
12945
+ if (!isObject(raw)) {
12946
+ fail("must be a JSON object");
12947
+ return null;
12948
+ }
12949
+ const manifest = {};
12950
+ for (const [field, value] of Object.entries(raw)) {
12951
+ if (!MANIFEST_FIELDS.has(field))
12952
+ fail(`unknown field "${field}" is ignored`);
12953
+ else if (field === "extensions" && !isObject(value)) {
12954
+ fail('"extensions" is not an object and is ignored');
12955
+ } else
12956
+ manifest[field] = value;
12957
+ }
12958
+ if (typeof manifest.$schema === "string" && manifest.$schema !== MANIFEST_SCHEMA_ID) {
12959
+ fail(`unsupported Agent Plugins version: $schema "${manifest.$schema}"`);
12960
+ return null;
12961
+ }
12962
+ const checked = manifestSchema().safeParse(manifest);
12963
+ if (!checked.success) {
12964
+ for (const issue of checked.error.issues) {
12965
+ fail(`${issue.path.length > 0 ? `${issue.path.join(".")}: ` : ""}${issue.message}`);
12966
+ }
12967
+ return null;
12968
+ }
12969
+ return { id: String(manifest.name) };
12970
+ }
12971
+ function readSkill(root, dir, name, fail) {
12972
+ const where = `${SKILLS_DIR}/${name}/${SKILL_FILE}`;
12973
+ const path = join23(dir, SKILLS_DIR, name, SKILL_FILE);
12974
+ const kind = pathKind(root, path);
12975
+ if (kind === "outside") {
12976
+ fail(where, "resolves outside the plugin folder; skipped");
12977
+ return null;
12978
+ }
12979
+ if (kind !== "file")
12980
+ return null;
12981
+ const parsed = parseFrontmatter(readText(path));
12982
+ if (!parsed.ok) {
12983
+ fail(where, `${parsed.problem}; skipped`);
12984
+ return null;
12985
+ }
12986
+ const problems = [];
12987
+ const skillName = parsed.meta.name;
12988
+ const description = typeof parsed.meta.description === "string" ? parsed.meta.description.trim() : "";
12989
+ if (skillName !== name)
12990
+ problems.push(`name must be the folder's name "${name}"`);
12991
+ else if (!SKILL_NAME.test(name) || name.length > MAX_SKILL_NAME_CHARS) {
12992
+ problems.push("name must be 1-64 lowercase letters, digits and single inner hyphens");
12993
+ }
12994
+ if (!description)
12995
+ problems.push("description (when to read it) is missing");
12996
+ else if (description.length > MAX_SKILL_DESCRIPTION_CHARS) {
12997
+ problems.push(`description is over ${MAX_SKILL_DESCRIPTION_CHARS} characters`);
12998
+ }
12999
+ if (problems.length > 0) {
13000
+ fail(where, `${problems.join("; ")}; skipped`);
13001
+ return null;
13002
+ }
13003
+ return { name, description, path };
13004
+ }
13005
+ function readSkills(root, dir, fail) {
13006
+ const skillsDir = join23(root, SKILLS_DIR);
13007
+ const kind = pathKind(root, skillsDir);
13008
+ if (kind === "missing")
13009
+ return [];
13010
+ if (kind !== "dir") {
13011
+ fail(SKILLS_DIR, kind === "outside" ? "resolves outside the plugin folder" : "not a folder");
13012
+ return [];
13013
+ }
13014
+ return readdirSync5(skillsDir).filter(visible).sort(byName).flatMap((name) => readSkill(root, dir, name, fail) ?? []);
13015
+ }
13016
+ function remoteUrlProblem(raw) {
13017
+ let url;
13018
+ try {
13019
+ url = new URL(raw);
13020
+ } catch {
13021
+ return "url must be an absolute http or https URL";
13022
+ }
13023
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
13024
+ return "url must be an absolute http or https URL";
13025
+ }
13026
+ if (url.username || url.password)
13027
+ return "url must not contain user information";
13028
+ if (url.hash || raw.includes("#"))
13029
+ return "url must not contain a fragment";
13030
+ if (url.protocol === "http:" && !isLoopbackHost(url.hostname)) {
13031
+ return "a non-loopback url must use https";
13032
+ }
13033
+ return null;
13034
+ }
13035
+ function isLoopbackHost(hostname) {
13036
+ if (hostname === "localhost" || hostname === "[::1]")
13037
+ return true;
13038
+ const parts = hostname.split(".");
13039
+ return parts.length === 4 && parts[0] === "127" && parts.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255);
13040
+ }
13041
+ function readServer(name, spec, fail) {
13042
+ if (!isObject(spec) || typeof spec.type !== "string") {
13043
+ fail(`"${name}": a server is an object with a "type"; skipped`);
13044
+ return null;
13045
+ }
13046
+ if (spec.type === "stdio") {
13047
+ fail(`"${name}": stdio servers are not supported here (remote servers only); skipped`);
13048
+ return null;
13049
+ }
13050
+ const variant = REMOTE_SERVERS[spec.type];
13051
+ if (!variant) {
13052
+ fail(`"${name}": unknown type "${spec.type}"; skipped`);
13053
+ return null;
13054
+ }
13055
+ const allowed = new Set(Object.keys(variant.properties));
13056
+ const unknown = Object.keys(spec).find((key) => !allowed.has(key));
13057
+ if (unknown) {
13058
+ fail(`"${name}": field "${unknown}" does not belong to a ${spec.type} server; skipped`);
13059
+ return null;
13060
+ }
13061
+ if (typeof spec.url !== "string" || !spec.url) {
13062
+ fail(`"${name}": url is required; skipped`);
13063
+ return null;
13064
+ }
13065
+ const headers = spec.headers;
13066
+ if (headers !== undefined) {
13067
+ const values = isObject(headers) ? Object.entries(headers) : null;
13068
+ const lower = values?.map(([key]) => key.toLowerCase()) ?? [];
13069
+ if (!values || values.some(([, value]) => typeof value !== "string") || new Set(lower).size !== lower.length) {
13070
+ fail(`"${name}": headers must be distinct header names with string values; skipped`);
13071
+ return null;
13072
+ }
13073
+ }
13074
+ const server = {
13075
+ type: NODE_TRANSPORT[spec.type],
13076
+ url: spec.url,
13077
+ ...headers ? { headers } : {}
13078
+ };
13079
+ const urlProblem = remoteUrlProblem(spec.url);
13080
+ if (urlProblem) {
13081
+ fail(`"${name}": ${urlProblem}; skipped`);
13082
+ return null;
13083
+ }
13084
+ try {
13085
+ parseHostMcpServers({ [name]: server });
13086
+ } catch (error) {
13087
+ fail(`"${name}": ${error instanceof Error ? error.message : String(error)}; skipped`);
13088
+ return null;
13089
+ }
13090
+ return server;
13091
+ }
13092
+ function readMcpFile(root, fail) {
13093
+ const path = join23(root, MCP_FILE);
13094
+ const kind = pathKind(root, path);
13095
+ if (kind === "missing")
13096
+ return {};
13097
+ if (kind !== "file") {
13098
+ fail(`${kind === "outside" ? "resolves outside the plugin folder" : "not a file"}; no servers`);
13099
+ return {};
13100
+ }
13101
+ const raw = readJson(path, fail);
13102
+ if (raw === undefined)
13103
+ return {};
13104
+ const extra = isObject(raw) ? Object.keys(raw).find((key) => key !== "$schema" && key !== "mcpServers") : undefined;
13105
+ if (!isObject(raw) || raw.$schema !== MCP_SCHEMA_ID || !isObject(raw.mcpServers) || extra) {
13106
+ fail(`must be {"$schema": "${MCP_SCHEMA_ID}", "mcpServers": {\u2026}} and nothing else; no servers`);
13107
+ return {};
13108
+ }
13109
+ const servers = {};
13110
+ for (const [name, spec] of Object.entries(raw.mcpServers)) {
13111
+ const server = readServer(name, spec, fail);
13112
+ if (server)
13113
+ servers[name] = server;
13114
+ }
13115
+ return servers;
13116
+ }
13117
+ function loadTopicPlugins(dirs) {
13118
+ const problems = [];
13119
+ const plugins = [];
13120
+ const pluginOwner = new Map;
13121
+ const skillOwner = new Map;
13122
+ const serverOwner = new Map;
13123
+ for (const dir of dirs) {
13124
+ if (!isAbsolute6(dir)) {
13125
+ problems.push(`${dir}: a plugin is given by its folder's absolute path`);
13126
+ continue;
13127
+ }
13128
+ if (!existsSync22(dir) || !statSync8(dir).isDirectory()) {
13129
+ problems.push(`${dir}: not a folder`);
13130
+ continue;
13131
+ }
13132
+ const root = realpathSync6(dir);
13133
+ const failIn = (file, problem) => problems.push(`${dir}/${file}: ${problem}`);
13134
+ const manifest = readManifest(root, (problem) => failIn(MANIFEST_FILE, problem));
13135
+ if (!manifest)
13136
+ continue;
13137
+ const owner = pluginOwner.get(manifest.id);
13138
+ if (owner) {
13139
+ failIn(MANIFEST_FILE, `plugin name "${manifest.id}" is already used by ${owner}; skipped`);
13140
+ continue;
13141
+ }
13142
+ pluginOwner.set(manifest.id, dir);
13143
+ const unique = (owners, key, what, file) => {
13144
+ const other = owners.get(key);
13145
+ if (other)
13146
+ failIn(file, `${what} "${key}" is already used by ${other}; skipped`);
13147
+ else
13148
+ owners.set(key, dir);
13149
+ return !other;
13150
+ };
13151
+ const skills = readSkills(root, dir, failIn).filter((skill) => unique(skillOwner, skill.name, "skill name", SKILLS_DIR));
13152
+ const mcpServers = Object.fromEntries(Object.entries(readMcpFile(root, (problem) => failIn(MCP_FILE, problem))).filter(([name]) => unique(serverOwner, name, "server name", MCP_FILE)));
13153
+ plugins.push({ ...manifest, dir, skills, mcpServers });
13154
+ }
13155
+ return { plugins, problems };
13156
+ }
13157
+ function renderTopicPluginsPrompt(plugins) {
13158
+ const skills = plugins.flatMap((plugin) => plugin.skills);
13159
+ if (skills.length === 0)
13160
+ return "";
13161
+ return [
13162
+ "## Skills",
13163
+ "",
13164
+ "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.",
13165
+ "",
13166
+ ...skills.map((skill) => `- \`${skill.name}\`: ${skill.description} (file: ${skill.path})`)
13167
+ ].join(`
13168
+ `);
13169
+ }
13170
+ 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;
13171
+ var init_plugins = __esm(() => {
13172
+ init_runtime_gateway();
13173
+ init_mcp_schema();
13174
+ init_plugin_schema();
13175
+ MANIFEST_SCHEMA_ID = plugin_schema_default.properties.$schema.const;
13176
+ MCP_SCHEMA_ID = mcp_schema_default.properties.$schema.const;
13177
+ MANIFEST_FIELDS = new Set(Object.keys(plugin_schema_default.properties));
13178
+ REMOTE_SERVERS = {
13179
+ "streamable-http": mcp_schema_default.$defs.streamableHttpServer,
13180
+ sse: mcp_schema_default.$defs.sseServer
13181
+ };
13182
+ NODE_TRANSPORT = { "streamable-http": "http", sse: "sse" };
13183
+ SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
13184
+ });
13185
+
12587
13186
  // ../../packages/core/src/prompts/builders.ts
12588
- import { readFileSync as readFileSync17 } from "fs";
13187
+ import { readFileSync as readFileSync18 } from "fs";
12589
13188
  import { resolve as resolve16 } from "path";
12590
13189
  function loadPrompt(filename, dir = SESSIONS_DIR) {
12591
- const raw = readFileSync17(resolve16(dir, filename), "utf-8");
13190
+ const raw = readFileSync18(resolve16(dir, filename), "utf-8");
12592
13191
  return raw.replace(/\{\{RESOURCES_DIR\}\}/g, RESOURCES_DIR);
12593
13192
  }
12594
13193
  function replaceVars(template, vars) {
@@ -12651,7 +13250,7 @@ function visualDesignGuide() {
12651
13250
  return _visualDesignGuide;
12652
13251
  }
12653
13252
  function loadAgentPrompt(filename) {
12654
- const raw = readFileSync17(resolve16(AGENTS_PROMPTS_DIR, filename), "utf-8");
13253
+ const raw = readFileSync18(resolve16(AGENTS_PROMPTS_DIR, filename), "utf-8");
12655
13254
  const match = raw.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
12656
13255
  if (!match)
12657
13256
  throw new Error(`Agent prompt ${filename} is missing frontmatter`);
@@ -12899,6 +13498,11 @@ function createPromptBuilders(host = {}) {
12899
13498
  ## Topic-Specific Instructions
12900
13499
  ${opts.description.trim()}`;
12901
13500
  }
13501
+ const plugins = renderTopicPluginsPrompt(opts.plugins ?? []);
13502
+ if (plugins)
13503
+ prompt += `
13504
+
13505
+ ${plugins}`;
12902
13506
  if (sessionKind === "manager") {
12903
13507
  const managerTemplate = replaceVars(template(opts.surface === "otium" ? {
12904
13508
  kind: "surface-profile",
@@ -12988,6 +13592,7 @@ var init_builders = __esm(() => {
12988
13592
  init_browser_backend();
12989
13593
  init_config();
12990
13594
  init_logger();
13595
+ init_plugins();
12991
13596
  PROMPTS_DIR = resolve16(PROJECT_ROOT, "src/prompts");
12992
13597
  SESSIONS_DIR = resolve16(PROMPTS_DIR, "sessions");
12993
13598
  SURFACE_PROFILE_FILES = {
@@ -13072,9 +13677,9 @@ var init_api_topic_brief = __esm(async () => {
13072
13677
  });
13073
13678
 
13074
13679
  // ../../packages/core/src/storage/wiki.ts
13075
- import { basename as basename5, dirname as dirname15, join as join23 } from "path";
13680
+ import { basename as basename5, dirname as dirname15, join as join24 } from "path";
13076
13681
  function getSharedWikiDir(workspaceDir = resolveStorageWorkspaceDir()) {
13077
- return workspaceDir === resolveStorageWorkspaceDir() ? resolveStorageSharedWikiDir() : join23(workspaceDir, "wiki");
13682
+ return workspaceDir === resolveStorageWorkspaceDir() ? resolveStorageSharedWikiDir() : join24(workspaceDir, "wiki");
13078
13683
  }
13079
13684
  var init_wiki = __esm(async () => {
13080
13685
  await init_storage_host();
@@ -13082,8 +13687,8 @@ var init_wiki = __esm(async () => {
13082
13687
 
13083
13688
  // ../../packages/core/src/agents/archiver.ts
13084
13689
  import { randomUUID as randomUUID11 } from "crypto";
13085
- import { existsSync as existsSync22, readdirSync as readdirSync5, readFileSync as readFileSync18, statSync as statSync8 } from "fs";
13086
- import { join as join24 } from "path";
13690
+ import { existsSync as existsSync23, readdirSync as readdirSync6, readFileSync as readFileSync19, statSync as statSync9 } from "fs";
13691
+ import { join as join25 } from "path";
13087
13692
  function resolveMemoryLanguage() {
13088
13693
  const override = process.env.NEGOTIUM_MEMORY_LANG?.trim();
13089
13694
  return override && override.length > 0 ? override : resolveOutputLanguage();
@@ -13341,10 +13946,10 @@ function distillOneLine(summaryMd) {
13341
13946
  return "";
13342
13947
  }
13343
13948
  function findSummaryFile(storage, topicTitle, date, sinceMs, topicId) {
13344
- const dir = join24(storage.getWikiDir(), "summaries");
13949
+ const dir = join25(storage.getWikiDir(), "summaries");
13345
13950
  if (!storage.fileExists(dir))
13346
13951
  return null;
13347
- const predicted = join24(dir, wikiSummaryFilename(date, topicTitle, topicId));
13952
+ const predicted = join25(dir, wikiSummaryFilename(date, topicTitle, topicId));
13348
13953
  if (storage.fileExists(predicted) && storage.fileModifiedAt(predicted) >= sinceMs)
13349
13954
  return predicted;
13350
13955
  let best = null;
@@ -13352,7 +13957,7 @@ function findSummaryFile(storage, topicTitle, date, sinceMs, topicId) {
13352
13957
  if (!f.startsWith(`${date}-`) || !isTopicSummaryFile(f, topicId ?? "", topicTitle)) {
13353
13958
  continue;
13354
13959
  }
13355
- const p = join24(dir, f);
13960
+ const p = join25(dir, f);
13356
13961
  try {
13357
13962
  const m = storage.fileModifiedAt(p);
13358
13963
  if (m >= sinceMs && (!best || m > best.mtime))
@@ -13438,11 +14043,11 @@ var init_archiver = __esm(async () => {
13438
14043
  defaultArchiverRuntime = createArchiverRuntime({
13439
14044
  storage: {
13440
14045
  getWikiDir: getSharedWikiDir,
13441
- fileExists: existsSync22,
13442
- listDirectory: readdirSync5,
13443
- readTextFile: (path) => readFileSync18(path, "utf-8"),
13444
- fileSize: (path) => statSync8(path).size,
13445
- fileModifiedAt: (path) => statSync8(path).mtimeMs,
14046
+ fileExists: existsSync23,
14047
+ listDirectory: readdirSync6,
14048
+ readTextFile: (path) => readFileSync19(path, "utf-8"),
14049
+ fileSize: (path) => statSync9(path).size,
14050
+ fileModifiedAt: (path) => statSync9(path).mtimeMs,
13446
14051
  getGeneralTopicId: (userId, sourceTopicId) => {
13447
14052
  const source = sourceTopicId ? getTopic(sourceTopicId) : null;
13448
14053
  return source ? ensurePersonalGeneral(userId, source.surface, {
@@ -13566,13 +14171,13 @@ function formatTopicArchiveTranscriptRecord(row, topicTitle, index) {
13566
14171
 
13567
14172
  // ../../packages/core/src/storage/topic-archive.ts
13568
14173
  import { mkdirSync as mkdirSync14, writeFileSync as writeFileSync12 } from "fs";
13569
- import { join as join25 } from "path";
14174
+ import { join as join26 } from "path";
13570
14175
  function archiveTopicMessages(topicId, topicTitle, options = {}) {
13571
14176
  const rows = options.afterRowid !== undefined ? getMessagesForTopicAfterRowid(topicId, options.afterRowid) : getAllMessagesForTopic(topicId);
13572
14177
  if (rows.length === 0)
13573
14178
  return null;
13574
14179
  const safeTopic = sanitizeTopicName(topicTitle, true);
13575
- const archiveDir = join25(getSharedWikiDir(), "archive");
14180
+ const archiveDir = join26(getSharedWikiDir(), "archive");
13576
14181
  mkdirSync14(archiveDir, { recursive: true });
13577
14182
  const date = new Date().toISOString().slice(0, 10);
13578
14183
  const reasonSuffix = options.reason && options.reason !== "delete" ? `_${options.reason}` : "";
@@ -13585,7 +14190,7 @@ function archiveTopicMessages(topicId, topicTitle, options = {}) {
13585
14190
  let path;
13586
14191
  while (true) {
13587
14192
  filename = `${safeTopic}_${date}${reasonSuffix}${counter === 1 ? "" : `_${counter}`}.jsonl`;
13588
- path = join25(archiveDir, filename);
14193
+ path = join26(archiveDir, filename);
13589
14194
  try {
13590
14195
  writeFileSync12(path, body, { flag: "wx" });
13591
14196
  break;
@@ -13630,7 +14235,7 @@ function archiveConversationEvents(topicId, topicTitle, userId, options = {}) {
13630
14235
  const entries = readRawConversation(userId, topicTitle);
13631
14236
  if (entries.length === 0)
13632
14237
  return null;
13633
- const archiveDir = join25(getSharedWikiDir(), "archive");
14238
+ const archiveDir = join26(getSharedWikiDir(), "archive");
13634
14239
  mkdirSync14(archiveDir, { recursive: true });
13635
14240
  const safeTopic = sanitizeTopicName(topicTitle, true);
13636
14241
  const date = new Date().toISOString().slice(0, 10);
@@ -13658,7 +14263,7 @@ function archiveConversationEvents(topicId, topicTitle, userId, options = {}) {
13658
14263
  let counter = 1;
13659
14264
  while (true) {
13660
14265
  const suffix = counter === 1 ? "" : `_${counter}`;
13661
- const path = join25(archiveDir, `${safeTopic}_${date}${reasonSuffix}_events${suffix}.jsonl`);
14266
+ const path = join26(archiveDir, `${safeTopic}_${date}${reasonSuffix}_events${suffix}.jsonl`);
13662
14267
  try {
13663
14268
  writeFileSync12(path, body, { flag: "wx" });
13664
14269
  logger.info({ topicId, topicTitle, archive: path, eventCount: entries.length }, "archiveConversationEvents: archived raw conversation events");
@@ -13986,7 +14591,7 @@ var init_idle_archiver = __esm(async () => {
13986
14591
  // ../../packages/core/src/storage/token-stats.ts
13987
14592
  import { createHash as createHash7 } from "crypto";
13988
14593
  import { mkdirSync as mkdirSync15, writeFileSync as writeFileSync13 } from "fs";
13989
- import { join as join26 } from "path";
14594
+ import { join as join27 } from "path";
13990
14595
  function emptyBucket() {
13991
14596
  return {
13992
14597
  inputTokens: 0,
@@ -14005,7 +14610,7 @@ function queriesPath(userId) {
14005
14610
  const fileId = tokenStatsFileId(userId);
14006
14611
  const logDir = resolveStorageLogDir();
14007
14612
  mkdirSync15(logDir, { recursive: true });
14008
- return join26(logDir, `token-queries-${fileId}.jsonl`);
14613
+ return join27(logDir, `token-queries-${fileId}.jsonl`);
14009
14614
  }
14010
14615
  function loadRecords(userId) {
14011
14616
  try {
@@ -14632,7 +15237,7 @@ var init_usage_alert = __esm(() => {
14632
15237
  import { randomUUID as randomUUID12 } from "crypto";
14633
15238
  import { mkdtempSync as mkdtempSync2, rmSync as rmSync4, writeFileSync as writeFileSync15 } from "fs";
14634
15239
  import { tmpdir as tmpdir4 } from "os";
14635
- import { join as join27 } from "path";
15240
+ import { join as join28 } from "path";
14636
15241
  async function fenceTopicWork(topicId, maintenance) {
14637
15242
  for (const queryId of cancelRuntimeUserTurnRequestsBeforeEpoch(topicId, maintenance.epoch)) {
14638
15243
  WsHub.get().broadcastAborted(topicId, queryId, "stopped");
@@ -14841,7 +15446,7 @@ function formatCompactElapsed(startedAt) {
14841
15446
  async function summarizeTopicContext(request) {
14842
15447
  const startedAt = Date.now();
14843
15448
  const sessionIds = [];
14844
- const compactCwd = mkdtempSync2(join27(tmpdir4(), "negotium-compact-"));
15449
+ const compactCwd = mkdtempSync2(join28(tmpdir4(), "negotium-compact-"));
14845
15450
  const abortController = new AbortController;
14846
15451
  const relayAbort = () => abortController.abort(request.signal?.reason);
14847
15452
  if (request.signal?.aborted)
@@ -14868,7 +15473,7 @@ async function summarizeTopicContext(request) {
14868
15473
  let error = "";
14869
15474
  let toolViolation = false;
14870
15475
  let compactionLogCalls = 0;
14871
- const compactionLogPath = join27(compactCwd, "conversation.log");
15476
+ const compactionLogPath = join28(compactCwd, "conversation.log");
14872
15477
  try {
14873
15478
  const compactionMcp = useCompactionLog ? {
14874
15479
  compact_log: {
@@ -15627,14 +16232,14 @@ var init_derive = __esm(async () => {
15627
16232
  });
15628
16233
 
15629
16234
  // ../../packages/core/src/query/session-inbox-path.ts
15630
- import { join as join28 } from "path";
16235
+ import { join as join29 } from "path";
15631
16236
  function sessionInboxPath(userId, topicId) {
15632
16237
  const key = Buffer.from(topicId, "utf8").toString("base64url");
15633
- return join28(SESSION_INBOX_DIR, userId, `${TOPIC_ID_FILE_PREFIX}${key}${JSONL_SUFFIX}`);
16238
+ return join29(SESSION_INBOX_DIR, userId, `${TOPIC_ID_FILE_PREFIX}${key}${JSONL_SUFFIX}`);
15634
16239
  }
15635
16240
  function scheduledSessionInboxPath(userId, topicId) {
15636
16241
  const key = Buffer.from(topicId, "utf8").toString("base64url");
15637
- return join28(SESSION_INBOX_DIR, userId, `${TOPIC_ID_FILE_PREFIX}${key}${SCHEDULE_SUFFIX}`);
16242
+ return join29(SESSION_INBOX_DIR, userId, `${TOPIC_ID_FILE_PREFIX}${key}${SCHEDULE_SUFFIX}`);
15638
16243
  }
15639
16244
  var TOPIC_ID_FILE_PREFIX = "topic-id-", JSONL_SUFFIX = ".jsonl", SCHEDULE_SUFFIX = ".schedule";
15640
16245
  var init_session_inbox_path = __esm(() => {
@@ -15642,12 +16247,12 @@ var init_session_inbox_path = __esm(() => {
15642
16247
  });
15643
16248
 
15644
16249
  // ../../packages/core/src/storage/session-inbox-signal.ts
15645
- import { join as join29 } from "path";
16250
+ import { join as join30 } from "path";
15646
16251
  var SESSION_INBOX_WAKE_FILE, listeners;
15647
16252
  var init_session_inbox_signal = __esm(() => {
15648
16253
  init_config();
15649
16254
  init_logger();
15650
- SESSION_INBOX_WAKE_FILE = join29(SESSION_INBOX_DIR, ".wake");
16255
+ SESSION_INBOX_WAKE_FILE = join30(SESSION_INBOX_DIR, ".wake");
15651
16256
  listeners = new Set;
15652
16257
  });
15653
16258
 
@@ -15685,13 +16290,13 @@ var init_session_inbox = __esm(async () => {
15685
16290
 
15686
16291
  // ../../packages/core/src/query/session-inbox-cleanup.ts
15687
16292
  import { unlinkSync as unlinkSync16 } from "fs";
15688
- import { basename as basename6, join as join30 } from "path";
16293
+ import { basename as basename6, join as join31 } from "path";
15689
16294
  function cleanupSessionInboxFiles(userId, topicId, legacyTopicTitle) {
15690
16295
  const live = sessionInboxPath(userId, topicId);
15691
16296
  const scheduled = scheduledSessionInboxPath(userId, topicId);
15692
16297
  const candidates = new Set([live, `${live}.processing`, scheduled, `${scheduled}.processing`]);
15693
16298
  if (legacyTopicTitle && legacyTopicTitle !== "." && legacyTopicTitle !== ".." && basename6(legacyTopicTitle) === legacyTopicTitle) {
15694
- const legacyBase = join30(SESSION_INBOX_DIR, userId, legacyTopicTitle);
16299
+ const legacyBase = join31(SESSION_INBOX_DIR, userId, legacyTopicTitle);
15695
16300
  for (const suffix of [".jsonl", ".jsonl.processing", ".schedule", ".schedule.processing"]) {
15696
16301
  candidates.add(`${legacyBase}${suffix}`);
15697
16302
  }
@@ -15931,35 +16536,35 @@ import {
15931
16536
  closeSync as closeSync3,
15932
16537
  mkdirSync as mkdirSync18,
15933
16538
  openSync as openSync3,
15934
- readdirSync as readdirSync6,
15935
- readFileSync as readFileSync19,
15936
- statSync as statSync9,
16539
+ readdirSync as readdirSync7,
16540
+ readFileSync as readFileSync20,
16541
+ statSync as statSync10,
15937
16542
  unlinkSync as unlinkSync17,
15938
16543
  writeFileSync as writeFileSync16
15939
16544
  } from "fs";
15940
- import { dirname as dirname17, join as join31 } from "path";
16545
+ import { dirname as dirname17, join as join32 } from "path";
15941
16546
  function pendingAskDir(userId) {
15942
16547
  const rawUserId = String(userId);
15943
16548
  const safeUserId = /^[A-Za-z0-9][A-Za-z0-9_.@-]{0,255}$/.test(rawUserId) && !rawUserId.includes("..") ? rawUserId : `sha256-${createHash9("sha256").update(rawUserId).digest("hex")}`;
15944
- return join31(resolveStorageSessionAsksDir(), safeUserId);
16549
+ return join32(resolveStorageSessionAsksDir(), safeUserId);
15945
16550
  }
15946
16551
  function encodeAskKey(key) {
15947
16552
  return JSON.stringify([key.from, key.to]);
15948
16553
  }
15949
16554
  function pendingAskPath(key) {
15950
16555
  const digest = createHash9("sha256").update(encodeAskKey(key)).digest("hex");
15951
- return join31(pendingAskDir(key.userId), `${ASK_FILENAME_PREFIX}${digest}.pending`);
16556
+ return join32(pendingAskDir(key.userId), `${ASK_FILENAME_PREFIX}${digest}.pending`);
15952
16557
  }
15953
16558
  function v2PendingAskPath(key) {
15954
16559
  const encoded = Buffer.from(encodeAskKey(key), "utf8").toString("base64url");
15955
- return join31(pendingAskDir(key.userId), `${V2_ASK_FILENAME_PREFIX}${encoded}.pending`);
16560
+ return join32(pendingAskDir(key.userId), `${V2_ASK_FILENAME_PREFIX}${encoded}.pending`);
15956
16561
  }
15957
16562
  function legacyPendingAskPath(key) {
15958
16563
  if (key.from.includes("/") || key.from.includes("\\") || key.to.includes("/") || key.to.includes("\\") || key.from.includes("\x00") || key.to.includes("\x00")) {
15959
16564
  return null;
15960
16565
  }
15961
16566
  const dir = pendingAskDir(key.userId);
15962
- const candidate = join31(dir, `${key.from}___${key.to}.pending`);
16567
+ const candidate = join32(dir, `${key.from}___${key.to}.pending`);
15963
16568
  return dirname17(candidate) === dir ? candidate : null;
15964
16569
  }
15965
16570
  function parsePendingAskFilename(fileName) {
@@ -15981,11 +16586,11 @@ function parsePendingAskFilename(fileName) {
15981
16586
  }
15982
16587
  function readPendingAskFile(path, fallback) {
15983
16588
  try {
15984
- const raw = readFileSync19(path, "utf8").trim();
16589
+ const raw = readFileSync20(path, "utf8").trim();
15985
16590
  if (!raw)
15986
16591
  return null;
15987
16592
  if (!raw.startsWith("{")) {
15988
- const ts = new Date(statSync9(path).mtimeMs).toISOString();
16593
+ const ts = new Date(statSync10(path).mtimeMs).toISOString();
15989
16594
  return {
15990
16595
  userId: fallback.userId,
15991
16596
  from: fallback.from,
@@ -16105,13 +16710,13 @@ function deletePendingAsksForTopic(args) {
16105
16710
  const dir = pendingAskDir(args.userId);
16106
16711
  let files;
16107
16712
  try {
16108
- files = readdirSync6(dir);
16713
+ files = readdirSync7(dir);
16109
16714
  } catch {
16110
16715
  return 0;
16111
16716
  }
16112
16717
  let deleted = 0;
16113
16718
  for (const fileName of files) {
16114
- const path = join31(dir, fileName);
16719
+ const path = join32(dir, fileName);
16115
16720
  const parsed = parsePendingAskFilename(fileName);
16116
16721
  const record = readPendingAskFile(path, {
16117
16722
  userId: args.userId,
@@ -16827,82 +17432,6 @@ var init_self_schedules = __esm(async () => {
16827
17432
  });
16828
17433
  });
16829
17434
 
16830
- // ../../packages/core/src/runtime-gateway.ts
16831
- function parseHostMcpServers(value) {
16832
- if (value === undefined)
16833
- return;
16834
- if (!value || typeof value !== "object" || Array.isArray(value)) {
16835
- throw new TypeError("hostMcpServers must be an object");
16836
- }
16837
- const parsedEntries = [];
16838
- for (const [name, raw] of Object.entries(value)) {
16839
- if (!HOST_MCP_SERVER_NAME.test(name)) {
16840
- throw new TypeError(`invalid host MCP server name: ${name}`);
16841
- }
16842
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
16843
- throw new TypeError(`hostMcpServers.${name} must be an object`);
16844
- }
16845
- const spec = raw;
16846
- const unsupported = Object.keys(spec).find((key) => !HOST_MCP_SERVER_KEYS.has(key));
16847
- if (unsupported) {
16848
- throw new TypeError(`hostMcpServers.${name}.${unsupported} is not allowed`);
16849
- }
16850
- if (spec.type !== "sse" && spec.type !== "http") {
16851
- throw new TypeError(`hostMcpServers.${name}.type must be sse or http`);
16852
- }
16853
- if (typeof spec.url !== "string") {
16854
- throw new TypeError(`hostMcpServers.${name}.url must be a string`);
16855
- }
16856
- let url;
16857
- try {
16858
- url = new URL(spec.url);
16859
- } catch {
16860
- throw new TypeError(`hostMcpServers.${name}.url must be a valid URL`);
16861
- }
16862
- if (url.protocol !== "http:" && url.protocol !== "https:") {
16863
- throw new TypeError(`hostMcpServers.${name}.url must use http or https`);
16864
- }
16865
- let headers;
16866
- if (spec.headers !== undefined) {
16867
- if (!spec.headers || typeof spec.headers !== "object" || Array.isArray(spec.headers)) {
16868
- throw new TypeError(`hostMcpServers.${name}.headers must be an object`);
16869
- }
16870
- const headerEntries = [];
16871
- for (const [key, headerValue] of Object.entries(spec.headers)) {
16872
- if (!HTTP_HEADER_NAME.test(key) || typeof headerValue !== "string") {
16873
- throw new TypeError(`hostMcpServers.${name}.headers must contain string values`);
16874
- }
16875
- try {
16876
- new Headers([[key, headerValue]]);
16877
- } catch {
16878
- throw new TypeError(`hostMcpServers.${name}.headers contains an invalid header`);
16879
- }
16880
- headerEntries.push([key, headerValue]);
16881
- }
16882
- headers = Object.fromEntries(headerEntries);
16883
- }
16884
- if (spec.timeout !== undefined && (typeof spec.timeout !== "number" || !Number.isFinite(spec.timeout) || spec.timeout <= 0)) {
16885
- throw new TypeError(`hostMcpServers.${name}.timeout must be a positive number`);
16886
- }
16887
- parsedEntries.push([
16888
- name,
16889
- {
16890
- type: spec.type,
16891
- url: url.toString(),
16892
- ...headers ? { headers } : {},
16893
- ...spec.timeout !== undefined ? { timeout: spec.timeout } : {}
16894
- }
16895
- ]);
16896
- }
16897
- return Object.fromEntries(parsedEntries);
16898
- }
16899
- var HOST_MCP_SERVER_NAME, HOST_MCP_SERVER_KEYS, HTTP_HEADER_NAME;
16900
- var init_runtime_gateway = __esm(() => {
16901
- HOST_MCP_SERVER_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
16902
- HOST_MCP_SERVER_KEYS = new Set(["type", "url", "headers", "timeout"]);
16903
- HTTP_HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
16904
- });
16905
-
16906
17435
  // ../../packages/core/src/storage/topic-host-mcp-grants.ts
16907
17436
  function getTopicHostMcpGrant(topicId) {
16908
17437
  const row = db.query("SELECT servers_json FROM api_topic_host_mcp_grants WHERE topic_id = ?").get(topicId);
@@ -17211,7 +17740,7 @@ var init_lifecycle = __esm(async () => {
17211
17740
 
17212
17741
  // ../../packages/core/src/runtime/attachments.ts
17213
17742
  import { copyFileSync as copyFileSync2, mkdirSync as mkdirSync19, writeFileSync as writeFileSync17 } from "fs";
17214
- import { basename as basename7, join as join32 } from "path";
17743
+ import { basename as basename7, join as join33 } from "path";
17215
17744
  function workspaceCwdFor(topicId) {
17216
17745
  return resolveTopicWorkspaceDir(topicId);
17217
17746
  }
@@ -17224,7 +17753,7 @@ function materializePromptAttachments(topicId, queryId, attachmentIds) {
17224
17753
  if (!attachmentIds?.length)
17225
17754
  return [];
17226
17755
  const out = [];
17227
- const destDir = join32(workspaceCwdFor(topicId), "attachments", queryId);
17756
+ const destDir = join33(workspaceCwdFor(topicId), "attachments", queryId);
17228
17757
  for (const rawId of attachmentIds) {
17229
17758
  if (typeof rawId !== "string")
17230
17759
  continue;
@@ -17241,7 +17770,7 @@ function materializePromptAttachments(topicId, queryId, attachmentIds) {
17241
17770
  mkdirSync19(destDir, { recursive: true });
17242
17771
  const index = String(out.length + 1).padStart(2, "0");
17243
17772
  const safeName = safeAttachmentFilename(attachment.filename, fileId);
17244
- const destPath = join32(destDir, `${index}-${fileId.slice(0, 8)}-${safeName}`);
17773
+ const destPath = join33(destDir, `${index}-${fileId.slice(0, 8)}-${safeName}`);
17245
17774
  copyFileSync2(sourcePath, destPath);
17246
17775
  out.push({
17247
17776
  id: attachment.id,
@@ -17725,7 +18254,7 @@ var init_ask_user_gates = __esm(async () => {
17725
18254
 
17726
18255
  // ../../packages/core/src/agents/mcp-tools/ask-user.ts
17727
18256
  import { createHash as createHash11, randomUUID as randomUUID16 } from "crypto";
17728
- import { z as z5 } from "zod";
18257
+ import { z as z6 } from "zod";
17729
18258
  function normalizeAskText(value, maxChars) {
17730
18259
  if (typeof value !== "string")
17731
18260
  return;
@@ -17770,8 +18299,8 @@ function answerToolResult(answer) {
17770
18299
  return textResult("The user skipped this question. Continue using your best judgment and finish the current turn.");
17771
18300
  }
17772
18301
  if (answer.kind === "custom") {
17773
- return textResult(`User answered in their own words: ${answer.label}
17774
- Continue from this answer and finish the current turn.`);
18302
+ return textResult(`The user did not pick a listed option. They typed this reply in the chat instead: "${answer.label}"
18303
+ Treat it as their free-text answer to your question and read it for what it says. If it hands the decision back to you (for example "decide yourself" or "you handle it"), choose the best option yourself and go on. Continue from this answer and finish the current turn.`);
17775
18304
  }
17776
18305
  const description = answer.description ? `
17777
18306
  Description: ${answer.description}` : "";
@@ -17863,6 +18392,7 @@ function createAskUserRuntime(host) {
17863
18392
  id: createId(),
17864
18393
  topicId,
17865
18394
  authorId: userId,
18395
+ ...options.answerMessage,
17866
18396
  text: label,
17867
18397
  parentId: messageId,
17868
18398
  ...existing.threadRootId ? { threadRootId: existing.threadRootId } : {},
@@ -17881,6 +18411,20 @@ function createAskUserRuntime(host) {
17881
18411
  pending.resolve({ ...choice, userId, ...kind ? { kind } : {} });
17882
18412
  return { ok: true, queryId: pending.queryId, answerMessage };
17883
18413
  }
18414
+ function answerOpenQuestionWithText(topicId, text, userId, options = {}) {
18415
+ for (const [messageId, pending] of pendingAsks) {
18416
+ if (pending.topicId !== topicId)
18417
+ continue;
18418
+ const card = host.messaging.persistence.getMessage(topicId, messageId);
18419
+ if ((card?.threadRootId ?? undefined) !== (options.threadRootId ?? undefined))
18420
+ continue;
18421
+ return answerPendingQuestion(topicId, messageId, text, userId, {
18422
+ kind: "custom",
18423
+ ...options.answerMessage ? { answerMessage: options.answerMessage } : {}
18424
+ });
18425
+ }
18426
+ return null;
18427
+ }
17884
18428
  function cancelPendingQuestions(topicId, queryId) {
17885
18429
  for (const [messageId, pending] of pendingAsks) {
17886
18430
  if (pending.topicId === topicId && pending.queryId === queryId) {
@@ -18018,12 +18562,12 @@ function createAskUserRuntime(host) {
18018
18562
  name: "ask_user_question",
18019
18563
  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.",
18020
18564
  schema: {
18021
- question: z5.string().describe("The concise question to show to the user."),
18022
- choices: z5.array(z5.object({
18023
- label: z5.string().describe("Choice label shown on the button."),
18024
- description: z5.string().optional().describe("Optional one-sentence consequence.")
18565
+ question: z6.string().describe("The concise question to show to the user."),
18566
+ choices: z6.array(z6.object({
18567
+ label: z6.string().describe("Choice label shown on the button."),
18568
+ description: z6.string().optional().describe("Optional one-sentence consequence.")
18025
18569
  })).min(1).max(MAX_CHOICES).describe("Choices the user can select."),
18026
- idempotency_key: z5.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.")
18570
+ idempotency_key: z6.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.")
18027
18571
  },
18028
18572
  async handler(input) {
18029
18573
  return askUserQuestion(ctx, input);
@@ -18036,6 +18580,7 @@ function createAskUserRuntime(host) {
18036
18580
  reconcilePendingGates,
18037
18581
  hasPendingQuestion,
18038
18582
  answerPendingQuestion,
18583
+ answerOpenQuestionWithText,
18039
18584
  cancelPendingQuestions,
18040
18585
  createToolDefinition
18041
18586
  };
@@ -18295,7 +18840,7 @@ var init_vault_request_gates = __esm(async () => {
18295
18840
 
18296
18841
  // ../../packages/core/src/agents/mcp-tools/request-vault.ts
18297
18842
  import { createHash as createHash12, randomUUID as randomUUID17 } from "crypto";
18298
- import { z as z6 } from "zod";
18843
+ import { z as z7 } from "zod";
18299
18844
  function requestBodyHash(key, description) {
18300
18845
  return createHash12("sha256").update(JSON.stringify({ key, description })).digest("hex");
18301
18846
  }
@@ -18562,10 +19107,10 @@ function createRequestVaultRuntime(host) {
18562
19107
  name: "request_vault_secret",
18563
19108
  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.",
18564
19109
  schema: {
18565
- key: z6.string().describe("Vault key name, e.g. STRIPE_API_KEY. Letters/digits/underscores, must start with a letter."),
18566
- description: z6.string().max(MAX_DESCRIPTION_CHARS).describe("One sentence telling the user what value to paste and where it's from."),
18567
- overwrite: z6.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."),
18568
- idempotency_key: z6.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.")
19110
+ key: z7.string().describe("Vault key name, e.g. STRIPE_API_KEY. Letters/digits/underscores, must start with a letter."),
19111
+ description: z7.string().max(MAX_DESCRIPTION_CHARS).describe("One sentence telling the user what value to paste and where it's from."),
19112
+ overwrite: z7.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."),
19113
+ idempotency_key: z7.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.")
18569
19114
  },
18570
19115
  async handler(input) {
18571
19116
  return requestVaultSecret(ctx, input);
@@ -18602,7 +19147,7 @@ function createRequestVaultRuntime(host) {
18602
19147
  name: "delete_vault_secret",
18603
19148
  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.",
18604
19149
  schema: {
18605
- key: z6.string().describe("Vault key name to delete, e.g. STRIPE_API_KEY.")
19150
+ key: z7.string().describe("Vault key name to delete, e.g. STRIPE_API_KEY.")
18606
19151
  },
18607
19152
  async handler(input) {
18608
19153
  return deleteVaultSecret(ctx, input);
@@ -18908,8 +19453,8 @@ var init_visual_html = __esm(() => {
18908
19453
  });
18909
19454
 
18910
19455
  // ../../packages/core/src/runtime/visuals.ts
18911
- import { realpathSync as realpathSync6 } from "fs";
18912
- import { isAbsolute as isAbsolute6, resolve as resolve17 } from "path";
19456
+ import { realpathSync as realpathSync7 } from "fs";
19457
+ import { isAbsolute as isAbsolute7, resolve as resolve17 } from "path";
18913
19458
  function activeVisualHtmlForPrompt(html) {
18914
19459
  if (html.length <= ACTIVE_VISUAL_PROMPT_MAX_CHARS) {
18915
19460
  return { html, omittedChars: 0 };
@@ -18958,8 +19503,8 @@ function topicAllowsVisualFileId(topicId, fileId) {
18958
19503
  }
18959
19504
  function isPathInside(baseDir, filePath) {
18960
19505
  try {
18961
- const realBase = realpathSync6(resolve17(baseDir));
18962
- const real = realpathSync6(resolve17(filePath));
19506
+ const realBase = realpathSync7(resolve17(baseDir));
19507
+ const real = realpathSync7(resolve17(filePath));
18963
19508
  return isInsideDir(real, realBase);
18964
19509
  } catch {
18965
19510
  return false;
@@ -19014,10 +19559,10 @@ function locateVisualMediaInput(topicId, input) {
19014
19559
  }
19015
19560
  const rawPath = input.file_path.trim();
19016
19561
  const cwd = workspaceCwdFor(topicId);
19017
- const candidate = isAbsolute6(rawPath) ? rawPath : resolve17(cwd, rawPath);
19562
+ const candidate = isAbsolute7(rawPath) ? rawPath : resolve17(cwd, rawPath);
19018
19563
  let realCandidate;
19019
19564
  try {
19020
- realCandidate = realpathSync6(candidate);
19565
+ realCandidate = realpathSync7(candidate);
19021
19566
  } catch {
19022
19567
  return { error: `file not found: ${rawPath}` };
19023
19568
  }
@@ -19070,8 +19615,8 @@ var init_visuals = __esm(async () => {
19070
19615
 
19071
19616
  // ../../packages/core/src/runtime/turn-event-stream.ts
19072
19617
  import { randomUUID as randomUUID18 } from "crypto";
19073
- import { realpathSync as realpathSync7, statSync as statSync10 } from "fs";
19074
- import { isAbsolute as isAbsolute7, resolve as resolve18 } from "path";
19618
+ import { realpathSync as realpathSync8, statSync as statSync11 } from "fs";
19619
+ import { isAbsolute as isAbsolute8, resolve as resolve18 } from "path";
19075
19620
  function sessionEventMatchesCurrentExecution(topicId, queryId, agent, model) {
19076
19621
  if (getRoomQuery(topicId)?.queryId !== queryId)
19077
19622
  return false;
@@ -19496,15 +20041,15 @@ ${JSON.stringify(event.input ?? {})}`);
19496
20041
  case "file":
19497
20042
  if (!silent && peerBridge) {
19498
20043
  const cwd = workspaceCwdFor(topicId);
19499
- const path = isAbsolute7(event.path) ? event.path : resolve18(cwd, event.path);
20044
+ const path = isAbsolute8(event.path) ? event.path : resolve18(cwd, event.path);
19500
20045
  if (!isPathInside(cwd, path)) {
19501
20046
  logger.warn({ topicId, path }, "peer output file is outside the topic workspace");
19502
20047
  break;
19503
20048
  }
19504
20049
  let safePath;
19505
20050
  try {
19506
- safePath = realpathSync7(path);
19507
- if (!statSync10(safePath).isFile()) {
20051
+ safePath = realpathSync8(path);
20052
+ if (!statSync11(safePath).isFile()) {
19508
20053
  logger.warn({ topicId, path }, "peer output path is not a regular file");
19509
20054
  break;
19510
20055
  }
@@ -19833,16 +20378,16 @@ var init_turn_session = __esm(async () => {
19833
20378
  });
19834
20379
 
19835
20380
  // ../../packages/core/src/storage/app-settings.ts
19836
- import { existsSync as existsSync23, mkdirSync as mkdirSync20, readFileSync as readFileSync20, writeFileSync as writeFileSync18 } from "fs";
19837
- import { dirname as dirname18, join as join33 } from "path";
20381
+ import { existsSync as existsSync24, mkdirSync as mkdirSync20, readFileSync as readFileSync21, writeFileSync as writeFileSync18 } from "fs";
20382
+ import { dirname as dirname18, join as join34 } from "path";
19838
20383
  function settingsFile() {
19839
- return join33(resolveStorageDataDir(), "otium-settings.json");
20384
+ return join34(resolveStorageDataDir(), "otium-settings.json");
19840
20385
  }
19841
20386
  function getGlobalAiName() {
19842
20387
  const path = settingsFile();
19843
20388
  try {
19844
- if (existsSync23(path)) {
19845
- const data = JSON.parse(readFileSync20(path, "utf8"));
20389
+ if (existsSync24(path)) {
20390
+ const data = JSON.parse(readFileSync21(path, "utf8"));
19846
20391
  if (typeof data.aiName === "string" && data.aiName.trim()) {
19847
20392
  return data.aiName.trim();
19848
20393
  }
@@ -19855,10 +20400,154 @@ var init_app_settings = __esm(async () => {
19855
20400
  await init_storage_host();
19856
20401
  });
19857
20402
 
20403
+ // ../../packages/core/src/topics/plugin-server-instructions.ts
20404
+ import { Client as Client2 } from "@modelcontextprotocol/sdk/client/index.js";
20405
+ import { SSEClientTransport as SSEClientTransport2 } from "@modelcontextprotocol/sdk/client/sse.js";
20406
+ import { StreamableHTTPClientTransport as StreamableHTTPClientTransport2 } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
20407
+ function cacheKey(server, spec) {
20408
+ const headers = Object.entries(spec.headers ?? {}).map(([name, value]) => [name.toLowerCase(), value]).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
20409
+ return JSON.stringify([server, spec.type, spec.url, headers]);
20410
+ }
20411
+ function transportFor(spec, signal) {
20412
+ const url = new URL(spec.url);
20413
+ const requestInit = spec.headers ? { headers: spec.headers } : undefined;
20414
+ const noRedirect = (input, init) => fetch(input, {
20415
+ ...init,
20416
+ redirect: "error",
20417
+ signal: init?.signal ? AbortSignal.any([init.signal, signal]) : signal
20418
+ });
20419
+ return spec.type === "sse" ? new SSEClientTransport2(url, { requestInit, fetch: noRedirect }) : new StreamableHTTPClientTransport2(url, { requestInit, fetch: noRedirect });
20420
+ }
20421
+ async function readInstructions(spec, timeoutMs, stop) {
20422
+ const ended = new AbortController;
20423
+ const timer = setTimeout(() => ended.abort(new Error(`no answer in ${timeoutMs} ms`)), timeoutMs);
20424
+ timer.unref?.();
20425
+ const onStop = () => ended.abort(new Error("the turn was stopped"));
20426
+ if (stop?.aborted)
20427
+ onStop();
20428
+ else
20429
+ stop?.addEventListener("abort", onStop, { once: true });
20430
+ const client = new Client2({ name: "negotium-plugin-instructions", version: "1.0.0" });
20431
+ const transport = transportFor(spec, ended.signal);
20432
+ try {
20433
+ return await Promise.race([
20434
+ client.connect(transport).then(() => client.getInstructions() ?? ""),
20435
+ new Promise((_, reject) => {
20436
+ if (ended.signal.aborted)
20437
+ reject(ended.signal.reason);
20438
+ ended.signal.addEventListener("abort", () => reject(ended.signal.reason), { once: true });
20439
+ })
20440
+ ]);
20441
+ } finally {
20442
+ clearTimeout(timer);
20443
+ stop?.removeEventListener("abort", onStop);
20444
+ const ending = !ended.signal.aborted && transport instanceof StreamableHTTPClientTransport2 ? transport.terminateSession() : Promise.resolve();
20445
+ ending.catch(() => {}).finally(() => client.close().catch(() => {}));
20446
+ }
20447
+ }
20448
+ async function fetchMcpServerInstructions(servers, options = {}) {
20449
+ const timeoutMs = options.timeoutMs ?? SERVER_INSTRUCTIONS_TIMEOUT_MS;
20450
+ const entries = Object.entries(servers);
20451
+ const results = await Promise.allSettled(entries.map(async ([server, spec]) => {
20452
+ const key = cacheKey(server, spec);
20453
+ const hit = cache.get(key);
20454
+ if (hit && hit.expires > Date.now())
20455
+ return hit.text;
20456
+ const text = await readInstructions(spec, timeoutMs, options.signal);
20457
+ cache.set(key, { text, expires: Date.now() + SERVER_INSTRUCTIONS_TTL_MS });
20458
+ return text;
20459
+ }));
20460
+ const fetched = { instructions: [], problems: [] };
20461
+ results.forEach((result, index) => {
20462
+ const server = entries[index][0];
20463
+ if (result.status === "rejected") {
20464
+ const reason = result.reason instanceof Error ? result.reason.message : String(result.reason);
20465
+ fetched.problems.push(`plugin server "${server}": instructions not read (${reason})`);
20466
+ } else if (result.value.trim()) {
20467
+ fetched.instructions.push({ server, text: result.value });
20468
+ }
20469
+ });
20470
+ return fetched;
20471
+ }
20472
+ function cutToBytes(text, maxBytes) {
20473
+ const encoded = encoder.encode(text);
20474
+ let end = Math.max(0, maxBytes);
20475
+ while (end > 0 && (encoded[end] & 192) === 128)
20476
+ end--;
20477
+ return new TextDecoder().decode(encoded.subarray(0, end));
20478
+ }
20479
+ function renderMcpServerInstructions(instructions) {
20480
+ const head = [
20481
+ "## MCP Server Instructions",
20482
+ "",
20483
+ "The following MCP servers have provided instructions for how to use their tools and resources:"
20484
+ ].join(`
20485
+ `);
20486
+ const blocks = [];
20487
+ const problems = [];
20488
+ let left = INSTRUCTIONS_SECTION_MAX_BYTES - byteLength(head);
20489
+ for (const { server, text: sent } of instructions) {
20490
+ const heading = `
20491
+
20492
+ ### ${server}
20493
+
20494
+ `;
20495
+ const text = sent.trim();
20496
+ const size = byteLength(text);
20497
+ const room = Math.min(SERVER_INSTRUCTIONS_MAX_BYTES, left - byteLength(heading));
20498
+ if (size <= room) {
20499
+ blocks.push(`${heading}${text}`);
20500
+ left -= byteLength(heading) + size;
20501
+ continue;
20502
+ }
20503
+ const marker = cutMarker(server, size);
20504
+ if (room <= byteLength(marker)) {
20505
+ problems.push(`plugin server "${server}": instructions left out (the section is full)`);
20506
+ continue;
20507
+ }
20508
+ const shown = `${cutToBytes(text, room - byteLength(marker))}${marker}`;
20509
+ blocks.push(`${heading}${shown}`);
20510
+ left -= byteLength(heading) + byteLength(shown);
20511
+ problems.push(`plugin server "${server}": instructions cut from ${size} bytes`);
20512
+ }
20513
+ return { section: blocks.length > 0 ? `${head}${blocks.join("")}` : "", problems };
20514
+ }
20515
+ 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) => `
20516
+
20517
+ [negotium cut the instructions of "${server}" here; the server sent ${sent} bytes]`;
20518
+ var init_plugin_server_instructions = __esm(() => {
20519
+ SERVER_INSTRUCTIONS_TTL_MS = 5 * 60 * 1000;
20520
+ SERVER_INSTRUCTIONS_MAX_BYTES = 8 * 1024;
20521
+ INSTRUCTIONS_SECTION_MAX_BYTES = 32 * 1024;
20522
+ cache = new Map;
20523
+ encoder = new TextEncoder;
20524
+ });
20525
+
20526
+ // ../../packages/core/src/topics/plugin-turn.ts
20527
+ function resolveTopicPluginTurn(topic, hostServerNames) {
20528
+ if (!topic.plugins?.length)
20529
+ return NONE;
20530
+ const { plugins, problems: loadProblems } = loadTopicPlugins(topic.plugins);
20531
+ const servers = Object.assign({}, ...plugins.map((plugin) => plugin.mcpServers));
20532
+ const refusal = pluginMcpRefusal(topic, Object.keys(servers), hostServerNames);
20533
+ return {
20534
+ plugins,
20535
+ mcpServers: refusal ? {} : servers,
20536
+ loadProblems,
20537
+ serverProblems: refusal ? [refusal] : []
20538
+ };
20539
+ }
20540
+ var NONE;
20541
+ var init_plugin_turn = __esm(async () => {
20542
+ init_plugins();
20543
+ await init_mcp_config();
20544
+ NONE = { plugins: [], mcpServers: {}, loadProblems: [], serverProblems: [] };
20545
+ });
20546
+
19858
20547
  // ../../packages/core/src/runtime/turn-runner.ts
19859
20548
  import { randomUUID as randomUUID19 } from "crypto";
19860
- import { existsSync as existsSync24, mkdirSync as mkdirSync21, readdirSync as readdirSync7, statSync as statSync11 } from "fs";
19861
- import { join as join34 } from "path";
20549
+ import { existsSync as existsSync25, mkdirSync as mkdirSync21, readdirSync as readdirSync8, statSync as statSync12 } from "fs";
20550
+ import { join as join35 } from "path";
19862
20551
  function withDefaultPlaywright(configuredMcp, isManager) {
19863
20552
  if (isManager)
19864
20553
  return configuredMcp;
@@ -19922,19 +20611,19 @@ function appendAskReplyMessage(topicId, text, sourceLabel, body, kind, agentType
19922
20611
  return message;
19923
20612
  }
19924
20613
  function resolveWikiMirrorPath(directory, preferredFilename, matchesLegacyId, matchesTitle, preferExact = true) {
19925
- const preferred = join34(directory, preferredFilename);
19926
- if (preferExact && existsSync24(preferred))
20614
+ const preferred = join35(directory, preferredFilename);
20615
+ if (preferExact && existsSync25(preferred))
19927
20616
  return preferred;
19928
20617
  let newestLegacyId = null;
19929
20618
  let newestTitle = null;
19930
20619
  try {
19931
- for (const filename of readdirSync7(directory)) {
20620
+ for (const filename of readdirSync8(directory)) {
19932
20621
  const titleMatch = matchesTitle(filename);
19933
20622
  const legacyIdMatch = !titleMatch && matchesLegacyId(filename);
19934
20623
  if (!titleMatch && !legacyIdMatch)
19935
20624
  continue;
19936
- const path = join34(directory, filename);
19937
- const mtimeMs = statSync11(path).mtimeMs;
20625
+ const path = join35(directory, filename);
20626
+ const mtimeMs = statSync12(path).mtimeMs;
19938
20627
  if (titleMatch) {
19939
20628
  if (!newestTitle || mtimeMs > newestTitle.mtimeMs) {
19940
20629
  newestTitle = { path, mtimeMs };
@@ -19947,10 +20636,10 @@ function resolveWikiMirrorPath(directory, preferredFilename, matchesLegacyId, ma
19947
20636
  return newestTitle?.path ?? newestLegacyId?.path ?? preferred;
19948
20637
  }
19949
20638
  function resolveWikiMemoryMirror(wikiDir, topicId, topicTitle) {
19950
- const briefFile = resolveWikiMirrorPath(join34(wikiDir, "topic"), `${wikiBriefStorageKey(topicTitle, topicId)}.md`, (filename) => isTopicBriefFile(filename, topicId), (filename) => isTopicBriefFile(filename, topicId, topicTitle));
19951
- const hasBriefFile = existsSync24(briefFile) && statSync11(briefFile).isFile();
19952
- const latestSummaryCandidate = resolveWikiMirrorPath(join34(wikiDir, "summaries"), `__missing__-${wikiSummaryFilename("0000-00-00", topicTitle, topicId)}`, (filename) => isTopicSummaryFile(filename, topicId), (filename) => isTopicSummaryFile(filename, topicId, topicTitle), false);
19953
- const latestSummaryFile = existsSync24(latestSummaryCandidate) && statSync11(latestSummaryCandidate).isFile() ? latestSummaryCandidate : null;
20639
+ const briefFile = resolveWikiMirrorPath(join35(wikiDir, "topic"), `${wikiBriefStorageKey(topicTitle, topicId)}.md`, (filename) => isTopicBriefFile(filename, topicId), (filename) => isTopicBriefFile(filename, topicId, topicTitle));
20640
+ const hasBriefFile = existsSync25(briefFile) && statSync12(briefFile).isFile();
20641
+ const latestSummaryCandidate = resolveWikiMirrorPath(join35(wikiDir, "summaries"), `__missing__-${wikiSummaryFilename("0000-00-00", topicTitle, topicId)}`, (filename) => isTopicSummaryFile(filename, topicId), (filename) => isTopicSummaryFile(filename, topicId, topicTitle), false);
20642
+ const latestSummaryFile = existsSync25(latestSummaryCandidate) && statSync12(latestSummaryCandidate).isFile() ? latestSummaryCandidate : null;
19954
20643
  return { briefFile, hasBriefFile, latestSummaryFile };
19955
20644
  }
19956
20645
  async function streamAgentEvents(topicId, topicTitle, queryId, events, control, agentType, model, effort, userId, retryableSessionExpired = true, onSessionId, execution) {
@@ -20185,6 +20874,23 @@ function resolveTurnHostMcpServers(topic, sessionType) {
20185
20874
  return;
20186
20875
  return getTopicHostMcpGrant(topic.id) ?? undefined;
20187
20876
  }
20877
+ function resolveTurnPlugins(topic, sessionType, hostMcpServers) {
20878
+ const ownScope = topic.kind === "manager" ? "manager" : "forum";
20879
+ const stored = getTopic(topic.id);
20880
+ if (!stored?.plugins?.length || (sessionType ?? ownScope) !== ownScope) {
20881
+ return { plugins: [], pluginMcpServers: {}, hostMcpServers };
20882
+ }
20883
+ const turn = resolveTopicPluginTurn(stored, Object.keys(hostMcpServers ?? {}));
20884
+ const problems = [...turn.loadProblems, ...turn.serverProblems];
20885
+ if (problems.length > 0) {
20886
+ logger.warn({ topicId: topic.id, problems }, "ai: topic plugins partly or wholly left out of the turn");
20887
+ }
20888
+ return {
20889
+ plugins: turn.plugins,
20890
+ pluginMcpServers: turn.mcpServers,
20891
+ hostMcpServers: Object.keys(turn.mcpServers).length > 0 ? { ...hostMcpServers, ...turn.mcpServers } : hostMcpServers
20892
+ };
20893
+ }
20188
20894
  function sameTurnActor(runningActorUserId, incomingActorUserId) {
20189
20895
  return (runningActorUserId ?? null) === (incomingActorUserId ?? null);
20190
20896
  }
@@ -20342,7 +21048,7 @@ function startAiTurn(params) {
20342
21048
  const sessionName = params.sessionName ?? topic.title;
20343
21049
  const sessionType = params.sessionType;
20344
21050
  const { visualTools, fileDeliveryTools } = resolveTurnToolCapabilities(topicId, params);
20345
- const hostMcpServers = resolveTurnHostMcpServers(topic, sessionType);
21051
+ const { plugins, pluginMcpServers, hostMcpServers } = resolveTurnPlugins(topic, sessionType, resolveTurnHostMcpServers(topic, sessionType));
20346
21052
  const onSessionId = params.onSessionId;
20347
21053
  const onSessionReset = params.onSessionReset;
20348
21054
  const bridgeSessionFromHistory = params.bridgeSessionFromHistory === true;
@@ -20723,7 +21429,8 @@ function startAiTurn(params) {
20723
21429
  subagentParentTitle: topicRecord?.isSubagent && topicRecord.parentTopicId ? getTopic(topicRecord.parentTopicId)?.title : undefined,
20724
21430
  subagentReportMode: topicRecord?.isSubagent ? subagentReportMode(topicId) : undefined,
20725
21431
  visualTools,
20726
- fileDeliveryTools
21432
+ fileDeliveryTools,
21433
+ plugins
20727
21434
  };
20728
21435
  const isManager = topicRecord?.kind === "manager";
20729
21436
  const isMentionOnlyChannel = topic.aiMode === "mention" && !isManager;
@@ -20869,6 +21576,21 @@ function startAiTurn(params) {
20869
21576
  if (consumePlaywrightUnavailable(userId, topic.title)) {
20870
21577
  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>");
20871
21578
  }
21579
+ if (Object.keys(pluginMcpServers).length > 0) {
21580
+ const fetched = await fetchMcpServerInstructions(pluginMcpServers, {
21581
+ signal: abortController.signal
21582
+ });
21583
+ if (abortController.signal.aborted)
21584
+ return;
21585
+ const { section, problems } = renderMcpServerInstructions(fetched.instructions);
21586
+ if (fetched.problems.length + problems.length > 0) {
21587
+ logger.warn({ topicId, problems: [...fetched.problems, ...problems] }, "ai: plugin server instructions cut or left out of the turn");
21588
+ }
21589
+ if (section)
21590
+ systemPrompt += `
21591
+
21592
+ ${section}`;
21593
+ }
20872
21594
  const reminderQuery = buildTurnReminderQuery(agentKind, agentPrompt, turnReminders);
20873
21595
  try {
20874
21596
  yield* runAgent({
@@ -21231,6 +21953,7 @@ var init_turn_runner = __esm(async () => {
21231
21953
  init_remote_session_grant();
21232
21954
  init_user_turn_envelope();
21233
21955
  init_wiki_summary_names();
21956
+ init_plugin_server_instructions();
21234
21957
  init_user_turn_envelope();
21235
21958
  await __promiseAll([
21236
21959
  init_fork(),
@@ -21261,7 +21984,8 @@ var init_turn_runner = __esm(async () => {
21261
21984
  init_topic_host_mcp_grants(),
21262
21985
  init_topic_tool_capabilities(),
21263
21986
  init_wiki(),
21264
- init_derive()
21987
+ init_derive(),
21988
+ init_plugin_turn()
21265
21989
  ]);
21266
21990
  init_model_catalog();
21267
21991
  init_attachments();
@@ -21283,9 +22007,9 @@ var init_turn_runner = __esm(async () => {
21283
22007
 
21284
22008
  // ../../packages/core/src/agents/auth-check.ts
21285
22009
  import { execFileSync as execFileSync7 } from "child_process";
21286
- import { existsSync as existsSync25 } from "fs";
22010
+ import { existsSync as existsSync26 } from "fs";
21287
22011
  import { homedir as homedir9, platform } from "os";
21288
- import { join as join35 } from "path";
22012
+ import { join as join36 } from "path";
21289
22013
  function hasMaestroCredential(host, key, userId) {
21290
22014
  if (userId && host.getVaultValue(userId, key)?.trim())
21291
22015
  return true;
@@ -21305,7 +22029,7 @@ function checkAgentAuth(agent, host = defaultAgentAuthHost, userId) {
21305
22029
  case "claude": {
21306
22030
  if (host.environment.ANTHROPIC_API_KEY)
21307
22031
  return { ok: true };
21308
- const path = join35(host.homeDirectory(), ".claude", ".credentials.json");
22032
+ const path = join36(host.homeDirectory(), ".claude", ".credentials.json");
21309
22033
  if (host.operatingSystem() === "darwin") {
21310
22034
  if (host.hasMacOsCredential("Claude Code-credentials") || host.exists(path)) {
21311
22035
  return { ok: true };
@@ -21362,7 +22086,7 @@ var init_auth_check = __esm(async () => {
21362
22086
  await init_vault();
21363
22087
  defaultAgentAuthHost = {
21364
22088
  codexAuthFilePath,
21365
- exists: existsSync25,
22089
+ exists: existsSync26,
21366
22090
  environment: process.env,
21367
22091
  homeDirectory: homedir9,
21368
22092
  operatingSystem: platform,
@@ -21379,7 +22103,7 @@ var init_auth_check = __esm(async () => {
21379
22103
  });
21380
22104
 
21381
22105
  // ../../packages/core/src/agents/mcp-tools/spawn-subagent.ts
21382
- import { z as z7 } from "zod";
22106
+ import { z as z8 } from "zod";
21383
22107
  function activeQueryUserId(topic) {
21384
22108
  return topic?.participants.find((participant) => hasActiveQuery(participant.userId, topic.id))?.userId;
21385
22109
  }
@@ -21946,7 +22670,7 @@ ${card.task}${reportInstruction}`;
21946
22670
  name: "start_subagent",
21947
22671
  description: "Start a prepared descendant subagent task.",
21948
22672
  schema: {
21949
- topic_id: z7.string().describe("Prepared subagent room id.")
22673
+ topic_id: z8.string().describe("Prepared subagent room id.")
21950
22674
  },
21951
22675
  async handler(input) {
21952
22676
  const result = ownedSubagentTree(ctx);
@@ -21966,7 +22690,7 @@ ${card.task}${reportInstruction}`;
21966
22690
  name: "delete_subagent",
21967
22691
  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.",
21968
22692
  schema: {
21969
- topic_id: z7.string().describe("Exact subagent room id returned by list_subagents; names are not accepted.")
22693
+ topic_id: z8.string().describe("Exact subagent room id returned by list_subagents; names are not accepted.")
21970
22694
  },
21971
22695
  async handler(input) {
21972
22696
  const result = ownedSubagentTree(ctx);
@@ -21990,8 +22714,8 @@ ${card.task}${reportInstruction}`;
21990
22714
  name: "grant_subagent_tell",
21991
22715
  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.",
21992
22716
  schema: {
21993
- subagent_topic_id: z7.string().describe("Source descendant subagent topic id."),
21994
- target_topic_id: z7.string().describe("Target topic id: this manager room or another descendant in its tree.")
22717
+ subagent_topic_id: z8.string().describe("Source descendant subagent topic id."),
22718
+ target_topic_id: z8.string().describe("Target topic id: this manager room or another descendant in its tree.")
21995
22719
  },
21996
22720
  async handler(input) {
21997
22721
  const result = ownedSubagentTree(ctx);
@@ -22016,8 +22740,8 @@ ${card.task}${reportInstruction}`;
22016
22740
  name: "revoke_subagent_tell",
22017
22741
  description: "Remove an extra tell_session connection previously granted to a descendant subagent.",
22018
22742
  schema: {
22019
- subagent_topic_id: z7.string().describe("Source descendant subagent topic id."),
22020
- target_topic_id: z7.string().describe("Granted target topic id.")
22743
+ subagent_topic_id: z8.string().describe("Source descendant subagent topic id."),
22744
+ target_topic_id: z8.string().describe("Granted target topic id.")
22021
22745
  },
22022
22746
  async handler(input) {
22023
22747
  const result = ownedSubagentTree(ctx);
@@ -22039,18 +22763,18 @@ ${card.task}${reportInstruction}`;
22039
22763
  }
22040
22764
  function createSpawnSubagentToolDefinition(ctx, options = {}) {
22041
22765
  const executionOverrideSchema = options.executionOverrides === false ? {} : {
22042
- agent: z7.enum(["claude", "codex", "maestro"]).optional().describe("Agent backend override. Defaults to this room's agent."),
22043
- model: z7.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.`)
22766
+ agent: z8.enum(["claude", "codex", "maestro"]).optional().describe("Agent backend override. Defaults to this room's agent."),
22767
+ model: z8.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.`)
22044
22768
  };
22045
22769
  return {
22046
22770
  name: "spawn_subagent",
22047
22771
  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.",
22048
22772
  schema: {
22049
- task: z7.string().describe("Self-contained task brief. The worker has topic memory but no parent conversation history, so include all task-specific context."),
22050
- name: z7.string().optional().describe("Short name for the subagent room. Auto-generated when omitted."),
22773
+ task: z8.string().describe("Self-contained task brief. The worker has topic memory but no parent conversation history, so include all task-specific context."),
22774
+ name: z8.string().optional().describe("Short name for the subagent room. Auto-generated when omitted."),
22051
22775
  ...executionOverrideSchema,
22052
- memory_topic: z7.string().optional().describe("Optional knowledge source: an accessible topic id/title or topic/*.md brief. Defaults to the parent room's effective topic brief."),
22053
- report_mode: z7.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.")
22776
+ memory_topic: z8.string().optional().describe("Optional knowledge source: an accessible topic id/title or topic/*.md brief. Defaults to the parent room's effective topic brief."),
22777
+ report_mode: z8.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.")
22054
22778
  },
22055
22779
  async handler(input) {
22056
22780
  return createSubagent(ctx, input, true);
@@ -22062,14 +22786,14 @@ ${card.task}${reportInstruction}`;
22062
22786
  name: "create_subagent",
22063
22787
  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.",
22064
22788
  schema: {
22065
- task: z7.string().describe("Self-contained task brief for the subagent."),
22066
- name: z7.string().optional().describe("Short room name. Auto-generated when omitted."),
22789
+ task: z8.string().describe("Self-contained task brief for the subagent."),
22790
+ name: z8.string().optional().describe("Short room name. Auto-generated when omitted."),
22067
22791
  ...options.executionOverrides === false ? {} : {
22068
- agent: z7.enum(["claude", "codex", "maestro"]).optional(),
22069
- model: z7.string().optional()
22792
+ agent: z8.enum(["claude", "codex", "maestro"]).optional(),
22793
+ model: z8.string().optional()
22070
22794
  },
22071
- memory_topic: z7.string().optional().describe("Optional accessible topic id/title or topic/*.md brief to use as this worker's knowledge source. Defaults to the parent."),
22072
- report_mode: z7.enum(["auto", "tell", "status-only"]).optional()
22795
+ memory_topic: z8.string().optional().describe("Optional accessible topic id/title or topic/*.md brief to use as this worker's knowledge source. Defaults to the parent."),
22796
+ report_mode: z8.enum(["auto", "tell", "status-only"]).optional()
22073
22797
  },
22074
22798
  async handler(input) {
22075
22799
  return createSubagent(ctx, input, false);
@@ -23685,6 +24409,12 @@ ${fresh.join(`
23685
24409
  `;
23686
24410
  }
23687
24411
  const skillDir = resolve2(runtime().skillsDir, name);
24412
+ if (dirname2(skillDir) !== resolve2(runtime().skillsDir) || name !== basename(skillDir)) {
24413
+ return {
24414
+ content: [{ type: "text", text: "Skill name must be a single folder name." }],
24415
+ isError: true
24416
+ };
24417
+ }
23688
24418
  ensureDir(skillDir);
23689
24419
  const skillPath = resolve2(skillDir, "skill.md");
23690
24420
  let finalContent = content;
@@ -25012,7 +25742,7 @@ ${renderDecisionList(decisions)}`);
25012
25742
  }
25013
25743
  // ../../packages/core/src/mcp/factories/session-comm.ts
25014
25744
  import { McpServer as McpServer4 } from "@modelcontextprotocol/sdk/server/mcp.js";
25015
- import { z as z8 } from "zod";
25745
+ import { z as z9 } from "zod";
25016
25746
 
25017
25747
  // ../../packages/core/src/mcp/session-comm/history-tools.ts
25018
25748
  import { z as z4 } from "zod";
@@ -25102,32 +25832,32 @@ function createSessionCommMcpServer(context, host, options = {}) {
25102
25832
  const subagentIdentity = resolveSubagentTellIdentity(context.currentTopicId, context.subagentParentTopicId);
25103
25833
  server.tool("list_sessions", "List available sessions and remote peer sessions for inter-session communication.", {}, async () => host.listSessions(context));
25104
25834
  server.tool("configure_mcp", `Configure optional MCP servers for the current topic. Required: ${required}. Optional: ${optional}.`, {
25105
- enabled: z8.array(z8.string()).nullable().optional()
25835
+ enabled: z9.array(z9.string()).nullable().optional()
25106
25836
  }, async ({ enabled }) => host.configureMcp(context, enabled));
25107
25837
  server.tool("get_mcp_config", "Get the current topic MCP configuration.", {}, async () => host.getMcpConfig(context));
25108
25838
  if (host.getBrowserProfile) {
25109
25839
  server.tool("get_browser_profile", "Get this topic's browser profile and the profiles owned by the same user.", {}, async () => host.getBrowserProfile(context));
25110
25840
  }
25111
25841
  if (host.setBrowserProfile) {
25112
- server.tool("set_browser_profile", "Assign this topic to a named shared browser profile. Takes effect next turn.", { profile: z8.string() }, async ({ profile }) => host.setBrowserProfile(context, profile));
25842
+ server.tool("set_browser_profile", "Assign this topic to a named shared browser profile. Takes effect next turn.", { profile: z9.string() }, async ({ profile }) => host.setBrowserProfile(context, profile));
25113
25843
  }
25114
25844
  if (host.deleteBrowserProfile) {
25115
- server.tool("delete_browser_profile", "Delete an unused named browser profile and its on-disk data. The default or an assigned profile cannot be deleted.", { profile: z8.string() }, async ({ profile }) => host.deleteBrowserProfile(context, profile));
25845
+ server.tool("delete_browser_profile", "Delete an unused named browser profile and its on-disk data. The default or an assigned profile cannot be deleted.", { profile: z9.string() }, async ({ profile }) => host.deleteBrowserProfile(context, profile));
25116
25846
  }
25117
25847
  server.tool("peek_session", "Inspect running and idle sessions, including pending ask_session calls.", {}, async () => host.peekSession(context));
25118
- server.tool("set_description", "Set the current session description used as a routing hint.", { description: z8.string() }, async ({ description }) => host.setDescription(context, description));
25848
+ server.tool("set_description", "Set the current session description used as a routing hint.", { description: z9.string() }, async ({ description }) => host.setDescription(context, description));
25119
25849
  if (host.sessionHistoryOf) {
25120
25850
  registerSessionHistoryOfTools(server, host.sessionHistoryOf(context));
25121
25851
  }
25122
25852
  if (!context.replyOnly) {
25123
25853
  if (!subagentIdentity.restricted) {
25124
- server.tool("ask_session", "Ask another local or remote session a question and wait for its answer. To hand over long context, cite an entry range or sessionId of your own history (list_session_boundaries) instead of pasting it \u2014 the target can read it with read_session_history_of.", { to: z8.string(), message: z8.string() }, async (input) => host.askSession(context, input));
25125
- server.tool("ask_cron", "Ask this topic's shared Cron session a question. The answer is injected asynchronously into the current conversation.", { message: z8.string() }, async ({ message }) => host.askCron(context, message));
25854
+ server.tool("ask_session", "Ask another local or remote session a question and wait for its answer. To hand over long context, cite an entry range or sessionId of your own history (list_session_boundaries) instead of pasting it \u2014 the target can read it with read_session_history_of.", { to: z9.string(), message: z9.string() }, async (input) => host.askSession(context, input));
25855
+ server.tool("ask_cron", "Ask this topic's shared Cron session a question. The answer is injected asynchronously into the current conversation.", { message: z9.string() }, async ({ message }) => host.askCron(context, message));
25126
25856
  }
25127
25857
  if (!subagentIdentity.restricted) {
25128
- server.tool("abort_session", "Abort the active query in another session.", { to: z8.string() }, async ({ to }) => host.abortSession(context, to));
25858
+ server.tool("abort_session", "Abort the active query in another session.", { to: z9.string() }, async ({ to }) => host.abortSession(context, to));
25129
25859
  }
25130
- server.tool("tell_session", "Send a one-way message to another local or remote session. To hand over long context, cite an entry range or sessionId of your own history (list_session_boundaries) instead of pasting it \u2014 the target can read it with read_session_history_of.", { to: z8.string(), message: z8.string() }, async (input) => {
25860
+ server.tool("tell_session", "Send a one-way message to another local or remote session. To hand over long context, cite an entry range or sessionId of your own history (list_session_boundaries) instead of pasting it \u2014 the target can read it with read_session_history_of.", { to: z9.string(), message: z9.string() }, async (input) => {
25131
25861
  if (subagentIdentity.restricted && !canSubagentTellTargetByName(subagentIdentity, input.to)) {
25132
25862
  return {
25133
25863
  content: [
@@ -25147,7 +25877,7 @@ function createSessionCommMcpServer(context, host, options = {}) {
25147
25877
  // ../../packages/core/src/mcp/factories/session-history.ts
25148
25878
  init_mcp_helpers();
25149
25879
  import { McpServer as McpServer5 } from "@modelcontextprotocol/sdk/server/mcp.js";
25150
- import { z as z9 } from "zod";
25880
+ import { z as z10 } from "zod";
25151
25881
 
25152
25882
  // ../../packages/core/src/mcp/session-history-reader.ts
25153
25883
  init_mcp_helpers();
@@ -25414,9 +26144,9 @@ function createSessionHistoryMcpServer(context) {
25414
26144
  "list_session_boundaries, then pass sessionId to read only that session's range instead of",
25415
26145
  "paging through the whole topic."
25416
26146
  ].join(" "), {
25417
- offset: z9.number().optional().describe("One-based entry number. Defaults to 1."),
25418
- limit: z9.number().optional().describe(`Number of entries. Defaults to ${SESSION_HISTORY_DEFAULT_LINE_LIMIT}, max ${SESSION_HISTORY_MAX_LINE_LIMIT}.`),
25419
- sessionId: z9.string().optional().describe("Restrict to one session's entry range (see list_session_boundaries).")
26147
+ offset: z10.number().optional().describe("One-based entry number. Defaults to 1."),
26148
+ limit: z10.number().optional().describe(`Number of entries. Defaults to ${SESSION_HISTORY_DEFAULT_LINE_LIMIT}, max ${SESSION_HISTORY_MAX_LINE_LIMIT}.`),
26149
+ sessionId: z10.string().optional().describe("Restrict to one session's entry range (see list_session_boundaries).")
25420
26150
  }, async (args) => requireContext() ?? reader.read(self, args));
25421
26151
  server.tool("search_session_history", [
25422
26152
  "Keyword-search the full raw conversation manifest (case-insensitive substring match)",
@@ -25426,9 +26156,9 @@ function createSessionHistoryMcpServer(context) {
25426
26156
  "topic's size, but prefer sessionId to narrow the scan when you already know which session",
25427
26157
  "from list_session_boundaries."
25428
26158
  ].join(" "), {
25429
- query: z9.string().min(1).describe("Case-insensitive substring to search for."),
25430
- sessionId: z9.string().optional().describe("Restrict the scan to one session's range."),
25431
- limit: z9.number().optional().describe(`Max matches to return. Defaults to ${SESSION_HISTORY_DEFAULT_SEARCH_LIMIT}, max ${SESSION_HISTORY_MAX_SEARCH_LIMIT}.`)
26159
+ query: z10.string().min(1).describe("Case-insensitive substring to search for."),
26160
+ sessionId: z10.string().optional().describe("Restrict the scan to one session's range."),
26161
+ limit: z10.number().optional().describe(`Max matches to return. Defaults to ${SESSION_HISTORY_DEFAULT_SEARCH_LIMIT}, max ${SESSION_HISTORY_MAX_SEARCH_LIMIT}.`)
25432
26162
  }, async (args) => requireContext() ?? reader.search(self, args));
25433
26163
  return server;
25434
26164
  }
@@ -25632,7 +26362,7 @@ function createSystemHealthMcpServer(host = defaultSystemHealthMcpHost) {
25632
26362
  init_mcp_helpers();
25633
26363
  await init_tasks();
25634
26364
  import { McpServer as McpServer7 } from "@modelcontextprotocol/sdk/server/mcp.js";
25635
- import { z as z10 } from "zod";
26365
+ import { z as z11 } from "zod";
25636
26366
  var defaultTaskMcpHost = {
25637
26367
  readTasks,
25638
26368
  writeTasks
@@ -25646,13 +26376,13 @@ function createTaskMcpServer(context, host = defaultTaskMcpHost) {
25646
26376
  }
25647
26377
  return null;
25648
26378
  };
25649
- const statusEnum = z10.enum(TASK_STATUS_VALUES);
26379
+ const statusEnum = z11.enum(TASK_STATUS_VALUES);
25650
26380
  server.tool("task_create", "Add one or more tasks to this topic's shared Otium task list. Use this instead of provider-native todo/task tools.", {
25651
- tasks: z10.array(z10.object({
25652
- subject: z10.string().min(1).describe("Short imperative task description"),
25653
- active_form: z10.string().optional().describe("Label to show while the task is in progress"),
25654
- blocked_by: z10.array(z10.string()).optional().describe("Task ids blocking this task"),
25655
- owner: z10.string().optional().describe("Owner/agent label for multi-agent work")
26381
+ tasks: z11.array(z11.object({
26382
+ subject: z11.string().min(1).describe("Short imperative task description"),
26383
+ active_form: z11.string().optional().describe("Label to show while the task is in progress"),
26384
+ blocked_by: z11.array(z11.string()).optional().describe("Task ids blocking this task"),
26385
+ owner: z11.string().optional().describe("Owner/agent label for multi-agent work")
25656
26386
  })).min(1)
25657
26387
  }, async ({ tasks: inputs }) => {
25658
26388
  const guard = requireContext();
@@ -25676,13 +26406,13 @@ ${renderTaskList(tasks)}`);
25676
26406
  }
25677
26407
  });
25678
26408
  server.tool("task_update", "Update task status/content in this topic's shared Otium task list. Batch related status changes in one call.", {
25679
- updates: z10.array(z10.object({
25680
- id: z10.string().describe("Target task id"),
26409
+ updates: z11.array(z11.object({
26410
+ id: z11.string().describe("Target task id"),
25681
26411
  status: statusEnum.optional().describe("New status"),
25682
- subject: z10.string().min(1).optional().describe("Replacement task description"),
25683
- active_form: z10.string().optional().describe("Replacement in-progress label; empty string clears it"),
25684
- blocked_by: z10.array(z10.string()).optional().describe("Replacement blocker id list"),
25685
- owner: z10.string().optional().describe("Replacement owner; empty string clears it")
26412
+ subject: z11.string().min(1).optional().describe("Replacement task description"),
26413
+ active_form: z11.string().optional().describe("Replacement in-progress label; empty string clears it"),
26414
+ blocked_by: z11.array(z11.string()).optional().describe("Replacement blocker id list"),
26415
+ owner: z11.string().optional().describe("Replacement owner; empty string clears it")
25686
26416
  })).min(1)
25687
26417
  }, async ({ updates }) => {
25688
26418
  const guard = requireContext();
@@ -25716,7 +26446,7 @@ Missing ids ignored: ${missing.join(", ")}` : "";
25716
26446
  return mcpError(`task_list failed: ${errMsg(error)}`);
25717
26447
  }
25718
26448
  });
25719
- server.tool("task_get", "Read one task from this topic's shared Otium task list as JSON.", { id: z10.string().describe("Task id") }, async ({ id }) => {
26449
+ server.tool("task_get", "Read one task from this topic's shared Otium task list as JSON.", { id: z11.string().describe("Task id") }, async ({ id }) => {
25720
26450
  const guard = requireContext();
25721
26451
  if (guard)
25722
26452
  return guard;
@@ -25730,8 +26460,8 @@ Missing ids ignored: ${missing.join(", ")}` : "";
25730
26460
  }
25731
26461
  });
25732
26462
  server.tool("task_delete", "Delete tasks from this topic's shared Otium task list. Use all=true only when starting a new plan.", {
25733
- ids: z10.array(z10.string()).optional().describe("Task ids to delete"),
25734
- all: z10.boolean().optional().describe("Delete the whole list")
26463
+ ids: z11.array(z11.string()).optional().describe("Task ids to delete"),
26464
+ all: z11.boolean().optional().describe("Delete the whole list")
25735
26465
  }, async ({ ids, all }) => {
25736
26466
  const guard = requireContext();
25737
26467
  if (guard)
@@ -25754,7 +26484,7 @@ ${renderTaskList(tasks)}`);
25754
26484
  // ../../packages/core/src/mcp/factories/token-stats.ts
25755
26485
  await init_token_stats();
25756
26486
  import { McpServer as McpServer8 } from "@modelcontextprotocol/sdk/server/mcp.js";
25757
- import { z as z11 } from "zod";
26487
+ import { z as z12 } from "zod";
25758
26488
  var defaultTokenStatsMcpHost = {
25759
26489
  getStats,
25760
26490
  calcCost
@@ -25774,9 +26504,9 @@ function createTokenStatsMcpServer(context, host = defaultTokenStatsMcpHost) {
25774
26504
  "groupBy: 'session'\uC73C\uB85C \uC124\uC815\uD558\uBA74 \uC138\uC158\uBCC4 \uD1A0\uD070 \uC0AC\uC6A9\uB7C9 \uB7AD\uD0B9\uC744 \uBC18\uD658\uD569\uB2C8\uB2E4."
25775
26505
  ].join(`
25776
26506
  `), {
25777
- from: z11.string().optional().describe("\uC2DC\uC791 \uC2DC\uAC01 ISO 8601. \uC608: '2026-03-28T09:00:00Z'"),
25778
- to: z11.string().optional().describe("\uC885\uB8CC \uC2DC\uAC01 ISO 8601. \uC0DD\uB7B5 \uC2DC \uD604\uC7AC"),
25779
- groupBy: z11.enum(["hour", "session"]).optional().describe("\uC9D1\uACC4 \uAE30\uC900. \uAE30\uBCF8\uAC12: hour")
26507
+ from: z12.string().optional().describe("\uC2DC\uC791 \uC2DC\uAC01 ISO 8601. \uC608: '2026-03-28T09:00:00Z'"),
26508
+ to: z12.string().optional().describe("\uC885\uB8CC \uC2DC\uAC01 ISO 8601. \uC0DD\uB7B5 \uC2DC \uD604\uC7AC"),
26509
+ groupBy: z12.enum(["hour", "session"]).optional().describe("\uC9D1\uACC4 \uAE30\uC900. \uAE30\uBCF8\uAC12: hour")
25780
26510
  }, async ({ from, to, groupBy = "hour" }) => {
25781
26511
  const snapshot = host.getStats(context.userId, from, to);
25782
26512
  const {
@@ -25887,4 +26617,4 @@ export {
25887
26617
  protectMcpStdio
25888
26618
  };
25889
26619
 
25890
- //# debugId=6F1E51F59983617264756E2164756E21
26620
+ //# debugId=9AC2A26228EF3BBD64756E2164756E21