@ymy88/pi-subagents 0.0.0-stage → 0.24.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 (196) hide show
  1. package/CHANGELOG.md +904 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1170 -2
  5. package/SECURITY.md +95 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/agent-color.d.ts +35 -0
  9. package/dist/agent-color.js +123 -0
  10. package/dist/agent-file-toggle.d.ts +133 -0
  11. package/dist/agent-file-toggle.js +287 -0
  12. package/dist/agent-manager.d.ts +552 -0
  13. package/dist/agent-manager.js +1466 -0
  14. package/dist/agent-record-entry.d.ts +96 -0
  15. package/dist/agent-record-entry.js +121 -0
  16. package/dist/agent-runner.d.ts +310 -0
  17. package/dist/agent-runner.js +1195 -0
  18. package/dist/agent-source-badge.d.ts +50 -0
  19. package/dist/agent-source-badge.js +74 -0
  20. package/dist/agent-types.d.ts +119 -0
  21. package/dist/agent-types.js +286 -0
  22. package/dist/child-context.d.ts +2 -0
  23. package/dist/child-context.js +12 -0
  24. package/dist/completion-outbox.d.ts +63 -0
  25. package/dist/completion-outbox.js +104 -0
  26. package/dist/context.d.ts +12 -0
  27. package/dist/context.js +56 -0
  28. package/dist/cross-extension-rpc.d.ts +72 -0
  29. package/dist/cross-extension-rpc.js +153 -0
  30. package/dist/custom-agents.d.ts +77 -0
  31. package/dist/custom-agents.js +396 -0
  32. package/dist/default-agents.d.ts +7 -0
  33. package/dist/default-agents.js +121 -0
  34. package/dist/enabled-models.d.ts +49 -0
  35. package/dist/enabled-models.js +145 -0
  36. package/dist/env.d.ts +6 -0
  37. package/dist/env.js +28 -0
  38. package/dist/group-join.d.ts +32 -0
  39. package/dist/group-join.js +116 -0
  40. package/dist/index.d.ts +50 -0
  41. package/dist/index.js +4111 -0
  42. package/dist/invocation-config.d.ts +108 -0
  43. package/dist/invocation-config.js +83 -0
  44. package/dist/memory.d.ts +53 -0
  45. package/dist/memory.js +165 -0
  46. package/dist/mention-clone.d.ts +79 -0
  47. package/dist/mention-clone.js +155 -0
  48. package/dist/mention.d.ts +81 -0
  49. package/dist/mention.js +131 -0
  50. package/dist/model-resolver.d.ts +36 -0
  51. package/dist/model-resolver.js +95 -0
  52. package/dist/model-scope.d.ts +49 -0
  53. package/dist/model-scope.js +48 -0
  54. package/dist/nested-tools.d.ts +57 -0
  55. package/dist/nested-tools.js +303 -0
  56. package/dist/output-file.d.ts +43 -0
  57. package/dist/output-file.js +153 -0
  58. package/dist/package-resources.d.ts +240 -0
  59. package/dist/package-resources.js +519 -0
  60. package/dist/prompts.d.ts +76 -0
  61. package/dist/prompts.js +121 -0
  62. package/dist/schedule-store.d.ts +38 -0
  63. package/dist/schedule-store.js +155 -0
  64. package/dist/schedule.d.ts +109 -0
  65. package/dist/schedule.js +359 -0
  66. package/dist/settings.d.ts +398 -0
  67. package/dist/settings.js +282 -0
  68. package/dist/skill-loader.d.ts +24 -0
  69. package/dist/skill-loader.js +93 -0
  70. package/dist/status-note.d.ts +61 -0
  71. package/dist/status-note.js +85 -0
  72. package/dist/structured-output.d.ts +61 -0
  73. package/dist/structured-output.js +112 -0
  74. package/dist/types.d.ts +391 -0
  75. package/dist/types.js +5 -0
  76. package/dist/ui/agent-mention.d.ts +82 -0
  77. package/dist/ui/agent-mention.js +187 -0
  78. package/dist/ui/agent-widget.d.ts +219 -0
  79. package/dist/ui/agent-widget.js +585 -0
  80. package/dist/ui/conversation-viewer.d.ts +177 -0
  81. package/dist/ui/conversation-viewer.js +905 -0
  82. package/dist/ui/fleet-list.d.ts +211 -0
  83. package/dist/ui/fleet-list.js +489 -0
  84. package/dist/ui/schedule-menu.d.ts +16 -0
  85. package/dist/ui/schedule-menu.js +94 -0
  86. package/dist/ui/select-item.d.ts +27 -0
  87. package/dist/ui/select-item.js +34 -0
  88. package/dist/ui/viewer-keys.d.ts +22 -0
  89. package/dist/ui/viewer-keys.js +18 -0
  90. package/dist/ui/workflow-card.d.ts +175 -0
  91. package/dist/ui/workflow-card.js +332 -0
  92. package/dist/ui/workflow-dialog.d.ts +305 -0
  93. package/dist/ui/workflow-dialog.js +843 -0
  94. package/dist/ui/workflow-menu.d.ts +60 -0
  95. package/dist/ui/workflow-menu.js +147 -0
  96. package/dist/usage.d.ts +135 -0
  97. package/dist/usage.js +120 -0
  98. package/dist/workflow/collisions.d.ts +95 -0
  99. package/dist/workflow/collisions.js +88 -0
  100. package/dist/workflow/entry.d.ts +32 -0
  101. package/dist/workflow/entry.js +29 -0
  102. package/dist/workflow/host.d.ts +62 -0
  103. package/dist/workflow/host.js +419 -0
  104. package/dist/workflow/journal.d.ts +97 -0
  105. package/dist/workflow/journal.js +120 -0
  106. package/dist/workflow/json-schema.d.ts +52 -0
  107. package/dist/workflow/json-schema.js +112 -0
  108. package/dist/workflow/meta.d.ts +67 -0
  109. package/dist/workflow/meta.js +317 -0
  110. package/dist/workflow/progress.d.ts +224 -0
  111. package/dist/workflow/progress.js +361 -0
  112. package/dist/workflow/runtime.d.ts +334 -0
  113. package/dist/workflow/runtime.js +830 -0
  114. package/dist/workflow/saved.d.ts +102 -0
  115. package/dist/workflow/saved.js +247 -0
  116. package/dist/workflow/task.d.ts +136 -0
  117. package/dist/workflow/task.js +207 -0
  118. package/dist/workflow/tool-description.d.ts +38 -0
  119. package/dist/workflow/tool-description.js +199 -0
  120. package/dist/workflow/worker-source.d.ts +47 -0
  121. package/dist/workflow/worker-source.js +778 -0
  122. package/dist/worktree.d.ts +52 -0
  123. package/dist/worktree.js +164 -0
  124. package/dist/xml.d.ts +10 -0
  125. package/dist/xml.js +12 -0
  126. package/docs/packages.md +211 -0
  127. package/docs/rpc.md +192 -0
  128. package/docs/workflows.md +447 -0
  129. package/examples/agent-tool-description.md +42 -0
  130. package/examples/workflows/compose.js +51 -0
  131. package/examples/workflows/fan-out-audit.js +47 -0
  132. package/examples/workflows/gated-fix.js +60 -0
  133. package/examples/workflows/lib/count-child.js +27 -0
  134. package/examples/workflows/review-panel.js +63 -0
  135. package/examples/workflows/structured-findings.js +78 -0
  136. package/package.json +74 -4
  137. package/src/abortable.ts +43 -0
  138. package/src/agent-color.ts +161 -0
  139. package/src/agent-file-toggle.ts +297 -0
  140. package/src/agent-manager.ts +1735 -0
  141. package/src/agent-record-entry.ts +153 -0
  142. package/src/agent-runner.ts +1468 -0
  143. package/src/agent-source-badge.ts +75 -0
  144. package/src/agent-types.ts +346 -0
  145. package/src/child-context.ts +15 -0
  146. package/src/completion-outbox.ts +116 -0
  147. package/src/context.ts +58 -0
  148. package/src/cross-extension-rpc.ts +221 -0
  149. package/src/custom-agents.ts +452 -0
  150. package/src/default-agents.ts +125 -0
  151. package/src/enabled-models.ts +180 -0
  152. package/src/env.ts +33 -0
  153. package/src/group-join.ts +141 -0
  154. package/src/index.ts +4433 -0
  155. package/src/invocation-config.ts +155 -0
  156. package/src/memory.ts +179 -0
  157. package/src/mention-clone.ts +195 -0
  158. package/src/mention.ts +141 -0
  159. package/src/model-resolver.ts +118 -0
  160. package/src/model-scope.ts +70 -0
  161. package/src/nested-tools.ts +426 -0
  162. package/src/output-file.ts +164 -0
  163. package/src/package-resources.ts +652 -0
  164. package/src/prompts.ts +171 -0
  165. package/src/schedule-store.ts +153 -0
  166. package/src/schedule.ts +386 -0
  167. package/src/settings.ts +650 -0
  168. package/src/skill-loader.ts +102 -0
  169. package/src/status-note.ts +90 -0
  170. package/src/structured-output.ts +130 -0
  171. package/src/types.ts +404 -0
  172. package/src/ui/agent-mention.ts +216 -0
  173. package/src/ui/agent-widget.ts +661 -0
  174. package/src/ui/conversation-viewer.ts +928 -0
  175. package/src/ui/fleet-list.ts +559 -0
  176. package/src/ui/schedule-menu.ts +105 -0
  177. package/src/ui/select-item.ts +45 -0
  178. package/src/ui/viewer-keys.ts +43 -0
  179. package/src/ui/workflow-card.ts +470 -0
  180. package/src/ui/workflow-dialog.ts +1115 -0
  181. package/src/ui/workflow-menu.ts +193 -0
  182. package/src/usage.ts +167 -0
  183. package/src/workflow/collisions.ts +123 -0
  184. package/src/workflow/entry.ts +47 -0
  185. package/src/workflow/host.ts +467 -0
  186. package/src/workflow/journal.ts +164 -0
  187. package/src/workflow/json-schema.ts +129 -0
  188. package/src/workflow/meta.ts +325 -0
  189. package/src/workflow/progress.ts +551 -0
  190. package/src/workflow/runtime.ts +1219 -0
  191. package/src/workflow/saved.ts +259 -0
  192. package/src/workflow/task.ts +302 -0
  193. package/src/workflow/tool-description.ts +200 -0
  194. package/src/workflow/worker-source.ts +781 -0
  195. package/src/worktree.ts +205 -0
  196. package/src/xml.ts +13 -0
