@timmyjl12/pi-subagents 0.0.0-stage → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/CHANGELOG.md +862 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1125 -3
  5. package/SECURITY.md +97 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/active-agents-prompt.d.ts +40 -0
  9. package/dist/active-agents-prompt.js +98 -0
  10. package/dist/advisor-status.d.ts +16 -0
  11. package/dist/advisor-status.js +74 -0
  12. package/dist/agent-color.d.ts +35 -0
  13. package/dist/agent-color.js +131 -0
  14. package/dist/agent-file-toggle.d.ts +125 -0
  15. package/dist/agent-file-toggle.js +264 -0
  16. package/dist/agent-manager.d.ts +872 -0
  17. package/dist/agent-manager.js +2910 -0
  18. package/dist/agent-runner.d.ts +358 -0
  19. package/dist/agent-runner.js +1219 -0
  20. package/dist/agent-types.d.ts +142 -0
  21. package/dist/agent-types.js +315 -0
  22. package/dist/awaited-result.d.ts +37 -0
  23. package/dist/awaited-result.js +150 -0
  24. package/dist/child-context.d.ts +15 -0
  25. package/dist/child-context.js +181 -0
  26. package/dist/child-session-shutdown.d.ts +21 -0
  27. package/dist/child-session-shutdown.js +97 -0
  28. package/dist/cleanup-plans.d.ts +10 -0
  29. package/dist/cleanup-plans.js +112 -0
  30. package/dist/context.d.ts +12 -0
  31. package/dist/context.js +56 -0
  32. package/dist/cross-extension-rpc.d.ts +73 -0
  33. package/dist/cross-extension-rpc.js +192 -0
  34. package/dist/custom-agents.d.ts +79 -0
  35. package/dist/custom-agents.js +583 -0
  36. package/dist/default-agents.d.ts +7 -0
  37. package/dist/default-agents.js +125 -0
  38. package/dist/enabled-models.d.ts +49 -0
  39. package/dist/enabled-models.js +145 -0
  40. package/dist/env.d.ts +6 -0
  41. package/dist/env.js +28 -0
  42. package/dist/error-log.d.ts +64 -0
  43. package/dist/error-log.js +176 -0
  44. package/dist/force-main-model.d.ts +21 -0
  45. package/dist/force-main-model.js +28 -0
  46. package/dist/goal-bridge.d.ts +155 -0
  47. package/dist/goal-bridge.js +305 -0
  48. package/dist/group-join.d.ts +36 -0
  49. package/dist/group-join.js +161 -0
  50. package/dist/index.d.ts +52 -0
  51. package/dist/index.js +6390 -0
  52. package/dist/invocation-config.d.ts +164 -0
  53. package/dist/invocation-config.js +158 -0
  54. package/dist/memory.d.ts +53 -0
  55. package/dist/memory.js +165 -0
  56. package/dist/mention-clone.d.ts +87 -0
  57. package/dist/mention-clone.js +178 -0
  58. package/dist/mention.d.ts +81 -0
  59. package/dist/mention.js +131 -0
  60. package/dist/model-resolver.d.ts +36 -0
  61. package/dist/model-resolver.js +95 -0
  62. package/dist/model-scope.d.ts +49 -0
  63. package/dist/model-scope.js +48 -0
  64. package/dist/nested-tools.d.ts +76 -0
  65. package/dist/nested-tools.js +393 -0
  66. package/dist/output-diagnostics.d.ts +11 -0
  67. package/dist/output-diagnostics.js +64 -0
  68. package/dist/output-file.d.ts +64 -0
  69. package/dist/output-file.js +351 -0
  70. package/dist/prompts.d.ts +61 -0
  71. package/dist/prompts.js +94 -0
  72. package/dist/recovery.d.ts +56 -0
  73. package/dist/recovery.js +341 -0
  74. package/dist/report-cleanup.d.ts +204 -0
  75. package/dist/report-cleanup.js +1632 -0
  76. package/dist/report-store.d.ts +738 -0
  77. package/dist/report-store.js +3612 -0
  78. package/dist/schedule-store.d.ts +52 -0
  79. package/dist/schedule-store.js +240 -0
  80. package/dist/schedule.d.ts +121 -0
  81. package/dist/schedule.js +420 -0
  82. package/dist/settings.d.ts +388 -0
  83. package/dist/settings.js +268 -0
  84. package/dist/skill-loader.d.ts +24 -0
  85. package/dist/skill-loader.js +93 -0
  86. package/dist/standalone-fallback.d.ts +30 -0
  87. package/dist/standalone-fallback.js +239 -0
  88. package/dist/status-note.d.ts +61 -0
  89. package/dist/status-note.js +85 -0
  90. package/dist/structured-output.d.ts +61 -0
  91. package/dist/structured-output.js +112 -0
  92. package/dist/terminal-progress.d.ts +115 -0
  93. package/dist/terminal-progress.js +206 -0
  94. package/dist/types.d.ts +411 -0
  95. package/dist/types.js +5 -0
  96. package/dist/ui/agent-mention.d.ts +82 -0
  97. package/dist/ui/agent-mention.js +187 -0
  98. package/dist/ui/agent-widget.d.ts +304 -0
  99. package/dist/ui/agent-widget.js +770 -0
  100. package/dist/ui/cleanup-preview.d.ts +59 -0
  101. package/dist/ui/cleanup-preview.js +466 -0
  102. package/dist/ui/conversation-viewer.d.ts +105 -0
  103. package/dist/ui/conversation-viewer.js +544 -0
  104. package/dist/ui/fleet-list.d.ts +183 -0
  105. package/dist/ui/fleet-list.js +494 -0
  106. package/dist/ui/fleet-overlay.d.ts +203 -0
  107. package/dist/ui/fleet-overlay.js +887 -0
  108. package/dist/ui/hub-feed.d.ts +52 -0
  109. package/dist/ui/hub-feed.js +148 -0
  110. package/dist/ui/native-transcript.d.ts +33 -0
  111. package/dist/ui/native-transcript.js +234 -0
  112. package/dist/ui/schedule-menu.d.ts +16 -0
  113. package/dist/ui/schedule-menu.js +94 -0
  114. package/dist/ui/select-item.d.ts +27 -0
  115. package/dist/ui/select-item.js +34 -0
  116. package/dist/ui/tool-progress.d.ts +22 -0
  117. package/dist/ui/tool-progress.js +56 -0
  118. package/dist/ui/viewer-keys.d.ts +20 -0
  119. package/dist/ui/viewer-keys.js +17 -0
  120. package/dist/ui/workflow-card.d.ts +175 -0
  121. package/dist/ui/workflow-card.js +332 -0
  122. package/dist/ui/workflow-dialog.d.ts +305 -0
  123. package/dist/ui/workflow-dialog.js +848 -0
  124. package/dist/ui/workflow-menu.d.ts +60 -0
  125. package/dist/ui/workflow-menu.js +147 -0
  126. package/dist/usage.d.ts +147 -0
  127. package/dist/usage.js +147 -0
  128. package/dist/workflow/collisions.d.ts +95 -0
  129. package/dist/workflow/collisions.js +88 -0
  130. package/dist/workflow/entry.d.ts +32 -0
  131. package/dist/workflow/entry.js +29 -0
  132. package/dist/workflow/host.d.ts +65 -0
  133. package/dist/workflow/host.js +477 -0
  134. package/dist/workflow/journal.d.ts +113 -0
  135. package/dist/workflow/journal.js +177 -0
  136. package/dist/workflow/json-schema.d.ts +51 -0
  137. package/dist/workflow/json-schema.js +111 -0
  138. package/dist/workflow/meta.d.ts +67 -0
  139. package/dist/workflow/meta.js +317 -0
  140. package/dist/workflow/progress.d.ts +224 -0
  141. package/dist/workflow/progress.js +361 -0
  142. package/dist/workflow/runtime.d.ts +373 -0
  143. package/dist/workflow/runtime.js +919 -0
  144. package/dist/workflow/saved.d.ts +90 -0
  145. package/dist/workflow/saved.js +203 -0
  146. package/dist/workflow/task.d.ts +145 -0
  147. package/dist/workflow/task.js +213 -0
  148. package/dist/workflow/tool-description.d.ts +43 -0
  149. package/dist/workflow/tool-description.js +204 -0
  150. package/dist/workflow/worker-source.d.ts +47 -0
  151. package/dist/workflow/worker-source.js +778 -0
  152. package/dist/worktree.d.ts +52 -0
  153. package/dist/worktree.js +164 -0
  154. package/dist/xml.d.ts +10 -0
  155. package/dist/xml.js +12 -0
  156. package/docs/DEVELOPMENT.md +40 -0
  157. package/docs/artifacts.md +93 -0
  158. package/docs/recovery.md +62 -0
  159. package/docs/rpc.md +252 -0
  160. package/docs/runtime-performance.md +53 -0
  161. package/docs/workflows.md +467 -0
  162. package/examples/agent-tool-description.md +43 -0
  163. package/examples/workflows/compose.js +51 -0
  164. package/examples/workflows/fan-out-audit.js +47 -0
  165. package/examples/workflows/gated-fix.js +60 -0
  166. package/examples/workflows/lib/count-child.js +27 -0
  167. package/examples/workflows/review-panel.js +66 -0
  168. package/examples/workflows/structured-findings.js +78 -0
  169. package/package.json +75 -6
  170. package/src/abortable.ts +43 -0
  171. package/src/active-agents-prompt.ts +115 -0
  172. package/src/advisor-status.ts +74 -0
  173. package/src/agent-color.ts +169 -0
  174. package/src/agent-file-toggle.ts +273 -0
  175. package/src/agent-manager.ts +3312 -0
  176. package/src/agent-runner.ts +1500 -0
  177. package/src/agent-types.ts +390 -0
  178. package/src/awaited-result.ts +187 -0
  179. package/src/child-context.ts +173 -0
  180. package/src/child-session-shutdown.ts +114 -0
  181. package/src/cleanup-plans.ts +112 -0
  182. package/src/context.ts +58 -0
  183. package/src/cross-extension-rpc.ts +257 -0
  184. package/src/custom-agents.ts +689 -0
  185. package/src/default-agents.ts +129 -0
  186. package/src/enabled-models.ts +180 -0
  187. package/src/env.ts +33 -0
  188. package/src/error-log.ts +202 -0
  189. package/src/force-main-model.ts +29 -0
  190. package/src/goal-bridge.ts +468 -0
  191. package/src/group-join.ts +188 -0
  192. package/src/index.ts +6856 -0
  193. package/src/invocation-config.ts +276 -0
  194. package/src/memory.ts +179 -0
  195. package/src/mention-clone.ts +221 -0
  196. package/src/mention.ts +141 -0
  197. package/src/model-resolver.ts +118 -0
  198. package/src/model-scope.ts +70 -0
  199. package/src/nested-tools.ts +553 -0
  200. package/src/output-diagnostics.ts +68 -0
  201. package/src/output-file.ts +380 -0
  202. package/src/prompts.ts +151 -0
  203. package/src/recovery.ts +320 -0
  204. package/src/report-cleanup.ts +2044 -0
  205. package/src/report-store.ts +4130 -0
  206. package/src/schedule-store.ts +244 -0
  207. package/src/schedule.ts +450 -0
  208. package/src/settings.ts +632 -0
  209. package/src/skill-loader.ts +102 -0
  210. package/src/standalone-fallback.ts +195 -0
  211. package/src/status-note.ts +90 -0
  212. package/src/structured-output.ts +130 -0
  213. package/src/terminal-progress.ts +215 -0
  214. package/src/types.ts +424 -0
  215. package/src/ui/agent-mention.ts +216 -0
  216. package/src/ui/agent-widget.ts +866 -0
  217. package/src/ui/cleanup-preview.ts +518 -0
  218. package/src/ui/conversation-viewer.ts +527 -0
  219. package/src/ui/fleet-list.ts +563 -0
  220. package/src/ui/fleet-overlay.ts +1048 -0
  221. package/src/ui/hub-feed.ts +179 -0
  222. package/src/ui/native-transcript.ts +224 -0
  223. package/src/ui/schedule-menu.ts +105 -0
  224. package/src/ui/select-item.ts +45 -0
  225. package/src/ui/tool-progress.ts +67 -0
  226. package/src/ui/viewer-keys.ts +39 -0
  227. package/src/ui/workflow-card.ts +470 -0
  228. package/src/ui/workflow-dialog.ts +1119 -0
  229. package/src/ui/workflow-menu.ts +193 -0
  230. package/src/usage.ts +217 -0
  231. package/src/workflow/collisions.ts +123 -0
  232. package/src/workflow/entry.ts +47 -0
  233. package/src/workflow/host.ts +524 -0
  234. package/src/workflow/journal.ts +221 -0
  235. package/src/workflow/json-schema.ts +128 -0
  236. package/src/workflow/meta.ts +325 -0
  237. package/src/workflow/progress.ts +550 -0
  238. package/src/workflow/runtime.ts +1342 -0
  239. package/src/workflow/saved.ts +217 -0
  240. package/src/workflow/task.ts +313 -0
  241. package/src/workflow/tool-description.ts +205 -0
  242. package/src/workflow/worker-source.ts +781 -0
  243. package/src/worktree.ts +205 -0
  244. package/src/xml.ts +13 -0
