pi-braid 0.41.2 → 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.
Files changed (34) hide show
  1. package/CHANGELOG.md +1006 -0
  2. package/build-info.json +4 -4
  3. package/dist/extensions/cognitive/metacognition/handlers/think.js +9 -0
  4. package/dist/extensions/core/prompt-builder/index.js +10 -11
  5. package/dist/extensions/core/skills-tool/auto-inject.d.ts +17 -2
  6. package/dist/extensions/core/skills-tool/auto-inject.js +100 -24
  7. package/dist/extensions/core/skills-tool/index.js +47 -26
  8. package/dist/extensions/core/skills-tool/loading-guidance.d.ts +149 -28
  9. package/dist/extensions/core/skills-tool/loading-guidance.js +257 -29
  10. package/dist/extensions/manifest.js +6 -0
  11. package/dist/extensions/self/path-miss/detect.d.ts +30 -0
  12. package/dist/extensions/self/path-miss/detect.js +67 -0
  13. package/dist/extensions/self/path-miss/index.d.ts +33 -0
  14. package/dist/extensions/self/path-miss/index.js +118 -0
  15. package/dist/lib/core/event-names.d.ts +1 -0
  16. package/dist/lib/core/event-names.js +1 -0
  17. package/dist/lib/utils/argument-report.d.ts +41 -0
  18. package/dist/lib/utils/argument-report.js +95 -0
  19. package/package.json +4 -3
  20. package/src/extensions/cognitive/metacognition/handlers/think.ts +9 -0
  21. package/src/extensions/core/AGENTS.md +8 -6
  22. package/src/extensions/core/prompt-builder/AGENTS.md +2 -2
  23. package/src/extensions/core/prompt-builder/index.ts +10 -14
  24. package/src/extensions/core/skills-tool/auto-inject.ts +138 -26
  25. package/src/extensions/core/skills-tool/index.ts +60 -37
  26. package/src/extensions/core/skills-tool/loading-guidance.ts +303 -29
  27. package/src/extensions/manifest.ts +6 -0
  28. package/src/extensions/self/AGENTS.md +2 -1
  29. package/src/extensions/self/path-miss/AGENTS.md +39 -0
  30. package/src/extensions/self/path-miss/detect.ts +78 -0
  31. package/src/extensions/self/path-miss/index.ts +135 -0
  32. package/src/lib/core/event-names.ts +1 -0
  33. package/src/lib/utils/AGENTS.md +1 -0
  34. package/src/lib/utils/argument-report.ts +105 -0
