@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,360 @@
1
+ import type { Context } from "@earendil-works/chord/context";
2
+ import {
3
+ defineDoc,
4
+ defineDocFamily,
5
+ defineSignal,
6
+ type JsonObject,
7
+ type ToolExecutionApi,
8
+ type ToolExecutionResult,
9
+ type ToolPark,
10
+ type ToolRegistration,
11
+ type Tx,
12
+ } from "@earendil-works/pi-durable";
13
+ import { obj, oneOf, opt, str } from "@earendil-works/pi-schema";
14
+ import { Predicate, Schema } from "effect";
15
+ import type { SessionRuntime } from "../../runtime/session.ts";
16
+ import type { ViewPort } from "../view.ts";
17
+ import { ToolkitDoc, type ApprovalRule } from "../toolkit.ts";
18
+ import { taskId as toTaskId } from "../ids.ts";
19
+
20
+ export class GateNotFound extends Schema.TaggedError<
21
+ GateNotFound,
22
+ { readonly brand: unique symbol }
23
+ >()("GateNotFound", {
24
+ message: Schema.String,
25
+ }) {}
26
+ export class GateAlreadyDecided extends Schema.TaggedError<
27
+ GateAlreadyDecided,
28
+ { readonly brand: unique symbol }
29
+ >()("GateAlreadyDecided", { message: Schema.String }) {}
30
+
31
+ export const DAY_MS = 24 * 60 * 60 * 1000;
32
+
33
+ export const GateDecision = defineSignal({
34
+ name: "delegates.gate-decision",
35
+ version: 1,
36
+ schema: obj({
37
+ decision: oneOf(["approve", "deny"]),
38
+ note: opt(str()),
39
+ sessionId: str(),
40
+ }),
41
+ });
42
+
43
+ export const GateRecord = Schema.Struct({
44
+ runId: Schema.String,
45
+ gate: Schema.String,
46
+ status: Schema.Literals(["pending", "approved", "denied", "expired"]),
47
+ tool: Schema.NullOr(Schema.String),
48
+ /** The first parked task; kept for compatibility and status displays. */
49
+ taskId: Schema.NullOr(Schema.Finite),
50
+ /** Every task parked on this gate. */
51
+ taskIds: Schema.Array(Schema.Finite),
52
+ /** Every child run whose conversation reached this gate. */
53
+ childRunIds: Schema.Array(Schema.String),
54
+ requestedAt: Schema.Finite,
55
+ deadline: Schema.Finite,
56
+ decision: Schema.NullOr(Schema.String),
57
+ decidedBy: Schema.NullOr(Schema.Struct({ sessionId: Schema.String })),
58
+ reason: Schema.NullOr(Schema.String),
59
+ });
60
+ export type GateRecord = typeof GateRecord.Type;
61
+
62
+ export const GateDoc = defineDocFamily<
63
+ GateRecord & JsonObject,
64
+ { runId: string; gate: string } & JsonObject
65
+ >({
66
+ kind: "delegates.gate",
67
+ version: 1,
68
+ scope: "session",
69
+ family: true,
70
+ initial: (seed) => ({
71
+ runId: seed.runId,
72
+ gate: seed.gate,
73
+ status: "pending",
74
+ tool: null,
75
+ taskId: null,
76
+ taskIds: [],
77
+ childRunIds: [],
78
+ requestedAt: 0,
79
+ deadline: 0,
80
+ decision: null,
81
+ decidedBy: null,
82
+ reason: null,
83
+ }),
84
+ checkpointWhen: () => true,
85
+ });
86
+
87
+ /** Every gate key the session ever wrote; the only enumeration a viewer needs. */
88
+ export const GateIndexDoc = defineDoc<{ keys: string[] } & JsonObject>({
89
+ kind: "delegates.gate-index",
90
+ version: 1,
91
+ scope: "session",
92
+ initial: () => ({ keys: [] }),
93
+ checkpointWhen: () => true,
94
+ });
95
+
96
+ export const gateKey = (runId: string, gate: string): string => `${runId}:${gate}`;
97
+
98
+ /**
99
+ * The rule that gates this call, or `undefined`. `match` is a case-sensitive
100
+ * substring of the raw bash command; it applies to `bash` only.
101
+ */
102
+ export const matchRule = (
103
+ rules: readonly ApprovalRule[],
104
+ tool: string,
105
+ args: unknown,
106
+ ): ApprovalRule | undefined => {
107
+ const record = Predicate.isObject(args) ? args : {};
108
+ const command = typeof record.command === "string" ? record.command : undefined;
109
+ return rules.find((rule) => {
110
+ if (!rule.tools.includes(tool)) return false;
111
+ if (rule.match === undefined) return true;
112
+ return tool === "bash" && command !== undefined && command.includes(rule.match);
113
+ });
114
+ };
115
+
116
+ /** The one blocking result: an `isError` whose text names the reason. */
117
+ export const blockedResult = (text: string): ToolExecutionResult => ({
118
+ output: [{ type: "text", text }],
119
+ isError: true,
120
+ });
121
+
122
+ export interface GateRequest {
123
+ readonly key: string;
124
+ readonly runId: string;
125
+ readonly gate: string;
126
+ /** The tool that asked, for the status display. */
127
+ readonly tool: string;
128
+ readonly until: number;
129
+ /** The child run whose conversation reached the gate, when a gated tool is the caller. */
130
+ readonly childRunId?: string;
131
+ }
132
+
133
+ /** One commit writes the pending gate, its parked task and its index key. */
134
+ export const requestGate = async (
135
+ api: ToolExecutionApi,
136
+ request: GateRequest,
137
+ context: Context,
138
+ ): Promise<void> => {
139
+ await api.commit(async (tx) => {
140
+ const doc = await tx.doc(GateDoc, request.key, {
141
+ runId: request.runId,
142
+ gate: request.gate,
143
+ });
144
+ if (doc.status !== "pending") return;
145
+ const taskId = api.taskId;
146
+ if (doc.taskId === null) {
147
+ doc.tool = request.tool;
148
+ doc.taskId = taskId;
149
+ doc.requestedAt = api.now();
150
+ doc.deadline = request.until;
151
+ }
152
+ const taskIds = doc.taskIds ?? [];
153
+ if (!taskIds.includes(taskId)) taskIds.push(taskId);
154
+ doc.taskIds = taskIds;
155
+ const childRunId = request.childRunId ?? "";
156
+ const childRunIds = doc.childRunIds ?? [];
157
+ if (childRunId.length > 0 && !childRunIds.includes(childRunId)) {
158
+ childRunIds.push(childRunId);
159
+ }
160
+ doc.childRunIds = childRunIds;
161
+ const index = await tx.doc(GateIndexDoc);
162
+ if (!index.keys.includes(request.key)) index.keys.push(request.key);
163
+ }, context);
164
+ };
165
+
166
+ /** The decision a decided record carries; a missing or pending record reads as expired. */
167
+ export const decisionOf = (
168
+ record: Pick<GateRecord, "status"> | undefined,
169
+ ): "approved" | "denied" | "expired" => {
170
+ if (record?.status === "approved") return "approved";
171
+ if (record?.status === "denied") return "denied";
172
+ return "expired";
173
+ };
174
+
175
+ /**
176
+ * A same-name override: it commits `GateDoc`, then parks on `GateDecision`.
177
+ * Only a tool can commit and park; a wrapper and a hook each have one power.
178
+ */
179
+ export const gatedTool = (base: ToolRegistration): ToolRegistration => ({
180
+ ...base,
181
+ execute: async (
182
+ args: JsonObject,
183
+ api: ToolExecutionApi,
184
+ context: Context,
185
+ ): Promise<ToolExecutionResult | ToolPark> => {
186
+ const toolkit = await api.snapshot(ToolkitDoc, api.conversationId, context);
187
+ if (toolkit === undefined) return base.execute(args, api, context);
188
+ const rule = matchRule(toolkit.approval.gates ?? [], base.name, args);
189
+ if (rule === undefined) return base.execute(args, api, context);
190
+
191
+ const key = gateKey(toolkit.runId, rule.name);
192
+ const record = await api.snapshot(GateDoc, key, context);
193
+ if (record?.status === "approved") return base.execute(args, api, context);
194
+ if (record?.status === "denied") {
195
+ return blockedResult(`Gate ${rule.name} was denied; ${base.name} did not run.`);
196
+ }
197
+ if (record?.status === "expired") {
198
+ return blockedResult(`Gate ${rule.name} expired; ${base.name} did not run.`);
199
+ }
200
+
201
+ const until = await api.memo(`gate.deadline.${key}`, api.now() + DAY_MS, context);
202
+ if (record !== undefined && record.status === "pending" && api.now() >= until) {
203
+ await api.commit(async (tx) => {
204
+ const doc = await tx.doc(GateDoc, key, { runId: toolkit.runId, gate: rule.name });
205
+ doc.status = "expired";
206
+ doc.reason = "deadline";
207
+ }, context);
208
+ return blockedResult(`Gate ${rule.name} expired; ${base.name} did not run.`);
209
+ }
210
+
211
+ await requestGate(
212
+ api,
213
+ {
214
+ key,
215
+ runId: toolkit.runId,
216
+ gate: rule.name,
217
+ tool: base.name,
218
+ until,
219
+ childRunId: toolkit.childRunId,
220
+ },
221
+ context,
222
+ );
223
+
224
+ return {
225
+ sleep: { checkpoint: { args }, signals: [GateDecision.key(key)], until },
226
+ };
227
+ },
228
+ });
229
+
230
+ export interface GateDecisionInput {
231
+ readonly decision: "approve" | "deny";
232
+ readonly note?: string;
233
+ readonly sessionId: string;
234
+ }
235
+
236
+ export interface GateDecisionOutcome {
237
+ readonly record: GateRecord;
238
+ readonly deliveredTaskIds: readonly number[];
239
+ readonly endedTaskIds: readonly number[];
240
+ }
241
+
242
+ /** One commit writes the decision; the delivery wakes the parked call. */
243
+ export const decideGate = async (
244
+ request: {
245
+ readonly run: string;
246
+ readonly gate: string;
247
+ readonly decision: "approve" | "deny";
248
+ readonly note?: string;
249
+ },
250
+ runtime: SessionRuntime,
251
+ ): Promise<GateDecisionOutcome> => {
252
+ const key = gateKey(request.run, request.gate);
253
+ const current = await runtime.snapshot(GateDoc, key);
254
+ if (current === undefined) {
255
+ throw GateNotFound.make({
256
+ message: `Gate ${request.gate} of run ${request.run} not found.`,
257
+ });
258
+ }
259
+ if (current.status === "pending" && current.deadline > 0 && runtime.now() >= current.deadline) {
260
+ await runtime.run((context) =>
261
+ runtime.harness.commit(async (tx) => {
262
+ const doc = await tx.doc(GateDoc, key, { runId: request.run, gate: request.gate });
263
+ if (doc.status === "pending") {
264
+ doc.status = "expired";
265
+ doc.reason = "deadline";
266
+ }
267
+ return doc;
268
+ }, context),
269
+ );
270
+ throw GateAlreadyDecided.make({
271
+ message: `Gate ${request.gate} of run ${request.run} expired before a decision.`,
272
+ });
273
+ }
274
+
275
+ const committed = await runtime.run((context) =>
276
+ runtime.harness.commit(async (tx: Tx) => {
277
+ const doc = await tx.doc(GateDoc, key, { runId: request.run, gate: request.gate });
278
+ const won = doc.status === "pending";
279
+ if (won) {
280
+ doc.status = request.decision === "approve" ? "approved" : "denied";
281
+ doc.decision = request.decision;
282
+ doc.decidedBy = { sessionId: runtime.sessionId };
283
+ doc.reason = request.note ?? null;
284
+ }
285
+ const record: GateRecord = {
286
+ runId: doc.runId,
287
+ gate: doc.gate,
288
+ status: doc.status,
289
+ tool: doc.tool,
290
+ taskId: doc.taskId,
291
+ taskIds: [...doc.taskIds],
292
+ childRunIds: [...doc.childRunIds],
293
+ requestedAt: doc.requestedAt,
294
+ deadline: doc.deadline,
295
+ decision: doc.decision,
296
+ decidedBy: doc.decidedBy === null ? null : { sessionId: doc.decidedBy.sessionId },
297
+ reason: doc.reason,
298
+ };
299
+ return { won, status: doc.status, record };
300
+ }, context),
301
+ );
302
+
303
+ if (!committed.won) {
304
+ throw GateAlreadyDecided.make({
305
+ message: `Gate ${request.gate} of run ${request.run} is already ${committed.status}.`,
306
+ });
307
+ }
308
+
309
+ const record = committed.record;
310
+ const taskIds = [
311
+ ...new Set([...(record.taskIds ?? []), ...(record.taskId === null ? [] : [record.taskId])]),
312
+ ];
313
+ const deliveredTaskIds: number[] = [];
314
+ const endedTaskIds: number[] = [];
315
+ for (const taskId of taskIds) {
316
+ const delivery = await runtime.run((context) =>
317
+ runtime.harness.signal(
318
+ toTaskId(taskId),
319
+ GateDecision,
320
+ key,
321
+ {
322
+ decision: request.decision,
323
+ ...(request.note === undefined ? {} : { note: request.note }),
324
+ sessionId: runtime.sessionId,
325
+ },
326
+ context,
327
+ ),
328
+ );
329
+ if (delivery === "closed" || delivery === "not_found") endedTaskIds.push(taskId);
330
+ else deliveredTaskIds.push(taskId);
331
+ }
332
+ return { record, deliveredTaskIds, endedTaskIds };
333
+ };
334
+
335
+ /** The document reads a gate listing needs; live and read-only runtimes both satisfy it. */
336
+ type SnapshotPort = Pick<ViewPort, "snapshot">;
337
+
338
+ /** Every gate record of one run, or of the whole session. */
339
+ export const gateRecords = async (
340
+ runtime: SnapshotPort,
341
+ runId?: string,
342
+ ): Promise<readonly GateRecord[]> => {
343
+ const index = await runtime.snapshot(GateIndexDoc);
344
+ const prefix = runId === undefined ? undefined : `${runId}:`;
345
+ const keys = (index?.keys ?? []).filter((key) => prefix === undefined || key.startsWith(prefix));
346
+ const gates: GateRecord[] = [];
347
+ for (const key of keys) {
348
+ const record = await runtime.snapshot(GateDoc, key);
349
+ if (record === undefined) continue;
350
+ gates.push(record);
351
+ }
352
+ return gates;
353
+ };
354
+
355
+ /** Pending gates of one run, or of the whole session. */
356
+ export const pendingGates = async (
357
+ runtime: SnapshotPort,
358
+ runId?: string,
359
+ ): Promise<readonly GateRecord[]> =>
360
+ (await gateRecords(runtime, runId)).filter((record) => record.status === "pending");