teapot-coding-agent 0.29.28 → 0.29.29

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) {
@@ -2233,6 +2234,24 @@ export function repairToolInput(name, rawArgs) {
2233
2234
  return { args, notes };
2234
2235
  }
2235
2236
  export async function executeTool(name, rawArgs, ctx) {
2237
+ // MCP tools are namespaced (`mcp__server__tool`) so they can never reach this point
2238
+ // by shadowing a built-in. Dispatched BEFORE the built-in lookup because there is no
2239
+ // static TOOLS entry to find — the tool list belongs to the server.
2240
+ if (name.startsWith(MCP_PREFIX)) {
2241
+ if (ctx.signal?.aborted)
2242
+ return { ok: false, result: "aborted (harness shutdown)" };
2243
+ let args = {};
2244
+ try {
2245
+ args = rawArgs.trim() ? JSON.parse(rawArgs) : {};
2246
+ }
2247
+ catch {
2248
+ return { ok: false, result: `${name}: arguments are not valid JSON` };
2249
+ }
2250
+ const r = await mcp.call(name, args);
2251
+ if (!r)
2252
+ return { ok: false, result: `unknown tool: ${name}` };
2253
+ return { ok: r.ok, result: r.text };
2254
+ }
2236
2255
  const def = TOOLS.find((t) => t.name === name);
2237
2256
  if (!def)
2238
2257
  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 } : {}),
@@ -53,6 +53,8 @@ async function listModels(baseUrl, apiKey) {
53
53
  import path from "node:path";
54
54
  import { bus } from "../bus.js";
55
55
  import { readEvents, readEventsTail, filterByBranch } from "../log/events.js";
56
+ import { mcp } from "../agent/mcp-registry.js";
57
+ import { connectMcp } from "../agent/mcp.js";
56
58
  /** media categories the file tree can preview inline */
57
59
  const IMAGE_EXT = new Set(["png", "jpg", "jpeg", "gif", "webp", "svg", "bmp", "ico", "avif"]);
58
60
  const VIDEO_EXT = new Set(["mp4", "webm", "mov", "mkv", "avi", "m4v"]);
@@ -355,11 +357,9 @@ export function buildApp(master) {
355
357
  : spawn(shell, [], { cwd: agent.workspace, env: { ...env, TERM: "dumb" } });
356
358
  console.log(`[teapot] ⌨ terminal open: ${agentId} @ ${agent.workspace} (${hasScript ? "pty" : "pipe"})`);
357
359
  child.stdout?.on("data", (b) => {
358
- termSizes.markBusy(child);
359
360
  send({ kind: "data", data: b.toString("utf8") });
360
361
  });
361
362
  child.stderr?.on("data", (b) => {
362
- termSizes.markBusy(child);
363
363
  send({ kind: "data", data: b.toString("utf8") });
364
364
  });
365
365
  child.on("close", (code) => {
@@ -826,14 +826,90 @@ export function buildApp(master) {
826
826
  onError: patch.onError,
827
827
  retryDelayMs: patch.retryDelayMs,
828
828
  maxSpawnDepth: patch.maxSpawnDepth,
829
+ shortContext: patch.shortContext,
829
830
  tasks: patch.tasks,
831
+ mcpServers: patch.mcpServers,
830
832
  });
833
+ // #67: apply the new server list to the live registry and connect in the
834
+ // background — an added server's tools must appear on the next turn without a
835
+ // restart, and a removed one's connection must be closed now.
836
+ if (patch.mcpServers) {
837
+ mcp.apply(patch.mcpServers);
838
+ void mcp.connectAll();
839
+ }
831
840
  return c.json({ ok: true });
832
841
  }
833
842
  catch (err) {
834
843
  return c.json({ error: err.message }, 400);
835
844
  }
836
845
  });