@@ -1,38 +1,129 @@
1
1
  /**
2
- * Skills-loading directive, owned by the skills-tool module.
2
+ * Skills floor, owned by the skills-tool module: the visible catalog section
3
+ * and the drift trigger that re-points at it.
3
4
  *
4
- * The skills-tool module owns the strategy text for using its own tool;
5
- * prompt-builder imports it and renders it as the "skills-loading" section
6
- * ONLY when both `read` and `list_skills` are active tools.
5
+ * prompt-builder imports the section text and renders it as the
6
+ * "skills-loading" section ONLY when both `read` and `list_skills` are active
7
+ * tools.
7
8
  *
8
- * Current rule: task-start list_skills puts the full catalog (name, path,
9
- * purpose) in view so the domain-match trigger is decidable; the catalog
10
- * one-liner is metadata, the SKILL.md path is the knowledge — no skill
11
- * content is injected into the prompt. The trigger has a mechanical form
12
- * (a tool call whose family word appears in a skill's name) because the
13
- * judgment form loses sessions that are inside a skill's domain by
14
- * construction. Decision logic lives in the prompt, mechanics in tool
15
- * descriptions (strategy-only contract; each fact in exactly one place).
9
+ * Why the catalog is rendered instead of described. A pointer the model has
10
+ * to redeem with a tool call is a probability, not a mechanism: the first
11
+ * prompt of a resumed session is thin ("let's pick up where we left off"),
12
+ * the catalog is one call away, and nothing in a thin prompt demands it.
13
+ * Rendering every visible skill as one `- name: description` row removes the
14
+ * redemption step, so a domain match needs only the task text in front of the
15
+ * model, not a decision to go look. The row is metadata; the file is still
16
+ * the knowledge, and the rule below says so.
17
+ *
18
+ * The read path is derived from the entries' own paths, never hardcoded: the
19
+ * same text renders for a checkout, an npm install tree, or a worktree. A
20
+ * catalog installed from more than one pack has no single root, so each
21
+ * directory heads its own group of rows instead of one root being named for
22
+ * all of them (a root that resolves for 22 rows and misdirects the other 5 is
23
+ * worse than no root at all).
16
24
  *
17
25
  * The mechanical trigger's worked examples are derived at assembly time from
18
- * the live tool and skill names (mechanicalTriggerExamples): a tool's family
19
- * token paired with an installed visible skill's dash-token. The text never
20
- * hardcodes a tool or skill name, so it cannot name a pair that does not
21
- * exist in the running session; when no pair computes, the sentence renders
22
- * without a parenthetical.
26
+ * the live tool and skill names: a tool's family token paired with an
27
+ * installed visible skill's dash-token. The text never hardcodes a tool or
28
+ * skill name, so it cannot name a pair that does not exist in the running
29
+ * session; when no pair computes, the sentence renders without a
30
+ * parenthetical.
31
+ *
32
+ * The same module owns the drift trigger (below): work that moves to a new
33
+ * directory is the moment a visible catalog stops matching the task text in
34
+ * view, and the trigger re-points at the catalog with one line. Its state is
35
+ * plain data and its decisions are pure functions, so the wiring lives in
36
+ * auto-inject.ts and the reasoning stays testable here.
37
+ */
38
+ import { isAbsolute, relative, resolve, sep } from "node:path";
39
+ /**
40
+ * Paragraph 1: what the catalog is, where the bodies live, and the obligation.
41
+ *
42
+ * `readRoot` is the single pack directory the rule can state; `grouped` says
43
+ * the rows are rendered under directory headings instead, so the rule points
44
+ * at the heading rather than at a root that does not exist. Neither given (a
45
+ * catalog whose bodies carry no pack) leaves the location unstated, which is
46
+ * the honest answer when the paths cannot be derived.
23
47
  */
24
- /** Paragraph 1: the discovery rule (pinned verbatim by test-prompt-budget.mjs). */
25
- export const SKILLS_DISCOVERY_RULE = `You discover skills on demand, not in advance: at the start of a task, call list_skills once to see the catalog (name, path, purpose). When the task enters a listed skill's domain, read the WHOLE SKILL.md before acting in that domain; never act from memory of a skill's contents.`;
48
+ export function skillsCatalogRule(readRoot, grouped = false) {
49
+ const readPath = readRoot
50
+ ? ` Each row's body is at \`${readRoot}/<name>/SKILL.md\`.`
51
+ : grouped
52
+ ? ` Each row's body is at \`<dir>/<name>/SKILL.md\`, where \`<dir>\` is the row's directory heading.`
53
+ : "";
54
+ return `This catalog is every installed skill: one row per skill, name and description.${readPath} When the task enters a listed skill's domain, read the WHOLE SKILL.md before acting in that domain; never act from memory of a skill's contents.`;
55
+ }
26
56
  /** Paragraph 2: the pointer rule (pinned verbatim by test-prompt-budget.mjs). */
27
- export const SKILLS_POINTER_RULE = `Pointer rule: the catalog one-liner is metadata, not content — the SKILL.md path is the knowledge. Mid-task, enter a domain absent from the visible catalog → call list_skills again (catalog is paginated). The prompt already covering the domain is the only reason to skip the read.`;
57
+ export const SKILLS_POINTER_RULE = `Pointer rule: the catalog one-liner is metadata, not content — the SKILL.md path is the knowledge. The prompt already covering the domain is the only reason to skip the read.`;
28
58
  const MECHANICAL_TRIGGER_LEAD = `Mechanical trigger, no judgment call: about to use a tool family whose word appears in a skill's name`;
