@trevonistrevon/pi-loop 0.4.11 → 0.5.1

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 (87) hide show
  1. package/README.md +20 -9
  2. package/dist/commands/loop-command.d.ts +22 -0
  3. package/dist/commands/loop-command.js +148 -0
  4. package/dist/commands/tasks-command.d.ts +15 -0
  5. package/dist/commands/tasks-command.js +117 -0
  6. package/dist/coordinator.d.ts +35 -0
  7. package/dist/coordinator.js +56 -0
  8. package/dist/goal-coordinator.d.ts +22 -0
  9. package/dist/goal-coordinator.js +28 -0
  10. package/dist/goal-reducer.d.ts +89 -0
  11. package/dist/goal-reducer.js +181 -0
  12. package/dist/goal-store.d.ts +31 -0
  13. package/dist/goal-store.js +298 -0
  14. package/dist/goal-types.d.ts +82 -0
  15. package/dist/goal-types.js +1 -0
  16. package/dist/goal-verifier.d.ts +20 -0
  17. package/dist/goal-verifier.js +198 -0
  18. package/dist/index.js +130 -1087
  19. package/dist/loop-reducer.d.ts +63 -0
  20. package/dist/loop-reducer.js +67 -0
  21. package/dist/monitor-completion-coordinator.d.ts +10 -0
  22. package/dist/monitor-completion-coordinator.js +13 -0
  23. package/dist/monitor-manager.d.ts +2 -0
  24. package/dist/monitor-manager.js +107 -29
  25. package/dist/monitor-reducer.d.ts +82 -0
  26. package/dist/monitor-reducer.js +69 -0
  27. package/dist/notification-reducer.d.ts +81 -0
  28. package/dist/notification-reducer.js +65 -0
  29. package/dist/runtime/monitor-ondone-runtime.d.ts +13 -0
  30. package/dist/runtime/monitor-ondone-runtime.js +49 -0
  31. package/dist/runtime/notification-runtime.d.ts +34 -0
  32. package/dist/runtime/notification-runtime.js +152 -0
  33. package/dist/runtime/scope.d.ts +8 -0
  34. package/dist/runtime/scope.js +33 -0
  35. package/dist/runtime/session-runtime.d.ts +39 -0
  36. package/dist/runtime/session-runtime.js +110 -0
  37. package/dist/runtime/task-backlog-runtime.d.ts +36 -0
  38. package/dist/runtime/task-backlog-runtime.js +105 -0
  39. package/dist/runtime/task-rpc.d.ts +19 -0
  40. package/dist/runtime/task-rpc.js +118 -0
  41. package/dist/store.d.ts +7 -4
  42. package/dist/store.js +129 -49
  43. package/dist/task-backlog-coordinator.d.ts +12 -0
  44. package/dist/task-backlog-coordinator.js +22 -0
  45. package/dist/task-reducer.d.ts +66 -0
  46. package/dist/task-reducer.js +76 -0
  47. package/dist/task-store.d.ts +8 -4
  48. package/dist/task-store.js +102 -33
  49. package/dist/tools/loop-tools.d.ts +41 -0
  50. package/dist/tools/loop-tools.js +241 -0
  51. package/dist/tools/monitor-tools.d.ts +25 -0
  52. package/dist/tools/monitor-tools.js +110 -0
  53. package/dist/tools/native-task-tools.d.ts +15 -0
  54. package/dist/tools/native-task-tools.js +127 -0
  55. package/docs/architecture/goal-state-schema.md +505 -0
  56. package/docs/architecture/state-machine-migration.md +546 -0
  57. package/docs/architecture/state-machine-reducer-event-model.md +823 -0
  58. package/docs/architecture/state-machine-test-matrix.md +249 -0
  59. package/docs/architecture/state-machine-transition-map.md +436 -0
  60. package/package.json +1 -1
  61. package/src/commands/loop-command.ts +184 -0
  62. package/src/commands/tasks-command.ts +135 -0
  63. package/src/coordinator.ts +115 -0
  64. package/src/goal-coordinator.ts +58 -0
  65. package/src/goal-reducer.ts +280 -0
  66. package/src/goal-store.ts +315 -0
  67. package/src/goal-types.ts +104 -0
  68. package/src/goal-verifier.ts +241 -0
  69. package/src/index.ts +134 -1147
  70. package/src/loop-reducer.ts +148 -0
  71. package/src/monitor-completion-coordinator.ts +24 -0
  72. package/src/monitor-manager.ts +115 -27
  73. package/src/monitor-reducer.ts +166 -0
  74. package/src/notification-reducer.ts +155 -0
  75. package/src/runtime/monitor-ondone-runtime.ts +75 -0
  76. package/src/runtime/notification-runtime.ts +212 -0
  77. package/src/runtime/scope.ts +37 -0
  78. package/src/runtime/session-runtime.ts +168 -0
  79. package/src/runtime/task-backlog-runtime.ts +163 -0
  80. package/src/runtime/task-rpc.ts +150 -0
  81. package/src/store.ts +132 -50
  82. package/src/task-backlog-coordinator.ts +32 -0
  83. package/src/task-reducer.ts +152 -0
  84. package/src/task-store.ts +103 -31
  85. package/src/tools/loop-tools.ts +304 -0
  86. package/src/tools/monitor-tools.ts +145 -0
  87. package/src/tools/native-task-tools.ts +144 -0
package/dist/index.js CHANGED
@@ -13,14 +13,21 @@
13
13
  * /loop — Schedule a re-wake loop: /loop [interval] [prompt]
14
14
  * /loops — Interactive menu: view, create, cancel, settings
15
15
  */
16
- import { randomUUID } from "node:crypto";
17
- import { join, resolve } from "node:path";
18
- import { Type } from "typebox";
19
- import { parseInterval } from "./loop-parse.js";
16
+ import { registerLoopCommand } from "./commands/loop-command.js";
17
+ import { registerTasksCommand } from "./commands/tasks-command.js";
20
18
  import { MonitorManager } from "./monitor-manager.js";
19
+ import { createMonitorOnDoneRuntime } from "./runtime/monitor-ondone-runtime.js";
20
+ import { createNotificationRuntime, } from "./runtime/notification-runtime.js";
21
+ import { resolveLoopStorePath, resolveTaskStorePath } from "./runtime/scope.js";
22
+ import { registerSessionRuntimeHooks } from "./runtime/session-runtime.js";
23
+ import { createTaskBacklogRuntime } from "./runtime/task-backlog-runtime.js";
24
+ import { createTaskRuntimeBridge } from "./runtime/task-rpc.js";
21
25
  import { CronScheduler } from "./scheduler.js";
22
26
  import { LoopStore } from "./store.js";
23
27
  import { TaskStore } from "./task-store.js";
28
+ import { registerLoopTools } from "./tools/loop-tools.js";
29
+ import { registerMonitorTools } from "./tools/monitor-tools.js";
30
+ import { registerNativeTaskTools } from "./tools/native-task-tools.js";
24
31
  import { TriggerSystem } from "./trigger-system.js";
25
32
  import { LoopWidget } from "./ui/widget.js";
26
33
  const DEBUG = !!process.env.PI_LOOP_DEBUG;
@@ -28,42 +35,12 @@ function debug(...args) {
28
35
  if (DEBUG)
29
36
  console.error("[pi-loop]", ...args);
30
37
  }
