@ftrdotdev/pi-delegates 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/LICENSE +21 -0
  3. package/OPERATIONS.md +57 -0
  4. package/README.md +448 -2
  5. package/ROADMAP.md +158 -0
  6. package/TESTING.md +1061 -0
  7. package/agents.ts +8 -0
  8. package/examples/README.md +114 -0
  9. package/examples/gated.ts +28 -0
  10. package/index.ts +9 -0
  11. package/package.json +93 -4
  12. package/skills/pi-delegates/SKILL.md +147 -0
  13. package/skills/pi-delegates/references/control.md +159 -0
  14. package/skills/pi-delegates/references/definitions.md +163 -0
  15. package/skills/pi-delegates/references/gates.md +175 -0
  16. package/skills/pi-delegates/references/launch.md +156 -0
  17. package/src/domain/definitions.test.ts +41 -0
  18. package/src/domain/definitions.ts +161 -0
  19. package/src/domain/ids.ts +13 -0
  20. package/src/domain/names.ts +35 -0
  21. package/src/domain/orchestration/admission.ts +78 -0
  22. package/src/domain/orchestration/control.test.ts +1298 -0
  23. package/src/domain/orchestration/control.ts +436 -0
  24. package/src/domain/orchestration/fanout.test.ts +419 -0
  25. package/src/domain/orchestration/fanout.ts +334 -0
  26. package/src/domain/orchestration/gates.test.ts +686 -0
  27. package/src/domain/orchestration/gates.ts +360 -0
  28. package/src/domain/orchestration/launch.test.ts +173 -0
  29. package/src/domain/orchestration/launch.ts +581 -0
  30. package/src/domain/orchestration/requests.test.ts +700 -0
  31. package/src/domain/orchestration/requests.ts +769 -0
  32. package/src/domain/orchestration/review.test.ts +214 -0
  33. package/src/domain/orchestration/review.ts +168 -0
  34. package/src/domain/orchestration/run-wait.test.ts +262 -0
  35. package/src/domain/orchestration/run-wait.ts +256 -0
  36. package/src/domain/orchestration/workflow-section.test.ts +62 -0
  37. package/src/domain/orchestration/workflow-section.ts +99 -0
  38. package/src/domain/orchestration/workflow.test.ts +1425 -0
  39. package/src/domain/orchestration/workflow.ts +705 -0
  40. package/src/domain/run-records.test.ts +27 -0
  41. package/src/domain/run-records.ts +527 -0
  42. package/src/domain/shapes.test.ts +165 -0
  43. package/src/domain/skills.test.ts +466 -0
  44. package/src/domain/skills.ts +97 -0
  45. package/src/domain/tool-schema.test.ts +46 -0
  46. package/src/domain/tool-schema.ts +20 -0
  47. package/src/domain/toolkit.test.ts +201 -0
  48. package/src/domain/toolkit.ts +379 -0
  49. package/src/domain/view.test.ts +739 -0
  50. package/src/domain/view.ts +459 -0
  51. package/src/example.test.ts +15 -0
  52. package/src/extension/commands.test.ts +481 -0
  53. package/src/extension/commands.ts +227 -0
  54. package/src/extension/entry.test.ts +1118 -0
  55. package/src/extension/entry.ts +342 -0
  56. package/src/extension/gate-alerts.test.ts +235 -0
  57. package/src/extension/gate-alerts.ts +143 -0
  58. package/src/extension/guard.test.ts +48 -0
  59. package/src/extension/guard.ts +31 -0
  60. package/src/extension/host-signals.test.ts +20 -0
  61. package/src/extension/host-signals.ts +13 -0
  62. package/src/extension/inspector-command.test.ts +1191 -0
  63. package/src/extension/inspector-command.ts +638 -0
  64. package/src/extension/prompt.test.ts +110 -0
  65. package/src/extension/prompt.ts +50 -0
  66. package/src/extension/request-alerts.test.ts +183 -0
  67. package/src/extension/request-alerts.ts +181 -0
  68. package/src/extension/revocation.test.ts +81 -0
  69. package/src/extension/revocation.ts +84 -0
  70. package/src/extension/shortcut.test.ts +64 -0
  71. package/src/extension/shortcut.ts +105 -0
  72. package/src/extension/tools.test.ts +993 -0
  73. package/src/extension/tools.ts +505 -0
  74. package/src/extension/version.test.ts +123 -0
  75. package/src/extension/version.ts +97 -0
  76. package/src/harness-policy.test.ts +74 -0
  77. package/src/package-manifest.test.ts +157 -0
  78. package/src/presentation/actions.test.ts +221 -0
  79. package/src/presentation/actions.ts +85 -0
  80. package/src/presentation/activity.test.ts +387 -0
  81. package/src/presentation/activity.ts +66 -0
  82. package/src/presentation/close.test.ts +361 -0
  83. package/src/presentation/inspector.test.ts +679 -0
  84. package/src/presentation/inspector.ts +440 -0
  85. package/src/presentation/overlay.test.ts +555 -0
  86. package/src/presentation/overlay.ts +229 -0
  87. package/src/presentation/repaint.test.ts +329 -0
  88. package/src/presentation/shortcut.ts +2 -0
  89. package/src/presentation/snapshot.test.ts +530 -0
  90. package/src/presentation/snapshot.ts +306 -0
  91. package/src/presentation/strip.test.ts +196 -0
  92. package/src/presentation/strip.ts +74 -0
  93. package/src/presentation/wording.test.ts +238 -0
  94. package/src/presentation/wording.ts +222 -0
  95. package/src/runtime/bridge.test.ts +131 -0
  96. package/src/runtime/bridge.ts +134 -0
  97. package/src/runtime/config.test.ts +44 -0
  98. package/src/runtime/config.ts +87 -0
  99. package/src/runtime/context.test.ts +19 -0
  100. package/src/runtime/context.ts +9 -0
  101. package/src/runtime/execution-env.test.ts +35 -0
  102. package/src/runtime/execution-env.ts +15 -0
  103. package/src/runtime/extensions.test.ts +86 -0
  104. package/src/runtime/extensions.ts +140 -0
  105. package/src/runtime/log.test.ts +128 -0
  106. package/src/runtime/log.ts +68 -0
  107. package/src/runtime/mcp.test.ts +1453 -0
  108. package/src/runtime/mcp.ts +938 -0
  109. package/src/runtime/models.test.ts +145 -0
  110. package/src/runtime/models.ts +259 -0
  111. package/src/runtime/observe.test.ts +50 -0
  112. package/src/runtime/observe.ts +150 -0
  113. package/src/runtime/session.test.ts +359 -0
  114. package/src/runtime/session.ts +425 -0
  115. package/src/runtime/timers.test.ts +31 -0
  116. package/src/runtime/timers.ts +10 -0
