@ftrdotdev/pi-delegates 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/OPERATIONS.md +79 -6
  3. package/README.md +25 -17
  4. package/ROADMAP.md +21 -0
  5. package/TESTING.md +153 -318
  6. package/package.json +4 -3
  7. package/skills/pi-delegates/SKILL.md +29 -0
  8. package/skills/pi-delegates/references/launch.md +28 -0
  9. package/src/docs-contract.test.ts +106 -0
  10. package/src/domain/definitions.ts +3 -1
  11. package/src/domain/failure.ts +33 -0
  12. package/src/domain/model-source.ts +30 -0
  13. package/src/domain/orchestration/control.test.ts +69 -35
  14. package/src/domain/orchestration/control.ts +110 -89
  15. package/src/domain/orchestration/fanout.test.ts +125 -20
  16. package/src/domain/orchestration/fanout.ts +60 -22
  17. package/src/domain/orchestration/gates.test.ts +14 -15
  18. package/src/domain/orchestration/launch.test.ts +210 -11
  19. package/src/domain/orchestration/launch.ts +142 -32
  20. package/src/domain/orchestration/requests.test.ts +11 -16
  21. package/src/domain/orchestration/requests.ts +14 -1
  22. package/src/domain/orchestration/review.test.ts +89 -11
  23. package/src/domain/orchestration/run-wait.test.ts +4 -1
  24. package/src/domain/orchestration/run-wait.ts +1 -1
  25. package/src/domain/orchestration/workflow.test.ts +157 -16
  26. package/src/domain/orchestration/workflow.ts +269 -196
  27. package/src/domain/run-records.ts +214 -52
  28. package/src/domain/settlement.test.ts +186 -0
  29. package/src/domain/settlement.ts +137 -0
  30. package/src/domain/shapes.test.ts +20 -0
  31. package/src/domain/skills.test.ts +31 -20
  32. package/src/domain/skills.ts +36 -19
  33. package/src/domain/toolkit.test.ts +15 -1
  34. package/src/domain/toolkit.ts +8 -13
  35. package/src/domain/turn-budget.test.ts +37 -0
  36. package/src/domain/turn-budget.ts +23 -0
  37. package/src/domain/view.test.ts +78 -14
  38. package/src/domain/view.ts +67 -35
  39. package/src/extension/commands.test.ts +27 -23
  40. package/src/extension/commands.ts +10 -7
  41. package/src/extension/entry.test.ts +214 -56
  42. package/src/extension/entry.ts +78 -40
  43. package/src/extension/gate-alerts.test.ts +10 -8
  44. package/src/extension/inspector-command.test.ts +173 -21
  45. package/src/extension/inspector-command.ts +100 -53
  46. package/src/extension/prompt.test.ts +2 -4
  47. package/src/extension/retry-observer.test.ts +292 -0
  48. package/src/extension/retry-observer.ts +150 -0
  49. package/src/extension/settle-alerts.test.ts +579 -0
  50. package/src/extension/settle-alerts.ts +175 -0
  51. package/src/extension/shortcut.test.ts +6 -8
  52. package/src/extension/tools.test.ts +325 -24
  53. package/src/extension/tools.ts +61 -13
  54. package/src/extension/version.test.ts +21 -29
  55. package/src/goldens.test.ts +294 -0
  56. package/src/harness-policy.test.ts +13 -11
  57. package/src/layers.test.ts +309 -0
  58. package/src/layers.ts +405 -0
  59. package/src/package-manifest.test.ts +32 -19
  60. package/src/presentation/actions.test.ts +8 -8
  61. package/src/presentation/activity.test.ts +7 -8
  62. package/src/presentation/close.test.ts +14 -16
  63. package/src/presentation/inspector.test.ts +14 -11
  64. package/src/presentation/inspector.ts +27 -25
  65. package/src/presentation/overlay.test.ts +1 -3
  66. package/src/presentation/repaint.test.ts +226 -190
  67. package/src/presentation/snapshot.test.ts +5 -0
  68. package/src/presentation/status.test.ts +43 -0
  69. package/src/presentation/status.ts +30 -0
  70. package/src/presentation/strip.test.ts +13 -6
  71. package/src/presentation/strip.ts +7 -14
  72. package/src/presentation/wording.test.ts +153 -3
  73. package/src/presentation/wording.ts +78 -6
  74. package/src/runtime/bridge.ts +38 -44
  75. package/src/runtime/{timers.test.ts → clock.test.ts} +1 -1
  76. package/src/runtime/clock.ts +31 -0
  77. package/src/runtime/config.test.ts +26 -7
  78. package/src/runtime/config.ts +6 -1
  79. package/src/runtime/execution-env.test.ts +6 -8
  80. package/src/runtime/extensions.test.ts +4 -4
  81. package/src/runtime/extensions.ts +23 -11
  82. package/src/runtime/handle.ts +54 -0
  83. package/src/runtime/log.test.ts +19 -7
  84. package/src/runtime/log.ts +23 -0
  85. package/src/runtime/mcp.test.ts +29 -32
  86. package/src/runtime/mcp.ts +70 -3
  87. package/src/runtime/runtime-state.test.ts +25 -0
  88. package/src/runtime/runtime-state.ts +36 -0
  89. package/src/runtime/session-tag.ts +11 -0
  90. package/src/runtime/session.test.ts +24 -31
  91. package/src/runtime/session.ts +99 -261
  92. package/src/runtime/storage.ts +29 -0
  93. package/src/test-hygiene.test.ts +97 -0
  94. package/src/runtime/timers.ts +0 -10