846
+ // ---- MCP servers (#67) ----
847
+ //
848
+ // `test` is the endpoint the settings panel uses to answer "does this work?" before
849
+ // saving: it connects, lists tools, and reports the count or the exact failure. Doing
850
+ // that through `PUT /api/config` would mean saving a broken server first, and the
851
+ // failure would then surface on an agent's turn instead of in the panel that caused it.
852
+ app.get("/api/mcp", (c) => c.json({
853
+ servers: master.config.mcpServers ?? [],
854
+ states: mcp.states().map((s) => ({
855
+ name: s.config.name,
856
+ status: s.status,
857
+ tools: s.tools.length,
858
+ ...(s.lastError ? { lastError: s.lastError } : {}),
859
+ ...(s.lastChecked ? { lastChecked: s.lastChecked } : {}),
860
+ })),
861
+ }));
862
+ // Agent Plugins (#162): what was loaded, and where from. Read-only on purpose —
863
+ // installing a plugin is a filesystem act, and a web endpoint that unpacks an
864
+ // archive is a much larger surface than this feature is worth.
865
+ app.get("/api/plugins", (c) => c.json({
866
+ pluginsDir: master.config.pluginsDir === false
867
+ ? null
868
+ : (master.config.pluginsDir ?? null),
869
+ plugins: master.plugins.map((p) => ({
870
+ name: p.name,
871
+ ...(p.version ? { version: p.version } : {}),
872
+ ...(p.description ? { description: p.description } : {}),
873
+ root: p.root,
874
+ skills: p.skills,
875
+ mcpServers: p.mcpServers.map((s) => s.name),
876
+ warnings: p.warnings,
877
+ })),
878
+ }));
879
+ app.post("/api/mcp/test", async (c) => {
880
+ const body = await c.req.json().catch(() => null);
881
+ if (!body?.name)
882
+ return c.json({ error: "a server needs a name" }, 400);
883
+ try {
884
+ const conn = await connectMcp({ ...body, enabled: true });
885
+ try {
886
+ const tools = await conn.tools();
887
+ return c.json({
888
+ ok: true,
889
+ tools: tools.map((t) => ({ name: t.name, description: t.description })),
890
+ });
891
+ }
892
+ finally {
893
+ await conn.close();
894
+ }
895
+ }
896
+ catch (err) {
897
+ const e = err;
898
+ return c.json({ ok: false, error: e.message, authRequired: Boolean(e.authRequired) }, 200);
899
+ }
900
+ });
901
+ app.post("/api/mcp/connect", async (c) => {
902
+ const body = await c.req.json().catch(() => null);
903
+ if (!body?.name)
904
+ return c.json({ error: "missing name" }, 400);
905
+ try {
906
+ const st = await mcp.connect(body.name);
907
+ return c.json({ ok: true, status: st.status, tools: st.tools.length });
908
+ }
909
+ catch (err) {
910
+ return c.json({ ok: false, error: err.message }, 200);
911
+ }
912
+ });
837
913
  app.get("/api/agents/:id", (c) => {
838
914
  const a = master.agents.get(c.req.param("id"));
839
915
  return a ? c.json(a.snapshot()) : notFound(c, "agent", c.req.param("id"));
@@ -69,8 +69,6 @@ function ptySlaveOf(pid) {
69
69
  }
70
70
  /** debounce window: long enough to collapse a drag, short enough to feel instant */
71
71
  export const TERM_RESIZE_DEBOUNCE_MS = 250;
72
- /** how long after output a terminal counts as "a program is running" */
73
- export const TERM_BUSY_MS = 400;
74
72
  export class TermSizeTracker {
75
73
  states = new Map();
76
74
  /**
@@ -78,7 +76,7 @@ export class TermSizeTracker {
78
76
  * debounce.
79
77
  */
80
78
  request(child, rows, cols, write) {
81
- const st = this.states.get(child) ?? { rows: 0, cols: 0, timer: null, busyUntil: 0 };
79
+ const st = this.states.get(child) ?? { rows: 0, cols: 0, timer: null };
82
80
  this.states.set(child, st);
83
81
  if (st.timer) {
84
82
  clearTimeout(st.timer);
@@ -87,7 +85,6 @@ export class TermSizeTracker {
87
85
  // already the applied size → nothing a shell could act on
88
86
  if (st.rows === rows && st.cols === cols)
89
87
  return;
90
- const wait = Math.max(0, st.busyUntil - Date.now());
91
88
  const apply = () => {
92
89
  st.timer = null;
93
90
  st.rows = rows;
@@ -99,26 +96,7 @@ export class TermSizeTracker {
99
96
  /* child exited mid-debounce */
100
97
  }
101
98
  };
102
- st.timer = setTimeout(() => {
103
- // output may have CONTINUED past the deadline this timer was computed
104
- // from (markBusy only extends busyUntil — it cannot reach an already
105
- // pending timer). Writing now would type stty into a running program,
106
- // so defer to whatever busy window remains.
107
- const remain = st.busyUntil - Date.now();
108
- if (remain > 0) {
109
- st.timer = setTimeout(apply, remain);
110
- return;
111
- }
112
- apply();
113
- }, wait > 0 ? wait : TERM_RESIZE_DEBOUNCE_MS);
114
- }
115
- /** a child produced output — defer resizes so we never type into it */
116
- markBusy(child, ms = TERM_BUSY_MS) {
117
- // create the entry if absent: output usually arrives long before the first
118
- // resize, and dropping the signal then let the resize land in the program
119
- const st = this.states.get(child) ?? { rows: 0, cols: 0, timer: null, busyUntil: 0 };
120
- this.states.set(child, st);
121
- st.busyUntil = Date.now() + ms;
99
+ st.timer = setTimeout(apply, TERM_RESIZE_DEBOUNCE_MS);
122
100
  }
123
101
  /** forget a child; cancels its pending resize so we can't write to a corpse */
124
102
  forget(child) {