@ftrdotdev/pi-delegates 0.0.0-stage → 0.1.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 (116) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/LICENSE +21 -0
  3. package/OPERATIONS.md +57 -0
  4. package/README.md +448 -2
  5. package/ROADMAP.md +158 -0
  6. package/TESTING.md +1061 -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 +93 -4
  12. package/skills/pi-delegates/SKILL.md +147 -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 +156 -0
  17. package/src/domain/definitions.test.ts +41 -0
  18. package/src/domain/definitions.ts +161 -0
  19. package/src/domain/ids.ts +13 -0
  20. package/src/domain/names.ts +35 -0
  21. package/src/domain/orchestration/admission.ts +78 -0
  22. package/src/domain/orchestration/control.test.ts +1298 -0
  23. package/src/domain/orchestration/control.ts +436 -0
  24. package/src/domain/orchestration/fanout.test.ts +419 -0
  25. package/src/domain/orchestration/fanout.ts +334 -0
  26. package/src/domain/orchestration/gates.test.ts +686 -0
  27. package/src/domain/orchestration/gates.ts +360 -0
  28. package/src/domain/orchestration/launch.test.ts +173 -0
  29. package/src/domain/orchestration/launch.ts +581 -0
  30. package/src/domain/orchestration/requests.test.ts +700 -0
  31. package/src/domain/orchestration/requests.ts +769 -0
  32. package/src/domain/orchestration/review.test.ts +214 -0
  33. package/src/domain/orchestration/review.ts +168 -0
  34. package/src/domain/orchestration/run-wait.test.ts +262 -0
  35. package/src/domain/orchestration/run-wait.ts +256 -0
  36. package/src/domain/orchestration/workflow-section.test.ts +62 -0
  37. package/src/domain/orchestration/workflow-section.ts +99 -0
  38. package/src/domain/orchestration/workflow.test.ts +1425 -0
  39. package/src/domain/orchestration/workflow.ts +705 -0
  40. package/src/domain/run-records.test.ts +27 -0
  41. package/src/domain/run-records.ts +527 -0
  42. package/src/domain/shapes.test.ts +165 -0
  43. package/src/domain/skills.test.ts +466 -0
  44. package/src/domain/skills.ts +97 -0
  45. package/src/domain/tool-schema.test.ts +46 -0
  46. package/src/domain/tool-schema.ts +20 -0
  47. package/src/domain/toolkit.test.ts +201 -0
  48. package/src/domain/toolkit.ts +379 -0
  49. package/src/domain/view.test.ts +739 -0
  50. package/src/domain/view.ts +459 -0
  51. package/src/example.test.ts +15 -0
  52. package/src/extension/commands.test.ts +481 -0
  53. package/src/extension/commands.ts +227 -0
  54. package/src/extension/entry.test.ts +1118 -0
  55. package/src/extension/entry.ts +342 -0
  56. package/src/extension/gate-alerts.test.ts +235 -0
  57. package/src/extension/gate-alerts.ts +143 -0
  58. package/src/extension/guard.test.ts +48 -0
  59. package/src/extension/guard.ts +31 -0
  60. package/src/extension/host-signals.test.ts +20 -0
  61. package/src/extension/host-signals.ts +13 -0
  62. package/src/extension/inspector-command.test.ts +1191 -0
  63. package/src/extension/inspector-command.ts +638 -0
  64. package/src/extension/prompt.test.ts +110 -0
  65. package/src/extension/prompt.ts +50 -0
  66. package/src/extension/request-alerts.test.ts +183 -0
  67. package/src/extension/request-alerts.ts +181 -0
  68. package/src/extension/revocation.test.ts +81 -0
  69. package/src/extension/revocation.ts +84 -0
  70. package/src/extension/shortcut.test.ts +64 -0
  71. package/src/extension/shortcut.ts +105 -0
  72. package/src/extension/tools.test.ts +993 -0
  73. package/src/extension/tools.ts +505 -0
  74. package/src/extension/version.test.ts +123 -0
  75. package/src/extension/version.ts +97 -0
  76. package/src/harness-policy.test.ts +74 -0
  77. package/src/package-manifest.test.ts +157 -0
  78. package/src/presentation/actions.test.ts +221 -0
  79. package/src/presentation/actions.ts +85 -0
  80. package/src/presentation/activity.test.ts +387 -0
  81. package/src/presentation/activity.ts +66 -0
  82. package/src/presentation/close.test.ts +361 -0
  83. package/src/presentation/inspector.test.ts +679 -0
  84. package/src/presentation/inspector.ts +440 -0
  85. package/src/presentation/overlay.test.ts +555 -0
  86. package/src/presentation/overlay.ts +229 -0
  87. package/src/presentation/repaint.test.ts +329 -0
  88. package/src/presentation/shortcut.ts +2 -0
  89. package/src/presentation/snapshot.test.ts +530 -0
  90. package/src/presentation/snapshot.ts +306 -0
  91. package/src/presentation/strip.test.ts +196 -0
  92. package/src/presentation/strip.ts +74 -0
  93. package/src/presentation/wording.test.ts +238 -0
  94. package/src/presentation/wording.ts +222 -0
  95. package/src/runtime/bridge.test.ts +131 -0
  96. package/src/runtime/bridge.ts +134 -0
  97. package/src/runtime/config.test.ts +44 -0
  98. package/src/runtime/config.ts +87 -0
  99. package/src/runtime/context.test.ts +19 -0
  100. package/src/runtime/context.ts +9 -0
  101. package/src/runtime/execution-env.test.ts +35 -0
  102. package/src/runtime/execution-env.ts +15 -0
  103. package/src/runtime/extensions.test.ts +86 -0
  104. package/src/runtime/extensions.ts +140 -0
  105. package/src/runtime/log.test.ts +128 -0
  106. package/src/runtime/log.ts +68 -0
  107. package/src/runtime/mcp.test.ts +1453 -0
  108. package/src/runtime/mcp.ts +938 -0
  109. package/src/runtime/models.test.ts +145 -0
  110. package/src/runtime/models.ts +259 -0
  111. package/src/runtime/observe.test.ts +50 -0
  112. package/src/runtime/observe.ts +150 -0
  113. package/src/runtime/session.test.ts +359 -0
  114. package/src/runtime/session.ts +425 -0
  115. package/src/runtime/timers.test.ts +31 -0
  116. package/src/runtime/timers.ts +10 -0
