@ftrdotdev/pi-delegates 0.0.0-stage → 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 (138) hide show
  1. package/CHANGELOG.md +128 -0
  2. package/LICENSE +21 -0
  3. package/OPERATIONS.md +130 -0
  4. package/README.md +456 -2
  5. package/ROADMAP.md +179 -0
  6. package/TESTING.md +896 -0
  7. package/agents.ts +8 -0
  8. package/examples/README.md +114 -0
  9. package/examples/gated.ts +28 -0
  10. package/index.ts +9 -0
  11. package/package.json +94 -4
  12. package/skills/pi-delegates/SKILL.md +176 -0
  13. package/skills/pi-delegates/references/control.md +159 -0
  14. package/skills/pi-delegates/references/definitions.md +163 -0
  15. package/skills/pi-delegates/references/gates.md +175 -0
  16. package/skills/pi-delegates/references/launch.md +184 -0
  17. package/src/docs-contract.test.ts +106 -0
  18. package/src/domain/definitions.test.ts +41 -0
  19. package/src/domain/definitions.ts +163 -0
  20. package/src/domain/failure.ts +33 -0
  21. package/src/domain/ids.ts +13 -0
  22. package/src/domain/model-source.ts +30 -0
  23. package/src/domain/names.ts +35 -0
  24. package/src/domain/orchestration/admission.ts +78 -0
  25. package/src/domain/orchestration/control.test.ts +1332 -0
  26. package/src/domain/orchestration/control.ts +457 -0
  27. package/src/domain/orchestration/fanout.test.ts +524 -0
  28. package/src/domain/orchestration/fanout.ts +372 -0
  29. package/src/domain/orchestration/gates.test.ts +685 -0
  30. package/src/domain/orchestration/gates.ts +360 -0
  31. package/src/domain/orchestration/launch.test.ts +372 -0
  32. package/src/domain/orchestration/launch.ts +691 -0
  33. package/src/domain/orchestration/requests.test.ts +695 -0
  34. package/src/domain/orchestration/requests.ts +782 -0
  35. package/src/domain/orchestration/review.test.ts +292 -0
  36. package/src/domain/orchestration/review.ts +168 -0
  37. package/src/domain/orchestration/run-wait.test.ts +265 -0
  38. package/src/domain/orchestration/run-wait.ts +256 -0
  39. package/src/domain/orchestration/workflow-section.test.ts +62 -0
  40. package/src/domain/orchestration/workflow-section.ts +99 -0
  41. package/src/domain/orchestration/workflow.test.ts +1566 -0
  42. package/src/domain/orchestration/workflow.ts +778 -0
  43. package/src/domain/run-records.test.ts +27 -0
  44. package/src/domain/run-records.ts +689 -0
  45. package/src/domain/settlement.test.ts +186 -0
  46. package/src/domain/settlement.ts +137 -0
  47. package/src/domain/shapes.test.ts +185 -0
  48. package/src/domain/skills.test.ts +477 -0
  49. package/src/domain/skills.ts +114 -0
  50. package/src/domain/tool-schema.test.ts +46 -0
  51. package/src/domain/tool-schema.ts +20 -0
  52. package/src/domain/toolkit.test.ts +215 -0
  53. package/src/domain/toolkit.ts +374 -0
  54. package/src/domain/turn-budget.test.ts +37 -0
  55. package/src/domain/turn-budget.ts +23 -0
  56. package/src/domain/view.test.ts +803 -0
  57. package/src/domain/view.ts +491 -0
  58. package/src/example.test.ts +15 -0
  59. package/src/extension/commands.test.ts +485 -0
  60. package/src/extension/commands.ts +230 -0
  61. package/src/extension/entry.test.ts +1276 -0
  62. package/src/extension/entry.ts +380 -0
  63. package/src/extension/gate-alerts.test.ts +237 -0
  64. package/src/extension/gate-alerts.ts +143 -0
  65. package/src/extension/guard.test.ts +48 -0
  66. package/src/extension/guard.ts +31 -0
  67. package/src/extension/host-signals.test.ts +20 -0
  68. package/src/extension/host-signals.ts +13 -0
  69. package/src/extension/inspector-command.test.ts +1343 -0
  70. package/src/extension/inspector-command.ts +685 -0
  71. package/src/extension/prompt.test.ts +108 -0
  72. package/src/extension/prompt.ts +50 -0
  73. package/src/extension/request-alerts.test.ts +183 -0
  74. package/src/extension/request-alerts.ts +181 -0
  75. package/src/extension/retry-observer.test.ts +292 -0
  76. package/src/extension/retry-observer.ts +150 -0
  77. package/src/extension/revocation.test.ts +81 -0
  78. package/src/extension/revocation.ts +84 -0
  79. package/src/extension/settle-alerts.test.ts +579 -0
  80. package/src/extension/settle-alerts.ts +175 -0
  81. package/src/extension/shortcut.test.ts +62 -0
  82. package/src/extension/shortcut.ts +105 -0
  83. package/src/extension/tools.test.ts +1294 -0
  84. package/src/extension/tools.ts +553 -0
  85. package/src/extension/version.test.ts +115 -0
  86. package/src/extension/version.ts +97 -0
  87. package/src/goldens.test.ts +294 -0
  88. package/src/harness-policy.test.ts +76 -0
  89. package/src/layers.test.ts +309 -0
  90. package/src/layers.ts +405 -0
  91. package/src/package-manifest.test.ts +170 -0
  92. package/src/presentation/actions.test.ts +221 -0
  93. package/src/presentation/actions.ts +85 -0
  94. package/src/presentation/activity.test.ts +386 -0
  95. package/src/presentation/activity.ts +66 -0
  96. package/src/presentation/close.test.ts +359 -0
  97. package/src/presentation/inspector.test.ts +682 -0
  98. package/src/presentation/inspector.ts +442 -0
  99. package/src/presentation/overlay.test.ts +553 -0
  100. package/src/presentation/overlay.ts +229 -0
  101. package/src/presentation/repaint.test.ts +365 -0
  102. package/src/presentation/shortcut.ts +2 -0
  103. package/src/presentation/snapshot.test.ts +535 -0
  104. package/src/presentation/snapshot.ts +306 -0
  105. package/src/presentation/status.test.ts +43 -0
  106. package/src/presentation/status.ts +30 -0
  107. package/src/presentation/strip.test.ts +203 -0
  108. package/src/presentation/strip.ts +67 -0
  109. package/src/presentation/wording.test.ts +388 -0
  110. package/src/presentation/wording.ts +294 -0
  111. package/src/runtime/bridge.test.ts +131 -0
  112. package/src/runtime/bridge.ts +128 -0
  113. package/src/runtime/clock.test.ts +31 -0
  114. package/src/runtime/clock.ts +31 -0
  115. package/src/runtime/config.test.ts +63 -0
  116. package/src/runtime/config.ts +92 -0
  117. package/src/runtime/context.test.ts +19 -0
  118. package/src/runtime/context.ts +9 -0
  119. package/src/runtime/execution-env.test.ts +33 -0
  120. package/src/runtime/execution-env.ts +15 -0
  121. package/src/runtime/extensions.test.ts +86 -0
  122. package/src/runtime/extensions.ts +152 -0
  123. package/src/runtime/handle.ts +54 -0
  124. package/src/runtime/log.test.ts +140 -0
  125. package/src/runtime/log.ts +91 -0
  126. package/src/runtime/mcp.test.ts +1450 -0
  127. package/src/runtime/mcp.ts +1005 -0
  128. package/src/runtime/models.test.ts +145 -0
  129. package/src/runtime/models.ts +259 -0
  130. package/src/runtime/observe.test.ts +50 -0
  131. package/src/runtime/observe.ts +150 -0
  132. package/src/runtime/runtime-state.test.ts +25 -0
  133. package/src/runtime/runtime-state.ts +36 -0
  134. package/src/runtime/session-tag.ts +11 -0
  135. package/src/runtime/session.test.ts +352 -0
  136. package/src/runtime/session.ts +263 -0
  137. package/src/runtime/storage.ts +29 -0
  138. package/src/test-hygiene.test.ts +97 -0
