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