@ilya-lesikov/pi-pi 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/3p/pi-ask-user/index.ts +71 -124
  2. package/3p/pi-ask-user/single-select-layout.ts +3 -14
  3. package/3p/pi-subagents/package.json +12 -7
  4. package/3p/pi-subagents/src/agent-manager.ts +243 -79
  5. package/3p/pi-subagents/src/agent-runner.ts +501 -365
  6. package/3p/pi-subagents/src/agent-types.ts +46 -57
  7. package/3p/pi-subagents/src/cross-extension-rpc.ts +52 -46
  8. package/3p/pi-subagents/src/custom-agents.ts +30 -6
  9. package/3p/pi-subagents/src/default-agents.ts +25 -43
  10. package/3p/pi-subagents/src/enabled-models.ts +180 -0
  11. package/3p/pi-subagents/src/index.ts +599 -839
  12. package/3p/pi-subagents/src/model-resolver.ts +26 -7
  13. package/3p/pi-subagents/src/output-file.ts +21 -2
  14. package/3p/pi-subagents/src/prompts.ts +17 -3
  15. package/3p/pi-subagents/src/schedule-store.ts +153 -0
  16. package/3p/pi-subagents/src/schedule.ts +365 -0
  17. package/3p/pi-subagents/src/settings.ts +261 -0
  18. package/3p/pi-subagents/src/skill-loader.ts +77 -54
  19. package/3p/pi-subagents/src/status-note.ts +25 -0
  20. package/3p/pi-subagents/src/types.ts +97 -6
  21. package/3p/pi-subagents/src/ui/agent-widget.ts +94 -21
  22. package/3p/pi-subagents/src/ui/conversation-viewer.ts +147 -35
  23. package/3p/pi-subagents/src/ui/schedule-menu.ts +104 -0
  24. package/3p/pi-subagents/src/ui/viewer-keys.ts +39 -0
  25. package/3p/pi-subagents/src/usage.ts +60 -0
  26. package/3p/pi-subagents/src/worktree.ts +49 -20
  27. package/extensions/orchestrator/agents/advisor.ts +13 -8
  28. package/extensions/orchestrator/agents/brainstorm-reviewer.ts +8 -3
  29. package/extensions/orchestrator/agents/code-reviewer.ts +8 -3
  30. package/extensions/orchestrator/agents/constraints.test.ts +26 -0
  31. package/extensions/orchestrator/agents/constraints.ts +12 -2
  32. package/extensions/orchestrator/agents/deep-debugger.ts +13 -8
  33. package/extensions/orchestrator/agents/explore.ts +12 -6
  34. package/extensions/orchestrator/agents/librarian.ts +13 -5
  35. package/extensions/orchestrator/agents/plan-reviewer.ts +8 -3
  36. package/extensions/orchestrator/agents/planner.ts +8 -3
  37. package/extensions/orchestrator/agents/pools.test.ts +56 -0
  38. package/extensions/orchestrator/agents/prompts.test.ts +52 -10
  39. package/extensions/orchestrator/agents/registry.test.ts +245 -0
  40. package/extensions/orchestrator/agents/registry.ts +145 -10
  41. package/extensions/orchestrator/agents/reviewer.ts +14 -8
  42. package/extensions/orchestrator/agents/task.ts +12 -6
  43. package/extensions/orchestrator/agents/tool-routing.ts +213 -85
  44. package/extensions/orchestrator/agents/wait-for-completion.test.ts +171 -0
  45. package/extensions/orchestrator/ast-search.test.ts +124 -0
  46. package/extensions/orchestrator/billing-spoof.test.ts +67 -0
  47. package/extensions/orchestrator/billing-spoof.ts +95 -0
  48. package/extensions/orchestrator/cbm.more.test.ts +358 -0
  49. package/extensions/orchestrator/command-handlers.ts +6 -0
  50. package/extensions/orchestrator/commands.test.ts +15 -2
  51. package/extensions/orchestrator/commands.ts +1 -1
  52. package/extensions/orchestrator/config.test.ts +89 -1
  53. package/extensions/orchestrator/config.ts +102 -19
  54. package/extensions/orchestrator/context.test.ts +46 -0
  55. package/extensions/orchestrator/context.ts +18 -5
  56. package/extensions/orchestrator/custom-footer.test.ts +24 -10
  57. package/extensions/orchestrator/custom-footer.ts +4 -2
  58. package/extensions/orchestrator/doctor.more.test.ts +315 -0
  59. package/extensions/orchestrator/doctor.ts +6 -2
  60. package/extensions/orchestrator/event-handlers.more.test.ts +561 -0
  61. package/extensions/orchestrator/event-handlers.test.ts +96 -9
  62. package/extensions/orchestrator/event-handlers.ts +344 -151
  63. package/extensions/orchestrator/exa.more.test.ts +118 -0
  64. package/extensions/orchestrator/flant-infra.more.test.ts +381 -0
  65. package/extensions/orchestrator/flant-infra.test.ts +127 -0
  66. package/extensions/orchestrator/flant-infra.ts +126 -41
  67. package/extensions/orchestrator/index.test.ts +76 -0
  68. package/extensions/orchestrator/index.ts +2 -0
  69. package/extensions/orchestrator/integration.test.ts +183 -65
  70. package/extensions/orchestrator/model-registry.test.ts +2 -1
  71. package/extensions/orchestrator/model-registry.ts +12 -2
  72. package/extensions/orchestrator/orchestrator.test.ts +67 -0
  73. package/extensions/orchestrator/orchestrator.ts +119 -27
  74. package/extensions/orchestrator/phases/brainstorm.test.ts +30 -1
  75. package/extensions/orchestrator/phases/brainstorm.ts +43 -6
  76. package/extensions/orchestrator/phases/implementation.ts +2 -0
  77. package/extensions/orchestrator/phases/machine.test.ts +17 -1
  78. package/extensions/orchestrator/phases/machine.ts +4 -1
  79. package/extensions/orchestrator/phases/planning.test.ts +47 -1
  80. package/extensions/orchestrator/phases/planning.ts +18 -3
  81. package/extensions/orchestrator/phases/review-task.ts +5 -0
  82. package/extensions/orchestrator/phases/review.test.ts +10 -0
  83. package/extensions/orchestrator/phases/review.ts +22 -7
  84. package/extensions/orchestrator/phases/spawn-blocking.test.ts +1 -0
  85. package/extensions/orchestrator/phases/verdict.ts +6 -5
  86. package/extensions/orchestrator/plannotator-open-failure.test.ts +67 -0
  87. package/extensions/orchestrator/plannotator.test.ts +38 -1
  88. package/extensions/orchestrator/plannotator.ts +50 -3
  89. package/extensions/orchestrator/pp-menu.leaves.test.ts +590 -0
  90. package/extensions/orchestrator/pp-menu.more.test.ts +524 -0
  91. package/extensions/orchestrator/pp-menu.test.ts +114 -7
  92. package/extensions/orchestrator/pp-menu.ts +580 -91
  93. package/extensions/orchestrator/pp-state-tools.test.ts +80 -0
  94. package/extensions/orchestrator/pp-state-tools.ts +65 -0
  95. package/extensions/orchestrator/rate-limit-fallback.more.test.ts +241 -0
  96. package/extensions/orchestrator/rate-limit-fallback.test.ts +20 -1
  97. package/extensions/orchestrator/rate-limit-fallback.ts +12 -0
  98. package/extensions/orchestrator/review-files.test.ts +26 -0
  99. package/extensions/orchestrator/review-files.ts +3 -0
  100. package/extensions/orchestrator/state.test.ts +73 -1
  101. package/extensions/orchestrator/state.ts +95 -23
  102. package/extensions/orchestrator/suppress-pierre-theme-spam.test.ts +56 -0
  103. package/extensions/orchestrator/suppress-pierre-theme-spam.ts +45 -0
  104. package/extensions/orchestrator/validate-artifacts.ts +1 -1
  105. package/package.json +9 -2
  106. package/scripts/lib/smoke-resolve.mjs +99 -0
  107. package/scripts/test-3p.sh +52 -0
  108. package/scripts/test-package.sh +62 -0
