@diousk/pi-subagents-fast 0.20.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.
- package/CHANGELOG.md +808 -0
- package/CONTRIBUTING.md +72 -0
- package/LICENSE +21 -0
- package/README.md +1034 -0
- package/SECURITY.md +95 -0
- package/dist/abortable.d.ts +12 -0
- package/dist/abortable.js +42 -0
- package/dist/agent-color.d.ts +35 -0
- package/dist/agent-color.js +123 -0
- package/dist/agent-file-toggle.d.ts +125 -0
- package/dist/agent-file-toggle.js +260 -0
- package/dist/agent-manager.d.ts +472 -0
- package/dist/agent-manager.js +1338 -0
- package/dist/agent-runner.d.ts +312 -0
- package/dist/agent-runner.js +1034 -0
- package/dist/agent-types.d.ts +119 -0
- package/dist/agent-types.js +286 -0
- package/dist/child-context.d.ts +2 -0
- package/dist/child-context.js +12 -0
- package/dist/context.d.ts +12 -0
- package/dist/context.js +56 -0
- package/dist/cross-extension-rpc.d.ts +66 -0
- package/dist/cross-extension-rpc.js +138 -0
- package/dist/custom-agents.d.ts +54 -0
- package/dist/custom-agents.js +316 -0
- package/dist/default-agents.d.ts +7 -0
- package/dist/default-agents.js +122 -0
- package/dist/enabled-models.d.ts +49 -0
- package/dist/enabled-models.js +145 -0
- package/dist/env.d.ts +6 -0
- package/dist/env.js +28 -0
- package/dist/group-join.d.ts +32 -0
- package/dist/group-join.js +116 -0
- package/dist/index.d.ts +50 -0
- package/dist/index.js +3682 -0
- package/dist/invocation-config.d.ts +107 -0
- package/dist/invocation-config.js +83 -0
- package/dist/memory.d.ts +53 -0
- package/dist/memory.js +165 -0
- package/dist/mention-clone.d.ts +87 -0
- package/dist/mention-clone.js +153 -0
- package/dist/mention.d.ts +81 -0
- package/dist/mention.js +131 -0
- package/dist/model-resolver.d.ts +36 -0
- package/dist/model-resolver.js +95 -0
- package/dist/model-scope.d.ts +49 -0
- package/dist/model-scope.js +48 -0
- package/dist/nested-tools.d.ts +55 -0
- package/dist/nested-tools.js +299 -0
- package/dist/output-file.d.ts +43 -0
- package/dist/output-file.js +142 -0
- package/dist/prompts.d.ts +55 -0
- package/dist/prompts.js +91 -0
- package/dist/schedule-store.d.ts +38 -0
- package/dist/schedule-store.js +155 -0
- package/dist/schedule.d.ts +109 -0
- package/dist/schedule.js +359 -0
- package/dist/settings.d.ts +360 -0
- package/dist/settings.js +251 -0
- package/dist/skill-loader.d.ts +24 -0
- package/dist/skill-loader.js +93 -0
- package/dist/status-note.d.ts +61 -0
- package/dist/status-note.js +85 -0
- package/dist/structured-output.d.ts +61 -0
- package/dist/structured-output.js +112 -0
- package/dist/types.d.ts +371 -0
- package/dist/types.js +5 -0
- package/dist/ui/agent-mention.d.ts +82 -0
- package/dist/ui/agent-mention.js +187 -0
- package/dist/ui/agent-widget.d.ts +219 -0
- package/dist/ui/agent-widget.js +592 -0
- package/dist/ui/conversation-viewer.d.ts +120 -0
- package/dist/ui/conversation-viewer.js +578 -0
- package/dist/ui/fleet-list.d.ts +195 -0
- package/dist/ui/fleet-list.js +471 -0
- package/dist/ui/schedule-menu.d.ts +16 -0
- package/dist/ui/schedule-menu.js +94 -0
- package/dist/ui/select-item.d.ts +27 -0
- package/dist/ui/select-item.js +34 -0
- package/dist/ui/viewer-keys.d.ts +20 -0
- package/dist/ui/viewer-keys.js +17 -0
- package/dist/ui/workflow-card.d.ts +175 -0
- package/dist/ui/workflow-card.js +332 -0
- package/dist/ui/workflow-dialog.d.ts +305 -0
- package/dist/ui/workflow-dialog.js +843 -0
- package/dist/ui/workflow-menu.d.ts +60 -0
- package/dist/ui/workflow-menu.js +147 -0
- package/dist/usage.d.ts +135 -0
- package/dist/usage.js +120 -0
- package/dist/workflow/collisions.d.ts +95 -0
- package/dist/workflow/collisions.js +88 -0
- package/dist/workflow/entry.d.ts +32 -0
- package/dist/workflow/entry.js +29 -0
- package/dist/workflow/host.d.ts +62 -0
- package/dist/workflow/host.js +362 -0
- package/dist/workflow/journal.d.ts +97 -0
- package/dist/workflow/journal.js +120 -0
- package/dist/workflow/json-schema.d.ts +51 -0
- package/dist/workflow/json-schema.js +111 -0
- package/dist/workflow/meta.d.ts +67 -0
- package/dist/workflow/meta.js +317 -0
- package/dist/workflow/progress.d.ts +224 -0
- package/dist/workflow/progress.js +361 -0
- package/dist/workflow/runtime.d.ts +334 -0
- package/dist/workflow/runtime.js +830 -0
- package/dist/workflow/saved.d.ts +90 -0
- package/dist/workflow/saved.js +203 -0
- package/dist/workflow/task.d.ts +136 -0
- package/dist/workflow/task.js +207 -0
- package/dist/workflow/tool-description.d.ts +38 -0
- package/dist/workflow/tool-description.js +199 -0
- package/dist/workflow/worker-source.d.ts +47 -0
- package/dist/workflow/worker-source.js +778 -0
- package/dist/worktree.d.ts +52 -0
- package/dist/worktree.js +164 -0
- package/dist/xml.d.ts +10 -0
- package/dist/xml.js +12 -0
- package/docs/rpc.md +183 -0
- package/docs/workflows.md +437 -0
- package/examples/agent-tool-description.md +42 -0
- package/examples/workflows/compose.js +51 -0
- package/examples/workflows/fan-out-audit.js +47 -0
- package/examples/workflows/gated-fix.js +60 -0
- package/examples/workflows/lib/count-child.js +27 -0
- package/examples/workflows/review-panel.js +63 -0
- package/examples/workflows/structured-findings.js +78 -0
- package/package.json +68 -0
- package/src/abortable.ts +43 -0
- package/src/agent-color.ts +161 -0
- package/src/agent-file-toggle.ts +270 -0
- package/src/agent-manager.ts +1581 -0
- package/src/agent-runner.ts +1286 -0
- package/src/agent-types.ts +346 -0
- package/src/child-context.ts +15 -0
- package/src/context.ts +58 -0
- package/src/cross-extension-rpc.ts +198 -0
- package/src/custom-agents.ts +333 -0
- package/src/default-agents.ts +126 -0
- package/src/enabled-models.ts +180 -0
- package/src/env.ts +33 -0
- package/src/group-join.ts +141 -0
- package/src/index.ts +3991 -0
- package/src/invocation-config.ts +155 -0
- package/src/memory.ts +179 -0
- package/src/mention-clone.ts +196 -0
- package/src/mention.ts +141 -0
- package/src/model-resolver.ts +118 -0
- package/src/model-scope.ts +70 -0
- package/src/nested-tools.ts +422 -0
- package/src/output-file.ts +155 -0
- package/src/prompts.ts +142 -0
- package/src/schedule-store.ts +153 -0
- package/src/schedule.ts +386 -0
- package/src/settings.ts +587 -0
- package/src/skill-loader.ts +102 -0
- package/src/status-note.ts +90 -0
- package/src/structured-output.ts +130 -0
- package/src/types.ts +384 -0
- package/src/ui/agent-mention.ts +216 -0
- package/src/ui/agent-widget.ts +664 -0
- package/src/ui/conversation-viewer.ts +589 -0
- package/src/ui/fleet-list.ts +543 -0
- package/src/ui/schedule-menu.ts +105 -0
- package/src/ui/select-item.ts +45 -0
- package/src/ui/viewer-keys.ts +39 -0
- package/src/ui/workflow-card.ts +470 -0
- package/src/ui/workflow-dialog.ts +1115 -0
- package/src/ui/workflow-menu.ts +193 -0
- package/src/usage.ts +167 -0
- package/src/workflow/collisions.ts +123 -0
- package/src/workflow/entry.ts +47 -0
- package/src/workflow/host.ts +403 -0
- package/src/workflow/journal.ts +164 -0
- package/src/workflow/json-schema.ts +128 -0
- package/src/workflow/meta.ts +325 -0
- package/src/workflow/progress.ts +550 -0
- package/src/workflow/runtime.ts +1219 -0
- package/src/workflow/saved.ts +217 -0
- package/src/workflow/task.ts +302 -0
- package/src/workflow/tool-description.ts +200 -0
- package/src/workflow/worker-source.ts +781 -0
- package/src/worktree.ts +205 -0
- package/src/xml.ts +13 -0
package/src/schedule.ts
ADDED
|
@@ -0,0 +1,386 @@
|
|
|
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.js";
|
|
22
|
+
import { normalizeMaxTurns } from "./agent-runner.js";
|
|
23
|
+
import { resolveSpawnType } from "./agent-types.js";
|
|
24
|
+
import { resolveModel } from "./model-resolver.js";
|
|
25
|
+
import type { ScheduleStore } from "./schedule-store.js";
|
|
26
|
+
import type { IsolationMode, ScheduledSubagent, SubagentType, ThinkingLevel } from "./types.js";
|
|
27
|
+
|
|
28
|
+
/** Event emitted on `pi.events` for cross-extension consumers. */
|
|
29
|
+
export type ScheduleChangeEvent =
|
|
30
|
+
| { type: "added"; job: ScheduledSubagent }
|
|
31
|
+
| { type: "removed"; jobId: string }
|
|
32
|
+
| { type: "updated"; job: ScheduledSubagent }
|
|
33
|
+
| { type: "fired"; jobId: string; agentId: string; name: string }
|
|
34
|
+
| { type: "error"; jobId: string; error: string };
|
|
35
|
+
|
|
36
|
+
/** Params accepted at job creation — ID, timestamps, and state are derived. */
|
|
37
|
+
export interface NewJobInput {
|
|
38
|
+
name: string;
|
|
39
|
+
description: string;
|
|
40
|
+
schedule: string;
|
|
41
|
+
subagent_type: SubagentType;
|
|
42
|
+
prompt: string;
|
|
43
|
+
model?: string;
|
|
44
|
+
thinking?: ThinkingLevel;
|
|
45
|
+
max_turns?: number;
|
|
46
|
+
isolated?: boolean;
|
|
47
|
+
isolation?: IsolationMode;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export class SubagentScheduler {
|
|
51
|
+
private jobs = new Map<string, Cron>();
|
|
52
|
+
private intervals = new Map<string, NodeJS.Timeout>();
|
|
53
|
+
private store: ScheduleStore | undefined;
|
|
54
|
+
private pi: ExtensionAPI | undefined;
|
|
55
|
+
private ctx: ExtensionContext | undefined;
|
|
56
|
+
private manager: AgentManager | undefined;
|
|
57
|
+
|
|
58
|
+
/** Start the scheduler: bind to a session's store and arm enabled jobs. */
|
|
59
|
+
start(pi: ExtensionAPI, ctx: ExtensionContext, manager: AgentManager, store: ScheduleStore): void {
|
|
60
|
+
this.pi = pi;
|
|
61
|
+
this.ctx = ctx;
|
|
62
|
+
this.manager = manager;
|
|
63
|
+
this.store = store;
|
|
64
|
+
|
|
65
|
+
for (const job of store.list()) {
|
|
66
|
+
if (job.enabled) this.scheduleJob(job);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Stop all timers; drop refs. Safe to call repeatedly. */
|
|
71
|
+
stop(): void {
|
|
72
|
+
for (const cron of this.jobs.values()) cron.stop();
|
|
73
|
+
this.jobs.clear();
|
|
74
|
+
for (const t of this.intervals.values()) clearTimeout(t);
|
|
75
|
+
this.intervals.clear();
|
|
76
|
+
this.store = undefined;
|
|
77
|
+
this.pi = undefined;
|
|
78
|
+
this.ctx = undefined;
|
|
79
|
+
this.manager = undefined;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** True if start() has bound a store and the scheduler is active. */
|
|
83
|
+
isActive(): boolean {
|
|
84
|
+
return this.store !== undefined;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
list(): ScheduledSubagent[] {
|
|
88
|
+
return this.store?.list() ?? [];
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Build a `ScheduledSubagent` from user input. Validates the schedule
|
|
93
|
+
* format and tags `scheduleType`. Throws on invalid input.
|
|
94
|
+
*/
|
|
95
|
+
buildJob(input: NewJobInput): ScheduledSubagent {
|
|
96
|
+
const detected = SubagentScheduler.detectSchedule(input.schedule);
|
|
97
|
+
return {
|
|
98
|
+
id: nanoid(10),
|
|
99
|
+
name: input.name,
|
|
100
|
+
description: input.description,
|
|
101
|
+
schedule: detected.normalized,
|
|
102
|
+
scheduleType: detected.type,
|
|
103
|
+
intervalMs: detected.intervalMs,
|
|
104
|
+
subagent_type: input.subagent_type,
|
|
105
|
+
prompt: input.prompt,
|
|
106
|
+
model: input.model,
|
|
107
|
+
thinking: input.thinking,
|
|
108
|
+
max_turns: input.max_turns,
|
|
109
|
+
isolated: input.isolated,
|
|
110
|
+
isolation: input.isolation,
|
|
111
|
+
enabled: true,
|
|
112
|
+
createdAt: new Date().toISOString(),
|
|
113
|
+
runCount: 0,
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Add a job, persist, and arm if enabled. Returns the stored job. */
|
|
118
|
+
addJob(input: NewJobInput): ScheduledSubagent {
|
|
119
|
+
const store = this.requireStore();
|
|
120
|
+
if (store.hasName(input.name)) {
|
|
121
|
+
throw new Error(`A scheduled job named "${input.name}" already exists.`);
|
|
122
|
+
}
|
|
123
|
+
const job = this.buildJob(input);
|
|
124
|
+
store.add(job);
|
|
125
|
+
if (job.enabled) this.scheduleJob(job);
|
|
126
|
+
this.emit({ type: "added", job });
|
|
127
|
+
return job;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
removeJob(id: string): boolean {
|
|
131
|
+
const store = this.requireStore();
|
|
132
|
+
if (!store.get(id)) return false;
|
|
133
|
+
this.unscheduleJob(id);
|
|
134
|
+
const ok = store.remove(id);
|
|
135
|
+
if (ok) this.emit({ type: "removed", jobId: id });
|
|
136
|
+
return ok;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Toggle / mutate a job. Re-arms based on the new `enabled` state. */
|
|
140
|
+
updateJob(id: string, patch: Partial<ScheduledSubagent>): ScheduledSubagent | undefined {
|
|
141
|
+
const store = this.requireStore();
|
|
142
|
+
const updated = store.update(id, patch);
|
|
143
|
+
if (!updated) return undefined;
|
|
144
|
+
this.unscheduleJob(id);
|
|
145
|
+
if (updated.enabled) this.scheduleJob(updated);
|
|
146
|
+
this.emit({ type: "updated", job: updated });
|
|
147
|
+
return updated;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Next-run time as ISO, or undefined if not currently armed. */
|
|
151
|
+
getNextRun(jobId: string): string | undefined {
|
|
152
|
+
const cron = this.jobs.get(jobId);
|
|
153
|
+
if (cron) return cron.nextRun()?.toISOString();
|
|
154
|
+
const job = this.store?.get(jobId);
|
|
155
|
+
if (!job?.enabled) return undefined;
|
|
156
|
+
if (job.scheduleType === "once") return job.schedule;
|
|
157
|
+
if (job.scheduleType === "interval" && job.intervalMs) {
|
|
158
|
+
// Before the first fire there's no `lastRun`, so fall back to "now" —
|
|
159
|
+
// accurate at create time (setInterval was just armed) and within
|
|
160
|
+
// intervalMs of correct in any pre-first-fire view.
|
|
161
|
+
const base = job.lastRun ? new Date(job.lastRun).getTime() : Date.now();
|
|
162
|
+
return new Date(base + job.intervalMs).toISOString();
|
|
163
|
+
}
|
|
164
|
+
return undefined;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// ── Scheduling primitives ────────────────────────────────────────────
|
|
168
|
+
|
|
169
|
+
private scheduleJob(job: ScheduledSubagent): void {
|
|
170
|
+
const store = this.store;
|
|
171
|
+
if (!store) return;
|
|
172
|
+
try {
|
|
173
|
+
if (job.scheduleType === "interval" && job.intervalMs) {
|
|
174
|
+
const t = setInterval(() => this.executeJob(job.id), job.intervalMs);
|
|
175
|
+
this.intervals.set(job.id, t);
|
|
176
|
+
} else if (job.scheduleType === "once") {
|
|
177
|
+
const target = new Date(job.schedule).getTime();
|
|
178
|
+
const delay = target - Date.now();
|
|
179
|
+
if (delay > 0) {
|
|
180
|
+
const t = setTimeout(() => {
|
|
181
|
+
this.executeJob(job.id);
|
|
182
|
+
// Auto-disable one-shots after they fire (mirrors pi-cron-schedule)
|
|
183
|
+
store.update(job.id, { enabled: false });
|
|
184
|
+
const updated = store.get(job.id);
|
|
185
|
+
if (updated) this.emit({ type: "updated", job: updated });
|
|
186
|
+
}, delay);
|
|
187
|
+
this.intervals.set(job.id, t);
|
|
188
|
+
} else {
|
|
189
|
+
// Past timestamp — disable, mark error, never fire
|
|
190
|
+
store.update(job.id, { enabled: false, lastStatus: "error" });
|
|
191
|
+
this.emit({ type: "error", jobId: job.id, error: `Scheduled time ${job.schedule} is in the past` });
|
|
192
|
+
}
|
|
193
|
+
} else {
|
|
194
|
+
const cron = new Cron(job.schedule, () => this.executeJob(job.id));
|
|
195
|
+
this.jobs.set(job.id, cron);
|
|
196
|
+
}
|
|
197
|
+
} catch (err) {
|
|
198
|
+
this.emit({ type: "error", jobId: job.id, error: err instanceof Error ? err.message : String(err) });
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
private unscheduleJob(id: string): void {
|
|
203
|
+
const cron = this.jobs.get(id);
|
|
204
|
+
if (cron) {
|
|
205
|
+
cron.stop();
|
|
206
|
+
this.jobs.delete(id);
|
|
207
|
+
}
|
|
208
|
+
const t = this.intervals.get(id);
|
|
209
|
+
if (t) {
|
|
210
|
+
clearTimeout(t);
|
|
211
|
+
clearInterval(t);
|
|
212
|
+
this.intervals.delete(id);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Fire a job: persist running state, spawn (bypassing the concurrency
|
|
218
|
+
* queue), persist completion. Fire-and-forget: the timer tick returns
|
|
219
|
+
* immediately so other jobs keep firing.
|
|
220
|
+
*/
|
|
221
|
+
private executeJob(id: string): void {
|
|
222
|
+
const store = this.store;
|
|
223
|
+
const pi = this.pi;
|
|
224
|
+
const ctx = this.ctx;
|
|
225
|
+
const manager = this.manager;
|
|
226
|
+
if (!store || !pi || !ctx || !manager) return;
|
|
227
|
+
const job = store.get(id);
|
|
228
|
+
if (!job?.enabled) return;
|
|
229
|
+
|
|
230
|
+
store.update(id, { lastStatus: "running" });
|
|
231
|
+
|
|
232
|
+
// Resolve model at fire time — registry contents may have changed since the
|
|
233
|
+
// job was created (auth added/removed). Fall back silently to spawn-default
|
|
234
|
+
// if resolution fails; the spawn path handles undefined model gracefully.
|
|
235
|
+
let resolvedModel: any | undefined;
|
|
236
|
+
if (job.model) {
|
|
237
|
+
const r = resolveModel(job.model, ctx.modelRegistry);
|
|
238
|
+
if (typeof r !== "string") resolvedModel = r;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
let agentId: string;
|
|
242
|
+
try {
|
|
243
|
+
// Re-resolve at fire time against the registry as it stands. This does not
|
|
244
|
+
// reload from disk (the scheduler has no reason to rebuild process-global
|
|
245
|
+
// state from a timer), so it catches changes that went through /agents or
|
|
246
|
+
// an Agent call — not a file deleted directly from a shell. The catch below turns
|
|
247
|
+
// this into lastStatus: "error" plus an error event, like any other
|
|
248
|
+
// fire-time failure.
|
|
249
|
+
const dispatch = resolveSpawnType(job.subagent_type);
|
|
250
|
+
if (!dispatch.ok) throw new Error(dispatch.message);
|
|
251
|
+
agentId = manager.spawn(pi, ctx, dispatch.type, job.prompt, {
|
|
252
|
+
description: job.description,
|
|
253
|
+
isBackground: true,
|
|
254
|
+
bypassQueue: true,
|
|
255
|
+
model: resolvedModel,
|
|
256
|
+
maxTurns: job.max_turns,
|
|
257
|
+
isolated: job.isolated,
|
|
258
|
+
thinkingLevel: job.thinking,
|
|
259
|
+
isolation: job.isolation,
|
|
260
|
+
// A scheduled run has no tool call to build this, so without it the
|
|
261
|
+
// conversation viewer shows nothing about how the job was configured.
|
|
262
|
+
// The model is left out on purpose: agent-manager fills in the effective
|
|
263
|
+
// one when the session reports it, and naming the pre-session pick here
|
|
264
|
+
// would only be right until then.
|
|
265
|
+
invocation: {
|
|
266
|
+
thinking: job.thinking,
|
|
267
|
+
// Normalized like the Agent tool's own snapshot: `0` means unlimited,
|
|
268
|
+
// and rendering it as "max turns: 0" would read as a limit of none.
|
|
269
|
+
maxTurns: normalizeMaxTurns(job.max_turns),
|
|
270
|
+
isolated: job.isolated,
|
|
271
|
+
runInBackground: true,
|
|
272
|
+
isolation: job.isolation,
|
|
273
|
+
},
|
|
274
|
+
});
|
|
275
|
+
} catch (err) {
|
|
276
|
+
const error = err instanceof Error ? err.message : String(err);
|
|
277
|
+
store.update(id, { lastRun: new Date().toISOString(), lastStatus: "error" });
|
|
278
|
+
this.emit({ type: "error", jobId: id, error });
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
this.emit({ type: "fired", jobId: id, agentId, name: job.name });
|
|
283
|
+
|
|
284
|
+
const finalize = (status: "success" | "error") => {
|
|
285
|
+
const next = this.getNextRun(id);
|
|
286
|
+
const current = store.get(id);
|
|
287
|
+
store.update(id, {
|
|
288
|
+
lastRun: new Date().toISOString(),
|
|
289
|
+
lastStatus: status,
|
|
290
|
+
runCount: (current?.runCount ?? 0) + 1,
|
|
291
|
+
nextRun: next,
|
|
292
|
+
});
|
|
293
|
+
};
|
|
294
|
+
|
|
295
|
+
// AgentManager's promise resolves either way (its .catch returns ""), so we
|
|
296
|
+
// can't infer success/failure from the promise — read record.status instead.
|
|
297
|
+
// Terminal states: completed/steered = success; error/aborted/stopped = error.
|
|
298
|
+
// awaitStartup first: with isolation: "worktree" the run promise only exists
|
|
299
|
+
// once the repo copy is made, and a failed copy rejects here.
|
|
300
|
+
manager.awaitStartup(agentId)
|
|
301
|
+
.then(() => manager.getRecord(agentId)?.promise)
|
|
302
|
+
.then(() => {
|
|
303
|
+
const r = manager.getRecord(agentId);
|
|
304
|
+
const failed = r?.status === "error" || r?.status === "aborted" || r?.status === "stopped";
|
|
305
|
+
finalize(failed ? "error" : "success");
|
|
306
|
+
})
|
|
307
|
+
.catch(() => finalize("error"));
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
private emit(event: ScheduleChangeEvent): void {
|
|
311
|
+
if (this.pi) this.pi.events.emit("subagents:scheduled", event);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
private requireStore(): ScheduleStore {
|
|
315
|
+
if (!this.store) throw new Error("Scheduler not started — no active session.");
|
|
316
|
+
return this.store;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// ── Format detection / parsers (statics — pure) ──────────────────────
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Sniff a schedule string and tag its type. Throws on invalid input.
|
|
323
|
+
* Order matters: relative ("+10m") and interval ("5m") both match digit+unit;
|
|
324
|
+
* relative requires the leading "+" to disambiguate.
|
|
325
|
+
*/
|
|
326
|
+
static detectSchedule(s: string): { type: "cron" | "once" | "interval"; intervalMs?: number; normalized: string } {
|
|
327
|
+
const trimmed = s.trim();
|
|
328
|
+
// "+10m" — relative one-shot
|
|
329
|
+
const rel = SubagentScheduler.parseRelativeTime(trimmed);
|
|
330
|
+
if (rel !== null) return { type: "once", normalized: rel };
|
|
331
|
+
// "5m" — interval
|
|
332
|
+
const ivl = SubagentScheduler.parseInterval(trimmed);
|
|
333
|
+
if (ivl !== null) return { type: "interval", intervalMs: ivl, normalized: trimmed };
|
|
334
|
+
// ISO timestamp — one-shot. Reject past timestamps upfront so we never
|
|
335
|
+
// create a dead-on-arrival record (scheduleJob's safety net still catches
|
|
336
|
+
// micro-races from `+0s`-style relatives).
|
|
337
|
+
if (/^\d{4}-\d{2}-\d{2}T/.test(trimmed)) {
|
|
338
|
+
const d = new Date(trimmed);
|
|
339
|
+
if (!Number.isNaN(d.getTime())) {
|
|
340
|
+
if (d.getTime() <= Date.now()) {
|
|
341
|
+
throw new Error(`Scheduled time ${d.toISOString()} is in the past.`);
|
|
342
|
+
}
|
|
343
|
+
return { type: "once", normalized: d.toISOString() };
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
// Cron — 6-field
|
|
347
|
+
const cronCheck = SubagentScheduler.validateCronExpression(trimmed);
|
|
348
|
+
if (cronCheck.valid) return { type: "cron", normalized: trimmed };
|
|
349
|
+
throw new Error(
|
|
350
|
+
`Invalid schedule "${s}". Use 6-field cron (e.g. "0 0 9 * * 1" — 9am every Monday), interval ("5m"/"1h"), or one-shot ("+10m" / ISO).`
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** 6-field cron — 'second minute hour dom month dow'. */
|
|
355
|
+
static validateCronExpression(expr: string): { valid: boolean; error?: string } {
|
|
356
|
+
const fields = expr.trim().split(/\s+/);
|
|
357
|
+
if (fields.length !== 6) {
|
|
358
|
+
return {
|
|
359
|
+
valid: false,
|
|
360
|
+
error: `Cron must have 6 fields (second minute hour dom month dow), got ${fields.length}. Example: "0 0 9 * * 1" for 9am every Monday.`,
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
try {
|
|
364
|
+
// Croner validates by construction.
|
|
365
|
+
new Cron(expr, () => {});
|
|
366
|
+
return { valid: true };
|
|
367
|
+
} catch (e) {
|
|
368
|
+
return { valid: false, error: e instanceof Error ? e.message : "Invalid cron expression" };
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** "+10s"/"+5m"/"+1h"/"+2d" → ISO timestamp. */
|
|
373
|
+
static parseRelativeTime(s: string): string | null {
|
|
374
|
+
const m = s.match(/^\+(\d+)(s|m|h|d)$/);
|
|
375
|
+
if (!m) return null;
|
|
376
|
+
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"];
|
|
377
|
+
return new Date(Date.now() + ms).toISOString();
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** "10s"/"5m"/"1h"/"2d" → milliseconds. */
|
|
381
|
+
static parseInterval(s: string): number | null {
|
|
382
|
+
const m = s.match(/^(\d+)(s|m|h|d)$/);
|
|
383
|
+
if (!m) return null;
|
|
384
|
+
return parseInt(m[1], 10) * { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 }[m[2] as "s" | "m" | "h" | "d"];
|
|
385
|
+
}
|
|
386
|
+
}
|