@otium-team/negotium 0.23.14 → 0.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-helpers.js +956 -243
- package/dist/agent-helpers.js.map +12 -9
- package/dist/{chunk-3v58ejrk.js → chunk-3r4xfhkx.js} +3 -3
- package/dist/{chunk-3v58ejrk.js.map → chunk-3r4xfhkx.js.map} +2 -2
- package/dist/{chunk-ng13grfj.js → chunk-fzfzskjq.js} +18 -2
- package/dist/{chunk-ng13grfj.js.map → chunk-fzfzskjq.js.map} +4 -4
- package/dist/{chunk-m1ngkjdd.js → chunk-hn2cqdd0.js} +1 -1
- package/dist/hosted-agent.js +19 -3
- package/dist/hosted-agent.js.map +5 -5
- package/dist/main.js +38697 -37819
- package/dist/main.js.map +89 -85
- package/dist/mcp-factories.js +946 -227
- package/dist/mcp-factories.js.map +13 -10
- package/dist/prompts.js +221 -1
- package/dist/prompts.js.map +7 -5
- package/dist/registry.js +3 -3
- package/dist/rollout.js +2 -2
- package/dist/runtime/src/mcp/wiki-server.ts +8 -0
- package/dist/runtime/src/platform/mcp-config.ts +26 -0
- package/dist/runtime/src/prompts/builders.ts +5 -0
- package/dist/runtime/src/runtime/turn-runner.ts +104 -1
- package/dist/runtime/src/storage/api-topics.ts +29 -0
- package/dist/runtime/src/topics/agent-plugins/mcp.schema.json +120 -0
- package/dist/runtime/src/topics/agent-plugins/plugin.schema.json +65 -0
- package/dist/runtime/src/topics/plugin-server-instructions.ts +201 -0
- package/dist/runtime/src/topics/plugin-turn.ts +37 -0
- package/dist/runtime/src/topics/plugins.ts +445 -0
- package/dist/runtime/src/topics/update.ts +34 -0
- package/dist/runtime/src/types/api.ts +5 -0
- package/dist/runtime/src/version.ts +1 -1
- package/dist/storage.js +23 -2
- package/dist/storage.js.map +3 -3
- package/dist/types/packages/core/src/platform/mcp-config.d.ts +6 -0
- package/dist/types/packages/core/src/prompts/builders.d.ts +3 -0
- package/dist/types/packages/core/src/runtime/turn-runner.d.ts +14 -1
- package/dist/types/packages/core/src/storage/api-topics.d.ts +3 -0
- package/dist/types/packages/core/src/topics/plugin-server-instructions.d.ts +55 -0
- package/dist/types/packages/core/src/topics/plugin-turn.d.ts +17 -0
- package/dist/types/packages/core/src/topics/plugins.d.ts +66 -0
- package/dist/types/packages/core/src/types/api.d.ts +5 -0
- package/dist/types/packages/core/src/version.d.ts +1 -1
- package/package.json +1 -1
- /package/dist/{chunk-m1ngkjdd.js.map → chunk-hn2cqdd0.js.map} +0 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `instructions` a room's plugin MCP servers return from `initialize`,
|
|
3
|
+
* shown to the model the same way on Claude, Codex and Maestro.
|
|
4
|
+
*
|
|
5
|
+
* The engines do not agree on their own. Claude Code puts each connected
|
|
6
|
+
* server's instructions in a reminder of its own, cut at 2048 characters.
|
|
7
|
+
* Codex shows them as tool metadata only, and only for some models. Maestro
|
|
8
|
+
* never reads them. So the node reads them itself and puts the same text in
|
|
9
|
+
* every engine's system prompt; a Claude turn may see a server's text twice.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
13
|
+
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
14
|
+
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
15
|
+
import type { HostMcpServerSpec } from "#runtime-gateway";
|
|
16
|
+
|
|
17
|
+
/** How long one server gets to answer `initialize`. */
|
|
18
|
+
export const SERVER_INSTRUCTIONS_TIMEOUT_MS = 3000;
|
|
19
|
+
/** How long a server's answer is reused before it is read again. */
|
|
20
|
+
export const SERVER_INSTRUCTIONS_TTL_MS = 5 * 60 * 1000;
|
|
21
|
+
/** The most UTF-8 bytes of one server's text the prompt carries. */
|
|
22
|
+
export const SERVER_INSTRUCTIONS_MAX_BYTES = 8 * 1024;
|
|
23
|
+
/** The most UTF-8 bytes the whole section carries. */
|
|
24
|
+
export const INSTRUCTIONS_SECTION_MAX_BYTES = 32 * 1024;
|
|
25
|
+
|
|
26
|
+
export interface McpServerInstructions {
|
|
27
|
+
server: string;
|
|
28
|
+
/** As the server sent it. */
|
|
29
|
+
text: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface FetchedServerInstructions {
|
|
33
|
+
/** Servers that returned non-empty instructions, in the order given. */
|
|
34
|
+
instructions: McpServerInstructions[];
|
|
35
|
+
/** Servers that could not be read in time, each with why. */
|
|
36
|
+
problems: string[];
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface FetchInstructionsOptions {
|
|
40
|
+
timeoutMs?: number;
|
|
41
|
+
/** The turn's stop: every read in flight ends when it fires. */
|
|
42
|
+
signal?: AbortSignal;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const cache = new Map<string, { text: string; expires: number }>();
|
|
46
|
+
|
|
47
|
+
/** A server's answer is reused only for the same name, url and headers. */
|
|
48
|
+
function cacheKey(server: string, spec: HostMcpServerSpec): string {
|
|
49
|
+
const headers = Object.entries(spec.headers ?? {})
|
|
50
|
+
.map(([name, value]) => [name.toLowerCase(), value])
|
|
51
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
52
|
+
return JSON.stringify([server, spec.type, spec.url, headers]);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Forget every cached answer. */
|
|
56
|
+
export function clearMcpServerInstructionsCache(): void {
|
|
57
|
+
cache.clear();
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function transportFor(spec: HostMcpServerSpec, signal: AbortSignal) {
|
|
61
|
+
const url = new URL(spec.url);
|
|
62
|
+
const requestInit = spec.headers ? { headers: spec.headers } : undefined;
|
|
63
|
+
// A redirect would carry the server's headers, often a credential, to
|
|
64
|
+
// another url, so it fails the read instead.
|
|
65
|
+
const noRedirect = (input: string | URL, init?: RequestInit) =>
|
|
66
|
+
fetch(input, {
|
|
67
|
+
...init,
|
|
68
|
+
redirect: "error",
|
|
69
|
+
signal: init?.signal ? AbortSignal.any([init.signal, signal]) : signal,
|
|
70
|
+
});
|
|
71
|
+
return spec.type === "sse"
|
|
72
|
+
? new SSEClientTransport(url, { requestInit, fetch: noRedirect })
|
|
73
|
+
: new StreamableHTTPClientTransport(url, { requestInit, fetch: noRedirect });
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function readInstructions(
|
|
77
|
+
spec: HostMcpServerSpec,
|
|
78
|
+
timeoutMs: number,
|
|
79
|
+
stop: AbortSignal | undefined,
|
|
80
|
+
): Promise<string> {
|
|
81
|
+
const ended = new AbortController();
|
|
82
|
+
const timer = setTimeout(() => ended.abort(new Error(`no answer in ${timeoutMs} ms`)), timeoutMs);
|
|
83
|
+
timer.unref?.();
|
|
84
|
+
const onStop = () => ended.abort(new Error("the turn was stopped"));
|
|
85
|
+
if (stop?.aborted) onStop();
|
|
86
|
+
else stop?.addEventListener("abort", onStop, { once: true });
|
|
87
|
+
const client = new Client({ name: "negotium-plugin-instructions", version: "1.0.0" });
|
|
88
|
+
const transport = transportFor(spec, ended.signal);
|
|
89
|
+
try {
|
|
90
|
+
return await Promise.race([
|
|
91
|
+
client.connect(transport).then(() => client.getInstructions() ?? ""),
|
|
92
|
+
new Promise<never>((_, reject) => {
|
|
93
|
+
if (ended.signal.aborted) reject(ended.signal.reason);
|
|
94
|
+
ended.signal.addEventListener("abort", () => reject(ended.signal.reason), { once: true });
|
|
95
|
+
}),
|
|
96
|
+
]);
|
|
97
|
+
} finally {
|
|
98
|
+
clearTimeout(timer);
|
|
99
|
+
stop?.removeEventListener("abort", onStop);
|
|
100
|
+
// End the server's session when it opened one; the turn does not wait.
|
|
101
|
+
const ending =
|
|
102
|
+
!ended.signal.aborted && transport instanceof StreamableHTTPClientTransport
|
|
103
|
+
? transport.terminateSession()
|
|
104
|
+
: Promise.resolve();
|
|
105
|
+
void ending.catch(() => {}).finally(() => client.close().catch(() => {}));
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Read every server's `instructions` at once, reusing an answer younger than
|
|
111
|
+
* `SERVER_INSTRUCTIONS_TTL_MS`; never throws. A failed read is not cached.
|
|
112
|
+
*/
|
|
113
|
+
export async function fetchMcpServerInstructions(
|
|
114
|
+
servers: Readonly<Record<string, HostMcpServerSpec>>,
|
|
115
|
+
options: FetchInstructionsOptions = {},
|
|
116
|
+
): Promise<FetchedServerInstructions> {
|
|
117
|
+
const timeoutMs = options.timeoutMs ?? SERVER_INSTRUCTIONS_TIMEOUT_MS;
|
|
118
|
+
const entries = Object.entries(servers);
|
|
119
|
+
const results = await Promise.allSettled(
|
|
120
|
+
entries.map(async ([server, spec]) => {
|
|
121
|
+
const key = cacheKey(server, spec);
|
|
122
|
+
const hit = cache.get(key);
|
|
123
|
+
if (hit && hit.expires > Date.now()) return hit.text;
|
|
124
|
+
const text = await readInstructions(spec, timeoutMs, options.signal);
|
|
125
|
+
cache.set(key, { text, expires: Date.now() + SERVER_INSTRUCTIONS_TTL_MS });
|
|
126
|
+
return text;
|
|
127
|
+
}),
|
|
128
|
+
);
|
|
129
|
+
const fetched: FetchedServerInstructions = { instructions: [], problems: [] };
|
|
130
|
+
results.forEach((result, index) => {
|
|
131
|
+
const server = entries[index][0];
|
|
132
|
+
if (result.status === "rejected") {
|
|
133
|
+
const reason = result.reason instanceof Error ? result.reason.message : String(result.reason);
|
|
134
|
+
fetched.problems.push(`plugin server "${server}": instructions not read (${reason})`);
|
|
135
|
+
} else if (result.value.trim()) {
|
|
136
|
+
fetched.instructions.push({ server, text: result.value });
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
return fetched;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const encoder = new TextEncoder();
|
|
143
|
+
const byteLength = (text: string) => encoder.encode(text).length;
|
|
144
|
+
|
|
145
|
+
/** The longest start of `text` within `maxBytes` UTF-8 bytes, never splitting a character. */
|
|
146
|
+
function cutToBytes(text: string, maxBytes: number): string {
|
|
147
|
+
const encoded = encoder.encode(text);
|
|
148
|
+
let end = Math.max(0, maxBytes);
|
|
149
|
+
while (end > 0 && (encoded[end] & 0xc0) === 0x80) end--;
|
|
150
|
+
return new TextDecoder().decode(encoded.subarray(0, end));
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const cutMarker = (server: string, sent: number) =>
|
|
154
|
+
`\n\n[negotium cut the instructions of "${server}" here; the server sent ${sent} bytes]`;
|
|
155
|
+
|
|
156
|
+
export interface RenderedServerInstructions {
|
|
157
|
+
/** The system prompt section; empty when no server's text is shown. */
|
|
158
|
+
section: string;
|
|
159
|
+
/** Servers whose text was cut or left out for size. */
|
|
160
|
+
problems: string[];
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* The system prompt section for the servers' instructions, the same text for
|
|
165
|
+
* every engine. A server's text is cut at `SERVER_INSTRUCTIONS_MAX_BYTES` and
|
|
166
|
+
* the section at `INSTRUCTIONS_SECTION_MAX_BYTES`, each cut marked in the
|
|
167
|
+
* text; servers past the section's limit are left out.
|
|
168
|
+
*/
|
|
169
|
+
export function renderMcpServerInstructions(
|
|
170
|
+
instructions: readonly McpServerInstructions[],
|
|
171
|
+
): RenderedServerInstructions {
|
|
172
|
+
const head = [
|
|
173
|
+
"## MCP Server Instructions",
|
|
174
|
+
"",
|
|
175
|
+
"The following MCP servers have provided instructions for how to use their tools and resources:",
|
|
176
|
+
].join("\n");
|
|
177
|
+
const blocks: string[] = [];
|
|
178
|
+
const problems: string[] = [];
|
|
179
|
+
let left = INSTRUCTIONS_SECTION_MAX_BYTES - byteLength(head);
|
|
180
|
+
for (const { server, text: sent } of instructions) {
|
|
181
|
+
const heading = `\n\n### ${server}\n\n`;
|
|
182
|
+
const text = sent.trim();
|
|
183
|
+
const size = byteLength(text);
|
|
184
|
+
const room = Math.min(SERVER_INSTRUCTIONS_MAX_BYTES, left - byteLength(heading));
|
|
185
|
+
if (size <= room) {
|
|
186
|
+
blocks.push(`${heading}${text}`);
|
|
187
|
+
left -= byteLength(heading) + size;
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
const marker = cutMarker(server, size);
|
|
191
|
+
if (room <= byteLength(marker)) {
|
|
192
|
+
problems.push(`plugin server "${server}": instructions left out (the section is full)`);
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
const shown = `${cutToBytes(text, room - byteLength(marker))}${marker}`;
|
|
196
|
+
blocks.push(`${heading}${shown}`);
|
|
197
|
+
left -= byteLength(heading) + byteLength(shown);
|
|
198
|
+
problems.push(`plugin server "${server}": instructions cut from ${size} bytes`);
|
|
199
|
+
}
|
|
200
|
+
return { section: blocks.length > 0 ? `${head}${blocks.join("")}` : "", problems };
|
|
201
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a room's plugins give one turn: the plugins whose skills the system
|
|
3
|
+
* prompt carries, and their root `mcp.json` servers. Turns fail closed: what
|
|
4
|
+
* does not load gives nothing, and servers whose names clash are left out.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { pluginMcpRefusal } from "#platform/mcp-config";
|
|
8
|
+
import type { HostMcpServerSpec } from "#runtime-gateway";
|
|
9
|
+
import { loadTopicPlugins, type TopicPlugin } from "#topics/plugins";
|
|
10
|
+
import type { TopicDto } from "#types/api";
|
|
11
|
+
|
|
12
|
+
export interface TopicPluginTurn {
|
|
13
|
+
plugins: readonly TopicPlugin[];
|
|
14
|
+
mcpServers: Record<string, HostMcpServerSpec>;
|
|
15
|
+
/** What the plugin folders reported while loading. */
|
|
16
|
+
loadProblems: readonly string[];
|
|
17
|
+
/** Why the plugins' servers were left out: a name that clashes. */
|
|
18
|
+
serverProblems: readonly string[];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const NONE: TopicPluginTurn = { plugins: [], mcpServers: {}, loadProblems: [], serverProblems: [] };
|
|
22
|
+
|
|
23
|
+
export function resolveTopicPluginTurn(
|
|
24
|
+
topic: Pick<TopicDto, "kind" | "isSubagent" | "plugins">,
|
|
25
|
+
hostServerNames: readonly string[],
|
|
26
|
+
): TopicPluginTurn {
|
|
27
|
+
if (!topic.plugins?.length) return NONE;
|
|
28
|
+
const { plugins, problems: loadProblems } = loadTopicPlugins(topic.plugins);
|
|
29
|
+
const servers = Object.assign({}, ...plugins.map((plugin) => plugin.mcpServers));
|
|
30
|
+
const refusal = pluginMcpRefusal(topic, Object.keys(servers), hostServerNames);
|
|
31
|
+
return {
|
|
32
|
+
plugins,
|
|
33
|
+
mcpServers: refusal ? {} : servers,
|
|
34
|
+
loadProblems,
|
|
35
|
+
serverProblems: refusal ? [refusal] : [],
|
|
36
|
+
};
|
|
37
|
+
}
|
|
@@ -0,0 +1,445 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plugins a host attaches to a room (`plugins` on the topic), read as Agent
|
|
3
|
+
* Plugins 1.0.0 (https://agent-plugins.org/specification) the same way for
|
|
4
|
+
* every agent kind, so a room gets the same instructions and tools on Claude,
|
|
5
|
+
* Codex and Maestro. Engine-native plugin systems (`.claude-plugin`,
|
|
6
|
+
* `.codex-plugin`) are deliberately not used.
|
|
7
|
+
*
|
|
8
|
+
* Portable parts:
|
|
9
|
+
* - `plugin.json`: the closed manifest, checked against the vendored schema
|
|
10
|
+
* (`agent-plugins/plugin.schema.json`); never fetched.
|
|
11
|
+
* - `skills/<name>/SKILL.md`: Agent Skills, listed in the system prompt by
|
|
12
|
+
* name, description and path; the model opens them with its file-read tool.
|
|
13
|
+
* - `mcp.json`: remote servers (`streamable-http`, `sse`), taken literally.
|
|
14
|
+
* `stdio` servers are skipped: a gateway host must not make the node launch
|
|
15
|
+
* processes (the same line `parseHostMcpServers` draws).
|
|
16
|
+
*
|
|
17
|
+
* Nothing else is read: other folders, client extension folders (spec §8)
|
|
18
|
+
* and the manifest's `extensions` entries are ignored unread. Servers that
|
|
19
|
+
* only the host can describe, such as one whose url carries a room token,
|
|
20
|
+
* come with each turn's `hostMcpServers`, never from a plugin.
|
|
21
|
+
*
|
|
22
|
+
* A plugin brings no always-on prompt text. A server says how to use its
|
|
23
|
+
* tools in their descriptions and in its MCP `instructions`, which every
|
|
24
|
+
* turn shows the model (`plugin-server-instructions.ts`).
|
|
25
|
+
*
|
|
26
|
+
* Failure boundaries follow the spec: a manifest violation rejects the
|
|
27
|
+
* plugin; a bad skill, server entry or component location is skipped. Every
|
|
28
|
+
* problem is reported.
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
32
|
+
import { isAbsolute, join, relative } from "node:path";
|
|
33
|
+
import { z } from "zod";
|
|
34
|
+
import { type HostMcpServerSpec, parseHostMcpServers } from "#runtime-gateway";
|
|
35
|
+
import mcpSchemaJson from "./agent-plugins/mcp.schema.json";
|
|
36
|
+
import manifestSchemaJson from "./agent-plugins/plugin.schema.json";
|
|
37
|
+
|
|
38
|
+
const MANIFEST_FILE = "plugin.json";
|
|
39
|
+
const SKILLS_DIR = "skills";
|
|
40
|
+
const SKILL_FILE = "SKILL.md";
|
|
41
|
+
const MCP_FILE = "mcp.json";
|
|
42
|
+
|
|
43
|
+
const MANIFEST_SCHEMA_ID = manifestSchemaJson.properties.$schema.const;
|
|
44
|
+
const MCP_SCHEMA_ID = mcpSchemaJson.properties.$schema.const;
|
|
45
|
+
const MANIFEST_FIELDS = new Set(Object.keys(manifestSchemaJson.properties));
|
|
46
|
+
const REMOTE_SERVERS = {
|
|
47
|
+
"streamable-http": mcpSchemaJson.$defs.streamableHttpServer,
|
|
48
|
+
sse: mcpSchemaJson.$defs.sseServer,
|
|
49
|
+
} as const;
|
|
50
|
+
/** The node's transport name for each remote type `mcp.json` declares. */
|
|
51
|
+
const NODE_TRANSPORT = { "streamable-http": "http", sse: "sse" } as const;
|
|
52
|
+
|
|
53
|
+
/** Agent Skills: lowercase letters, digits and single hyphens, not at either end. */
|
|
54
|
+
const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
55
|
+
const MAX_SKILL_NAME_CHARS = 64;
|
|
56
|
+
const MAX_SKILL_DESCRIPTION_CHARS = 1024;
|
|
57
|
+
|
|
58
|
+
export interface PluginSkill {
|
|
59
|
+
/** Folder name, repeated by `SKILL.md`'s `name`. Unique across a room's plugins. */
|
|
60
|
+
name: string;
|
|
61
|
+
/** When to read it; the only text of the skill the system prompt carries. */
|
|
62
|
+
description: string;
|
|
63
|
+
/** Absolute path of its `SKILL.md`. */
|
|
64
|
+
path: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface TopicPlugin {
|
|
68
|
+
/** The manifest's `name`. */
|
|
69
|
+
id: string;
|
|
70
|
+
/** Absolute folder path, as the room lists it. */
|
|
71
|
+
dir: string;
|
|
72
|
+
/** In folder name order. */
|
|
73
|
+
skills: readonly PluginSkill[];
|
|
74
|
+
/** Root `mcp.json` servers, ready to connect. */
|
|
75
|
+
mcpServers: Readonly<Record<string, HostMcpServerSpec>>;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface TopicPluginsLoad {
|
|
79
|
+
/** The plugins that loaded, in the room's order, without what was skipped. */
|
|
80
|
+
plugins: readonly TopicPlugin[];
|
|
81
|
+
/** Every rejected plugin and skipped component, with where and why. */
|
|
82
|
+
problems: readonly string[];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** UTF-8 text without a byte order mark, with `\n` line ends. */
|
|
86
|
+
function readText(path: string): string {
|
|
87
|
+
return readFileSync(path, "utf-8")
|
|
88
|
+
.replace(/^\uFEFF/, "")
|
|
89
|
+
.replace(/\r\n/g, "\n");
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Hidden files, such as the `.DS_Store` a Mac's Finder leaves, are not part of a plugin. */
|
|
93
|
+
const visible = (name: string) => !name.startsWith(".");
|
|
94
|
+
|
|
95
|
+
/** Code-unit order: the disk's own order differs between Windows, macOS and Linux. */
|
|
96
|
+
const byName = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
|
|
97
|
+
|
|
98
|
+
const isObject = (value: unknown): value is Record<string, unknown> =>
|
|
99
|
+
typeof value === "object" && value !== null && !Array.isArray(value);
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The kind of a package path that resolves inside the plugin root (spec
|
|
103
|
+
* §4.1): "missing", "outside", or what is there.
|
|
104
|
+
*/
|
|
105
|
+
function pathKind(root: string, path: string): "missing" | "outside" | "file" | "dir" | "other" {
|
|
106
|
+
if (!existsSync(path)) return "missing";
|
|
107
|
+
const real = realpathSync(path);
|
|
108
|
+
const fromRoot = relative(root, real);
|
|
109
|
+
if (fromRoot.startsWith("..") || isAbsolute(fromRoot)) return "outside";
|
|
110
|
+
const stat = statSync(real);
|
|
111
|
+
return stat.isFile() ? "file" : stat.isDirectory() ? "dir" : "other";
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
type Frontmatter =
|
|
115
|
+
| { ok: true; meta: Record<string, unknown>; body: string }
|
|
116
|
+
| { ok: false; problem: string };
|
|
117
|
+
|
|
118
|
+
/** A `---` YAML block, read with Bun's YAML parser, then the body. */
|
|
119
|
+
function parseFrontmatter(raw: string): Frontmatter {
|
|
120
|
+
const match = raw.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
|
|
121
|
+
if (!match) return { ok: false, problem: "missing the --- frontmatter block" };
|
|
122
|
+
let meta: unknown;
|
|
123
|
+
try {
|
|
124
|
+
meta = Bun.YAML.parse(match[1]);
|
|
125
|
+
} catch (error) {
|
|
126
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
127
|
+
return { ok: false, problem: `frontmatter is not valid YAML (${reason})` };
|
|
128
|
+
}
|
|
129
|
+
if (!isObject(meta)) return { ok: false, problem: "frontmatter must be a YAML mapping" };
|
|
130
|
+
return { ok: true, meta, body: match[2] };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function readJson(path: string, fail: (problem: string) => void): unknown {
|
|
134
|
+
try {
|
|
135
|
+
return JSON.parse(readText(path));
|
|
136
|
+
} catch (error) {
|
|
137
|
+
fail(`not valid JSON (${error instanceof Error ? error.message : String(error)})`);
|
|
138
|
+
return undefined;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
let manifestValidator: z.ZodType | null = null;
|
|
143
|
+
|
|
144
|
+
function manifestSchema(): z.ZodType {
|
|
145
|
+
manifestValidator ??= z.fromJSONSchema(
|
|
146
|
+
manifestSchemaJson as Parameters<typeof z.fromJSONSchema>[0],
|
|
147
|
+
);
|
|
148
|
+
return manifestValidator;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* `plugin.json` (spec §5): unknown top-level fields and a non-object
|
|
153
|
+
* `extensions` are reported and ignored; any other violation rejects the
|
|
154
|
+
* plugin.
|
|
155
|
+
*/
|
|
156
|
+
function readManifest(root: string, fail: (problem: string) => void): { id: string } | null {
|
|
157
|
+
const path = join(root, MANIFEST_FILE);
|
|
158
|
+
const kind = pathKind(root, path);
|
|
159
|
+
if (kind !== "file") {
|
|
160
|
+
fail(kind === "outside" ? "resolves outside the plugin folder" : "missing");
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
const raw = readJson(path, fail);
|
|
164
|
+
if (raw === undefined) return null;
|
|
165
|
+
if (!isObject(raw)) {
|
|
166
|
+
fail("must be a JSON object");
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
const manifest: Record<string, unknown> = {};
|
|
170
|
+
for (const [field, value] of Object.entries(raw)) {
|
|
171
|
+
if (!MANIFEST_FIELDS.has(field)) fail(`unknown field "${field}" is ignored`);
|
|
172
|
+
else if (field === "extensions" && !isObject(value)) {
|
|
173
|
+
fail('"extensions" is not an object and is ignored');
|
|
174
|
+
} else manifest[field] = value;
|
|
175
|
+
}
|
|
176
|
+
if (typeof manifest.$schema === "string" && manifest.$schema !== MANIFEST_SCHEMA_ID) {
|
|
177
|
+
fail(`unsupported Agent Plugins version: $schema "${manifest.$schema}"`);
|
|
178
|
+
return null;
|
|
179
|
+
}
|
|
180
|
+
const checked = manifestSchema().safeParse(manifest);
|
|
181
|
+
if (!checked.success) {
|
|
182
|
+
for (const issue of checked.error.issues) {
|
|
183
|
+
fail(`${issue.path.length > 0 ? `${issue.path.join(".")}: ` : ""}${issue.message}`);
|
|
184
|
+
}
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
return { id: String(manifest.name) };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* One skill (spec §7.1, Agent Skills): skipped when its frontmatter is not
|
|
192
|
+
* YAML or its `name` or `description` breaks the Agent Skills rules.
|
|
193
|
+
*/
|
|
194
|
+
function readSkill(
|
|
195
|
+
root: string,
|
|
196
|
+
dir: string,
|
|
197
|
+
name: string,
|
|
198
|
+
fail: (file: string, problem: string) => void,
|
|
199
|
+
): PluginSkill | null {
|
|
200
|
+
const where = `${SKILLS_DIR}/${name}/${SKILL_FILE}`;
|
|
201
|
+
// Listed under the folder the room names, which the model and the host see.
|
|
202
|
+
const path = join(dir, SKILLS_DIR, name, SKILL_FILE);
|
|
203
|
+
const kind = pathKind(root, path);
|
|
204
|
+
if (kind === "outside") {
|
|
205
|
+
fail(where, "resolves outside the plugin folder; skipped");
|
|
206
|
+
return null;
|
|
207
|
+
}
|
|
208
|
+
if (kind !== "file") return null;
|
|
209
|
+
const parsed = parseFrontmatter(readText(path));
|
|
210
|
+
if (!parsed.ok) {
|
|
211
|
+
fail(where, `${parsed.problem}; skipped`);
|
|
212
|
+
return null;
|
|
213
|
+
}
|
|
214
|
+
const problems: string[] = [];
|
|
215
|
+
const skillName = parsed.meta.name;
|
|
216
|
+
const description =
|
|
217
|
+
typeof parsed.meta.description === "string" ? parsed.meta.description.trim() : "";
|
|
218
|
+
if (skillName !== name) problems.push(`name must be the folder's name "${name}"`);
|
|
219
|
+
else if (!SKILL_NAME.test(name) || name.length > MAX_SKILL_NAME_CHARS) {
|
|
220
|
+
problems.push("name must be 1-64 lowercase letters, digits and single inner hyphens");
|
|
221
|
+
}
|
|
222
|
+
if (!description) problems.push("description (when to read it) is missing");
|
|
223
|
+
else if (description.length > MAX_SKILL_DESCRIPTION_CHARS) {
|
|
224
|
+
problems.push(`description is over ${MAX_SKILL_DESCRIPTION_CHARS} characters`);
|
|
225
|
+
}
|
|
226
|
+
if (problems.length > 0) {
|
|
227
|
+
fail(where, `${problems.join("; ")}; skipped`);
|
|
228
|
+
return null;
|
|
229
|
+
}
|
|
230
|
+
return { name, description, path };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** `skills/`: each immediate child folder holding a `SKILL.md` is one skill. */
|
|
234
|
+
function readSkills(
|
|
235
|
+
root: string,
|
|
236
|
+
dir: string,
|
|
237
|
+
fail: (file: string, problem: string) => void,
|
|
238
|
+
): PluginSkill[] {
|
|
239
|
+
const skillsDir = join(root, SKILLS_DIR);
|
|
240
|
+
const kind = pathKind(root, skillsDir);
|
|
241
|
+
if (kind === "missing") return [];
|
|
242
|
+
if (kind !== "dir") {
|
|
243
|
+
fail(SKILLS_DIR, kind === "outside" ? "resolves outside the plugin folder" : "not a folder");
|
|
244
|
+
return [];
|
|
245
|
+
}
|
|
246
|
+
return readdirSync(skillsDir)
|
|
247
|
+
.filter(visible)
|
|
248
|
+
.sort(byName)
|
|
249
|
+
.flatMap((name) => readSkill(root, dir, name, fail) ?? []);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Why a remote server's url breaks spec §7.2.1, or null. */
|
|
253
|
+
function remoteUrlProblem(raw: string): string | null {
|
|
254
|
+
let url: URL;
|
|
255
|
+
try {
|
|
256
|
+
url = new URL(raw);
|
|
257
|
+
} catch {
|
|
258
|
+
return "url must be an absolute http or https URL";
|
|
259
|
+
}
|
|
260
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
261
|
+
return "url must be an absolute http or https URL";
|
|
262
|
+
}
|
|
263
|
+
if (url.username || url.password) return "url must not contain user information";
|
|
264
|
+
if (url.hash || raw.includes("#")) return "url must not contain a fragment";
|
|
265
|
+
if (url.protocol === "http:" && !isLoopbackHost(url.hostname)) {
|
|
266
|
+
return "a non-loopback url must use https";
|
|
267
|
+
}
|
|
268
|
+
return null;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Exactly `localhost`, `[::1]`, or an IPv4 literal in 127.0.0.0/8; the URL
|
|
273
|
+
* parser has already turned short forms such as `127.1` into four parts.
|
|
274
|
+
*/
|
|
275
|
+
function isLoopbackHost(hostname: string): boolean {
|
|
276
|
+
if (hostname === "localhost" || hostname === "[::1]") return true;
|
|
277
|
+
const parts = hostname.split(".");
|
|
278
|
+
return (
|
|
279
|
+
parts.length === 4 &&
|
|
280
|
+
parts[0] === "127" &&
|
|
281
|
+
parts.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255)
|
|
282
|
+
);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* One `mcp.json` server entry, checked like a host grant; null when it is
|
|
287
|
+
* skipped.
|
|
288
|
+
*/
|
|
289
|
+
function readServer(
|
|
290
|
+
name: string,
|
|
291
|
+
spec: unknown,
|
|
292
|
+
fail: (problem: string) => void,
|
|
293
|
+
): HostMcpServerSpec | null {
|
|
294
|
+
if (!isObject(spec) || typeof spec.type !== "string") {
|
|
295
|
+
fail(`"${name}": a server is an object with a "type"; skipped`);
|
|
296
|
+
return null;
|
|
297
|
+
}
|
|
298
|
+
if (spec.type === "stdio") {
|
|
299
|
+
fail(`"${name}": stdio servers are not supported here (remote servers only); skipped`);
|
|
300
|
+
return null;
|
|
301
|
+
}
|
|
302
|
+
const variant = REMOTE_SERVERS[spec.type as keyof typeof REMOTE_SERVERS];
|
|
303
|
+
if (!variant) {
|
|
304
|
+
fail(`"${name}": unknown type "${spec.type}"; skipped`);
|
|
305
|
+
return null;
|
|
306
|
+
}
|
|
307
|
+
const allowed = new Set(Object.keys(variant.properties));
|
|
308
|
+
const unknown = Object.keys(spec).find((key) => !allowed.has(key));
|
|
309
|
+
if (unknown) {
|
|
310
|
+
fail(`"${name}": field "${unknown}" does not belong to a ${spec.type} server; skipped`);
|
|
311
|
+
return null;
|
|
312
|
+
}
|
|
313
|
+
if (typeof spec.url !== "string" || !spec.url) {
|
|
314
|
+
fail(`"${name}": url is required; skipped`);
|
|
315
|
+
return null;
|
|
316
|
+
}
|
|
317
|
+
const headers = spec.headers;
|
|
318
|
+
if (headers !== undefined) {
|
|
319
|
+
const values = isObject(headers) ? Object.entries(headers) : null;
|
|
320
|
+
const lower = values?.map(([key]) => key.toLowerCase()) ?? [];
|
|
321
|
+
if (
|
|
322
|
+
!values ||
|
|
323
|
+
values.some(([, value]) => typeof value !== "string") ||
|
|
324
|
+
new Set(lower).size !== lower.length
|
|
325
|
+
) {
|
|
326
|
+
fail(`"${name}": headers must be distinct header names with string values; skipped`);
|
|
327
|
+
return null;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
const server: HostMcpServerSpec = {
|
|
331
|
+
type: NODE_TRANSPORT[spec.type as keyof typeof NODE_TRANSPORT],
|
|
332
|
+
url: spec.url,
|
|
333
|
+
...(headers ? { headers: headers as Record<string, string> } : {}),
|
|
334
|
+
};
|
|
335
|
+
const urlProblem = remoteUrlProblem(spec.url);
|
|
336
|
+
if (urlProblem) {
|
|
337
|
+
fail(`"${name}": ${urlProblem}; skipped`);
|
|
338
|
+
return null;
|
|
339
|
+
}
|
|
340
|
+
try {
|
|
341
|
+
parseHostMcpServers({ [name]: server });
|
|
342
|
+
} catch (error) {
|
|
343
|
+
fail(`"${name}": ${error instanceof Error ? error.message : String(error)}; skipped`);
|
|
344
|
+
return null;
|
|
345
|
+
}
|
|
346
|
+
return server;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* The root `mcp.json` (spec §7.2.2): a broken or mismatched file disables
|
|
351
|
+
* its servers; a broken entry is skipped.
|
|
352
|
+
*/
|
|
353
|
+
function readMcpFile(
|
|
354
|
+
root: string,
|
|
355
|
+
fail: (problem: string) => void,
|
|
356
|
+
): Record<string, HostMcpServerSpec> {
|
|
357
|
+
const path = join(root, MCP_FILE);
|
|
358
|
+
const kind = pathKind(root, path);
|
|
359
|
+
if (kind === "missing") return {};
|
|
360
|
+
if (kind !== "file") {
|
|
361
|
+
fail(`${kind === "outside" ? "resolves outside the plugin folder" : "not a file"}; no servers`);
|
|
362
|
+
return {};
|
|
363
|
+
}
|
|
364
|
+
const raw = readJson(path, fail);
|
|
365
|
+
if (raw === undefined) return {};
|
|
366
|
+
const extra = isObject(raw)
|
|
367
|
+
? Object.keys(raw).find((key) => key !== "$schema" && key !== "mcpServers")
|
|
368
|
+
: undefined;
|
|
369
|
+
if (!isObject(raw) || raw.$schema !== MCP_SCHEMA_ID || !isObject(raw.mcpServers) || extra) {
|
|
370
|
+
fail(`must be {"$schema": "${MCP_SCHEMA_ID}", "mcpServers": {…}} and nothing else; no servers`);
|
|
371
|
+
return {};
|
|
372
|
+
}
|
|
373
|
+
const servers: Record<string, HostMcpServerSpec> = {};
|
|
374
|
+
for (const [name, spec] of Object.entries(raw.mcpServers)) {
|
|
375
|
+
const server = readServer(name, spec, fail);
|
|
376
|
+
if (server) servers[name] = server;
|
|
377
|
+
}
|
|
378
|
+
return servers;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* Read the plugin folders a room lists, in its order. A plugin name is
|
|
383
|
+
* taken once, and skill and server names are unique across the room: a later
|
|
384
|
+
* duplicate is skipped.
|
|
385
|
+
*/
|
|
386
|
+
export function loadTopicPlugins(dirs: readonly string[]): TopicPluginsLoad {
|
|
387
|
+
const problems: string[] = [];
|
|
388
|
+
const plugins: TopicPlugin[] = [];
|
|
389
|
+
const pluginOwner = new Map<string, string>();
|
|
390
|
+
const skillOwner = new Map<string, string>();
|
|
391
|
+
const serverOwner = new Map<string, string>();
|
|
392
|
+
for (const dir of dirs) {
|
|
393
|
+
if (!isAbsolute(dir)) {
|
|
394
|
+
problems.push(`${dir}: a plugin is given by its folder's absolute path`);
|
|
395
|
+
continue;
|
|
396
|
+
}
|
|
397
|
+
if (!existsSync(dir) || !statSync(dir).isDirectory()) {
|
|
398
|
+
problems.push(`${dir}: not a folder`);
|
|
399
|
+
continue;
|
|
400
|
+
}
|
|
401
|
+
const root = realpathSync(dir);
|
|
402
|
+
const failIn = (file: string, problem: string) => problems.push(`${dir}/${file}: ${problem}`);
|
|
403
|
+
const manifest = readManifest(root, (problem) => failIn(MANIFEST_FILE, problem));
|
|
404
|
+
if (!manifest) continue;
|
|
405
|
+
const owner = pluginOwner.get(manifest.id);
|
|
406
|
+
if (owner) {
|
|
407
|
+
failIn(MANIFEST_FILE, `plugin name "${manifest.id}" is already used by ${owner}; skipped`);
|
|
408
|
+
continue;
|
|
409
|
+
}
|
|
410
|
+
pluginOwner.set(manifest.id, dir);
|
|
411
|
+
const unique = (owners: Map<string, string>, key: string, what: string, file: string) => {
|
|
412
|
+
const other = owners.get(key);
|
|
413
|
+
if (other) failIn(file, `${what} "${key}" is already used by ${other}; skipped`);
|
|
414
|
+
else owners.set(key, dir);
|
|
415
|
+
return !other;
|
|
416
|
+
};
|
|
417
|
+
const skills = readSkills(root, dir, failIn).filter((skill) =>
|
|
418
|
+
unique(skillOwner, skill.name, "skill name", SKILLS_DIR),
|
|
419
|
+
);
|
|
420
|
+
const mcpServers = Object.fromEntries(
|
|
421
|
+
Object.entries(readMcpFile(root, (problem) => failIn(MCP_FILE, problem))).filter(([name]) =>
|
|
422
|
+
unique(serverOwner, name, "server name", MCP_FILE),
|
|
423
|
+
),
|
|
424
|
+
);
|
|
425
|
+
plugins.push({ ...manifest, dir, skills, mcpServers });
|
|
426
|
+
}
|
|
427
|
+
return { plugins, problems };
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* The prompt text a room's plugins add: one table of contents of every
|
|
432
|
+
* skill. The same input always renders the same text, whatever the agent
|
|
433
|
+
* kind; empty without skills.
|
|
434
|
+
*/
|
|
435
|
+
export function renderTopicPluginsPrompt(plugins: readonly TopicPlugin[]): string {
|
|
436
|
+
const skills = plugins.flatMap((plugin) => plugin.skills);
|
|
437
|
+
if (skills.length === 0) return "";
|
|
438
|
+
return [
|
|
439
|
+
"## Skills",
|
|
440
|
+
"",
|
|
441
|
+
"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.",
|
|
442
|
+
"",
|
|
443
|
+
...skills.map((skill) => `- \`${skill.name}\`: ${skill.description} (file: ${skill.path})`),
|
|
444
|
+
].join("\n");
|
|
445
|
+
}
|