@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,230 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { join } from "node:path";
3
+ import type { AgentDefinition } from "../domain/definitions.ts";
4
+ import { viewSession, type RunView, type SessionView } from "../domain/view.ts";
5
+ import {
6
+ answerRequest,
7
+ declineRequest,
8
+ pendingRequests,
9
+ requestState,
10
+ type RequestRecord,
11
+ } from "../domain/orchestration/requests.ts";
12
+ import { detachedPart, laneLine, runStatusLine } from "../presentation/wording.ts";
13
+ import { errorFields, fileLogSink, type LogSink } from "../runtime/log.ts";
14
+ import type { SessionHandle } from "../runtime/handle.ts";
15
+ import { Effect, Ref } from "effect";
16
+ import { noticeFor, type RefusedVerdict } from "./revocation.ts";
17
+
18
+ export interface CommandDeps {
19
+ readonly definitions: readonly AgentDefinition[];
20
+ /** The current handle; absent before a session opens or after it closes. */
21
+ readonly session?: Ref.Ref<SessionHandle | undefined>;
22
+ readonly log: () => LogSink;
23
+ /** The TUI toggle; every other mode prints the listing below. */
24
+ readonly inspector?: (ctx: ExtensionContext) => Promise<void>;
25
+ /** Present and non-undefined: the package refused coexistence; print this instead. */
26
+ readonly revoked?: () => RefusedVerdict | undefined;
27
+ /** Opens the store for reading; `undefined` when it does not exist. */
28
+ readonly reader?: (ctx: ExtensionContext) => Promise<SessionView | undefined>;
29
+ }
30
+
31
+ /** The direct form: `<run> <request> <answer…>`; fewer tokens open the picker instead. */
32
+ export const parseAnswerArgs = (
33
+ text: string,
34
+ ): { readonly run: string; readonly request: string; readonly answer: string } | undefined => {
35
+ const tokens = text
36
+ .trim()
37
+ .split(/\s+/)
38
+ .filter((token) => token.length > 0);
39
+ if (tokens.length < 3) return undefined;
40
+ const [run, request, ...rest] = tokens;
41
+ if (run === undefined || request === undefined) return undefined;
42
+ return { run, request, answer: rest.join(" ") };
43
+ };
44
+
45
+ const TYPE_SOMETHING = "Type something.";
46
+
47
+ const messageOf = (error: unknown): string =>
48
+ error instanceof Error ? error.message : String(error);
49
+
50
+ /** The answer a chosen request takes: a label, free text, or `undefined` for a cancelled dialog. */
51
+ const pickAnswer = async (
52
+ ctx: ExtensionContext,
53
+ record: RequestRecord,
54
+ ): Promise<string | undefined> => {
55
+ if (record.options.length === 0) {
56
+ return ctx.ui.input(`Answer request ${record.requestId}`, "Type the answer");
57
+ }
58
+ const labels = record.options.map((option) => option.label);
59
+ const chosen = await ctx.ui.select(`Answer request ${record.requestId}`, [
60
+ ...labels,
61
+ ...(record.allowOther ? [TYPE_SOMETHING] : []),
62
+ ]);
63
+ if (chosen === undefined) return undefined;
64
+ if (chosen !== TYPE_SOMETHING) return chosen;
65
+ return ctx.ui.input(`Answer request ${record.requestId}`, "Type the answer");
66
+ };
67
+
68
+ /** Both paths call the same write: an answer, or a decline when the dialog is cancelled. */
69
+ const answerFromCommand = async (
70
+ ctx: ExtensionContext,
71
+ deps: CommandDeps,
72
+ text: string,
73
+ ): Promise<void> => {
74
+ const runtime = deps.session === undefined ? undefined : Ref.getUnsafe(deps.session)?.runtime;
75
+ if (runtime === undefined) {
76
+ ctx.ui.notify("The delegation runtime is not ready.", "error");
77
+ return;
78
+ }
79
+ const sessionId = runtime.sessionId;
80
+ const parsed = parseAnswerArgs(text);
81
+ if (parsed !== undefined) {
82
+ try {
83
+ await answerRequest({ ...parsed, sessionId }, runtime);
84
+ ctx.ui.notify(`answer ${parsed.run}: answered`, "info");
85
+ } catch (error) {
86
+ deps.log().write("warn", "command.answer_failed", errorFields(error));
87
+ ctx.ui.notify(messageOf(error), "error");
88
+ }
89
+ return;
90
+ }
91
+ try {
92
+ const pending = await pendingRequests(runtime);
93
+ if (pending.length === 0) {
94
+ ctx.ui.notify("No delegation request is waiting.", "info");
95
+ return;
96
+ }
97
+ const labels = pending.map(
98
+ (record) => `${record.runId} · ${record.requestId} · ${record.prompt}`,
99
+ );
100
+ const chosen = await ctx.ui.select("Answer which delegation request?", labels);
101
+ if (chosen === undefined) return;
102
+ const record = pending[labels.indexOf(chosen)];
103
+ if (record === undefined) return;
104
+ const answer = await pickAnswer(ctx, record);
105
+ if (answer === undefined) {
106
+ await declineRequest({ run: record.runId, request: record.requestId, sessionId }, runtime);
107
+ ctx.ui.notify(`decline ${record.runId}: cancelled`, "info");
108
+ return;
109
+ }
110
+ await answerRequest(
111
+ { run: record.runId, request: record.requestId, answer, sessionId },
112
+ runtime,
113
+ );
114
+ ctx.ui.notify(`answer ${record.runId}: answered`, "info");
115
+ } catch (error) {
116
+ deps.log().write("warn", "command.answer_failed", errorFields(error));
117
+ ctx.ui.notify(messageOf(error), "error");
118
+ }
119
+ };
120
+
121
+ /** The live text for one run; the refused listing prints the same lines. */
122
+ const runLines = (runs: readonly RunView[]): string[] =>
123
+ runs.map(
124
+ (run) =>
125
+ `${run.runId} ${runStatusLine(run)}` +
126
+ (run.diagnostic === null ? "" : ` (${run.diagnostic})`) +
127
+ detachedPart(run.execution),
128
+ );
129
+
130
+ /** Pending requests as list lines, oldest first; a viewer derives expiry from the deadline. */
131
+ const requestLines = (requests: readonly RequestRecord[], now: number): string[] =>
132
+ requests
133
+ .filter((record) => requestState(record, now) === "pending")
134
+ .sort((left, right) => left.requestedAt - right.requestedAt)
135
+ .map((record) => `request ${record.requestId} pending for ${record.runId}`);
136
+
137
+ /** The refusal message, then the runs and requests committed before it; never throws. */
138
+ const printRefusedListing = async (
139
+ ctx: ExtensionContext,
140
+ deps: CommandDeps,
141
+ verdict: RefusedVerdict,
142
+ ): Promise<void> => {
143
+ const lines = [noticeFor(verdict)];
144
+ try {
145
+ const session = await deps.reader?.(ctx);
146
+ if (session !== undefined) {
147
+ if (session.runs.length > 0) lines.push("", ...runLines(session.runs));
148
+ lines.push(...requestLines(session.requests, Date.now()));
149
+ }
150
+ } catch (error) {
151
+ fileLogSink(join(ctx.sessionManager.getSessionDir(), "delegates.log")).write(
152
+ "warn",
153
+ "command.viewer_failed",
154
+ errorFields(error),
155
+ );
156
+ lines.push("The stored runs could not be read.");
157
+ }
158
+ ctx.ui.notify(lines.join("\n"), "error");
159
+ };
160
+
161
+ /** The catalogue, the session's runs, lanes, pending gates and requests, in one text block. */
162
+ export const printDelegatesListing = async (
163
+ ctx: ExtensionContext,
164
+ deps: CommandDeps,
165
+ ): Promise<void> => {
166
+ const refused = deps.revoked?.();
167
+ if (refused !== undefined) {
168
+ await printRefusedListing(ctx, deps, refused);
169
+ return;
170
+ }
171
+ const lines = deps.definitions.map(
172
+ (definition) =>
173
+ `${definition.name} — ${definition.role} — tools: ${definition.tools.join(", ")}` +
174
+ ` — skills: ${(definition.skills ?? []).join(", ") || "none"}` +
175
+ ` — gates: ${definition.approval.gates.map((gate) => gate.name).join(", ") || "none"}`,
176
+ );
177
+ const runtime = deps.session === undefined ? undefined : Ref.getUnsafe(deps.session)?.runtime;
178
+ if (runtime !== undefined) {
179
+ try {
180
+ const session = await viewSession(runtime);
181
+ if (session.runs.length > 0) lines.push("", ...runLines(session.runs));
182
+ for (const lane of session.lanes) lines.push(laneLine(lane));
183
+ for (const gate of session.gates) {
184
+ lines.push(`gate ${gate.gate} pending for ${gate.runId}`);
185
+ }
186
+ lines.push(...requestLines(session.requests, runtime.now()));
187
+ for (const diagnostic of Effect.runSync(runtime.skills.diagnostics)) {
188
+ lines.push(`${diagnostic.code}: ${diagnostic.detail}`);
189
+ }
190
+ } catch (error) {
191
+ deps.log().write("warn", "command.viewer_failed", errorFields(error));
192
+ // A viewer never fails the command; the registry is always printed.
193
+ }
194
+ }
195
+ ctx.ui.notify(lines.join("\n"), "info");
196
+ };
197
+
198
+ /**
199
+ * `/delegates` toggles the inspector in TUI and prints the listing in every
200
+ * other mode; `/delegates:list` prints the listing in every mode.
201
+ */
202
+ export const registerDelegatesCommand = (pi: ExtensionAPI, deps: CommandDeps): void => {
203
+ pi.registerCommand("delegates", {
204
+ description: "Toggle the live inspector, or print the run listing outside TUI",
205
+ handler: async (_args, ctx) => {
206
+ const refused = deps.revoked?.();
207
+ if (refused !== undefined) {
208
+ await printRefusedListing(ctx, deps, refused);
209
+ return;
210
+ }
211
+ if (ctx.mode === "tui" && deps.inspector !== undefined) {
212
+ await deps.inspector(ctx);
213
+ return;
214
+ }
215
+ await printDelegatesListing(ctx, deps);
216
+ },
217
+ });
218
+ pi.registerCommand("delegates:list", {
219
+ description: "List delegation agents, runs, lanes, pending gates and requests",
220
+ handler: async (_args, ctx) => {
221
+ await printDelegatesListing(ctx, deps);
222
+ },
223
+ });
224
+ pi.registerCommand("delegates:answer", {
225
+ description: "Answer a delegate's pending question, or open a picker",
226
+ handler: async (args, ctx) => {
227
+ await answerFromCommand(ctx, deps, args);
228
+ },
229
+ });
230
+ };