@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,352 @@
1
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
+ import { MemoryStorage, type Harness, type Storage } from "@earendil-works/pi-durable";
3
+ import { Effect } from "effect";
4
+ import type { CodemodeSandboxBase } from "@earendil-works/pi-codemode/portable";
5
+ import { assert, it } from "@effect/vitest";
6
+ import { rejects } from "../../test-support/assertions.ts";
7
+ import { failingStorage } from "../../test-support/failing-storage.ts";
8
+ import { ProbeDoc } from "../../test-support/probe-doc.ts";
9
+ import { stubHostSource } from "../../test-support/stub-model-source.ts";
10
+ import { RunDoc } from "../domain/run-records.ts";
11
+ import { viewSession } from "../domain/view.ts";
12
+ import { createCatalogue } from "../domain/definitions.ts";
13
+ import { launch } from "../domain/orchestration/launch.ts";
14
+ import { HarnessClosed } from "./bridge.ts";
15
+ import { HostModelAdapter } from "./models.ts";
16
+ import type { LogFields, LogLevel, LogSink } from "./log.ts";
17
+ import { openReadOnlyRuntime, storePathFor, type SessionIdentity } from "./session.ts";
18
+ import { openTestSession } from "../../test-support/seams.ts";
19
+ import { existsPath, join, makeTempDir, readDir, writeText } from "../../test-support/platform.ts";
20
+
21
+ const identityFor = async (sessionId: string): Promise<SessionIdentity> => {
22
+ const sessionDir = await makeTempDir("delegates-session-");
23
+ return {
24
+ sessionId,
25
+ sessionDir,
26
+ cwd: sessionDir,
27
+ agentDir: sessionDir,
28
+ };
29
+ };
30
+
31
+ const models = () => new HostModelAdapter(stubHostSource());
32
+
33
+ const commitProbe = async (harness: Harness, counter: number): Promise<void> => {
34
+ await harness.commit(async (tx) => {
35
+ const doc = await tx.doc(ProbeDoc);
36
+ doc.counter = counter;
37
+ }, BACKGROUND_CONTEXT);
38
+ };
39
+
40
+ /** A sandbox double that records a real `start()` or `close()`; a start is a bug in this test. */
41
+ const countingSandbox = (): {
42
+ readonly sandbox: CodemodeSandboxBase;
43
+ readonly events: string[];
44
+ } => {
45
+ const events: string[] = [];
46
+ const sandbox = {
47
+ start: async () => {
48
+ events.push("start");
49
+ throw new Error("this test runs no script");
50
+ },
51
+ execute: async () => ({
52
+ ok: false as const,
53
+ error: { kind: "sandbox" as const, message: "this test runs no script" },
54
+ }),
55
+ close: async () => {
56
+ events.push("close");
57
+ },
58
+ } as unknown as CodemodeSandboxBase;
59
+ return { sandbox, events };
60
+ };
61
+
62
+ const recordingSink = () => {
63
+ const entries: { level: LogLevel; code: string; fields: LogFields }[] = [];
64
+ const sink: LogSink = {
65
+ write: (level, code, fields = {}) => {
66
+ entries.push({ level, code, fields });
67
+ },
68
+ };
69
+ return { sink, entries };
70
+ };
71
+
72
+ it("opening a session creates one store under the session directory", async () => {
73
+ const identity = await identityFor("s-1");
74
+ const runtime = await openTestSession({ identity, models: models() });
75
+ try {
76
+ assert.strictEqual(runtime.storePath, join(identity.sessionDir, "delegates-s-1.sqlite"));
77
+ assert.strictEqual(runtime.storePath, storePathFor(identity));
78
+ assert.ok(await existsPath(runtime.storePath));
79
+ assert.strictEqual(runtime.state.kind, "ready");
80
+ const stores = (await readDir(identity.sessionDir)).filter((name) => name.endsWith(".sqlite"));
81
+ assert.deepStrictEqual(stores, ["delegates-s-1.sqlite"]);
82
+ } finally {
83
+ await runtime.close();
84
+ }
85
+ });
86
+
87
+ it("reopening the same identity resumes committed state", async () => {
88
+ const identity = await identityFor("s-1");
89
+ const first = await openTestSession({ identity, models: models() });
90
+ await commitProbe(first.harness, 1);
91
+ await first.close();
92
+
93
+ const second = await openTestSession({ identity, models: models() });
94
+ try {
95
+ assert.deepStrictEqual(await second.snapshot(ProbeDoc), { counter: 1 });
96
+ assert.strictEqual(second.state.kind, "ready");
97
+ } finally {
98
+ await second.close();
99
+ }
100
+ });
101
+
102
+ it("a forked session gets a fresh store", async () => {
103
+ const identity = await identityFor("s-1");
104
+ const first = await openTestSession({ identity, models: models() });
105
+ await commitProbe(first.harness, 1);
106
+ await first.close();
107
+
108
+ const forkedIdentity = { ...identity, sessionId: "s-2" };
109
+ const forked = await openTestSession({ identity: forkedIdentity, models: models() });
110
+ try {
111
+ assert.notStrictEqual(forked.storePath, storePathFor(identity));
112
+ assert.strictEqual(await forked.snapshot(ProbeDoc), undefined);
113
+ } finally {
114
+ await forked.close();
115
+ }
116
+ });
117
+
118
+ it("a read-only open refuses writes but reads", async () => {
119
+ const identity = await identityFor("s-1");
120
+ const writer = await openTestSession({ identity, models: models() });
121
+ await commitProbe(writer.harness, 5);
122
+ await writer.close();
123
+
124
+ const viewer = await openReadOnlyRuntime({ storePath: storePathFor(identity), models: models() });
125
+ try {
126
+ await rejects(
127
+ viewer.harness.commit(async (tx) => {
128
+ const doc = await tx.doc(ProbeDoc);
129
+ doc.counter = 6;
130
+ }, BACKGROUND_CONTEXT),
131
+ (error: unknown) => error instanceof Error && error.name === "ReadOnlySession",
132
+ );
133
+ assert.deepStrictEqual(await viewer.snapshot(ProbeDoc), { counter: 5 });
134
+ } finally {
135
+ await viewer.close();
136
+ }
137
+ });
138
+
139
+ it("a failing storage ends the runtime with its reason", async () => {
140
+ const identity = await identityFor("s-1");
141
+ const { storage, failNext } = failingStorage(new MemoryStorage());
142
+ const states: string[] = [];
143
+ const runtime = await openTestSession({ identity, models: models(), storage });
144
+ const unsubscribe = runtime.onState((state) => states.push(state.kind));
145
+
146
+ failNext();
147
+ await rejects(commitProbe(runtime.harness, 1));
148
+ await runtime.harness.closed;
149
+
150
+ assert.deepStrictEqual(states, ["failing", "closed"]);
151
+ assert.strictEqual(runtime.state.kind, "closed");
152
+ assert.ok(runtime.state.kind === "closed" && runtime.state.reason?.includes("storage failed"));
153
+
154
+ const failure = await runtime.bridge.call(async () => 1).pipe(Effect.flip, Effect.runPromise);
155
+ assert.ok(failure instanceof HarnessClosed);
156
+ assert.ok(failure.reason.includes("storage failed"));
157
+ unsubscribe();
158
+ await runtime.close();
159
+ });
160
+
161
+ it("a failed open closes the sandbox", async () => {
162
+ const identity = await identityFor("s-1");
163
+ const events = countingSandbox();
164
+ const { storage, failAnyNext } = failingStorage(new MemoryStorage());
165
+ failAnyNext();
166
+ await rejects(
167
+ openTestSession({ identity, models: models(), storage, sandbox: events.sandbox }),
168
+ /storage failed/,
169
+ );
170
+ assert.deepStrictEqual(events.events, ["close"]);
171
+ });
172
+
173
+ it("a storage failure logs one entry and closes the runtime", async () => {
174
+ const identity = await identityFor("s-1");
175
+ const { storage, failNext } = failingStorage(new MemoryStorage());
176
+ const { sink, entries } = recordingSink();
177
+ const runtime = await openTestSession({ identity, models: models(), storage, log: sink });
178
+ try {
179
+ failNext();
180
+ await rejects(commitProbe(runtime.harness, 1));
181
+ await runtime.harness.closed;
182
+
183
+ assert.deepStrictEqual(
184
+ entries.map((entry) => entry.code),
185
+ ["report.storage_failed"],
186
+ );
187
+ assert.strictEqual(entries[0]?.level, "error");
188
+ assert.strictEqual(runtime.state.kind, "closed");
189
+ } finally {
190
+ await runtime.close();
191
+ }
192
+ });
193
+
194
+ it("config diagnostics are logged when delegates.json is invalid", async () => {
195
+ const identity = await identityFor("s-1");
196
+ const path = join(identity.agentDir, "delegates.json");
197
+ await writeText(path, "{\n");
198
+ const { sink, entries } = recordingSink();
199
+ const runtime = await openTestSession({ identity, models: models(), log: sink });
200
+ try {
201
+ assert.strictEqual(entries.length, 1);
202
+ assert.strictEqual(entries[0]?.level, "warn");
203
+ assert.strictEqual(entries[0]?.code, "config.invalid_json");
204
+ assert.ok(String(entries[0]?.fields.detail).includes(path), String(entries[0]?.fields.detail));
205
+ } finally {
206
+ await runtime.close();
207
+ }
208
+ });
209
+
210
+ it("a failed open closes the storage", async () => {
211
+ const identity = await identityFor("s-1");
212
+ let closed = false;
213
+ const base = new MemoryStorage();
214
+ const storage = new Proxy(base, {
215
+ get(target, property, receiver) {
216
+ if (property === "mintId") return () => Promise.reject(new Error("no id"));
217
+ if (property === "close") {
218
+ return () => {
219
+ closed = true;
220
+ return Promise.resolve();
221
+ };
222
+ }
223
+ const value = Reflect.get(target, property, receiver) as unknown;
224
+ return typeof value === "function" ? value.bind(target) : value;
225
+ },
226
+ }) as unknown as Storage;
227
+ await rejects(openTestSession({ identity, models: models(), storage }));
228
+ assert.strictEqual(closed, true);
229
+ });
230
+
231
+ it("the injected clock is the runtime clock", async () => {
232
+ const identity = await identityFor("s-1");
233
+ let now = 1_000;
234
+ const runtime = await openTestSession({ identity, models: models(), now: () => now });
235
+ try {
236
+ assert.strictEqual(runtime.now(), 1_000);
237
+ now = 2_000;
238
+ assert.strictEqual(runtime.now(), 2_000);
239
+ } finally {
240
+ await runtime.close();
241
+ }
242
+ });
243
+
244
+ it("the root conversation carries no tools and no extensions", async () => {
245
+ const identity = await identityFor("s-1");
246
+ const runtime = await openTestSession({ identity, models: models() });
247
+ try {
248
+ const agent = await runtime.root.agent(BACKGROUND_CONTEXT);
249
+ assert.deepStrictEqual(agent.tools, []);
250
+ assert.deepStrictEqual(agent.extensions, []);
251
+ } finally {
252
+ await runtime.close();
253
+ }
254
+ });
255
+
256
+ it("the caller signal reaches the harness call", async () => {
257
+ const identity = await identityFor("s-1");
258
+ const runtime = await openTestSession({ identity, models: models() });
259
+ try {
260
+ const controller = new AbortController();
261
+ let abortedDuring: boolean | undefined;
262
+ let entered: () => void = () => {};
263
+ const started = new Promise<void>((resolve) => {
264
+ entered = resolve;
265
+ });
266
+ const pending = runtime.run(async (context) => {
267
+ entered();
268
+ await new Promise<void>((resolve) => {
269
+ if (context.abortSignal?.aborted ?? false) resolve();
270
+ else context.abortSignal?.addEventListener("abort", () => resolve(), { once: true });
271
+ });
272
+ abortedDuring = context.abortSignal?.aborted ?? false;
273
+ return abortedDuring;
274
+ }, controller.signal);
275
+ await started;
276
+ controller.abort();
277
+ await rejects(pending);
278
+ await new Promise((resolve) => setTimeout(resolve, 10));
279
+ assert.strictEqual(abortedDuring, true);
280
+ } finally {
281
+ await runtime.close();
282
+ }
283
+ });
284
+
285
+ it("a skill scan problem reaches the log at open", async () => {
286
+ const identity = await identityFor("s-1");
287
+ const { sink, entries } = recordingSink();
288
+ const runtime = await openTestSession({
289
+ identity,
290
+ models: models(),
291
+ log: sink,
292
+ skills: {
293
+ cwd: identity.cwd,
294
+ agentDir: identity.agentDir,
295
+ skillPaths: [join(identity.sessionDir, "absent-skills")],
296
+ },
297
+ });
298
+ try {
299
+ assert.ok(
300
+ entries.some(
301
+ (entry) =>
302
+ entry.code === "skill.warning" && JSON.stringify(entry.fields).includes("absent-skills"),
303
+ ),
304
+ JSON.stringify(entries),
305
+ );
306
+ } finally {
307
+ await runtime.close();
308
+ }
309
+ });
310
+
311
+ it("a viewer reads a store written by a runtime", async () => {
312
+ const identity = await identityFor("s-1");
313
+ const writer = await openTestSession({ identity, models: models() });
314
+ await commitProbe(writer.harness, 1);
315
+ await writer.close();
316
+
317
+ const viewer = await openReadOnlyRuntime({ storePath: storePathFor(identity), models: models() });
318
+ try {
319
+ assert.deepStrictEqual(await viewer.snapshot(ProbeDoc), { counter: 1 });
320
+ } finally {
321
+ await viewer.close();
322
+ }
323
+ });
324
+
325
+ it("the read-only viewer satisfies the view port", async () => {
326
+ const identity = await identityFor("s-1");
327
+ const writer = await openTestSession({ identity, models: models() });
328
+ const launched = await launch(
329
+ { kind: "single", agent: "scout", task: "look" },
330
+ {
331
+ runtime: writer,
332
+ catalogue: createCatalogue(),
333
+ host: { model: { provider: "stub", modelId: "stub-1" }, thinkingLevel: "low" },
334
+ waitMs: 10_000,
335
+ },
336
+ );
337
+ const runId = launched.view.runId;
338
+ await writer.close();
339
+
340
+ const viewer = await openReadOnlyRuntime({ storePath: storePathFor(identity), models: models() });
341
+ try {
342
+ const session = await viewSession(viewer);
343
+ assert.deepStrictEqual(
344
+ session.runs.map((run) => run.runId),
345
+ [runId],
346
+ );
347
+ const doc = await viewer.snapshot(RunDoc, runId);
348
+ assert.strictEqual(doc?.definition, "scout");
349
+ } finally {
350
+ await viewer.close();
351
+ }
352
+ });
@@ -0,0 +1,263 @@
1
+ import { BACKGROUND_CONTEXT, type Context } from "@earendil-works/chord/context";
2
+ import type { Models } from "@earendil-works/pi-ai/models";
3
+ import type { JsonValue } from "@earendil-works/chord/json";
4
+ import {
5
+ Harness,
6
+ type Conversation,
7
+ type ConversationId,
8
+ type JsonObject,
9
+ type Registry,
10
+ type SessionDocFamilyToken,
11
+ type SessionDocToken,
12
+ type SetTimer,
13
+ } from "@earendil-works/pi-durable";
14
+ import { openNodeSqliteStorage } from "@earendil-works/pi-durable/storage/sqlite/node";
15
+ import { Effect } from "effect";
16
+ import { join } from "node:path";
17
+ import { DurableBridge, type HarnessCalls } from "./bridge.ts";
18
+ import { type DelegatesConfig } from "./config.ts";
19
+ import { createDelegatesRegistry, type DelegatesTasks } from "./extensions.ts";
20
+ import type { DefinitionCatalogue } from "../domain/definitions.ts";
21
+ import { sweepRequests } from "../domain/orchestration/requests.ts";
22
+ import type { RuntimeState, RuntimeStateMachine } from "./runtime-state.ts";
23
+ import type { HostDefaults } from "../domain/orchestration/launch.ts";
24
+ import { refusingSandbox } from "../domain/orchestration/workflow-section.ts";
25
+ import type { ViewPort } from "../domain/view.ts";
26
+ import type { CodemodeSandboxBase } from "@earendil-works/pi-codemode/portable";
27
+ import { reasonOf, type LogSink } from "./log.ts";
28
+ import type { McpHost, McpPresence } from "./mcp.ts";
29
+ import { SkillsCatalogue } from "../domain/skills.ts";
30
+ import type { Timers } from "./clock.ts";
31
+ import type { SettleSignal } from "../domain/settlement.ts";
32
+
33
+ export interface SessionIdentity {
34
+ readonly sessionId: string;
35
+ readonly sessionDir: string;
36
+ readonly cwd: string;
37
+ readonly agentDir: string;
38
+ }
39
+
40
+ export type { RuntimeState } from "./runtime-state.ts";
41
+
42
+ export interface SessionRuntime {
43
+ readonly storePath: string;
44
+ readonly sessionId: string;
45
+ readonly harness: Harness;
46
+ readonly root: Conversation;
47
+ readonly bridge: DurableBridge["Service"];
48
+ /** Every harness call crosses the bridge; domain errors stay outside it. */
49
+ readonly run: <A>(
50
+ operation: (context: Context) => Promise<A>,
51
+ signal?: AbortSignal,
52
+ ) => Promise<A>;
53
+ readonly config: DelegatesConfig;
54
+ /** The one log sink a surface writes diagnostics and failures to. */
55
+ readonly log: LogSink;
56
+ readonly registry: Registry;
57
+ readonly tasks: DelegatesTasks;
58
+ /** The registered definitions a workflow resolves at launch. */
59
+ readonly catalogue: DefinitionCatalogue;
60
+ /** The host model a scripted child fills in, read at each launch. */
61
+ readonly host: () => HostDefaults;
62
+ /** The one code mode sandbox; it closes after the harness. */
63
+ readonly sandbox: CodemodeSandboxBase;
64
+ /** The session's skill catalogue; one scan when the runtime opens. */
65
+ readonly skills: SkillsCatalogue["Service"];
66
+ /** The MCP servers this session connects to; none in a read-only runtime. */
67
+ readonly mcp: McpHost;
68
+ /** Configured servers with no live connection. */
69
+ readonly mcpPresence: McpPresence;
70
+ /** The clock the domain reads, shared with the harness. */
71
+ readonly now: () => number;
72
+ /** The timer source the domain reads, shared with the harness. */
73
+ readonly timers: Timers;
74
+ /** The one in-process settle signal: the recorder emits, the batcher listens. */
75
+ readonly settle: SettleSignal;
76
+ readonly state: RuntimeState;
77
+ readonly onState: (listener: (state: RuntimeState) => void) => () => void;
78
+ snapshot<T extends JsonObject>(token: SessionDocToken<T>): Promise<Readonly<T> | undefined>;
79
+ snapshot<T extends JsonObject, I extends JsonValue>(
80
+ token: SessionDocFamilyToken<T, I>,
81
+ key: string,
82
+ ): Promise<Readonly<T> | undefined>;
83
+ }
84
+
85
+ export type ReadOnlyRuntime = ViewPort & { readonly close: () => Promise<void> };
86
+
87
+ /** A family token's definition carries `family: true`; a singleton token's does not. */
88
+ export const isFamilyToken = <T extends JsonObject, I extends JsonValue>(
89
+ token: SessionDocToken<T> | SessionDocFamilyToken<T, I>,
90
+ ): token is SessionDocFamilyToken<T, I> => "family" in token.definition;
91
+
92
+ export const storePathFor = (identity: SessionIdentity): string =>
93
+ join(identity.sessionDir, `delegates-${identity.sessionId}.sqlite`);
94
+
95
+ /** The harness's timer seam, armed by the runtime's one timer source. */
96
+ export const setTimerFrom =
97
+ (timers: Timers): SetTimer =>
98
+ (callback, delayMs) => {
99
+ const handle = timers.setTimeout(callback, delayMs);
100
+ return () => timers.clearTimeout(handle);
101
+ };
102
+
103
+ // Re-exported from a leaf module: `workflow.ts` requires the tag, and this file
104
+ // reaches `workflow.ts` through `extensions.ts`.
105
+ export { SessionRuntimeTag } from "./session-tag.ts";
106
+
107
+ /**
108
+ * Filled once, after the runtime object exists, for getters created before it.
109
+ *
110
+ * Two registries reach the same runtime on purpose. This one is filled inside
111
+ * `buildSessionRuntime`, before the handle exists, because `harness.resume()`
112
+ * runs in the same turn and the registry's thunks (`admission.inspect`,
113
+ * `mcpPresence`) read it. The handle's `Ref` is written only once the handle is
114
+ * built, so it cannot serve that window.
115
+ */
116
+ export interface RuntimeHolder {
117
+ runtime?: SessionRuntime;
118
+ }
119
+
120
+ export interface SessionSnapshot {
121
+ <T extends JsonObject>(token: SessionDocToken<T>): Promise<Readonly<T> | undefined>;
122
+ <T extends JsonObject, I extends JsonValue>(
123
+ token: SessionDocFamilyToken<T, I>,
124
+ key: string,
125
+ ): Promise<Readonly<T> | undefined>;
126
+ }
127
+
128
+ /**
129
+ * Everything the opened harness owns, before the bridge exists. The graph
130
+ * builds it once and hands it to `buildSessionRuntime`; `close` runs the three
131
+ * closes once and is shared with the scope's finalizer.
132
+ */
133
+ export interface HarnessParts extends RuntimeStateMachine {
134
+ readonly storePath: string;
135
+ readonly sessionId: string;
136
+ readonly harness: Harness;
137
+ readonly root: Conversation;
138
+ readonly calls: HarnessCalls;
139
+ readonly config: DelegatesConfig;
140
+ readonly log: LogSink;
141
+ readonly registry: Registry;
142
+ readonly tasks: DelegatesTasks;
143
+ readonly catalogue: DefinitionCatalogue;
144
+ readonly host: () => HostDefaults;
145
+ readonly sandbox: CodemodeSandboxBase;
146
+ readonly skills: SkillsCatalogue["Service"];
147
+ readonly mcp: McpHost;
148
+ readonly mcpPresence: McpPresence;
149
+ readonly now: () => number;
150
+ readonly timers: Timers;
151
+ readonly settle: SettleSignal;
152
+ readonly snapshot: SessionSnapshot;
153
+ readonly close: () => Promise<void>;
154
+ readonly holder: RuntimeHolder;
155
+ }
156
+
157
+ /**
158
+ * Assembles the public runtime from the opened session and the bridge. It
159
+ * receives both, so it cannot create a scope and owns no close of its own:
160
+ * `close` arrives from the graph's finalizer.
161
+ */
162
+ export const buildSessionRuntime = async (
163
+ core: HarnessParts,
164
+ bridge: DurableBridge["Service"],
165
+ ): Promise<SessionRuntime> => {
166
+ const run = <A>(operation: (context: Context) => Promise<A>, signal?: AbortSignal): Promise<A> =>
167
+ Effect.runPromise(bridge.call(operation), signal === undefined ? undefined : { signal });
168
+
169
+ core.setState({ kind: "ready" });
170
+ core.harness.resume();
171
+
172
+ void core.harness.closed.then((end) => {
173
+ const reason = end.kind === "failed" ? reasonOf(end.error) : undefined;
174
+ const failing = core.state();
175
+ if (failing.kind !== "failing")
176
+ core.setState({ kind: "closed", ...(reason === undefined ? {} : { reason }) });
177
+ else core.setState({ kind: "closed", reason: failing.reason });
178
+ });
179
+
180
+ // The runtime is the core minus its owner-only members, plus the bridge and the
181
+ // getter. The spread keeps the two shapes in step; a field added to the core that the
182
+ // runtime exposes needs no second line here.
183
+ const {
184
+ calls: _calls,
185
+ setState: _setState,
186
+ close: _close,
187
+ holder: _holder,
188
+ state,
189
+ ...shared
190
+ } = core;
191
+ const runtime: SessionRuntime = {
192
+ ...shared,
193
+ bridge,
194
+ run,
195
+ get state() {
196
+ return state();
197
+ },
198
+ };
199
+ core.holder.runtime = runtime;
200
+ // The start-up sweep never fails the session; see `sweepRequests`.
201
+ await sweepRequests(runtime);
202
+ return runtime;
203
+ };
204
+ /**
205
+ * The read-only viewer path: it opens an existing store, exposes only reads and
206
+ * runs no task. The registry gets no session runtime, so it installs no run
207
+ * tools: a viewer can read runs and cannot start or control one. The refused
208
+ * `/delegates` reader opens it; `session.test.ts` proves reads succeed and
209
+ * writes are refused.
210
+ */
211
+ export async function openReadOnlyRuntime(options: {
212
+ readonly storePath: string;
213
+ readonly models: Models;
214
+ /** Overrides the refusing sandbox in tests. */
215
+ readonly sandbox?: CodemodeSandboxBase;
216
+ }): Promise<ReadOnlyRuntime> {
217
+ const storage = await openNodeSqliteStorage(options.storePath);
218
+ const skills = SkillsCatalogue.make();
219
+ const installed = createDelegatesRegistry({
220
+ admission: {
221
+ inspect: () => Promise.reject(new Error("a read-only viewer runs no task")),
222
+ caps: () => ({ laneCap: 0, sessionCeiling: 0 }),
223
+ pollMs: 1000,
224
+ },
225
+ skills,
226
+ sandbox: options.sandbox ?? refusingSandbox(),
227
+ });
228
+ const harness = await Harness.open(
229
+ storage,
230
+ {
231
+ models: options.models,
232
+ registry: installed.registry,
233
+ readOnly: true,
234
+ },
235
+ BACKGROUND_CONTEXT,
236
+ );
237
+ const snapshot = <T extends JsonObject, I extends JsonValue>(
238
+ token: SessionDocToken<T> | SessionDocFamilyToken<T, I>,
239
+ key?: string,
240
+ ): Promise<Readonly<T> | undefined> => {
241
+ if (isFamilyToken(token)) {
242
+ if (key === undefined) {
243
+ return Promise.reject(new Error("A family document token needs a key."));
244
+ }
245
+ return harness.snapshot(token, key, BACKGROUND_CONTEXT);
246
+ }
247
+ return harness.snapshot(token, BACKGROUND_CONTEXT);
248
+ };
249
+ return {
250
+ harness,
251
+ registry: installed.registry,
252
+ skills,
253
+ snapshot,
254
+ run: (operation) => operation(BACKGROUND_CONTEXT),
255
+ close: async () => {
256
+ await harness.close(BACKGROUND_CONTEXT);
257
+ await installed.sandbox.close();
258
+ },
259
+ };
260
+ }
261
+
262
+ /** A conversation id as the harness records it. */
263
+ export type { ConversationId };
@@ -0,0 +1,29 @@
1
+ import type { Storage } from "@earendil-works/pi-durable";
2
+ import { Context, Effect, Layer, Schema } from "effect";
3
+
4
+ /** The session's durable store: one per session, opened and closed by the seam layer. */
5
+ export class StorageService extends Context.Service<StorageService, Storage>()(
6
+ "@ftrdotdev/pi-delegates/runtime/storage/StorageService",
7
+ ) {
8
+ /**
9
+ * The store, opened once per build; a failed open fails the build here.
10
+ * `Harness.close` owns the backend once the harness holds it, so this layer
11
+ * adds no finalizer: the only other close is the graph's own failure path,
12
+ * which releases a store the harness never received.
13
+ */
14
+ static layer(open: () => Promise<Storage>): Layer.Layer<StorageService, StorageError> {
15
+ return Layer.effect(
16
+ StorageService,
17
+ Effect.tryPromise({
18
+ try: open,
19
+ catch: (cause) => StorageError.make({ cause }),
20
+ }),
21
+ );
22
+ }
23
+ }
24
+
25
+ /** The store could not be opened; the layer refuses the build rather than expose no store. */
26
+ export class StorageError extends Schema.TaggedError<
27
+ StorageError,
28
+ { readonly brand: unique symbol }
29
+ >()("StorageError", { cause: Schema.Defect() }) {}