@@ -0,0 +1,137 @@
1
+ import type { Draft } from "@earendil-works/chord/delta";
2
+ import type { JsonObject } from "@earendil-works/pi-durable";
3
+ import { Schema } from "effect";
4
+ import { failureDetailText, type LogSink } from "../runtime/log.ts";
5
+ import { FAILURE_REASONS, FailureReason, type FailureFact, type Resolution } from "./failure.ts";
6
+ import type { RunMetadata } from "./run-records.ts";
7
+
8
+ export { Execution, FAILURE_REASONS, FailureFact, FailureReason, Resolution } from "./failure.ts";
9
+
10
+ export const Remedy = Schema.Literals(["relaunch", "narrow", "fix_config"]);
11
+ export type Remedy = typeof Remedy.Type;
12
+
13
+ /** Exhaustive: a new reason fails the type-check here, before any test runs. */
14
+ const REMEDIES: Readonly<Record<FailureReason, Remedy>> = {
15
+ model_error: "relaunch",
16
+ interrupted: "relaunch",
17
+ faulted: "relaunch",
18
+ orphaned: "relaunch",
19
+ restart_limit: "relaunch",
20
+ aborted: "relaunch",
21
+ reset: "relaunch",
22
+ internal: "relaunch",
23
+ turn_limit: "narrow",
24
+ nothing_to_answer: "narrow",
25
+ no_model: "fix_config",
26
+ };
27
+
28
+ export const remedyOf = (reason: FailureReason): Remedy => REMEDIES[reason];
29
+
30
+ /** Retryability is observed evidence, never a classification of the text. */
31
+ export const retryableOf = (retryCount: number): boolean => retryCount > 0;
32
+
33
+ /** A durable settlement reason; anything the package did not observe is `internal`. */
34
+ export const reasonFor = (reason: string | undefined): FailureReason =>
35
+ reason !== undefined && (FAILURE_REASONS as readonly string[]).includes(reason)
36
+ ? (reason as FailureReason)
37
+ : "internal";
38
+
39
+ export interface RecordedSettlement {
40
+ readonly failure: FailureFact;
41
+ readonly retryable: boolean;
42
+ readonly remedy: Remedy;
43
+ }
44
+
45
+ export interface SettlementFact {
46
+ readonly resolution: Resolution;
47
+ readonly reason?: FailureReason;
48
+ readonly rawDetail?: string;
49
+ }
50
+
51
+ /**
52
+ * The settle outcome of one task, and no failure fact: a group ends with a
53
+ * resolution but writes no failure, so the notice still names it.
54
+ */
55
+ export const recordResolution = (
56
+ doc: Draft<RunMetadata & JsonObject>,
57
+ resolution: Resolution,
58
+ ): void => {
59
+ doc.resolution = resolution;
60
+ doc.failure = null;
61
+ };
62
+
63
+ /**
64
+ * The only writer of terminal facts: one document write per settlement, no log
65
+ * line. The caller already holds the run's draft, so this module never reads the
66
+ * store and the module graph stays acyclic. Returns the failure evidence for the
67
+ * log line, or `undefined` when the run did not fail.
68
+ */
69
+ export const recordSettlement = async (
70
+ doc: Draft<RunMetadata & JsonObject>,
71
+ fact: SettlementFact,
72
+ ): Promise<RecordedSettlement | undefined> => {
73
+ recordResolution(doc, fact.resolution);
74
+ if (fact.resolution !== "failed") return undefined;
75
+ const failure: FailureFact = {
76
+ reason: fact.reason ?? "internal",
77
+ detail: failureDetailText(fact.rawDetail),
78
+ };
79
+ doc.failure = failure;
80
+ return {
81
+ failure,
82
+ retryable: retryableOf(doc.retryCount),
83
+ remedy: remedyOf(failure.reason),
84
+ };
85
+ };
86
+
87
+ /** Exactly one error line per failed run. */
88
+ export const logRunFailed = (
89
+ log: LogSink,
90
+ runId: string,
91
+ failure: FailureFact,
92
+ retryable: boolean,
93
+ ): void => {
94
+ log.write("error", "run.failed", {
95
+ runId,
96
+ reason: failure.reason,
97
+ detail: failure.detail,
98
+ retryable,
99
+ remedy: remedyOf(failure.reason),
100
+ });
101
+ };
102
+
103
+ /** One settlement, announced in-process after its commit landed. */
104
+ export interface SettleEvent {
105
+ readonly runId: string;
106
+ }
107
+
108
+ /**
109
+ * The in-process carrier between the recorder (inside a run task) and the
110
+ * batcher (a session-level observer). One per session, so it cannot leak
111
+ * across sessions.
112
+ */
113
+ export interface SettleSignal {
114
+ readonly emit: (event: SettleEvent) => void;
115
+ readonly on: (listener: (event: SettleEvent) => void) => () => void;
116
+ }
117
+
118
+ export const makeSettleSignal = (): SettleSignal => {
119
+ const listeners = new Set<(event: SettleEvent) => void>();
120
+ return {
121
+ emit: (event) => {
122
+ for (const listener of listeners) listener(event);
123
+ },
124
+ on: (listener) => {
125
+ listeners.add(listener);
126
+ return () => {
127
+ listeners.delete(listener);
128
+ };
129
+ },
130
+ };
131
+ };
132
+
133
+ /** The signal a runtime without one uses: no settlement is announced. */
134
+ export const nullSettleSignal: SettleSignal = {
135
+ emit: () => {},
136
+ on: () => () => {},
137
+ };
@@ -61,6 +61,8 @@ it("the view shapes decode their values", () => {
61
61
  status: "answered",
62
62
  answer: "done",
63
63
  durationMs: 3_000,
64
+ maxTurns: null,
65
+ failure: null,
64
66
  });