31
- function textResult(msg) {
32
- return { content: [{ type: "text", text: msg }], details: undefined };
33
- }
34
38
  export default function (pi) {
35
39
  const piLoopEnv = process.env.PI_LOOP;
36
40
  const piLoopScope = process.env.PI_LOOP_SCOPE;
37
41
  let loopScope = piLoopScope ?? "session";
38
- function resolveStorePath(sessionId) {
39
- if (piLoopEnv === "off")
40
- return undefined;
41
- if (piLoopEnv?.startsWith("/"))
42
- return piLoopEnv;
43
- if (piLoopEnv?.startsWith("."))
44
- return resolve(piLoopEnv);
45
- if (piLoopEnv)
46
- return piLoopEnv;
47
- if (loopScope === "memory")
48
- return undefined;
49
- if (loopScope === "session" && sessionId) {
50
- return join(process.cwd(), ".pi", "loops", `loops-${sessionId}.json`);
51
- }
52
- if (loopScope === "session")
53
- return undefined;
54
- return join(process.cwd(), ".pi", "loops", "loops.json");
55
- }
56
- function resolveTaskStorePath(sessionId) {
57
- if (loopScope === "memory")
58
- return undefined;
59
- if (loopScope === "session" && sessionId) {
60
- return join(process.cwd(), ".pi", "tasks", `tasks-${sessionId}.json`);
61
- }
62
- if (loopScope === "session")
63
- return undefined;
64
- return join(process.cwd(), ".pi", "tasks", "tasks.json");
65
- }
66
- let store = new LoopStore(resolveStorePath());
42
+ const getScopeOptions = () => ({ piLoopEnv, loopScope });
43
+ let store = new LoopStore(resolveLoopStorePath(getScopeOptions()));
67
44
  const monitorManager = new MonitorManager(pi);
68
45
  let scheduler;
69
46
  let triggerSystem;
@@ -87,134 +64,44 @@ export default function (pi) {
87
64
  let tasksAvailable = false;
88
65
  let nativeTaskStore;
89
66
  let nativeTasksRegistered = false;
90
- function checkTasksVersion() {
91
- const requestId = randomUUID();
92
- const timer = setTimeout(() => { unsub(); }, 5000);
93
- const unsub = pi.events.on(`tasks:rpc:ping:reply:${requestId}`, (raw) => {
94
- unsub();
95
- clearTimeout(timer);
96
- const remoteVersion = raw?.data?.version;
97
- if (remoteVersion !== undefined)
67
+ const taskRuntime = createTaskRuntimeBridge({
68
+ pi,
69
+ isTasksAvailable: () => tasksAvailable,
70
+ setTasksAvailable: (available) => {
71
+ if (available)
98
72
  tasksAvailable = true;
99
- });
100
- pi.events.emit("tasks:rpc:ping", { requestId });
101
- }
102
- checkTasksVersion();
103
- pi.events.on("tasks:ready", () => checkTasksVersion());
104
- async function autoCreateTask(entry) {
105
- if (!entry.autoTask)
106
- return undefined;
107
- if (tasksAvailable) {
108
- try {
109
- const requestId = randomUUID();
110
- const taskId = await new Promise((resolve, _reject) => {
111
- const timer = setTimeout(() => { unsub(); resolve(undefined); }, 5000);
112
- const unsub = pi.events.on(`tasks:rpc:create:reply:${requestId}`, (raw) => {
113
- unsub();
114
- clearTimeout(timer);
115
- const reply = raw;
116
- if (reply.success && reply.data)
117
- resolve(reply.data.id);
118
- else
119
- resolve(undefined);
120
- });
121
- pi.events.emit("tasks:rpc:create", {
122
- requestId,
123
- subject: entry.prompt.slice(0, 80),
124
- description: `Auto-created from loop #${entry.id}`,
125
- metadata: { loopId: entry.id, trigger: entry.trigger },
126
- });
127
- });
128
- return taskId;
129
- }
130
- catch {
131
- return undefined;
132
- }
133
- }
134
- if (!nativeTaskStore)
135
- return undefined;
136
- const task = nativeTaskStore.create(entry.prompt.slice(0, 80), `Auto-created from loop #${entry.id}`, {
137
- loopId: entry.id,
138
- trigger: entry.trigger,
139
- });
140
- widget.update();
141
- return task.id;
142
- }
143
- async function hasPendingTasks() {
144
- if (tasksAvailable) {
145
- try {
146
- const requestId = randomUUID();
147
- const count = await new Promise((resolve) => {
148
- const timer = setTimeout(() => { unsub(); resolve(-1); }, 3000);
149
- const unsub = pi.events.on(`tasks:rpc:pending:reply:${requestId}`, (raw) => {
150
- unsub();
151
- clearTimeout(timer);
152
- const reply = raw;
153
- resolve(reply.success && reply.data ? reply.data.pending : -1);
154
- });
155
- pi.events.emit("tasks:rpc:pending", { requestId });
156
- });
157
- return count;
158
- }
159
- catch {
160
- return -1;
161
- }
162
- }
163
- return nativeTaskStore ? nativeTaskStore.pendingCount() : -1;
164
- }
165
- async function cleanDoneTasks() {
166
- if (tasksAvailable) {
167
- try {
168
- const requestId = randomUUID();
169
- await new Promise((resolve) => {
170
- const timer = setTimeout(() => { unsub(); resolve(); }, 3000);
171
- const unsub = pi.events.on(`tasks:rpc:clean:reply:${requestId}`, () => {
172
- unsub();
173
- clearTimeout(timer);
174
- debug("tasks:rpc:clean — done tasks swept");
175
- resolve();
176
- });
177
- pi.events.emit("tasks:rpc:clean", { requestId });
178
- });
179
- }
180
- catch { /* timeout or error, ignore */ }
181
- return;
182
- }
183
- if (nativeTaskStore) {
184
- nativeTaskStore.sweepCompleted();
73
+ },
74
+ getNativeTaskStore: () => nativeTaskStore,
75
+ onNativeTaskCreated: () => {
185
76
  widget.update();
186
- await cleanupTaskBacklogLoops();
187
- }
188
- }
189
- let agentRunning = false;
190
- const pendingNotifications = new Map();
191
- let flushPromise;
192
- function buildLoopFireMessage(data) {
193
- const triggerInfo = typeof data.trigger === "string"
194
- ? data.trigger
195
- : data.trigger?.type === "cron"
196
- ? `schedule: ${data.trigger.schedule}`
197
- : data.trigger?.type === "event"
198
- ? `event: ${data.trigger.source}`
199
- : "hybrid";
200
- const loopId = data.loopId || "?";
201
- const prompt = data.prompt || "loop fired";
202
- const constraint = data.readOnly
203
- ? "\n\nREAD-ONLY MODE — use only read tools (Read, TaskList, LoopList, MonitorList, etc.). No file writes, shell execution, or destructive changes."
204
- : "";
205
- return [
206
- `[pi-loop] Loop #${loopId} fired (${triggerInfo}).${constraint}`,
207
- prompt,
208
- ].join("\n");
209
- }
210
- function buildPendingNotification(data) {
211
- const key = data.recurring ? `loop:${data.loopId}` : `loop:${data.loopId}:${data.timestamp}`;
212
- return {
213
- ...data,
214
- key,
215
- message: buildLoopFireMessage(data),
216
- };
217
- }
77
+ },
78
+ onNativeTasksPruned: async (taskStore) => {
79
+ widget.update();
80
+ await evaluateTaskBacklog(taskStore, taskStore.pendingCount());
81
+ },
82
+ debug,
83
+ });
84
+ taskRuntime.checkTasksVersion();
85
+ pi.events.on("tasks:ready", () => taskRuntime.checkTasksVersion());
86
+ const autoCreateTask = taskRuntime.autoCreateTask;
87
+ const hasPendingTasks = taskRuntime.hasPendingTasks;
88
+ const cleanDoneTasks = taskRuntime.cleanDoneTasks;
89
+ const notificationRuntime = createNotificationRuntime({
90
+ pi,
91
+ hasPendingTasks: () => hasPendingTasks(),
92
+ cleanDoneTasks: () => cleanDoneTasks(),
93
+ getHasPendingMessages: () => _latestCtx?.hasPendingMessages() ?? false,
94
+ debug,
95
+ });
96
+ const monitorOnDoneRuntime = createMonitorOnDoneRuntime({
97
+ monitorManager,
98
+ getLoop: (id) => store.get(id),
99
+ deleteLoop: (id) => {
100
+ store.delete(id);
101
+ },
102
+ onLoopFire,
103
+ debug,
104
+ });
218
105
  function triggerHasEventSource(trigger, source) {
219
106
  if (typeof trigger === "string")
220
107
  return false;
@@ -244,60 +131,30 @@ export default function (pi) {
244
131
  });
245
132
  return true;
246
133
  }
247
- async function deliverNotification(notification) {
248
- if (notification.autoTask) {
249
- const pending = await hasPendingTasks();
250
- if (pending === 0) {
251
- debug(`loop:fire #${notification.loopId} — no pending tasks at delivery time, dropping wake`);
252
- await cleanDoneTasks();
253
- return false;
254
- }
255
- }
256
- agentRunning = true;
257
- pi.sendMessage({
258
- customType: "pi-loop",
259
- content: notification.message,
260
- display: false,
261
- details: {
262
- loopId: notification.loopId,
263
- trigger: notification.trigger,
264
- recurring: notification.recurring,
265
- readOnly: notification.readOnly,
266
- autoTask: notification.autoTask,
267
- timestamp: notification.timestamp,
268
- },
269
- }, {
270
- deliverAs: "steer",
271
- triggerTurn: true,
272
- });
273
- return true;
274
- }
275
- async function flushPendingNotifications(options) {
276
- if (flushPromise)
277
- return flushPromise;
278
- flushPromise = (async () => {
279
- if (agentRunning)
280
- return;
281
- if (!options?.ignorePendingMessages && _latestCtx?.hasPendingMessages())
282
- return;
283
- const entries = [...pendingNotifications.entries()]
284
- .sort(([, left], [, right]) => left.timestamp - right.timestamp);
285
- for (const [key, notification] of entries) {
286
- pendingNotifications.delete(key);
287
- const delivered = await deliverNotification(notification);
288
- if (delivered)
289
- return;
290
- }
291
- })().finally(() => {
292
- flushPromise = undefined;
293
- });
294
- return flushPromise;
295
- }
296
- async function queueOrDeliverNotification(data) {
297
- const notification = buildPendingNotification(data);
298
- pendingNotifications.set(notification.key, notification);
299
- await flushPendingNotifications();
300
- }
134
+ const taskBacklogRuntime = createTaskBacklogRuntime({
135
+ getLoops: () => store.list(),
136
+ createLoop: (trigger, prompt, options) => store.create(trigger, prompt, options),
137
+ deleteLoop: (id) => {
138
+ store.delete(id);
139
+ },
140
+ addTrigger: (entry) => {
141
+ triggerSystem.add(entry);
142
+ },
143
+ removeTrigger: (id) => {
144
+ triggerSystem.remove(id);
145
+ },
146
+ updateWidget: () => {
147
+ widget.update();
148
+ },
149
+ hasPendingTasks: () => hasPendingTasks(),
150
+ bootstrapTaskLoop: (entry) => maybeBootstrapTaskLoop(entry),
151
+ triggerHasEventSource,
152
+ debug,
153
+ });
154
+ const flushPendingNotifications = notificationRuntime.flushPendingNotifications;
155
+ const queueOrDeliverNotification = notificationRuntime.queueOrDeliverNotification;
156
+ const cleanupTaskBacklogLoops = taskBacklogRuntime.cleanupTaskBacklogLoops;
157
+ const evaluateTaskBacklog = taskBacklogRuntime.evaluateTaskBacklog;
301
158
  // ── Loop fire handler ──
302
159
  function onLoopFire(entry) {
303
160
  debug(`loop:fire #${entry.id}`, { prompt: entry.prompt.slice(0, 50) });
@@ -306,7 +163,7 @@ export default function (pi) {
306
163
  store.delete(entry.id);
307
164
  return;
308
165
  }
309
- store.update(entry.id, { fireCount: (entry.fireCount ?? 0) + 1 });
166
+ store.fire(entry.id);
310
167
  if (entry.autoTask) {
311
168
  autoCreateTask(entry).then((taskId) => {
312
169
  if (taskId)
@@ -324,116 +181,38 @@ export default function (pi) {
324
181
  });
325
182
  }
326
183
  // ── Session lifecycle ──
327
- let storeUpgraded = false;
328
- let persistedShown = false;
329
184
  let _latestCtx;
330
185
  let _sessionId;
331
- function upgradeStoreIfNeeded(ctx) {
332
- if (storeUpgraded)
333
- return;
334
- if (loopScope === "session" && !piLoopEnv) {
335
- const sessionId = ctx.sessionManager.getSessionId();
336
- const path = resolveStorePath(sessionId);
186
+ registerSessionRuntimeHooks({
187
+ pi,
188
+ getLoopScope: () => loopScope,
189
+ getPiLoopEnv: () => piLoopEnv,
190
+ recreateSessionStore: (sessionId) => {
191
+ const path = resolveLoopStorePath(getScopeOptions(), sessionId);
337
192
  store = new LoopStore(path);
338
193
  widget.setStore(store);
339
194
  scheduler = new CronScheduler(store, onLoopFire);
340
195
  triggerSystem = new TriggerSystem(pi, scheduler, store, onLoopFire);
341
- }
342
- storeUpgraded = true;
343
- }
344
- function showPersistedLoops(_isResume = false) {
345
- if (persistedShown)
346
- return;
347
- persistedShown = true;
348
- const sessionStartedAt = Date.now();
349
- const loops = store.list();
350
- if (loops.length > 0) {
351
- store.clearExpired();
352
- store.expireEventLoops(sessionStartedAt);
353
- triggerSystem.start();
354
- widget.update();
355
- }
356
- }
357
- pi.on("turn_start", async (_event, ctx) => {
358
- _latestCtx = ctx;
359
- _sessionId = ctx.sessionManager.getSessionId();
360
- widget.setUICtx(ctx.ui);
361
- upgradeStoreIfNeeded(ctx);
362
- widget.update();
363
- await pumpLoops();
364
- });
365
- pi.on("before_agent_start", async (_event, ctx) => {
366
- _latestCtx = ctx;
367
- widget.setUICtx(ctx.ui);
368
- upgradeStoreIfNeeded(ctx);
369
- showPersistedLoops();
370
- widget.update();
371
- });
372
- pi.on("agent_start", async (_event, ctx) => {
373
- agentRunning = true;
374
- _latestCtx = ctx;
375
- widget.setUICtx(ctx.ui);
376
- });
377
- pi.on("agent_end", async (_event, ctx) => {
378
- agentRunning = false;
379
- _latestCtx = ctx;
380
- widget.setUICtx(ctx.ui);
381
- await flushPendingNotifications({ ignorePendingMessages: true });
382
- await cleanupTaskBacklogLoops();
383
- await pumpLoops();
384
- });
385
- pi.on("session_shutdown", async () => {
386
- agentRunning = false;
387
- pendingNotifications.clear();
388
- });
389
- pi.on("session_switch", async (event, ctx) => {
390
- _latestCtx = ctx;
391
- widget.setUICtx(ctx.ui);
392
- triggerSystem.stop();
393
- agentRunning = false;
394
- pendingNotifications.clear();
395
- _sessionId = undefined;
396
- const isResume = event?.reason === "resume";
397
- storeUpgraded = false;
398
- persistedShown = false;
399
- if (!isResume && loopScope === "memory") {
196
+ },
197
+ clearAllLoops: () => {
400
198
  store.clearAll();
401
- }
402
- upgradeStoreIfNeeded(ctx);
403
- showPersistedLoops(isResume);
404
- widget.update();
405
- });
406
- pi.on("tool_execution_end", async (event, ctx) => {
407
- _latestCtx = ctx;
408
- widget.setUICtx(ctx.ui);
409
- if (event?.toolName !== "bash" || event?.isError)
410
- return;
411
- const command = event?.args?.command ?? event?.input?.command;
412
- if (typeof command !== "string")
413
- return;
414
- if (!/^\s*git\s+commit\b/i.test(command))
415
- return;
416
- await cleanDoneTasks();
199
+ },
200
+ getStore: () => store,
201
+ getScheduler: () => scheduler,
202
+ getTriggerSystem: () => triggerSystem,
203
+ setLatestCtx: (ctx) => {
204
+ _latestCtx = ctx;
205
+ },
206
+ setSessionId: (sessionId) => {
207
+ _sessionId = sessionId;
208
+ },
209
+ widget,
210
+ notificationRuntime,
211
+ flushPendingNotifications,
212
+ cleanupTaskBacklogLoops,
213
+ hasPendingTasks,
214
+ cleanDoneTasks,
417
215
  });
418
- // ── Dynamic loop pump — fires cron/hybrid loops on idle instead of wall-clock timers ──
419
- async function pumpLoops() {
420
- const pendingTasks = new Map();
421
- for (const entry of store.list()) {
422
- if (entry.status !== "active")
423
- continue;
424
- if (!entry.autoTask)
425
- continue;
426
- if (entry.trigger.type !== "cron" && entry.trigger.type !== "hybrid")
427
- continue;
428
- const nextFire = scheduler.nextFire(entry.id);
429
- if (!nextFire || Date.now() < nextFire)
430
- continue;
431
- const pending = await hasPendingTasks();
432
- if (pending <= 0)
433
- pendingTasks.set(entry.id, true);
434
- }
435
- scheduler.pump(Date.now(), (entry) => !pendingTasks.has(entry.id));
436
- }
437
216
  // ── Loop fire handler — queues an in-memory notification, then injects a custom message when delivery is safe ──
438
217
  pi.events.on("loop:fire", async (event) => {
439
218
  const data = event;
@@ -447,795 +226,59 @@ export default function (pi) {
447
226
  }
448
227
  await queueOrDeliverNotification(data);
449
228
  });
450
- // ──────────────────────────────────────────────────
451
- // Tool 1: LoopCreate
452
- // ──────────────────────────────────────────────────
453
- pi.registerTool({
454
- name: "LoopCreate",
455
- label: "LoopCreate",
456
- description: `Create a scheduled repeating task (loop) that runs a prompt on a timer or when an event fires.
457
-
458
- Use this tool whenever the user asks to:
459
- - "create a loop" to check something periodically
460
- - "run every X seconds/minutes/hours"
461
- - "remind me to check..."
462
- - "watch for..." or "when X happens, do Y"
463
- - "schedule a recurring check"
464
- - set up a periodic monitor or poller
465
- - has a task list with open items — create a loop to work through tasks automatically
466
-
467
- DO NOT use raw Bash loops (for/sleep/while). Use LoopCreate instead — it integrates with the session lifecycle, survives across turns, and the scheduler handles timing.
468
-
469
- ## When NOT to Use
470
-
471
- Skip this tool when the task is a one-off check (just do it directly) or when the user wants a purely reactive hook.
472
-
473
- ## Trigger Types
474
-
475
- - **cron**: time-based. "30s" (rounded to 1m), "5m", "2h", "1d", or full cron like "0 9 * * 1-5"
476
- - **event**: fires on pi events like "tool_execution_start", "before_agent_start"
477
- - **hybrid**: both cron + event with debounce
478
-
479
- ## Parameters
480
-
481
- - **trigger**: interval like "30s", "5m", "2h", event source, or hybrid spec
482
- - **prompt**: what to do when the loop fires (e.g., "check if the build passed")
483
- - **recurring**: repeat or fire once (default: true)
484
- - **autoTask**: when pi-tasks is loaded or native task fallback is active, auto-create a task on each fire
485
- - **taskBacklog**: mark this as a task-backlog worker loop so it auto-deletes when pending tasks reach zero
486
- - **readOnly**: restrict the agent to read-only tools when this loop fires (default: false)
487
- - **maxFires**: auto-stop after N fires — prevents infinite token burn on polling loops`,
488
- promptGuidelines: [
489
- "Use LoopCreate when the user asks for a repeating task, periodic check, scheduled reminder, or 'every X' — never use raw Bash for/sleep/while.",
490
- "## Choosing trigger type",
491
- "Prefer event triggers over cron when possible — they fire exactly when needed instead of polling.",
492
- "Use event triggers for: tool completion ('tool_execution_end'), task creation ('tasks:created'), monitor completion ('monitor:done').",
493
- "Use cron triggers only when: the user explicitly asks for a time interval, or there's no relevant pi event to subscribe to.",
494
- "Hybrid triggers (cron + event) give you both: event-driven responsiveness with a cron safety-net fallback.",
495
- "## Choosing an interval",
496
- "Default to 5m unless the user specifies differently. Use shorter intervals only when time-sensitive.",
497
- "## maxFires — prevent infinite token burn",
498
- "Always set maxFires on polling loops so they don't run forever. For task-continuation loops, use maxFires: 20-50.",
499
- "When a loop fires and finds nothing to do, call LoopDelete on its own ID to stop it — don't keep polling.",
500
- "## readOnly mode",
501
- "Set readOnly: true for loops that only observe and report (checks, status polls). This prevents unintended changes.",
502
- "## Task-driven workflows",
503
- "Do not rely on a past 'tasks:created' event to replay. If tasks already exist, bootstrap the first pass in the current turn or use a hybrid/event loop that can catch future task creation and a cron safety-net.",
504
- "Use autoTask only when you want the loop itself to create a task on each fire. For processing an existing task backlog, leave autoTask off and have the loop run TaskList to pick the next pending task.",
505
- "Set taskBacklog: true for task-worker loops that process the existing pending queue. Task-backlog loops bootstrap against existing pending tasks and auto-delete when the queue reaches zero.",
506
- "When no tasks are pending, the loop should stop itself or skip the wake entirely — no tokens burned on empty polls.",
507
- "After creating a loop, tell the user the loop ID so they can cancel it with LoopDelete.",
508
- ],
509
- parameters: Type.Object({
510
- trigger: Type.String({ description: "Cron expression (e.g., '5m', '1h', '0 9 * * 1-5'), event source (e.g., 'tool_execution_start'), or JSON hybrid spec" }),
511
- prompt: Type.String({ description: "Prompt to run when the loop fires" }),
512
- recurring: Type.Optional(Type.Boolean({ description: "Whether loop repeats (default: true)", default: true })),
513
- autoTask: Type.Optional(Type.Boolean({ description: "Auto-create pi-tasks task on fire", default: false })),
514
- taskBacklog: Type.Optional(Type.Boolean({ description: "Mark as a task-backlog worker loop that auto-deletes when pending tasks reach zero", default: false })),
515
- triggerType: Type.Optional(Type.String({ description: "cron, event, or hybrid (inferred from trigger string if omitted)", enum: ["cron", "event", "hybrid"] })),
516
- debounceMs: Type.Optional(Type.Number({ description: "Debounce for hybrid triggers (default: 30000)", default: 30000 })),
517
- readOnly: Type.Optional(Type.Boolean({ description: "Restrict the agent to read-only tools when this loop fires (default: false)", default: false })),
518
- maxFires: Type.Optional(Type.Number({ description: "Auto-stop after N fires. Prevents infinite token burn on polling loops." })),
519
- }),
520
- async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
521
- const { trigger: triggerInput, prompt, recurring, autoTask, taskBacklog, triggerType, debounceMs, readOnly, maxFires } = params;
522
- let trigger;
523
- const inferred = triggerType ?? inferTriggerType(triggerInput);
524
- if (inferred === "cron") {
525
- const parsed = parseInterval(triggerInput);
526
- trigger = { type: "cron", schedule: parsed.cron };
527
- }
528
- else if (inferred === "event") {
529
- trigger = { type: "event", source: triggerInput };
530
- }
531
- else {
532
- const cronPart = triggerInput.match(/cron:?\s*(\S+)/)?.[1] || triggerInput;
533
- const eventPart = triggerInput.match(/event:?\s*(\S+)/)?.[1];
534
- const parsed = parseInterval(cronPart);
535
- trigger = {
536
- type: "hybrid",
537
- cron: parsed.cron,
538
- event: { source: eventPart || "tool_execution_start" },
539
- debounceMs: debounceMs ?? 30000,
540
- };
541
- }
542
- const validationError = validateTrigger(trigger);
543
- if (validationError)
544
- return Promise.resolve(textResult(validationError));
545
- const entry = store.create(trigger, prompt, {
546
- recurring: recurring ?? (inferred !== "event"),
547
- autoTask,
548
- taskBacklog,
549
- readOnly,
550
- maxFires,
551
- });
552
- triggerSystem.add(entry);
553
- if (trigger.type === "event" && trigger.source === "monitor:done" && trigger.filter) {
554
- try {
555
- const filterObj = JSON.parse(trigger.filter);
556
- const monitorId = filterObj.monitorId;
557
- if (monitorId) {
558
- const monitor = monitorManager.get(monitorId);
559
- if (monitor && monitor.status !== "running") {
560
- debug(`loop #${entry.id} — monitor #${monitorId} already ${monitor.status}, expiring`);
561
- triggerSystem.remove(entry.id);
562
- store.delete(entry.id);
563
- }
564
- }
565
- }
566
- catch { /* filter parse failure, ignore */ }
567
- }
568
- const bootstrapped = await maybeBootstrapTaskLoop(entry);
229
+ registerLoopTools({
230
+ pi,
231
+ getStore: () => store,
232
+ getTriggerSystem: () => triggerSystem,
233
+ getScheduler: () => scheduler,
234
+ getMonitorManager: () => monitorManager,
235
+ updateWidget: () => {
569
236
  widget.update();
570
- const triggerDesc = trigger.type === "cron"
571
- ? `schedule: ${trigger.schedule}`
572
- : trigger.type === "event"
573
- ? `event: ${trigger.source}`
574
- : `hybrid: cron ${trigger.cron} + event ${trigger.event.source}`;
575
- return Promise.resolve(textResult(`Loop #${entry.id} created: ${entry.prompt.slice(0, 60)}\n` +
576
- `Trigger: ${triggerDesc}\n` +
577
- `Recurring: ${entry.recurring}\n` +
578
- (entry.autoTask ? `Auto-task: enabled\n` : "") +
579
- (entry.taskBacklog ? `Task-backlog: enabled\n` : "") +
580
- (bootstrapped ? "Bootstrap: queued initial wake for existing pending tasks\n" : "") +
581
- ((tasksAvailable || nativeTasksRegistered) ? "" : "(task system not ready yet — autoTask may not fire until native fallback or pi-tasks becomes available)\n") +
582
- `ID: ${entry.id} (use LoopDelete to cancel)`));
583
237
  },
238
+ maybeBootstrapTaskLoop,
239
+ isTaskSystemReady: () => tasksAvailable || nativeTasksRegistered,
584
240
  });
585
241
  function handleMonitorDoneLoop(doneLoop, monitorId) {
586
- const deliver = () => {
587
- const current = store.get(doneLoop.id);
588
- if (!current)
589
- return;
590
- debug(`onDone loop #${doneLoop.id} — monitor #${monitorId} completed, delivering directly`);
591
- onLoopFire(current);
592
- store.delete(doneLoop.id);
593
- };
594
- const registered = monitorManager.onComplete(monitorId, deliver);
595
- if (registered)
596
- return;
597
- const monitor = monitorManager.get(monitorId);
598
- if (monitor && monitor.status !== "running") {
599
- if (monitor.status === "completed") {
600
- deliver();
601
- return;
602
- }
603
- debug(`onDone loop #${doneLoop.id} — monitor #${monitorId} already ${monitor.status}, expiring`);
604
- store.delete(doneLoop.id);
605
- }
606
- }
607
- function validateTrigger(trigger) {
608
- if (trigger.type === "cron") {
609
- const parts = trigger.schedule.trim().split(/\s+/);
610
- if (parts.length !== 5) {
611
- return `Invalid cron trigger. Expected 5 fields, got ${parts.length}: "${trigger.schedule}". Use formats like "5m", "1h", "0 9 * * 1-5", or set triggerType to "event" for event sources.`;
612
- }
613
- }
614
- else if (trigger.type === "event") {
615
- if (!trigger.source || trigger.source.trim().length === 0) {
616
- return `Invalid event trigger. Event source must be non-empty (e.g., "tool_execution_start").`;
617
- }
618
- }
619
- else if (trigger.type === "hybrid") {
620
- const cronParts = trigger.cron.trim().split(/\s+/);
621
- if (cronParts.length !== 5) {
622
- return `Invalid hybrid trigger. Cron part must have 5 fields, got ${cronParts.length}: "${trigger.cron}".`;
623
- }
624
- if (!trigger.event.source || trigger.event.source.trim().length === 0) {
625
- return `Invalid hybrid trigger. Event source must be non-empty (e.g., "tool_execution_start").`;
626
- }
627
- }
628
- return null;
629
- }
630
- function inferTriggerType(input) {
631
- if (input.includes("hybrid") || (input.includes("cron") && input.includes("event")))
632
- return "hybrid";
633
- if (/^\d+\s*[smhd]$/i.test(input.trim()))
634
- return "cron";
635
- if (/^(\*|\d+)/.test(input.trim()) && input.trim().split(/\s+/).length === 5)
636
- return "cron";
637
- return "event";
638
- }
639
- // ──────────────────────────────────────────────────
640
- // Tool 2: LoopList
641
- // ──────────────────────────────────────────────────
642
- pi.registerTool({
643
- name: "LoopList",
644
- label: "LoopList",
645
- description: `List all active scheduled loops with their IDs, triggers, and next-fire times.
646
-
647
- Use this before creating new loops to avoid duplicates, or to find IDs for LoopDelete.`,
648
- parameters: Type.Object({}),
649
- execute(_toolCallId, _params, _signal, _onUpdate, _ctx) {
650
- const loops = store.list();
651
- if (loops.length === 0)
652
- return Promise.resolve(textResult("No loops configured. Use LoopCreate to set up a schedule."));
653
- const lines = [];
654
- for (const entry of loops) {
655
- const triggerDesc = entry.trigger.type === "cron"
656
- ? `cron: ${entry.trigger.schedule}`
657
- : entry.trigger.type === "event"
658
- ? `event: ${entry.trigger.source}`
659
- : `hybrid: ${entry.trigger.cron} + ${entry.trigger.event.source}`;
660
- const nextFire = entry.trigger.type !== "event"
661
- ? scheduler.nextFire(entry.id)
662
- : undefined;
663
- const statusIcon = entry.status === "active" ? "*" : entry.status === "paused" ? "-" : "x";
664
- let line = `${statusIcon} #${entry.id} [${entry.status}] ${entry.prompt.slice(0, 60)}`;
665
- line += ` (${triggerDesc})`;
666
- if (nextFire) {
667
- const remaining = Math.max(0, nextFire - Date.now());
668
- line += ` next: ${formatRemaining(remaining)}`;
669
- }
670
- if (entry.autoTask)
671
- line += " [auto-task]";
672
- lines.push(line);
673
- }
674
- return Promise.resolve(textResult(lines.join("\n")));
675
- },
676
- });
677
- function formatRemaining(ms) {
678
- if (ms < 60000)
679
- return `${Math.round(ms / 1000)}s`;
680
- if (ms < 3600000)
681
- return `${Math.round(ms / 60000)}m`;
682
- return `${Math.round(ms / 3600000)}h`;
242
+ monitorOnDoneRuntime.register(doneLoop, monitorId);
683
243
  }
684
- // ──────────────────────────────────────────────────
685
- // Tool 3: LoopDelete
686
- // ──────────────────────────────────────────────────
687
- pi.registerTool({
688
- name: "LoopDelete",
689
- label: "LoopDelete",
690
- description: `Delete or pause a loop by its ID.
691
-
692
- Use "pause" to temporarily stop a loop without removing it. Use "delete" to permanently remove it.`,
693
- parameters: Type.Object({
694
- id: Type.String({ description: "Loop ID to delete or pause" }),
695
- action: Type.Optional(Type.String({ description: "delete or pause (default: delete)", enum: ["delete", "pause"], default: "delete" })),
696
- }),
697
- execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
698
- const { id, action } = params;
699
- if (action === "pause") {
700
- const result = store.update(id, { status: "paused" });
701
- if (!result.entry)
702
- return Promise.resolve(textResult(`Loop #${id} not found`));
703
- triggerSystem.remove(id);
704
- widget.update();
705
- return Promise.resolve(textResult(`Loop #${id} paused`));
706
- }
707
- triggerSystem.remove(id);
708
- const deleted = store.delete(id);
709
- widget.update();
710
- if (deleted)
711
- return Promise.resolve(textResult(`Loop #${id} deleted`));
712
- return Promise.resolve(textResult(`Loop #${id} not found`));
713
- },
714
- });
715
- // ──────────────────────────────────────────────────
716
- // Tool 4: MonitorCreate
717
- // ──────────────────────────────────────────────────
718
- pi.registerTool({
719
- name: "MonitorCreate",
720
- label: "MonitorCreate",
721
- description: `Run a shell command in the background and get notified when it finishes. The core tool for async/parallel work.
722
-
723
- Fire off a build check, CI monitor, experiment, script, or any slow command — then keep working. Output streams back as "monitor:output" events. When the process exits, "monitor:done" fires (or "monitor:error" on failure).
724
-
725
- If you pass onDone with a prompt, the monitor auto-creates a one-shot completion loop — you get a completion wake with the exit code and output line count. No need to poll or create a separate loop.
726
-
727
- DO NOT use raw Bash while/sleep/for loops to watch something. DO NOT run slow commands inline that could be offloaded. Use MonitorCreate to run work in parallel while you continue.
728
-
729
- ## When to Use
730
-
731
- Default to MonitorCreate for any long-running or background work:\n- Watch a CI/CD build (hut, gh, curl polling) while you work on something else\n- Run experiments, benchmarks, or training scripts in parallel\n- Tail a log or poll an API endpoint\n- Fire off a slow curl/fetch and check the result later\n- Run any script or command you don't need to wait on inline
732
-
733
- ## Events emitted
734
-
735
- - "monitor:output" — { monitorId, line, timestamp } for each output line\n- "monitor:done" — { monitorId, exitCode, outputLines } on clean exit\n- "monitor:error" — { monitorId, error } on failure
736
-
737
- ## onDone — auto-notify on completion
738
-
739
- Pass onDone with a prompt and the monitor auto-creates a one-shot loop that fires when the process exits. The completion wake includes the exit code and output line count.\n\nExample: MonitorCreate command="python train.py" onDone="Check training results and report best loss"\nExample: MonitorCreate command="hut builds show 1769753" onDone="Analyze the build result and report status"`,
740
- promptGuidelines: [
741
- "Default to MonitorCreate for any long-running or background command — releases the agent to keep working on other tasks in parallel.",
742
- "When the user asks to monitor CI builds, watch a build, check a remote job, or run an experiment, use MonitorCreate instead of inline bash/curl/wait.",
743
- "Use onDone to auto-notify when a background command finishes — the agent will pick up the results automatically.",
744
- ],
745
- parameters: Type.Object({
746
- command: Type.String({ description: "Shell command to run in background" }),
747
- description: Type.Optional(Type.String({ description: "Human-readable description" })),
748
- timeout: Type.Optional(Type.Number({ description: "Auto-stop after N ms (default: 300000, 0 = no timeout)", default: 300000 })),
749
- onDone: Type.Optional(Type.String({ description: "Prompt to run when the monitor completes. Auto-creates a one-shot completion wake — no need for a separate LoopCreate." })),
750
- }),
751
- execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
752
- if (monitorManager.list().filter(m => m.status === "running").length >= 25) {
753
- return Promise.resolve(textResult("Maximum of 25 running monitors reached. Stop some before creating new ones."));
754
- }
755
- const entry = monitorManager.create(params.command, params.description, params.timeout);
244
+ registerMonitorTools({
245
+ pi,
246
+ getStore: () => store,
247
+ getMonitorManager: () => monitorManager,
248
+ updateWidget: () => {
756
249
  widget.update();
757
- let onDoneMsg = "";
758
- if (params.onDone) {
759
- const doneTrigger = { type: "event", source: "monitor:done", filter: JSON.stringify({ monitorId: entry.id }) };
760
- const doneLoop = store.create(doneTrigger, params.onDone, { recurring: false });
761
- handleMonitorDoneLoop(doneLoop, entry.id);
762
- onDoneMsg = `\nonDone loop #${doneLoop.id}: fires when monitor completes — no polling needed`;
763
- }
764
- return Promise.resolve(textResult(`Monitor #${entry.id} started: ${entry.command.slice(0, 60)}\n` +
765
- `Output stream: monitor:output (monitorId: ${entry.id})\n` +
766
- `Timeout: ${params.timeout ? `${params.timeout / 1000}s` : "none"}${onDoneMsg}`));
767
- },
768
- });
769
- // ──────────────────────────────────────────────────
770
- // Tool 5: MonitorList
771
- // ──────────────────────────────────────────────────
772
- pi.registerTool({
773
- name: "MonitorList",
774
- label: "MonitorList",
775
- description: `List all monitors with their status, command, exit code, output line count, and last 5 lines of buffered output.`,
776
- parameters: Type.Object({}),
777
- execute(_toolCallId, _params, _signal, _onUpdate, _ctx) {
778
- const monitors = monitorManager.list();
779
- if (monitors.length === 0)
780
- return Promise.resolve(textResult("No monitors running."));
781
- const lines = [];
782
- for (const m of monitors) {
783
- const icon = m.status === "running" ? ">" : m.status === "completed" ? "ok" : "!!";
784
- const age = Date.now() - m.startedAt;
785
- const ageStr = formatRemaining(age);
786
- let line = `${icon} #${m.id} [${m.status}] ${m.command.slice(0, 60)} — ${m.outputLines} lines (${ageStr})`;
787
- if (m.exitCode !== undefined)
788
- line += ` exit=${m.exitCode}`;
789
- lines.push(line);
790
- if (m.status !== "running" && m.outputBuffer.length > 0) {
791
- const tail = m.outputBuffer.slice(-5);
792
- for (const out of tail) {
793
- lines.push(` | ${out.slice(0, 100)}`);
794
- }
795
- }
796
- }
797
- return Promise.resolve(textResult(lines.join("\n")));
798
250
  },
251
+ handleMonitorDoneLoop,
799
252
  });
800
- // ──────────────────────────────────────────────────
801
- // Tool 6: MonitorStop
802
- // ──────────────────────────────────────────────────
803
- pi.registerTool({
804
- name: "MonitorStop",
805
- label: "MonitorStop",
806
- description: `Stop a running monitor. Sends SIGTERM, waits 5s, then SIGKILL.
807
-
808
- Use MonitorList to find the monitor ID, then stop it with this tool.`,
809
- parameters: Type.Object({
810
- monitorId: Type.String({ description: "Monitor ID to stop" }),
811
- }),
812
- async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
813
- const stopped = await monitorManager.stop(params.monitorId);
253
+ registerLoopCommand({
254
+ pi,
255
+ getStore: () => store,
256
+ getTriggerSystem: () => triggerSystem,
257
+ updateWidget: () => {
814
258
  widget.update();
815
- if (stopped)
816
- return textResult(`Monitor #${params.monitorId} stopped`);
817
- return textResult(`Monitor #${params.monitorId} not found or not running`);
818
- },
819
- });
820
- // ──────────────────────────────────────────────────
821
- // /loop command
822
- // ──────────────────────────────────────────────────
823
- pi.registerCommand("loop", {
824
- description: "Create a repeating scheduled task: /loop [interval] [prompt]. E.g., /loop 5m check the deploy, /loop 30s am I still here",
825
- handler: async (args, ctx) => {
826
- const trimmed = args.trim();
827
- const ui = ctx.ui;
828
- if (!trimmed) {
829
- const choice = await ui.select("Loop", [
830
- "Create scheduled loop",
831
- "Create event-triggered loop",
832
- "View active loops",
833
- "Settings",
834
- ]);
835
- if (!choice)
836
- return;
837
- if (choice.startsWith("Create scheduled"))
838
- return scheduleLoop(ui);
839
- if (choice.startsWith("Create event"))
840
- return eventLoop(ui);
841
- if (choice.startsWith("View active"))
842
- return viewLoops(ui);
843
- return settings(ui);
844
- }
845
- const intervalMatch = trimmed.match(/^(\d+\s*[smhdS]\b)/i);
846
- if (intervalMatch) {
847
- const interval = intervalMatch[1];
848
- const prompt = trimmed.slice(intervalMatch[0].length).trim();
849
- if (!prompt) {
850
- ui.notify("Provide a prompt after the interval, e.g., /loop 5m check the deploy", "warning");
851
- return;
852
- }
853
- try {
854
- const parsed = parseInterval(interval);
855
- const trigger = { type: "cron", schedule: parsed.cron };
856
- const entry = store.create(trigger, prompt, { recurring: true });
857
- triggerSystem.add(entry);
858
- widget.update();
859
- ui.notify(`Loop #${entry.id} created: every ${parsed.description} — ${prompt.slice(0, 50)}`, "info");
860
- }
861
- catch (err) {
862
- ui.notify(err.message, "error");
863
- }
864
- return;
865
- }
866
- const choice = await ui.select("Loop mode", [
867
- `Scheduled: "${trimmed.slice(0, 50)}"`,
868
- `Event-triggered: "${trimmed.slice(0, 50)}"`,
869
- `Self-paced: "${trimmed.slice(0, 50)}"`,
870
- ]);
871
- if (!choice)
872
- return;
873
- if (choice.startsWith("Event"))
874
- return eventLoop(ui, trimmed);
875
- return scheduleLoop(ui, trimmed);
876
259
  },
877
260
  });
878
- async function scheduleLoop(ui, prompt) {
879
- const p = prompt || await ui.input("Prompt (what should the agent check?)");
880
- if (!p)
881
- return;
882
- const interval = await ui.input("Interval (e.g., 5m, 2h, 1d)");
883
- if (!interval)
884
- return;
885
- try {
886
- const parsed = parseInterval(interval);
887
- const trigger = { type: "cron", schedule: parsed.cron };
888
- const entry = store.create(trigger, p, { recurring: true });
889
- triggerSystem.add(entry);
890
- widget.update();
891
- ui.notify(`Loop #${entry.id} created: every ${parsed.description}`, "info");
892
- }
893
- catch (err) {
894
- ui.notify(err.message, "error");
895
- }
896
- }
897
- async function eventLoop(ui, prompt) {
898
- const p = prompt || await ui.input("Prompt");
899
- if (!p)
900
- return;
901
- const source = await ui.input("Pi event source (e.g., tool_execution_start, before_agent_start)");
902
- if (!source)
903
- return;
904
- const trigger = { type: "event", source };
905
- const entry = store.create(trigger, p, { recurring: true });
906
- triggerSystem.add(entry);
907
- widget.update();
908
- ui.notify(`Event loop #${entry.id} created: fires on "${source}"`, "info");
909
- }
910
- async function viewLoops(ui) {
911
- const loops = store.list();
912
- if (loops.length === 0) {
913
- await ui.select("No active loops", ["< Back"]);
914
- return;
915
- }
916
- const choices = loops.map((l) => {
917
- const icon = l.status === "active" ? "*" : l.status === "paused" ? "-" : "x";
918
- const triggerDesc = l.trigger.type === "cron" ? `cron: ${l.trigger.schedule}` : l.trigger.type === "event" ? `event: ${l.trigger.source}` : `hybrid: ${l.trigger.cron}`;
919
- return `${icon} #${l.id} [${l.status}] ${l.prompt.slice(0, 50)} (${triggerDesc})`;
920
- });
921
- choices.push("< Back");
922
- const selected = await ui.select("Active Loops", choices);
923
- if (!selected || selected === "< Back")
924
- return;
925
- const match = selected.match(/#(\d+)/);
926
- if (match) {
927
- const entry = store.get(match[1]);
928
- if (entry) {
929
- const actions = ["x Delete"];
930
- if (entry.status === "active")
931
- actions.unshift("- Pause");
932
- else if (entry.status === "paused")
933
- actions.unshift("* Resume");
934
- actions.push("< Back");
935
- const action = await ui.select(`#${entry.id}: ${entry.prompt}\nTrigger: ${JSON.stringify(entry.trigger)}`, actions);
936
- if (action === "x Delete") {
937
- triggerSystem.remove(entry.id);
938
- store.delete(entry.id);
939
- widget.update();
940
- ui.notify(`Loop #${entry.id} deleted`, "info");
941
- }
942
- else if (action === "- Pause") {
943
- store.update(entry.id, { status: "paused" });
944
- triggerSystem.remove(entry.id);
945
- widget.update();
946
- ui.notify(`Loop #${entry.id} paused`, "info");
947
- }
948
- else if (action === "* Resume") {
949
- store.update(entry.id, { status: "active" });
950
- triggerSystem.add(entry);
951
- widget.update();
952
- ui.notify(`Loop #${entry.id} resumed`, "info");
953
- }
954
- }
955
- }
956
- return viewLoops(ui);
957
- }
958
- async function settings(ui) {
959
- const loops = store.list();
960
- const active = loops.filter(l => l.status === "active").length;
961
- ui.notify(`${active}/${loops.length} active loops (max 25)`, "info");
962
- }
963
- const AUTO_TASK_WORKER_THRESHOLD = 5;
964
- const AUTO_TASK_WORKER_PROMPT = "Run TaskList, pick next pending task, mark it in_progress, implement it, run validation, complete it. If no pending tasks remain, call LoopDelete on your own loop ID.";
965
- function isAutoTaskWorkerLoop(entry) {
966
- return entry.status === "active"
967
- && entry.prompt === AUTO_TASK_WORKER_PROMPT
968
- && triggerHasEventSource(entry.trigger, "tasks:created");
969
- }
970
- function isTaskBacklogLoop(entry) {
971
- return entry.status === "active"
972
- && triggerHasEventSource(entry.trigger, "tasks:created")
973
- && (entry.taskBacklog === true || isAutoTaskWorkerLoop(entry));
974
- }
975
- function findAutoTaskWorkerLoop() {
976
- return store.list().find(isAutoTaskWorkerLoop);
977
- }
978
- async function cleanupTaskBacklogLoops() {
979
- const backlogLoops = store.list().filter(isTaskBacklogLoop);
980
- if (backlogLoops.length === 0)
981
- return 0;
982
- const pending = await hasPendingTasks();
983
- if (pending < 0 || pending > 0)
984
- return 0;
985
- for (const entry of backlogLoops) {
986
- debug(`task backlog loop #${entry.id} — no pending tasks remain, deleting`);
987
- triggerSystem.remove(entry.id);
988
- store.delete(entry.id);
989
- }
990
- widget.update();
991
- return backlogLoops.length;
992
- }
993
- async function ensureAutoTaskWorkerLoop(taskStore) {
994
- if (taskStore.pendingCount() < AUTO_TASK_WORKER_THRESHOLD)
995
- return { created: false };
996
- const existing = findAutoTaskWorkerLoop();
997
- if (existing)
998
- return { entry: existing, created: false };
999
- const trigger = {
1000
- type: "hybrid",
1001
- cron: "*/5 * * * *",
1002
- event: { source: "tasks:created" },
1003
- debounceMs: 30000,
1004
- };
1005
- const entry = store.create(trigger, AUTO_TASK_WORKER_PROMPT, {
1006
- recurring: true,
1007
- taskBacklog: true,
1008
- maxFires: 30,
1009
- });
1010
- triggerSystem.add(entry);
1011
- await maybeBootstrapTaskLoop(entry);
1012
- widget.update();
1013
- return { entry, created: true };
1014
- }
1015
- async function createNativeTaskInteractively(ui) {
1016
- if (!nativeTaskStore) {
1017
- ui.notify("Native tasks are unavailable while pi-tasks is active", "warning");
1018
- return;
1019
- }
1020
- const subject = await ui.input("Task subject");
1021
- if (!subject)
1022
- return;
1023
- const description = await ui.input("Task description") || subject;
1024
- const entry = nativeTaskStore.create(subject, description);
1025
- pi.events.emit("tasks:created", {
1026
- taskId: entry.id,
1027
- subject: entry.subject,
1028
- description: entry.description,
1029
- status: entry.status,
1030
- });
1031
- const worker = await ensureAutoTaskWorkerLoop(nativeTaskStore);
1032
- widget.update();
1033
- ui.notify(`Task #${entry.id} created`, "info");
1034
- if (worker.created && worker.entry) {
1035
- ui.notify(`Worker loop #${worker.entry.id} auto-created`, "info");
1036
- }
1037
- }
1038
- async function viewNativeTasks(ui) {
1039
- if (!nativeTaskStore) {
1040
- ui.notify("Native tasks are unavailable while pi-tasks is active", "warning");
1041
- return;
1042
- }
1043
- const tasks = nativeTaskStore.list();
1044
- const choices = tasks.map((task) => {
1045
- const icon = task.status === "in_progress" ? ">" : task.status === "completed" ? "ok" : "*";
1046
- return `${icon} #${task.id} [${task.status}] ${task.subject.slice(0, 60)}`;
1047
- });
1048
- choices.unshift("+ Create task");
1049
- choices.push("< Back");
1050
- const selected = await ui.select("Native Tasks", choices);
1051
- if (!selected || selected === "< Back")
1052
- return;
1053
- if (selected === "+ Create task") {
1054
- await createNativeTaskInteractively(ui);
1055
- return viewNativeTasks(ui);
1056
- }
1057
- const match = selected.match(/#(\d+)/);
1058
- if (!match)
1059
- return viewNativeTasks(ui);
1060
- const task = nativeTaskStore.get(match[1]);
1061
- if (!task)
1062
- return viewNativeTasks(ui);
1063
- const actions = ["x Delete"];
1064
- if (task.status === "pending") {
1065
- actions.unshift("ok Complete");
1066
- actions.unshift("> Start");
1067
- }
1068
- else if (task.status === "in_progress") {
1069
- actions.unshift("ok Complete");
1070
- actions.unshift("* Return to pending");
1071
- }
1072
- else {
1073
- actions.unshift("* Reopen");
1074
- }
1075
- actions.push("< Back");
1076
- const action = await ui.select(`#${task.id}: ${task.subject}\n\n${task.description}`, actions);
1077
- if (!action || action === "< Back")
1078
- return viewNativeTasks(ui);
1079
- if (action === "x Delete") {
1080
- nativeTaskStore.delete(task.id);
1081
- ui.notify(`Task #${task.id} deleted`, "info");
1082
- }
1083
- else if (action === "> Start") {
1084
- nativeTaskStore.update(task.id, { status: "in_progress" });
1085
- ui.notify(`Task #${task.id} started`, "info");
1086
- }
1087
- else if (action === "ok Complete") {
1088
- nativeTaskStore.update(task.id, { status: "completed" });
1089
- ui.notify(`Task #${task.id} completed`, "info");
1090
- }
1091
- else if (action === "* Return to pending" || action === "* Reopen") {
1092
- nativeTaskStore.update(task.id, { status: "pending" });
1093
- ui.notify(`Task #${task.id} reopened`, "info");
1094
- }
1095
- widget.update();
1096
- await cleanupTaskBacklogLoops();
1097
- return viewNativeTasks(ui);
1098
- }
1099
261
  // ── Native task tools (only when pi-tasks is absent) ──
1100
262
  setTimeout(async () => {
1101
263
  if (tasksAvailable || nativeTasksRegistered)
1102
264
  return;
1103
- nativeTaskStore = new TaskStore(resolveTaskStorePath(_sessionId));
265
+ nativeTaskStore = new TaskStore(resolveTaskStorePath(getScopeOptions(), _sessionId));
1104
266
  nativeTasksRegistered = true;
1105
267
  const taskStore = nativeTaskStore;
1106
- pi.registerCommand("tasks", {
1107
- description: "View or manage native pi-loop tasks when pi-tasks is not installed",
1108
- handler: async (args, ctx) => {
1109
- const trimmed = args.trim();
1110
- if (!nativeTaskStore) {
1111
- ctx.ui.notify("Native tasks are unavailable while pi-tasks is active", "warning");
1112
- return;
1113
- }
1114
- if (trimmed) {
1115
- const entry = nativeTaskStore.create(trimmed.slice(0, 80), trimmed);
1116
- pi.events.emit("tasks:created", {
1117
- taskId: entry.id,
1118
- subject: entry.subject,
1119
- description: entry.description,
1120
- status: entry.status,
1121
- });
1122
- const worker = await ensureAutoTaskWorkerLoop(nativeTaskStore);
1123
- widget.update();
1124
- ctx.ui.notify(`Task #${entry.id} created`, "info");
1125
- if (worker.created && worker.entry) {
1126
- ctx.ui.notify(`Worker loop #${worker.entry.id} auto-created`, "info");
1127
- }
1128
- return;
1129
- }
1130
- await viewNativeTasks(ctx.ui);
1131
- },
1132
- });
1133
- pi.registerTool({
1134
- name: "TaskCreate",
1135
- label: "TaskCreate",
1136
- description: `Create a task for tracking work across turns. Use when you need to track progress on complex multi-step tasks.
1137
-
1138
- Fields:
1139
- - subject: brief actionable title
1140
- - description: detailed requirements
1141
- - metadata: optional tags/metadata`,
1142
- promptGuidelines: [
1143
- "Use TaskCreate to track complex multi-step work across turns.",
1144
- "Break work into small, independently completable tasks. A task should be finishable in one focused session — if a task would take multiple turns, split it further.",
1145
- "TaskCreate accepts `subject` and `description` parameters only — do not invent extra fields unless the schema explicitly adds them.",
1146
- ],
1147
- parameters: Type.Object({
1148
- subject: Type.String({ description: "Brief actionable title for the task" }),
1149
- description: Type.String({ description: "Detailed description of what needs to be done" }),
1150
- }),
1151
- async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
1152
- const entry = taskStore.create(params.subject, params.description);
1153
- pi.events.emit("tasks:created", {
1154
- taskId: entry.id,
1155
- subject: entry.subject,
1156
- description: entry.description,
1157
- status: entry.status,
1158
- });
1159
- const worker = await ensureAutoTaskWorkerLoop(taskStore);
1160
- widget.update();
1161
- const autoLoopMsg = worker.created && worker.entry
1162
- ? `\nWorker loop #${worker.entry.id} auto-created`
1163
- : "";
1164
- return Promise.resolve(textResult(`Task #${entry.id} created: ${entry.subject}${autoLoopMsg}`));
1165
- },
1166
- });
1167
- pi.registerTool({
1168
- name: "TaskList",
1169
- label: "TaskList",
1170
- description: `List all tasks with status. Use to check progress and find available work.`,
1171
- parameters: Type.Object({}),
1172
- execute(_toolCallId, _params, _signal, _onUpdate, _ctx) {
1173
- const tasks = taskStore.list();
1174
- if (tasks.length === 0)
1175
- return Promise.resolve(textResult("No tasks."));
1176
- const lines = [];
1177
- const statuses = {
1178
- pending: 0,
1179
- in_progress: 0,
1180
- completed: 0,
1181
- };
1182
- for (const t of tasks) {
1183
- statuses[t.status]++;
1184
- const icon = t.status === "completed" ? "ok" : t.status === "in_progress" ? ">" : "*";
1185
- lines.push(`${icon} #${t.id} [${t.status}] ${t.subject.slice(0, 80)}`);
1186
- }
1187
- lines.unshift(`${tasks.length} tasks (${statuses.pending} pending, ${statuses.in_progress} in progress, ${statuses.completed} done)`);
1188
- return Promise.resolve(textResult(lines.join("\n")));
1189
- },
1190
- });
1191
- pi.registerTool({
1192
- name: "TaskUpdate",
1193
- label: "TaskUpdate",
1194
- description: `Update task status or details. Set status to "in_progress" before starting work, "completed" when done.
1195
-
1196
- Statuses: pending → in_progress → completed
1197
- Parameters: id (required), status, subject, description`,
1198
- promptGuidelines: [
1199
- "TaskUpdate uses parameter `id`, not `taskId`.",
1200
- "Accepted parameters: `id` (required), `status`, `subject`, `description`.",
1201
- "When validation fails with 'must have required properties id', you passed `taskId` instead of `id`. Correct silently and retry.",
1202
- ],
1203
- parameters: Type.Object({
1204
- id: Type.String({ description: "Task ID to update" }),
1205
- status: Type.Optional(Type.String({ description: "New status", enum: ["pending", "in_progress", "completed"] })),
1206
- subject: Type.Optional(Type.String({ description: "New title" })),
1207
- description: Type.Optional(Type.String({ description: "New description" })),
1208
- }),
1209
- async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
1210
- const { id, status, subject, description } = params;
1211
- const entry = taskStore.update(id, {
1212
- status: status,
1213
- subject,
1214
- description,
1215
- });
1216
- if (!entry)
1217
- return Promise.resolve(textResult(`Task #${id} not found`));
268
+ registerTasksCommand({
269
+ pi,
270
+ getNativeTaskStore: () => nativeTaskStore,
271
+ evaluateTaskBacklog,
272
+ updateWidget: () => {
1218
273
  widget.update();
1219
- await cleanupTaskBacklogLoops();
1220
- const statusMsg = status ? ` → ${status}` : "";
1221
- return Promise.resolve(textResult(`Task #${id} updated${statusMsg}`));
1222
274
  },
1223
275
  });
1224
- pi.registerTool({
1225
- name: "TaskDelete",
1226
- label: "TaskDelete",
1227
- description: `Delete a task by ID. Use for cleaning up completed or irrelevant tasks.`,
1228
- parameters: Type.Object({
1229
- id: Type.String({ description: "Task ID to delete" }),
1230
- }),
1231
- async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
1232
- const deleted = taskStore.delete(params.id);
276
+ registerNativeTaskTools({
277
+ pi,
278
+ taskStore,
279
+ evaluateTaskBacklog,
280
+ updateWidget: () => {
1233
281
  widget.update();
1234
- if (deleted) {
1235
- await cleanupTaskBacklogLoops();
1236
- return Promise.resolve(textResult(`Task #${params.id} deleted`));
1237
- }
1238
- return Promise.resolve(textResult(`Task #${params.id} not found`));
1239
282
  },
1240
283
  });
1241
284
  debug("native task tools registered (pi-tasks not detected)");