@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,175 @@
1
+ import { listedRuns, RunDoc } from "../domain/run-records.ts";
2
+ import { errorFields, truncate, type LogSink, DETAIL_LIMIT } from "../runtime/log.ts";
3
+ import type { SessionRuntime } from "../runtime/session.ts";
4
+ import {
5
+ SETTLE_MAX_ROWS,
6
+ settleAgentMessage,
7
+ type SettleNotice,
8
+ type SettleRow,
9
+ } from "../presentation/wording.ts";
10
+
11
+ /** One coalescing window: every settlement inside it arrives as one message. */
12
+ export const SETTLE_COALESCE_MS = 1_000;
13
+
14
+ /** The start scan reads the newest this many run ids; the rest are not enumerated. */
15
+ export const SETTLE_SCAN_LIMIT = 200;
16
+
17
+ /** The surface a settle notice needs, independent of whether the inspector is active. */
18
+ export interface SettleAlertHost {
19
+ readonly notifySettled: (notice: SettleNotice, omitted?: number) => void;
20
+ }
21
+
22
+ export interface SettleAlertDeps {
23
+ readonly runtime: SessionRuntime;
24
+ readonly host: SettleAlertHost;
25
+ /** The only committer of the announced marker: the recorder's announcement path. */
26
+ readonly announce: (runId: string, taskId: number) => Promise<void>;
27
+ readonly log: LogSink;
28
+ /** Overrides `SETTLE_COALESCE_MS` in tests. */
29
+ readonly intervalMs?: number;
30
+ }
31
+
32
+ export interface SettleAlertWatch {
33
+ readonly close: () => Promise<void>;
34
+ }
35
+
36
+ /** One admitted row and the task whose settlement it reports. */
37
+ interface PendingRow {
38
+ readonly runId: string;
39
+ readonly taskId: number;
40
+ readonly row: SettleRow;
41
+ }
42
+
43
+ /**
44
+ * One session-level settle watcher. It never observes a run document: the
45
+ * recorder emits in-process after its commit landed, and the start scan covers
46
+ * a run that settled while Pi was closed. It holds no announcement state — the
47
+ * marker is the run document's — so one run is announced once.
48
+ */
49
+ export const startSettleAlerts = (deps: SettleAlertDeps): SettleAlertWatch => {
50
+ let closed = false;
51
+ let armed: unknown;
52
+ let chain: Promise<void> = Promise.resolve();
53
+ const pending: PendingRow[] = [];
54
+
55
+ const log = (error: unknown): void => {
56
+ deps.log.write("warn", "settle.notify_failed", errorFields(error));
57
+ };
58
+
59
+ const enqueue = (task: () => Promise<void>): Promise<void> => {
60
+ chain = chain.then(task).catch(log);
61
+ return chain;
62
+ };
63
+
64
+ const roleOf = (value: unknown): string =>
65
+ typeof value === "string" && value.length > 0 ? value : "unknown";
66
+
67
+ /** Admit one run when it is detached, settled and not yet announced for this task. */
68
+ const admit = async (runId: string): Promise<void> => {
69
+ if (closed) return;
70
+ const doc = await deps.runtime.snapshot(RunDoc, runId);
71
+ if (doc === undefined) return;
72
+ const taskId = doc.taskId;
73
+ if (doc.execution !== "detached") return;
74
+ if (doc.resolution === null) return;
75
+ if (taskId === null || doc.settledTaskId === taskId) return;
76
+ const row: SettleRow = {
77
+ runId,
78
+ definition: roleOf(doc.definition),
79
+ outcome: doc.resolution,
80
+ failure: doc.failure,
81
+ parentRunId: doc.parentRunId,
82
+ };
83
+ const existing = pending.findIndex((entry) => entry.runId === runId);
84
+ if (existing >= 0) pending.splice(existing, 1, { runId, taskId, row });
85
+ else pending.push({ runId, taskId, row });
86
+ arm();
87
+ };
88
+
89
+ const arm = (): void => {
90
+ if (closed || armed !== undefined) return;
91
+ armed = deps.runtime.timers.setTimeout(() => {
92
+ armed = undefined;
93
+ void enqueue(deliver);
94
+ }, deps.intervalMs ?? SETTLE_COALESCE_MS);
95
+ };
96
+
97
+ /** One window: hand at most `SETTLE_MAX_ROWS` rows to the host, then commit each marker. */
98
+ const deliver = async (): Promise<void> => {
99
+ if (closed || pending.length === 0) return;
100
+ const batch = pending.slice(0, SETTLE_MAX_ROWS);
101
+ const omitted = pending.length - batch.length;
102
+ const runs = batch.map((entry) => entry.runId).join(",");
103
+ try {
104
+ deps.host.notifySettled({ rows: batch.map((entry) => entry.row) }, omitted);
105
+ } catch (error) {
106
+ deps.log.write("warn", "settle.notify_failed", { runs, ...errorFields(error) });
107
+ // Nothing was delivered: the rows stay pending for the next window.
108
+ arm();
109
+ return;
110
+ }
111
+ pending.splice(0, batch.length);
112
+ for (const entry of batch) {
113
+ try {
114
+ await deps.announce(entry.runId, entry.taskId);
115
+ } catch (error) {
116
+ log(error);
117
+ }
118
+ }
119
+ if (pending.length > 0) arm();
120
+ };
121
+
122
+ /**
123
+ * Once at start: the newest `SETTLE_SCAN_LIMIT` run ids with their group children,
124
+ * and one line when the window truncates.
125
+ */
126
+ const scan = async (): Promise<void> => {
127
+ const { runIds, omitted } = await listedRuns(deps.runtime, { limit: SETTLE_SCAN_LIMIT });
128
+ if (omitted > 0) {
129
+ deps.log.write("info", "settle.scan_truncated", { omitted });
130
+ }
131
+ for (const runId of runIds) {
132
+ if (closed) return;
133
+ await admit(runId);
134
+ }
135
+ };
136
+
137
+ const unsubscribe = deps.runtime.settle.on((event) => {
138
+ void enqueue(() => admit(event.runId));
139
+ });
140
+
141
+ const onState = deps.runtime.onState((state) => {
142
+ if (state.kind === "closed" || state.kind === "failing") void close();
143
+ });
144
+
145
+ const close = async (): Promise<void> => {
146
+ if (closed) return;
147
+ closed = true;
148
+ unsubscribe();
149
+ onState();
150
+ if (armed !== undefined) {
151
+ deps.runtime.timers.clearTimeout(armed);
152
+ armed = undefined;
153
+ }
154
+ await chain;
155
+ };
156
+
157
+ void enqueue(scan);
158
+ return { close };
159
+ };
160
+
161
+ /** A host with no surface: one id-only log line per batch. */
162
+ export const logOnlySettleHost = (log: LogSink): SettleAlertHost => ({
163
+ notifySettled: (notice, omitted = 0) =>
164
+ log.write("info", "run.settled", {
165
+ runs: notice.rows.map((row) => row.runId).join(","),
166
+ detail: truncate(settleAgentMessage(notice, omitted), DETAIL_LIMIT),
167
+ }),
168
+ });
169
+
170
+ /** The host a mode gets: a person-facing surface in `tui`/`rpc`, the log line otherwise. */
171
+ export const settleHostFor = (
172
+ mode: "tui" | "rpc" | "json" | "print",
173
+ surface: SettleAlertHost,
174
+ log: LogSink,
175
+ ): SettleAlertHost => (mode === "tui" || mode === "rpc" ? surface : logOnlySettleHost(log));
@@ -0,0 +1,62 @@
1
+ import { assert, it, vi } from "@effect/vitest";
2
+ import { join, makeTempDir, writeText } from "../../test-support/platform.ts";
3
+ import { DEFAULT_INSPECT_SHORTCUT } from "../presentation/shortcut.ts";
4
+ import {
5
+ INSPECT_SHORTCUT_ENV,
6
+ INSPECT_SHORTCUT_FILE,
7
+ isValidInspectShortcut,
8
+ resolveInspectShortcut,
9
+ } from "./shortcut.ts";
10
+
11
+ const agentDir = (): Promise<string> => makeTempDir("delegates-shortcut-");
12
+
13
+ it("accepts the documented key shapes", () => {
14
+ for (const key of ["ctrl+space", "ctrl+alt+i", "ctrl+shift+i", "f2", "escape"]) {
15
+ assert.strictEqual(isValidInspectShortcut(key), true, key);
16
+ }
17
+ for (const key of ["", "ctrl+", "ctrl+nope", "ctrl+ctrl+i", "f13"]) {
18
+ assert.strictEqual(isValidInspectShortcut(key), false, key);
19
+ }
20
+ });
21
+
22
+ it("defaults to ctrl+space", async () => {
23
+ assert.strictEqual(resolveInspectShortcut(undefined, await agentDir()), DEFAULT_INSPECT_SHORTCUT);
24
+ });
25
+
26
+ it("reads inspectorShortcut from delegates.json", async () => {
27
+ const dir = await agentDir();
28
+ await writeText(
29
+ join(dir, INSPECT_SHORTCUT_FILE),
30
+ JSON.stringify({ inspectorShortcut: "ctrl+alt+i" }),
31
+ );
32
+ assert.strictEqual(resolveInspectShortcut(undefined, dir), "ctrl+alt+i");
33
+ });
34
+
35
+ it("an explicit option beats the environment and the file", async () => {
36
+ const dir = await agentDir();
37
+ await writeText(
38
+ join(dir, INSPECT_SHORTCUT_FILE),
39
+ JSON.stringify({ inspectorShortcut: "ctrl+alt+i" }),
40
+ );
41
+ vi.stubEnv(INSPECT_SHORTCUT_ENV, "f2");
42
+ assert.strictEqual(resolveInspectShortcut("ctrl+shift+i", dir), "ctrl+shift+i");
43
+ });
44
+
45
+ it("the environment beats the file", async () => {
46
+ const dir = await agentDir();
47
+ await writeText(
48
+ join(dir, INSPECT_SHORTCUT_FILE),
49
+ JSON.stringify({ inspectorShortcut: "ctrl+alt+i" }),
50
+ );
51
+ vi.stubEnv(INSPECT_SHORTCUT_ENV, "f2");
52
+ assert.strictEqual(resolveInspectShortcut(undefined, dir), "f2");
53
+ });
54
+
55
+ it("an invalid file value falls back to the default", async () => {
56
+ const dir = await agentDir();
57
+ await writeText(
58
+ join(dir, INSPECT_SHORTCUT_FILE),
59
+ JSON.stringify({ inspectorShortcut: "ctrl+nope" }),
60
+ );
61
+ assert.strictEqual(resolveInspectShortcut(undefined, dir), DEFAULT_INSPECT_SHORTCUT);
62
+ });
@@ -0,0 +1,105 @@
1
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
2
+ import { Predicate } from "effect";
3
+ import { readFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { DEFAULT_INSPECT_SHORTCUT } from "../presentation/shortcut.ts";
6
+
7
+ /** A per-user override; the CLI environment is the least surprising place for a one-off run. */
8
+ export const INSPECT_SHORTCUT_ENV = "PI_DELEGATES_INSPECTOR_SHORTCUT";
9
+
10
+ /** The extension's own settings file; Pi's `keybindings.json` only names built-in actions. */
11
+ export const INSPECT_SHORTCUT_FILE = "delegates.json";
12
+
13
+ const SYMBOLS = [
14
+ "`",
15
+ "-",
16
+ "=",
17
+ "[",
18
+ "]",
19
+ "\\",
20
+ ";",
21
+ "'",
22
+ ",",
23
+ ".",
24
+ "/",
25
+ "!",
26
+ "@",
27
+ "#",
28
+ "$",
29
+ "%",
30
+ "^",
31
+ "&",
32
+ "*",
33
+ "(",
34
+ ")",
35
+ "_",
36
+ "+",
37
+ "|",
38
+ "~",
39
+ "{",
40
+ "}",
41
+ ":",
42
+ "<",
43
+ ">",
44
+ "?",
45
+ ];
46
+
47
+ const NAMED_KEYS = new Set([
48
+ // ASCII ranges only: splitting into code units is exact here.
49
+ ..."abcdefghijklmnopqrstuvwxyz".split(""),
50
+ ..."0123456789".split(""),
51
+ ...SYMBOLS,
52
+ "escape",
53
+ "esc",
54
+ "enter",
55
+ "return",
56
+ "tab",
57
+ "space",
58
+ "backspace",
59
+ "delete",
60
+ "insert",
61
+ "clear",
62
+ "home",
63
+ "end",
64
+ "pageup",
65
+ "pagedown",
66
+ "up",
67
+ "down",
68
+ "left",
69
+ "right",
70
+ ]);
71
+
72
+ const MODIFIERS = new Set(["ctrl", "shift", "alt", "super"]);
73
+
74
+ /** `ctrl+space`, `ctrl+alt+i`, `f2`, or any key Pi's `KeyId` accepts. */
75
+ export const isValidInspectShortcut = (value: string): boolean => {
76
+ const parts = value.trim().toLowerCase().split("+");
77
+ const key = parts.pop();
78
+ if (key === undefined || key.length === 0) return false;
79
+ if (parts.some((modifier) => !MODIFIERS.has(modifier))) return false;
80
+ if (new Set(parts).size !== parts.length) return false;
81
+ return NAMED_KEYS.has(key) || /^f(?:[1-9]|1[0-2])$/.test(key);
82
+ };
83
+
84
+ const accepted = (value: unknown): string | undefined =>
85
+ typeof value === "string" && isValidInspectShortcut(value) ? value.trim() : undefined;
86
+
87
+ const fromFile = (agentDir: string): string | undefined => {
88
+ try {
89
+ const parsed: unknown = JSON.parse(readFileSync(join(agentDir, INSPECT_SHORTCUT_FILE), "utf8"));
90
+ if (!Predicate.isObject(parsed)) return undefined;
91
+ return accepted(parsed.inspectorShortcut);
92
+ } catch {
93
+ return undefined;
94
+ }
95
+ };
96
+
97
+ /** Option beats environment, environment beats the user file, then the default. */
98
+ export const resolveInspectShortcut = (
99
+ configured: string | undefined,
100
+ agentDir: string = getAgentDir(),
101
+ ): string =>
102
+ accepted(configured) ??
103
+ accepted(process.env[INSPECT_SHORTCUT_ENV]) ??
104
+ fromFile(agentDir) ??
105
+ DEFAULT_INSPECT_SHORTCUT;