65
67
  const lane = Schema.decodeSync(LaneView)({
66
68
  name: "default",
@@ -78,6 +80,9 @@ it("the view shapes decode their values", () => {
78
80
  status: "answered",
79
81
  answer: "done",
80
82
  durationMs: 3_000,
83
+ execution: "wait",
84
+ maxTurns: null,
85
+ failure: null,
81
86
  children: [child],
82
87
  missing: [],
83
88
  gates: [],
@@ -163,3 +168,18 @@ it("a valid inline definition carries no extensions or approval", () => {
163
168
  assert.ok(!("extensions" in decoded));
164
169
  assert.ok(!("approval" in decoded));
165
170
  });
171
+
172
+ it("an inline definition cannot declare a turn budget", () => {
173
+ let caught: unknown;
174
+ try {
175
+ decodeInlineDefinition({ ...inlineValue, maxTurns: 500 });
176
+ } catch (error) {
177
+ caught = error;
178
+ }
179
+ assert.ok(
180
+ caught instanceof DefinitionFieldNotAllowed &&
181
+ caught.field === "maxTurns" &&
182
+ caught.message.includes("maxTurns"),
183
+ "maxTurns was not refused",
184
+ );
185
+ });
@@ -1,10 +1,8 @@
1
1
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
2
  import { defineDoc, MemoryStorage, type JsonObject } from "@earendil-works/pi-durable";
3
- import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
4
- import { tmpdir } from "node:os";
5
- import { join } from "node:path";
6
3
  import { Effect } from "effect";
7
4
  import { assert, it } from "@effect/vitest";
5
+ import { join, makeDir, makeTempDir, removePath, writeText } from "../../test-support/platform.ts";
8
6
  import { rejects, throws } from "../../test-support/assertions.ts";
9
7
  import { stubHostSource, type StubModelSource } from "../../test-support/stub-model-source.ts";
10
8
  import {
@@ -17,27 +15,28 @@ import {
17
15
  import { CODING_EXTENSION, SKILLS_EXTENSION } from "./names.ts";
18
16
  import { RunDoc, RunIndexDoc } from "./run-records.ts";
19
17
  import { resolverFor } from "./run-records.ts";
20
- import { emptySkills } from "./skills.ts";
18
+ import { SkillsCatalogue } from "./skills.ts";
21
19
  import { bindToolkit, ToolkitDoc, ToolkitUnresolved, type ToolkitResolver } from "./toolkit.ts";
22
20
  import { HostModelAdapter } from "../runtime/models.ts";
23
21
  import { createDelegatesRegistry } from "../runtime/extensions.ts";
24
22
  import {
25
23
  openReadOnlyRuntime,
26
- openSessionRuntime,
27
24
  storePathFor,
28
25
  type SessionIdentity,
29
26
  type SessionRuntime,
30
27
  } from "../runtime/session.ts";
28
+
31
29
  import { launch, type HostDefaults } from "./orchestration/launch.ts";
32
30
  import { viewRun } from "./view.ts";
31
+ import { openTestSession } from "../../test-support/seams.ts";
33
32
 
34
33
  const identityFor = async (sessionId: string): Promise<SessionIdentity> => {
35
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-skills-"));
34
+ const sessionDir = await makeTempDir("delegates-skills-");
36
35
  return { sessionId, sessionDir, cwd: sessionDir, agentDir: sessionDir };
37
36
  };
38
37
 
39
38
  const openRuntime = (identity: SessionIdentity, skillPaths: readonly string[] = []) =>
40
- openSessionRuntime({
39
+ openTestSession({
41
40
  identity,
42
41
  models: new HostModelAdapter(stubHostSource()),
43
42
  storage: new MemoryStorage(),
@@ -49,7 +48,7 @@ const openWithSource = (
49
48
  skillPaths: readonly string[],
50
49
  source: StubModelSource,
51
50
  ) =>
52
- openSessionRuntime({
51
+ openTestSession({
53
52
  identity,
54
53
  models: new HostModelAdapter(source),
55
54
  storage: new MemoryStorage(),
@@ -57,7 +56,7 @@ const openWithSource = (
57
56
  });
58
57
 
59
58
  const openPersistent = (identity: SessionIdentity, skillPaths: readonly string[]) =>
60
- openSessionRuntime({
59
+ openTestSession({
61
60
  identity,
62
61
  models: new HostModelAdapter(stubHostSource()),
63
62
  skills: { cwd: identity.cwd, agentDir: identity.agentDir, skillPaths },
@@ -108,12 +107,12 @@ const skillFile = (name: string, options: { readonly hidden?: boolean } = {}): s
108
107
  const skillRoot = async (
109
108
  entries: readonly (string | { readonly name: string; readonly hidden: boolean })[] = [],
110
109
  ): Promise<string> => {
111
- const root = await mkdtemp(join(tmpdir(), "delegates-skill-root-"));
110
+ const root = await makeTempDir("delegates-skill-root-");
112
111
  for (const entry of entries) {
113
112
  const name = typeof entry === "string" ? entry : entry.name;
114
113
  const hidden = typeof entry === "string" ? false : entry.hidden;
115
- await mkdir(join(root, name), { recursive: true });
116
- await writeFile(join(root, name, "SKILL.md"), skillFile(name, { hidden }));
114
+ await makeDir(join(root, name));
115
+ await writeText(join(root, name, "SKILL.md"), skillFile(name, { hidden }));
117
116
  }
118
117
  return root;
119
118
  };
@@ -252,7 +251,7 @@ it("a declared skill binds and is carried by name", async () => {
252
251
  });
253
252
 
254
253
  it("an empty catalogue names no available skills", async () => {
255
- const skills = emptySkills();
254
+ const skills = SkillsCatalogue.make();
256
255
  const resolver: ToolkitResolver = {
257
256
  availableExtensions: [],
258
257
  availableTools: [],
@@ -340,7 +339,10 @@ it("the toolkit document records the names and no bodies", async () => {
340
339
  });
341
340
 
342
341
  it("the skills section renders nothing without declared skills", async () => {
343
- const registry = createDelegatesRegistry({ admission: quiet, skills: emptySkills() }).registry;
342
+ const registry = createDelegatesRegistry({
343
+ admission: quiet,
344
+ skills: SkillsCatalogue.make(),
345
+ }).registry;
344
346
  const found = registry
345
347
  .snapshot()
346
348
  .sections()
@@ -350,6 +352,15 @@ it("the skills section renders nothing without declared skills", async () => {
350
352
  assert.strictEqual(rendered, undefined);
351
353
  });
352
354
 
355
+ it("the skills reload hands back its diagnostics when one root cannot be read", async () => {
356
+ const root = await skillRoot(["alpha"]);
357
+ const missing = join(root, "missing-root");
358
+ const skills = SkillsCatalogue.make({ cwd: root, agentDir: root, skillPaths: [root, missing] });
359
+ const diagnostics = await Effect.runPromise(skills.reload);
360
+ assert.strictEqual(diagnostics.length, 1);
361
+ assert.ok(diagnostics[0]?.detail.includes(missing), JSON.stringify(diagnostics));
362
+ });
363
+
353
364
  it("reload sees a skill added since the session opened", async () => {
354
365
  const root = await skillRoot(["alpha"]);
355
366
  const runtime = await openRuntime(await identityFor("s-1"), [root]);
@@ -358,8 +369,8 @@ it("reload sees a skill added since the session opened", async () => {
358
369
  runtime.skills.all().map((skill) => skill.name),
359
370
  ["alpha"],
360
371
  );
361
- await mkdir(join(root, "delta"), { recursive: true });
362
- await writeFile(join(root, "delta", "SKILL.md"), skillFile("delta"));
372
+ await makeDir(join(root, "delta"));
373
+ await writeText(join(root, "delta", "SKILL.md"), skillFile("delta"));
363
374
 
364
375
  await Effect.runPromise(runtime.skills.reload);
365
376
 
@@ -392,10 +403,10 @@ it("a reopened session sees the new skill and keeps declared names", async () =>
392
403
  await first.close();
393
404
  }
394
405
 
395
- await mkdir(join(root, "delta"), { recursive: true });
396
- await writeFile(join(root, "delta", "SKILL.md"), skillFile("delta"));
406
+ await makeDir(join(root, "delta"));
407
+ await writeText(join(root, "delta", "SKILL.md"), skillFile("delta"));
397
408
 
398
- const second = await openSessionRuntime({
409
+ const second = await openTestSession({
399
410
  identity,
400
411
  models: new HostModelAdapter(stubHostSource()),
401
412
  skills: { cwd: identity.cwd, agentDir: identity.agentDir, skillPaths: [root] },
@@ -454,7 +465,7 @@ it("a skill deleted after open joins the view's missing list", async () => {
454
465
  { kind: "single", agent: "tester", task: "look" },
455
466
  launchDeps(runtime, tester(["alpha"])),
456
467
  );
457
- await rm(join(root, "alpha", "SKILL.md"));
468
+ await removePath(join(root, "alpha", "SKILL.md"));
458
469
  await Effect.runPromise(runtime.skills.reload);
459
470
 
460
471
  const view = await viewRun(result.view.runId, runtime);
@@ -1,5 +1,5 @@
1
1
  import { formatSkillsForPrompt, loadSkills, type Skill } from "@earendil-works/pi-coding-agent";
2
- import { Effect } from "effect";
2
+ import { Context, Effect, Layer } from "effect";
3
3
 
4
4
  /** Where Pi finds skills for one session. */
5
5
  export interface SkillRoots {
@@ -14,15 +14,33 @@ export interface SkillDiagnostic {
14
14
  readonly detail: string;
15
15
  }
16
16
 
17
- export interface SkillsService {
18
- readonly all: () => readonly Skill[];
19
- readonly find: (name: string) => Skill | undefined;
20
- readonly resolve: (names: readonly string[]) => readonly Skill[];
21
- readonly render: (skills: readonly Skill[]) => string;
22
- /** Scan problems and skills the live catalogue dropped. */
23
- readonly diagnostics: () => readonly SkillDiagnostic[];
24
- /** Re-scans the roots; bodies stay uncached. */
25
- readonly reload: Effect.Effect<void>;
17
+ /** The session's skill catalogue: the seam layer scans once when it is built. */
18
+ export class SkillsCatalogue extends Context.Service<
19
+ SkillsCatalogue,
20
+ {
21
+ readonly all: () => readonly Skill[];
22
+ readonly find: (name: string) => Skill | undefined;
23
+ readonly resolve: (names: readonly string[]) => readonly Skill[];
24
+ readonly render: (skills: readonly Skill[]) => string;
25
+ /** Scan problems and skills the live catalogue dropped. */
26
+ readonly diagnostics: Effect.Effect<readonly SkillDiagnostic[]>;
27
+ /** Re-scans the roots; bodies stay uncached. It cannot fail, so it hands back diagnostics. */
28
+ readonly reload: Effect.Effect<readonly SkillDiagnostic[]>;
29
+ }
30
+ >()("@ftrdotdev/pi-delegates/domain/skills/SkillsCatalogue") {
31
+ /**
32
+ * The catalogue value itself, for a caller in promise-land with no context:
33
+ * `openReadOnlyRuntime` and a test that asserts on the getters. Everywhere else,
34
+ * provide `layer`.
35
+ */
36
+ static make(roots?: SkillRoots): SkillsCatalogue["Service"] {
37
+ return serviceFor(roots);
38
+ }
39
+
40
+ /** One scan per build; a dropped skill keeps its diagnostic for the next reload. */
41
+ static layer(roots: SkillRoots): Layer.Layer<SkillsCatalogue> {
42
+ return Layer.sync(SkillsCatalogue, () => SkillsCatalogue.make(roots));
43
+ }
26
44
  }
27
45
 
28
46
  const NONE = "(none)";
@@ -54,10 +72,11 @@ const scan = (roots: SkillRoots | undefined): Scan => {
54
72
  };
55
73
 
56
74
  /**
57
- * The accessors read a closure-held list, so the durable section and tool
58
- * callbacks stay free of an Effect run; only `reload` scans.
75
+ * The getters read a closure-held list, so the durable section and tool
76
+ * callbacks stay free of an Effect run; the two operations are Effects, and only
77
+ * `reload` scans.
59
78
  */
60
- const serviceFor = (roots: SkillRoots | undefined): SkillsService => {
79
+ const serviceFor = (roots: SkillRoots | undefined): SkillsCatalogue["Service"] => {
61
80
  let scanned = scan(roots);
62
81
  let dropped: SkillDiagnostic[] = [];
63
82
  const all = (): readonly Skill[] => scanned.skills;
@@ -79,10 +98,12 @@ const serviceFor = (roots: SkillRoots | undefined): SkillsService => {
79
98
  return found;
80
99
  };
81
100
  const render = (skills: readonly Skill[]): string => formatSkillsForPrompt([...skills]);
82
- const diagnostics = (): readonly SkillDiagnostic[] => [...dropped, ...scanned.diagnostics];
83
- const reload = Effect.sync(() => {
101
+ const diagnosticsOf = (): readonly SkillDiagnostic[] => [...dropped, ...scanned.diagnostics];
102
+ const diagnostics: Effect.Effect<readonly SkillDiagnostic[]> = Effect.sync(diagnosticsOf);
103
+ const reload: Effect.Effect<readonly SkillDiagnostic[]> = Effect.sync(() => {
84
104
  scanned = scan(roots);
85
105
  dropped = [];
106
+ return diagnosticsOf();
86
107
  });
87
108
  return { all, find, resolve, render, diagnostics, reload };
88
109
  };
@@ -91,7 +112,3 @@ const serviceFor = (roots: SkillRoots | undefined): SkillsService => {
91
112
  * One catalogue per runtime; per-conversation restriction comes from `ToolkitDoc.skills`.
92
113
  * The scan is synchronous, so the runtime holds the service directly: no Layer to unwrap.
93
114
  */
94
- export const createSkills = (roots: SkillRoots | undefined): SkillsService => serviceFor(roots);
95
-
96
- /** A catalogue over no roots: viewers and tests that never resolve a skill. */
97
- export const emptySkills = (): SkillsService => serviceFor(undefined);
@@ -10,7 +10,12 @@ import {
10
10
  type AgentDefinition,
11
11
  } from "./definitions.ts";
12
12
  import { CODING_EXTENSION, SKILLS_EXTENSION } from "../domain/names.ts";
13
- import { bindToolkit, resolveStoredToolkit, ToolkitUnresolved } from "./toolkit.ts";
13
+ import {
14
+ bindToolkit,
15
+ expandToolNames,
16
+ resolveStoredToolkit,
17
+ ToolkitUnresolved,
18
+ } from "./toolkit.ts";
14
19
  import { planLaunch, type HostDefaults } from "./orchestration/launch.ts";
15
20
 
16
21
  const host: HostDefaults = {
@@ -199,3 +204,12 @@ it("a stored name that no longer resolves is reported as missing", () => {
199
204
  ).missing;
200
205
  assert.deepStrictEqual(missing, ["gone-extension", "gone-tool"]);
201
206
  });
207
+
208
+ it("the tool names expand as a Result when a pattern matches no tool", () => {
209
+ const result = expandToolNames(["mcp__missing__*"], resolver([], [])) as {
210
+ readonly _tag?: string;
211
+ readonly failure?: ToolkitUnresolved;
212
+ };
213
+ assert.strictEqual(result._tag, "Failure");
214
+ assert.ok(result.failure?.message.includes("mcp__missing__*"), result.failure?.message);
215
+ });
@@ -11,7 +11,7 @@ import {
11
11
  type ToolRegistration,
12
12
  type Tx,
13
13
  } from "@earendil-works/pi-durable";
14
- import { Effect, Schema } from "effect";
14
+ import { Effect, Result, Schema } from "effect";
15
15
  import { CODEMODE_TOOL_NAME } from "@earendil-works/pi-durable/codemode";
16
16
  import type { Skill } from "@earendil-works/pi-coding-agent";
17
17
  import {
@@ -184,12 +184,10 @@ const patternMessage = (pattern: string, resolver: ToolkitResolver): string => {
184
184
  };
185
185
 
186
186
  /** Expands the declared names: a plain name stays exact, a pattern must be an MCP pattern. */
187
- const expandToolNames = (
187
+ export const expandToolNames = (
188
188
  declared: readonly string[],
189
189
  resolver: ToolkitResolver,
190
- ):
191
- | { readonly kind: "ok"; readonly names: readonly string[] }
192
- | { readonly kind: "failed"; readonly error: ToolkitUnresolved } => {
190
+ ): Result.Result<readonly string[], ToolkitUnresolved> => {
193
191
  const expanded: string[] = [];
194
192
  for (const name of declared) {
195
193
  if (!name.includes("*")) {
@@ -197,18 +195,15 @@ const expandToolNames = (
197
195
  continue;
198
196
  }
199
197
  if (!MCP_PATTERN.test(name)) {
200
- return { kind: "failed", error: grammarFailure(name, resolver) };
198
+ return Result.fail(grammarFailure(name, resolver));
201
199
  }
202
200
  const matched = resolver.matchTools(name);
203
201
  if (matched.length === 0) {
204
- return {
205
- kind: "failed",
206
- error: ToolkitUnresolved.make({ message: patternMessage(name, resolver) }),
207
- };
202
+ return Result.fail(ToolkitUnresolved.make({ message: patternMessage(name, resolver) }));
208
203
  }
209
204
  expanded.push(...matched);
210
205
  }
211
- return { kind: "ok", names: expanded };
206
+ return Result.succeed(expanded);
212
207
  };
213
208
 
214
209
  /**
@@ -233,8 +228,8 @@ export const bindToolkit = (
233
228
  );
234
229
  }
235
230
  const expansion = expandToolNames(definition.tools, resolver);
236
- if (expansion.kind === "failed") return Effect.fail(expansion.error);
237
- const expanded = expansion.names;
231
+ if (Result.isFailure(expansion)) return Effect.fail(expansion.failure);
232
+ const expanded = expansion.success;
238
233
  // A codemode-exposed tool needs the codemode extension; a deferred one needs `tool_search`.
239
234
  const needsCodemode = expanded.some((name) => resolver.codemodeTools.includes(name));
240
235
  const needsToolSearch = expanded.some((name) => resolver.tool(name)?.deferred ?? false);
@@ -0,0 +1,37 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { resolveMaxTurns } from "./turn-budget.ts";
3
+
4
+ const full = {
5
+ child: 60,
6
+ request: 80,
7
+ definition: 100,
8
+ configDefault: 120,
9
+ ceiling: 400,
10
+ };
11
+
12
+ it("the resolver takes the first present level", () => {
13
+ assert.strictEqual(resolveMaxTurns(full), 60);
14
+ assert.strictEqual(resolveMaxTurns({ ...full, child: undefined }), 80);
15
+ assert.strictEqual(resolveMaxTurns({ ...full, child: undefined, request: undefined }), 100);
16
+ assert.strictEqual(
17
+ resolveMaxTurns({
18
+ configDefault: full.configDefault,
19
+ ceiling: full.ceiling,
20
+ }),
21
+ 120,
22
+ );
23
+ });
24
+
25
+ it("a value above the ceiling clamps silently", () => {
26
+ const resolved = resolveMaxTurns({ child: 9_000, configDefault: 120, ceiling: 400 });
27
+ assert.strictEqual(resolved, 400);
28
+ assert.strictEqual(typeof resolved, "number");
29
+ });
30
+
31
+ it("an unusable budget floors at one round", () => {
32
+ // The wire accepts any finite number; a zero or negative budget would end the
33
+ // child before its first round.
34
+ assert.strictEqual(resolveMaxTurns({ child: 0, configDefault: 120, ceiling: 400 }), 1);
35
+ assert.strictEqual(resolveMaxTurns({ child: -5, configDefault: 120, ceiling: 400 }), 1);
36
+ assert.strictEqual(resolveMaxTurns({ request: 0, configDefault: 120, ceiling: 400 }), 1);
37
+ });
@@ -0,0 +1,23 @@
1
+ /** The smallest usable budget: one round. */
2
+ export const MIN_MAX_TURNS = 1;
3
+
4
+ /**
5
+ * One rule resolves the four levels once per child: child, then request, then
6
+ * definition, then the config default; the first present value wins. The result
7
+ * is clamped silently to `caps.maxTurns`, and floors at one round: a wire value
8
+ * of zero or less would end a child before its first tool round.
9
+ */
10
+ export const resolveMaxTurns = (input: {
11
+ readonly child?: number | undefined;
12
+ readonly request?: number | undefined;
13
+ readonly definition?: number | undefined;
14
+ readonly configDefault: number;
15
+ readonly ceiling: number;
16
+ }): number =>
17
+ Math.min(
18
+ Math.max(
19
+ input.child ?? input.request ?? input.definition ?? input.configDefault,
20
+ MIN_MAX_TURNS,
21
+ ),
22
+ input.ceiling,
23
+ );