@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,152 @@
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 type { SkillsCatalogue } from "../domain/skills.ts";
24
+ import { ToolkitDoc } from "../domain/toolkit.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 { Ref } from "effect";
39
+ import type { SessionHandle } from "../runtime/handle.ts";
40
+ import { nullLogSink, type LogSink } from "./log.ts";
41
+ import type { SettleSignal } from "../domain/settlement.ts";
42
+ import { systemTimers, type Timers } from "./clock.ts";
43
+ import { mcpTool, type McpHost, type McpPresence } from "./mcp.ts";
44
+
45
+ export interface RegistryDeps {
46
+ readonly admission: AdmissionHost;
47
+ /** Slice 10 adds the gate rules. */
48
+ readonly gates?: readonly unknown[];
49
+ /** The one catalogue the run task binds skill names against. */
50
+ readonly skills: SkillsCatalogue["Service"];
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.
55
+ */
56
+ readonly session?: Ref.Ref<SessionHandle | undefined>;
57
+ /** Overrides the sandbox in tests; default one worker sandbox per runtime. */
58
+ readonly sandbox?: CodemodeSandboxBase;
59
+ /** The connected MCP servers; absent when the runtime opens none. */
60
+ readonly mcp?: McpHost;
61
+ /** Lazy MCP presence for the run task's binder; absent in the viewer. */
62
+ readonly mcpPresence?: () => McpPresence | undefined;
63
+ /** The sink an MCP call writes a timeout to; default none. */
64
+ readonly log?: LogSink;
65
+ /** The timer source an MCP call bounds itself with; default `systemTimers`. */
66
+ readonly timers?: Timers;
67
+ /** The session's settle signal, emitted by every terminal run commit. */
68
+ readonly settle?: SettleSignal;
69
+ }
70
+
71
+ export interface DelegatesTasks {
72
+ readonly run: Task<RunInput, RunState, RunResult, Record<never, never>>;
73
+ readonly fanout: Task<FanoutInput, FanoutState, RunResult, FanoutHooks>;
74
+ }
75
+
76
+ export interface DelegatesInstallation {
77
+ readonly registry: Registry;
78
+ readonly tasks: DelegatesTasks;
79
+ readonly sandbox: CodemodeSandboxBase;
80
+ }
81
+
82
+ /** The one skills renderer: it reads the committed document, never a live copy. */
83
+ const skillsSection = (skills: SkillsCatalogue["Service"]) =>
84
+ section("skills", async (input, context) => {
85
+ const doc = await input.read.snapshot(ToolkitDoc, input.conversationId, context);
86
+ const names = doc?.skills ?? [];
87
+ if (names.length === 0) return undefined;
88
+ const found = skills.resolve(names);
89
+ if (found.length === 0) return undefined;
90
+ const text = skills.render(found);
91
+ return text === "" ? undefined : text;
92
+ });
93
+
94
+ /** The durable extension set: `coding`, `skills`, the gate guard, code mode, the
95
+ * run tools and the run tasks. Install order is a contract: code mode comes
96
+ * before the run tools, which it exposes to scripts.
97
+ */
98
+ export const createDelegatesRegistry = (deps: RegistryDeps): DelegatesInstallation => {
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);
108
+ const sandbox = diagnosticSandbox(deps.sandbox ?? new CodemodeSandbox());
109
+ const registry = createRegistry();
110
+ registry.install(CodingTools);
111
+ registry.install(
112
+ defineExtension({ name: SKILLS_EXTENSION, sections: [skillsSection(deps.skills)] }),
113
+ );
114
+ for (const connection of deps.mcp?.connections ?? []) {
115
+ registry.install(
116
+ defineExtension({
117
+ name: connection.extension,
118
+ namespace: {
119
+ name: connection.namespace,
120
+ description: `MCP server ${connection.server}`,
121
+ },
122
+ tools: connection.tools.map((tool) =>
123
+ mcpTool(connection, tool, {
124
+ log: deps.log ?? nullLogSink,
125
+ timers: deps.timers ?? systemTimers,
126
+ timeout: connection.timeout,
127
+ }),
128
+ ),
129
+ }),
130
+ );
131
+ }
132
+ // Installed always, so a child that selects it finds it; the binder adds it for a deferred tool.
133
+ registry.install(createToolSearchExtension());
134
+ registry.install(
135
+ defineExtension({
136
+ name: GATE_GUARD_EXTENSION,
137
+ tools: (CodingTools.tools ?? []).map((tool) => gatedTool(tool)),
138
+ }),
139
+ );
140
+ registry.install(
141
+ defineExtension({
142
+ ...createCodemodeExtension({ sandbox, models: false }),
143
+ name: CODEMODE_EXTENSION,
144
+ }),
145
+ );
146
+ registry.install(createRunsExtension(deps.session));
147
+ registry.install(defineExtension({ name: RUN_TASK_EXTENSION, tasks: [run, fanout] }));
148
+ registry.install(
149
+ defineExtension({ name: QUESTIONS_EXTENSION, tools: [askTool(deps.log ?? nullLogSink)] }),
150
+ );
151
+ return { registry, tasks: { run, fanout }, sandbox };
152
+ };
@@ -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
+ }
@@ -0,0 +1,140 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { join, makeTempDir, readText, writeText } from "../../test-support/platform.ts";
3
+ import type { Report } from "@earendil-works/pi-durable";
4
+ import {
5
+ errorFields,
6
+ failureDetailText,
7
+ fileLogSink,
8
+ logReport,
9
+ reasonOf,
10
+ truncate,
11
+ type LogFields,
12
+ type LogLevel,
13
+ type LogSink,
14
+ } from "./log.ts";
15
+
16
+ const scratch = () => makeTempDir("delegates-log-");
17
+
18
+ it("the file sink appends one JSON object per line", async () => {
19
+ const path = join(await scratch(), "delegates.log");
20
+ const sink = fileLogSink(path);
21
+ sink.write("info", "a.one", { taskId: 7 });
22
+ sink.write("warn", "b.two");
23
+
24
+ const lines = (await readText(path)).trim().split("\n");
25
+ assert.strictEqual(lines.length, 2);
26
+ const first = JSON.parse(lines[0] ?? "") as Record<string, unknown>;
27
+ assert.strictEqual(first.level, "info");
28
+ assert.strictEqual(first.code, "a.one");
29
+ assert.strictEqual(first.taskId, 7);
30
+ assert.strictEqual(typeof first.ts, "number");
31
+ assert.strictEqual((JSON.parse(lines[1] ?? "") as Record<string, unknown>).code, "b.two");
32
+ });
33
+
34
+ it("the file sink never throws when its path cannot be written", async () => {
35
+ const blocker = join(await scratch(), "blocker");
36
+ await writeText(blocker, "not a directory");
37
+ const sink = fileLogSink(join(blocker, "delegates.log"));
38
+ assert.doesNotThrow(() => sink.write("error", "broken.write"));
39
+ });
40
+
41
+ it("truncate keeps at most its maximum and reasonOf reads a message", () => {
42
+ assert.strictEqual(truncate("x".repeat(5000), 200).length, 200);
43
+ assert.strictEqual(truncate("short", 200), "short");
44
+ assert.strictEqual(reasonOf(new Error("boom")), "boom");
45
+ assert.strictEqual(reasonOf("text"), "text");
46
+ });
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
+
61
+ const reportTask = { id: 7 as never, kind: "delegates.run", conversationId: 3 as never };
62
+ const reportError = new Error("boom");
63
+
64
+ const reportFixtures: ReadonlyArray<Report> = [
65
+ { kind: "storage_failed", error: reportError },
66
+ { kind: "task_faulted", task: reportTask, reason: "threw", error: reportError },
67
+ {
68
+ kind: "task_interrupted",
69
+ task: reportTask,
70
+ reason: "interrupted",
71
+ restarts: 2,
72
+ error: reportError,
73
+ },
74
+ { kind: "migration_failed", task: reportTask, error: reportError },
75
+ { kind: "task_outdated", task: reportTask, reason: "missing_task", error: reportError },
76
+ { kind: "task_error", task: reportTask, error: reportError },
77
+ { kind: "extension_error", task: reportTask, error: reportError },
78
+ { kind: "host_error", callback: "now", task: reportTask, error: reportError },
79
+ { kind: "listener_error", error: reportError },
80
+ ];
81
+
82
+ const tasksInReports = new Set([
83
+ "task_faulted",
84
+ "task_interrupted",
85
+ "migration_failed",
86
+ "task_outdated",
87
+ "task_error",
88
+ "extension_error",
89
+ "host_error",
90
+ ]);
91
+
92
+ const recordingSink = () => {
93
+ const entries: { level: LogLevel; code: string; fields: LogFields }[] = [];
94
+ const sink: LogSink = {
95
+ write: (level, code, fields = {}) => {
96
+ entries.push({ level, code, fields });
97
+ },
98
+ };
99
+ return { sink, entries };
100
+ };
101
+
102
+ it("the report mapper logs every kind without task content", () => {
103
+ const { sink, entries } = recordingSink();
104
+ for (const report of reportFixtures) logReport(sink, report);
105
+
106
+ assert.deepStrictEqual(
107
+ entries.map((entry) => entry.code),
108
+ reportFixtures.map((report) => `report.${report.kind}`),
109
+ );
110
+ for (const [index, entry] of entries.entries()) {
111
+ const kind = reportFixtures[index]!.kind;
112
+ assert.strictEqual(entry.level, errorLevels.has(kind) ? "error" : "warn");
113
+ assert.strictEqual(entry.fields.error, "Error");
114
+ assert.strictEqual(entry.fields.detail, "boom");
115
+ if (tasksInReports.has(kind)) assert.strictEqual(entry.fields.taskId, 7);
116
+ for (const forbidden of ["task", "answer", "prompt", "command"]) {
117
+ assert.ok(!(forbidden in entry.fields), `${kind} logged ${forbidden}`);
118
+ }
119
+ }
120
+ });
121
+
122
+ const errorLevels = new Set([
123
+ "storage_failed",
124
+ "task_faulted",
125
+ "task_interrupted",
126
+ "migration_failed",
127
+ "task_outdated",
128
+ "task_error",
129
+ ]);
130
+
131
+ it("an error message is truncated, not dropped", () => {
132
+ const { sink, entries } = recordingSink();
133
+ logReport(sink, { kind: "task_error", task: reportTask, error: new Error("x".repeat(5000)) });
134
+
135
+ const entry = entries[0];
136
+ assert.ok(entry !== undefined);
137
+ assert.strictEqual(typeof entry.fields.detail, "string");
138
+ assert.strictEqual((entry.fields.detail as string).length, 200);
139
+ assert.deepStrictEqual(Object.keys(entry.fields).sort(), ["detail", "error", "taskId"]);
140
+ });
@@ -0,0 +1,91 @@
1
+ import type { Report } from "@earendil-works/pi-durable";
2
+ import { Context, Layer } from "effect";
3
+ import { appendFileSync } from "node:fs";
4
+
5
+ export type LogLevel = "debug" | "info" | "warn" | "error";
6
+ export type LogFields = Record<string, string | number | boolean | null | undefined>;
7
+
8
+ export interface LogSink {
9
+ write(level: LogLevel, code: string, fields?: LogFields): void;
10
+ }
11
+
12
+ export const nullLogSink: LogSink = { write: () => {} };
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
+
24
+ /** `detail` is display-only: it is never parsed and never classifies state. */
25
+ export const DETAIL_LIMIT = 200;
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
+
39
+ export const truncate = (text: string, max: number): string =>
40
+ text.length <= max ? text : text.slice(0, max);
41
+
42
+ export const reasonOf = (error: unknown): string =>
43
+ error instanceof Error ? error.message : String(error);
44
+
45
+ export const errorName = (error: unknown): string =>
46
+ error instanceof Error ? error.name : typeof error;
47
+
48
+ /** The two fields every failure entry carries: the name and the truncated message. */
49
+ export const errorFields = (error: unknown): LogFields => ({
50
+ error: errorName(error),
51
+ detail: truncate(reasonOf(error), DETAIL_LIMIT),
52
+ });
53
+
54
+ const reportLevels: Readonly<Record<Report["kind"], LogLevel>> = {
55
+ storage_failed: "error",
56
+ task_faulted: "error",
57
+ task_interrupted: "error",
58
+ migration_failed: "error",
59
+ task_outdated: "error",
60
+ task_error: "error",
61
+ extension_error: "warn",
62
+ host_error: "warn",
63
+ listener_error: "warn",
64
+ };
65
+
66
+ /** One entry per harness report; the code names the kind, never the message. */
67
+ export const logReport = (sink: LogSink, report: Report): void => {
68
+ const fields: LogFields = { ...errorFields(report.error) };
69
+ if ("task" in report && report.task !== undefined) fields.taskId = report.task.id;
70
+ if ("extension" in report && report.extension !== undefined) {
71
+ fields.extension = report.extension;
72
+ }
73
+ if ("callback" in report) fields.callback = report.callback;
74
+ if ("reason" in report) fields.reason = report.reason;
75
+ if ("restarts" in report) fields.restarts = report.restarts;
76
+ sink.write(reportLevels[report.kind], `report.${report.kind}`, fields);
77
+ };
78
+
79
+ /**
80
+ * One JSON object per line under the session directory. No rotation: a session
81
+ * writes a few short lines. A failed write is dropped, never thrown.
82
+ */
83
+ export const fileLogSink = (path: string): LogSink => ({
84
+ write: (level, code, fields) => {
85
+ try {
86
+ appendFileSync(path, `${JSON.stringify({ ts: Date.now(), level, code, ...fields })}\n`);
87
+ } catch {
88
+ // A logger never throws: a dropped line is better than a failed call.
89
+ }
90
+ },
91
+ });