@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.
- package/CHANGELOG.md +51 -0
- package/OPERATIONS.md +79 -6
- package/README.md +25 -17
- package/ROADMAP.md +21 -0
- package/TESTING.md +153 -318
- package/package.json +4 -3
- package/skills/pi-delegates/SKILL.md +29 -0
- package/skills/pi-delegates/references/launch.md +28 -0
- package/src/docs-contract.test.ts +106 -0
- package/src/domain/definitions.ts +3 -1
- package/src/domain/failure.ts +33 -0
- package/src/domain/model-source.ts +30 -0
- package/src/domain/orchestration/control.test.ts +69 -35
- package/src/domain/orchestration/control.ts +110 -89
- package/src/domain/orchestration/fanout.test.ts +125 -20
- package/src/domain/orchestration/fanout.ts +60 -22
- package/src/domain/orchestration/gates.test.ts +14 -15
- package/src/domain/orchestration/launch.test.ts +210 -11
- package/src/domain/orchestration/launch.ts +142 -32
- package/src/domain/orchestration/requests.test.ts +11 -16
- package/src/domain/orchestration/requests.ts +14 -1
- package/src/domain/orchestration/review.test.ts +89 -11
- package/src/domain/orchestration/run-wait.test.ts +4 -1
- package/src/domain/orchestration/run-wait.ts +1 -1
- package/src/domain/orchestration/workflow.test.ts +157 -16
- package/src/domain/orchestration/workflow.ts +269 -196
- package/src/domain/run-records.ts +214 -52
- package/src/domain/settlement.test.ts +186 -0
- package/src/domain/settlement.ts +137 -0
- package/src/domain/shapes.test.ts +20 -0
- package/src/domain/skills.test.ts +31 -20
- package/src/domain/skills.ts +36 -19
- package/src/domain/toolkit.test.ts +15 -1
- package/src/domain/toolkit.ts +8 -13
- package/src/domain/turn-budget.test.ts +37 -0
- package/src/domain/turn-budget.ts +23 -0
- package/src/domain/view.test.ts +78 -14
- package/src/domain/view.ts +67 -35
- package/src/extension/commands.test.ts +27 -23
- package/src/extension/commands.ts +10 -7
- package/src/extension/entry.test.ts +214 -56
- package/src/extension/entry.ts +78 -40
- package/src/extension/gate-alerts.test.ts +10 -8
- package/src/extension/inspector-command.test.ts +173 -21
- package/src/extension/inspector-command.ts +100 -53
- package/src/extension/prompt.test.ts +2 -4
- package/src/extension/retry-observer.test.ts +292 -0
- package/src/extension/retry-observer.ts +150 -0
- package/src/extension/settle-alerts.test.ts +579 -0
- package/src/extension/settle-alerts.ts +175 -0
- package/src/extension/shortcut.test.ts +6 -8
- package/src/extension/tools.test.ts +325 -24
- package/src/extension/tools.ts +61 -13
- package/src/extension/version.test.ts +21 -29
- package/src/goldens.test.ts +294 -0
- package/src/harness-policy.test.ts +13 -11
- package/src/layers.test.ts +309 -0
- package/src/layers.ts +405 -0
- package/src/package-manifest.test.ts +32 -19
- package/src/presentation/actions.test.ts +8 -8
- package/src/presentation/activity.test.ts +7 -8
- package/src/presentation/close.test.ts +14 -16
- package/src/presentation/inspector.test.ts +14 -11
- package/src/presentation/inspector.ts +27 -25
- package/src/presentation/overlay.test.ts +1 -3
- package/src/presentation/repaint.test.ts +226 -190
- package/src/presentation/snapshot.test.ts +5 -0
- package/src/presentation/status.test.ts +43 -0
- package/src/presentation/status.ts +30 -0
- package/src/presentation/strip.test.ts +13 -6
- package/src/presentation/strip.ts +7 -14
- package/src/presentation/wording.test.ts +153 -3
- package/src/presentation/wording.ts +78 -6
- package/src/runtime/bridge.ts +38 -44
- package/src/runtime/{timers.test.ts → clock.test.ts} +1 -1
- package/src/runtime/clock.ts +31 -0
- package/src/runtime/config.test.ts +26 -7
- package/src/runtime/config.ts +6 -1
- package/src/runtime/execution-env.test.ts +6 -8
- package/src/runtime/extensions.test.ts +4 -4
- package/src/runtime/extensions.ts +23 -11
- package/src/runtime/handle.ts +54 -0
- package/src/runtime/log.test.ts +19 -7
- package/src/runtime/log.ts +23 -0
- package/src/runtime/mcp.test.ts +29 -32
- package/src/runtime/mcp.ts +70 -3
- package/src/runtime/runtime-state.test.ts +25 -0
- package/src/runtime/runtime-state.ts +36 -0
- package/src/runtime/session-tag.ts +11 -0
- package/src/runtime/session.test.ts +24 -31
- package/src/runtime/session.ts +99 -261
- package/src/runtime/storage.ts +29 -0
- package/src/test-hygiene.test.ts +97 -0
- package/src/runtime/timers.ts +0 -10
|
@@ -20,8 +20,8 @@ import {
|
|
|
20
20
|
import { gatedTool } from "../domain/orchestration/gates.ts";
|
|
21
21
|
import { askTool } from "../domain/orchestration/requests.ts";
|
|
22
22
|
import { createRunsExtension, diagnosticSandbox } from "../domain/orchestration/workflow.ts";
|
|
23
|
+
import type { SkillsCatalogue } from "../domain/skills.ts";
|
|
23
24
|
import { ToolkitDoc } from "../domain/toolkit.ts";
|
|
24
|
-
import type { SkillsService } from "../domain/skills.ts";
|
|
25
25
|
import {
|
|
26
26
|
createRunTask,
|
|
27
27
|
type RunInput,
|
|
@@ -35,9 +35,11 @@ import {
|
|
|
35
35
|
type FanoutState,
|
|
36
36
|
} from "../domain/orchestration/fanout.ts";
|
|
37
37
|
import type { AdmissionHost } from "../domain/orchestration/admission.ts";
|
|
38
|
-
import type {
|
|
38
|
+
import type { Ref } from "effect";
|
|
39
|
+
import type { SessionHandle } from "../runtime/handle.ts";
|
|
39
40
|
import { nullLogSink, type LogSink } from "./log.ts";
|
|
40
|
-
import {
|
|
41
|
+
import type { SettleSignal } from "../domain/settlement.ts";
|
|
42
|
+
import { systemTimers, type Timers } from "./clock.ts";
|
|
41
43
|
import { mcpTool, type McpHost, type McpPresence } from "./mcp.ts";
|
|
42
44
|
|
|
43
45
|
export interface RegistryDeps {
|
|
@@ -45,12 +47,13 @@ export interface RegistryDeps {
|
|
|
45
47
|
/** Slice 10 adds the gate rules. */
|
|
46
48
|
readonly gates?: readonly unknown[];
|
|
47
49
|
/** The one catalogue the run task binds skill names against. */
|
|
48
|
-
readonly skills:
|
|
50
|
+
readonly skills: SkillsCatalogue["Service"];
|
|
49
51
|
/**
|
|
50
|
-
* The session
|
|
51
|
-
*
|
|
52
|
+
* The live session handle, read at tool-call time: the registry is built
|
|
53
|
+
* before the graph fills it. Omitted by the read-only runtime, whose tools
|
|
54
|
+
* fail loudly.
|
|
52
55
|
*/
|
|
53
|
-
readonly
|
|
56
|
+
readonly session?: Ref.Ref<SessionHandle | undefined>;
|
|
54
57
|
/** Overrides the sandbox in tests; default one worker sandbox per runtime. */
|
|
55
58
|
readonly sandbox?: CodemodeSandboxBase;
|
|
56
59
|
/** The connected MCP servers; absent when the runtime opens none. */
|
|
@@ -61,6 +64,8 @@ export interface RegistryDeps {
|
|
|
61
64
|
readonly log?: LogSink;
|
|
62
65
|
/** The timer source an MCP call bounds itself with; default `systemTimers`. */
|
|
63
66
|
readonly timers?: Timers;
|
|
67
|
+
/** The session's settle signal, emitted by every terminal run commit. */
|
|
68
|
+
readonly settle?: SettleSignal;
|
|
64
69
|
}
|
|
65
70
|
|
|
66
71
|
export interface DelegatesTasks {
|
|
@@ -75,7 +80,7 @@ export interface DelegatesInstallation {
|
|
|
75
80
|
}
|
|
76
81
|
|
|
77
82
|
/** The one skills renderer: it reads the committed document, never a live copy. */
|
|
78
|
-
const skillsSection = (skills:
|
|
83
|
+
const skillsSection = (skills: SkillsCatalogue["Service"]) =>
|
|
79
84
|
section("skills", async (input, context) => {
|
|
80
85
|
const doc = await input.read.snapshot(ToolkitDoc, input.conversationId, context);
|
|
81
86
|
const names = doc?.skills ?? [];
|
|
@@ -91,8 +96,15 @@ const skillsSection = (skills: SkillsService) =>
|
|
|
91
96
|
* before the run tools, which it exposes to scripts.
|
|
92
97
|
*/
|
|
93
98
|
export const createDelegatesRegistry = (deps: RegistryDeps): DelegatesInstallation => {
|
|
94
|
-
const
|
|
95
|
-
const
|
|
99
|
+
const log = deps.log ?? nullLogSink;
|
|
100
|
+
const run = createRunTask(
|
|
101
|
+
deps.admission,
|
|
102
|
+
deps.skills,
|
|
103
|
+
deps.mcpPresence ?? (() => undefined),
|
|
104
|
+
log,
|
|
105
|
+
deps.settle,
|
|
106
|
+
);
|
|
107
|
+
const fanout = createFanoutTask(deps.admission, run, deps.settle);
|
|
96
108
|
const sandbox = diagnosticSandbox(deps.sandbox ?? new CodemodeSandbox());
|
|
97
109
|
const registry = createRegistry();
|
|
98
110
|
registry.install(CodingTools);
|
|
@@ -131,7 +143,7 @@ export const createDelegatesRegistry = (deps: RegistryDeps): DelegatesInstallati
|
|
|
131
143
|
name: CODEMODE_EXTENSION,
|
|
132
144
|
}),
|
|
133
145
|
);
|
|
134
|
-
registry.install(createRunsExtension(deps.
|
|
146
|
+
registry.install(createRunsExtension(deps.session));
|
|
135
147
|
registry.install(defineExtension({ name: RUN_TASK_EXTENSION, tasks: [run, fanout] }));
|
|
136
148
|
registry.install(
|
|
137
149
|
defineExtension({ name: QUESTIONS_EXTENSION, tools: [askTool(deps.log ?? nullLogSink)] }),
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { Context as EffectContext } from "effect";
|
|
2
|
+
import type { Effect, Layer } from "effect";
|
|
3
|
+
import type { ModelSourceService } from "../domain/model-source.ts";
|
|
4
|
+
import type { WorkflowService } from "../domain/orchestration/workflow.ts";
|
|
5
|
+
import type { SkillsCatalogue } from "../domain/skills.ts";
|
|
6
|
+
import type { DurableBridge } from "./bridge.ts";
|
|
7
|
+
import type { ClockService, TimersService } from "./clock.ts";
|
|
8
|
+
import type { LogSinkService } from "./log.ts";
|
|
9
|
+
import type { McpHostService } from "./mcp.ts";
|
|
10
|
+
import type { HarnessParts, SessionRuntime } from "./session.ts";
|
|
11
|
+
import type { SessionRuntimeTag } from "./session-tag.ts";
|
|
12
|
+
import type { StorageError, StorageService } from "./storage.ts";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The shape of one opened session, as a leaf module. `runtime`, `domain` and
|
|
16
|
+
* `extension` modules name the handle without loading `src/layers.ts`, so the
|
|
17
|
+
* composition root depends on them and never the other way round. Only
|
|
18
|
+
* `src/layers.ts` builds the graph these types describe.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/** Every service the seam layer provides. */
|
|
22
|
+
export type SessionSeams =
|
|
23
|
+
| StorageService
|
|
24
|
+
| ClockService
|
|
25
|
+
| TimersService
|
|
26
|
+
| LogSinkService
|
|
27
|
+
| ModelSourceService
|
|
28
|
+
| SkillsCatalogue
|
|
29
|
+
| McpHostService;
|
|
30
|
+
|
|
31
|
+
/** The opened session, exactly once; its close runs in the graph's scope. */
|
|
32
|
+
export class SessionCore extends EffectContext.Service<SessionCore, HarnessParts>()(
|
|
33
|
+
"@ftrdotdev/pi-delegates/runtime/handle/SessionCore",
|
|
34
|
+
) {}
|
|
35
|
+
|
|
36
|
+
export type SessionGraphLayer = Layer.Layer<
|
|
37
|
+
SessionRuntimeTag | WorkflowService | DurableBridge | SessionCore | SessionSeams,
|
|
38
|
+
StorageError
|
|
39
|
+
>;
|
|
40
|
+
|
|
41
|
+
/** What the graph provides: every tag a `SessionHandle.run` effect may require. */
|
|
42
|
+
export type SessionGraph = Layer.Success<SessionGraphLayer>;
|
|
43
|
+
|
|
44
|
+
/** One opened session: the runtime, its graph context, and the close that owns the scope. */
|
|
45
|
+
export interface SessionHandle {
|
|
46
|
+
readonly runtime: SessionRuntime;
|
|
47
|
+
/**
|
|
48
|
+
* Provides the graph context; the `ManagedRuntime` never leaves `src/layers.ts`.
|
|
49
|
+
* `R` is covariant, so an effect that requires one graph service fits as well.
|
|
50
|
+
*/
|
|
51
|
+
readonly run: <A, E>(effect: Effect.Effect<A, E, SessionGraph>) => Effect.Effect<A, E>;
|
|
52
|
+
/** `ManagedRuntime.dispose`, bounded by the caller's `closeWithin`; already re-awaitable. */
|
|
53
|
+
readonly close: () => Promise<void>;
|
|
54
|
+
}
|
package/src/runtime/log.test.ts
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import { readFileSync } from "node:fs";
|
|
2
|
-
import { mkdtemp, writeFile } from "node:fs/promises";
|
|
3
|
-
import { tmpdir } from "node:os";
|
|
4
|
-
import { join } from "node:path";
|
|
5
1
|
import { assert, it } from "@effect/vitest";
|
|
2
|
+
import { join, makeTempDir, readText, writeText } from "../../test-support/platform.ts";
|
|
6
3
|
import type { Report } from "@earendil-works/pi-durable";
|
|
7
4
|
import {
|
|
5
|
+
errorFields,
|
|
6
|
+
failureDetailText,
|
|
8
7
|
fileLogSink,
|
|
9
8
|
logReport,
|
|
10
9
|
reasonOf,
|
|
@@ -14,7 +13,7 @@ import {
|
|
|
14
13
|
type LogSink,
|
|
15
14
|
} from "./log.ts";
|
|
16
15
|
|
|
17
|
-
const scratch = () =>
|
|
16
|
+
const scratch = () => makeTempDir("delegates-log-");
|
|
18
17
|
|
|
19
18
|
it("the file sink appends one JSON object per line", async () => {
|
|
20
19
|
const path = join(await scratch(), "delegates.log");
|
|
@@ -22,7 +21,7 @@ it("the file sink appends one JSON object per line", async () => {
|
|
|
22
21
|
sink.write("info", "a.one", { taskId: 7 });
|
|
23
22
|
sink.write("warn", "b.two");
|
|
24
23
|
|
|
25
|
-
const lines =
|
|
24
|
+
const lines = (await readText(path)).trim().split("\n");
|
|
26
25
|
assert.strictEqual(lines.length, 2);
|
|
27
26
|
const first = JSON.parse(lines[0] ?? "") as Record<string, unknown>;
|
|
28
27
|
assert.strictEqual(first.level, "info");
|
|
@@ -34,7 +33,7 @@ it("the file sink appends one JSON object per line", async () => {
|
|
|
34
33
|
|
|
35
34
|
it("the file sink never throws when its path cannot be written", async () => {
|
|
36
35
|
const blocker = join(await scratch(), "blocker");
|
|
37
|
-
await
|
|
36
|
+
await writeText(blocker, "not a directory");
|
|
38
37
|
const sink = fileLogSink(join(blocker, "delegates.log"));
|
|
39
38
|
assert.doesNotThrow(() => sink.write("error", "broken.write"));
|
|
40
39
|
});
|
|
@@ -46,6 +45,19 @@ it("truncate keeps at most its maximum and reasonOf reads a message", () => {
|
|
|
46
45
|
assert.strictEqual(reasonOf("text"), "text");
|
|
47
46
|
});
|
|
48
47
|
|
|
48
|
+
it("the failure detail elides the middle and keeps both ends", () => {
|
|
49
|
+
const long = `429: rate limit exceeded ${"x".repeat(300)} request_id=abc123`;
|
|
50
|
+
const text = failureDetailText(long);
|
|
51
|
+
assert.strictEqual(text?.length, 200);
|
|
52
|
+
assert.ok(text?.startsWith("429: rate limit exceeded"), text ?? "");
|
|
53
|
+
assert.ok(text?.endsWith("request_id=abc123"), text ?? "");
|
|
54
|
+
assert.ok(text?.includes("..."), text ?? "");
|
|
55
|
+
assert.strictEqual(failureDetailText(undefined), null);
|
|
56
|
+
assert.strictEqual(failureDetailText(""), null);
|
|
57
|
+
assert.strictEqual(failureDetailText("120 turns"), "120 turns");
|
|
58
|
+
assert.strictEqual(String(errorFields(new Error("y".repeat(500))).detail).length, 200);
|
|
59
|
+
});
|
|
60
|
+
|
|
49
61
|
const reportTask = { id: 7 as never, kind: "delegates.run", conversationId: 3 as never };
|
|
50
62
|
const reportError = new Error("boom");
|
|
51
63
|
|
package/src/runtime/log.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Report } from "@earendil-works/pi-durable";
|
|
2
|
+
import { Context, Layer } from "effect";
|
|
2
3
|
import { appendFileSync } from "node:fs";
|
|
3
4
|
|
|
4
5
|
export type LogLevel = "debug" | "info" | "warn" | "error";
|
|
@@ -10,9 +11,31 @@ export interface LogSink {
|
|
|
10
11
|
|
|
11
12
|
export const nullLogSink: LogSink = { write: () => {} };
|
|
12
13
|
|
|
14
|
+
/** The session's one sink; every surface writes diagnostics through it. */
|
|
15
|
+
export class LogSinkService extends Context.Service<LogSinkService, LogSink>()(
|
|
16
|
+
"@ftrdotdev/pi-delegates/runtime/log/LogSinkService",
|
|
17
|
+
) {
|
|
18
|
+
/** The one sink; the caller supplies it. */
|
|
19
|
+
static layer(sink: LogSink): Layer.Layer<LogSinkService> {
|
|
20
|
+
return Layer.succeed(LogSinkService, sink);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
13
24
|
/** `detail` is display-only: it is never parsed and never classifies state. */
|
|
14
25
|
export const DETAIL_LIMIT = 200;
|
|
15
26
|
|
|
27
|
+
export const DETAIL_ELISION = "...";
|
|
28
|
+
/** Chars kept from the head: provider text leads with the status that matters. */
|
|
29
|
+
export const DETAIL_HEAD = 120;
|
|
30
|
+
|
|
31
|
+
/** The one failure detail: at most 200 chars, middle elided, or null when absent. */
|
|
32
|
+
export const failureDetailText = (detail: string | undefined): string | null => {
|
|
33
|
+
if (detail === undefined || detail === "") return null;
|
|
34
|
+
if (detail.length <= DETAIL_LIMIT) return detail;
|
|
35
|
+
const tail = DETAIL_LIMIT - DETAIL_HEAD - DETAIL_ELISION.length;
|
|
36
|
+
return `${detail.slice(0, DETAIL_HEAD)}${DETAIL_ELISION}${detail.slice(-tail)}`;
|
|
37
|
+
};
|
|
38
|
+
|
|
16
39
|
export const truncate = (text: string, max: number): string =>
|
|
17
40
|
text.length <= max ? text : text.slice(0, max);
|
|
18
41
|
|
package/src/runtime/mcp.test.ts
CHANGED
|
@@ -4,12 +4,10 @@ import { AgentDoc, type ToolRegistration } from "@earendil-works/pi-durable";
|
|
|
4
4
|
import type { CallToolResult, Tool } from "@earendil-works/pi-mcp";
|
|
5
5
|
import { MCP_OUTPUT_MAX_BYTES } from "@earendil-works/pi-mcp";
|
|
6
6
|
import { Effect } from "effect";
|
|
7
|
-
import { readFileSync } from "node:fs";
|
|
8
|
-
import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
|
|
9
|
-
import { tmpdir } from "node:os";
|
|
10
|
-
import { join } from "node:path";
|
|
11
7
|
import { assert, it } from "@effect/vitest";
|
|
12
8
|
import { rejects } from "../../test-support/assertions.ts";
|
|
9
|
+
import type { SkillsCatalogue } from "../domain/skills.ts";
|
|
10
|
+
import { join, makeDir, makeTempDir, readText, writeText } from "../../test-support/platform.ts";
|
|
13
11
|
import { waitFor } from "../../test-support/wait.ts";
|
|
14
12
|
import { makeStubPi } from "../../test-support/stub-pi.ts";
|
|
15
13
|
import { stubHostSource } from "../../test-support/stub-model-source.ts";
|
|
@@ -19,7 +17,6 @@ import type { HostDefaults } from "../domain/orchestration/launch.ts";
|
|
|
19
17
|
import { launch } from "../domain/orchestration/launch.ts";
|
|
20
18
|
import { refusingSandbox } from "../domain/orchestration/workflow.ts";
|
|
21
19
|
import { resolverFor, RunIndexDoc } from "../domain/run-records.ts";
|
|
22
|
-
import type { SkillsService } from "../domain/skills.ts";
|
|
23
20
|
import { bindToolkit, ToolkitUnresolved, type ToolkitResolver } from "../domain/toolkit.ts";
|
|
24
21
|
import { viewRun, viewSession } from "../domain/view.ts";
|
|
25
22
|
import { createDelegatesExtension } from "../extension/entry.ts";
|
|
@@ -36,12 +33,12 @@ import {
|
|
|
36
33
|
import { HostModelAdapter } from "./models.ts";
|
|
37
34
|
import {
|
|
38
35
|
openReadOnlyRuntime,
|
|
39
|
-
openSessionRuntime,
|
|
40
36
|
storePathFor,
|
|
41
37
|
type SessionIdentity,
|
|
42
38
|
type SessionRuntime,
|
|
43
39
|
} from "./session.ts";
|
|
44
|
-
import { systemTimers, type Timers } from "./
|
|
40
|
+
import { systemTimers, type Timers } from "./clock.ts";
|
|
41
|
+
import { openTestSession, type TestSession } from "../../test-support/seams.ts";
|
|
45
42
|
|
|
46
43
|
/** A workspace with an agent directory and a project directory, both under one temp root. */
|
|
47
44
|
const tempWorkspace = async (options: {
|
|
@@ -54,18 +51,18 @@ const tempWorkspace = async (options: {
|
|
|
54
51
|
readonly projectPath: string;
|
|
55
52
|
readonly read: (projectTrusted?: boolean) => ReturnType<typeof readMcpConfig>;
|
|
56
53
|
}> => {
|
|
57
|
-
const root = await
|
|
54
|
+
const root = await makeTempDir("delegates-mcp-");
|
|
58
55
|
const agentDir = join(root, "agent");
|
|
59
56
|
const cwd = join(root, "repo");
|
|
60
|
-
await
|
|
61
|
-
await
|
|
57
|
+
await makeDir(agentDir);
|
|
58
|
+
await makeDir(cwd);
|
|
62
59
|
const projectPath = join(cwd, ".pi", "mcp.json");
|
|
63
60
|
if (options.global !== undefined) {
|
|
64
|
-
await
|
|
61
|
+
await writeText(join(agentDir, "mcp.json"), textOf(options.global));
|
|
65
62
|
}
|
|
66
63
|
if (options.project !== undefined) {
|
|
67
|
-
await
|
|
68
|
-
await
|
|
64
|
+
await makeDir(join(cwd, ".pi"));
|
|
65
|
+
await writeText(projectPath, textOf(options.project));
|
|
69
66
|
}
|
|
70
67
|
return {
|
|
71
68
|
agentDir,
|
|
@@ -439,7 +436,7 @@ const hostFor = async (
|
|
|
439
436
|
readonly sessionDir?: string;
|
|
440
437
|
} = {},
|
|
441
438
|
): Promise<McpHost> => {
|
|
442
|
-
const sessionDir = options.sessionDir ?? (await
|
|
439
|
+
const sessionDir = options.sessionDir ?? (await makeTempDir("delegates-mcp-"));
|
|
443
440
|
return connectServers(entries, options.log ?? nullLogSink, {
|
|
444
441
|
referenced: options.referenced ?? new Set(entries.map((entry) => entry.name)),
|
|
445
442
|
timers: options.timers ?? systemTimers,
|
|
@@ -480,13 +477,13 @@ const outputText = (result: {
|
|
|
480
477
|
readonly output?: readonly { readonly type: string; readonly text?: string }[];
|
|
481
478
|
}): string => (result.output ?? []).map((item) => item.text ?? "").join("");
|
|
482
479
|
|
|
483
|
-
const skills:
|
|
480
|
+
const skills: SkillsCatalogue["Service"] = {
|
|
484
481
|
all: () => [],
|
|
485
482
|
find: () => undefined,
|
|
486
483
|
resolve: () => [],
|
|
487
484
|
render: () => "",
|
|
488
|
-
diagnostics: (
|
|
489
|
-
reload: Effect.
|
|
485
|
+
diagnostics: Effect.succeed([]),
|
|
486
|
+
reload: Effect.succeed([]),
|
|
490
487
|
};
|
|
491
488
|
|
|
492
489
|
const admission: AdmissionHost = {
|
|
@@ -808,7 +805,7 @@ it("a call stops when the run is aborted", async () => {
|
|
|
808
805
|
});
|
|
809
806
|
|
|
810
807
|
const sessionIdentity = async (sessionId: string): Promise<SessionIdentity> => {
|
|
811
|
-
const sessionDir = await
|
|
808
|
+
const sessionDir = await makeTempDir("delegates-mcp-session-");
|
|
812
809
|
return { sessionId, sessionDir, cwd: sessionDir, agentDir: sessionDir };
|
|
813
810
|
};
|
|
814
811
|
|
|
@@ -824,7 +821,7 @@ const definitionOf = (name: string, tools: readonly string[]): AgentDefinition =
|
|
|
824
821
|
});
|
|
825
822
|
|
|
826
823
|
const writeMcpJson = async (dir: string, servers: Record<string, unknown>): Promise<void> => {
|
|
827
|
-
await
|
|
824
|
+
await writeText(join(dir, "mcp.json"), JSON.stringify({ mcpServers: servers }));
|
|
828
825
|
};
|
|
829
826
|
|
|
830
827
|
it("only a referenced server connects", async () => {
|
|
@@ -832,7 +829,7 @@ it("only a referenced server connects", async () => {
|
|
|
832
829
|
await writeMcpJson(identity.agentDir, { demo: { command: "node" }, other: { command: "node" } });
|
|
833
830
|
const fake = fakeClient({ tools: [{ name: "echo", inputSchema: {} }] });
|
|
834
831
|
const { factory, asked } = fakeFactory(async () => fake.client);
|
|
835
|
-
const runtime = await
|
|
832
|
+
const runtime = await openTestSession({
|
|
836
833
|
identity,
|
|
837
834
|
models: models(),
|
|
838
835
|
catalogue: createCatalogue([definitionOf("echoer", ["read", "mcp__demo__*"])]),
|
|
@@ -858,7 +855,7 @@ it("an exact tool name references its server", async () => {
|
|
|
858
855
|
await writeMcpJson(identity.agentDir, { demo: { command: "node" } });
|
|
859
856
|
const fake = fakeClient({ tools: [{ name: "echo", inputSchema: {} }] });
|
|
860
857
|
const { factory, asked } = fakeFactory(async () => fake.client);
|
|
861
|
-
const runtime = await
|
|
858
|
+
const runtime = await openTestSession({
|
|
862
859
|
identity,
|
|
863
860
|
models: models(),
|
|
864
861
|
catalogue: createCatalogue([definitionOf("echoer", ["mcp__demo__echo"])]),
|
|
@@ -882,7 +879,7 @@ it("a runtime with no MCP reference connects nothing", async () => {
|
|
|
882
879
|
await writeMcpJson(identity.agentDir, { demo: { command: "node" } });
|
|
883
880
|
const fake = fakeClient();
|
|
884
881
|
const { factory, asked } = fakeFactory(async () => fake.client);
|
|
885
|
-
const runtime = await
|
|
882
|
+
const runtime = await openTestSession({
|
|
886
883
|
identity,
|
|
887
884
|
models: models(),
|
|
888
885
|
catalogue: createCatalogue([definitionOf("reader", ["read"])]),
|
|
@@ -914,7 +911,7 @@ it("the runtime reports unconnected servers", async () => {
|
|
|
914
911
|
return fakeClient({ tools: [{ name: "echo", inputSchema: {} }] }).client;
|
|
915
912
|
},
|
|
916
913
|
};
|
|
917
|
-
const runtime = await
|
|
914
|
+
const runtime = await openTestSession({
|
|
918
915
|
identity,
|
|
919
916
|
models: models(),
|
|
920
917
|
catalogue: createCatalogue([
|
|
@@ -931,8 +928,8 @@ it("the runtime reports unconnected servers", async () => {
|
|
|
931
928
|
});
|
|
932
929
|
|
|
933
930
|
it("session start shows one aggregated notice", async () => {
|
|
934
|
-
const sessionDir = await
|
|
935
|
-
const agentDir = await
|
|
931
|
+
const sessionDir = await makeTempDir("delegates-mcp-entry-");
|
|
932
|
+
const agentDir = await makeTempDir("delegates-mcp-agent-");
|
|
936
933
|
await writeMcpJson(agentDir, {
|
|
937
934
|
demo: { command: "/nonexistent/delegates-mcp-demo" },
|
|
938
935
|
other: { command: "/nonexistent/delegates-mcp-other" },
|
|
@@ -958,7 +955,7 @@ it("session start shows one aggregated notice", async () => {
|
|
|
958
955
|
assert.ok(notice.message.includes("other"), notice.message);
|
|
959
956
|
assert.ok(!notice.message.includes("off"), notice.message);
|
|
960
957
|
assert.ok(!notice.message.includes("unused"), notice.message);
|
|
961
|
-
const lines =
|
|
958
|
+
const lines = (await readText(join(sessionDir, "delegates.log")))
|
|
962
959
|
.trim()
|
|
963
960
|
.split("\n")
|
|
964
961
|
.map((line) => JSON.parse(line) as { code: string; detail?: string });
|
|
@@ -978,10 +975,10 @@ const openWithMcp = async (options: {
|
|
|
978
975
|
readonly definitions: readonly AgentDefinition[];
|
|
979
976
|
readonly servers: Record<string, unknown>;
|
|
980
977
|
readonly factory: McpClientFactory;
|
|
981
|
-
}): Promise<{ readonly runtime:
|
|
978
|
+
}): Promise<{ readonly runtime: TestSession; readonly identity: SessionIdentity }> => {
|
|
982
979
|
const identity = await sessionIdentity("s-1");
|
|
983
980
|
await writeMcpJson(identity.agentDir, options.servers);
|
|
984
|
-
const runtime = await
|
|
981
|
+
const runtime = await openTestSession({
|
|
985
982
|
identity,
|
|
986
983
|
models: models(),
|
|
987
984
|
catalogue: createCatalogue(options.definitions),
|
|
@@ -1299,7 +1296,7 @@ it("a large result is bounded and saved", async () => {
|
|
|
1299
1296
|
tools: [{ name: "long", inputSchema: {} }],
|
|
1300
1297
|
callTool: async () => ({ content: [{ type: "text", text: full }] }),
|
|
1301
1298
|
});
|
|
1302
|
-
const sessionDir = await
|
|
1299
|
+
const sessionDir = await makeTempDir("delegates-mcp-output-");
|
|
1303
1300
|
const host = await hostFor([entryOf("demo")], {
|
|
1304
1301
|
factory: fakeFactory(async () => fake.client).factory,
|
|
1305
1302
|
sessionDir,
|
|
@@ -1319,7 +1316,7 @@ it("a large result is bounded and saved", async () => {
|
|
|
1319
1316
|
assert.ok(match !== null, diagnostic.message);
|
|
1320
1317
|
const path = match[1]!;
|
|
1321
1318
|
assert.ok(path.startsWith(join(sessionDir, "mcp")), path);
|
|
1322
|
-
const saved =
|
|
1319
|
+
const saved = await readText(path);
|
|
1323
1320
|
assert.strictEqual(saved.length, full.length);
|
|
1324
1321
|
} finally {
|
|
1325
1322
|
await host.close();
|
|
@@ -1381,7 +1378,7 @@ it("shutdown closes connections after the harness", async () => {
|
|
|
1381
1378
|
events.push("mcp");
|
|
1382
1379
|
},
|
|
1383
1380
|
};
|
|
1384
|
-
const runtime = await
|
|
1381
|
+
const runtime = await openTestSession({
|
|
1385
1382
|
identity,
|
|
1386
1383
|
models: models(),
|
|
1387
1384
|
mcp,
|
|
@@ -1398,7 +1395,7 @@ it("a drop notifies once through the runtime", async () => {
|
|
|
1398
1395
|
const fake = fakeClient({ tools: [{ name: "echo", inputSchema: {} }] });
|
|
1399
1396
|
const notices: string[] = [];
|
|
1400
1397
|
const { sink, entries } = recordingSink();
|
|
1401
|
-
const runtime = await
|
|
1398
|
+
const runtime = await openTestSession({
|
|
1402
1399
|
identity,
|
|
1403
1400
|
models: models(),
|
|
1404
1401
|
log: sink,
|
package/src/runtime/mcp.ts
CHANGED
|
@@ -20,9 +20,10 @@ import {
|
|
|
20
20
|
import { mkdir, writeFile } from "node:fs/promises";
|
|
21
21
|
import { readFileSync } from "node:fs";
|
|
22
22
|
import { join } from "node:path";
|
|
23
|
-
import { Predicate } from "effect";
|
|
24
|
-
import { reasonOf, type LogSink } from "./log.ts";
|
|
25
|
-
import type
|
|
23
|
+
import { Context as EffectContext, Effect, Layer, Predicate } from "effect";
|
|
24
|
+
import { reasonOf, LogSinkService, type LogSink } from "./log.ts";
|
|
25
|
+
import { TimersService, type Timers } from "./clock.ts";
|
|
26
|
+
import type { DefinitionCatalogue } from "../domain/definitions.ts";
|
|
26
27
|
|
|
27
28
|
/** Where the two `mcp.json` files live; trust comes from the host, never from a file. */
|
|
28
29
|
export interface McpConfigSources {
|
|
@@ -378,6 +379,72 @@ export interface McpHost {
|
|
|
378
379
|
close(): Promise<void>;
|
|
379
380
|
}
|
|
380
381
|
|
|
382
|
+
/** The session's MCP host: every connected server, opened and closed by the seam layer. */
|
|
383
|
+
export class McpHostService extends EffectContext.Service<McpHostService, McpHost>()(
|
|
384
|
+
"@ftrdotdev/pi-delegates/runtime/mcp/McpHostService",
|
|
385
|
+
) {
|
|
386
|
+
/** The connected servers, read from the two `mcp.json` files; the seam layer owns the close. */
|
|
387
|
+
static layer(
|
|
388
|
+
options: McpHostLayerOptions,
|
|
389
|
+
): Layer.Layer<McpHostService, never, TimersService | LogSinkService> {
|
|
390
|
+
return Layer.effect(
|
|
391
|
+
McpHostService,
|
|
392
|
+
Effect.gen(function* () {
|
|
393
|
+
const timers = yield* TimersService;
|
|
394
|
+
const log = yield* LogSinkService;
|
|
395
|
+
const config = readMcpConfig({
|
|
396
|
+
agentDir: options.agentDir,
|
|
397
|
+
cwd: options.cwd,
|
|
398
|
+
projectTrusted: options.projectTrusted,
|
|
399
|
+
});
|
|
400
|
+
const mcp: McpHost = yield* Effect.acquireRelease(
|
|
401
|
+
Effect.promise(() =>
|
|
402
|
+
connectServers(config.servers, log, {
|
|
403
|
+
referenced: referencedServers(options.catalogue.all, config.servers),
|
|
404
|
+
timers,
|
|
405
|
+
sessionDir: options.sessionDir,
|
|
406
|
+
...(options.mcpFactory === undefined ? {} : { factory: options.mcpFactory }),
|
|
407
|
+
...(options.notify === undefined
|
|
408
|
+
? {}
|
|
409
|
+
: {
|
|
410
|
+
onLost: (server: string) =>
|
|
411
|
+
options.notify?.(
|
|
412
|
+
`MCP server "${server}" disconnected; its tools fail until the session restarts.`,
|
|
413
|
+
),
|
|
414
|
+
}),
|
|
415
|
+
}),
|
|
416
|
+
),
|
|
417
|
+
(host) => Effect.promise(() => host.close()),
|
|
418
|
+
);
|
|
419
|
+
for (const diagnostic of [...config.diagnostics, ...mcp.diagnostics]) {
|
|
420
|
+
log.write("warn", diagnostic.code, { detail: diagnostic.detail });
|
|
421
|
+
}
|
|
422
|
+
return McpHostService.of(mcp);
|
|
423
|
+
}),
|
|
424
|
+
);
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** A host a test already opened: the seam layer adopts it and closes it. */
|
|
428
|
+
static adopt(host: McpHost): Layer.Layer<McpHostService> {
|
|
429
|
+
return Layer.effect(
|
|
430
|
+
McpHostService,
|
|
431
|
+
Effect.acquireRelease(Effect.succeed(host), (value) => Effect.promise(() => value.close())),
|
|
432
|
+
);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/** What the seam layer hands the MCP host; the graph reads it from the session config. */
|
|
437
|
+
export interface McpHostLayerOptions {
|
|
438
|
+
readonly agentDir: string;
|
|
439
|
+
readonly cwd: string;
|
|
440
|
+
readonly sessionDir: string;
|
|
441
|
+
readonly projectTrusted: boolean;
|
|
442
|
+
readonly catalogue: DefinitionCatalogue;
|
|
443
|
+
/** The transport seam: a test injects one and never starts a process. */
|
|
444
|
+
readonly mcpFactory?: McpClientFactory | undefined;
|
|
445
|
+
readonly notify?: ((message: string) => void) | undefined;
|
|
446
|
+
}
|
|
447
|
+
|
|
381
448
|
/** The four calls this package makes on a client; the rest of `McpClient` is not used. */
|
|
382
449
|
export interface McpClientPort {
|
|
383
450
|
listTools(): Promise<Tool[]>;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { assert, it } from "@effect/vitest";
|
|
2
|
+
|
|
3
|
+
import { makeRuntimeState } from "./runtime-state.ts";
|
|
4
|
+
|
|
5
|
+
it("setState notifies every listener and a detached listener hears nothing", () => {
|
|
6
|
+
const machine = makeRuntimeState();
|
|
7
|
+
const heard: string[] = [];
|
|
8
|
+
const detach = machine.onState((state) => heard.push(state.kind));
|
|
9
|
+
machine.onState((state) => heard.push(`second:${state.kind}`));
|
|
10
|
+
|
|
11
|
+
machine.setState({ kind: "ready" });
|
|
12
|
+
detach();
|
|
13
|
+
machine.setState({ kind: "closed", reason: "stopped" });
|
|
14
|
+
|
|
15
|
+
assert.deepStrictEqual(heard, ["ready", "second:ready", "second:closed"]);
|
|
16
|
+
assert.deepStrictEqual(machine.state(), { kind: "closed", reason: "stopped" });
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it("a fresh machine is opening and a listener never sees a state from before it attached", () => {
|
|
20
|
+
const machine = makeRuntimeState();
|
|
21
|
+
machine.setState({ kind: "ready" });
|
|
22
|
+
const heard: string[] = [];
|
|
23
|
+
machine.onState((state) => heard.push(state.kind));
|
|
24
|
+
assert.deepStrictEqual(heard, []);
|
|
25
|
+
});
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** Where one session stands: the harness reports into it, and the surfaces read it. */
|
|
2
|
+
export type RuntimeState =
|
|
3
|
+
| { readonly kind: "opening" }
|
|
4
|
+
| { readonly kind: "ready" }
|
|
5
|
+
| { readonly kind: "failing"; readonly reason: string }
|
|
6
|
+
| { readonly kind: "closed"; readonly reason?: string };
|
|
7
|
+
|
|
8
|
+
/** The one mutable state and its listeners: the session's whole lifecycle surface. */
|
|
9
|
+
export interface RuntimeStateMachine {
|
|
10
|
+
readonly state: () => RuntimeState;
|
|
11
|
+
readonly setState: (state: RuntimeState) => void;
|
|
12
|
+
/** Registers a listener; the returned function detaches it. */
|
|
13
|
+
readonly onState: (listener: (state: RuntimeState) => void) => () => void;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* A state value and its listener set, with no harness and no layer: a session
|
|
18
|
+
* starts `opening`, the harness moves it, and presentation subscribes.
|
|
19
|
+
*/
|
|
20
|
+
export const makeRuntimeState = (): RuntimeStateMachine => {
|
|
21
|
+
let state: RuntimeState = { kind: "opening" };
|
|
22
|
+
const listeners = new Set<(state: RuntimeState) => void>();
|
|
23
|
+
return {
|
|
24
|
+
state: () => state,
|
|
25
|
+
setState: (next) => {
|
|
26
|
+
state = next;
|
|
27
|
+
for (const listener of listeners) listener(next);
|
|
28
|
+
},
|
|
29
|
+
onState: (listener) => {
|
|
30
|
+
listeners.add(listener);
|
|
31
|
+
return () => {
|
|
32
|
+
listeners.delete(listener);
|
|
33
|
+
};
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Context as EffectContext } from "effect";
|
|
2
|
+
import type { SessionRuntime } from "./session.ts";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The session's resolved runtime, as the graph provides it. A leaf module so
|
|
6
|
+
* `workflow.ts` can require it without loading `session.ts`, which reaches back
|
|
7
|
+
* to `workflow.ts` through `extensions.ts`.
|
|
8
|
+
*/
|
|
9
|
+
export class SessionRuntimeTag extends EffectContext.Service<SessionRuntimeTag, SessionRuntime>()(
|
|
10
|
+
"@ftrdotdev/pi-delegates/runtime/session-tag/SessionRuntimeTag",
|
|
11
|
+
) {}
|