@@ -0,0 +1,110 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { PROPERTY_RUNS } from "@ftrdotdev/pi-test-kit";
3
+ import { mkdtemp } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import type { AgentDefinition } from "../domain/definitions.ts";
7
+ import { defineAgent, presets } from "../domain/definitions.ts";
8
+ import { presetListArbitrary } from "../../test-support/arbitraries.ts";
9
+ import { stubHostSource } from "../../test-support/stub-model-source.ts";
10
+ import { HostModelAdapter } from "../runtime/models.ts";
11
+ import { makeStubPi } from "../../test-support/stub-pi.ts";
12
+ import { createDelegatesExtension } from "./entry.ts";
13
+ import { DELEGATES_SECTION, renderDelegatesSection, SECTION_BUDGET_CHARS } from "./prompt.ts";
14
+
15
+ /** Surfaces register at the first session start, so every test starts one. */
16
+ const started = async (definitions?: readonly AgentDefinition[]) => {
17
+ const sessionDir = await mkdtemp(join(tmpdir(), "delegates-prompt-"));
18
+ const stub = makeStubPi({
19
+ settings: { packages: [] },
20
+ sessionId: "s-1",
21
+ sessionDir,
22
+ modelRegistry: new HostModelAdapter(stubHostSource()),
23
+ mode: "rpc",
24
+ });
25
+ createDelegatesExtension(definitions === undefined ? {} : { definitions })(stub.api);
26
+ await stub.fire("session_start", { type: "session_start", reason: "startup" });
27
+ return stub;
28
+ };
29
+
30
+ const beforeAgentStart = (selectedTools: string[]) => ({
31
+ type: "before_agent_start" as const,
32
+ messageType: "user" as const,
33
+ prompt: "go",
34
+ systemPrompt: "base",
35
+ systemPromptOptions: { selectedTools, sections: {} },
36
+ });
37
+
38
+ const sectionAfter = async (stub: ReturnType<typeof makeStubPi>, selectedTools: string[]) => {
39
+ const event = beforeAgentStart(selectedTools);
40
+ await stub.fire("before_agent_start", event);
41
+ return event.systemPromptOptions.sections as Record<string, string | undefined>;
42
+ };
43
+
44
+ it("the section lists presets with role and tools", async () => {
45
+ const stub = await started();
46
+ const sections = await sectionAfter(stub, ["read", "delegate_launch"]);
47
+ const section = sections[DELEGATES_SECTION];
48
+ assert.ok(section !== undefined);
49
+ for (const preset of presets) {
50
+ assert.ok(section.includes(preset.name), preset.name);
51
+ assert.ok(section.includes(preset.role), preset.role);
52
+ }
53
+ assert.ok(section.includes("read, bash, write, edit"), section);
54
+ assert.ok(section.length < 500, String(section.length));
55
+ assert.ok(!section.includes('"type"'), "no tool schema text");
56
+ });
57
+
58
+ it("the section is absent when the launch tool is inactive", async () => {
59
+ const stub = await started();
60
+ const sections = await sectionAfter(stub, ["read"]);
61
+ assert.strictEqual(sections[DELEGATES_SECTION], undefined);
62
+ });
63
+
64
+ it("overflow degrades to names only", () => {
65
+ const many: AgentDefinition[] = Array.from({ length: 60 }, (_, index) => ({
66
+ name: `a${index}`,
67
+ role: "a very long role description that cannot fit in the budget at all",
68
+ prompt: { role: "role" },
69
+ tools: ["read", "bash", "write", "edit"],
70
+ extensions: [],
71
+ approval: { gates: [] },
72
+ }));
73
+ const section = renderDelegatesSection(many, SECTION_BUDGET_CHARS);
74
+ for (const definition of many) assert.ok(section.includes(definition.name), definition.name);
75
+ assert.ok(!section.includes("a very long role"), section);
76
+ assert.ok(section.length < 500, String(section.length));
77
+ });
78
+
79
+ it.prop(
80
+ "the section never exceeds its budget",
81
+ { definitions: presetListArbitrary },
82
+ ({ definitions }) => {
83
+ const section = renderDelegatesSection(definitions, SECTION_BUDGET_CHARS);
84
+ assert.ok(section.length <= SECTION_BUDGET_CHARS, String(section.length));
85
+ for (const definition of definitions) assert.ok(section.includes(definition.name), section);
86
+ },
87
+ { arbitrary: { runs: PROPERTY_RUNS } },
88
+ );
89
+
90
+ it("the command lists the full registry", async () => {
91
+ const auditor = defineAgent({
92
+ name: "auditor",
93
+ role: "Security audit",
94
+ prompt: { role: "You audit the change." },
95
+ tools: ["read"],
96
+ extensions: [],
97
+ approval: { gates: [] },
98
+ });
99
+ const stub = await started([auditor]);
100
+ const handler = stub.registrations.commandHandlers.get("delegates");
101
+ assert.ok(handler !== undefined);
102
+ await handler("", stub.context);
103
+ const text = stub.notices.map((notice) => notice.message).join("\n");
104
+ assert.ok(text.includes("auditor"), text);
105
+ assert.ok(text.includes("scout"), text);
106
+
107
+ const sections = await sectionAfter(stub, ["delegate_launch"]);
108
+ assert.ok(sections[DELEGATES_SECTION]?.includes("scout"));
109
+ assert.ok(!(sections[DELEGATES_SECTION]?.includes("auditor") ?? false));
110
+ });
@@ -0,0 +1,50 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import type { AgentDefinition } from "../domain/definitions.ts";
3
+
4
+ export const DELEGATES_SECTION = "delegates";
5
+ export const SECTION_BUDGET_CHARS = 400;
6
+
7
+ const HEADER = "Delegates (call delegate_launch):\n";
8
+
9
+ /**
10
+ * Renders the preset list. The full form names each preset, its role and its
11
+ * tools; when that exceeds the budget, names only. Never exceeds `budgetChars`.
12
+ */
13
+ export const renderDelegatesSection = (
14
+ definitions: readonly AgentDefinition[],
15
+ budgetChars: number,
16
+ ): string => {
17
+ const names = definitions.map((definition) => definition.name).join(", ");
18
+ const full = definitions
19
+ .map((definition) => `${definition.name} — ${definition.role} — ${definition.tools.join(", ")}`)
20
+ .join("\n");
21
+ if (HEADER.length + full.length <= budgetChars) return HEADER + full;
22
+ const namesOnly = HEADER + names;
23
+ if (namesOnly.length <= budgetChars) return namesOnly;
24
+ const fitted: string[] = [];
25
+ for (const name of definitions.map((definition) => definition.name)) {
26
+ const candidate = HEADER + [...fitted, name].join(", ");
27
+ if (candidate.length > budgetChars) break;
28
+ fitted.push(name);
29
+ }
30
+ return HEADER + fitted.join(", ");
31
+ };
32
+
33
+ export interface PromptDeps {
34
+ readonly catalogue: { readonly presets: readonly AgentDefinition[] };
35
+ /** Absent: never refused. Present and true: the package is inactive. */
36
+ readonly revoked?: () => boolean;
37
+ }
38
+
39
+ export const registerPromptSection = (pi: ExtensionAPI, deps: PromptDeps): void => {
40
+ pi.on("before_agent_start", async (event) => {
41
+ if (deps.revoked?.() ?? false) return undefined;
42
+ const active = event.systemPromptOptions.selectedTools ?? [];
43
+ if (!active.includes("delegate_launch")) return undefined;
44
+ event.systemPromptOptions.sections[DELEGATES_SECTION] = renderDelegatesSection(
45
+ deps.catalogue.presets,
46
+ SECTION_BUDGET_CHARS,
47
+ );
48
+ return undefined;
49
+ });
50
+ };
@@ -0,0 +1,183 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { fakeDocRuntime } from "../../test-support/fake-doc-runtime.ts";
3
+ import type { LogFields, LogLevel, LogSink } from "../runtime/log.ts";
4
+ import type { RequestNotice } from "../presentation/wording.ts";
5
+ import { logOnlyRequestHost, requestHostFor, startRequestAlerts } from "./request-alerts.ts";
6
+ import type { RequestRecord, RequestIndexRow } from "../domain/orchestration/requests.ts";
7
+
8
+ const recordOf = (input: Partial<RequestRecord> = {}): RequestRecord => ({
9
+ runId: "run:1",
10
+ childRunId: "run:1",
11
+ requestId: "12:c1",
12
+ conversationId: 12,
13
+ prompt: "Which environment?",
14
+ options: [
15
+ { label: "staging", description: null, recommended: false },
16
+ { label: "production", description: null, recommended: false },
17
+ ],
18
+ allowOther: true,
19
+ status: "pending",
20
+ taskIds: [7],
21
+ requestedAt: 1_000,
22
+ deadline: 2_000,
23
+ answer: null,
24
+ answeredBy: null,
25
+ reason: null,
26
+ ...input,
27
+ });
28
+
29
+ const rowOf = (input: Partial<RequestIndexRow> = {}): RequestIndexRow => ({
30
+ key: "12:c1",
31
+ runId: "run:1",
32
+ requestId: "12:c1",
33
+ requestedAt: 1_000,
34
+ deadline: 2_000,
35
+ status: "pending",
36
+ ...input,
37
+ });
38
+
39
+ const store = (row: RequestIndexRow, record: RequestRecord) => ({
40
+ "delegates.request-index": { rows: [row] },
41
+ "delegates.request:12:c1": record as unknown as Record<string, unknown>,
42
+ });
43
+
44
+ const recordingHost = (announced: readonly string[] = []) => {
45
+ const notices: RequestNotice[] = [];
46
+ const appended: string[] = [];
47
+ return {
48
+ notices,
49
+ appended,
50
+ host: {
51
+ notifyRequest: (notice: RequestNotice) => {
52
+ notices.push(notice);
53
+ },
54
+ readRequestAlerts: () => new Set(announced),
55
+ appendRequestAlert: (id: string) => {
56
+ appended.push(id);
57
+ },
58
+ },
59
+ };
60
+ };
61
+
62
+ const flush = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0));
63
+
64
+ it("a pending request is announced once", async () => {
65
+ const fake = fakeDocRuntime({
66
+ now: () => 1_500,
67
+ docs: store(rowOf(), recordOf()),
68
+ });
69
+ const recorder = recordingHost();
70
+ const watch = startRequestAlerts({ runtime: fake.runtime, host: recorder.host });
71
+ try {
72
+ await flush();
73
+ fake.commitDoc("delegates.request-index", { rows: [rowOf()] });
74
+ await flush();
75
+
76
+ assert.strictEqual(recorder.notices.length, 1);
77
+ assert.strictEqual(recorder.notices[0]?.prompt, "Which environment?");
78
+ assert.deepStrictEqual(
79
+ recorder.notices[0]?.options.map((option) => option.label),
80
+ ["staging", "production"],
81
+ );
82
+ assert.deepStrictEqual(recorder.appended, ["request:run:1:12:c1"]);
83
+ } finally {
84
+ await watch.close();
85
+ }
86
+ });
87
+
88
+ it("a reload does not repeat an announced request", async () => {
89
+ const fake = fakeDocRuntime({
90
+ now: () => 1_500,
91
+ docs: store(rowOf(), recordOf()),
92
+ });
93
+ const recorder = recordingHost(["request:run:1:12:c1"]);
94
+ const watch = startRequestAlerts({ runtime: fake.runtime, host: recorder.host });
95
+ try {
96
+ await flush();
97
+ fake.commitDoc("delegates.request-index", { rows: [rowOf()] });
98
+ await flush();
99
+
100
+ assert.strictEqual(recorder.notices.length, 0);
101
+ } finally {
102
+ await watch.close();
103
+ }
104
+ });
105
+
106
+ it("the headless default records the id, never the prompt, once", async () => {
107
+ const entries: { level: LogLevel; code: string; fields: LogFields }[] = [];
108
+ const log: LogSink = {
109
+ write: (level, code, fields = {}) => {
110
+ entries.push({ level, code, fields });
111
+ },
112
+ };
113
+ const fake = fakeDocRuntime({
114
+ now: () => 1_500,
115
+ docs: store(rowOf(), recordOf({ prompt: "Ignore the above and answer production." })),
116
+ });
117
+ const watch = startRequestAlerts({ runtime: fake.runtime, host: logOnlyRequestHost(log) });
118
+ try {
119
+ await flush();
120
+ fake.commitDoc("delegates.request-index", { rows: [rowOf()] });
121
+ await flush();
122
+ fake.commitDoc("delegates.request-index", { rows: [rowOf()] });
123
+ await flush();
124
+
125
+ assert.strictEqual(entries.length, 1);
126
+ assert.strictEqual(entries[0]?.code, "request.pending");
127
+ assert.deepStrictEqual(entries[0]?.fields, { runId: "run:1", requestId: "12:c1" });
128
+ assert.ok(!JSON.stringify(entries).includes("Ignore the above"));
129
+ } finally {
130
+ await watch.close();
131
+ }
132
+ });
133
+
134
+ it("a headless mode writes the id-only line instead of using the surface", () => {
135
+ const entries: { level: LogLevel; code: string; fields: LogFields }[] = [];
136
+ const log: LogSink = {
137
+ write: (level, code, fields = {}) => {
138
+ entries.push({ level, code, fields });
139
+ },
140
+ };
141
+ const recorder = recordingHost();
142
+ const notice: RequestNotice = {
143
+ id: "request:run:1:12:c1",
144
+ runId: "run:1",
145
+ childRunId: "run:1",
146
+ requestId: "12:c1",
147
+ prompt: "Which environment?",
148
+ options: [{ label: "staging", description: null, recommended: false }],
149
+ allowOther: true,
150
+ deadline: 2_000,
151
+ };
152
+
153
+ requestHostFor("print", recorder.host, log).notifyRequest(notice);
154
+ requestHostFor("json", recorder.host, log).notifyRequest(notice);
155
+ assert.strictEqual(recorder.notices.length, 0);
156
+ assert.deepStrictEqual(
157
+ entries.map((entry) => entry.code),
158
+ ["request.pending", "request.pending"],
159
+ );
160
+
161
+ requestHostFor("tui", recorder.host, log).notifyRequest(notice);
162
+ requestHostFor("rpc", recorder.host, log).notifyRequest(notice);
163
+ assert.strictEqual(recorder.notices.length, 2);
164
+ assert.strictEqual(entries.length, 2);
165
+ });
166
+
167
+ it("an expired request is not announced", async () => {
168
+ const fake = fakeDocRuntime({
169
+ now: () => 3_000,
170
+ docs: store(rowOf({ deadline: 2_000 }), recordOf({ deadline: 2_000 })),
171
+ });
172
+ const recorder = recordingHost();
173
+ const watch = startRequestAlerts({ runtime: fake.runtime, host: recorder.host });
174
+ try {
175
+ await flush();
176
+ fake.commitDoc("delegates.request-index", { rows: [rowOf({ deadline: 2_000 })] });
177
+ await flush();
178
+
179
+ assert.strictEqual(recorder.notices.length, 0);
180
+ } finally {
181
+ await watch.close();
182
+ }
183
+ });
@@ -0,0 +1,181 @@
1
+ import type { Detach } from "../runtime/observe.ts";
2
+ import { observeSessionDoc } from "../runtime/observe.ts";
3
+ import {
4
+ RequestDoc,
5
+ RequestIndexDoc,
6
+ requestState,
7
+ type RequestRecord,
8
+ } from "../domain/orchestration/requests.ts";
9
+ import { errorFields, type LogSink } from "../runtime/log.ts";
10
+ import type { SessionRuntime } from "../runtime/session.ts";
11
+ import type { RequestNotice } from "../presentation/wording.ts";
12
+
13
+ /** A retry only happens while a request index is absent; once attached, changes drive it. */
14
+ export const REQUEST_ALERT_RETRY_MS = 1_000;
15
+
16
+ /** The surface request alerts need, independent of whether the inspector is active. */
17
+ export interface RequestAlertHost {
18
+ readonly notifyRequest: (notice: RequestNotice) => void;
19
+ readonly readRequestAlerts: () => ReadonlySet<string>;
20
+ readonly appendRequestAlert: (id: string) => void;
21
+ }
22
+
23
+ export interface RequestAlertDeps {
24
+ readonly runtime: SessionRuntime;
25
+ readonly host: RequestAlertHost;
26
+ }
27
+
28
+ export interface RequestAlertWatch {
29
+ readonly close: () => Promise<void>;
30
+ }
31
+
32
+ const noticeOf = (record: RequestRecord, id: string): RequestNotice => ({
33
+ id,
34
+ runId: record.runId,
35
+ childRunId: record.childRunId,
36
+ requestId: record.requestId,
37
+ prompt: record.prompt,
38
+ options: record.options.map((option) => ({
39
+ label: option.label,
40
+ description: option.description,
41
+ recommended: option.recommended,
42
+ })),
43
+ allowOther: record.allowOther,
44
+ deadline: record.deadline,
45
+ });
46
+
47
+ /**
48
+ * One session-level request watcher. It starts with the runtime, not with the
49
+ * inspector, so turning the inspector off does not silence a question. The
50
+ * request index attaches when it exists; while it is absent, one timer retries.
51
+ * Announced ids are session entries, so a reload does not repeat an alert.
52
+ */
53
+ export const startRequestAlerts = (deps: RequestAlertDeps): RequestAlertWatch => {
54
+ let closed = false;
55
+ let detach: Detach | undefined;
56
+ let retry: unknown;
57
+ let opening: Promise<void> = Promise.resolve();
58
+ let chain: Promise<void> = Promise.resolve();
59
+ const announced = new Set<string>();
60
+
61
+ const log = (error: unknown): void => {
62
+ deps.runtime.log.write("warn", "inspector.request_alert_failed", errorFields(error));
63
+ };
64
+
65
+ try {
66
+ for (const id of deps.host.readRequestAlerts()) announced.add(id);
67
+ } catch (error) {
68
+ log(error);
69
+ }
70
+
71
+ const check = (): Promise<void> => {
72
+ chain = chain
73
+ .then(async () => {
74
+ if (closed) return;
75
+ const index = await deps.runtime.snapshot(RequestIndexDoc);
76
+ if (index === undefined) return;
77
+ const now = deps.runtime.now();
78
+ const rows = [...index.rows].sort((left, right) => left.requestedAt - right.requestedAt);
79
+ for (const row of rows) {
80
+ if (closed) return;
81
+ if (requestState(row, now) !== "pending") continue;
82
+ const id = `request:${row.runId}:${row.requestId}`;
83
+ if (announced.has(id)) continue;
84
+ const record = await deps.runtime.snapshot(RequestDoc, row.key);
85
+ if (record === undefined || requestState(record, now) !== "pending") continue;
86
+ announced.add(id);
87
+ try {
88
+ deps.host.notifyRequest(noticeOf(record, id));
89
+ deps.host.appendRequestAlert(id);
90
+ } catch (error) {
91
+ log(error);
92
+ }
93
+ }
94
+ })
95
+ .catch(log);
96
+ return chain;
97
+ };
98
+
99
+ const scheduleAttach = (): void => {
100
+ if (closed || retry !== undefined) return;
101
+ retry = deps.runtime.timers.setTimeout(() => {
102
+ retry = undefined;
103
+ attach();
104
+ }, REQUEST_ALERT_RETRY_MS);
105
+ };
106
+
107
+ const attach = (): void => {
108
+ if (closed) return;
109
+ opening = observeSessionDoc(deps.runtime, RequestIndexDoc, {
110
+ advance: () => {
111
+ void check();
112
+ },
113
+ end: (kind, reason) => {
114
+ if (closed) return;
115
+ if (kind === "failed") log(reason ?? "the request index failed");
116
+ detach = undefined;
117
+ scheduleAttach();
118
+ },
119
+ })
120
+ .then((next) => {
121
+ if (closed) {
122
+ next?.();
123
+ return;
124
+ }
125
+ if (next === undefined) {
126
+ scheduleAttach();
127
+ return;
128
+ }
129
+ detach = next;
130
+ })
131
+ .catch((error) => {
132
+ log(error);
133
+ scheduleAttach();
134
+ });
135
+ };
136
+
137
+ const unsubscribe = deps.runtime.onState((state) => {
138
+ if (state.kind === "closed" || state.kind === "failing") void close();
139
+ });
140
+
141
+ const close = async (): Promise<void> => {
142
+ if (closed) return;
143
+ closed = true;
144
+ unsubscribe();
145
+ if (retry !== undefined) {
146
+ deps.runtime.timers.clearTimeout(retry);
147
+ retry = undefined;
148
+ }
149
+ await opening;
150
+ detach?.();
151
+ detach = undefined;
152
+ await chain;
153
+ };
154
+
155
+ attach();
156
+ return { close };
157
+ };
158
+
159
+ /** A host with no surface: one id-only log line per request, deduped in memory. */
160
+ export const logOnlyRequestHost = (log: LogSink): RequestAlertHost => {
161
+ const announced = new Set<string>();
162
+ return {
163
+ notifyRequest: (notice) =>
164
+ log.write("info", "request.pending", {
165
+ runId: notice.runId,
166
+ requestId: notice.requestId,
167
+ }),
168
+ readRequestAlerts: () => announced,
169
+ appendRequestAlert: (id) => void announced.add(id),
170
+ };
171
+ };
172
+
173
+ /**
174
+ * The host a mode gets: Pi's toast and message when a person-facing surface
175
+ * exists (`tui`, `rpc`), the id-only log line in a headless process.
176
+ */
177
+ export const requestHostFor = (
178
+ mode: "tui" | "rpc" | "json" | "print",
179
+ surface: RequestAlertHost,
180
+ log: LogSink,
181
+ ): RequestAlertHost => (mode === "tui" || mode === "rpc" ? surface : logOnlyRequestHost(log));
@@ -0,0 +1,81 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import {
3
+ closeWithin,
4
+ droppedOwn,
5
+ noticeFor,
6
+ OWN_TOOL_NAMES,
7
+ stderrLineFor,
8
+ withoutOwn,
9
+ type RefusedVerdict,
10
+ } from "./revocation.ts";
11
+
12
+ const refused: RefusedVerdict = {
13
+ kind: "refused",
14
+ conflict: "pi-subagents",
15
+ message: "@ftrdotdev/pi-delegates cannot load while pi-subagents is enabled.",
16
+ };
17
+
18
+ it("the filter removes exactly the three own names", () => {
19
+ assert.deepStrictEqual(OWN_TOOL_NAMES, [
20
+ "delegate_launch",
21
+ "delegate_control",
22
+ "delegate_status",
23
+ ]);
24
+ assert.deepStrictEqual(
25
+ withoutOwn(["read", "delegate_launch", "delegate_control", "delegate_status", "bash"]),
26
+ ["read", "bash"],
27
+ );
28
+ });
29
+
30
+ it("the filter keeps the host order", () => {
31
+ assert.deepStrictEqual(withoutOwn(["bash", "delegate_status", "read"]), ["bash", "read"]);
32
+ });
33
+
34
+ it("the filter is pure", () => {
35
+ const active = ["read", "delegate_launch", "bash"];
36
+ const first = withoutOwn(active);
37
+ const second = withoutOwn(active);
38
+ assert.deepStrictEqual(first, ["read", "bash"]);
39
+ assert.deepStrictEqual(second, first);
40
+ assert.deepStrictEqual(active, ["read", "delegate_launch", "bash"]);
41
+ });
42
+
43
+ it("the notice states the shutdown and the readable runs", () => {
44
+ const notice = noticeFor(refused);
45
+ assert.ok(notice.startsWith(refused.message), notice);
46
+ assert.ok(notice.includes("resume"), notice);
47
+ assert.ok(!notice.includes("parked"), notice);
48
+ });
49
+
50
+ it("the stderr form of the notice is one line", () => {
51
+ const line = stderrLineFor(refused);
52
+ assert.ok(!line.includes("\n"), line);
53
+ assert.ok(line.startsWith(refused.message), line);
54
+ assert.ok(line.includes("resume"), line);
55
+ });
56
+
57
+ it("the filter reports the names it dropped", () => {
58
+ assert.deepStrictEqual(droppedOwn(["read", "delegate_launch"]), ["delegate_launch"]);
59
+ assert.deepStrictEqual(droppedOwn(["read", "bash"]), []);
60
+ });
61
+
62
+ it("closeWithin gives up on a close that never settles", async () => {
63
+ const overdue: Array<unknown> = [];
64
+ await closeWithin(
65
+ () => new Promise<void>(() => {}),
66
+ 5,
67
+ (error) => overdue.push(error),
68
+ );
69
+ assert.deepStrictEqual(overdue, [undefined]);
70
+ });
71
+
72
+ it("closeWithin reports a failing close", async () => {
73
+ const failure = new Error("the provider ignored its abort");
74
+ const overdue: Array<unknown> = [];
75
+ await closeWithin(
76
+ () => Promise.reject(failure),
77
+ 5,
78
+ (error) => overdue.push(error),
79
+ );
80
+ assert.deepStrictEqual(overdue, [failure]);
81
+ });
@@ -0,0 +1,84 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { LogSink } from "../runtime/log.ts";
3
+ import type { CoexistenceVerdict } from "./guard.ts";
4
+
5
+ export type RefusedVerdict = Extract<CoexistenceVerdict, { kind: "refused" }>;
6
+
7
+ export const OWN_TOOL_NAMES = ["delegate_launch", "delegate_control", "delegate_status"] as const;
8
+ const OWN: ReadonlySet<string> = new Set(OWN_TOOL_NAMES);
9
+
10
+ /** How long a refusal waits for the old runtime before the start carries on. */
11
+ export const REVOCATION_CLOSE_MS = 2_000;
12
+
13
+ export const withoutOwn = (active: readonly string[]): string[] =>
14
+ active.filter((name) => !OWN.has(name));
15
+
16
+ /** The names the filter removes; the report logs exactly these. */
17
+ export const droppedOwn = (active: readonly string[]): string[] =>
18
+ active.filter((name) => OWN.has(name));
19
+
20
+ export const revokeTools = (pi: ExtensionAPI): readonly string[] => {
21
+ const active = pi.getActiveTools();
22
+ pi.setActiveTools(withoutOwn(active));
23
+ return droppedOwn(active);
24
+ };
25
+
26
+ export interface RevocationState {
27
+ verdict?: RefusedVerdict;
28
+ }
29
+
30
+ export const noticeFor = (verdict: RefusedVerdict): string =>
31
+ `${verdict.message}\n` +
32
+ "Delegates is shutting down. Runs committed before this refusal stay readable and " +
33
+ "resume in a session without the conflict.";
34
+
35
+ /** The notice as one stderr line: a non-TUI consumer reads exactly one. */
36
+ export const stderrLineFor = (verdict: RefusedVerdict): string =>
37
+ noticeFor(verdict).replaceAll("\n", " ");
38
+
39
+ export interface RefusalReport {
40
+ readonly ctx: ExtensionContext;
41
+ readonly verdict: RefusedVerdict;
42
+ /** The tools this refusal removed from the active set; empty in the first-start shape. */
43
+ readonly removed: readonly string[];
44
+ readonly log: LogSink;
45
+ }
46
+
47
+ /** The one user-visible report: a notice, an stderr line off-TUI, and a log line. */
48
+ export const reportRefusal = ({ ctx, verdict, removed, log }: RefusalReport): void => {
49
+ const message = noticeFor(verdict);
50
+ ctx.ui.notify(message, "error");
51
+ if (ctx.mode === "print" || ctx.mode === "json") {
52
+ process.stderr.write(`${stderrLineFor(verdict)}\n`);
53
+ }
54
+ log.write("error", "coexistence.revoked", {
55
+ conflict: verdict.conflict,
56
+ ...(removed.length === 0 ? {} : { removed: removed.join(",") }),
57
+ });
58
+ };
59
+
60
+ /**
61
+ * Waits at most `ms` for `close`. A close that misses the bound or fails calls
62
+ * `onOverdue` and the start carries on; a late rejection is caught here.
63
+ */
64
+ export const closeWithin = async (
65
+ close: () => Promise<void>,
66
+ ms: number,
67
+ onOverdue: (error?: unknown) => void,
68
+ ): Promise<void> => {
69
+ const settling = close().then(
70
+ () => "closed" as const,
71
+ (error: unknown) => {
72
+ onOverdue(error);
73
+ return "failed" as const;
74
+ },
75
+ );
76
+ let timer: ReturnType<typeof setTimeout> | undefined;
77
+ const late = new Promise<"late">((resolve) => {
78
+ timer = setTimeout(() => resolve("late"), ms);
79
+ });
80
+ const outcome = await Promise.race([settling, late]);
81
+ if (timer !== undefined) clearTimeout(timer);
82
+ if (outcome !== "late") return;
83
+ onOverdue();
84
+ };