@@ -0,0 +1,244 @@
1
+ /**
2
+ * schedule-store.ts — File-backed store for scheduled subagents.
3
+ *
4
+ * Session-scoped: each pi session owns its own schedules at
5
+ * `<cwd>/.pi/subagent-schedules/<sessionId>.json`. `/new` starts a fresh
6
+ * empty store; `/resume` reloads.
7
+ *
8
+ * Concurrency model lifted from pi-chonky-tasks/src/task-store.ts: every
9
+ * mutation acquires a PID-based exclusion lock, re-reads the latest state
10
+ * from disk, applies the change, atomic-writes via temp+rename, releases.
11
+ */
12
+
13
+ import { randomBytes } from "node:crypto";
14
+ import { readFileSync } from "node:fs";
15
+ import { mkdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
16
+ import { dirname, join } from "node:path";
17
+ import { setTimeout as sleep } from "node:timers/promises";
18
+ import type { ScheduledSubagent, ScheduleStoreData } from "./types.ts";
19
+
20
+ const LOCK_RETRY_MS = 50;
21
+ /** Total asynchronous wait for the lock. */
22
+ const LOCK_MAX_WAIT_MS = 1000;
23
+ /**
24
+ * A lock older than this is stale whatever its PID says: Windows reuses PIDs
25
+ * aggressively, so "that process is alive" does not mean it holds the lock.
26
+ * A mutation holds the lock for a few milliseconds.
27
+ */
28
+ export const LOCK_STALE_MS = 30_000;
29
+ const RENAME_RETRIES = 5;
30
+ const RENAME_RETRY_MS = 20;
31
+
32
+ function isProcessRunning(pid: number): boolean {
33
+ try {
34
+ process.kill(pid, 0);
35
+ return true;
36
+ } catch {
37
+ return false;
38
+ }
39
+ }
40
+
41
+ function errorCode(e: unknown): string | undefined {
42
+ const code = (e as { code?: unknown } | null)?.code;
43
+ return typeof code === "string" ? code : undefined;
44
+ }
45
+
46
+ /** True when the existing lock file can be broken: too old, or its owner is gone. */
47
+ async function isLockStale(lockPath: string): Promise<boolean> {
48
+ try {
49
+ if (Date.now() - (await stat(lockPath)).mtimeMs > LOCK_STALE_MS) return true;
50
+ const pid = parseInt(await readFile(lockPath, "utf-8"), 10);
51
+ return Number.isInteger(pid) && pid > 0 && !isProcessRunning(pid);
52
+ } catch (e) {
53
+ // Vanished between our write attempt and this check: retry the write.
54
+ return errorCode(e) === "ENOENT";
55
+ }
56
+ }
57
+
58
+ async function acquireLock(lockPath: string): Promise<void> {
59
+ const deadline = Date.now() + LOCK_MAX_WAIT_MS;
60
+ for (;;) {
61
+ try {
62
+ await writeFile(lockPath, `${process.pid}`, { flag: "wx" });
63
+ return;
64
+ } catch (e) {
65
+ if (errorCode(e) !== "EEXIST") throw e;
66
+ }
67
+ if (await isLockStale(lockPath)) {
68
+ try {
69
+ await unlink(lockPath);
70
+ } catch (e) {
71
+ if (errorCode(e) !== "ENOENT") throw e;
72
+ }
73
+ continue;
74
+ }
75
+ if (Date.now() >= deadline) break;
76
+ await sleep(LOCK_RETRY_MS);
77
+ }
78
+ throw new Error(`Failed to acquire schedule lock: ${lockPath}`);
79
+ }
80
+
81
+ /** rename with a bounded retry: Windows reports EPERM/EBUSY while AV or an indexer holds the target. */
82
+ async function renameWithRetry(from: string, to: string): Promise<void> {
83
+ for (let attempt = 0; ; attempt++) {
84
+ try {
85
+ await rename(from, to);
86
+ return;
87
+ } catch (e) {
88
+ const code = errorCode(e);
89
+ const transient = code === "EPERM" || code === "EBUSY" || code === "EACCES";
90
+ if (!transient || attempt >= RENAME_RETRIES) {
91
+ // Best effort: the rename error below is the one that matters.
92
+ await unlink(from).catch(() => undefined);
93
+ throw e;
94
+ }
95
+ await sleep(RENAME_RETRY_MS * (attempt + 1));
96
+ }
97
+ }
98
+ }
99
+
100
+ async function releaseLock(lockPath: string): Promise<void> {
101
+ await unlink(lockPath).catch(() => undefined);
102
+ }
103
+
104
+ /** Resolve the storage path for a session-scoped store. */
105
+ export function resolveStorePath(cwd: string, sessionId: string): string {
106
+ return join(cwd, ".pi", "subagent-schedules", `${sessionId}.json`);
107
+ }
108
+
109
+ function parseStoreData(serialized: string): ScheduleStoreData | undefined {
110
+ try {
111
+ return JSON.parse(serialized) as ScheduleStoreData;
112
+ } catch {
113
+ return undefined;
114
+ }
115
+ }
116
+
117
+ export class ScheduleStore {
118
+ private filePath: string;
119
+ private lockPath: string;
120
+ private jobs = new Map<string, ScheduledSubagent>();
121
+
122
+ constructor(filePath: string) {
123
+ this.filePath = filePath;
124
+ this.lockPath = filePath + ".lock";
125
+ this.loadInitial();
126
+ }
127
+
128
+ /** Create the backing directory lazily — only when we're about to persist. */
129
+ private async ensureDir(): Promise<void> {
130
+ await mkdir(dirname(this.filePath), { recursive: true });
131
+ }
132
+
133
+ /**
134
+ * One cold synchronous read preserves the synchronous constructor and the
135
+ * list/get snapshot API. Every reload on a mutation path uses async I/O.
136
+ */
137
+ private loadInitial(): void {
138
+ let serialized: string;
139
+ try {
140
+ serialized = readFileSync(this.filePath, "utf-8");
141
+ } catch {
142
+ return;
143
+ }
144
+ const data = parseStoreData(serialized);
145
+ if (data) this.replaceJobs(data);
146
+ }
147
+
148
+ /** Reload from disk into the in-memory cache. Silent on parse errors. */
149
+ private async load(): Promise<void> {
150
+ let serialized: string;
151
+ try {
152
+ serialized = await readFile(this.filePath, "utf-8");
153
+ } catch (e) {
154
+ if (errorCode(e) === "ENOENT") return;
155
+ throw e;
156
+ }
157
+ const data = parseStoreData(serialized);
158
+ if (data) this.replaceJobs(data);
159
+ }
160
+
161
+ private replaceJobs(data: ScheduleStoreData): void {
162
+ this.jobs.clear();
163
+ for (const j of data.jobs ?? []) this.jobs.set(j.id, j);
164
+ }
165
+
166
+ /** Atomic write via temp file + rename (POSIX-atomic). */
167
+ private async save(): Promise<void> {
168
+ const data: ScheduleStoreData = { version: 1, jobs: [...this.jobs.values()] };
169
+ // Unique per write, so two writers can never clobber each other's temp file.
170
+ const tmp = `${this.filePath}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
171
+ await writeFile(tmp, JSON.stringify(data, null, 2));
172
+ await renameWithRetry(tmp, this.filePath);
173
+ }
174
+
175
+ /** Acquire lock → reload → mutate → save → release. */
176
+ private async withLock<T>(fn: () => T): Promise<T> {
177
+ await this.ensureDir();
178
+ await acquireLock(this.lockPath);
179
+ try {
180
+ await this.load();
181
+ const result = fn();
182
+ await this.save();
183
+ return result;
184
+ } finally {
185
+ await releaseLock(this.lockPath);
186
+ }
187
+ }
188
+
189
+ /** Read-only — returns a snapshot of the in-memory cache. */
190
+ list(): ScheduledSubagent[] {
191
+ return [...this.jobs.values()];
192
+ }
193
+
194
+ /** Read-only check — uses the cache. */
195
+ hasName(name: string, exceptId?: string): boolean {
196
+ for (const j of this.jobs.values()) {
197
+ if (j.id !== exceptId && j.name === name) return true;
198
+ }
199
+ return false;
200
+ }
201
+
202
+ get(id: string): ScheduledSubagent | undefined {
203
+ return this.jobs.get(id);
204
+ }
205
+
206
+ async add(job: ScheduledSubagent): Promise<void> {
207
+ await this.withLock(() => {
208
+ this.jobs.set(job.id, job);
209
+ });
210
+ }
211
+
212
+ /** Atomically re-check the latest committed names and insert only if unique. */
213
+ async addUnlessNameExists(job: ScheduledSubagent): Promise<boolean> {
214
+ return this.withLock(() => {
215
+ if (this.hasName(job.name)) return false;
216
+ this.jobs.set(job.id, job);
217
+ return true;
218
+ });
219
+ }
220
+
221
+ async update(id: string, patch: Partial<ScheduledSubagent>): Promise<ScheduledSubagent | undefined> {
222
+ // No-op fast path — an unknown id changes nothing, so don't lock or touch
223
+ // disk (which would otherwise lazily create the backing directory).
224
+ if (!this.jobs.has(id)) return undefined;
225
+ return this.withLock(() => {
226
+ const existing = this.jobs.get(id);
227
+ if (!existing) return undefined;
228
+ const updated = { ...existing, ...patch };
229
+ this.jobs.set(id, updated);
230
+ return updated;
231
+ });
232
+ }
233
+
234
+ async remove(id: string): Promise<boolean> {
235
+ // No-op fast path — see update().
236
+ if (!this.jobs.has(id)) return false;
237
+ return this.withLock(() => this.jobs.delete(id));
238
+ }
239
+
240
+ /** Delete the backing file (used when no jobs remain, optional cleanup). */
241
+ async deleteFileIfEmpty(): Promise<void> {
242
+ if (this.jobs.size === 0) await unlink(this.filePath).catch(() => undefined);
243
+ }
244
+ }
@@ -0,0 +1,450 @@
1
+ /**
2
+ * schedule.ts — `SubagentScheduler`: timer-driven dispatcher of scheduled subagents.
3
+ *
4
+ * Mirrors the engine shape of pi-cron-schedule/src/scheduler.ts:
5
+ * - two-Map split (jobs = croner Cron, intervals = setInterval/setTimeout)
6
+ * - addJob/removeJob/updateJob/scheduleJob/unscheduleJob/executeJob
7
+ * - static parsers for cron / "+10m" / "5m" / ISO formats
8
+ *
9
+ * Differences vs pi-cron-schedule:
10
+ * - Persistence is via ScheduleStore (PID-locked, session-scoped, atomic).
11
+ * - `executeJob` calls `manager.spawn(..., { bypassQueue: true })` instead
12
+ * of dispatching a user message — schedule fires bypass maxConcurrent so
13
+ * a 5-minute interval can't be deferred behind 4 long-running agents.
14
+ * - Result delivery is implicit: spawn → background completion → existing
15
+ * `subagent-notification` followUp path. No new delivery code.
16
+ */
17
+
18
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
19
+ import { Cron } from "croner";
20
+ import { nanoid } from "nanoid";
21
+ import type { AgentManager } from "./agent-manager.ts";
22
+ import { getAllowPerCallTurnLimits, resolveEffectiveMaxTurns } from "./agent-runner.ts";
23
+ import { resolveSpawnType } from "./agent-types.ts";
24
+ import { resolveModel } from "./model-resolver.ts";
25
+ import type { ScheduleStore } from "./schedule-store.ts";
26
+ import type { IsolationMode, ScheduledSubagent, SubagentType, ThinkingLevel } from "./types.ts";
27
+
28
+ const MAX_TIMER_DELAY_MS = 2_147_483_647;
29
+
30
+ function timerDelayError(delayMs: number): string {
31
+ return `Schedule delay ${delayMs}ms exceeds Node's maximum timer delay of ${MAX_TIMER_DELAY_MS}ms; use a shorter delay.`;
32
+ }
33
+
34
+ function assertSupportedTimerDelay(delayMs: number): void {
35
+ if (delayMs > MAX_TIMER_DELAY_MS) throw new Error(timerDelayError(delayMs));
36
+ }
37
+
38
+ /** Event emitted on `pi.events` for cross-extension consumers. */
39
+ export type ScheduleChangeEvent =
40
+ | { type: "added"; job: ScheduledSubagent }
41
+ | { type: "removed"; jobId: string }
42
+ | { type: "updated"; job: ScheduledSubagent }
43
+ | { type: "fired"; jobId: string; agentId: string; name: string }
44
+ | { type: "skipped"; jobId: string; name: string; reason: "overlap" }
45
+ | { type: "error"; jobId: string; error: string };
46
+
47
+ /** Params accepted at job creation — ID, timestamps, and state are derived. */
48
+ export interface NewJobInput {
49
+ name: string;
50
+ description: string;
51
+ schedule: string;
52
+ subagent_type: SubagentType;
53
+ prompt: string;
54
+ model?: string;
55
+ thinking?: ThinkingLevel;
56
+ max_turns?: number;
57
+ isolated?: boolean;
58
+ isolation?: IsolationMode;
59
+ }
60
+
61
+ export class SubagentScheduler {
62
+ private jobs = new Map<string, Cron>();
63
+ private intervals = new Map<string, NodeJS.Timeout>();
64
+ private activeRuns = new Set<string>();
65
+ private store: ScheduleStore | undefined;
66
+ private pi: ExtensionAPI | undefined;
67
+ private ctx: ExtensionContext | undefined;
68
+ private manager: AgentManager | undefined;
69
+
70
+ /** Start the scheduler: bind to a session's store and arm enabled jobs. */
71
+ start(pi: ExtensionAPI, ctx: ExtensionContext, manager: AgentManager, store: ScheduleStore): void {
72
+ this.pi = pi;
73
+ this.ctx = ctx;
74
+ this.manager = manager;
75
+ this.store = store;
76
+
77
+ for (const job of store.list()) {
78
+ if (job.enabled) this.scheduleJob(job);
79
+ }
80
+ }
81
+
82
+ /** Stop all timers; drop refs. Safe to call repeatedly. */
83
+ stop(): void {
84
+ for (const cron of this.jobs.values()) cron.stop();
85
+ this.jobs.clear();
86
+ for (const t of this.intervals.values()) clearTimeout(t);
87
+ this.intervals.clear();
88
+ this.store = undefined;
89
+ this.pi = undefined;
90
+ this.ctx = undefined;
91
+ this.manager = undefined;
92
+ }
93
+
94
+ /** True if start() has bound a store and the scheduler is active. */
95
+ isActive(): boolean {
96
+ return this.store !== undefined;
97
+ }
98
+
99
+ list(): ScheduledSubagent[] {
100
+ return this.store?.list() ?? [];
101
+ }
102
+
103
+ /**
104
+ * Build a `ScheduledSubagent` from user input. Validates the schedule
105
+ * format and tags `scheduleType`. Throws on invalid input.
106
+ */
107
+ buildJob(input: NewJobInput): ScheduledSubagent {
108
+ const detected = SubagentScheduler.detectSchedule(input.schedule);
109
+ return {
110
+ id: nanoid(10),
111
+ name: input.name,
112
+ description: input.description,
113
+ schedule: detected.normalized,
114
+ scheduleType: detected.type,
115
+ intervalMs: detected.intervalMs,
116
+ subagent_type: input.subagent_type,
117
+ prompt: input.prompt,
118
+ model: input.model,
119
+ thinking: input.thinking,
120
+ max_turns: input.max_turns,
121
+ isolated: input.isolated,
122
+ isolation: input.isolation,
123
+ enabled: true,
124
+ createdAt: new Date().toISOString(),
125
+ runCount: 0,
126
+ };
127
+ }
128
+
129
+ /** Add a job, persist, and arm if enabled. Returns the stored job. */
130
+ async addJob(input: NewJobInput): Promise<ScheduledSubagent> {
131
+ const store = this.requireStore();
132
+ const job = this.buildJob(input);
133
+ const added = await store.addUnlessNameExists(job);
134
+ if (!added) throw new Error(`A scheduled job named "${input.name}" already exists.`);
135
+ if (job.enabled) this.scheduleJob(job);
136
+ this.emit({ type: "added", job });
137
+ return job;
138
+ }
139
+
140
+ async removeJob(id: string): Promise<boolean> {
141
+ const store = this.requireStore();
142
+ if (!store.get(id)) return false;
143
+ this.unscheduleJob(id);
144
+ const ok = await store.remove(id);
145
+ if (ok) this.emit({ type: "removed", jobId: id });
146
+ return ok;
147
+ }
148
+
149
+ /** Toggle / mutate a job. Re-arms based on the new `enabled` state. */
150
+ async updateJob(id: string, patch: Partial<ScheduledSubagent>): Promise<ScheduledSubagent | undefined> {
151
+ const store = this.requireStore();
152
+ const updated = await store.update(id, patch);
153
+ if (!updated) return undefined;
154
+ this.unscheduleJob(id);
155
+ if (updated.enabled) this.scheduleJob(updated);
156
+ this.emit({ type: "updated", job: updated });
157
+ return updated;
158
+ }
159
+
160
+ /** Next-run time as ISO, or undefined if not currently armed. */
161
+ getNextRun(jobId: string): string | undefined {
162
+ const cron = this.jobs.get(jobId);
163
+ if (cron) return cron.nextRun()?.toISOString();
164
+ const job = this.store?.get(jobId);
165
+ if (!job?.enabled) return undefined;
166
+ if (job.scheduleType === "once") return job.schedule;
167
+ if (job.scheduleType === "interval" && job.intervalMs) {
168
+ // Before the first fire there's no `lastRun`, so fall back to "now" —
169
+ // accurate at create time (setInterval was just armed) and within
170
+ // intervalMs of correct in any pre-first-fire view.
171
+ const base = job.lastRun ? new Date(job.lastRun).getTime() : Date.now();
172
+ return new Date(base + job.intervalMs).toISOString();
173
+ }
174
+ return undefined;
175
+ }
176
+
177
+ // ── Scheduling primitives ────────────────────────────────────────────
178
+
179
+ private scheduleJob(job: ScheduledSubagent): void {
180
+ const store = this.store;
181
+ if (!store) return;
182
+ try {
183
+ if (job.scheduleType === "interval" && job.intervalMs) {
184
+ if (job.intervalMs > MAX_TIMER_DELAY_MS) {
185
+ void this.disableJobWithError(job, store, timerDelayError(job.intervalMs)).catch(err => this.reportError(job.id, err));
186
+ return;
187
+ }
188
+ const t = setInterval(() => this.dispatchJob(job.id), job.intervalMs);
189
+ this.intervals.set(job.id, t);
190
+ } else if (job.scheduleType === "once") {
191
+ const target = new Date(job.schedule).getTime();
192
+ const delay = target - Date.now();
193
+ if (delay > MAX_TIMER_DELAY_MS) {
194
+ void this.disableJobWithError(job, store, timerDelayError(delay)).catch(err => this.reportError(job.id, err));
195
+ } else if (delay > 0) {
196
+ const t = setTimeout(() => this.executeOnce(job.id, store).catch(err => this.reportError(job.id, err)), delay);
197
+ this.intervals.set(job.id, t);
198
+ } else {
199
+ // Past timestamp — disable, mark error, never fire
200
+ void this.disableJobWithError(job, store, `Scheduled time ${job.schedule} is in the past`).catch(err => this.reportError(job.id, err));
201
+ }
202
+ } else {
203
+ const cron = new Cron(job.schedule, () => this.dispatchJob(job.id));
204
+ this.jobs.set(job.id, cron);
205
+ }
206
+ } catch (err) {
207
+ this.reportError(job.id, err);
208
+ }
209
+ }
210
+
211
+ private dispatchJob(id: string): Promise<void> {
212
+ return this.executeJob(id).catch(err => this.reportError(id, err));
213
+ }
214
+
215
+ private async executeOnce(id: string, store: ScheduleStore): Promise<void> {
216
+ const execution = this.executeJob(id).catch(err => this.reportError(id, err));
217
+ // Auto-disable after dispatch, without waiting for a long-running agent.
218
+ const updated = await store.update(id, { enabled: false });
219
+ if (updated) this.emit({ type: "updated", job: updated });
220
+ await execution;
221
+ }
222
+
223
+ private async disableJobWithError(job: ScheduledSubagent, store: ScheduleStore, error: string): Promise<void> {
224
+ await store.update(job.id, { enabled: false, lastStatus: "error" });
225
+ this.emit({ type: "error", jobId: job.id, error });
226
+ }
227
+
228
+ private unscheduleJob(id: string): void {
229
+ const cron = this.jobs.get(id);
230
+ if (cron) {
231
+ cron.stop();
232
+ this.jobs.delete(id);
233
+ }
234
+ const t = this.intervals.get(id);
235
+ if (t) {
236
+ clearTimeout(t);
237
+ clearInterval(t);
238
+ this.intervals.delete(id);
239
+ }
240
+ }
241
+
242
+ /**
243
+ * Fire a job: persist running state, spawn (bypassing the concurrency
244
+ * queue), persist completion. The in-memory guard covers the complete run,
245
+ * so persisted `running` state from a previous process never blocks recovery.
246
+ */
247
+ private async executeJob(id: string): Promise<void> {
248
+ const store = this.store;
249
+ const pi = this.pi;
250
+ const ctx = this.ctx;
251
+ const manager = this.manager;
252
+ if (!store || !pi || !ctx || !manager) return;
253
+ const job = store.get(id);
254
+ if (!job?.enabled) return;
255
+ if (this.activeRuns.has(id)) {
256
+ this.emit({ type: "skipped", jobId: id, name: job.name, reason: "overlap" });
257
+ return;
258
+ }
259
+ this.activeRuns.add(id);
260
+
261
+ try {
262
+ await store.update(id, { lastStatus: "running" });
263
+
264
+ // Resolve model at fire time — registry contents may have changed since the
265
+ // job was created (auth added/removed). Fall back silently to spawn-default
266
+ // if resolution fails; the spawn path handles undefined model gracefully.
267
+ let resolvedModel: any | undefined;
268
+ if (job.model) {
269
+ const r = resolveModel(job.model, ctx.modelRegistry);
270
+ if (typeof r !== "string") resolvedModel = r;
271
+ }
272
+
273
+ // Re-resolve at fire time against the registry as it stands. This does not
274
+ // reload from disk (the scheduler has no reason to rebuild process-global
275
+ // state from a timer), so it catches changes that went through /agents or
276
+ // an Agent call — not a file deleted directly from a shell.
277
+ const dispatch = resolveSpawnType(job.subagent_type);
278
+ if (!dispatch.ok) throw new Error(dispatch.message);
279
+ // Caller caps are a policy opt-in. Re-check at fire time rather than
280
+ // trusting the stored job: the switch can change after creation, and a
281
+ // job persisted while caps were allowed must not keep enforcing its cap
282
+ // after the user turns them off. When off, the runner still applies the
283
+ // agent's own or the project's configured budget (passing undefined).
284
+ const forwardedMaxTurns = getAllowPerCallTurnLimits() ? job.max_turns : undefined;
285
+ // Snapshot the budget that will actually be enforced, not the ignored job
286
+ // field — role/default resolution otherwise lives only in the runner and
287
+ // the conversation viewer would report a cap no longer applied.
288
+ const effectiveMaxTurns = resolveEffectiveMaxTurns(dispatch.type, forwardedMaxTurns);
289
+ const agentId = manager.spawn(pi, ctx, dispatch.type, job.prompt, {
290
+ description: job.description,
291
+ isBackground: true,
292
+ bypassQueue: true,
293
+ model: resolvedModel,
294
+ maxTurns: forwardedMaxTurns,
295
+ isolated: job.isolated,
296
+ thinkingLevel: job.thinking,
297
+ isolation: job.isolation,
298
+ // A scheduled run has no tool call to build this, so without it the
299
+ // conversation viewer shows nothing about how the job was configured.
300
+ // The model is left out on purpose: agent-manager fills in the effective
301
+ // one when the session reports it, and naming the pre-session pick here
302
+ // would only be right until then.
303
+ invocation: {
304
+ thinking: job.thinking,
305
+ // Already normalized and resolved for the configured/global fallback;
306
+ // `0` and an ignored stored cap both land as undefined.
307
+ maxTurns: effectiveMaxTurns,
308
+ isolated: job.isolated,
309
+ runInBackground: true,
310
+ isolation: job.isolation,
311
+ },
312
+ });
313
+
314
+ this.emit({ type: "fired", jobId: id, agentId, name: job.name });
315
+
316
+ // AgentManager's promise resolves either way (its .catch returns ""), so we
317
+ // can't infer success/failure from the promise — read record.status instead.
318
+ // Terminal states: completed/steered = success; error/aborted/stopped = error.
319
+ // awaitStartup first: with isolation: "worktree" the run promise only exists
320
+ // once the repo copy is made, and a failed copy rejects here.
321
+ let status: "success" | "error";
322
+ try {
323
+ await manager.awaitStartup(agentId);
324
+ await manager.getRecord(agentId)?.promise;
325
+ const r = manager.getRecord(agentId);
326
+ const failed = r?.status === "error" || r?.status === "aborted" || r?.status === "stopped";
327
+ status = failed ? "error" : "success";
328
+ } catch {
329
+ status = "error";
330
+ }
331
+ await this.finalizeRun(store, id, status);
332
+ } catch (err) {
333
+ await this.recordRunError(store, id, err);
334
+ } finally {
335
+ this.activeRuns.delete(id);
336
+ }
337
+ }
338
+
339
+ private async finalizeRun(store: ScheduleStore, id: string, status: "success" | "error"): Promise<void> {
340
+ const lastRun = new Date().toISOString();
341
+ const current = store.get(id);
342
+ const next = current?.scheduleType === "interval" && current.intervalMs
343
+ ? new Date(new Date(lastRun).getTime() + current.intervalMs).toISOString()
344
+ : this.getNextRun(id);
345
+ await store.update(id, {
346
+ lastRun,
347
+ lastStatus: status,
348
+ runCount: (current?.runCount ?? 0) + 1,
349
+ nextRun: next,
350
+ });
351
+ }
352
+
353
+ private async recordRunError(store: ScheduleStore, id: string, err: unknown): Promise<void> {
354
+ const error = err instanceof Error ? err.message : String(err);
355
+ try {
356
+ await store.update(id, { lastRun: new Date().toISOString(), lastStatus: "error" });
357
+ } catch (persistErr) {
358
+ const detail = persistErr instanceof Error ? persistErr.message : String(persistErr);
359
+ this.emit({ type: "error", jobId: id, error: `${error}; failed to persist schedule status: ${detail}` });
360
+ return;
361
+ }
362
+ this.emit({ type: "error", jobId: id, error });
363
+ }
364
+
365
+ private reportError(id: string, err: unknown): void {
366
+ this.emit({ type: "error", jobId: id, error: err instanceof Error ? err.message : String(err) });
367
+ }
368
+
369
+ private emit(event: ScheduleChangeEvent): void {
370
+ if (this.pi) this.pi.events.emit("subagents:scheduled", event);
371
+ }
372
+
373
+ private requireStore(): ScheduleStore {
374
+ if (!this.store) throw new Error("Scheduler not started — no active session.");
375
+ return this.store;
376
+ }
377
+
378
+ // ── Format detection / parsers (statics — pure) ──────────────────────
379
+
380
+ /**
381
+ * Sniff a schedule string and tag its type. Throws on invalid input.
382
+ * Order matters: relative ("+10m") and interval ("5m") both match digit+unit;
383
+ * relative requires the leading "+" to disambiguate.
384
+ */
385
+ static detectSchedule(s: string): { type: "cron" | "once" | "interval"; intervalMs?: number; normalized: string } {
386
+ const trimmed = s.trim();
387
+ // "+10m" — relative one-shot
388
+ const rel = SubagentScheduler.parseRelativeTime(trimmed);
389
+ if (rel !== null) return { type: "once", normalized: rel };
390
+ // "5m" — interval
391
+ const ivl = SubagentScheduler.parseInterval(trimmed);
392
+ if (ivl !== null) return { type: "interval", intervalMs: ivl, normalized: trimmed };
393
+ // ISO timestamp — one-shot. Reject past timestamps upfront so we never
394
+ // create a dead-on-arrival record (scheduleJob's safety net still catches
395
+ // micro-races from `+0s`-style relatives).
396
+ if (/^\d{4}-\d{2}-\d{2}T/.test(trimmed)) {
397
+ const d = new Date(trimmed);
398
+ if (!Number.isNaN(d.getTime())) {
399
+ const delay = d.getTime() - Date.now();
400
+ if (delay <= 0) {
401
+ throw new Error(`Scheduled time ${d.toISOString()} is in the past.`);
402
+ }
403
+ assertSupportedTimerDelay(delay);
404
+ return { type: "once", normalized: d.toISOString() };
405
+ }
406
+ }
407
+ // Cron — 6-field
408
+ const cronCheck = SubagentScheduler.validateCronExpression(trimmed);
409
+ if (cronCheck.valid) return { type: "cron", normalized: trimmed };
410
+ throw new Error(
411
+ `Invalid schedule "${s}". Use 6-field cron (e.g. "0 0 9 * * 1" — 9am every Monday), interval ("5m"/"1h"), or one-shot ("+10m" / ISO).`
412
+ );
413
+ }
414
+
415
+ /** 6-field cron — 'second minute hour dom month dow'. */
416
+ static validateCronExpression(expr: string): { valid: boolean; error?: string } {
417
+ const fields = expr.trim().split(/\s+/);
418
+ if (fields.length !== 6) {
419
+ return {
420
+ valid: false,
421
+ error: `Cron must have 6 fields (second minute hour dom month dow), got ${fields.length}. Example: "0 0 9 * * 1" for 9am every Monday.`,
422
+ };
423
+ }
424
+ try {
425
+ // Croner validates by construction.
426
+ new Cron(expr, () => {});
427
+ return { valid: true };
428
+ } catch (e) {
429
+ return { valid: false, error: e instanceof Error ? e.message : "Invalid cron expression" };
430
+ }
431
+ }
432
+
433
+ /** "+10s"/"+5m"/"+1h"/"+2d" → ISO timestamp. */
434
+ static parseRelativeTime(s: string): string | null {
435
+ const m = s.match(/^\+(\d+)(s|m|h|d)$/);
436
+ if (!m) return null;
437
+ const ms = parseInt(m[1], 10) * { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 }[m[2] as "s" | "m" | "h" | "d"];
438
+ assertSupportedTimerDelay(ms);
439
+ return new Date(Date.now() + ms).toISOString();
440
+ }
441
+
442
+ /** "10s"/"5m"/"1h"/"2d" → milliseconds. */
443
+ static parseInterval(s: string): number | null {
444
+ const m = s.match(/^(\d+)(s|m|h|d)$/);
445
+ if (!m) return null;
446
+ const ms = parseInt(m[1], 10) * { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 }[m[2] as "s" | "m" | "h" | "d"];
447
+ assertSupportedTimerDelay(ms);
448
+ return ms;
449
+ }
450
+ }