@gotgenes/pi-subagents 1.0.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/.markdownlint-cli2.yaml +19 -0
- package/.prettierignore +5 -0
- package/.release-please-manifest.json +3 -0
- package/AGENTS.md +85 -0
- package/CHANGELOG.md +495 -0
- package/LICENSE +21 -0
- package/README.md +528 -0
- package/dist/agent-manager.d.ts +108 -0
- package/dist/agent-manager.js +390 -0
- package/dist/agent-runner.d.ts +93 -0
- package/dist/agent-runner.js +428 -0
- package/dist/agent-types.d.ts +48 -0
- package/dist/agent-types.js +136 -0
- package/dist/context.d.ts +12 -0
- package/dist/context.js +56 -0
- package/dist/cross-extension-rpc.d.ts +46 -0
- package/dist/cross-extension-rpc.js +54 -0
- package/dist/custom-agents.d.ts +14 -0
- package/dist/custom-agents.js +127 -0
- package/dist/default-agents.d.ts +7 -0
- package/dist/default-agents.js +119 -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 +13 -0
- package/dist/index.js +1731 -0
- package/dist/invocation-config.d.ts +22 -0
- package/dist/invocation-config.js +15 -0
- package/dist/memory.d.ts +49 -0
- package/dist/memory.js +151 -0
- package/dist/model-resolver.d.ts +19 -0
- package/dist/model-resolver.js +62 -0
- package/dist/output-file.d.ts +24 -0
- package/dist/output-file.js +86 -0
- package/dist/prompts.d.ts +29 -0
- package/dist/prompts.js +72 -0
- package/dist/schedule-store.d.ts +36 -0
- package/dist/schedule-store.js +144 -0
- package/dist/schedule.d.ts +109 -0
- package/dist/schedule.js +338 -0
- package/dist/settings.d.ts +66 -0
- package/dist/settings.js +130 -0
- package/dist/skill-loader.d.ts +24 -0
- package/dist/skill-loader.js +93 -0
- package/dist/types.d.ts +164 -0
- package/dist/types.js +5 -0
- package/dist/ui/agent-widget.d.ts +134 -0
- package/dist/ui/agent-widget.js +451 -0
- package/dist/ui/conversation-viewer.d.ts +35 -0
- package/dist/ui/conversation-viewer.js +252 -0
- package/dist/ui/schedule-menu.d.ts +16 -0
- package/dist/ui/schedule-menu.js +95 -0
- package/dist/usage.d.ts +50 -0
- package/dist/usage.js +49 -0
- package/dist/worktree.d.ts +36 -0
- package/dist/worktree.js +139 -0
- package/docs/decisions/0001-deferred-patches.md +75 -0
- package/package.json +68 -0
- package/prek.toml +24 -0
- package/release-please-config.json +22 -0
- package/src/agent-manager.ts +482 -0
- package/src/agent-runner.ts +625 -0
- package/src/agent-types.ts +164 -0
- package/src/context.ts +58 -0
- package/src/cross-extension-rpc.ts +95 -0
- package/src/custom-agents.ts +136 -0
- package/src/default-agents.ts +123 -0
- package/src/env.ts +33 -0
- package/src/group-join.ts +141 -0
- package/src/index.ts +1894 -0
- package/src/invocation-config.ts +40 -0
- package/src/memory.ts +165 -0
- package/src/model-resolver.ts +81 -0
- package/src/output-file.ts +96 -0
- package/src/prompts.ts +105 -0
- package/src/schedule-store.ts +143 -0
- package/src/schedule.ts +365 -0
- package/src/settings.ts +186 -0
- package/src/skill-loader.ts +102 -0
- package/src/types.ts +176 -0
- package/src/ui/agent-widget.ts +533 -0
- package/src/ui/conversation-viewer.ts +261 -0
- package/src/ui/schedule-menu.ts +104 -0
- package/src/usage.ts +60 -0
- package/src/worktree.ts +162 -0
|
@@ -0,0 +1,144 @@
|
|
|
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
|
+
mkdirSync(dirname(filePath), { recursive: true });
|
|
68
|
+
this.load();
|
|
69
|
+
}
|
|
70
|
+
/** Load from disk into the in-memory cache. Silent on parse errors. */
|
|
71
|
+
load() {
|
|
72
|
+
if (!existsSync(this.filePath))
|
|
73
|
+
return;
|
|
74
|
+
try {
|
|
75
|
+
const data = JSON.parse(readFileSync(this.filePath, "utf-8"));
|
|
76
|
+
this.jobs.clear();
|
|
77
|
+
for (const j of data.jobs ?? [])
|
|
78
|
+
this.jobs.set(j.id, j);
|
|
79
|
+
}
|
|
80
|
+
catch { /* corrupt — start fresh, next save rewrites */ }
|
|
81
|
+
}
|
|
82
|
+
/** Atomic write via temp file + rename (POSIX-atomic). */
|
|
83
|
+
save() {
|
|
84
|
+
const data = { version: 1, jobs: [...this.jobs.values()] };
|
|
85
|
+
const tmp = this.filePath + ".tmp";
|
|
86
|
+
writeFileSync(tmp, JSON.stringify(data, null, 2));
|
|
87
|
+
renameSync(tmp, this.filePath);
|
|
88
|
+
}
|
|
89
|
+
/** Acquire lock → reload → mutate → save → release. */
|
|
90
|
+
withLock(fn) {
|
|
91
|
+
acquireLock(this.lockPath);
|
|
92
|
+
try {
|
|
93
|
+
this.load();
|
|
94
|
+
const result = fn();
|
|
95
|
+
this.save();
|
|
96
|
+
return result;
|
|
97
|
+
}
|
|
98
|
+
finally {
|
|
99
|
+
releaseLock(this.lockPath);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
/** Read-only — returns a snapshot of the in-memory cache. */
|
|
103
|
+
list() {
|
|
104
|
+
return [...this.jobs.values()];
|
|
105
|
+
}
|
|
106
|
+
/** Read-only check — uses the cache. */
|
|
107
|
+
hasName(name, exceptId) {
|
|
108
|
+
for (const j of this.jobs.values()) {
|
|
109
|
+
if (j.id !== exceptId && j.name === name)
|
|
110
|
+
return true;
|
|
111
|
+
}
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
get(id) {
|
|
115
|
+
return this.jobs.get(id);
|
|
116
|
+
}
|
|
117
|
+
add(job) {
|
|
118
|
+
this.withLock(() => {
|
|
119
|
+
this.jobs.set(job.id, job);
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
update(id, patch) {
|
|
123
|
+
return this.withLock(() => {
|
|
124
|
+
const existing = this.jobs.get(id);
|
|
125
|
+
if (!existing)
|
|
126
|
+
return undefined;
|
|
127
|
+
const updated = { ...existing, ...patch };
|
|
128
|
+
this.jobs.set(id, updated);
|
|
129
|
+
return updated;
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
remove(id) {
|
|
133
|
+
return this.withLock(() => this.jobs.delete(id));
|
|
134
|
+
}
|
|
135
|
+
/** Delete the backing file (used when no jobs remain, optional cleanup). */
|
|
136
|
+
deleteFileIfEmpty() {
|
|
137
|
+
if (this.jobs.size === 0 && existsSync(this.filePath)) {
|
|
138
|
+
try {
|
|
139
|
+
unlinkSync(this.filePath);
|
|
140
|
+
}
|
|
141
|
+
catch { /* ignore */ }
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
@@ -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,338 @@
|
|
|
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 { resolveModel } from "./model-resolver.js";
|
|
20
|
+
export class SubagentScheduler {
|
|
21
|
+
jobs = new Map();
|
|
22
|
+
intervals = new Map();
|
|
23
|
+
store;
|
|
24
|
+
pi;
|
|
25
|
+
ctx;
|
|
26
|
+
manager;
|
|
27
|
+
/** Start the scheduler: bind to a session's store and arm enabled jobs. */
|
|
28
|
+
start(pi, ctx, manager, store) {
|
|
29
|
+
this.pi = pi;
|
|
30
|
+
this.ctx = ctx;
|
|
31
|
+
this.manager = manager;
|
|
32
|
+
this.store = store;
|
|
33
|
+
for (const job of store.list()) {
|
|
34
|
+
if (job.enabled)
|
|
35
|
+
this.scheduleJob(job);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/** Stop all timers; drop refs. Safe to call repeatedly. */
|
|
39
|
+
stop() {
|
|
40
|
+
for (const cron of this.jobs.values())
|
|
41
|
+
cron.stop();
|
|
42
|
+
this.jobs.clear();
|
|
43
|
+
for (const t of this.intervals.values())
|
|
44
|
+
clearTimeout(t);
|
|
45
|
+
this.intervals.clear();
|
|
46
|
+
this.store = undefined;
|
|
47
|
+
this.pi = undefined;
|
|
48
|
+
this.ctx = undefined;
|
|
49
|
+
this.manager = undefined;
|
|
50
|
+
}
|
|
51
|
+
/** True if start() has bound a store and the scheduler is active. */
|
|
52
|
+
isActive() {
|
|
53
|
+
return this.store !== undefined;
|
|
54
|
+
}
|
|
55
|
+
list() {
|
|
56
|
+
return this.store?.list() ?? [];
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Build a `ScheduledSubagent` from user input. Validates the schedule
|
|
60
|
+
* format and tags `scheduleType`. Throws on invalid input.
|
|
61
|
+
*/
|
|
62
|
+
buildJob(input) {
|
|
63
|
+
const detected = SubagentScheduler.detectSchedule(input.schedule);
|
|
64
|
+
return {
|
|
65
|
+
id: nanoid(10),
|
|
66
|
+
name: input.name,
|
|
67
|
+
description: input.description,
|
|
68
|
+
schedule: detected.normalized,
|
|
69
|
+
scheduleType: detected.type,
|
|
70
|
+
intervalMs: detected.intervalMs,
|
|
71
|
+
subagent_type: input.subagent_type,
|
|
72
|
+
prompt: input.prompt,
|
|
73
|
+
model: input.model,
|
|
74
|
+
thinking: input.thinking,
|
|
75
|
+
max_turns: input.max_turns,
|
|
76
|
+
isolated: input.isolated,
|
|
77
|
+
isolation: input.isolation,
|
|
78
|
+
enabled: true,
|
|
79
|
+
createdAt: new Date().toISOString(),
|
|
80
|
+
runCount: 0,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/** Add a job, persist, and arm if enabled. Returns the stored job. */
|
|
84
|
+
addJob(input) {
|
|
85
|
+
const store = this.requireStore();
|
|
86
|
+
if (store.hasName(input.name)) {
|
|
87
|
+
throw new Error(`A scheduled job named "${input.name}" already exists.`);
|
|
88
|
+
}
|
|
89
|
+
const job = this.buildJob(input);
|
|
90
|
+
store.add(job);
|
|
91
|
+
if (job.enabled)
|
|
92
|
+
this.scheduleJob(job);
|
|
93
|
+
this.emit({ type: "added", job });
|
|
94
|
+
return job;
|
|
95
|
+
}
|
|
96
|
+
removeJob(id) {
|
|
97
|
+
const store = this.requireStore();
|
|
98
|
+
if (!store.get(id))
|
|
99
|
+
return false;
|
|
100
|
+
this.unscheduleJob(id);
|
|
101
|
+
const ok = store.remove(id);
|
|
102
|
+
if (ok)
|
|
103
|
+
this.emit({ type: "removed", jobId: id });
|
|
104
|
+
return ok;
|
|
105
|
+
}
|
|
106
|
+
/** Toggle / mutate a job. Re-arms based on the new `enabled` state. */
|
|
107
|
+
updateJob(id, patch) {
|
|
108
|
+
const store = this.requireStore();
|
|
109
|
+
const updated = store.update(id, patch);
|
|
110
|
+
if (!updated)
|
|
111
|
+
return undefined;
|
|
112
|
+
this.unscheduleJob(id);
|
|
113
|
+
if (updated.enabled)
|
|
114
|
+
this.scheduleJob(updated);
|
|
115
|
+
this.emit({ type: "updated", job: updated });
|
|
116
|
+
return updated;
|
|
117
|
+
}
|
|
118
|
+
/** Next-run time as ISO, or undefined if not currently armed. */
|
|
119
|
+
getNextRun(jobId) {
|
|
120
|
+
const cron = this.jobs.get(jobId);
|
|
121
|
+
if (cron)
|
|
122
|
+
return cron.nextRun()?.toISOString();
|
|
123
|
+
const job = this.store?.get(jobId);
|
|
124
|
+
if (!job?.enabled)
|
|
125
|
+
return undefined;
|
|
126
|
+
if (job.scheduleType === "once")
|
|
127
|
+
return job.schedule;
|
|
128
|
+
if (job.scheduleType === "interval" && job.intervalMs) {
|
|
129
|
+
// Before the first fire there's no `lastRun`, so fall back to "now" —
|
|
130
|
+
// accurate at create time (setInterval was just armed) and within
|
|
131
|
+
// intervalMs of correct in any pre-first-fire view.
|
|
132
|
+
const base = job.lastRun ? new Date(job.lastRun).getTime() : Date.now();
|
|
133
|
+
return new Date(base + job.intervalMs).toISOString();
|
|
134
|
+
}
|
|
135
|
+
return undefined;
|
|
136
|
+
}
|
|
137
|
+
// ── Scheduling primitives ────────────────────────────────────────────
|
|
138
|
+
scheduleJob(job) {
|
|
139
|
+
const store = this.store;
|
|
140
|
+
if (!store)
|
|
141
|
+
return;
|
|
142
|
+
try {
|
|
143
|
+
if (job.scheduleType === "interval" && job.intervalMs) {
|
|
144
|
+
const t = setInterval(() => this.executeJob(job.id), job.intervalMs);
|
|
145
|
+
this.intervals.set(job.id, t);
|
|
146
|
+
}
|
|
147
|
+
else if (job.scheduleType === "once") {
|
|
148
|
+
const target = new Date(job.schedule).getTime();
|
|
149
|
+
const delay = target - Date.now();
|
|
150
|
+
if (delay > 0) {
|
|
151
|
+
const t = setTimeout(() => {
|
|
152
|
+
this.executeJob(job.id);
|
|
153
|
+
// Auto-disable one-shots after they fire (mirrors pi-cron-schedule)
|
|
154
|
+
store.update(job.id, { enabled: false });
|
|
155
|
+
const updated = store.get(job.id);
|
|
156
|
+
if (updated)
|
|
157
|
+
this.emit({ type: "updated", job: updated });
|
|
158
|
+
}, delay);
|
|
159
|
+
this.intervals.set(job.id, t);
|
|
160
|
+
}
|
|
161
|
+
else {
|
|
162
|
+
// Past timestamp — disable, mark error, never fire
|
|
163
|
+
store.update(job.id, { enabled: false, lastStatus: "error" });
|
|
164
|
+
this.emit({ type: "error", jobId: job.id, error: `Scheduled time ${job.schedule} is in the past` });
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
else {
|
|
168
|
+
const cron = new Cron(job.schedule, () => this.executeJob(job.id));
|
|
169
|
+
this.jobs.set(job.id, cron);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
catch (err) {
|
|
173
|
+
this.emit({ type: "error", jobId: job.id, error: err instanceof Error ? err.message : String(err) });
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
unscheduleJob(id) {
|
|
177
|
+
const cron = this.jobs.get(id);
|
|
178
|
+
if (cron) {
|
|
179
|
+
cron.stop();
|
|
180
|
+
this.jobs.delete(id);
|
|
181
|
+
}
|
|
182
|
+
const t = this.intervals.get(id);
|
|
183
|
+
if (t) {
|
|
184
|
+
clearTimeout(t);
|
|
185
|
+
clearInterval(t);
|
|
186
|
+
this.intervals.delete(id);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Fire a job: persist running state, spawn (bypassing the concurrency
|
|
191
|
+
* queue), persist completion. Fire-and-forget: the timer tick returns
|
|
192
|
+
* immediately so other jobs keep firing.
|
|
193
|
+
*/
|
|
194
|
+
executeJob(id) {
|
|
195
|
+
const store = this.store;
|
|
196
|
+
const pi = this.pi;
|
|
197
|
+
const ctx = this.ctx;
|
|
198
|
+
const manager = this.manager;
|
|
199
|
+
if (!store || !pi || !ctx || !manager)
|
|
200
|
+
return;
|
|
201
|
+
const job = store.get(id);
|
|
202
|
+
if (!job?.enabled)
|
|
203
|
+
return;
|
|
204
|
+
store.update(id, { lastStatus: "running" });
|
|
205
|
+
// Resolve model at fire time — registry contents may have changed since the
|
|
206
|
+
// job was created (auth added/removed). Fall back silently to spawn-default
|
|
207
|
+
// if resolution fails; the spawn path handles undefined model gracefully.
|
|
208
|
+
let resolvedModel;
|
|
209
|
+
if (job.model) {
|
|
210
|
+
const r = resolveModel(job.model, ctx.modelRegistry);
|
|
211
|
+
if (typeof r !== "string")
|
|
212
|
+
resolvedModel = r;
|
|
213
|
+
}
|
|
214
|
+
let agentId;
|
|
215
|
+
try {
|
|
216
|
+
agentId = manager.spawn(pi, ctx, job.subagent_type, job.prompt, {
|
|
217
|
+
description: job.description,
|
|
218
|
+
isBackground: true,
|
|
219
|
+
bypassQueue: true,
|
|
220
|
+
model: resolvedModel,
|
|
221
|
+
maxTurns: job.max_turns,
|
|
222
|
+
isolated: job.isolated,
|
|
223
|
+
thinkingLevel: job.thinking,
|
|
224
|
+
isolation: job.isolation,
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
catch (err) {
|
|
228
|
+
const error = err instanceof Error ? err.message : String(err);
|
|
229
|
+
store.update(id, { lastRun: new Date().toISOString(), lastStatus: "error" });
|
|
230
|
+
this.emit({ type: "error", jobId: id, error });
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
this.emit({ type: "fired", jobId: id, agentId, name: job.name });
|
|
234
|
+
const record = manager.getRecord(agentId);
|
|
235
|
+
const finalize = (status) => {
|
|
236
|
+
const next = this.getNextRun(id);
|
|
237
|
+
const current = store.get(id);
|
|
238
|
+
store.update(id, {
|
|
239
|
+
lastRun: new Date().toISOString(),
|
|
240
|
+
lastStatus: status,
|
|
241
|
+
runCount: (current?.runCount ?? 0) + 1,
|
|
242
|
+
nextRun: next,
|
|
243
|
+
});
|
|
244
|
+
};
|
|
245
|
+
// AgentManager's promise resolves either way (its .catch returns ""), so we
|
|
246
|
+
// can't infer success/failure from the promise — read record.status instead.
|
|
247
|
+
// Terminal states: completed/steered = success; error/aborted/stopped = error.
|
|
248
|
+
if (record?.promise) {
|
|
249
|
+
record.promise
|
|
250
|
+
.then(() => {
|
|
251
|
+
const r = manager.getRecord(agentId);
|
|
252
|
+
const failed = r?.status === "error" || r?.status === "aborted" || r?.status === "stopped";
|
|
253
|
+
finalize(failed ? "error" : "success");
|
|
254
|
+
})
|
|
255
|
+
.catch(() => finalize("error"));
|
|
256
|
+
}
|
|
257
|
+
else {
|
|
258
|
+
// Spawn returned without a promise (defensive — bypassQueue path always sets one).
|
|
259
|
+
finalize("success");
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
emit(event) {
|
|
263
|
+
if (this.pi)
|
|
264
|
+
this.pi.events.emit("subagents:scheduled", event);
|
|
265
|
+
}
|
|
266
|
+
requireStore() {
|
|
267
|
+
if (!this.store)
|
|
268
|
+
throw new Error("Scheduler not started — no active session.");
|
|
269
|
+
return this.store;
|
|
270
|
+
}
|
|
271
|
+
// ── Format detection / parsers (statics — pure) ──────────────────────
|
|
272
|
+
/**
|
|
273
|
+
* Sniff a schedule string and tag its type. Throws on invalid input.
|
|
274
|
+
* Order matters: relative ("+10m") and interval ("5m") both match digit+unit;
|
|
275
|
+
* relative requires the leading "+" to disambiguate.
|
|
276
|
+
*/
|
|
277
|
+
static detectSchedule(s) {
|
|
278
|
+
const trimmed = s.trim();
|
|
279
|
+
// "+10m" — relative one-shot
|
|
280
|
+
const rel = SubagentScheduler.parseRelativeTime(trimmed);
|
|
281
|
+
if (rel !== null)
|
|
282
|
+
return { type: "once", normalized: rel };
|
|
283
|
+
// "5m" — interval
|
|
284
|
+
const ivl = SubagentScheduler.parseInterval(trimmed);
|
|
285
|
+
if (ivl !== null)
|
|
286
|
+
return { type: "interval", intervalMs: ivl, normalized: trimmed };
|
|
287
|
+
// ISO timestamp — one-shot. Reject past timestamps upfront so we never
|
|
288
|
+
// create a dead-on-arrival record (scheduleJob's safety net still catches
|
|
289
|
+
// micro-races from `+0s`-style relatives).
|
|
290
|
+
if (/^\d{4}-\d{2}-\d{2}T/.test(trimmed)) {
|
|
291
|
+
const d = new Date(trimmed);
|
|
292
|
+
if (!Number.isNaN(d.getTime())) {
|
|
293
|
+
if (d.getTime() <= Date.now()) {
|
|
294
|
+
throw new Error(`Scheduled time ${d.toISOString()} is in the past.`);
|
|
295
|
+
}
|
|
296
|
+
return { type: "once", normalized: d.toISOString() };
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
// Cron — 6-field
|
|
300
|
+
const cronCheck = SubagentScheduler.validateCronExpression(trimmed);
|
|
301
|
+
if (cronCheck.valid)
|
|
302
|
+
return { type: "cron", normalized: trimmed };
|
|
303
|
+
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).`);
|
|
304
|
+
}
|
|
305
|
+
/** 6-field cron — 'second minute hour dom month dow'. */
|
|
306
|
+
static validateCronExpression(expr) {
|
|
307
|
+
const fields = expr.trim().split(/\s+/);
|
|
308
|
+
if (fields.length !== 6) {
|
|
309
|
+
return {
|
|
310
|
+
valid: false,
|
|
311
|
+
error: `Cron must have 6 fields (second minute hour dom month dow), got ${fields.length}. Example: "0 0 9 * * 1" for 9am every Monday.`,
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
try {
|
|
315
|
+
// Croner validates by construction.
|
|
316
|
+
new Cron(expr, () => { });
|
|
317
|
+
return { valid: true };
|
|
318
|
+
}
|
|
319
|
+
catch (e) {
|
|
320
|
+
return { valid: false, error: e instanceof Error ? e.message : "Invalid cron expression" };
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
/** "+10s"/"+5m"/"+1h"/"+2d" → ISO timestamp. */
|
|
324
|
+
static parseRelativeTime(s) {
|
|
325
|
+
const m = s.match(/^\+(\d+)(s|m|h|d)$/);
|
|
326
|
+
if (!m)
|
|
327
|
+
return null;
|
|
328
|
+
const ms = parseInt(m[1], 10) * { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 }[m[2]];
|
|
329
|
+
return new Date(Date.now() + ms).toISOString();
|
|
330
|
+
}
|
|
331
|
+
/** "10s"/"5m"/"1h"/"2d" → milliseconds. */
|
|
332
|
+
static parseInterval(s) {
|
|
333
|
+
const m = s.match(/^(\d+)(s|m|h|d)$/);
|
|
334
|
+
if (!m)
|
|
335
|
+
return null;
|
|
336
|
+
return parseInt(m[1], 10) * { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 }[m[2]];
|
|
337
|
+
}
|
|
338
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { JoinMode } from "./types.js";
|
|
2
|
+
export interface SubagentsSettings {
|
|
3
|
+
maxConcurrent?: number;
|
|
4
|
+
/**
|
|
5
|
+
* 0 = unlimited — the extension's single source of truth for that convention:
|
|
6
|
+
* `normalizeMaxTurns()` in agent-runner.ts treats 0 → `undefined`, and the
|
|
7
|
+
* `/agents` → Settings input prompt explicitly says "0 = unlimited".
|
|
8
|
+
*/
|
|
9
|
+
defaultMaxTurns?: number;
|
|
10
|
+
graceTurns?: number;
|
|
11
|
+
defaultJoinMode?: JoinMode;
|
|
12
|
+
/**
|
|
13
|
+
* Master switch for the schedule subagent feature. Defaults to `true`.
|
|
14
|
+
* When `false`: the `Agent` tool's `schedule` param + its guideline are
|
|
15
|
+
* stripped from the tool spec at registration (zero LLM-context cost), the
|
|
16
|
+
* scheduler doesn't bind to the session, and the `/agents → Scheduled jobs`
|
|
17
|
+
* menu entry is hidden. Schema-level removal applies at extension load
|
|
18
|
+
* (next pi session); runtime menu/runtime-fire short-circuit is immediate.
|
|
19
|
+
*/
|
|
20
|
+
schedulingEnabled?: boolean;
|
|
21
|
+
}
|
|
22
|
+
/** Setter hooks used by applySettings to wire persisted values into in-memory state. */
|
|
23
|
+
export interface SettingsAppliers {
|
|
24
|
+
setMaxConcurrent: (n: number) => void;
|
|
25
|
+
setDefaultMaxTurns: (n: number) => void;
|
|
26
|
+
setGraceTurns: (n: number) => void;
|
|
27
|
+
setDefaultJoinMode: (mode: JoinMode) => void;
|
|
28
|
+
setSchedulingEnabled: (b: boolean) => void;
|
|
29
|
+
}
|
|
30
|
+
/** Emit callback — a subset of `pi.events.emit` to keep helpers testable. */
|
|
31
|
+
export type SettingsEmit = (event: string, payload: unknown) => void;
|
|
32
|
+
/** Load merged settings: global provides defaults, project overrides. */
|
|
33
|
+
export declare function loadSettings(cwd?: string): SubagentsSettings;
|
|
34
|
+
/**
|
|
35
|
+
* Write project-local settings. Global is never touched from code.
|
|
36
|
+
* Returns `true` on success, `false` if the write (or mkdir) failed so the
|
|
37
|
+
* caller can surface a warning — persistence isn't fatal but isn't silent.
|
|
38
|
+
*/
|
|
39
|
+
export declare function saveSettings(s: SubagentsSettings, cwd?: string): boolean;
|
|
40
|
+
/** Apply persisted settings to the in-memory state via caller-supplied setters. */
|
|
41
|
+
export declare function applySettings(s: SubagentsSettings, appliers: SettingsAppliers): void;
|
|
42
|
+
/**
|
|
43
|
+
* Format the user-facing toast for a settings mutation. Pure function —
|
|
44
|
+
* routes the success/failure of `saveSettings` into the right message + level
|
|
45
|
+
* so the UI layer (index.ts) stays a thin wire between input and notification.
|
|
46
|
+
*/
|
|
47
|
+
export declare function persistToastFor(successMsg: string, persisted: boolean): {
|
|
48
|
+
message: string;
|
|
49
|
+
level: "info" | "warning";
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* Load merged settings, apply them to in-memory state, and emit the
|
|
53
|
+
* `subagents:settings_loaded` lifecycle event. Returns the loaded settings so
|
|
54
|
+
* callers can log/inspect. Extension init wires this once.
|
|
55
|
+
*/
|
|
56
|
+
export declare function applyAndEmitLoaded(appliers: SettingsAppliers, emit: SettingsEmit, cwd?: string): SubagentsSettings;
|
|
57
|
+
/**
|
|
58
|
+
* Persist a settings snapshot, emit the `subagents:settings_changed` event
|
|
59
|
+
* (regardless of persist outcome so listeners see the in-memory change), and
|
|
60
|
+
* return the toast the UI should display. Event payload carries the `persisted`
|
|
61
|
+
* flag so listeners can react to write failures.
|
|
62
|
+
*/
|
|
63
|
+
export declare function saveAndEmitChanged(snapshot: SubagentsSettings, successMsg: string, emit: SettingsEmit, cwd?: string): {
|
|
64
|
+
message: string;
|
|
65
|
+
level: "info" | "warning";
|
|
66
|
+
};
|