29
59
  const MECHANICAL_TRIGGER_TAIL = `→ read that SKILL.md before the first call in the family.`;
60
+ /** Forward-slash form of a path, for segment arithmetic on either platform. */
61
+ function toSlashes(path) {
62
+ return path.replace(/\\/g, "/");
63
+ }
64
+ /** Sorted by name, byte-comparison so the order never depends on the locale. */
65
+ function byName(a, b) {
66
+ return a < b ? -1 : a > b ? 1 : 0;
67
+ }
68
+ /**
69
+ * The pack directory a skill's body sits in. pi's layout is
70
+ * `<pack>/<skill-name>/SKILL.md`, so the pack is two levels above the file;
71
+ * the row's stated path is `<pack>/<name>/SKILL.md`. A path too short to have
72
+ * a pack reports "", and its group renders without a heading.
73
+ */
74
+ function packOf(filePath) {
75
+ const parts = toSlashes(filePath ?? "").split("/");
76
+ if (parts.length < 3)
77
+ return "";
78
+ return parts.slice(0, -2).join("/");
79
+ }
80
+ /**
81
+ * File the entries by the pack their own SKILL.md lives in: the braid pack
82
+ * plus the user-global directory is two groups in one catalog. Groups and
83
+ * rows are sorted, so identical catalogs render byte-identical text in any
84
+ * cache order. Pure.
85
+ */
86
+ export function catalogGroups(skills) {
87
+ const byDir = new Map();
88
+ for (const skill of skills) {
89
+ const dir = packOf(skill.filePath ?? "");
90
+ const bucket = byDir.get(dir);
91
+ if (bucket)
92
+ bucket.push(skill);
93
+ else
94
+ byDir.set(dir, [skill]);
95
+ }
96
+ return [...byDir.keys()].sort(byName).map((dir) => ({ dir, skills: byDir.get(dir) ?? [] }));
97
+ }
98
+ /**
99
+ * The one directory every entry lives under, or "" when they do not share
100
+ * one: a single root is a fact a caller may state, and a common ancestor of
101
+ * two packs is not. Pure.
102
+ */
103
+ export function skillReadRoot(skills) {
104
+ const groups = catalogGroups(skills);
105
+ return groups.length === 1 ? groups[0].dir : "";
106
+ }
107
+ /**
108
+ * One row per skill: `- name: description`, whitespace collapsed to a single
109
+ * line. Descriptions are NOT clipped: the row is the whole reason the floor
110
+ * works, and a clipped description is what a model would have to guess from.
111
+ * Pure.
112
+ */
113
+ export function catalogRows(skills) {
114
+ return [...skills]
115
+ .sort((a, b) => byName(a.name, b.name))
116
+ .map((s) => {
117
+ const description = (s.description ?? "").replace(/\s+/g, " ").trim();
118
+ return description ? `- ${s.name}: ${description}` : `- ${s.name}`;
119
+ });
120
+ }
30
121
  /**
31
122
  * Worked examples for the mechanical trigger, derived from the live inputs.
32
123
  *
33
124
  * A pair exists when a tool's family token (the first underscore-delimited
34
- * token of the tool name: `herdr_layout` → `herdr`) equals a dash-delimited
35
- * token of a skill name (`herdr-topology` → `herdr`), case-insensitively.
125
+ * token of the tool name: `widget_open` → `widget`) equals a dash-delimited
126
+ * token of a skill name (`widget-map` → `widget`), case-insensitively.
36
127
  * One example renders per distinct family token: the trigger fires per
37
128
  * family ("before the first call in the family"), so enumerating every tool
38
129
  * in a family would restate one fact; the representative tool is the
@@ -72,16 +163,153 @@ export function mechanicalTriggerExamples(toolNames, skillNames) {
72
163
  .map(([family, { casing }]) => `\`${familyTool.get(family)}\` → ${casing}`);
73
164
  }
74
165
  /**
75
- * The full skills-loading text: discovery rule, pointer rule, and the
76
- * mechanical trigger with only the pairs computed from the given tool and
77
- * skill names. prompt-builder feeds it the active tool names and the
78
- * skills-tool module's visible-catalog names.
166
+ * The full skills-loading section: catalog rule (with the derived read path),
167
+ * pointer rule, one row per visible skill, and the mechanical trigger with
168
+ * only the pairs computed from the given tool and skill names.
169
+ *
170
+ * prompt-builder feeds it the active tool names and the skills-tool module's
171
+ * visible catalog. An empty catalog renders no section: the floor is a
172
+ * catalog, and a section claiming to list every skill while listing none
173
+ * would be a lie the model has no way to check.
174
+ *
175
+ * One pack renders its root in the rule; several packs render a directory
176
+ * heading before each group of rows, because no single root describes them.
79
177
  */