@@ -0,0 +1,121 @@
1
+ /**
2
+ * prompts.ts — System prompt builder for agents.
3
+ */
4
+ /**
5
+ * Build the system prompt for an agent from its config.
6
+ *
7
+ * - "replace" mode: env header + config.systemPrompt (full control, no parent identity)
8
+ * - "append" mode: parent system prompt + sub-agent context + env header + config.systemPrompt
9
+ * - "append" with empty systemPrompt: pure parent clone
10
+ *
11
+ * Both modes include an `<active_agent name="${config.name}"/>` tag so downstream
12
+ * extensions (e.g. permission/policy systems) can resolve per-agent policy
13
+ * inside the child session by parsing the system prompt. In replace mode the tag
14
+ * is prepended; in append mode it follows the shared inherited content so the
15
+ * parent prompt forms an identical, cacheable byte prefix with the parent
16
+ * session (the LLM's KV cache can then reuse those tokens across every spawn).
17
+ *
18
+ * @param parentSystemPrompt The parent agent's effective system prompt (for append mode).
19
+ * @param extras Optional extra sections to inject (memory, preloaded skills).
20
+ */
21
+ export function buildAgentPrompt(config, cwd, env, parentSystemPrompt, extras) {
22
+ const activeAgentTag = `<active_agent name="${config.name}"/>\n\n`;
23
+ const envBlock = `# Environment
24
+ Working directory: ${cwd}
25
+ ${env.isGitRepo ? `Git repository: yes\nBranch: ${env.branch}` : "Not a git repository"}
26
+ Platform: ${env.platform}`;
27
+ // A worktree agent is told its cwd twice: by the env block above (the copy)
28
+ // and by whatever names the main checkout — the inherited parent prompt in
29
+ // append mode, or the task prompt in either mode. It follows the latter and
30
+ // works in the shared tree (#187), so resolve the contradiction explicitly.
31
+ const worktreeBlock = extras?.worktreeBase
32
+ ? `\n\n<worktree_isolation>
33
+ Your working directory is an isolated git worktree copy of ${extras.worktreeBase}.
34
+ Work only inside it — never in ${extras.worktreeBase}, even if other instructions name that path as your working directory.
35
+ </worktree_isolation>`
36
+ : "";
37
+ // The script, not a person, reads what this child returns — see
38
+ // `PromptExtras.workflowChild` for why only workflow children get this.
39
+ const workflowBlock = extras?.workflowChild
40
+ ? `\n\n<workflow_child>
41
+ Your final message IS the return value of this task. A workflow script captures it and passes it to the next stage; no person reads it.
42
+ Return only the answer, in exactly the shape the prompt asks for — no preamble, no summary of what you did, no offer to continue.
43
+ </workflow_child>`
44
+ : "";
45
+ // Build optional extras suffix
46
+ const extraSections = [];
47
+ if (extras?.memoryBlock) {
48
+ extraSections.push(extras.memoryBlock);
49
+ }
50
+ if (extras?.skillBlocks?.length) {
51
+ for (const skill of extras.skillBlocks) {
52
+ extraSections.push(`\n# Preloaded Skill: ${skill.name}\n${skill.content}`);
53
+ }
54
+ }
55
+ const extrasSuffix = extraSections.length > 0 ? "\n\n" + extraSections.join("\n") : "";
56
+ if (config.promptMode === "append") {
57
+ const identity = parentSystemPrompt || genericBase;
58
+ const bridge = `<sub_agent_context>
59
+ You are operating as a sub-agent invoked to handle a specific task.
60
+ - Use the read tool instead of cat/head/tail
61
+ - Use the edit tool instead of sed/awk
62
+ - Use the write tool instead of echo/heredoc
63
+ - Use the find tool instead of bash find/ls for file search
64
+ - Use the grep tool instead of bash grep/rg for content search
65
+ - Make independent tool calls in parallel
66
+ - Use absolute file paths
67
+ - Do not use emojis
68
+ - Be concise but complete
69
+ </sub_agent_context>`;
70
+ const customSection = config.systemPrompt?.trim()
71
+ ? `\n\n<agent_instructions>\n${config.systemPrompt}\n</agent_instructions>`
72
+ : "";
73
+ // Place shared/stable content first so the LLM's KV cache can reuse the
74
+ // inherited prefix across all subagent invocations. The parent prompt is
75
+ // placed verbatim (no wrapper tag) so it forms an identical byte prefix
76
+ // with the parent session, maximising KV cache hits. The <active_agent>
77
+ // tag and env block vary per call and are placed after the cached prefix.
78
+ return identity + "\n\n" + bridge + "\n\n" + activeAgentTag + envBlock + worktreeBlock + workflowBlock + customSection + extrasSuffix;
79
+ }
80
+ // "replace" mode — env header + the config's full system prompt
81
+ const replaceHeader = `You are a pi coding agent sub-agent.
82
+ You have been invoked to handle a specific task autonomously.
83
+
84
+ ${envBlock}`;
85
+ return activeAgentTag + replaceHeader + worktreeBlock + workflowBlock + "\n\n" + config.systemPrompt + extrasSuffix;
86
+ }
87
+ /**
88
+ * The part of the parent's rendered system prompt that an append-mode child inherits.
89
+ *
90
+ * Pi renders a prompt as the preamble followed by tagged sections in a fixed order:
91
+ * `tools`, `rules`, `docs` (default preamble only), `addendum`, `project_context`,
92
+ * `skills`, `cwd`, then the sections extensions add during a turn. The child session renders its own `skills` (from its `skills:`
93
+ * setting), its own `cwd` and its own extension sections after the inherited text.
94
+ * Inheriting the parent's copies too listed them twice, showed the parent's skills to
95
+ * children configured with `skills: false` or a preload list, and left copies that
96
+ * section-editing extensions in the child cannot reach. It also made the result depend
97
+ * on timing: `getSystemPrompt()` includes the extension sections only while the
98
+ * parent's turn runs.
99
+ *
100
+ * Returns the text before the `skills` section, or before the `cwd` section when there
101
+ * are no skills. A prompt without the `cwd` section (for example, a forced prompt) is
102
+ * returned unchanged.
103
+ *
104
+ * @param rendered The parent's `ctx.getSystemPrompt()`.
105
+ * @param cwd The cwd the parent's prompt was rendered with.
106
+ */
107
+ export function inheritableParentPrompt(rendered, cwd) {
108
+ const cwdAt = rendered.lastIndexOf(`\n\n<cwd>\n${cwd.replace(/\\/g, "/")}\n</cwd>`);
109
+ if (cwdAt < 0)
110
+ return rendered;
111
+ const head = rendered.slice(0, cwdAt);
112
+ if (!head.endsWith("\n</skills>"))
113
+ return head;
114
+ const skillsAt = head.lastIndexOf("\n\n<skills>\n");
115
+ return skillsAt < 0 ? head : head.slice(0, skillsAt);
116
+ }
117
+ /** Fallback base prompt when parent system prompt is unavailable in append mode. */
118
+ const genericBase = `# Role
119
+ You are a general-purpose coding agent for complex, multi-step tasks.
120
+ You have full access to read, write, edit files, and execute commands.
121
+ Do what has been asked; nothing more, nothing less.`;
@@ -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` 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
+ }