pi-braid 0.42.0 → 0.42.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -34,6 +34,7 @@
34
34
 
35
35
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
36
36
  import { Type } from "typebox";
37
+ import type { Static } from "typebox";
37
38
  import { createLogger } from "../../../lib/core/logger.js";
38
39
  import { getSkillsRankingMode } from "../../../lib/config/braid-settings.js";
39
40
  import type { SkillsRankingMode } from "../../../lib/config/braid-settings.js";
@@ -55,6 +56,7 @@ import {
55
56
  readSkillReach,
56
57
  } from "./reach.js";
57
58
  import { getMonthlyAdoptionRollup } from "./session-records.js";
59
+ import { checkArgumentValues } from "../../../lib/utils/argument-report.js";
58
60
 
59
61
  const log = createLogger("skills-tool");
60
62
 
@@ -252,6 +254,52 @@ function rowOf(row: RankedSkill): RowRelevance {
252
254
 
253
255
  // Extension factory:
254
256
 
257
+ /**
258
+ * `list_skills` arguments: one action, one page of the catalog.
259
+ *
260
+ * The action is named here rather than inferred, because a pager call and a
261
+ * full-catalog call are the same call and the schema is what the model reads
262
+ * before choosing. The tool fills it when the call omits it (`prepareArguments`
263
+ * below), so a bare pager call behaves as the listing it obviously is while an
264
+ * unknown action is still refused.
265
+ */
266
+ const listSkillsSchema = Type.Object({
267
+ action: Type.Literal("list", {
268
+ description:
269
+ "list = paginated catalog with per-skill reach (reachable, lines, bytes, chars, estTokens, sectionCount, sections)",
270
+ }),
271
+ page: Type.Optional(
272
+ Type.Number({
273
+ minimum: 1,
274
+ default: 1,
275
+ description: "Page number for list (1-based)",
276
+ }),
277
+ ),
278
+ pageSize: Type.Optional(
279
+ Type.Number({
280
+ minimum: 1,
281
+ maximum: 50,
282
+ default: 10,
283
+ description: "Entries per page for list",
284
+ }),
285
+ ),
286
+ sectionsMax: Type.Optional(
287
+ Type.Number({
288
+ minimum: 0,
289
+ maximum: SECTIONS_MAX_LIMIT,
290
+ default: DEFAULT_SECTIONS_MAX,
291
+ description: "Headings reported per skill; 0 omits the section list and keeps sectionCount",
292
+ }),
293
+ ),
294
+ rank: Type.Optional(
295
+ Type.Union([Type.Literal("relevance"), Type.Literal("catalog")], {
296
+ default: "relevance",
297
+ description:
298
+ "relevance (default) = order by fit to the current task; catalog = the plain catalog order, with no ranking fields",
299
+ }),
300
+ ),
301
+ });
302
+
255
303
  export default function skillsToolExtension(pi: ExtensionAPI): void {
256
304
  registerAutoInject(pi);
257
305
 
@@ -260,43 +308,18 @@ export default function skillsToolExtension(pi: ExtensionAPI): void {
260
308
  label: "List Skills",
261
309
  description:
262
310
  "Discover skills on demand: paginated catalog (name, filePath, description, source) plus each skill's reach (reachable, lines, bytes, chars, estTokens, sectionCount, section headings with line numbers), so the price of a read is visible before the read. Rows are ordered by relevance to the current task; a row with match evidence carries relevance {score, reason}, and the response carries ranking {tier, basis, policy}. Pass rank: 'catalog' for the plain catalog order. `read` a SKILL.md to load it.",
263
- parameters: Type.Object({
264
- action: Type.Literal("list", {
265
- description:
266
- "list = paginated catalog with per-skill reach (reachable, lines, bytes, chars, estTokens, sectionCount, sections)",
267
- }),
268
- page: Type.Optional(
269
- Type.Number({
270
- minimum: 1,
271
- default: 1,
272
- description: "Page number for list (1-based)",
273
- }),
274
- ),
275
- pageSize: Type.Optional(
276
- Type.Number({
277
- minimum: 1,
278
- maximum: 50,
279
- default: 10,
280
- description: "Entries per page for list",
281
- }),
282
- ),
283
- sectionsMax: Type.Optional(
284
- Type.Number({
285
- minimum: 0,
286
- maximum: SECTIONS_MAX_LIMIT,
287
- default: DEFAULT_SECTIONS_MAX,
288
- description:
289
- "Headings reported per skill; 0 omits the section list and keeps sectionCount",
290
- }),
291
- ),
292
- rank: Type.Optional(
293
- Type.Union([Type.Literal("relevance"), Type.Literal("catalog")], {
294
- default: "relevance",
295
- description:
296
- "relevance (default) = order by fit to the current task; catalog = the plain catalog order, with no ranking fields",
297
- }),
298
- ),
299
- }),
311
+ parameters: listSkillsSchema,
312
+ // Paging without an action is a listing call: fill the action the call
313
+ // implies before pi validates, and refuse a guessed value with the accepted
314
+ // one named. The schema above stays the only description of the contract.
315
+ prepareArguments: (args: unknown) => {
316
+ const prepared =
317
+ args && typeof args === "object" && (args as { action?: unknown }).action == null
318
+ ? { ...args, action: "list" }
319
+ : args;
320
+ checkArgumentValues("list_skills", listSkillsSchema, prepared);
321
+ return prepared as Static<typeof listSkillsSchema>;
322
+ },
300
323
  execute: async (_id, params, signal, _onUpdate, ctx) => {
301
324
  const page = (params.page as number) ?? 1;
302
325
  const pageSize = (params.pageSize as number) ?? 10;
@@ -49,6 +49,7 @@ import errorCaptureFn from "./self/error-tracking/index.js";
49
49
  import watchdogFn from "./self/watchdog/index.js";
50
50
  import autoRecoveryFn from "./self/auto-recovery/index.js";
51
51
  import latentActivatorFn from "./self/latent-activator/index.js";
52
+ import pathMissFn from "./self/path-miss/index.js";
52
53
 
53
54
  // enforcement (turn pipeline: handlers, detection, substate)
54
55
  import enforcementFn from "./enforcement/index.js";
@@ -224,6 +225,11 @@ export const MANIFEST: ManifestEntry[] = [
224
225
  fn: latentActivatorFn,
225
226
  desc: "Latent behavior activator",
226
227
  },
228
+ {
229
+ id: "path-miss",
230
+ fn: pathMissFn,
231
+ desc: "Path-miss steer — name the listing that answers a missing path",
232
+ },
227
233
 
228
234
  // Watchdog (default-ON — liveness/stall state machine)
229
235
  // Default-ON per TG-HEARTBEAT-WATCHDOG-DESIGN.md ("default ON, NO new env
@@ -14,11 +14,12 @@ because they're specialized tools the user enables when they want them.
14
14
  | `watchdog/` | (TUI command) | Passive session monitor: uptime, idle time, message count. No LLM tool. |
15
15
  | `auto-recovery/` | (whisper-only) | On turn_start, checks for system degradation and suggests recovery. |
16
16
  | `latent-activator/` | `behavior` | Activates atomic behavior modes (planner, executor, reviewer, etc). |
17
+ | `path-miss/` | (whisper-only) | On a tool result that missed a path, names the listing that finds it. |
17
18
 
18
19
  ## Local Contracts
19
20
 
20
21
  - Most are **opt-in** (`disabledByDefault: true` in the manifest).
21
- - `auto-recovery` and `latent-activator` are always-on.
22
+ - `auto-recovery`, `latent-activator` and `path-miss` are always-on.
22
23
  - These extensions manipulate the agent's own state, not external state.
23
24
 
24
25
  ## Distinction from related categories
@@ -0,0 +1,39 @@
1
+ <!-- status: current -->
2
+
3
+ # src/extensions/self/path-miss/ - Path-Miss Steer
4
+
5
+ When a tool result reports a missing path, one whisper says which move would
6
+ have found it. The failure is the moment the cheaper instrument is obvious;
7
+ without it the agent guesses again.
8
+
9
+ ## Files
10
+
11
+ | File | Purpose |
12
+ | ----------- | ---------------------------------------------------------------------------------------------------- |
13
+ | `index.ts` | The emitter: subscribes to tool results, holds the budget, sends through `sendTrackedMessage`. |
14
+ | `detect.ts` | Recognises a missing-path failure and names the path. Pure: no state, no delivery, no extension API. |
15
+
16
+ ## Local Contracts
17
+
18
+ - **One line per turn, at most one line per path per session.** The turn flag
19
+ is reset by the `input` handler (the same boundary the whisper family uses);
20
+ the per-path set is keyed on the session id and bounded.
21
+ - **No new event registration.** The emitter rides pi's existing `tool_result`
22
+ event, the only seat that carries both the failure text and the call's own
23
+ arguments - the call's `path` is stronger evidence than a parse of the
24
+ message.
25
+ - **Delivered as a live steer** (`delivery: "live"`), so it reaches a running
26
+ loop and never wakes one by itself.
27
+ - **A suppressed send does not spend the path's budget.** If the whisper funnel
28
+ drops the line, the path stays steerable.
29
+ - **Only a missing path is a path miss.** `EACCES`, an unreadable file and a
30
+ failed assertion each call for a different next move.
31
+ - Tool coverage: `read`, `edit`, `write`, `bash`. A failure from any other tool
32
+ is not classified, whatever its text says.
33
+
34
+ ## Related modules
35
+
36
+ - `lib/utils/injection-tracker.ts` - `sendTrackedMessage`, the delivery trunk
37
+ (envelope, flood cap, delivery class).
38
+ - `extensions/self/auto-recovery/` and `extensions/self/watchdog/` - the
39
+ neighbouring whisper emitters.
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Recognition of a missing-path tool failure, and the path it names.
3
+ *
4
+ * The shapes below are the ones the tools actually emit on this platform,
5
+ * measured rather than invented:
6
+ *
7
+ * read ENOENT: no such file or directory, access '/x/y.ts'
8
+ * edit Could not edit file: /x/y.ts. Error code: ENOENT.
9
+ * bash ls: /x/y: No such file or directory
10
+ * bash /bin/bash: line 0: cd: /x/y: No such file or directory
11
+ *
12
+ * Two of those carry a usable path in the call and the rest only in the text,
13
+ * so the call wins when it has one: a path the model asked for is the path the
14
+ * whisper should name, even when the tool's own wording echoes it loosely.
15
+ *
16
+ * Only a missing path is a path miss. A permission error, an unreadable file
17
+ * or a failed assertion is a different failure with a different next move, and
18
+ * steering toward `ls` there would cost a call without teaching anything.
19
+ */
20
+
21
+ /** Tools whose failure can mean "the path was a guess". */
22
+ const PATH_BEARING_TOOLS = new Set(["read", "edit", "write", "bash"]);
23
+
24
+ /** The two spellings of "this path is not there" the tools emit. */
25
+ const MISSING_PATH = /ENOENT|no such file or directory/i;
26
+
27
+ /** A path quoted by a Node error: `ENOENT: ..., access '/x/y'`. */
28
+ const QUOTED_AFTER_SYSCALL =
29
+ /\b(?:access|open|stat|lstat|scandir|opendir|unlink|readlink)\s+'([^']+)'/;
30
+
31
+ /** A shell builtin naming the directory it could not enter. */
32
+ const BASH_CD_TARGET = /(?:^|[:\s])cd:\s+(.+?):\s*no such file/i;
33
+
34
+ /** A program naming the operand it could not find: `ls: /x/y: No such file`. */
35
+ const PROGRAM_OPERAND = /([^\s:]+):\s*no such file or directory/i;
36
+
37
+ /** A bare errno (`ENOENT`), not a path. */
38
+ const ERRNO_ONLY = /^[A-Z][A-Z0-9_]*$/;
39
+
40
+ export interface PathMiss {
41
+ /** The tool whose call missed. */
42
+ tool: string;
43
+ /** The path that was not there, as the tool or the call reported it. */
44
+ path: string;
45
+ }
46
+
47
+ /** The path the call itself asked for, when the tool takes one. */
48
+ function pathFromCall(input: unknown): string | undefined {
49
+ if (!input || typeof input !== "object") return undefined;
50
+ const path = (input as { path?: unknown }).path;
51
+ return typeof path === "string" && path.length > 0 ? path : undefined;
52
+ }
53
+
54
+ /** The path an error message names, when the call did not carry one. */
55
+ function pathFromText(text: string): string | undefined {
56
+ const candidates = [
57
+ QUOTED_AFTER_SYSCALL.exec(text)?.[1],
58
+ BASH_CD_TARGET.exec(text)?.[1],
59
+ PROGRAM_OPERAND.exec(text)?.[1],
60
+ ];
61
+ for (const candidate of candidates) {
62
+ const path = candidate?.trim();
63
+ if (!path || ERRNO_ONLY.test(path)) continue;
64
+ return path;
65
+ }
66
+ return undefined;
67
+ }
68
+
69
+ /**
70
+ * The path a failed call missed, or null when this result is not a path miss.
71
+ */
72
+ export function detectPathMiss(toolName: string, input: unknown, text: string): PathMiss | null {
73
+ if (!PATH_BEARING_TOOLS.has(toolName)) return null;
74
+ if (!text || !MISSING_PATH.test(text)) return null;
75
+ const path = pathFromCall(input) ?? pathFromText(text);
76
+ if (!path) return null;
77
+ return { tool: toolName, path };
78
+ }
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Path-miss steer — the tool failure that says what would have worked.
3
+ *
4
+ * A turn that guesses paths spends calls discovering a layout a listing would
5
+ * have named. The failure itself is the one moment the cheaper move is
6
+ * obvious, so it is where the line belongs: one steer per turn, the path that
7
+ * missed, and the three instruments that answer it (`ls`, `find`,
8
+ * `explore_paths`).
9
+ *
10
+ * Delivery is the standard whisper funnel (`sendTrackedMessage`), so this
11
+ * emitter inherits the envelope, the flood cap and the live-steer resolution
12
+ * every other whisper uses. The event is pi's existing `tool_result`, the only
13
+ * seat that carries both the failure text and the arguments the call made —
14
+ * the call's own `path` is more reliable than parsing the error wording.
15
+ *
16
+ * Budget: one line per turn, at most one line per path per session. A path
17
+ * already steered is not steered again, because a repeat tells the agent
18
+ * nothing it was not told, and the second occurrence usually means the agent
19
+ * chose to proceed rather than that it failed to read.
20
+ */
21
+
22
+ import { dirname } from "node:path";
23
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
24
+ import { createLogger } from "../../../lib/core/logger.js";
25
+ import { INPUT, TOOL_RESULT } from "../../../lib/core/event-names.js";
26
+ import { sendTrackedMessage } from "../../../lib/utils/injection-tracker.js";
27
+ import { detectPathMiss } from "./detect.js";
28
+
29
+ const log = createLogger("path-miss");
30
+
31
+ /**
32
+ * Sessions whose steered paths are remembered. A session id is stable for the
33
+ * life of a session and a long-lived process can host more than one, so the
34
+ * map is bounded rather than trusted to stay small.
35
+ */
36
+ const MAX_TRACKED_SESSIONS = 16;
37
+
38
+ /** Paths already steered, per session. */
39
+ const steeredPaths = new Map<string, Set<string>>();
40
+
41
+ /** Turn-scoped: the first path miss of a turn is the one worth a line. */
42
+ let steeredThisTurn = false;
43
+
44
+ function sessionKey(ctx: ExtensionContext | undefined): string {
45
+ const manager = ctx?.sessionManager as
46
+ | { getSessionId?: () => string; getSessionFile?: () => string | undefined }
47
+ | undefined;
48
+ return manager?.getSessionId?.() ?? manager?.getSessionFile?.() ?? "unknown";
49
+ }
50
+
51
+ function remember(session: string, path: string): void {
52
+ const paths = steeredPaths.get(session) ?? new Set<string>();
53
+ paths.add(path);
54
+ steeredPaths.set(session, paths);
55
+ if (steeredPaths.size > MAX_TRACKED_SESSIONS) {
56
+ // Insertion order: the oldest session is the first key.
57
+ const oldest = steeredPaths.keys().next().value;
58
+ if (oldest !== undefined && oldest !== session) steeredPaths.delete(oldest);
59
+ }
60
+ }
61
+
62
+ function alreadySteered(session: string, path: string): boolean {
63
+ return steeredPaths.get(session)?.has(path) ?? false;
64
+ }
65
+
66
+ /** The error text of a tool result, with any non-text parts ignored. */
67
+ function resultText(content: unknown): string {
68
+ if (typeof content === "string") return content;
69
+ if (!Array.isArray(content)) return "";
70
+ return content
71
+ .map((part) =>
72
+ part && typeof part === "object" && typeof (part as { text?: unknown }).text === "string"
73
+ ? (part as { text: string }).text
74
+ : "",
75
+ )
76
+ .join("\n");
77
+ }
78
+
79
+ /**
80
+ * One line: the path, and the cheaper moves next to it.
81
+ *
82
+ * The parent is named when the path has one, because `ls` needs an operand and
83
+ * a model that guessed a leaf usually had the parent wrong too — listing the
84
+ * parent is what tells it which of the two it got wrong.
85
+ */
86
+ export function pathMissLine(path: string): string {
87
+ const parent = dirname(path);
88
+ const listing = parent && parent !== "." && parent !== "/" ? `ls ${parent}` : "ls on its parent";
89
+ return `path miss: ${path} — ${listing} names the layout in one call; find and explore_paths when the parent is unknown too`;
90
+ }
91
+
92
+ /** Test hook: forget every steered path and the current turn's budget. */
93
+ export function _resetForTests(): void {
94
+ steeredPaths.clear();
95
+ steeredThisTurn = false;
96
+ }
97
+
98
+ export default function pathMissExtension(pi: ExtensionAPI): void {
99
+ // The same turn boundary the whisper family uses: a new user input opens a
100
+ // new turn, and a turn that has already been steered is done.
101
+ pi.on(INPUT, () => {
102
+ steeredThisTurn = false;
103
+ });
104
+
105
+ pi.on(TOOL_RESULT, (event, ctx) => {
106
+ if (steeredThisTurn) return;
107
+ if (!event?.isError) return;
108
+ const miss = detectPathMiss(event.toolName, event.input, resultText(event.content));
109
+ if (!miss) return;
110
+
111
+ const session = sessionKey(ctx);
112
+ if (alreadySteered(session, miss.path)) return;
113
+
114
+ steeredThisTurn = true;
115
+ const delivered = sendTrackedMessage(
116
+ pi,
117
+ {
118
+ customType: "path-miss",
119
+ content: [{ type: "text" as const, text: pathMissLine(miss.path) }],
120
+ display: true,
121
+ },
122
+ { delivery: "live" },
123
+ { type: "enforcement", source: "path-miss/steer" },
124
+ );
125
+ // A suppressed send must not spend the path's budget: the line did not
126
+ // arrive, so the next turn is still the first place the agent can read it.
127
+ if (!delivered) {
128
+ steeredThisTurn = false;
129
+ log.debug(`[path-miss] suppressed by the whisper funnel: ${miss.path}`);
130
+ return;
131
+ }
132
+ remember(session, miss.path);
133
+ log.debug(`[path-miss] steered ${miss.path} (${miss.tool})`);
134
+ });
135
+ }
@@ -23,6 +23,7 @@ export const MESSAGE_START = "message_start" as const;
23
23
  export const MESSAGE_END = "message_end" as const;
24
24
  export const TOOL_EXECUTION_START = "tool_execution_start" as const;
25
25
  export const TOOL_EXECUTION_END = "tool_execution_end" as const;
26
+ export const TOOL_RESULT = "tool_result" as const;
26
27
  export const AGENT_SETTLED = "agent_settled" as const;
27
28
 
28
29
  // ── Extension Communication ─────────────────────────────────────────────────
@@ -19,6 +19,7 @@ Misc utilities that don't fit a more specific subdir.
19
19
  | `error-guard.ts` | Wraps handler errors with logging and recovery. |
20
20
  | `async-fs.ts` | Async filesystem primitives (`asyncExists`). Replaces duplicate `existsSync` checks. |
21
21
  | `format-tool-result.ts` | Structured Output Catalyst - wraps tool output in consistent TOOL/STATUS/RESULT header format. MDA research (2601.21996) backing. |
22
+ | `argument-report.ts` | Builds the refusal text a tool-argument rejection carries: the accepted values and a required field's stated purpose, both read from the tool's own schema at the moment the message is built (no second copy to drift). Used from a tool's `prepareArguments`, which pi calls before its own validation. |
22
23
 
23
24
  ## Local Contracts
24
25
 
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Tool-argument refusal text.
3
+ *
4
+ * pi validates a tool call against its schema and reports the failure in
5
+ * schema terms: an out-of-list value says "must be equal to one of the allowed
6
+ * values", a missing required field says "must have required properties
7
+ * decision". Neither names the values, so the model that guessed one learns
8
+ * nothing it can act on and guesses again.
9
+ *
10
+ * The accepted values, and the sentence explaining a required field, are
11
+ * already in the schema. This module reads them from there at the moment the
12
+ * refusal is built: no list is written twice, so no copy can drift from the
13
+ * one the validator enforces.
14
+ *
15
+ * Seat: a tool's `prepareArguments`. pi calls it first, inside the same
16
+ * guarded block as its own schema validation, so a throw here is what the
17
+ * model reads — and the schema stays exactly as strict as it was. The checks
18
+ * below are equivalences, not relaxations: a call refused here is one pi would
19
+ * have refused too, only with a message the model can use.
20
+ *
21
+ * Scope is the top level of the argument object. A nested list is left to pi
22
+ * rather than described from a guess about its parent.
23
+ */
24
+
25
+ /** A schema node, as far as this module needs to read it. */
26
+ interface SchemaNode {
27
+ const?: unknown;
28
+ enum?: unknown;
29
+ anyOf?: unknown;
30
+ oneOf?: unknown;
31
+ description?: unknown;
32
+ properties?: unknown;
33
+ required?: unknown;
34
+ [keyword: string]: unknown;
35
+ }
36
+
37
+ function nodeOf(value: unknown): SchemaNode | undefined {
38
+ return value && typeof value === "object" ? (value as SchemaNode) : undefined;
39
+ }
40
+
41
+ /**
42
+ * The values a schema node accepts, read from the node.
43
+ *
44
+ * A single-valued node (`const`, which is what `Type.Literal` builds) yields
45
+ * one value; an `enum` yields its list; a union of those yields all of them.
46
+ * A node that constrains nothing yields no values, and the caller then leaves
47
+ * the message to pi.
48
+ */
49
+ export function acceptedValues(node: unknown): string[] {
50
+ const schema = nodeOf(node);
51
+ if (!schema) return [];
52
+ if (typeof schema.const === "string") return [schema.const];
53
+ if (Array.isArray(schema.enum) && schema.enum.every((v) => typeof v === "string")) {
54
+ return [...new Set(schema.enum as string[])];
55
+ }
56
+ const branches = Array.isArray(schema.anyOf)
57
+ ? schema.anyOf
58
+ : Array.isArray(schema.oneOf)
59
+ ? schema.oneOf
60
+ : undefined;
61
+ if (!branches) return [];
62
+ return [...new Set(branches.flatMap((branch) => acceptedValues(branch)))];
63
+ }
64
+
65
+ function quoted(value: string): string {
66
+ return JSON.stringify(value);
67
+ }
68
+
69
+ /**
70
+ * Throw the refusal a model can act on, when this module can say more than the
71
+ * validator does. Returns silently otherwise, leaving pi's own message intact.
72
+ *
73
+ * `schema` is the same object the tool declares as its `parameters`, and
74
+ * `args` the arguments the call carried.
75
+ */
76
+ export function checkArgumentValues(toolName: string, schema: unknown, args: unknown): void {
77
+ const root = nodeOf(schema);
78
+ const properties = nodeOf(root?.properties);
79
+ const input = nodeOf(args);
80
+ if (!root || !properties || !input) return;
81
+
82
+ // A required field with a stated purpose: say both, once.
83
+ if (Array.isArray(root.required)) {
84
+ for (const key of root.required) {
85
+ if (typeof key !== "string") continue;
86
+ const value = (input as Record<string, unknown>)[key];
87
+ if (value !== undefined && value !== null) continue;
88
+ const purpose = nodeOf(properties[key])?.description;
89
+ if (typeof purpose !== "string" || purpose.length === 0) continue;
90
+ throw new Error(`${toolName}: ${key} is required (${purpose})`);
91
+ }
92
+ }
93
+
94
+ // A value outside its declared list: name the list.
95
+ for (const [key, raw] of Object.entries(input as Record<string, unknown>)) {
96
+ if (typeof raw !== "string") continue;
97
+ const values = acceptedValues(properties[key]);
98
+ if (values.length === 0 || values.includes(raw)) continue;
99
+ throw new Error(
100
+ `${toolName}: ${key} ${quoted(raw)} is not accepted. Accepted: ${values
101
+ .map(quoted)
102
+ .join(", ")}`,
103
+ );
104
+ }
105
+ }