teapot-coding-agent 0.29.28 → 0.29.30

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.
@@ -0,0 +1,311 @@
1
+ /**
2
+ * Agent Plugins (#162): read a `plugin.json` package and turn it into things teapot
3
+ * already understands.
4
+ *
5
+ * The format (https://agent-plugins.org, spec 1.1.0) is deliberately tiny, and the
6
+ * whole point of adopting it is that it needs almost no new machinery here:
7
+ *
8
+ * my-plugin/
9
+ * ├── plugin.json manifest: `$schema` + `name` are the only required fields
10
+ * ├── skills/<name>/SKILL.md → a skill ROOT (teapot already scans for SKILL.md)
11
+ * ├── mcp.json → `mcpServers`, the same shape as teapot's own MCP config
12
+ * └── com.example.client/… → client extensions, which we do not implement
13
+ *
14
+ * So a plugin is loaded by VALIDATING it and then extracting those two components. No
15
+ * plugin runtime, no per-plugin process for skills.
16
+ *
17
+ * What is validated, and why each rule exists:
18
+ * - `plugin.json` must exist, be an object, and carry `$schema` and `name`. The spec
19
+ * requires both; a manifest without them is not a plugin, and guessing is worse
20
+ * than saying so.
21
+ * - `name` must match the spec's pattern (lowercase, no `--`, no `..`). The pattern is
22
+ * not cosmetic: the name is used in paths and in tool namespaces, so `..` in a name
23
+ * is a traversal primitive.
24
+ * - **containment**: `plugin.json`, `skills/`, and every discovered `SKILL.md` must
25
+ * resolve INSIDE the plugin root after following symlinks. The spec makes this a
26
+ * MUST, and it is the one rule with a real security consequence: a plugin shipped
27
+ * as an archive can contain a symlink pointing at `~/.ssh`.
28
+ * - a `cwd`/`command` in `mcp.json` that escapes the root invalidates that SERVER,
29
+ * not the whole plugin — the spec draws exactly that boundary (§4.1).
30
+ *
31
+ * `${PLUGIN_ROOT}` and `${PLUGIN_DATA}` are expanded in `args`, `env` and `cwd` of a
32
+ * stdio server, as the spec requires. `PLUGIN_DATA` is a client-managed per-plugin
33
+ * directory, so each plugin gets a stable writable location that survives an upgrade.
34
+ */
35
+ import { readFile, readdir, realpath, mkdir, stat } from "node:fs/promises";
36
+ import path from "node:path";
37
+ /** the spec's name pattern, verbatim from plugin.schema.json */
38
+ const NAME_RE = /^(?!.*(?:--|\.\.))[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/;
39
+ export class PluginError extends Error {
40
+ constructor(message) {
41
+ super(message);
42
+ this.name = "PluginError";
43
+ }
44
+ }
45
+ /** true when `child` is `parent` or inside it (both already resolved) */
46
+ function within(parent, child) {
47
+ const rel = path.relative(parent, child);
48
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
49
+ }
50
+ /**
51
+ * Resolve a path and prove it stays inside `root`.
52
+ *
53
+ * `realpath` FIRST, because a symlink is exactly how an archive escapes its own root —
54
+ * checking the literal path would let `skills/evil -> /etc` through. A path that does
55
+ * not exist cannot escape, so ENOENT returns the lexical join and lets the caller's own
56
+ * existence checks report it.
57
+ */
58
+ async function resolveInside(root, p) {
59
+ const abs = path.resolve(root, p);
60
+ try {
61
+ const real = await realpath(abs);
62
+ return within(root, real) ? real : null;
63
+ }
64
+ catch {
65
+ return within(root, abs) ? abs : null;
66
+ }
67
+ }
68
+ /** expand `${PLUGIN_ROOT}` / `${PLUGIN_DATA}` (the only two the spec defines) */
69
+ function expand(s, root, data) {
70
+ return s.split("${PLUGIN_ROOT}").join(root).split("${PLUGIN_DATA}").join(data);
71
+ }
72
+ /**
73
+ * Load and validate one plugin directory.
74
+ *
75
+ * @param dir the plugin root
76
+ * @param dataDir the client-managed `PLUGIN_DATA` directory for this plugin
77
+ */
78
+ export async function loadPlugin(dir, dataDir) {
79
+ let root;
80
+ try {
81
+ root = await realpath(dir);
82
+ }
83
+ catch {
84
+ throw new PluginError(`plugin directory does not exist: ${dir}`);
85
+ }
86
+ const st = await stat(root).catch(() => null);
87
+ if (!st?.isDirectory())
88
+ throw new PluginError(`not a directory: ${dir}`);
89
+ // ---- manifest ----
90
+ const manifestPath = await resolveInside(root, "plugin.json");
91
+ if (!manifestPath)
92
+ throw new PluginError("plugin.json resolves outside the plugin root");
93
+ let raw;
94
+ try {
95
+ raw = await readFile(manifestPath, "utf8");
96
+ }
97
+ catch {
98
+ throw new PluginError(`no plugin.json in ${root}`);
99
+ }
100
+ let manifest;
101
+ try {
102
+ manifest = JSON.parse(raw);
103
+ }
104
+ catch (err) {
105
+ throw new PluginError(`plugin.json is not valid JSON: ${err.message}`);
106
+ }
107
+ if (typeof manifest !== "object" || manifest === null || Array.isArray(manifest))
108
+ throw new PluginError("plugin.json must be a JSON object");
109
+ // the spec makes BOTH required; without $schema we cannot know which version's rules
110
+ // to apply, and silently assuming 1.1.0 is how a v2 plugin gets half-loaded
111
+ if (typeof manifest.$schema !== "string")
112
+ throw new PluginError("plugin.json is missing $schema (an Agent Plugins manifest requires it)");
113
+ if (typeof manifest.name !== "string" || !manifest.name)
114
+ throw new PluginError("plugin.json is missing name");
115
+ if (!NAME_RE.test(manifest.name))
116
+ throw new PluginError(`plugin name "${manifest.name}" is not a valid Agent Plugins name ` +
117
+ "(lowercase letters, digits, '.', '-'; no '--' and no '..')");
118
+ const out = {
119
+ name: manifest.name,
120
+ root,
121
+ skills: [],
122
+ mcpServers: [],
123
+ warnings: [],
124
+ };
125
+ if (typeof manifest.version === "string")
126
+ out.version = manifest.version;
127
+ if (typeof manifest.description === "string")
128
+ out.description = manifest.description;
129
+ // ---- skills/ ----
130
+ //
131
+ // An immediate child directory containing a regular `SKILL.md` is one skill. The
132
+ // spec says MUST NOT recurse deeper, and that is also what keeps a plugin from
133
+ // silently pulling in a skill buried in `scripts/vendor/…`.
134
+ const skillsDir = await resolveInside(root, "skills");
135
+ if (!skillsDir) {
136
+ out.warnings.push("skills/ resolves outside the plugin root — ignored");
137
+ }
138
+ else if ((await stat(skillsDir).catch(() => null))?.isDirectory()) {
139
+ out.skillsDir = skillsDir;
140
+ for (const entry of await readdir(skillsDir, { withFileTypes: true }).catch(() => [])) {
141
+ if (!entry.isDirectory() && !entry.isSymbolicLink())
142
+ continue;
143
+ const skillDir = await resolveInside(skillsDir, entry.name);
144
+ if (!skillDir) {
145
+ out.warnings.push(`skill "${entry.name}" resolves outside the plugin root — skipped`);
146
+ continue;
147
+ }
148
+ const sm = path.join(skillDir, "SKILL.md");
149
+ const sst = await stat(sm).catch(() => null);
150
+ if (!sst?.isFile())
151
+ continue;
152
+ // the SKILL.md itself must also be contained (a symlinked one could point anywhere)
153
+ const real = await realpath(sm).catch(() => null);
154
+ if (!real || !within(root, real)) {
155
+ out.warnings.push(`skill "${entry.name}": SKILL.md escapes the plugin root — skipped`);
156
+ continue;
157
+ }
158
+ out.skills.push(entry.name);
159
+ }
160
+ }
161
+ // ---- mcp.json ----
162
+ const mcpPath = await resolveInside(root, "mcp.json");
163
+ if (mcpPath && (await stat(mcpPath).catch(() => null))?.isFile()) {
164
+ let cfg;
165
+ try {
166
+ cfg = JSON.parse(await readFile(mcpPath, "utf8"));
167
+ }
168
+ catch (err) {
169
+ out.warnings.push(`mcp.json is not valid JSON: ${err.message}`);
170
+ cfg = {};
171
+ }
172
+ const servers = cfg?.mcpServers;
173
+ if (servers && typeof servers === "object" && !Array.isArray(servers)) {
174
+ for (const [name, s] of Object.entries(servers)) {
175
+ const parsed = await pluginServer(name, s, root, dataDir);
176
+ if (typeof parsed === "string")
177
+ out.warnings.push(parsed);
178
+ else
179
+ out.mcpServers.push(parsed);
180
+ }
181
+ }
182
+ else if (servers !== undefined) {
183
+ out.warnings.push("mcp.json: mcpServers must be an object");
184
+ }
185
+ }
186
+ return out;
187
+ }
188
+ /**
189
+ * Turn one `mcp.json` server entry into teapot's `McpServerConfig`.
190
+ *
191
+ * Returns a STRING when the entry is invalid, because the spec's failure boundary is
192
+ * per-server: one bad entry must not reject the plugin. The name is prefixed with the
193
+ * plugin name so two plugins can each ship a server called `db` without colliding in
194
+ * the shared registry.
195
+ */
196
+ async function pluginServer(name, raw, root, dataDir) {
197
+ if (typeof raw !== "object" || raw === null)
198
+ return `mcp server "${name}": not an object`;
199
+ const s = raw;
200
+ const type = s.type;
201
+ if (type === "stdio") {
202
+ if (typeof s.command !== "string" || !s.command)
203
+ return `mcp server "${name}": stdio requires a command`;
204
+ const command = expand(s.command, root, dataDir);
205
+ // a plugin-relative command must START with ./ (spec §4.1.4) and stay inside
206
+ let resolvedCmd = command;
207
+ if (command.startsWith("./")) {
208
+ const abs = await resolveInside(root, command);
209
+ if (!abs)
210
+ return `mcp server "${name}": command escapes the plugin root`;
211
+ resolvedCmd = abs;
212
+ }
213
+ else if (command.includes("${PLUGIN_ROOT}") || command.includes("${PLUGIN_DATA}")) {
214
+ const abs = path.resolve(command);
215
+ if (!within(root, abs) && !within(path.resolve(dataDir), abs))
216
+ return `mcp server "${name}": command escapes the plugin root`;
217
+ resolvedCmd = abs;
218
+ }
219
+ // cwd: "./x", "${PLUGIN_ROOT}/x" or "${PLUGIN_DATA}/x" — anything else is invalid
220
+ let cwd;
221
+ if (s.cwd !== undefined) {
222
+ if (typeof s.cwd !== "string")
223
+ return `mcp server "${name}": cwd must be a string`;
224
+ const expanded = expand(s.cwd, root, dataDir);
225
+ const rootedInData = s.cwd.startsWith("${PLUGIN_DATA}");
226
+ const base = rootedInData ? path.resolve(dataDir) : root;
227
+ if (!s.cwd.startsWith("./") && !rootedInData && !s.cwd.startsWith("${PLUGIN_ROOT}"))
228
+ return `mcp server "${name}": cwd must begin with "./", "\${PLUGIN_ROOT}" or "\${PLUGIN_DATA}"`;
229
+ const abs = path.resolve(expanded);
230
+ if (!within(base, abs))
231
+ return `mcp server "${name}": cwd escapes its root`;
232
+ // PLUGIN_DATA may not exist yet; the spec says the client manages it
233
+ if (rootedInData)
234
+ await mkdir(base, { recursive: true }).catch(() => { });
235
+ cwd = abs;
236
+ }
237
+ const env = {};
238
+ if (s.env && typeof s.env === "object" && !Array.isArray(s.env)) {
239
+ for (const [k, v] of Object.entries(s.env)) {
240
+ // the spec forbids these two in env: the client owns them
241
+ if (k === "PLUGIN_ROOT" || k === "PLUGIN_DATA")
242
+ return `mcp server "${name}": env may not set ${k}`;
243
+ if (typeof v === "string")
244
+ env[k] = expand(v, root, dataDir);
245
+ }
246
+ }
247
+ const args = Array.isArray(s.args)
248
+ ? s.args.filter((a) => typeof a === "string").map((a) => expand(a, root, dataDir))
249
+ : [];
250
+ const cfg = { name, transport: "stdio", command: resolvedCmd, enabled: true };
251
+ if (args.length)
252
+ cfg.args = args;
253
+ if (Object.keys(env).length)
254
+ cfg.env = env;
255
+ if (cwd)
256
+ cfg.cwd = cwd;
257
+ return cfg;
258
+ }
259
+ if (type === "streamable-http" || type === "sse") {
260
+ if (typeof s.url !== "string" || !s.url)
261
+ return `mcp server "${name}": ${type} requires a url`;
262
+ const cfg = {
263
+ name,
264
+ transport: type === "sse" ? "sse" : "http",
265
+ url: s.url,
266
+ enabled: true,
267
+ };
268
+ if (s.headers && typeof s.headers === "object" && !Array.isArray(s.headers)) {
269
+ const headers = {};
270
+ for (const [k, v] of Object.entries(s.headers)) {
271
+ if (typeof v === "string")
272
+ headers[k] = v;
273
+ }
274
+ if (Object.keys(headers).length)
275
+ cfg.headers = headers;
276
+ }
277
+ return cfg;
278
+ }
279
+ return `mcp server "${name}": unknown type ${JSON.stringify(type)} (expected stdio, streamable-http or sse)`;
280
+ }
281
+ /**
282
+ * Load every plugin under a directory of plugins.
283
+ *
284
+ * A broken plugin is reported and skipped rather than failing the whole collection —
285
+ * the operator installed it to get something else working, and a plugin is
286
+ * third-party code.
287
+ */
288
+ export async function loadPlugins(dir, dataRoot) {
289
+ const plugins = [];
290
+ const errors = [];
291
+ let entries;
292
+ try {
293
+ entries = (await readdir(dir, { withFileTypes: true }))
294
+ .filter((e) => e.isDirectory() || e.isSymbolicLink())
295
+ .map((e) => e.name)
296
+ .sort();
297
+ }
298
+ catch {
299
+ return { plugins, errors }; // no plugin dir is the normal case
300
+ }
301
+ for (const name of entries) {
302
+ const p = path.join(dir, name);
303
+ try {
304
+ plugins.push(await loadPlugin(p, path.join(dataRoot, name)));
305
+ }
306
+ catch (err) {
307
+ errors.push({ dir: p, error: err.message });
308
+ }
309
+ }
310
+ return { plugins, errors };
311
+ }
@@ -9,6 +9,7 @@ import { discoverSkills, isValidSkillName, readSkillFile, saveSkill, SKILL_FILE,
9
9
  import { isReasoningEffort } from "../model-meta.js";
10
10
  import { killTree, describeKill } from "./kill.js";
11
11
  import { editorConfigFor } from "./editorconfig.js";
12
+ import { mcp, MCP_PREFIX } from "./mcp-registry.js";
12
13
  const str = (v, fallback = "") => (typeof v === "string" ? v : fallback);
13
14
  const num = (v, fallback) => (typeof v === "number" ? v : fallback);
14
15
  function clip(s, max) {
@@ -1141,13 +1142,41 @@ export const TOOLS = [
1141
1142
  let off = num(args.offset, 1);
1142
1143
  off = off < 0 ? Math.max(0, lines.length + off) : Math.max(0, off - 1);
1143
1144
  const lim = num(args.limit, 2000);
1145
+ // A LINE cap alone does not bound the output: a single 5MB minified line is one
1146
+ // "line", and 2000 lines of 2000 chars is 4MB. The three caps below each kill a
1147
+ // different shape of oversized file (#17 item 3):
1148
+ // lines → a 3000-line source file
1149
+ // bytes → a big log, whatever its line structure
1150
+ // per-line → minified.js / a one-line JSON blob
1144
1151
  const pageLines = lines.slice(off, off + lim);
1145
- const slice = idMode === "hash" ? renderHashlines(pageLines, off + 1) : renderGutter(pageLines, off + 1);
1152
+ // PER-LINE cap first: clipping lines before joining means one giant line cannot
1153
+ // blow the byte budget on its own, and the marker names how much was cut.
1154
+ const cappedLines = pageLines.map((l) => l.length > MAX_READ_LINE_CHARS
1155
+ ? l.slice(0, MAX_READ_LINE_CHARS) +
1156
+ ` …[line clipped: ${l.length - MAX_READ_LINE_CHARS} more chars]`
1157
+ : l);
1158
+ const rendered = idMode === "hash" ? renderHashlines(cappedLines, off + 1) : renderGutter(cappedLines, off + 1);
1146
1159
  // the phantom trailing line is dropped for the count too, or a file that
1147
1160
  // ends in a newline always reports one line more than it has
1148
1161
  const total = lines.length && lines[lines.length - 1] === "" ? lines.length - 1 : lines.length;
1149
1162
  const more = off + lim < total ? `\n... (${total - off - lim} more lines)` : "";
1150
- return { ok: true, result: slice + more };
1163
+ const out = rendered + more;
1164
+ // BYTE cap last, with the remaining line count in the marker so the model knows
1165
+ // how to continue rather than assuming it saw everything.
1166
+ if (out.length > MAX_READ_BYTES) {
1167
+ const head = out.slice(0, MAX_READ_BYTES);
1168
+ const cutAt = head.lastIndexOf("\n");
1169
+ return {
1170
+ ok: true,
1171
+ result: (cutAt > 0 ? head.slice(0, cutAt) : head) +
1172
+ `\n... [output clipped at ${MAX_READ_BYTES} bytes of ${out.length}; ` +
1173
+ // `head` holds N rendered lines separated by N-1 newlines, and rendering
1174
+ // started at 1-indexed line `off + 1`, so the next unread line is
1175
+ // off + 1 + N. Counting newlines alone gives N-1 and would re-read one line.
1176
+ `continue with offset=${off + 1 + countLines(cutAt > 0 ? head.slice(0, cutAt) : head) + 1}]`,
1177
+ };
1178
+ }
1179
+ return { ok: true, result: out };
1151
1180
  },
1152
1181
  },
1153
1182
  {
@@ -1914,6 +1943,28 @@ export const TOOLS = [
1914
1943
  /** #16: how many files one read_file call may cover. Each costs context, so an
1915
1944
  * unbounded array would just be a way to overflow the window in one shot. */
1916
1945
  const MAX_MULTI_READ = 10;
1946
+ /**
1947
+ * The three read caps (#17 item 3). A line cap alone is not a bound: one 5MB minified
1948
+ * line is a single "line", and 2000 lines of 2000 chars is 4MB. Each cap kills a
1949
+ * different shape of oversized file:
1950
+ *
1951
+ * 2000 lines → a 3000-line source file (the `limit` default, unchanged)
1952
+ * 256 KB → a 5MB log, whatever its lines
1953
+ * 2000 chars → minified.js / a one-line JSON blob
1954
+ *
1955
+ * The byte cap is a SHARE of what a tool result can be, not the whole budget: the model
1956
+ * still needs room to reason about what it read.
1957
+ */
1958
+ const MAX_READ_BYTES = 256 * 1024;
1959
+ const MAX_READ_LINE_CHARS = 2_000;
1960
+ /** how many lines a string contains — used to say where to resume a clipped read */
1961
+ function countLines(s) {
1962
+ let n = 0;
1963
+ for (let i = 0; i < s.length; i++)
1964
+ if (s.charCodeAt(i) === 10)
1965
+ n++;
1966
+ return n;
1967
+ }
1917
1968
  /**
1918
1969
  * Subsequence match: every character of `needle` appears in `hay`, in order,
1919
1970
  * gaps allowed (#16 "fuzzy").
@@ -2233,6 +2284,24 @@ export function repairToolInput(name, rawArgs) {
2233
2284
  return { args, notes };
2234
2285
  }
2235
2286
  export async function executeTool(name, rawArgs, ctx) {
2287
+ // MCP tools are namespaced (`mcp__server__tool`) so they can never reach this point
2288
+ // by shadowing a built-in. Dispatched BEFORE the built-in lookup because there is no
2289
+ // static TOOLS entry to find — the tool list belongs to the server.
2290
+ if (name.startsWith(MCP_PREFIX)) {
2291
+ if (ctx.signal?.aborted)
2292
+ return { ok: false, result: "aborted (harness shutdown)" };
2293
+ let args = {};
2294
+ try {
2295
+ args = rawArgs.trim() ? JSON.parse(rawArgs) : {};
2296
+ }
2297
+ catch {
2298
+ return { ok: false, result: `${name}: arguments are not valid JSON` };
2299
+ }
2300
+ const r = await mcp.call(name, args);
2301
+ if (!r)
2302
+ return { ok: false, result: `unknown tool: ${name}` };
2303
+ return { ok: r.ok, result: r.text };
2304
+ }
2236
2305
  const def = TOOLS.find((t) => t.name === name);
2237
2306
  if (!def)
2238
2307
  return { ok: false, result: `unknown tool: ${name}` };
@@ -52,6 +52,8 @@ export const ConfigPatchSchema = z.object({
52
52
  // null clears a saved window pin → back to per-model inference (same contract as contextTokenBudget)
53
53
  contextWindowTokens: z.number().int().min(1_000).nullable().optional(),
54
54
  maxSpawnDepth: z.number().int().min(0).max(8).optional(),
55
+ /** #161: prune old tool output early (opt-in, for small-window models) */
56
+ shortContext: z.boolean().optional(),
55
57
  // soft cap on LLM turns in one round; reaching it nudges the model to wrap
56
58
  // up (not an error) — 0 disables the cap
57
59
  maxTurnsPerRound: z.number().int().min(0).optional(),
@@ -60,6 +62,32 @@ export const ConfigPatchSchema = z.object({
60
62
  onError: z.enum(["stop", "retry"]).optional(),
61
63
  retryDelayMs: z.number().int().min(1_000).optional(),
62
64
  tasks: z.array(TaskSchema).optional(),
65
+ /**
66
+ * MCP servers (#67). Validated here so a bad entry fails the SAVE with a readable
67
+ * message instead of surfacing later as a tool that never appears: a stdio server
68
+ * needs a command, a network one needs a url, and the name is what namespaces every
69
+ * tool it exposes.
70
+ */
71
+ mcpServers: z
72
+ .array(z
73
+ .object({
74
+ name: z.string().min(1, "MCP server name required"),
75
+ url: z.string().optional(),
76
+ command: z.string().optional(),
77
+ args: z.array(z.string()).optional(),
78
+ env: z.record(z.string(), z.string()).optional(),
79
+ headers: z.record(z.string(), z.string()).optional(),
80
+ transport: z.enum(["http", "sse", "stdio"]).optional(),
81
+ enabled: z.boolean().optional(),
82
+ timeoutMs: z.number().int().min(1_000).optional(),
83
+ })
84
+ .refine((v) => Boolean(v.url || v.command), {
85
+ message: "an MCP server needs a url or a command",
86
+ })
87
+ .refine((v) => v.transport !== "stdio" || Boolean(v.command), {
88
+ message: "stdio transport requires a command",
89
+ }))
90
+ .optional(),
63
91
  });
64
92
  /** Format a ZodError into a compact operator-readable message. */
65
93
  export function formatZodError(error) {
package/dist/master.js CHANGED
@@ -15,6 +15,8 @@ import { spawn } from "node:child_process";
15
15
  import { Agent } from "./agent/agent.js";
16
16
  import { parseSchedule, matches, nextFireAt } from "./scheduler/cron.js";
17
17
  import { bus } from "./bus.js";
18
+ import { mcp } from "./agent/mcp-registry.js";
19
+ import { loadPlugins } from "./agent/plugins.js";
18
20
  import { fetchModelList, peekModelList, contextLengthFor, isReasoningEffort, } from "./model-meta.js";
19
21
  /** how deep sub-agent spawning may nest (parent=0, its subs=1, …) */
20
22
  /**
@@ -392,6 +394,8 @@ export function sanitizeAgentId(id) {
392
394
  }
393
395
  export class Master {
394
396
  agents = new Map();
397
+ /** Agent Plugins loaded at boot (#162); their skill roots are offered to every agent */
398
+ plugins = [];
395
399
  /**
396
400
  * ONE key pool per provider name (#170), shared by every agent on it.
397
401
  *
@@ -630,6 +634,18 @@ export class Master {
630
634
  }
631
635
  if (patch.maxSpawnDepth !== undefined)
632
636
  this.config.maxSpawnDepth = patch.maxSpawnDepth;
637
+ // #67: the registry is applied by the caller (it also connects); this only
638
+ // records the list so a restart comes back with the same servers.
639
+ if (patch.mcpServers !== undefined)
640
+ this.config.mcpServers = patch.mcpServers;
641
+ if (patch.shortContext !== undefined) {
642
+ this.config.shortContext = patch.shortContext;
643
+ // apply to LIVE agents too: the mode is read every turn, so a restart should not
644
+ // be the price of switching it
645
+ for (const a of this.agents.values())
646
+ a.opts.shortContext =
647
+ patch.shortContext;
648
+ }
633
649
  if (patch.maxTurnsPerRound !== undefined)
634
650
  this.config.maxTurnsPerRound = patch.maxTurnsPerRound;
635
651
  if (patch.onError !== undefined)
@@ -668,6 +684,35 @@ export class Master {
668
684
  }
669
685
  this.saveConfig();
670
686
  }
687
+ /**
688
+ * Load Agent Plugins (#162) and merge their MCP servers with the configured ones.
689
+ *
690
+ * Separate from `start()` so it can be exercised without booting a server: this is
691
+ * where plugin servers get QUALIFIED with their plugin name, and a naming collision
692
+ * here silently makes one plugin's tools disappear.
693
+ */
694
+ async loadPluginsAndMcp() {
695
+ const pluginMcp = [];
696
+ if (this.config.pluginsDir !== false) {
697
+ const dir = this.config.pluginsDir ?? path.join(CONFIG_DIR, "plugins");
698
+ const { plugins, errors } = await loadPlugins(dir, path.join(DATA_DIR, "plugin-data"));
699
+ this.plugins = plugins;
700
+ for (const e of errors)
701
+ console.error(`[teapot] skipping plugin ${e.dir}: ${e.error}`);
702
+ for (const p of plugins) {
703
+ for (const w of p.warnings)
704
+ console.error(`[teapot] plugin "${p.name}": ${w}`);
705
+ // QUALIFY each server with its plugin name. A plugin's own `mcp.json` names its
706
+ // servers locally ("db"), and two plugins may each have one — the registry keys
707
+ // by name, so an unqualified collision would silently replace one with the other
708
+ // and its tools would appear to vanish. The plugin name is the natural prefix.
709
+ pluginMcp.push(...p.mcpServers.map((s) => ({ ...s, name: `${p.name}:${s.name}` })));
710
+ }
711
+ if (plugins.length)
712
+ console.error(`[teapot] loaded ${plugins.length} plugin(s): ${plugins.map((p) => p.name).join(", ")}`);
713
+ }
714
+ return [...(this.config.mcpServers ?? []), ...pluginMcp];
715
+ }
671
716
  async start() {
672
717
  mkdirSync(this.config.dataDir, { recursive: true });
673
718
  // #144: ONE config write for the whole boot instead of one per agent.
@@ -691,6 +736,20 @@ export class Master {
691
736
  // resolved — instead of the requests being serialised behind the agent loop,
692
737
  // where a slow endpoint's timeout is paid again and again.
693
738
  this.prefetchModelLists();
739
+ // #67: connect configured MCP servers in the background. Deliberately NOT
740
+ // awaited: a slow or unreachable server must not delay listening, and its tools
741
+ // appear as the connection lands (an agent's next turn picks them up because
742
+ // `allToolSpecs()` reads the registry each call).
743
+ // #162: Agent Plugins contribute skill roots and MCP servers. Loaded BEFORE the
744
+ // MCP connect below so a plugin's servers connect in the same pass as configured
745
+ // ones, and before any agent starts so its skills are discoverable on turn one.
746
+ if (this.config.mcpServers?.length || this.config.pluginsDir !== false) {
747
+ const allMcp = await this.loadPluginsAndMcp();
748
+ if (allMcp.length) {
749
+ mcp.apply(allMcp);
750
+ void mcp.connectAll();
751
+ }
752
+ }
694
753
  try {
695
754
  for (const ac of this.config.agents) {
696
755
  // archived agents keep their config entry and their history but do not run;
@@ -919,6 +978,15 @@ export class Master {
919
978
  ...(this.config.onError ? { onError: this.config.onError } : {}),
920
979
  ...(this.config.retryDelayMs ? { retryDelayMs: this.config.retryDelayMs } : {}),
921
980
  autoContinue: ac.autoContinue ?? true,
981
+ // BUG found while wiring #161: `autoCompact` was a field on AgentConfig and on
982
+ // AgentOptions, but nothing ever carried it between the two — so a configured
983
+ // `"autoCompact": false` was silently ignored and compaction stayed on. Passed
984
+ // here for the same reason as shortContext: a config knob that does nothing is
985
+ // worse than no knob.
986
+ ...(ac.autoCompact === false ? { autoCompact: false } : {}),
987
+ // #161: per-agent choice, else the global default. This mode DISCARDS information
988
+ // early by design, so it must never switch on by accident.
989
+ ...((ac.shortContext ?? this.config.shortContext) ? { shortContext: true } : {}),
922
990
  ...(this.config.contextTokenBudget ? { contextTokenBudget: this.config.contextTokenBudget } : {}),
923
991
  ...(ac.contextWindowTokens || this.config.contextWindowTokens || inferredWindow
924
992
  ? {
@@ -929,6 +997,11 @@ export class Master {
929
997
  : {}),
930
998
  globalSkillsDir: path.join(CONFIG_DIR, "skills"),
931
999
  bundledSkillsDir: BUNDLED_SKILLS_DIR,
1000
+ // #162: a plugin's own skills/ is a skill root, ranked with the global ones so
1001
+ // a workspace skill still wins on a name clash
1002
+ pluginSkillRoots: this.plugins
1003
+ .filter((p) => p.skillsDir)
1004
+ .map((p) => ({ dir: p.skillsDir, source: `plugin:${p.name}` })),
932
1005
  provider: provName,
933
1006
  spawnDepth: myDepth,
934
1007
  ...(ac.readOnly ? { readOnlyTools: true } : {}),