@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
|
@@ -0,0 +1,38 @@
|
|
|
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
|
+
import type { ScheduledSubagent } from "./types.js";
|
|
13
|
+
/** Resolve the storage path for a session-scoped store. */
|
|
14
|
+
export declare function resolveStorePath(cwd: string, sessionId: string): string;
|
|
15
|
+
export declare class ScheduleStore {
|
|
16
|
+
private filePath;
|
|
17
|
+
private lockPath;
|
|
18
|
+
private jobs;
|
|
19
|
+
constructor(filePath: string);
|
|
20
|
+
/** Create the backing directory lazily — only when we're about to persist. */
|
|
21
|
+
private ensureDir;
|
|
22
|
+
/** Load from disk into the in-memory cache. Silent on parse errors. */
|
|
23
|
+
private load;
|
|
24
|
+
/** Atomic write via temp file + rename (POSIX-atomic). */
|
|
25
|
+
private save;
|
|
26
|
+
/** Acquire lock → reload → mutate → save → release. */
|
|
27
|
+
private withLock;
|
|
28
|
+
/** Read-only — returns a snapshot of the in-memory cache. */
|
|
29
|
+
list(): ScheduledSubagent[];
|
|
30
|
+
/** Read-only check — uses the cache. */
|
|
31
|
+
hasName(name: string, exceptId?: string): boolean;
|
|
32
|
+
get(id: string): ScheduledSubagent | undefined;
|
|
33
|
+
add(job: ScheduledSubagent): void;
|
|
34
|
+
update(id: string, patch: Partial<ScheduledSubagent>): ScheduledSubagent | undefined;
|
|
35
|
+
remove(id: string): boolean;
|
|
36
|
+
/** Delete the backing file (used when no jobs remain, optional cleanup). */
|
|
37
|
+
deleteFileIfEmpty(): void;
|
|
38
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
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
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
13
|
+
import { dirname, join } from "node:path";
|
|
14
|
+
const LOCK_RETRY_MS = 50;
|
|
15
|
+
const LOCK_MAX_RETRIES = 100;
|
|
16
|
+
function isProcessRunning(pid) {
|
|
17
|
+
try {
|
|
18
|
+
process.kill(pid, 0);
|
|
19
|
+
return true;
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function acquireLock(lockPath) {
|
|
26
|
+
for (let i = 0; i < LOCK_MAX_RETRIES; i++) {
|
|
27
|
+
try {
|
|
28
|
+
writeFileSync(lockPath, `${process.pid}`, { flag: "wx" });
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
catch (e) {
|
|
32
|
+
if (e.code === "EEXIST") {
|
|
33
|
+
try {
|
|
34
|
+
const pid = parseInt(readFileSync(lockPath, "utf-8"), 10);
|
|
35
|
+
if (pid && !isProcessRunning(pid)) {
|
|
36
|
+
unlinkSync(lockPath);
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
catch { /* ignore — try again */ }
|
|
41
|
+
const start = Date.now();
|
|
42
|
+
while (Date.now() - start < LOCK_RETRY_MS) { /* busy wait */ }
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
throw e;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
throw new Error(`Failed to acquire schedule lock: ${lockPath}`);
|
|
49
|
+
}
|
|
50
|
+
function releaseLock(lockPath) {
|
|
51
|
+
try {
|
|
52
|
+
unlinkSync(lockPath);
|
|
53
|
+
}
|
|
54
|
+
catch { /* ignore */ }
|
|
55
|
+
}
|
|
56
|
+
/** Resolve the storage path for a session-scoped store. */
|
|
57
|
+
export function resolveStorePath(cwd, sessionId) {
|
|
58
|
+
return join(cwd, ".pi", "subagent-schedules", `${sessionId}.json`);
|
|
59
|
+
}
|
|
60
|
+
export class ScheduleStore {
|
|
61
|
+
filePath;
|
|
62
|
+
lockPath;
|
|
63
|
+
jobs = new Map();
|
|
64
|
+
constructor(filePath) {
|
|
65
|
+
this.filePath = filePath;
|
|
66
|
+
this.lockPath = filePath + ".lock";
|
|
67
|
+
this.load();
|
|
68
|
+
}
|
|
69
|
+
/** Create the backing directory lazily — only when we're about to persist. */
|
|
70
|
+
ensureDir() {
|
|
71
|
+
mkdirSync(dirname(this.filePath), { recursive: true });
|
|
72
|
+
}
|
|
73
|
+
/** Load from disk into the in-memory cache. Silent on parse errors. */
|
|
74
|
+
load() {
|
|
75
|
+
if (!existsSync(this.filePath))
|
|
76
|
+
return;
|
|
77
|
+
try {
|
|
78
|
+
const data = JSON.parse(readFileSync(this.filePath, "utf-8"));
|
|
79
|
+
this.jobs.clear();
|
|
80
|
+
for (const j of data.jobs ?? [])
|
|
81
|
+
this.jobs.set(j.id, j);
|
|
82
|
+
}
|
|
83
|
+
catch { /* corrupt — start fresh, next save rewrites */ }
|
|
84
|
+
}
|
|
85
|
+
/** Atomic write via temp file + rename (POSIX-atomic). */
|
|
86
|
+
save() {
|
|
87
|
+
const data = { version: 1, jobs: [...this.jobs.values()] };
|
|
88
|
+
const tmp = this.filePath + ".tmp";
|
|
89
|
+
writeFileSync(tmp, JSON.stringify(data, null, 2));
|
|
90
|
+
renameSync(tmp, this.filePath);
|
|
91
|
+
}
|
|
92
|
+
/** Acquire lock → reload → mutate → save → release. */
|
|
93
|
+
withLock(fn) {
|
|
94
|
+
this.ensureDir();
|
|
95
|
+
acquireLock(this.lockPath);
|
|
96
|
+
try {
|
|
97
|
+
this.load();
|
|
98
|
+
const result = fn();
|
|
99
|
+
this.save();
|
|
100
|
+
return result;
|
|
101
|
+
}
|
|
102
|
+
finally {
|
|
103
|
+
releaseLock(this.lockPath);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/** Read-only — returns a snapshot of the in-memory cache. */
|
|
107
|
+
list() {
|
|
108
|
+
return [...this.jobs.values()];
|
|
109
|
+
}
|
|
110
|
+
/** Read-only check — uses the cache. */
|
|
111
|
+
hasName(name, exceptId) {
|
|
112
|
+
for (const j of this.jobs.values()) {
|
|
113
|
+
if (j.id !== exceptId && j.name === name)
|
|
114
|
+
return true;
|
|
115
|
+
}
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
get(id) {
|
|
119
|
+
return this.jobs.get(id);
|
|
120
|
+
}
|
|
121
|
+
add(job) {
|
|
122
|
+
this.withLock(() => {
|
|
123
|
+
this.jobs.set(job.id, job);
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
update(id, patch) {
|
|
127
|
+
// No-op fast path — an unknown id changes nothing, so don't lock or touch
|
|
128
|
+
// disk (which would otherwise lazily create the backing directory).
|
|
129
|
+
if (!this.jobs.has(id))
|
|
130
|
+
return undefined;
|
|
131
|
+
return this.withLock(() => {
|
|
132
|
+
const existing = this.jobs.get(id);
|
|
133
|
+
if (!existing)
|
|
134
|
+
return undefined;
|
|
135
|
+
const updated = { ...existing, ...patch };
|
|
136
|
+
this.jobs.set(id, updated);
|
|
137
|
+
return updated;
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
remove(id) {
|
|
141
|
+
// No-op fast path — see update().
|
|
142
|
+
if (!this.jobs.has(id))
|
|
143
|
+
return false;
|
|
144
|
+
return this.withLock(() => this.jobs.delete(id));
|
|
145
|
+
}
|
|
146
|
+
/** Delete the backing file (used when no jobs remain, optional cleanup). */
|
|
147
|
+
deleteFileIfEmpty() {
|
|
148
|
+
if (this.jobs.size === 0 && existsSync(this.filePath)) {
|
|
149
|
+
try {
|
|
150
|
+
unlinkSync(this.filePath);
|
|
151
|
+
}
|
|
152
|
+
catch { /* ignore */ }
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
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
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
18
|
+
import type { AgentManager } from "./agent-manager.js";
|
|
19
|
+
import type { ScheduleStore } from "./schedule-store.js";
|
|
20
|
+
import type { IsolationMode, ScheduledSubagent, SubagentType, ThinkingLevel } from "./types.js";
|
|
21
|
+
/** Event emitted on `pi.events` for cross-extension consumers. */
|
|
22
|
+
export type ScheduleChangeEvent = {
|
|
23
|
+
type: "added";
|
|
24
|
+
job: ScheduledSubagent;
|
|
25
|
+
} | {
|
|
26
|
+
type: "removed";
|
|
27
|
+
jobId: string;
|
|
28
|
+
} | {
|
|
29
|
+
type: "updated";
|
|
30
|
+
job: ScheduledSubagent;
|
|
31
|
+
} | {
|
|
32
|
+
type: "fired";
|
|
33
|
+
jobId: string;
|
|
34
|
+
agentId: string;
|
|
35
|
+
name: string;
|
|
36
|
+
} | {
|
|
37
|
+
type: "error";
|
|
38
|
+
jobId: string;
|
|
39
|
+
error: string;
|
|
40
|
+
};
|
|
41
|
+
/** Params accepted at job creation — ID, timestamps, and state are derived. */
|
|
42
|
+
export interface NewJobInput {
|
|
43
|
+
name: string;
|
|
44
|
+
description: string;
|
|
45
|
+
schedule: string;
|
|
46
|
+
subagent_type: SubagentType;
|
|
47
|
+
prompt: string;
|
|
48
|
+
model?: string;
|
|
49
|
+
thinking?: ThinkingLevel;
|
|
50
|
+
max_turns?: number;
|
|
51
|
+
isolated?: boolean;
|
|
52
|
+
isolation?: IsolationMode;
|
|
53
|
+
}
|
|
54
|
+
export declare class SubagentScheduler {
|
|
55
|
+
private jobs;
|
|
56
|
+
private intervals;
|
|
57
|
+
private store;
|
|
58
|
+
private pi;
|
|
59
|
+
private ctx;
|
|
60
|
+
private manager;
|
|
61
|
+
/** Start the scheduler: bind to a session's store and arm enabled jobs. */
|
|
62
|
+
start(pi: ExtensionAPI, ctx: ExtensionContext, manager: AgentManager, store: ScheduleStore): void;
|
|
63
|
+
/** Stop all timers; drop refs. Safe to call repeatedly. */
|
|
64
|
+
stop(): void;
|
|
65
|
+
/** True if start() has bound a store and the scheduler is active. */
|
|
66
|
+
isActive(): boolean;
|
|
67
|
+
list(): ScheduledSubagent[];
|
|
68
|
+
/**
|
|
69
|
+
* Build a `ScheduledSubagent` from user input. Validates the schedule
|
|
70
|
+
* format and tags `scheduleType`. Throws on invalid input.
|
|
71
|
+
*/
|
|
72
|
+
buildJob(input: NewJobInput): ScheduledSubagent;
|
|
73
|
+
/** Add a job, persist, and arm if enabled. Returns the stored job. */
|
|
74
|
+
addJob(input: NewJobInput): ScheduledSubagent;
|
|
75
|
+
removeJob(id: string): boolean;
|
|
76
|
+
/** Toggle / mutate a job. Re-arms based on the new `enabled` state. */
|
|
77
|
+
updateJob(id: string, patch: Partial<ScheduledSubagent>): ScheduledSubagent | undefined;
|
|
78
|
+
/** Next-run time as ISO, or undefined if not currently armed. */
|
|
79
|
+
getNextRun(jobId: string): string | undefined;
|
|
80
|
+
private scheduleJob;
|
|
81
|
+
private unscheduleJob;
|
|
82
|
+
/**
|
|
83
|
+
* Fire a job: persist running state, spawn (bypassing the concurrency
|
|
84
|
+
* queue), persist completion. Fire-and-forget: the timer tick returns
|
|
85
|
+
* immediately so other jobs keep firing.
|
|
86
|
+
*/
|
|
87
|
+
private executeJob;
|
|
88
|
+
private emit;
|
|
89
|
+
private requireStore;
|
|
90
|
+
/**
|
|
91
|
+
* Sniff a schedule string and tag its type. Throws on invalid input.
|
|
92
|
+
* Order matters: relative ("+10m") and interval ("5m") both match digit+unit;
|
|
93
|
+
* relative requires the leading "+" to disambiguate.
|
|
94
|
+
*/
|
|
95
|
+
static detectSchedule(s: string): {
|
|
96
|
+
type: "cron" | "once" | "interval";
|
|
97
|
+
intervalMs?: number;
|
|
98
|
+
normalized: string;
|
|
99
|
+
};
|
|
100
|
+
/** 6-field cron — 'second minute hour dom month dow'. */
|
|
101
|
+
static validateCronExpression(expr: string): {
|
|
102
|
+
valid: boolean;
|
|
103
|
+
error?: string;
|
|
104
|
+
};
|
|
105
|
+
/** "+10s"/"+5m"/"+1h"/"+2d" → ISO timestamp. */
|
|
106
|
+
static parseRelativeTime(s: string): string | null;
|
|
107
|
+
/** "10s"/"5m"/"1h"/"2d" → milliseconds. */
|
|
108
|
+
static parseInterval(s: string): number | null;
|
|
109
|
+
}
|
package/dist/schedule.js
ADDED
|
@@ -0,0 +1,359 @@
|
|
|
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
|
+
import { Cron } from "croner";
|
|
18
|
+
import { nanoid } from "nanoid";
|
|
19
|
+
import { normalizeMaxTurns } from "./agent-runner.js";
|
|
20
|
+
import { resolveSpawnType } from "./agent-types.js";
|
|
21
|
+
import { resolveModel } from "./model-resolver.js";
|
|
22
|
+
export class SubagentScheduler {
|
|
23
|
+
jobs = new Map();
|
|
24
|
+
intervals = new Map();
|
|
25
|
+
store;
|
|
26
|
+
pi;
|
|
27
|
+
ctx;
|
|
28
|
+
manager;
|
|
29
|
+
/** Start the scheduler: bind to a session's store and arm enabled jobs. */
|
|
30
|
+
start(pi, ctx, manager, store) {
|
|
31
|
+
this.pi = pi;
|
|
32
|
+
this.ctx = ctx;
|
|
33
|
+
this.manager = manager;
|
|
34
|
+
this.store = store;
|
|
35
|
+
for (const job of store.list()) {
|
|
36
|
+
if (job.enabled)
|
|
37
|
+
this.scheduleJob(job);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** Stop all timers; drop refs. Safe to call repeatedly. */
|
|
41
|
+
stop() {
|
|
42
|
+
for (const cron of this.jobs.values())
|
|
43
|
+
cron.stop();
|
|
44
|
+
this.jobs.clear();
|
|
45
|
+
for (const t of this.intervals.values())
|
|
46
|
+
clearTimeout(t);
|
|
47
|
+
this.intervals.clear();
|
|
48
|
+
this.store = undefined;
|
|
49
|
+
this.pi = undefined;
|
|
50
|
+
this.ctx = undefined;
|
|
51
|
+
this.manager = undefined;
|
|
52
|
+
}
|
|
53
|
+
/** True if start() has bound a store and the scheduler is active. */
|
|
54
|
+
isActive() {
|
|
55
|
+
return this.store !== undefined;
|
|
56
|
+
}
|
|
57
|
+
list() {
|
|
58
|
+
return this.store?.list() ?? [];
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Build a `ScheduledSubagent` from user input. Validates the schedule
|
|
62
|
+
* format and tags `scheduleType`. Throws on invalid input.
|
|
63
|
+
*/
|
|
64
|
+
buildJob(input) {
|
|
65
|
+
const detected = SubagentScheduler.detectSchedule(input.schedule);
|
|
66
|
+
return {
|
|
67
|
+
id: nanoid(10),
|
|
68
|
+
name: input.name,
|
|
69
|
+
description: input.description,
|
|
70
|
+
schedule: detected.normalized,
|
|
71
|
+
scheduleType: detected.type,
|
|
72
|
+
intervalMs: detected.intervalMs,
|
|
73
|
+
subagent_type: input.subagent_type,
|
|
74
|
+
prompt: input.prompt,
|
|
75
|
+
model: input.model,
|
|
76
|
+
thinking: input.thinking,
|
|
77
|
+
max_turns: input.max_turns,
|
|
78
|
+
isolated: input.isolated,
|
|
79
|
+
isolation: input.isolation,
|
|
80
|
+
enabled: true,
|
|
81
|
+
createdAt: new Date().toISOString(),
|
|
82
|
+
runCount: 0,
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
/** Add a job, persist, and arm if enabled. Returns the stored job. */
|
|
86
|
+
addJob(input) {
|
|
87
|
+
const store = this.requireStore();
|
|
88
|
+
if (store.hasName(input.name)) {
|
|
89
|
+
throw new Error(`A scheduled job named "${input.name}" already exists.`);
|
|
90
|
+
}
|
|
91
|
+
const job = this.buildJob(input);
|
|
92
|
+
store.add(job);
|
|
93
|
+
if (job.enabled)
|
|
94
|
+
this.scheduleJob(job);
|
|
95
|
+
this.emit({ type: "added", job });
|
|
96
|
+
return job;
|
|
97
|
+
}
|
|
98
|
+
removeJob(id) {
|
|
99
|
+
const store = this.requireStore();
|
|
100
|
+
if (!store.get(id))
|
|
101
|
+
return false;
|
|
102
|
+
this.unscheduleJob(id);
|
|
103
|
+
const ok = store.remove(id);
|
|
104
|
+
if (ok)
|
|
105
|
+
this.emit({ type: "removed", jobId: id });
|
|
106
|
+
return ok;
|
|
107
|
+
}
|
|
108
|
+
/** Toggle / mutate a job. Re-arms based on the new `enabled` state. */
|
|
109
|
+
updateJob(id, patch) {
|
|
110
|
+
const store = this.requireStore();
|
|
111
|
+
const updated = store.update(id, patch);
|
|
112
|
+
if (!updated)
|
|
113
|
+
return undefined;
|
|
114
|
+
this.unscheduleJob(id);
|
|
115
|
+
if (updated.enabled)
|
|
116
|
+
this.scheduleJob(updated);
|
|
117
|
+
this.emit({ type: "updated", job: updated });
|
|
118
|
+
return updated;
|
|
119
|
+
}
|
|
120
|
+
/** Next-run time as ISO, or undefined if not currently armed. */
|
|
121
|
+
getNextRun(jobId) {
|
|
122
|
+
const cron = this.jobs.get(jobId);
|
|
123
|
+
if (cron)
|
|
124
|
+
return cron.nextRun()?.toISOString();
|
|
125
|
+
const job = this.store?.get(jobId);
|
|
126
|
+
if (!job?.enabled)
|
|
127
|
+
return undefined;
|
|
128
|
+
if (job.scheduleType === "once")
|
|
129
|
+
return job.schedule;
|
|
130
|
+
if (job.scheduleType === "interval" && job.intervalMs) {
|
|
131
|
+
// Before the first fire there's no `lastRun`, so fall back to "now" —
|
|
132
|
+
// accurate at create time (setInterval was just armed) and within
|
|
133
|
+
// intervalMs of correct in any pre-first-fire view.
|
|
134
|
+
const base = job.lastRun ? new Date(job.lastRun).getTime() : Date.now();
|
|
135
|
+
return new Date(base + job.intervalMs).toISOString();
|
|
136
|
+
}
|
|
137
|
+
return undefined;
|
|
138
|
+
}
|
|
139
|
+
// ── Scheduling primitives ────────────────────────────────────────────
|
|
140
|
+
scheduleJob(job) {
|
|
141
|
+
const store = this.store;
|
|
142
|
+
if (!store)
|
|
143
|
+
return;
|
|
144
|
+
try {
|
|
145
|
+
if (job.scheduleType === "interval" && job.intervalMs) {
|
|
146
|
+
const t = setInterval(() => this.executeJob(job.id), job.intervalMs);
|
|
147
|
+
this.intervals.set(job.id, t);
|
|
148
|
+
}
|
|
149
|
+
else if (job.scheduleType === "once") {
|
|
150
|
+
const target = new Date(job.schedule).getTime();
|
|
151
|
+
const delay = target - Date.now();
|
|
152
|
+
if (delay > 0) {
|
|
153
|
+
const t = setTimeout(() => {
|
|
154
|
+
this.executeJob(job.id);
|
|
155
|
+
// Auto-disable one-shots after they fire (mirrors pi-cron-schedule)
|
|
156
|
+
store.update(job.id, { enabled: false });
|
|
157
|
+
const updated = store.get(job.id);
|
|
158
|
+
if (updated)
|
|
159
|
+
this.emit({ type: "updated", job: updated });
|
|
160
|
+
}, delay);
|
|
161
|
+
this.intervals.set(job.id, t);
|
|
162
|
+
}
|
|
163
|
+
else {
|
|
164
|
+
// Past timestamp — disable, mark error, never fire
|
|
165
|
+
store.update(job.id, { enabled: false, lastStatus: "error" });
|
|
166
|
+
this.emit({ type: "error", jobId: job.id, error: `Scheduled time ${job.schedule} is in the past` });
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
else {
|
|
170
|
+
const cron = new Cron(job.schedule, () => this.executeJob(job.id));
|
|
171
|
+
this.jobs.set(job.id, cron);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
catch (err) {
|
|
175
|
+
this.emit({ type: "error", jobId: job.id, error: err instanceof Error ? err.message : String(err) });
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
unscheduleJob(id) {
|
|
179
|
+
const cron = this.jobs.get(id);
|
|
180
|
+
if (cron) {
|
|
181
|
+
cron.stop();
|
|
182
|
+
this.jobs.delete(id);
|
|
183
|
+
}
|
|
184
|
+
const t = this.intervals.get(id);
|
|
185
|
+
if (t) {
|
|
186
|
+
clearTimeout(t);
|
|
187
|
+
clearInterval(t);
|
|
188
|
+
this.intervals.delete(id);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Fire a job: persist running state, spawn (bypassing the concurrency
|
|
193
|
+
* queue), persist completion. Fire-and-forget: the timer tick returns
|
|
194
|
+
* immediately so other jobs keep firing.
|
|
195
|
+
*/
|
|
196
|
+
executeJob(id) {
|
|
197
|
+
const store = this.store;
|
|
198
|
+
const pi = this.pi;
|
|
199
|
+
const ctx = this.ctx;
|
|
200
|
+
const manager = this.manager;
|
|
201
|
+
if (!store || !pi || !ctx || !manager)
|
|
202
|
+
return;
|
|
203
|
+
const job = store.get(id);
|
|
204
|
+
if (!job?.enabled)
|
|
205
|
+
return;
|
|
206
|
+
store.update(id, { lastStatus: "running" });
|
|
207
|
+
// Resolve model at fire time — registry contents may have changed since the
|
|
208
|
+
// job was created (auth added/removed). Fall back silently to spawn-default
|
|
209
|
+
// if resolution fails; the spawn path handles undefined model gracefully.
|
|
210
|
+
let resolvedModel;
|
|
211
|
+
if (job.model) {
|
|
212
|
+
const r = resolveModel(job.model, ctx.modelRegistry);
|
|
213
|
+
if (typeof r !== "string")
|
|
214
|
+
resolvedModel = r;
|
|
215
|
+
}
|
|
216
|
+
let agentId;
|
|
217
|
+
try {
|
|
218
|
+
// Re-resolve at fire time against the registry as it stands. This does not
|
|
219
|
+
// reload from disk (the scheduler has no reason to rebuild process-global
|
|
220
|
+
// state from a timer), so it catches changes that went through /agents or
|
|
221
|
+
// an Agent call — not a file deleted directly from a shell. The catch below turns
|
|
222
|
+
// this into lastStatus: "error" plus an error event, like any other
|
|
223
|
+
// fire-time failure.
|
|
224
|
+
const dispatch = resolveSpawnType(job.subagent_type);
|
|
225
|
+
if (!dispatch.ok)
|
|
226
|
+
throw new Error(dispatch.message);
|
|
227
|
+
agentId = manager.spawn(pi, ctx, dispatch.type, job.prompt, {
|
|
228
|
+
description: job.description,
|
|
229
|
+
isBackground: true,
|
|
230
|
+
bypassQueue: true,
|
|
231
|
+
model: resolvedModel,
|
|
232
|
+
maxTurns: job.max_turns,
|
|
233
|
+
isolated: job.isolated,
|
|
234
|
+
thinkingLevel: job.thinking,
|
|
235
|
+
isolation: job.isolation,
|
|
236
|
+
// A scheduled run has no tool call to build this, so without it the
|
|
237
|
+
// conversation viewer shows nothing about how the job was configured.
|
|
238
|
+
// The model is left out on purpose: agent-manager fills in the effective
|
|
239
|
+
// one when the session reports it, and naming the pre-session pick here
|
|
240
|
+
// would only be right until then.
|
|
241
|
+
invocation: {
|
|
242
|
+
thinking: job.thinking,
|
|
243
|
+
// Normalized like the Agent tool's own snapshot: `0` means unlimited,
|
|
244
|
+
// and rendering it as "max turns: 0" would read as a limit of none.
|
|
245
|
+
maxTurns: normalizeMaxTurns(job.max_turns),
|
|
246
|
+
isolated: job.isolated,
|
|
247
|
+
runInBackground: true,
|
|
248
|
+
isolation: job.isolation,
|
|
249
|
+
},
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
catch (err) {
|
|
253
|
+
const error = err instanceof Error ? err.message : String(err);
|
|
254
|
+
store.update(id, { lastRun: new Date().toISOString(), lastStatus: "error" });
|
|
255
|
+
this.emit({ type: "error", jobId: id, error });
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
this.emit({ type: "fired", jobId: id, agentId, name: job.name });
|
|
259
|
+
const finalize = (status) => {
|
|
260
|
+
const next = this.getNextRun(id);
|
|
261
|
+
const current = store.get(id);
|
|
262
|
+
store.update(id, {
|
|
263
|
+
lastRun: new Date().toISOString(),
|
|
264
|
+
lastStatus: status,
|
|
265
|
+
runCount: (current?.runCount ?? 0) + 1,
|
|
266
|
+
nextRun: next,
|
|
267
|
+
});
|
|
268
|
+
};
|
|
269
|
+
// AgentManager's promise resolves either way (its .catch returns ""), so we
|
|
270
|
+
// can't infer success/failure from the promise — read record.status instead.
|
|
271
|
+
// Terminal states: completed/steered = success; error/aborted/stopped = error.
|
|
272
|
+
// awaitStartup first: with isolation: "worktree" the run promise only exists
|
|
273
|
+
// once the repo copy is made, and a failed copy rejects here.
|
|
274
|
+
manager.awaitStartup(agentId)
|
|
275
|
+
.then(() => manager.getRecord(agentId)?.promise)
|
|
276
|
+
.then(() => {
|
|
277
|
+
const r = manager.getRecord(agentId);
|
|
278
|
+
const failed = r?.status === "error" || r?.status === "aborted" || r?.status === "stopped";
|
|
279
|
+
finalize(failed ? "error" : "success");
|
|
280
|
+
})
|
|
281
|
+
.catch(() => finalize("error"));
|
|
282
|
+
}
|
|
283
|
+
emit(event) {
|
|
284
|
+
if (this.pi)
|
|
285
|
+
this.pi.events.emit("subagents:scheduled", event);
|
|
286
|
+
}
|
|
287
|
+
requireStore() {
|
|
288
|
+
if (!this.store)
|
|
289
|
+
throw new Error("Scheduler not started — no active session.");
|
|
290
|
+
return this.store;
|
|
291
|
+
}
|
|
292
|
+
// ── Format detection / parsers (statics — pure) ──────────────────────
|
|
293
|
+
/**
|
|
294
|
+
* Sniff a schedule string and tag its type. Throws on invalid input.
|
|
295
|
+
* Order matters: relative ("+10m") and interval ("5m") both match digit+unit;
|
|
296
|
+
* relative requires the leading "+" to disambiguate.
|
|
297
|
+
*/
|
|
298
|
+
static detectSchedule(s) {
|
|
299
|
+
const trimmed = s.trim();
|
|
300
|
+
// "+10m" — relative one-shot
|
|
301
|
+
const rel = SubagentScheduler.parseRelativeTime(trimmed);
|
|
302
|
+
if (rel !== null)
|
|
303
|
+
return { type: "once", normalized: rel };
|
|
304
|
+
// "5m" — interval
|
|
305
|
+
const ivl = SubagentScheduler.parseInterval(trimmed);
|
|
306
|
+
if (ivl !== null)
|
|
307
|
+
return { type: "interval", intervalMs: ivl, normalized: trimmed };
|
|
308
|
+
// ISO timestamp — one-shot. Reject past timestamps upfront so we never
|
|
309
|
+
// create a dead-on-arrival record (scheduleJob's safety net still catches
|
|
310
|
+
// micro-races from `+0s`-style relatives).
|
|
311
|
+
if (/^\d{4}-\d{2}-\d{2}T/.test(trimmed)) {
|
|
312
|
+
const d = new Date(trimmed);
|
|
313
|
+
if (!Number.isNaN(d.getTime())) {
|
|
314
|
+
if (d.getTime() <= Date.now()) {
|
|
315
|
+
throw new Error(`Scheduled time ${d.toISOString()} is in the past.`);
|
|
316
|
+
}
|
|
317
|
+
return { type: "once", normalized: d.toISOString() };
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
// Cron — 6-field
|
|
321
|
+
const cronCheck = SubagentScheduler.validateCronExpression(trimmed);
|
|
322
|
+
if (cronCheck.valid)
|
|
323
|
+
return { type: "cron", normalized: trimmed };
|
|
324
|
+
throw new Error(`Invalid schedule "${s}". Use 6-field cron (e.g. "0 0 9 * * 1" — 9am every Monday), interval ("5m"/"1h"), or one-shot ("+10m" / ISO).`);
|
|
325
|
+
}
|
|
326
|
+
/** 6-field cron — 'second minute hour dom month dow'. */
|
|
327
|
+
static validateCronExpression(expr) {
|
|
328
|
+
const fields = expr.trim().split(/\s+/);
|
|
329
|
+
if (fields.length !== 6) {
|
|
330
|
+
return {
|
|
331
|
+
valid: false,
|
|
332
|
+
error: `Cron must have 6 fields (second minute hour dom month dow), got ${fields.length}. Example: "0 0 9 * * 1" for 9am every Monday.`,
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
try {
|
|
336
|
+
// Croner validates by construction.
|
|
337
|
+
new Cron(expr, () => { });
|
|
338
|
+
return { valid: true };
|
|
339
|
+
}
|
|
340
|
+
catch (e) {
|
|
341
|
+
return { valid: false, error: e instanceof Error ? e.message : "Invalid cron expression" };
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
/** "+10s"/"+5m"/"+1h"/"+2d" → ISO timestamp. */
|
|
345
|
+
static parseRelativeTime(s) {
|
|
346
|
+
const m = s.match(/^\+(\d+)(s|m|h|d)$/);
|
|
347
|
+
if (!m)
|
|
348
|
+
return null;
|
|
349
|
+
const ms = parseInt(m[1], 10) * { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 }[m[2]];
|
|
350
|
+
return new Date(Date.now() + ms).toISOString();
|
|
351
|
+
}
|
|
352
|
+
/** "10s"/"5m"/"1h"/"2d" → milliseconds. */
|
|
353
|
+
static parseInterval(s) {
|
|
354
|
+
const m = s.match(/^(\d+)(s|m|h|d)$/);
|
|
355
|
+
if (!m)
|
|
356
|
+
return null;
|
|
357
|
+
return parseInt(m[1], 10) * { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 }[m[2]];
|
|
358
|
+
}
|
|
359
|
+
}
|