80
- export function skillsLoadingText(toolNames, skillNames) {
81
- const examples = mechanicalTriggerExamples(toolNames, skillNames);
178
+ export function skillsLoadingText(toolNames, skills) {
179
+ if (!skills.length)
180
+ return "";
181
+ const examples = mechanicalTriggerExamples(toolNames, skills.map((s) => s.name));
82
182
  const trigger = examples.length > 0
83
183
  ? `${MECHANICAL_TRIGGER_LEAD} (${examples.join(", ")}) ${MECHANICAL_TRIGGER_TAIL}`
84
184
  : `${MECHANICAL_TRIGGER_LEAD} ${MECHANICAL_TRIGGER_TAIL}`;
85
- return `${SKILLS_DISCOVERY_RULE}\n\n${SKILLS_POINTER_RULE}\n\n${trigger}\n`;
185
+ const groups = catalogGroups(skills);
186
+ const grouped = groups.length > 1;
187
+ const rows = grouped
188
+ ? groups
189
+ .map((g) => g.dir
190
+ ? `${g.dir}\n${catalogRows(g.skills).join("\n")}`
191
+ : catalogRows(g.skills).join("\n"))
192
+ .join("\n\n")
193
+ : catalogRows(groups[0].skills).join("\n");
194
+ return `${skillsCatalogRule(skillReadRoot(skills), grouped)}\n\n${SKILLS_POINTER_RULE}\n\n${rows}\n\n${trigger}\n`;
195
+ }
196
+ // Drift trigger
197
+ //
198
+ // The floor is a snapshot: the catalog does not change mid-session, but the
199
+ // work does. A session that starts in one directory and moves to another has
200
+ // its catalog in view and its task text elsewhere, which is the same silent
201
+ // prompt the floor exists for. The trigger watches where the path-taking
202
+ // tools actually write and reads, and when a new directory accumulates
203
+ // entries it says so in one line, pointing back at the catalog.
204
+ //
205
+ // Bounds, all deliberate:
206
+ // - two entries in one directory before it counts: a single stray read is
207
+ // not where the work is.
208
+ // - at most one fire per DRIFT_WINDOW_CALLS tool calls, and quiet for the
209
+ // same window after any skill surface (a suggestion or a SKILL.md read),
210
+ // because a surface that just landed is the pointer the trigger exists to
211
+ // supply.
212
+ // - at most DRIFT_MAX_FIRES per session, so the line stays a signal.
213
+ // - a directory is announced once; the entry counts restart after a fire,
214
+ // so the budget is spent on directories the session has not been told
215
+ // about.
216
+ // - paths with fewer than two directory segments are ignored: repo-root
217
+ // files and top-level directories are where a session starts, not where
218
+ // it moved to.
219
+ /** The path-taking tools whose calls describe where the work is. */
220
+ export const DRIFT_PATH_TOOLS = ["read", "edit", "write"];
221
+ /** Tool calls that must pass between fires, and after any skill surface. */
222
+ export const DRIFT_WINDOW_CALLS = 12;
223
+ /** Fires per session. */
224
+ export const DRIFT_MAX_FIRES = 3;
225
+ /** Entries in one directory before it counts as where the work is. */
226
+ export const DRIFT_ENTRIES = 2;
227
+ /** Directory segments a path must carry before it can name a work area. */
228
+ export const DRIFT_MIN_SEGMENTS = 2;
229
+ /** Fresh drift state for a session. */
230
+ export function initialDrift() {
231
+ return { calls: 0, lastFire: null, fires: 0, lastSurface: null, entries: {}, announced: [] };
232
+ }
233
+ /**
234
+ * The work area a finished tool call touched: the first two directory
235
+ * segments of its path, relative to the session's project root. Undefined for
236
+ * a tool that takes no path, a path outside the project, and a path with
237
+ * fewer than DRIFT_MIN_SEGMENTS directories. Pure.
238
+ */
239
+ export function driftDirectoryFor(toolName, inputPath, cwd) {
240
+ if (!toolName || !DRIFT_PATH_TOOLS.includes(toolName))
241
+ return undefined;
242
+ if (!inputPath || !cwd)
243
+ return undefined;
244
+ const root = resolve(cwd);
245
+ const absolute = isAbsolute(inputPath) ? resolve(inputPath) : resolve(root, inputPath);
246
+ const inside = relative(root, absolute);
247
+ const segments = inside.split(sep).filter(Boolean);
248
+ if (!segments.length || segments[0] === "..")
249
+ return undefined;
250
+ const directories = segments.slice(0, -1);
251
+ if (directories.length < DRIFT_MIN_SEGMENTS)
252
+ return undefined;
253
+ return directories.slice(0, DRIFT_MIN_SEGMENTS).join("/");
254
+ }
255
+ /**
256
+ * Count one finished tool call and answer whether it is a fire.
257
+ *
258
+ * Returns the work area to announce, or null. The caller fires the line and
259
+ * then calls recordDriftFire (on delivery) or recordDriftDrop (when the
260
+ * whisper was suppressed), so a dropped line never spends the budget. The
261
+ * tracker is the session's own mutable state; the answer is a pure function
262
+ * of its contents.
263
+ */
264
+ export function advanceDrift(tracker, directory) {
265
+ tracker.calls++;
266
+ if (!directory)
267
+ return null;
268
+ if (tracker.fires >= DRIFT_MAX_FIRES)
269
+ return null;
270
+ const entries = (tracker.entries[directory] ?? 0) + 1;
271
+ tracker.entries[directory] = entries;
272
+ if (entries < DRIFT_ENTRIES)
273
+ return null;
274
+ if (tracker.announced.includes(directory))
275
+ return null;
276
+ if (tracker.lastFire !== null && tracker.calls - tracker.lastFire < DRIFT_WINDOW_CALLS)
277
+ return null;
278
+ if (tracker.lastSurface !== null && tracker.calls - tracker.lastSurface < DRIFT_WINDOW_CALLS) {
279
+ return null;
280
+ }
281
+ return directory;
282
+ }
283
+ /** Mark a fire at the current call: spends one fire, announces, restarts counts. */
284
+ export function recordDriftFire(tracker, directory) {
285
+ tracker.fires++;
286
+ tracker.lastFire = tracker.calls;
287
+ if (!tracker.announced.includes(directory))
288
+ tracker.announced.push(directory);
289
+ tracker.entries = {};
290
+ }
291
+ /**
292
+ * Mark a fire attempt whose whisper was suppressed: no fire is spent and the
293
+ * directory is not announced, but the counts restart and the window opens, so
294
+ * a suppressed line is retried only after the session has done more work.
295
+ */
296
+ export function recordDriftDrop(tracker) {
297
+ tracker.lastFire = tracker.calls;
298
+ tracker.entries = {};
299
+ }
300
+ /** Note that a skill surface (a suggestion or a SKILL.md read) just landed. */
301
+ export function noteDriftSurface(tracker) {
302
+ tracker.lastSurface = tracker.calls;
303
+ }
304
+ /**
305
+ * The one-line steer: the work area and a pointer back at the catalog in the
306
+ * prompt. `readRoot` empty (several packs, see skillReadRoot) drops the path
307
+ * clause instead of naming a path that may not resolve.
308
+ */
309
+ export function driftPayload(directory, readRoot) {
310
+ const pointer = readRoot
311
+ ? `read \`${readRoot}/<name>/SKILL.md\``
312
+ : `read the matching skill's SKILL.md`;
313
+ return `[SKILL INDEX] work is in ${directory}. Catalog above; ${pointer}.`;
86
314
  }
87
315
  //# sourceMappingURL=loading-guidance.js.map
@@ -39,6 +39,7 @@ import errorCaptureFn from "./self/error-tracking/index.js";
39
39
  import watchdogFn from "./self/watchdog/index.js";
40
40
  import autoRecoveryFn from "./self/auto-recovery/index.js";
41
41
  import latentActivatorFn from "./self/latent-activator/index.js";
42
+ import pathMissFn from "./self/path-miss/index.js";
42
43
  // enforcement (turn pipeline: handlers, detection, substate)
43
44
  import enforcementFn from "./enforcement/index.js";
44
45
  // heartbeat (proactive background services: scheduler, analytics)
@@ -189,6 +190,11 @@ export const MANIFEST = [
189
190
  fn: latentActivatorFn,
190
191
  desc: "Latent behavior activator",
191
192
  },
193
+ {
194
+ id: "path-miss",
195
+ fn: pathMissFn,
196
+ desc: "Path-miss steer — name the listing that answers a missing path",
197
+ },
192
198
  // Watchdog (default-ON — liveness/stall state machine)
193
199
  // Default-ON per TG-HEARTBEAT-WATCHDOG-DESIGN.md ("default ON, NO new env
194
200
  // vars"); override via `broker.watchdog` in the one settings path that
@@ -0,0 +1,30 @@
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
+ export interface PathMiss {
21
+ /** The tool whose call missed. */
22
+ tool: string;
23
+ /** The path that was not there, as the tool or the call reported it. */
24
+ path: string;
25
+ }
26
+ /**
27
+ * The path a failed call missed, or null when this result is not a path miss.
28
+ */
29
+ export declare function detectPathMiss(toolName: string, input: unknown, text: string): PathMiss | null;
30
+ //# sourceMappingURL=detect.d.ts.map
@@ -0,0 +1,67 @@
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
+ /** Tools whose failure can mean "the path was a guess". */
21
+ const PATH_BEARING_TOOLS = new Set(["read", "edit", "write", "bash"]);
22
+ /** The two spellings of "this path is not there" the tools emit. */
23
+ const MISSING_PATH = /ENOENT|no such file or directory/i;
24
+ /** A path quoted by a Node error: `ENOENT: ..., access '/x/y'`. */
25
+ const QUOTED_AFTER_SYSCALL = /\b(?:access|open|stat|lstat|scandir|opendir|unlink|readlink)\s+'([^']+)'/;
26
+ /** A shell builtin naming the directory it could not enter. */
27
+ const BASH_CD_TARGET = /(?:^|[:\s])cd:\s+(.+?):\s*no such file/i;
28
+ /** A program naming the operand it could not find: `ls: /x/y: No such file`. */
29
+ const PROGRAM_OPERAND = /([^\s:]+):\s*no such file or directory/i;
30
+ /** A bare errno (`ENOENT`), not a path. */
31
+ const ERRNO_ONLY = /^[A-Z][A-Z0-9_]*$/;
32
+ /** The path the call itself asked for, when the tool takes one. */
33
+ function pathFromCall(input) {
34
+ if (!input || typeof input !== "object")
35
+ return undefined;
36
+ const path = input.path;
37
+ return typeof path === "string" && path.length > 0 ? path : undefined;
38
+ }
39
+ /** The path an error message names, when the call did not carry one. */
40
+ function pathFromText(text) {
41
+ const candidates = [
42
+ QUOTED_AFTER_SYSCALL.exec(text)?.[1],
43
+ BASH_CD_TARGET.exec(text)?.[1],
44
+ PROGRAM_OPERAND.exec(text)?.[1],
45
+ ];
46
+ for (const candidate of candidates) {
47
+ const path = candidate?.trim();
48
+ if (!path || ERRNO_ONLY.test(path))
49
+ continue;
50
+ return path;
51
+ }
52
+ return undefined;
53
+ }
54
+ /**
55
+ * The path a failed call missed, or null when this result is not a path miss.
56
+ */
57
+ export function detectPathMiss(toolName, input, text) {
58
+ if (!PATH_BEARING_TOOLS.has(toolName))
59
+ return null;
60
+ if (!text || !MISSING_PATH.test(text))
61
+ return null;
62
+ const path = pathFromCall(input) ?? pathFromText(text);
63
+ if (!path)
64
+ return null;
65
+ return { tool: toolName, path };
66
+ }
67
+ //# sourceMappingURL=detect.js.map
@@ -0,0 +1,33 @@
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
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
22
+ /**
23
+ * One line: the path, and the cheaper moves next to it.
24
+ *
25
+ * The parent is named when the path has one, because `ls` needs an operand and
26
+ * a model that guessed a leaf usually had the parent wrong too — listing the
27
+ * parent is what tells it which of the two it got wrong.
28
+ */
29
+ export declare function pathMissLine(path: string): string;
30
+ /** Test hook: forget every steered path and the current turn's budget. */
31
+ export declare function _resetForTests(): void;
32
+ export default function pathMissExtension(pi: ExtensionAPI): void;
33
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,118 @@
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
+ import { dirname } from "node:path";
22
+ import { createLogger } from "../../../lib/core/logger.js";
23
+ import { INPUT, TOOL_RESULT } from "../../../lib/core/event-names.js";
24
+ import { sendTrackedMessage } from "../../../lib/utils/injection-tracker.js";
25
+ import { detectPathMiss } from "./detect.js";
26
+ const log = createLogger("path-miss");
27
+ /**
28
+ * Sessions whose steered paths are remembered. A session id is stable for the
29
+ * life of a session and a long-lived process can host more than one, so the
30
+ * map is bounded rather than trusted to stay small.
31
+ */
32
+ const MAX_TRACKED_SESSIONS = 16;
33
+ /** Paths already steered, per session. */
34
+ const steeredPaths = new Map();
35
+ /** Turn-scoped: the first path miss of a turn is the one worth a line. */
36
+ let steeredThisTurn = false;
37
+ function sessionKey(ctx) {
38
+ const manager = ctx?.sessionManager;
39
+ return manager?.getSessionId?.() ?? manager?.getSessionFile?.() ?? "unknown";
40
+ }
41
+ function remember(session, path) {
42
+ const paths = steeredPaths.get(session) ?? new Set();
43
+ paths.add(path);
44
+ steeredPaths.set(session, paths);
45
+ if (steeredPaths.size > MAX_TRACKED_SESSIONS) {
46
+ // Insertion order: the oldest session is the first key.
47
+ const oldest = steeredPaths.keys().next().value;
48
+ if (oldest !== undefined && oldest !== session)
49
+ steeredPaths.delete(oldest);
50
+ }
51
+ }
52
+ function alreadySteered(session, path) {
53
+ return steeredPaths.get(session)?.has(path) ?? false;
54
+ }
55
+ /** The error text of a tool result, with any non-text parts ignored. */
56
+ function resultText(content) {
57
+ if (typeof content === "string")
58
+ return content;
59
+ if (!Array.isArray(content))
60
+ return "";
61
+ return content
62
+ .map((part) => part && typeof part === "object" && typeof part.text === "string"
63
+ ? part.text
64
+ : "")
65
+ .join("\n");
66
+ }
67
+ /**
68
+ * One line: the path, and the cheaper moves next to it.
69
+ *
70
+ * The parent is named when the path has one, because `ls` needs an operand and
71
+ * a model that guessed a leaf usually had the parent wrong too — listing the
72
+ * parent is what tells it which of the two it got wrong.
73
+ */
74
+ export function pathMissLine(path) {
75
+ const parent = dirname(path);
76
+ const listing = parent && parent !== "." && parent !== "/" ? `ls ${parent}` : "ls on its parent";
77
+ return `path miss: ${path} — ${listing} names the layout in one call; find and explore_paths when the parent is unknown too`;
78
+ }
79
+ /** Test hook: forget every steered path and the current turn's budget. */
80
+ export function _resetForTests() {
81
+ steeredPaths.clear();
82
+ steeredThisTurn = false;
83
+ }
84
+ export default function pathMissExtension(pi) {
85
+ // The same turn boundary the whisper family uses: a new user input opens a
86
+ // new turn, and a turn that has already been steered is done.
87
+ pi.on(INPUT, () => {
88
+ steeredThisTurn = false;
89
+ });
90
+ pi.on(TOOL_RESULT, (event, ctx) => {
91
+ if (steeredThisTurn)
92
+ return;
93
+ if (!event?.isError)
94
+ return;
95
+ const miss = detectPathMiss(event.toolName, event.input, resultText(event.content));
96
+ if (!miss)
97
+ return;
98
+ const session = sessionKey(ctx);
99
+ if (alreadySteered(session, miss.path))
100
+ return;
101
+ steeredThisTurn = true;
102
+ const delivered = sendTrackedMessage(pi, {
103
+ customType: "path-miss",
104
+ content: [{ type: "text", text: pathMissLine(miss.path) }],
105
+ display: true,
106
+ }, { delivery: "live" }, { type: "enforcement", source: "path-miss/steer" });
107
+ // A suppressed send must not spend the path's budget: the line did not
108
+ // arrive, so the next turn is still the first place the agent can read it.
109
+ if (!delivered) {
110
+ steeredThisTurn = false;
111
+ log.debug(`[path-miss] suppressed by the whisper funnel: ${miss.path}`);
112
+ return;
113
+ }
114
+ remember(session, miss.path);
115
+ log.debug(`[path-miss] steered ${miss.path} (${miss.tool})`);
116
+ });
117
+ }
118
+ //# sourceMappingURL=index.js.map
@@ -17,6 +17,7 @@ export declare const MESSAGE_START: "message_start";
17
17
  export declare const MESSAGE_END: "message_end";