@@ -0,0 +1,134 @@
1
+ import type { Context } from "@earendil-works/chord/context";
2
+ import { ReadOnlySession, SessionFailed } from "@earendil-works/pi-durable";
3
+ import { createHash } from "node:crypto";
4
+ import { Context as EffectContext, Effect, Layer, Predicate, Ref, Schema } from "effect";
5
+
6
+ export type HarnessCalls = {
7
+ readonly call: <A>(
8
+ operation: (context: Context) => Promise<A>,
9
+ signal?: AbortSignal,
10
+ ) => Promise<A>;
11
+ /** A host hook for the one failure that closes the bridge; never throws. */
12
+ readonly report?: (error: unknown) => void;
13
+ };
14
+
15
+ export class HarnessClosed extends Schema.TaggedError<
16
+ HarnessClosed,
17
+ { readonly brand: unique symbol }
18
+ >()("HarnessClosed", {
19
+ reason: Schema.String,
20
+ }) {}
21
+
22
+ /** A rejection that leaves the harness usable: the call failed, the bridge did not close. */
23
+ export class HarnessFailure extends Schema.TaggedError<
24
+ HarnessFailure,
25
+ { readonly brand: unique symbol }
26
+ >()("HarnessFailure", {
27
+ reason: Schema.String,
28
+ cause: Schema.Unknown,
29
+ }) {}
30
+
31
+ /**
32
+ * The two fatal durable errors: `SessionFailed` ends the session and `ReadOnlySession` refuses
33
+ * writes. Every other rejection, `StorageRequestError` included, fails only that call.
34
+ */
35
+ const isFatal = (error: unknown): boolean =>
36
+ error instanceof SessionFailed || error instanceof ReadOnlySession;
37
+
38
+ const fatalReason = (error: unknown): string => {
39
+ if (error instanceof SessionFailed && error.cause !== undefined) return fatalReason(error.cause);
40
+ if (error instanceof Error) return error.message;
41
+ if (Predicate.isObject(error)) {
42
+ const message = error.message;
43
+ if (typeof message === "string") return message;
44
+ }
45
+ return String(error);
46
+ };
47
+
48
+ /**
49
+ * The single asynchronous seam between the Effect domain and the durable
50
+ * harness. Nothing else calls the harness directly.
51
+ */
52
+ export class DurableBridge extends EffectContext.Service<
53
+ DurableBridge,
54
+ {
55
+ readonly call: <A>(
56
+ operation: (context: Context) => Promise<A>,
57
+ ) => Effect.Effect<A, HarnessClosed | HarnessFailure>;
58
+ readonly closed: Effect.Effect<HarnessClosed | undefined>;
59
+ readonly report: (error: unknown) => Effect.Effect<void>;
60
+ }
61
+ >()("@ftrdotdev/pi-delegates/runtime/bridge/DurableBridge") {
62
+ static readonly layer = (calls: HarnessCalls): Layer.Layer<DurableBridge> =>
63
+ Layer.effect(
64
+ DurableBridge,
65
+ Effect.gen(function* () {
66
+ const closedRef = yield* Ref.make<HarnessClosed | undefined>(undefined);
67
+
68
+ const call = <A>(
69
+ operation: (context: Context) => Promise<A>,
70
+ ): Effect.Effect<A, HarnessClosed | HarnessFailure> =>
71
+ Effect.scoped(
72
+ Effect.gen(function* () {
73
+ const alreadyClosed = yield* Ref.get(closedRef);
74
+ if (alreadyClosed !== undefined) return yield* alreadyClosed;
75
+
76
+ // The enclosing scope owns the controller: it aborts when the call settles or interrupts.
77
+ const signal = yield* Effect.abortSignal;
78
+
79
+ const attempt: Effect.Effect<A, HarnessClosed | HarnessFailure> = Effect.tryPromise({
80
+ try: () => calls.call(operation, signal),
81
+ catch: (error): HarnessClosed | HarnessFailure =>
82
+ isFatal(error)
83
+ ? HarnessClosed.make({ reason: fatalReason(error) })
84
+ : HarnessFailure.make({ reason: fatalReason(error), cause: error }),
85
+ }).pipe(
86
+ Effect.catchTag("HarnessClosed", (failure) =>
87
+ Effect.gen(function* () {
88
+ const current = yield* Ref.modify(closedRef, (value) =>
89
+ value === undefined ? [failure, failure] : [value, value],
90
+ );
91
+ if (current === failure) calls.report?.(failure);
92
+ return yield* current;
93
+ }),
94
+ ),
95
+ );
96
+ return yield* attempt;
97
+ }),
98
+ );
99
+
100
+ const closed: Effect.Effect<HarnessClosed | undefined> = Ref.get(closedRef);
101
+
102
+ const report = (error: unknown): Effect.Effect<void> =>
103
+ Effect.sync(() => {
104
+ calls.report?.(error);
105
+ });
106
+
107
+ return DurableBridge.of({ call, closed, report });
108
+ }),
109
+ );
110
+ }
111
+
112
+ /** Canonical JSON: object keys sorted, arrays in order. */
113
+ export const stableJson = (value: unknown): string => {
114
+ const canonical = (input: unknown): unknown => {
115
+ if (Array.isArray(input)) return input.map(canonical);
116
+ if (Predicate.isObject(input)) {
117
+ return Object.fromEntries(
118
+ Object.keys(input)
119
+ .sort()
120
+ .map((key) => [key, canonical(input[key])]),
121
+ );
122
+ }
123
+ return input;
124
+ };
125
+ return JSON.stringify(canonical(value));
126
+ };
127
+
128
+ /**
129
+ * Content-addressed: the same request in the same session maps to one
130
+ * identity. The attempt number is added by `claimLaunch`, which reuses an
131
+ * unfinished run and starts a new attempt once the run is terminal.
132
+ */
133
+ export const requestId = (sessionId: string, request: object): string =>
134
+ `run:${sessionId}:${createHash("sha256").update(stableJson(request)).digest("hex").slice(0, 16)}`;
@@ -0,0 +1,44 @@
1
+ import { mkdtemp, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { assert, it } from "@effect/vitest";
5
+ import { DEFAULTS, readDelegatesConfig } from "./config.ts";
6
+
7
+ it("delegates.json overrides the caps and default turn limit", async () => {
8
+ const agentDir = await mkdtemp(join(tmpdir(), "delegates-config-"));
9
+ await writeFile(
10
+ join(agentDir, "delegates.json"),
11
+ JSON.stringify({
12
+ caps: { laneCap: 2, sessionCeiling: 3 },
13
+ defaults: { maxTurns: 7, launchWaitMs: 1000 },
14
+ }),
15
+ );
16
+ assert.deepStrictEqual(readDelegatesConfig(agentDir), {
17
+ laneCap: 2,
18
+ sessionCeiling: 3,
19
+ maxTurns: 7,
20
+ launchWaitMs: 1000,
21
+ diagnostics: [],
22
+ });
23
+ });
24
+
25
+ it("an absent file yields the defaults", () => {
26
+ assert.deepStrictEqual(readDelegatesConfig("/does/not/exist"), {
27
+ ...DEFAULTS,
28
+ diagnostics: [],
29
+ });
30
+ });
31
+
32
+ it("a malformed file yields the defaults plus one diagnostic naming the path", async () => {
33
+ const agentDir = await mkdtemp(join(tmpdir(), "delegates-config-"));
34
+ const path = join(agentDir, "delegates.json");
35
+ await writeFile(path, "{ not json");
36
+ const config = readDelegatesConfig(agentDir);
37
+ assert.strictEqual(config.laneCap, DEFAULTS.laneCap);
38
+ assert.strictEqual(config.sessionCeiling, DEFAULTS.sessionCeiling);
39
+ assert.strictEqual(config.maxTurns, DEFAULTS.maxTurns);
40
+ assert.strictEqual(config.launchWaitMs, DEFAULTS.launchWaitMs);
41
+ assert.strictEqual(config.diagnostics.length, 1);
42
+ assert.strictEqual(config.diagnostics[0]?.code, "config.invalid_json");
43
+ assert.ok(config.diagnostics[0]?.detail.includes(path), String(config.diagnostics[0]?.detail));
44
+ });
@@ -0,0 +1,87 @@
1
+ import { Predicate } from "effect";
2
+ import { readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+
5
+ export interface ConfigDiagnostic {
6
+ /** A stable identifier: `config.<problem>`. */
7
+ readonly code: string;
8
+ /** Display-only text that names the file and the problem. */
9
+ readonly detail: string;
10
+ }
11
+
12
+ export interface DelegatesConfig {
13
+ readonly laneCap: number;
14
+ readonly sessionCeiling: number;
15
+ readonly maxTurns: number;
16
+ readonly launchWaitMs: number;
17
+ readonly diagnostics: readonly ConfigDiagnostic[];
18
+ }
19
+
20
+ export const DEFAULTS: Omit<DelegatesConfig, "diagnostics"> = {
21
+ laneCap: 4,
22
+ sessionCeiling: 8,
23
+ maxTurns: 40,
24
+ launchWaitMs: 600_000,
25
+ };
26
+
27
+ const isPositiveInteger = (value: unknown): value is number =>
28
+ typeof value === "number" && Number.isInteger(value) && value > 0;
29
+
30
+ /**
31
+ * Reads `<agentDir>/delegates.json`; never throws, reports problems as
32
+ * diagnostics. `read` is injectable so tests need no file system.
33
+ */
34
+ export const readDelegatesConfig = (
35
+ agentDir: string,
36
+ read: (path: string) => string | undefined = (path) => {
37
+ try {
38
+ return readFileSync(path, "utf8");
39
+ } catch {
40
+ return undefined;
41
+ }
42
+ },
43
+ ): DelegatesConfig => {
44
+ const path = join(agentDir, "delegates.json");
45
+ const text = read(path);
46
+ if (text === undefined) return { ...DEFAULTS, diagnostics: [] };
47
+
48
+ let parsed: unknown;
49
+ try {
50
+ parsed = JSON.parse(text);
51
+ } catch (error) {
52
+ return {
53
+ ...DEFAULTS,
54
+ diagnostics: [
55
+ { code: "config.invalid_json", detail: `${path} is not valid JSON: ${String(error)}` },
56
+ ],
57
+ };
58
+ }
59
+
60
+ if (!Predicate.isObject(parsed)) {
61
+ return {
62
+ ...DEFAULTS,
63
+ diagnostics: [{ code: "config.not_object", detail: `${path} must hold a JSON object.` }],
64
+ };
65
+ }
66
+
67
+ const caps = Predicate.isObject(parsed.caps) ? parsed.caps : {};
68
+ const defaults = Predicate.isObject(parsed.defaults) ? parsed.defaults : {};
69
+ const diagnostics: ConfigDiagnostic[] = [];
70
+ const pick = (value: unknown, fallback: number, name: string): number => {
71
+ if (value === undefined) return fallback;
72
+ if (isPositiveInteger(value)) return value;
73
+ diagnostics.push({
74
+ code: "config.invalid_value",
75
+ detail: `${path}: ${name} must be a positive integer; using ${fallback}.`,
76
+ });
77
+ return fallback;
78
+ };
79
+
80
+ return {
81
+ laneCap: pick(caps.laneCap, DEFAULTS.laneCap, "caps.laneCap"),
82
+ sessionCeiling: pick(caps.sessionCeiling, DEFAULTS.sessionCeiling, "caps.sessionCeiling"),
83
+ maxTurns: pick(defaults.maxTurns, DEFAULTS.maxTurns, "defaults.maxTurns"),
84
+ launchWaitMs: pick(defaults.launchWaitMs, DEFAULTS.launchWaitMs, "defaults.launchWaitMs"),
85
+ diagnostics,
86
+ };
87
+ };
@@ -0,0 +1,19 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
3
+ import { operationContext } from "./context.ts";
4
+
5
+ it("a call with no signal uses the background context itself", () => {
6
+ assert.strictEqual(operationContext(), BACKGROUND_CONTEXT);
7
+ assert.strictEqual(operationContext(undefined), BACKGROUND_CONTEXT);
8
+ });
9
+
10
+ it("a call with a signal carries the caller's cancellation", () => {
11
+ const controller = new AbortController();
12
+ const context = operationContext(controller.signal);
13
+
14
+ assert.notStrictEqual(context, BACKGROUND_CONTEXT);
15
+ assert.strictEqual(context.abortSignal?.aborted, false);
16
+ controller.abort();
17
+ assert.strictEqual(context.abortSignal?.aborted, true);
18
+ assert.strictEqual(BACKGROUND_CONTEXT.abortSignal, undefined);
19
+ });
@@ -0,0 +1,9 @@
1
+ import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
2
+ import type { Context } from "@earendil-works/chord/context";
3
+
4
+ /**
5
+ * One place for the direction rule: outbound work uses the caller's signal.
6
+ * Cleanup that must finish runs with an unbounded context, built at the call site.
7
+ */
8
+ export const operationContext = (signal?: AbortSignal): Context =>
9
+ signal === undefined ? BACKGROUND_CONTEXT : withAbortSignal(signal, BACKGROUND_CONTEXT);
@@ -0,0 +1,35 @@
1
+ import { mkdtemp, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { assert, it } from "@effect/vitest";
5
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
6
+ import { getOrThrow } from "@earendil-works/pi-durable/env";
7
+ import { conversationEnv } from "./execution-env.ts";
8
+
9
+ it("a conversation reads the file its cwd names", async () => {
10
+ const dir = await mkdtemp(join(tmpdir(), "delegates-env-"));
11
+ await writeFile(join(dir, "note.txt"), "hello\n", "utf8");
12
+ const env = conversationEnv("/elsewhere")({ cwd: dir });
13
+ const text = getOrThrow(await env.readTextFile(join(dir, "note.txt"), BACKGROUND_CONTEXT));
14
+ assert.strictEqual(text, "hello\n");
15
+ });
16
+
17
+ it("a conversation without a cwd falls back to the session cwd", async () => {
18
+ const dir = await mkdtemp(join(tmpdir(), "delegates-env-"));
19
+ await writeFile(join(dir, "note.txt"), "fallback\n", "utf8");
20
+ const env = conversationEnv(dir)({});
21
+ const text = getOrThrow(await env.readTextFile(join(dir, "note.txt"), BACKGROUND_CONTEXT));
22
+ assert.strictEqual(text, "fallback\n");
23
+ });
24
+
25
+ it("a conversation runs a shell command in its cwd", async () => {
26
+ const dir = await mkdtemp(join(tmpdir(), "delegates-env-"));
27
+ const env = conversationEnv("/elsewhere")({ cwd: dir });
28
+ assert.strictEqual(env.cwd, dir);
29
+ const chunks: string[] = [];
30
+ const result = getOrThrow(
31
+ await env.exec("echo hello", { onOutput: (text) => chunks.push(text) }, BACKGROUND_CONTEXT),
32
+ );
33
+ assert.strictEqual(result.exitCode, 0);
34
+ assert.match(chunks.join(""), /hello/);
35
+ });
@@ -0,0 +1,15 @@
1
+ import type { EnvTarget } from "@earendil-works/pi-durable";
2
+ import { NodeExecutionEnv } from "@earendil-works/pi-durable/env/node";
3
+
4
+ /**
5
+ * Builds the file and shell environment of one delegate conversation.
6
+ *
7
+ * pi-durable leaves `api.env` undefined when `Harness.open` gets no `env`
8
+ * option, and then every read, write and bash tool inside a delegate fails with
9
+ * "No execution environment is configured". The conversation's own `cwd` wins;
10
+ * the session cwd is the fallback shown to every local environment.
11
+ */
12
+ export const conversationEnv =
13
+ (fallbackCwd: string) =>
14
+ (target: Pick<EnvTarget, "cwd">): NodeExecutionEnv =>
15
+ new NodeExecutionEnv({ cwd: target.cwd ?? fallbackCwd });
@@ -0,0 +1,86 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { Effect } from "effect";
3
+ import { throws } from "../../test-support/assertions.ts";
4
+ import type { AdmissionHost } from "../domain/orchestration/admission.ts";
5
+ import { WORKFLOW_SECTION_KEY, refusingSandbox } from "../domain/orchestration/workflow-section.ts";
6
+ import {
7
+ CODING_EXTENSION,
8
+ CODEMODE_EXTENSION,
9
+ GATE_GUARD_EXTENSION,
10
+ RUN_TASK_EXTENSION,
11
+ RUNS_EXTENSION,
12
+ SKILLS_EXTENSION,
13
+ QUESTIONS_EXTENSION,
14
+ } from "../domain/names.ts";
15
+ import type { SkillsService } from "../domain/skills.ts";
16
+ import { createDelegatesRegistry } from "./extensions.ts";
17
+
18
+ const skills: SkillsService = {
19
+ all: () => [],
20
+ find: () => undefined,
21
+ resolve: () => [],
22
+ render: () => "",
23
+ diagnostics: () => [],
24
+ reload: Effect.void,
25
+ };
26
+
27
+ const admission: AdmissionHost = {
28
+ inspect: () => Promise.reject(new Error("the install must not inspect the harness")),
29
+ caps: () => ({ laneCap: 1, sessionCeiling: 1 }),
30
+ pollMs: 10,
31
+ };
32
+
33
+ /** One installation over the refusing sandbox, so no worker starts. */
34
+ const install = () => createDelegatesRegistry({ admission, skills, sandbox: refusingSandbox() });
35
+
36
+ it("the registry installs the eight extensions in contract order", () => {
37
+ const installed = install()
38
+ .registry.snapshot()
39
+ .installed()
40
+ .map((extension) => extension.name);
41
+
42
+ assert.deepStrictEqual(installed, [
43
+ CODING_EXTENSION,
44
+ SKILLS_EXTENSION,
45
+ "tool-search",
46
+ GATE_GUARD_EXTENSION,
47
+ CODEMODE_EXTENSION,
48
+ RUNS_EXTENSION,
49
+ RUN_TASK_EXTENSION,
50
+ QUESTIONS_EXTENSION,
51
+ ]);
52
+ });
53
+
54
+ it("code mode is installed before the run tools that script it", () => {
55
+ const installed = install()
56
+ .registry.snapshot()
57
+ .installed()
58
+ .map((extension) => extension.name);
59
+
60
+ assert.ok(installed.indexOf(CODEMODE_EXTENSION) < installed.indexOf(RUNS_EXTENSION));
61
+ });
62
+
63
+ it("the registry registers the run and fanout tasks themselves", () => {
64
+ const { registry, tasks } = install();
65
+ const registered = registry.snapshot().tasks();
66
+
67
+ assert.ok(registered.includes(tasks.run));
68
+ assert.ok(registered.includes(tasks.fanout));
69
+ });
70
+
71
+ it("the registry carries the skills and workflow sections", () => {
72
+ const keys = install()
73
+ .registry.snapshot()
74
+ .sections()
75
+ .map((entry) => entry.section.key);
76
+
77
+ assert.ok(keys.includes(SKILLS_EXTENSION));
78
+ assert.ok(keys.includes(WORKFLOW_SECTION_KEY));
79
+ });
80
+
81
+ it("the installation's sandbox names a failed start", () => {
82
+ throws(
83
+ () => install().sandbox.start("1", {} as never),
84
+ /workflow sandbox: this runtime runs no script/,
85
+ );
86
+ });
@@ -0,0 +1,140 @@
1
+ import {
2
+ createRegistry,
3
+ defineExtension,
4
+ section,
5
+ type Registry,
6
+ type Task,
7
+ } from "@earendil-works/pi-durable";
8
+ import { CodingTools } from "@earendil-works/pi-durable/tools";
9
+ import { createCodemodeExtension } from "@earendil-works/pi-durable/codemode";
10
+ import { createToolSearchExtension } from "@earendil-works/pi-durable/tool-search";
11
+ import { CodemodeSandbox } from "@earendil-works/pi-codemode";
12
+ import type { CodemodeSandboxBase } from "@earendil-works/pi-codemode/portable";
13
+ import {
14
+ CODEMODE_EXTENSION,
15
+ GATE_GUARD_EXTENSION,
16
+ QUESTIONS_EXTENSION,
17
+ RUN_TASK_EXTENSION,
18
+ SKILLS_EXTENSION,
19
+ } from "../domain/names.ts";
20
+ import { gatedTool } from "../domain/orchestration/gates.ts";
21
+ import { askTool } from "../domain/orchestration/requests.ts";
22
+ import { createRunsExtension, diagnosticSandbox } from "../domain/orchestration/workflow.ts";
23
+ import { ToolkitDoc } from "../domain/toolkit.ts";
24
+ import type { SkillsService } from "../domain/skills.ts";
25
+ import {
26
+ createRunTask,
27
+ type RunInput,
28
+ type RunResult,
29
+ type RunState,
30
+ } from "../domain/run-records.ts";
31
+ import {
32
+ createFanoutTask,
33
+ type FanoutHooks,
34
+ type FanoutInput,
35
+ type FanoutState,
36
+ } from "../domain/orchestration/fanout.ts";
37
+ import type { AdmissionHost } from "../domain/orchestration/admission.ts";
38
+ import type { SessionRuntime } from "./session.ts";
39
+ import { nullLogSink, type LogSink } from "./log.ts";
40
+ import { systemTimers, type Timers } from "./timers.ts";
41
+ import { mcpTool, type McpHost, type McpPresence } from "./mcp.ts";
42
+
43
+ export interface RegistryDeps {
44
+ readonly admission: AdmissionHost;
45
+ /** Slice 10 adds the gate rules. */
46
+ readonly gates?: readonly unknown[];
47
+ /** The one catalogue the run task binds skill names against. */
48
+ readonly skills: SkillsService;
49
+ /**
50
+ * The session runtime, resolved lazily: the registry is built before the
51
+ * harness opens. Omitted by the read-only runtime, whose tools fail loudly.
52
+ */
53
+ readonly runtime?: () => SessionRuntime;
54
+ /** Overrides the sandbox in tests; default one worker sandbox per runtime. */
55
+ readonly sandbox?: CodemodeSandboxBase;
56
+ /** The connected MCP servers; absent when the runtime opens none. */
57
+ readonly mcp?: McpHost;
58
+ /** Lazy MCP presence for the run task's binder; absent in the viewer. */
59
+ readonly mcpPresence?: () => McpPresence | undefined;
60
+ /** The sink an MCP call writes a timeout to; default none. */
61
+ readonly log?: LogSink;
62
+ /** The timer source an MCP call bounds itself with; default `systemTimers`. */
63
+ readonly timers?: Timers;
64
+ }
65
+
66
+ export interface DelegatesTasks {
67
+ readonly run: Task<RunInput, RunState, RunResult, Record<never, never>>;
68
+ readonly fanout: Task<FanoutInput, FanoutState, RunResult, FanoutHooks>;
69
+ }
70
+
71
+ export interface DelegatesInstallation {
72
+ readonly registry: Registry;
73
+ readonly tasks: DelegatesTasks;
74
+ readonly sandbox: CodemodeSandboxBase;
75
+ }
76
+
77
+ /** The one skills renderer: it reads the committed document, never a live copy. */
78
+ const skillsSection = (skills: SkillsService) =>
79
+ section("skills", async (input, context) => {
80
+ const doc = await input.read.snapshot(ToolkitDoc, input.conversationId, context);
81
+ const names = doc?.skills ?? [];
82
+ if (names.length === 0) return undefined;
83
+ const found = skills.resolve(names);
84
+ if (found.length === 0) return undefined;
85
+ const text = skills.render(found);
86
+ return text === "" ? undefined : text;
87
+ });
88
+
89
+ /** The durable extension set: `coding`, `skills`, the gate guard, code mode, the
90
+ * run tools and the run tasks. Install order is a contract: code mode comes
91
+ * before the run tools, which it exposes to scripts.
92
+ */
93
+ export const createDelegatesRegistry = (deps: RegistryDeps): DelegatesInstallation => {
94
+ const run = createRunTask(deps.admission, deps.skills, deps.mcpPresence ?? (() => undefined));
95
+ const fanout = createFanoutTask(deps.admission, run);
96
+ const sandbox = diagnosticSandbox(deps.sandbox ?? new CodemodeSandbox());
97
+ const registry = createRegistry();
98
+ registry.install(CodingTools);
99
+ registry.install(
100
+ defineExtension({ name: SKILLS_EXTENSION, sections: [skillsSection(deps.skills)] }),
101
+ );
102
+ for (const connection of deps.mcp?.connections ?? []) {
103
+ registry.install(
104
+ defineExtension({
105
+ name: connection.extension,
106
+ namespace: {
107
+ name: connection.namespace,
108
+ description: `MCP server ${connection.server}`,
109
+ },
110
+ tools: connection.tools.map((tool) =>
111
+ mcpTool(connection, tool, {
112
+ log: deps.log ?? nullLogSink,
113
+ timers: deps.timers ?? systemTimers,
114
+ timeout: connection.timeout,
115
+ }),
116
+ ),
117
+ }),
118
+ );
119
+ }
120
+ // Installed always, so a child that selects it finds it; the binder adds it for a deferred tool.
121
+ registry.install(createToolSearchExtension());
122
+ registry.install(
123
+ defineExtension({
124
+ name: GATE_GUARD_EXTENSION,
125
+ tools: (CodingTools.tools ?? []).map((tool) => gatedTool(tool)),
126
+ }),
127
+ );
128
+ registry.install(
129
+ defineExtension({
130
+ ...createCodemodeExtension({ sandbox, models: false }),
131
+ name: CODEMODE_EXTENSION,
132
+ }),
133
+ );
134
+ registry.install(createRunsExtension(deps.runtime));
135
+ registry.install(defineExtension({ name: RUN_TASK_EXTENSION, tasks: [run, fanout] }));
136
+ registry.install(
137
+ defineExtension({ name: QUESTIONS_EXTENSION, tools: [askTool(deps.log ?? nullLogSink)] }),
138
+ );
139
+ return { registry, tasks: { run, fanout }, sandbox };
140
+ };