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