18
18
  export declare const TOOL_EXECUTION_START: "tool_execution_start";
19
19
  export declare const TOOL_EXECUTION_END: "tool_execution_end";
20
+ export declare const TOOL_RESULT: "tool_result";
20
21
  export declare const AGENT_SETTLED: "agent_settled";
21
22
  export declare const INPUT: "input";
22
23
  export declare const RESOURCES_DISCOVER: "resources_discover";
@@ -19,6 +19,7 @@ export const MESSAGE_START = "message_start";
19
19
  export const MESSAGE_END = "message_end";
20
20
  export const TOOL_EXECUTION_START = "tool_execution_start";
21
21
  export const TOOL_EXECUTION_END = "tool_execution_end";
22
+ export const TOOL_RESULT = "tool_result";
22
23
  export const AGENT_SETTLED = "agent_settled";
23
24
  // ── Extension Communication ─────────────────────────────────────────────────
24
25
  export const INPUT = "input";
@@ -0,0 +1,41 @@
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
+ * The values a schema node accepts, read from the node.
26
+ *
27
+ * A single-valued node (`const`, which is what `Type.Literal` builds) yields
28
+ * one value; an `enum` yields its list; a union of those yields all of them.
29
+ * A node that constrains nothing yields no values, and the caller then leaves
30
+ * the message to pi.
31
+ */
32
+ export declare function acceptedValues(node: unknown): string[];
33
+ /**
34
+ * Throw the refusal a model can act on, when this module can say more than the
35
+ * validator does. Returns silently otherwise, leaving pi's own message intact.
36
+ *
37
+ * `schema` is the same object the tool declares as its `parameters`, and
38
+ * `args` the arguments the call carried.
39
+ */
40
+ export declare function checkArgumentValues(toolName: string, schema: unknown, args: unknown): void;
41
+ //# sourceMappingURL=argument-report.d.ts.map