@@ -38,17 +38,20 @@ export function resolveModel(
38
38
  }
39
39
  }
40
40
 
41
- // 2. Fuzzy match against available models
42
- const query = input.toLowerCase();
41
+ // 2. Fuzzy match against available models. Normalize separators so cosmetic
42
+ // punctuation differences still match — e.g. "claude-haiku-4.5" and
43
+ // "claude-haiku-4-5" (dot vs dash in the version) resolve to the same model.
44
+ const normalize = (s: string) => s.toLowerCase().replace(/\./g, "-");
45
+ const query = normalize(input);
43
46
 
44
47
  // Score each model: prefer exact id match > id contains > name contains > provider+id contains
45
48
  let bestMatch: ModelEntry | undefined;
46
49
  let bestScore = 0;
47
50
 
48
51
  for (const m of all) {
49
- const id = m.id.toLowerCase();
50
- const name = m.name.toLowerCase();
51
- const full = `${m.provider}/${m.id}`.toLowerCase();
52
+ const id = normalize(m.id);
53
+ const name = normalize(m.name);
54
+ const full = normalize(`${m.provider}/${m.id}`);
52
55
 
53
56
  let score = 0;
54
57
  if (id === query || full === query) {
@@ -57,7 +60,14 @@ export function resolveModel(
57
60
  score = 60 + (query.length / id.length) * 30; // substring, prefer tighter matches
58
61
  } else if (name.includes(query)) {
59
62
  score = 40 + (query.length / name.length) * 20;
60
- } else if (query.split(/[\s\-/]+/).every(part => id.includes(part) || name.includes(part) || m.provider.toLowerCase().includes(part))) {
63
+ } else if (
64
+ // A trailing date-stamp token (e.g. "20251001") is optional, so a
65
+ // date-pinned config like "claude-haiku-4-5-20251001" still matches an
66
+ // undated registry id like "claude-haiku-4-5".
67
+ query
68
+ .split(/[\s\-/]+/)
69
+ .every(part => /^\d{8}$/.test(part) || id.includes(part) || name.includes(part) || m.provider.toLowerCase().includes(part))
70
+ ) {
61
71
  score = 20; // all parts present somewhere
62
72
  }
63
73
 
@@ -72,7 +82,16 @@ export function resolveModel(
72
82
  if (found) return found;
73
83
  }
74
84
 
75
- // 3. No match list available models
85
+ // 3. Provider fallback: a "provider/modelId" query that didn't match under the
86
+ // named provider (exact or fuzzy above) retries against all providers. The
87
+ // named provider is preferred when present; this only kicks in when it isn't,
88
+ // so the same model from another provider beats falling back to "inherit".
89
+ if (slashIdx !== -1) {
90
+ const bare = resolveModel(input.slice(slashIdx + 1), registry);
91
+ if (typeof bare !== "string") return bare;
92
+ }
93
+
94
+ // 4. No match — list available models
76
95
  const modelList = all
77
96
  .map(m => ` ${m.provider}/${m.id}`)
78
97
  .sort()
@@ -10,13 +10,32 @@ import { tmpdir } from "node:os";
10
10
  import { join } from "node:path";
11
11
  import type { AgentSession, AgentSessionEvent } from "@earendil-works/pi-coding-agent";
12
12
 
13
+ /**
14
+ * Encode a cwd path as a filesystem-safe directory name. Handles:
15
+ * - POSIX: "/home/user/project" → "home-user-project"
16
+ * - Windows: "C:\Users\foo\project" → "Users-foo-project"
17
+ * - UNC: "\\\\server\\share\\project" → "server-share-project"
18
+ */
19
+ export function encodeCwd(cwd: string): string {
20
+ return cwd
21
+ .replace(/[/\\]/g, "-") // both separators → dash
22
+ .replace(/^[A-Za-z]:-/, "") // strip Windows drive prefix ("C:-")
23
+ .replace(/^-+/, ""); // strip leading dashes (POSIX root, UNC)
24
+ }
25
+
13
26
  /** Create the output file path, ensuring the directory exists.
14
27
  * Mirrors Claude Code's layout: /tmp/{prefix}-{uid}/{encoded-cwd}/{sessionId}/tasks/{agentId}.output */
15
28
  export function createOutputFilePath(cwd: string, agentId: string, sessionId: string): string {
16
- const encoded = cwd.replace(/\//g, "-").replace(/^-/, "");
29
+ const encoded = encodeCwd(cwd);
17
30
  const root = join(tmpdir(), `pi-subagents-${process.getuid?.() ?? 0}`);
18
31
  mkdirSync(root, { recursive: true, mode: 0o700 });
19
- chmodSync(root, 0o700);
32
+ // chmod is a no-op on Windows and throws on some Windows filesystems.
33
+ // On Unix we still want to enforce 0o700 past umask, so only swallow on Windows.
34
+ try {
35
+ chmodSync(root, 0o700);
36
+ } catch (err) {
37
+ if (process.platform !== "win32") throw err;
38
+ }
20
39
  const dir = join(root, encoded, sessionId, "tasks");
21
40
  mkdirSync(dir, { recursive: true });
22
41
  return join(dir, `${agentId}.output`);
@@ -16,9 +16,16 @@ export interface PromptExtras {
16
16
  * Build the system prompt for an agent from its config.
17
17
  *
18
18
  * - "replace" mode: env header + config.systemPrompt (full control, no parent identity)
19
- * - "append" mode: env header + parent system prompt + sub-agent context + config.systemPrompt
19
+ * - "append" mode: parent system prompt + sub-agent context + env header + config.systemPrompt
20
20
  * - "append" with empty systemPrompt: pure parent clone
21
21
  *
22
+ * Both modes include an `<active_agent name="${config.name}"/>` tag so downstream
23
+ * extensions (e.g. permission/policy systems) can resolve per-agent policy
24
+ * inside the child session by parsing the system prompt. In replace mode the tag
25
+ * is prepended; in append mode it follows the shared inherited content so the
26
+ * parent prompt forms an identical, cacheable byte prefix with the parent
27
+ * session (the LLM's KV cache can then reuse those tokens across every spawn).
28
+ *
22
29
  * @param parentSystemPrompt The parent agent's effective system prompt (for append mode).
23
30
  * @param extras Optional extra sections to inject (memory, preloaded skills).
24
31
  */
@@ -29,6 +36,8 @@ export function buildAgentPrompt(
29
36
  parentSystemPrompt?: string,
30
37
  extras?: PromptExtras,
31
38
  ): string {
39
+ const activeAgentTag = `<active_agent name="${config.name}"/>\n\n`;
40
+
32
41
  const envBlock = `# Environment
33
42
  Working directory: ${cwd}
34
43
  ${env.isGitRepo ? `Git repository: yes\nBranch: ${env.branch}` : "Not a git repository"}
@@ -66,7 +75,12 @@ You are operating as a sub-agent invoked to handle a specific task.
66
75
  ? `\n\n<agent_instructions>\n${config.systemPrompt}\n</agent_instructions>`
67
76
  : "";
68
77
 
69
- return envBlock + "\n\n<inherited_system_prompt>\n" + identity + "\n</inherited_system_prompt>\n\n" + bridge + customSection + extrasSuffix;
78
+ // Place shared/stable content first so the LLM's KV cache can reuse the
79
+ // inherited prefix across all subagent invocations. The parent prompt is
80
+ // placed verbatim (no wrapper tag) so it forms an identical byte prefix
81
+ // with the parent session, maximising KV cache hits. The <active_agent>
82
+ // tag and env block vary per call and are placed after the cached prefix.
83
+ return identity + "\n\n" + bridge + "\n\n" + activeAgentTag + envBlock + customSection + extrasSuffix;
70
84
  }
71
85
 
72
86
  // "replace" mode — env header + the config's full system prompt
@@ -75,7 +89,7 @@ You have been invoked to handle a specific task autonomously.
75
89
 
76
90
  ${envBlock}`;
77
91
 
78
- return replaceHeader + "\n\n" + config.systemPrompt + extrasSuffix;
92
+ return activeAgentTag + replaceHeader + "\n\n" + config.systemPrompt + extrasSuffix;
79
93
  }
80
94
 
81
95
  /** Fallback base prompt when parent system prompt is unavailable in append mode. */
@@ -0,0 +1,153 @@
1
+ /**
2
+ * schedule-store.ts — File-backed store for scheduled subagents.
3
+ *
4
+ * Session-scoped: each pi session owns its own schedules at
5
+ * `<cwd>/.pi/subagent-schedules/<sessionId>.json`. `/new` starts a fresh
6
+ * empty store; `/resume` reloads.
7
+ *
8
+ * Concurrency model lifted from pi-chonky-tasks/src/task-store.ts: every
9
+ * mutation acquires a PID-based exclusion lock, re-reads the latest state
10
+ * from disk, applies the change, atomic-writes via temp+rename, releases.
11
+ */
12
+
13
+ import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
14
+ import { dirname, join } from "node:path";
15
+ import type { ScheduledSubagent, ScheduleStoreData } from "./types.js";
16
+
17
+ const LOCK_RETRY_MS = 50;
18
+ const LOCK_MAX_RETRIES = 100;
19
+
20
+ function isProcessRunning(pid: number): boolean {
21
+ try { process.kill(pid, 0); return true; } catch { return false; }
22
+ }
23
+
24
+ function acquireLock(lockPath: string): void {
25
+ for (let i = 0; i < LOCK_MAX_RETRIES; i++) {
26
+ try {
27
+ writeFileSync(lockPath, `${process.pid}`, { flag: "wx" });
28
+ return;
29
+ } catch (e: any) {
30
+ if (e.code === "EEXIST") {
31
+ try {
32
+ const pid = parseInt(readFileSync(lockPath, "utf-8"), 10);
33
+ if (pid && !isProcessRunning(pid)) {
34
+ unlinkSync(lockPath);
35
+ continue;
36
+ }
37
+ } catch { /* ignore — try again */ }
38
+ const start = Date.now();
39
+ while (Date.now() - start < LOCK_RETRY_MS) { /* busy wait */ }
40
+ continue;
41
+ }
42
+ throw e;
43
+ }
44
+ }
45
+ throw new Error(`Failed to acquire schedule lock: ${lockPath}`);
46
+ }
47
+
48
+ function releaseLock(lockPath: string): void {
49
+ try { unlinkSync(lockPath); } catch { /* ignore */ }
50
+ }
51
+
52
+ /** Resolve the storage path for a session-scoped store. */
53
+ export function resolveStorePath(cwd: string, sessionId: string): string {
54
+ return join(cwd, ".pi", "subagent-schedules", `${sessionId}.json`);
55
+ }
56
+
57
+ export class ScheduleStore {
58
+ private filePath: string;
59
+ private lockPath: string;
60
+ private jobs = new Map<string, ScheduledSubagent>();
61
+
62
+ constructor(filePath: string) {
63
+ this.filePath = filePath;
64
+ this.lockPath = filePath + ".lock";
65
+ this.load();
66
+ }
67
+
68
+ /** Create the backing directory lazily — only when we're about to persist. */
69
+ private ensureDir(): void {
70
+ mkdirSync(dirname(this.filePath), { recursive: true });
71
+ }
72
+
73
+ /** Load from disk into the in-memory cache. Silent on parse errors. */
74
+ private load(): void {
75
+ if (!existsSync(this.filePath)) return;
76
+ try {
77
+ const data: ScheduleStoreData = JSON.parse(readFileSync(this.filePath, "utf-8"));
78
+ this.jobs.clear();
79
+ for (const j of data.jobs ?? []) this.jobs.set(j.id, j);
80
+ } catch { /* corrupt — start fresh, next save rewrites */ }
81
+ }
82
+
83
+ /** Atomic write via temp file + rename (POSIX-atomic). */
84
+ private save(): void {
85
+ const data: ScheduleStoreData = { version: 1, jobs: [...this.jobs.values()] };
86
+ const tmp = this.filePath + ".tmp";
87
+ writeFileSync(tmp, JSON.stringify(data, null, 2));
88
+ renameSync(tmp, this.filePath);
89
+ }
90
+
91
+ /** Acquire lock → reload → mutate → save → release. */
92
+ private withLock<T>(fn: () => T): T {
93
+ this.ensureDir();
94
+ acquireLock(this.lockPath);
95
+ try {
96
+ this.load();
97
+ const result = fn();
98
+ this.save();
99
+ return result;
100
+ } finally {
101
+ releaseLock(this.lockPath);
102
+ }
103
+ }
104
+
105
+ /** Read-only — returns a snapshot of the in-memory cache. */
106
+ list(): ScheduledSubagent[] {
107
+ return [...this.jobs.values()];
108
+ }
109
+
110
+ /** Read-only check — uses the cache. */
111
+ hasName(name: string, exceptId?: string): boolean {
112
+ for (const j of this.jobs.values()) {
113
+ if (j.id !== exceptId && j.name === name) return true;
114
+ }
115
+ return false;
116
+ }
117
+
118
+ get(id: string): ScheduledSubagent | undefined {
119
+ return this.jobs.get(id);
120
+ }
121
+
122
+ add(job: ScheduledSubagent): void {
123
+ this.withLock(() => {
124
+ this.jobs.set(job.id, job);
125
+ });
126
+ }
127
+
128
+ update(id: string, patch: Partial<ScheduledSubagent>): ScheduledSubagent | undefined {
129
+ // No-op fast path — an unknown id changes nothing, so don't lock or touch
130
+ // disk (which would otherwise lazily create the backing directory).
131
+ if (!this.jobs.has(id)) return undefined;
132
+ return this.withLock(() => {
133
+ const existing = this.jobs.get(id);
134
+ if (!existing) return undefined;
135
+ const updated = { ...existing, ...patch };
136
+ this.jobs.set(id, updated);
137
+ return updated;
138
+ });
139
+ }
140
+
141
+ remove(id: string): boolean {
142
+ // No-op fast path — see update().
143
+ if (!this.jobs.has(id)) return false;
144
+ return this.withLock(() => this.jobs.delete(id));
145
+ }
146
+
147
+ /** Delete the backing file (used when no jobs remain, optional cleanup). */
148
+ deleteFileIfEmpty(): void {
149
+ if (this.jobs.size === 0 && existsSync(this.filePath)) {
150
+ try { unlinkSync(this.filePath); } catch { /* ignore */ }
151
+ }
152
+ }
153
+ }
@@ -0,0 +1,365 @@
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 { resolveModel } from "./model-resolver.js";
23
+ import type { ScheduleStore } from "./schedule-store.js";
24
+ import type { IsolationMode, ScheduledSubagent, SubagentType, ThinkingLevel } from "./types.js";
25
+
26
+ /** Event emitted on `pi.events` for cross-extension consumers. */
27
+ export type ScheduleChangeEvent =
28
+ | { type: "added"; job: ScheduledSubagent }
29
+ | { type: "removed"; jobId: string }
30
+ | { type: "updated"; job: ScheduledSubagent }
31
+ | { type: "fired"; jobId: string; agentId: string; name: string }
32
+ | { type: "error"; jobId: string; error: string };
33
+
34
+ /** Params accepted at job creation — ID, timestamps, and state are derived. */
35
+ export interface NewJobInput {
36
+ name: string;
37
+ description: string;
38
+ schedule: string;
39
+ subagent_type: SubagentType;
40
+ prompt: string;
41
+ model?: string;
42
+ thinking?: ThinkingLevel;
43
+ max_turns?: number;
44
+ isolated?: boolean;
45
+ isolation?: IsolationMode;
46
+ }
47
+
48
+ export class SubagentScheduler {
49
+ private jobs = new Map<string, Cron>();
50
+ private intervals = new Map<string, NodeJS.Timeout>();
51
+ private store: ScheduleStore | undefined;
52
+ private pi: ExtensionAPI | undefined;
53
+ private ctx: ExtensionContext | undefined;
54
+ private manager: AgentManager | undefined;
55
+
56
+ /** Start the scheduler: bind to a session's store and arm enabled jobs. */
57
+ start(pi: ExtensionAPI, ctx: ExtensionContext, manager: AgentManager, store: ScheduleStore): void {
58
+ this.pi = pi;
59
+ this.ctx = ctx;
60
+ this.manager = manager;
61
+ this.store = store;
62
+
63
+ for (const job of store.list()) {
64
+ if (job.enabled) this.scheduleJob(job);
65
+ }
66
+ }
67
+
68
+ /** Stop all timers; drop refs. Safe to call repeatedly. */
69
+ stop(): void {
70
+ for (const cron of this.jobs.values()) cron.stop();
71
+ this.jobs.clear();
72
+ for (const t of this.intervals.values()) clearTimeout(t);
73
+ this.intervals.clear();
74
+ this.store = undefined;
75
+ this.pi = undefined;
76
+ this.ctx = undefined;
77
+ this.manager = undefined;
78
+ }
79
+
80
+ /** True if start() has bound a store and the scheduler is active. */
81
+ isActive(): boolean {
82
+ return this.store !== undefined;
83
+ }
84
+
85
+ list(): ScheduledSubagent[] {
86
+ return this.store?.list() ?? [];
87
+ }
88
+
89
+ /**
90
+ * Build a `ScheduledSubagent` from user input. Validates the schedule
91
+ * format and tags `scheduleType`. Throws on invalid input.
92
+ */
93
+ buildJob(input: NewJobInput): ScheduledSubagent {
94
+ const detected = SubagentScheduler.detectSchedule(input.schedule);
95
+ return {
96
+ id: nanoid(10),
97
+ name: input.name,
98
+ description: input.description,
99
+ schedule: detected.normalized,
100
+ scheduleType: detected.type,
101
+ intervalMs: detected.intervalMs,
102
+ subagent_type: input.subagent_type,
103
+ prompt: input.prompt,
104
+ model: input.model,
105
+ thinking: input.thinking,
106
+ max_turns: input.max_turns,
107
+ isolated: input.isolated,
108
+ isolation: input.isolation,
109
+ enabled: true,
110
+ createdAt: new Date().toISOString(),
111
+ runCount: 0,
112
+ };
113
+ }
114
+
115
+ /** Add a job, persist, and arm if enabled. Returns the stored job. */
116
+ addJob(input: NewJobInput): ScheduledSubagent {
117
+ const store = this.requireStore();
118
+ if (store.hasName(input.name)) {
119
+ throw new Error(`A scheduled job named "${input.name}" already exists.`);
120
+ }
121
+ const job = this.buildJob(input);
122
+ store.add(job);
123
+ if (job.enabled) this.scheduleJob(job);
124
+ this.emit({ type: "added", job });
125
+ return job;
126
+ }
127
+
128
+ removeJob(id: string): boolean {
129
+ const store = this.requireStore();
130
+ if (!store.get(id)) return false;
131
+ this.unscheduleJob(id);
132
+ const ok = store.remove(id);
133
+ if (ok) this.emit({ type: "removed", jobId: id });
134
+ return ok;
135
+ }
136
+
137
+ /** Toggle / mutate a job. Re-arms based on the new `enabled` state. */
138
+ updateJob(id: string, patch: Partial<ScheduledSubagent>): ScheduledSubagent | undefined {
139
+ const store = this.requireStore();
140
+ const updated = store.update(id, patch);
141
+ if (!updated) return undefined;
142
+ this.unscheduleJob(id);
143
+ if (updated.enabled) this.scheduleJob(updated);
144
+ this.emit({ type: "updated", job: updated });
145
+ return updated;
146
+ }
147
+
148
+ /** Next-run time as ISO, or undefined if not currently armed. */
149
+ getNextRun(jobId: string): string | undefined {
150
+ const cron = this.jobs.get(jobId);
151
+ if (cron) return cron.nextRun()?.toISOString();
152
+ const job = this.store?.get(jobId);
153
+ if (!job?.enabled) return undefined;
154
+ if (job.scheduleType === "once") return job.schedule;
155
+ if (job.scheduleType === "interval" && job.intervalMs) {
156
+ // Before the first fire there's no `lastRun`, so fall back to "now" —
157
+ // accurate at create time (setInterval was just armed) and within
158
+ // intervalMs of correct in any pre-first-fire view.
159
+ const base = job.lastRun ? new Date(job.lastRun).getTime() : Date.now();
160
+ return new Date(base + job.intervalMs).toISOString();
161
+ }
162
+ return undefined;
163
+ }
164
+
165
+ // ── Scheduling primitives ────────────────────────────────────────────
166
+
167
+ private scheduleJob(job: ScheduledSubagent): void {
168
+ const store = this.store;
169
+ if (!store) return;
170
+ try {
171
+ if (job.scheduleType === "interval" && job.intervalMs) {
172
+ const t = setInterval(() => this.executeJob(job.id), job.intervalMs);
173
+ this.intervals.set(job.id, t);
174
+ } else if (job.scheduleType === "once") {
175
+ const target = new Date(job.schedule).getTime();
176
+ const delay = target - Date.now();
177
+ if (delay > 0) {
178
+ const t = setTimeout(() => {
179
+ this.executeJob(job.id);
180
+ // Auto-disable one-shots after they fire (mirrors pi-cron-schedule)
181
+ store.update(job.id, { enabled: false });
182
+ const updated = store.get(job.id);
183
+ if (updated) this.emit({ type: "updated", job: updated });
184
+ }, delay);
185
+ this.intervals.set(job.id, t);
186
+ } else {
187
+ // Past timestamp — disable, mark error, never fire
188
+ store.update(job.id, { enabled: false, lastStatus: "error" });
189
+ this.emit({ type: "error", jobId: job.id, error: `Scheduled time ${job.schedule} is in the past` });
190
+ }
191
+ } else {
192
+ const cron = new Cron(job.schedule, () => this.executeJob(job.id));
193
+ this.jobs.set(job.id, cron);
194
+ }
195
+ } catch (err) {
196
+ this.emit({ type: "error", jobId: job.id, error: err instanceof Error ? err.message : String(err) });
197
+ }
198
+ }
199
+
200
+ private unscheduleJob(id: string): void {
201
+ const cron = this.jobs.get(id);
202
+ if (cron) {
203
+ cron.stop();
204
+ this.jobs.delete(id);
205
+ }
206
+ const t = this.intervals.get(id);
207
+ if (t) {
208
+ clearTimeout(t);
209
+ clearInterval(t);
210
+ this.intervals.delete(id);
211
+ }
212
+ }
213
+
214
+ /**
215
+ * Fire a job: persist running state, spawn (bypassing the concurrency
216
+ * queue), persist completion. Fire-and-forget: the timer tick returns
217
+ * immediately so other jobs keep firing.
218
+ */
219
+ private executeJob(id: string): void {
220
+ const store = this.store;
221
+ const pi = this.pi;
222
+ const ctx = this.ctx;
223
+ const manager = this.manager;
224
+ if (!store || !pi || !ctx || !manager) return;
225
+ const job = store.get(id);
226
+ if (!job?.enabled) return;
227
+
228
+ store.update(id, { lastStatus: "running" });
229
+
230
+ // Resolve model at fire time — registry contents may have changed since the
231
+ // job was created (auth added/removed). Fall back silently to spawn-default
232
+ // if resolution fails; the spawn path handles undefined model gracefully.
233
+ let resolvedModel: any | undefined;
234
+ if (job.model) {
235
+ const r = resolveModel(job.model, ctx.modelRegistry);
236
+ if (typeof r !== "string") resolvedModel = r;
237
+ }
238
+
239
+ let agentId: string;
240
+ try {
241
+ agentId = manager.spawn(pi, ctx, job.subagent_type, job.prompt, {
242
+ description: job.description,
243
+ isBackground: true,
244
+ bypassQueue: true,
245
+ model: resolvedModel,
246
+ maxTurns: job.max_turns,
247
+ isolated: job.isolated,
248
+ thinkingLevel: job.thinking,
249
+ isolation: job.isolation,
250
+ });
251
+ } catch (err) {
252
+ const error = err instanceof Error ? err.message : String(err);
253
+ store.update(id, { lastRun: new Date().toISOString(), lastStatus: "error" });
254
+ this.emit({ type: "error", jobId: id, error });
255
+ return;
256
+ }
257
+
258
+ this.emit({ type: "fired", jobId: id, agentId, name: job.name });
259
+
260
+ const record = manager.getRecord(agentId);
261
+ const finalize = (status: "success" | "error") => {
262
+ const next = this.getNextRun(id);
263
+ const current = store.get(id);
264
+ store.update(id, {
265
+ lastRun: new Date().toISOString(),
266
+ lastStatus: status,
267
+ runCount: (current?.runCount ?? 0) + 1,
268
+ nextRun: next,
269
+ });
270
+ };
271
+
272
+ // AgentManager's promise resolves either way (its .catch returns ""), so we
273
+ // can't infer success/failure from the promise — read record.status instead.
274
+ // Terminal states: completed/steered = success; error/aborted/stopped = error.
275
+ if (record?.promise) {
276
+ record.promise
277
+ .then(() => {
278
+ const r = manager.getRecord(agentId);
279
+ const failed = r?.status === "error" || r?.status === "aborted" || r?.status === "stopped";
280
+ finalize(failed ? "error" : "success");
281
+ })
282
+ .catch(() => finalize("error"));
283
+ } else {
284
+ // Spawn returned without a promise (defensive — bypassQueue path always sets one).
285
+ finalize("success");
286
+ }
287
+ }
288
+
289
+ private emit(event: ScheduleChangeEvent): void {
290
+ if (this.pi) this.pi.events.emit("subagents:scheduled", event);
291
+ }
292
+
293
+ private requireStore(): ScheduleStore {
294
+ if (!this.store) throw new Error("Scheduler not started — no active session.");
295
+ return this.store;
296
+ }
297
+
298
+ // ── Format detection / parsers (statics — pure) ──────────────────────
299
+
300
+ /**
301
+ * Sniff a schedule string and tag its type. Throws on invalid input.
302
+ * Order matters: relative ("+10m") and interval ("5m") both match digit+unit;
303
+ * relative requires the leading "+" to disambiguate.
304
+ */
305
+ static detectSchedule(s: string): { type: "cron" | "once" | "interval"; intervalMs?: number; normalized: string } {
306
+ const trimmed = s.trim();
307
+ // "+10m" — relative one-shot
308
+ const rel = SubagentScheduler.parseRelativeTime(trimmed);
309
+ if (rel !== null) return { type: "once", normalized: rel };
310
+ // "5m" — interval
311
+ const ivl = SubagentScheduler.parseInterval(trimmed);
312
+ if (ivl !== null) return { type: "interval", intervalMs: ivl, normalized: trimmed };
313
+ // ISO timestamp — one-shot. Reject past timestamps upfront so we never
314
+ // create a dead-on-arrival record (scheduleJob's safety net still catches
315
+ // micro-races from `+0s`-style relatives).
316
+ if (/^\d{4}-\d{2}-\d{2}T/.test(trimmed)) {
317
+ const d = new Date(trimmed);
318
+ if (!Number.isNaN(d.getTime())) {
319
+ if (d.getTime() <= Date.now()) {
320
+ throw new Error(`Scheduled time ${d.toISOString()} is in the past.`);
321
+ }
322
+ return { type: "once", normalized: d.toISOString() };
323
+ }
324
+ }
325
+ // Cron — 6-field
326
+ const cronCheck = SubagentScheduler.validateCronExpression(trimmed);
327
+ if (cronCheck.valid) return { type: "cron", normalized: trimmed };
328
+ throw new Error(
329
+ `Invalid schedule "${s}". Use 6-field cron (e.g. "0 0 9 * * 1" — 9am every Monday), interval ("5m"/"1h"), or one-shot ("+10m" / ISO).`
330
+ );
331
+ }
332
+
333
+ /** 6-field cron — 'second minute hour dom month dow'. */
334
+ static validateCronExpression(expr: string): { valid: boolean; error?: string } {
335
+ const fields = expr.trim().split(/\s+/);
336
+ if (fields.length !== 6) {
337
+ return {
338
+ valid: false,
339
+ error: `Cron must have 6 fields (second minute hour dom month dow), got ${fields.length}. Example: "0 0 9 * * 1" for 9am every Monday.`,
340
+ };
341
+ }
342
+ try {
343
+ // Croner validates by construction.
344
+ new Cron(expr, () => {});
345
+ return { valid: true };
346
+ } catch (e) {
347
+ return { valid: false, error: e instanceof Error ? e.message : "Invalid cron expression" };
348
+ }
349
+ }
350
+
351
+ /** "+10s"/"+5m"/"+1h"/"+2d" → ISO timestamp. */
352
+ static parseRelativeTime(s: string): string | null {
353
+ const m = s.match(/^\+(\d+)(s|m|h|d)$/);
354
+ if (!m) return null;
355
+ 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"];
356
+ return new Date(Date.now() + ms).toISOString();
357
+ }
358
+
359
+ /** "10s"/"5m"/"1h"/"2d" → milliseconds. */
360
+ static parseInterval(s: string): number | null {
361
+ const m = s.match(/^(\d+)(s|m|h|d)$/);
362
+ if (!m) return null;
363
+ 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"];
364
+ }
365
+ }