@@ -0,0 +1,477 @@
1
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
+ import { defineDoc, MemoryStorage, type JsonObject } from "@earendil-works/pi-durable";
3
+ import { Effect } from "effect";
4
+ import { assert, it } from "@effect/vitest";
5
+ import { join, makeDir, makeTempDir, removePath, writeText } from "../../test-support/platform.ts";
6
+ import { rejects, throws } from "../../test-support/assertions.ts";
7
+ import { stubHostSource, type StubModelSource } from "../../test-support/stub-model-source.ts";
8
+ import {
9
+ createCatalogue,
10
+ decodeInlineDefinition,
11
+ defineAgent,
12
+ DefinitionFieldNotAllowed,
13
+ type AgentDefinition,
14
+ } from "./definitions.ts";
15
+ import { CODING_EXTENSION, SKILLS_EXTENSION } from "./names.ts";
16
+ import { RunDoc, RunIndexDoc } from "./run-records.ts";
17
+ import { resolverFor } from "./run-records.ts";
18
+ import { SkillsCatalogue } from "./skills.ts";
19
+ import { bindToolkit, ToolkitDoc, ToolkitUnresolved, type ToolkitResolver } from "./toolkit.ts";
20
+ import { HostModelAdapter } from "../runtime/models.ts";
21
+ import { createDelegatesRegistry } from "../runtime/extensions.ts";
22
+ import {
23
+ openReadOnlyRuntime,
24
+ storePathFor,
25
+ type SessionIdentity,
26
+ type SessionRuntime,
27
+ } from "../runtime/session.ts";
28
+
29
+ import { launch, type HostDefaults } from "./orchestration/launch.ts";
30
+ import { viewRun } from "./view.ts";
31
+ import { openTestSession } from "../../test-support/seams.ts";
32
+
33
+ const identityFor = async (sessionId: string): Promise<SessionIdentity> => {
34
+ const sessionDir = await makeTempDir("delegates-skills-");
35
+ return { sessionId, sessionDir, cwd: sessionDir, agentDir: sessionDir };
36
+ };
37
+
38
+ const openRuntime = (identity: SessionIdentity, skillPaths: readonly string[] = []) =>
39
+ openTestSession({
40
+ identity,
41
+ models: new HostModelAdapter(stubHostSource()),
42
+ storage: new MemoryStorage(),
43
+ skills: { cwd: identity.cwd, agentDir: identity.agentDir, skillPaths },
44
+ });
45
+
46
+ const openWithSource = (
47
+ identity: SessionIdentity,
48
+ skillPaths: readonly string[],
49
+ source: StubModelSource,
50
+ ) =>
51
+ openTestSession({
52
+ identity,
53
+ models: new HostModelAdapter(source),
54
+ storage: new MemoryStorage(),
55
+ skills: { cwd: identity.cwd, agentDir: identity.agentDir, skillPaths },
56
+ });
57
+
58
+ const openPersistent = (identity: SessionIdentity, skillPaths: readonly string[]) =>
59
+ openTestSession({
60
+ identity,
61
+ models: new HostModelAdapter(stubHostSource()),
62
+ skills: { cwd: identity.cwd, agentDir: identity.agentDir, skillPaths },
63
+ });
64
+
65
+ /** An admission host for a registry a test only reads sections from. */
66
+ const quiet = {
67
+ inspect: () => Promise.resolve({ tasks: [] }) as never,
68
+ caps: () => ({ laneCap: 0, sessionCeiling: 0 }),
69
+ pollMs: 1000,
70
+ };
71
+
72
+ /** A prompt input whose committed document read returns the given declared skills. */
73
+ const promptInput = (skills: readonly string[]) =>
74
+ ({
75
+ conversationId: 1,
76
+ agent: { tools: [] },
77
+ env: undefined,
78
+ shown: {},
79
+ read: {
80
+ snapshot: () =>
81
+ Promise.resolve({
82
+ definition: "tester",
83
+ runId: "",
84
+ childRunId: "",
85
+ approval: { gates: [] },
86
+ skills,
87
+ }),
88
+ snapshotAsOf: () => Promise.resolve(undefined),
89
+ },
90
+ }) as never;
91
+
92
+ const host: HostDefaults = { model: { provider: "stub", modelId: "stub-1" }, thinkingLevel: "low" };
93
+
94
+ const skillFile = (name: string, options: { readonly hidden?: boolean } = {}): string =>
95
+ [
96
+ "---",
97
+ `name: ${name}`,
98
+ `description: The ${name} skill`,
99
+ ...((options.hidden ?? false) ? ["disable-model-invocation: true"] : []),
100
+ "---",
101
+ "",
102
+ `${name.toUpperCase()}_BODY_MARKER`,
103
+ "",
104
+ ].join("\n");
105
+
106
+ /** A temp root holding `<name>/SKILL.md` for each entry. */
107
+ const skillRoot = async (
108
+ entries: readonly (string | { readonly name: string; readonly hidden: boolean })[] = [],
109
+ ): Promise<string> => {
110
+ const root = await makeTempDir("delegates-skill-root-");
111
+ for (const entry of entries) {
112
+ const name = typeof entry === "string" ? entry : entry.name;
113
+ const hidden = typeof entry === "string" ? false : entry.hidden;
114
+ await makeDir(join(root, name));
115
+ await writeText(join(root, name, "SKILL.md"), skillFile(name, { hidden }));
116
+ }
117
+ return root;
118
+ };
119
+
120
+ const tester = (skills: readonly string[]): AgentDefinition =>
121
+ defineAgent({
122
+ name: "tester",
123
+ role: "Test agent",
124
+ prompt: { role: "You test skills." },
125
+ tools: ["read"],
126
+ extensions: [CODING_EXTENSION],
127
+ approval: { gates: [] },
128
+ ...(skills.length === 0 ? {} : { skills: [...skills] }),
129
+ });
130
+
131
+ const launchDeps = (runtime: SessionRuntime, definition: AgentDefinition) => ({
132
+ runtime,
133
+ catalogue: createCatalogue([definition]),
134
+ host,
135
+ waitMs: 5_000,
136
+ });
137
+
138
+ /** The version 1 record a store written before this change holds. */
139
+ const LegacyToolkit = defineDoc<{
140
+ definition: string;
141
+ runId: string;
142
+ childRunId: string;
143
+ approval: JsonObject;
144
+ }>({
145
+ kind: "delegates.toolkit",
146
+ version: 1,
147
+ scope: "conversation",
148
+ history: "latest",
149
+ fork: "current",
150
+ initial: () => ({ definition: "", runId: "", childRunId: "", approval: { gates: [] } }),
151
+ checkpointWhen: () => true,
152
+ });
153
+
154
+ it("a version 1 toolkit document opens with no declared skills", async () => {
155
+ const runtime = await openRuntime(await identityFor("s-1"));
156
+ try {
157
+ const childId = await runtime.run((context) =>
158
+ runtime.harness.commit(async (tx) => {
159
+ const conversation = await tx.createConversation({ ownership: { kind: "ownerless" } });
160
+ const doc = await tx.doc(LegacyToolkit, conversation.id);
161
+ doc.definition = "legacy";
162
+ doc.runId = "run:legacy";
163
+ doc.childRunId = "run:legacy";
164
+ return conversation.id;
165
+ }, context),
166
+ );
167
+
168
+ const read = await runtime.run((context) =>
169
+ runtime.harness.snapshot(ToolkitDoc, childId, context),
170
+ );
171
+ assert.deepStrictEqual(read?.skills, []);
172
+ assert.strictEqual(read?.definition, "legacy");
173
+ } finally {
174
+ await runtime.close();
175
+ }
176
+ });
177
+
178
+ it("a version 2 document keeps the declared names", async () => {
179
+ const runtime = await openRuntime(await identityFor("s-1"));
180
+ try {
181
+ const childId = await runtime.run((context) =>
182
+ runtime.harness.commit(async (tx) => {
183
+ const conversation = await tx.createConversation({ ownership: { kind: "ownerless" } });
184
+ const doc = await tx.doc(ToolkitDoc, conversation.id);
185
+ doc.definition = "tester";
186
+ doc.runId = "run:tester";
187
+ doc.childRunId = "run:tester";
188
+ doc.skills = ["alpha", "beta"];
189
+ return conversation.id;
190
+ }, context),
191
+ );
192
+
193
+ const read = await runtime.run((context) =>
194
+ runtime.harness.snapshot(ToolkitDoc, childId, context),
195
+ );
196
+ assert.deepStrictEqual(read?.skills, ["alpha", "beta"]);
197
+ } finally {
198
+ await runtime.close();
199
+ }
200
+ });
201
+
202
+ it("an inline definition cannot declare skills", () => {
203
+ throws(
204
+ () =>
205
+ decodeInlineDefinition({
206
+ name: "nomad",
207
+ role: "audit",
208
+ prompt: { role: "audit" },
209
+ tools: ["read"],
210
+ skills: ["alpha"],
211
+ }),
212
+ (error: unknown) => error instanceof DefinitionFieldNotAllowed && error.field === "skills",
213
+ );
214
+ });
215
+
216
+ it("an unknown skill name fails before any run is claimed", async () => {
217
+ const root = await skillRoot(["alpha"]);
218
+ const runtime = await openRuntime(await identityFor("s-1"), [root]);
219
+ try {
220
+ const definition = tester(["gamma"]);
221
+ await rejects(
222
+ launch({ kind: "single", agent: "tester", task: "look" }, launchDeps(runtime, definition)),
223
+ (error: unknown) =>
224
+ error instanceof ToolkitUnresolved &&
225
+ error.message.includes("gamma") &&
226
+ error.message.includes("alpha"),
227
+ );
228
+ const index = await runtime.snapshot(RunIndexDoc);
229
+ assert.deepStrictEqual(index?.runIds ?? [], []);
230
+ } finally {
231
+ await runtime.close();
232
+ }
233
+ });
234
+
235
+ it("a declared skill binds and is carried by name", async () => {
236
+ const root = await skillRoot(["alpha", "beta"]);
237
+ const runtime = await openRuntime(await identityFor("s-1"), [root]);
238
+ try {
239
+ const definition = tester(["alpha"]);
240
+ const bound = await Effect.runPromise(
241
+ bindToolkit(
242
+ definition,
243
+ resolverFor({ registry: runtime.registry.snapshot(), skills: runtime.skills }),
244
+ ),
245
+ );
246
+ assert.deepStrictEqual(bound.names.skills, ["alpha"]);
247
+ assert.deepStrictEqual(bound.names.extensions, [CODING_EXTENSION, SKILLS_EXTENSION]);
248
+ } finally {
249
+ await runtime.close();
250
+ }
251
+ });
252
+
253
+ it("an empty catalogue names no available skills", async () => {
254
+ const skills = SkillsCatalogue.make();
255
+ const resolver: ToolkitResolver = {
256
+ availableExtensions: [],
257
+ availableTools: [],
258
+ availableSkills: skills.all().map((skill) => skill.name),
259
+ extension: () => undefined,
260
+ tool: () => undefined,
261
+ skill: skills.find,
262
+ mcpServers: [],
263
+ codemodeTools: [],
264
+ unconnected: undefined,
265
+ matchTools: () => [],
266
+ };
267
+ const failure = await bindToolkit(
268
+ defineAgent({
269
+ name: "tester",
270
+ role: "Test agent",
271
+ prompt: { role: "You test." },
272
+ tools: [],
273
+ extensions: [],
274
+ approval: { gates: [] },
275
+ skills: ["alpha"],
276
+ }),
277
+ resolver,
278
+ ).pipe(Effect.flip, Effect.runPromise);
279
+ assert.ok(failure instanceof ToolkitUnresolved);
280
+ assert.ok(failure.message.endsWith("Available skills: (none)."), failure.message);
281
+ });
282
+
283
+ it("a child prompt lists only its declared skills", async () => {
284
+ const root = await skillRoot(["alpha", "beta"]);
285
+ const source = stubHostSource({ text: "ok" });
286
+ const runtime = await openWithSource(await identityFor("s-1"), [root], source);
287
+ try {
288
+ const result = await launch(
289
+ { kind: "single", agent: "tester", task: "look" },
290
+ launchDeps(runtime, tester(["alpha"])),
291
+ );
292
+ assert.strictEqual(result.view.status, "answered");
293
+ const prompt = source.requests[0]?.systemPrompt ?? "";
294
+ assert.ok(prompt.includes("alpha"), prompt);
295
+ assert.ok(prompt.includes("read tool"), prompt);
296
+ assert.ok(!prompt.includes("beta"), prompt);
297
+ assert.ok(!prompt.includes("BETA_BODY_MARKER"), prompt);
298
+ } finally {
299
+ await runtime.close();
300
+ }
301
+ });
302
+
303
+ it("a skill marked disable-model-invocation is omitted from the prompt", async () => {
304
+ const root = await skillRoot(["alpha", { name: "gamma", hidden: true }]);
305
+ const source = stubHostSource({ text: "ok" });
306
+ const runtime = await openWithSource(await identityFor("s-1"), [root], source);
307
+ try {
308
+ const result = await launch(
309
+ { kind: "single", agent: "tester", task: "look" },
310
+ launchDeps(runtime, tester(["alpha", "gamma"])),
311
+ );
312
+ assert.strictEqual(result.view.status, "answered");
313
+ const prompt = source.requests[0]?.systemPrompt ?? "";
314
+ assert.ok(prompt.includes("alpha"), prompt);
315
+ assert.ok(!prompt.includes("gamma"), prompt);
316
+ } finally {
317
+ await runtime.close();
318
+ }
319
+ });
320
+
321
+ it("the toolkit document records the names and no bodies", async () => {
322
+ const root = await skillRoot(["alpha"]);
323
+ const runtime = await openRuntime(await identityFor("s-1"), [root]);
324
+ try {
325
+ const result = await launch(
326
+ { kind: "single", agent: "tester", task: "look" },
327
+ launchDeps(runtime, tester(["alpha"])),
328
+ );
329
+ const doc = await runtime.snapshot(RunDoc, result.view.runId);
330
+ const childId = doc!.childConversationId!;
331
+ const toolkit = await runtime.run((context) =>
332
+ runtime.harness.snapshot(ToolkitDoc, childId as never, context),
333
+ );
334
+ assert.deepStrictEqual(toolkit?.skills, ["alpha"]);
335
+ assert.ok(!JSON.stringify(toolkit).includes("ALPHA_BODY_MARKER"));
336
+ } finally {
337
+ await runtime.close();
338
+ }
339
+ });
340
+
341
+ it("the skills section renders nothing without declared skills", async () => {
342
+ const registry = createDelegatesRegistry({
343
+ admission: quiet,
344
+ skills: SkillsCatalogue.make(),
345
+ }).registry;
346
+ const found = registry
347
+ .snapshot()
348
+ .sections()
349
+ .find((entry) => entry.section.key === "skills");
350
+ assert.ok(found !== undefined);
351
+ const rendered = await found.section.render(promptInput([]), BACKGROUND_CONTEXT);
352
+ assert.strictEqual(rendered, undefined);
353
+ });
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
+
364
+ it("reload sees a skill added since the session opened", async () => {
365
+ const root = await skillRoot(["alpha"]);
366
+ const runtime = await openRuntime(await identityFor("s-1"), [root]);
367
+ try {
368
+ assert.deepStrictEqual(
369
+ runtime.skills.all().map((skill) => skill.name),
370
+ ["alpha"],
371
+ );
372
+ await makeDir(join(root, "delta"));
373
+ await writeText(join(root, "delta", "SKILL.md"), skillFile("delta"));
374
+
375
+ await Effect.runPromise(runtime.skills.reload);
376
+
377
+ assert.deepStrictEqual(
378
+ runtime.skills.all().map((skill) => skill.name),
379
+ ["alpha", "delta"],
380
+ );
381
+ assert.ok(runtime.skills.all().every((skill) => !("body" in skill)));
382
+ } finally {
383
+ await runtime.close();
384
+ }
385
+ });
386
+
387
+ it("a reopened session sees the new skill and keeps declared names", async () => {
388
+ const root = await skillRoot(["alpha"]);
389
+ const identity = await identityFor("s-1");
390
+ const first = await openPersistent(identity, [root]);
391
+ let runId = "";
392
+ let childId = 0;
393
+ try {
394
+ const result = await launch(
395
+ { kind: "single", agent: "tester", task: "look" },
396
+ launchDeps(first, tester(["alpha"])),
397
+ );
398
+ runId = result.view.runId;
399
+ const doc = await first.snapshot(RunDoc, runId);
400
+ childId = doc!.childConversationId!;
401
+ assert.ok(childId > 0);
402
+ } finally {
403
+ await first.close();
404
+ }
405
+
406
+ await makeDir(join(root, "delta"));
407
+ await writeText(join(root, "delta", "SKILL.md"), skillFile("delta"));
408
+
409
+ const second = await openTestSession({
410
+ identity,
411
+ models: new HostModelAdapter(stubHostSource()),
412
+ skills: { cwd: identity.cwd, agentDir: identity.agentDir, skillPaths: [root] },
413
+ });
414
+ try {
415
+ const toolkit = await second.run((context) =>
416
+ second.harness.snapshot(ToolkitDoc, childId as never, context),
417
+ );
418
+ assert.deepStrictEqual(toolkit?.skills, ["alpha"]);
419
+ assert.ok(second.skills.all().some((skill) => skill.name === "delta"));
420
+ } finally {
421
+ await second.close();
422
+ }
423
+ });
424
+
425
+ it("a viewer resolves the skills section from its own registry", async () => {
426
+ const root = await skillRoot(["alpha"]);
427
+ const identity = await identityFor("s-1");
428
+ const first = await openPersistent(identity, [root]);
429
+ let childId = 0;
430
+ try {
431
+ const result = await launch(
432
+ { kind: "single", agent: "tester", task: "look" },
433
+ launchDeps(first, tester(["alpha"])),
434
+ );
435
+ const doc = await first.snapshot(RunDoc, result.view.runId);
436
+ childId = doc!.childConversationId!;
437
+ assert.ok(childId > 0);
438
+ } finally {
439
+ await first.close();
440
+ }
441
+
442
+ const viewer = await openReadOnlyRuntime({
443
+ storePath: storePathFor(identity),
444
+ models: new HostModelAdapter(stubHostSource()),
445
+ });
446
+ try {
447
+ const conversation = await viewer.harness.conversation(childId as never, BACKGROUND_CONTEXT);
448
+ assert.ok(conversation !== undefined);
449
+ const agent = await conversation.agent(BACKGROUND_CONTEXT);
450
+ assert.ok(agent.extensions.some((extension) => extension.name === SKILLS_EXTENSION));
451
+ const skills = agent.sections.find((entry) => entry.key === "skills");
452
+ assert.ok(skills !== undefined);
453
+ // The viewer scanned no roots: the section exists but resolves nothing.
454
+ assert.strictEqual(await skills.render(promptInput(["alpha"]), BACKGROUND_CONTEXT), undefined);
455
+ } finally {
456
+ await viewer.close();
457
+ }
458
+ });
459
+
460
+ it("a skill deleted after open joins the view's missing list", async () => {
461
+ const root = await skillRoot(["alpha"]);
462
+ const runtime = await openRuntime(await identityFor("s-1"), [root]);
463
+ try {
464
+ const result = await launch(
465
+ { kind: "single", agent: "tester", task: "look" },
466
+ launchDeps(runtime, tester(["alpha"])),
467
+ );
468
+ await removePath(join(root, "alpha", "SKILL.md"));
469
+ await Effect.runPromise(runtime.skills.reload);
470
+
471
+ const view = await viewRun(result.view.runId, runtime);
472
+ assert.deepStrictEqual(view.missing, ["alpha"]);
473
+ assert.strictEqual(view.status, result.view.status);
474
+ } finally {
475
+ await runtime.close();
476
+ }
477
+ });
@@ -0,0 +1,114 @@
1
+ import { formatSkillsForPrompt, loadSkills, type Skill } from "@earendil-works/pi-coding-agent";
2
+ import { Context, Effect, Layer } from "effect";
3
+
4
+ /** Where Pi finds skills for one session. */
5
+ export interface SkillRoots {
6
+ readonly cwd: string;
7
+ readonly agentDir: string;
8
+ readonly skillPaths: readonly string[];
9
+ }
10
+
11
+ /** `code` is stable (`skill.<problem>`); `detail` names the file. */
12
+ export interface SkillDiagnostic {
13
+ readonly code: string;
14
+ readonly detail: string;
15
+ }
16
+
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
+ }
44
+ }
45
+
46
+ const NONE = "(none)";
47
+
48
+ const namesOf = (skills: readonly Skill[]): string =>
49
+ skills.map((skill) => skill.name).join(", ") || NONE;
50
+
51
+ interface Scan {
52
+ readonly skills: readonly Skill[];
53
+ readonly diagnostics: readonly SkillDiagnostic[];
54
+ }
55
+
56
+ /** One pass over Pi's roots. It caches the file list, never a body. */
57
+ const scan = (roots: SkillRoots | undefined): Scan => {
58
+ if (roots === undefined) return { skills: [], diagnostics: [] };
59
+ const result = loadSkills({
60
+ cwd: roots.cwd,
61
+ agentDir: roots.agentDir,
62
+ skillPaths: [...roots.skillPaths],
63
+ includeDefaults: true,
64
+ });
65
+ return {
66
+ skills: result.skills,
67
+ diagnostics: result.diagnostics.map((entry) => ({
68
+ code: `skill.${entry.type}`,
69
+ detail: `${entry.path ?? "skills"}: ${entry.message}`,
70
+ })),
71
+ };
72
+ };
73
+
74
+ /**
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.
78
+ */
79
+ const serviceFor = (roots: SkillRoots | undefined): SkillsCatalogue["Service"] => {
80
+ let scanned = scan(roots);
81
+ let dropped: SkillDiagnostic[] = [];
82
+ const all = (): readonly Skill[] => scanned.skills;
83
+ const find = (name: string): Skill | undefined =>
84
+ scanned.skills.find((skill) => skill.name === name);
85
+ const resolve = (names: readonly string[]): readonly Skill[] => {
86
+ const found: Skill[] = [];
87
+ for (const name of names) {
88
+ const skill = find(name);
89
+ if (skill !== undefined) {
90
+ found.push(skill);
91
+ continue;
92
+ }
93
+ const detail = `Skill "${name}" is not in the catalogue. Available: ${namesOf(all())}.`;
94
+ if (!dropped.some((entry) => entry.detail === detail)) {
95
+ dropped.push({ code: "skill.missing", detail });
96
+ }
97
+ }
98
+ return found;
99
+ };
100
+ const render = (skills: readonly Skill[]): string => formatSkillsForPrompt([...skills]);
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(() => {
104
+ scanned = scan(roots);
105
+ dropped = [];
106
+ return diagnosticsOf();
107
+ });
108
+ return { all, find, resolve, render, diagnostics, reload };
109
+ };
110
+
111
+ /**
112
+ * One catalogue per runtime; per-conversation restriction comes from `ToolkitDoc.skills`.
113
+ * The scan is synchronous, so the runtime holds the service directly: no Layer to unwrap.
114
+ */
@@ -0,0 +1,46 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { PROPERTY_RUNS } from "@ftrdotdev/pi-test-kit";
3
+ import { Arbitrary, Schema } from "effect";
4
+ import { throws } from "../../test-support/assertions.ts";
5
+ import { decode, declared } from "./tool-schema.ts";
6
+
7
+ /** A struct whose encoded side differs from its type: the seam must decode, not pass through. */
8
+ const Counted = Schema.Struct({
9
+ count: Schema.FiniteFromString,
10
+ label: Schema.String.check(Schema.isMaxLength(12)),
11
+ });
12
+
13
+ const countedArbitrary = Arbitrary.schema(
14
+ Schema.Struct({
15
+ count: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
16
+ label: Schema.String.check(Schema.isMaxLength(12)),
17
+ }),
18
+ );
19
+
20
+ it.prop(
21
+ "decode reads back the type that encode wrote as its encoded side",
22
+ { value: countedArbitrary },
23
+ ({ value }) => {
24
+ const encoded = Schema.encodeSync(Counted)(value);
25
+ assert.strictEqual(typeof encoded.count, "string");
26
+ assert.deepStrictEqual(decode(Counted, encoded), value);
27
+ },
28
+ { arbitrary: { runs: PROPERTY_RUNS } },
29
+ );
30
+
31
+ it("the declared document is the object schema the model sees", () => {
32
+ const document = declared(Counted).json as {
33
+ readonly type?: string;
34
+ readonly properties?: Record<string, unknown>;
35
+ };
36
+
37
+ assert.strictEqual(document.type, "object");
38
+ assert.deepStrictEqual(Object.keys(document.properties ?? {}).sort(), ["count", "label"]);
39
+ });
40
+
41
+ it("decode refuses arguments the schema does not accept", () => {
42
+ throws(
43
+ () => decode(Counted, { count: "not-a-number", label: "x" }),
44
+ (error: unknown) => error instanceof Error,
45
+ );
46
+ });
@@ -0,0 +1,20 @@
1
+ import { Schema } from "effect";
2
+
3
+ /** One Effect Schema with the JSON Schema durable validates and the model sees. */
4
+ export interface DeclaredSchema<T> {
5
+ readonly schema: Schema.ConstraintDecoder<T>;
6
+ readonly json: object;
7
+ }
8
+
9
+ /**
10
+ * The tool declaration seam: Effect Schema is the one source. `json` goes to a
11
+ * durable `ToolRegistration`; `decode` reads the validated arguments back.
12
+ */
13
+ export const declared = <T>(schema: Schema.ConstraintDecoder<T>): DeclaredSchema<T> => ({
14
+ schema,
15
+ json: Schema.toJsonSchemaDocument(schema).schema,
16
+ });
17
+
18
+ /** The arguments durable validated, decoded to their TypeScript shape. */
19
+ export const decode = <T>(schema: Schema.ConstraintDecoder<T>, args: unknown): T =>
20
+ Schema.decodeUnknownSync(schema)(args);