@timmyjl12/pi-subagents 0.20.0 → 0.21.1

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 (159) hide show
  1. package/CHANGELOG.md +862 -827
  2. package/README.md +1125 -1080
  3. package/dist/active-agents-prompt.d.ts +31 -9
  4. package/dist/active-agents-prompt.js +73 -9
  5. package/dist/agent-color.js +9 -1
  6. package/dist/agent-file-toggle.d.ts +1 -1
  7. package/dist/agent-manager.d.ts +405 -18
  8. package/dist/agent-manager.js +1661 -131
  9. package/dist/agent-runner.d.ts +45 -6
  10. package/dist/agent-runner.js +109 -18
  11. package/dist/agent-types.d.ts +30 -7
  12. package/dist/agent-types.js +38 -9
  13. package/dist/awaited-result.d.ts +37 -0
  14. package/dist/awaited-result.js +150 -0
  15. package/dist/child-session-shutdown.d.ts +19 -1
  16. package/dist/child-session-shutdown.js +60 -11
  17. package/dist/cleanup-plans.d.ts +10 -0
  18. package/dist/cleanup-plans.js +112 -0
  19. package/dist/cross-extension-rpc.d.ts +8 -1
  20. package/dist/cross-extension-rpc.js +59 -5
  21. package/dist/custom-agents.d.ts +34 -9
  22. package/dist/custom-agents.js +308 -111
  23. package/dist/default-agents.d.ts +1 -1
  24. package/dist/env.d.ts +1 -1
  25. package/dist/error-log.d.ts +6 -0
  26. package/dist/error-log.js +8 -0
  27. package/dist/force-main-model.d.ts +21 -0
  28. package/dist/force-main-model.js +28 -0
  29. package/dist/goal-bridge.d.ts +155 -0
  30. package/dist/goal-bridge.js +305 -0
  31. package/dist/group-join.d.ts +5 -1
  32. package/dist/group-join.js +52 -7
  33. package/dist/index.d.ts +5 -5
  34. package/dist/index.js +2827 -333
  35. package/dist/invocation-config.d.ts +30 -3
  36. package/dist/invocation-config.js +30 -1
  37. package/dist/memory.d.ts +1 -1
  38. package/dist/mention-clone.d.ts +1 -1
  39. package/dist/model-scope.d.ts +1 -1
  40. package/dist/nested-tools.d.ts +22 -1
  41. package/dist/nested-tools.js +120 -26
  42. package/dist/output-file.d.ts +15 -4
  43. package/dist/output-file.js +146 -43
  44. package/dist/prompts.d.ts +1 -1
  45. package/dist/recovery.d.ts +1 -1
  46. package/dist/report-cleanup.d.ts +204 -0
  47. package/dist/report-cleanup.js +1632 -0
  48. package/dist/report-store.d.ts +738 -0
  49. package/dist/report-store.js +3616 -0
  50. package/dist/schedule-store.d.ts +14 -6
  51. package/dist/schedule-store.js +88 -58
  52. package/dist/schedule.d.ts +20 -8
  53. package/dist/schedule.js +135 -74
  54. package/dist/settings.d.ts +39 -11
  55. package/dist/settings.js +22 -5
  56. package/dist/status-note.d.ts +1 -1
  57. package/dist/structured-output.d.ts +1 -1
  58. package/dist/types.d.ts +32 -3
  59. package/dist/ui/agent-mention.d.ts +2 -2
  60. package/dist/ui/agent-widget.d.ts +82 -13
  61. package/dist/ui/agent-widget.js +155 -37
  62. package/dist/ui/cleanup-preview.d.ts +59 -0
  63. package/dist/ui/cleanup-preview.js +466 -0
  64. package/dist/ui/conversation-viewer.d.ts +4 -4
  65. package/dist/ui/conversation-viewer.js +10 -6
  66. package/dist/ui/fleet-list.d.ts +3 -3
  67. package/dist/ui/fleet-list.js +3 -3
  68. package/dist/ui/fleet-overlay.d.ts +37 -6
  69. package/dist/ui/fleet-overlay.js +214 -18
  70. package/dist/ui/hub-feed.d.ts +52 -0
  71. package/dist/ui/hub-feed.js +148 -0
  72. package/dist/ui/native-transcript.js +5 -1
  73. package/dist/ui/schedule-menu.d.ts +1 -1
  74. package/dist/ui/schedule-menu.js +1 -1
  75. package/dist/ui/workflow-card.d.ts +4 -4
  76. package/dist/ui/workflow-dialog.d.ts +4 -4
  77. package/dist/ui/workflow-dialog.js +8 -3
  78. package/dist/ui/workflow-menu.d.ts +2 -2
  79. package/dist/usage.d.ts +12 -0
  80. package/dist/usage.js +28 -1
  81. package/dist/workflow/entry.d.ts +3 -3
  82. package/dist/workflow/host.d.ts +7 -4
  83. package/dist/workflow/host.js +162 -48
  84. package/dist/workflow/journal.d.ts +23 -7
  85. package/dist/workflow/journal.js +80 -23
  86. package/dist/workflow/progress.d.ts +1 -1
  87. package/dist/workflow/runtime.d.ts +45 -6
  88. package/dist/workflow/runtime.js +105 -16
  89. package/dist/workflow/task.d.ts +13 -4
  90. package/dist/workflow/task.js +7 -1
  91. package/dist/workflow/tool-description.d.ts +7 -2
  92. package/dist/workflow/tool-description.js +10 -5
  93. package/docs/{FORK.md → DEVELOPMENT.md} +4 -4
  94. package/docs/artifacts.md +93 -0
  95. package/docs/rpc.md +252 -189
  96. package/docs/runtime-performance.md +53 -0
  97. package/docs/workflows.md +48 -18
  98. package/examples/agent-tool-description.md +2 -2
  99. package/examples/workflows/review-panel.js +6 -3
  100. package/package.json +5 -5
  101. package/src/active-agents-prompt.ts +115 -39
  102. package/src/agent-color.ts +10 -2
  103. package/src/agent-file-toggle.ts +2 -2
  104. package/src/agent-manager.ts +3312 -1601
  105. package/src/agent-runner.ts +164 -36
  106. package/src/agent-types.ts +56 -11
  107. package/src/awaited-result.ts +187 -0
  108. package/src/child-session-shutdown.ts +114 -46
  109. package/src/cleanup-plans.ts +112 -0
  110. package/src/cross-extension-rpc.ts +68 -9
  111. package/src/custom-agents.ts +384 -112
  112. package/src/default-agents.ts +1 -1
  113. package/src/enabled-models.ts +1 -1
  114. package/src/env.ts +1 -1
  115. package/src/error-log.ts +10 -1
  116. package/src/force-main-model.ts +29 -0
  117. package/src/goal-bridge.ts +468 -0
  118. package/src/group-join.ts +56 -9
  119. package/src/index.ts +2987 -349
  120. package/src/invocation-config.ts +50 -4
  121. package/src/memory.ts +1 -1
  122. package/src/mention-clone.ts +3 -3
  123. package/src/model-scope.ts +1 -1
  124. package/src/nested-tools.ts +164 -33
  125. package/src/output-file.ts +168 -46
  126. package/src/prompts.ts +1 -1
  127. package/src/recovery.ts +2 -2
  128. package/src/report-cleanup.ts +2044 -0
  129. package/src/report-store.ts +4133 -0
  130. package/src/schedule-store.ts +244 -201
  131. package/src/schedule.ts +144 -80
  132. package/src/settings.ts +61 -16
  133. package/src/skill-loader.ts +1 -1
  134. package/src/standalone-fallback.ts +2 -2
  135. package/src/status-note.ts +1 -1
  136. package/src/structured-output.ts +1 -1
  137. package/src/types.ts +33 -3
  138. package/src/ui/agent-mention.ts +3 -3
  139. package/src/ui/agent-widget.ts +179 -45
  140. package/src/ui/cleanup-preview.ts +518 -0
  141. package/src/ui/conversation-viewer.ts +19 -15
  142. package/src/ui/fleet-list.ts +7 -7
  143. package/src/ui/fleet-overlay.ts +1048 -847
  144. package/src/ui/hub-feed.ts +179 -0
  145. package/src/ui/native-transcript.ts +7 -3
  146. package/src/ui/schedule-menu.ts +4 -4
  147. package/src/ui/workflow-card.ts +4 -4
  148. package/src/ui/workflow-dialog.ts +10 -6
  149. package/src/ui/workflow-menu.ts +4 -4
  150. package/src/usage.ts +53 -3
  151. package/src/workflow/collisions.ts +1 -1
  152. package/src/workflow/entry.ts +3 -3
  153. package/src/workflow/host.ts +174 -54
  154. package/src/workflow/journal.ts +80 -23
  155. package/src/workflow/progress.ts +1 -1
  156. package/src/workflow/runtime.ts +146 -23
  157. package/src/workflow/saved.ts +3 -3
  158. package/src/workflow/task.ts +18 -7
  159. package/src/workflow/tool-description.ts +10 -5
@@ -1,201 +1,244 @@
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 { randomBytes } from "node:crypto";
14
- import { existsSync, mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
15
- import { dirname, join } from "node:path";
16
- import type { ScheduledSubagent, ScheduleStoreData } from "./types.js";
17
-
18
- const LOCK_RETRY_MS = 50;
19
- /** Total synchronous wait for the lock. Mutations run on the UI thread. */
20
- const LOCK_MAX_WAIT_MS = 1000;
21
- /**
22
- * A lock older than this is stale whatever its PID says: Windows reuses PIDs
23
- * aggressively, so "that process is alive" does not mean it holds the lock.
24
- * A mutation holds the lock for a few milliseconds.
25
- */
26
- export const LOCK_STALE_MS = 30_000;
27
- const RENAME_RETRIES = 5;
28
- const RENAME_RETRY_MS = 20;
29
-
30
- /** Block the thread without spinning the CPU. */
31
- function sleepSync(ms: number): void {
32
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
33
- }
34
-
35
- function isProcessRunning(pid: number): boolean {
36
- try { process.kill(pid, 0); return true; } catch { return false; }
37
- }
38
-
39
- function errorCode(e: unknown): string | undefined {
40
- const code = (e as { code?: unknown } | null)?.code;
41
- return typeof code === "string" ? code : undefined;
42
- }
43
-
44
- /** True when the existing lock file can be broken: too old, or its owner is gone. */
45
- function isLockStale(lockPath: string): boolean {
46
- try {
47
- if (Date.now() - statSync(lockPath).mtimeMs > LOCK_STALE_MS) return true;
48
- const pid = parseInt(readFileSync(lockPath, "utf-8"), 10);
49
- return Number.isInteger(pid) && pid > 0 && !isProcessRunning(pid);
50
- } catch (e) {
51
- // Vanished between our write attempt and this check: retry the write.
52
- return errorCode(e) === "ENOENT";
53
- }
54
- }
55
-
56
- function acquireLock(lockPath: string): void {
57
- const deadline = Date.now() + LOCK_MAX_WAIT_MS;
58
- for (;;) {
59
- try {
60
- writeFileSync(lockPath, `${process.pid}`, { flag: "wx" });
61
- return;
62
- } catch (e) {
63
- if (errorCode(e) !== "EEXIST") throw e;
64
- }
65
- if (isLockStale(lockPath)) {
66
- try { unlinkSync(lockPath); } catch (e) {
67
- if (errorCode(e) !== "ENOENT") throw e;
68
- }
69
- continue;
70
- }
71
- if (Date.now() >= deadline) break;
72
- sleepSync(LOCK_RETRY_MS);
73
- }
74
- throw new Error(`Failed to acquire schedule lock: ${lockPath}`);
75
- }
76
-
77
- /** rename with a bounded retry: Windows reports EPERM/EBUSY while AV or an indexer holds the target. */
78
- function renameWithRetry(from: string, to: string): void {
79
- for (let attempt = 0; ; attempt++) {
80
- try {
81
- renameSync(from, to);
82
- return;
83
- } catch (e) {
84
- const code = errorCode(e);
85
- const transient = code === "EPERM" || code === "EBUSY" || code === "EACCES";
86
- if (!transient || attempt >= RENAME_RETRIES) {
87
- try { unlinkSync(from); } catch { /* best effort: the rename error below is the one that matters */ }
88
- throw e;
89
- }
90
- sleepSync(RENAME_RETRY_MS * (attempt + 1));
91
- }
92
- }
93
- }
94
-
95
- function releaseLock(lockPath: string): void {
96
- try { unlinkSync(lockPath); } catch { /* ignore */ }
97
- }
98
-
99
- /** Resolve the storage path for a session-scoped store. */
100
- export function resolveStorePath(cwd: string, sessionId: string): string {
101
- return join(cwd, ".pi", "subagent-schedules", `${sessionId}.json`);
102
- }
103
-
104
- export class ScheduleStore {
105
- private filePath: string;
106
- private lockPath: string;
107
- private jobs = new Map<string, ScheduledSubagent>();
108
-
109
- constructor(filePath: string) {
110
- this.filePath = filePath;
111
- this.lockPath = filePath + ".lock";
112
- this.load();
113
- }
114
-
115
- /** Create the backing directory lazily — only when we're about to persist. */
116
- private ensureDir(): void {
117
- mkdirSync(dirname(this.filePath), { recursive: true });
118
- }
119
-
120
- /** Load from disk into the in-memory cache. Silent on parse errors. */
121
- private load(): void {
122
- if (!existsSync(this.filePath)) return;
123
- try {
124
- const data: ScheduleStoreData = JSON.parse(readFileSync(this.filePath, "utf-8"));
125
- this.jobs.clear();
126
- for (const j of data.jobs ?? []) this.jobs.set(j.id, j);
127
- } catch { /* corrupt — start fresh, next save rewrites */ }
128
- }
129
-
130
- /** Atomic write via temp file + rename (POSIX-atomic). */
131
- private save(): void {
132
- const data: ScheduleStoreData = { version: 1, jobs: [...this.jobs.values()] };
133
- // Unique per write, so two writers can never clobber each other's temp file.
134
- const tmp = `${this.filePath}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
135
- writeFileSync(tmp, JSON.stringify(data, null, 2));
136
- renameWithRetry(tmp, this.filePath);
137
- }
138
-
139
- /** Acquire lock → reload → mutate → save → release. */
140
- private withLock<T>(fn: () => T): T {
141
- this.ensureDir();
142
- acquireLock(this.lockPath);
143
- try {
144
- this.load();
145
- const result = fn();
146
- this.save();
147
- return result;
148
- } finally {
149
- releaseLock(this.lockPath);
150
- }
151
- }
152
-
153
- /** Read-only — returns a snapshot of the in-memory cache. */
154
- list(): ScheduledSubagent[] {
155
- return [...this.jobs.values()];
156
- }
157
-
158
- /** Read-only check — uses the cache. */
159
- hasName(name: string, exceptId?: string): boolean {
160
- for (const j of this.jobs.values()) {
161
- if (j.id !== exceptId && j.name === name) return true;
162
- }
163
- return false;
164
- }
165
-
166
- get(id: string): ScheduledSubagent | undefined {
167
- return this.jobs.get(id);
168
- }
169
-
170
- add(job: ScheduledSubagent): void {
171
- this.withLock(() => {
172
- this.jobs.set(job.id, job);
173
- });
174
- }
175
-
176
- update(id: string, patch: Partial<ScheduledSubagent>): ScheduledSubagent | undefined {
177
- // No-op fast path — an unknown id changes nothing, so don't lock or touch
178
- // disk (which would otherwise lazily create the backing directory).
179
- if (!this.jobs.has(id)) return undefined;
180
- return this.withLock(() => {
181
- const existing = this.jobs.get(id);
182
- if (!existing) return undefined;
183
- const updated = { ...existing, ...patch };
184
- this.jobs.set(id, updated);
185
- return updated;
186
- });
187
- }
188
-
189
- remove(id: string): boolean {
190
- // No-op fast path — see update().
191
- if (!this.jobs.has(id)) return false;
192
- return this.withLock(() => this.jobs.delete(id));
193
- }
194
-
195
- /** Delete the backing file (used when no jobs remain, optional cleanup). */
196
- deleteFileIfEmpty(): void {
197
- if (this.jobs.size === 0 && existsSync(this.filePath)) {
198
- try { unlinkSync(this.filePath); } catch { /* ignore */ }
199
- }
200
- }
201
- }
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 { randomBytes } from "node:crypto";
14
+ import { readFileSync } from "node:fs";
15
+ import { mkdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
16
+ import { dirname, join } from "node:path";
17
+ import { setTimeout as sleep } from "node:timers/promises";
18
+ import type { ScheduledSubagent, ScheduleStoreData } from "./types.ts";
19
+
20
+ const LOCK_RETRY_MS = 50;
21
+ /** Total asynchronous wait for the lock. */
22
+ const LOCK_MAX_WAIT_MS = 1000;
23
+ /**
24
+ * A lock older than this is stale whatever its PID says: Windows reuses PIDs
25
+ * aggressively, so "that process is alive" does not mean it holds the lock.
26
+ * A mutation holds the lock for a few milliseconds.
27
+ */
28
+ export const LOCK_STALE_MS = 30_000;
29
+ const RENAME_RETRIES = 5;
30
+ const RENAME_RETRY_MS = 20;
31
+
32
+ function isProcessRunning(pid: number): boolean {
33
+ try {
34
+ process.kill(pid, 0);
35
+ return true;
36
+ } catch {
37
+ return false;
38
+ }
39
+ }
40
+
41
+ function errorCode(e: unknown): string | undefined {
42
+ const code = (e as { code?: unknown } | null)?.code;
43
+ return typeof code === "string" ? code : undefined;
44
+ }
45
+
46
+ /** True when the existing lock file can be broken: too old, or its owner is gone. */
47
+ async function isLockStale(lockPath: string): Promise<boolean> {
48
+ try {
49
+ if (Date.now() - (await stat(lockPath)).mtimeMs > LOCK_STALE_MS) return true;
50
+ const pid = parseInt(await readFile(lockPath, "utf-8"), 10);
51
+ return Number.isInteger(pid) && pid > 0 && !isProcessRunning(pid);
52
+ } catch (e) {
53
+ // Vanished between our write attempt and this check: retry the write.
54
+ return errorCode(e) === "ENOENT";
55
+ }
56
+ }
57
+
58
+ async function acquireLock(lockPath: string): Promise<void> {
59
+ const deadline = Date.now() + LOCK_MAX_WAIT_MS;
60
+ for (;;) {
61
+ try {
62
+ await writeFile(lockPath, `${process.pid}`, { flag: "wx" });
63
+ return;
64
+ } catch (e) {
65
+ if (errorCode(e) !== "EEXIST") throw e;
66
+ }
67
+ if (await isLockStale(lockPath)) {
68
+ try {
69
+ await unlink(lockPath);
70
+ } catch (e) {
71
+ if (errorCode(e) !== "ENOENT") throw e;
72
+ }
73
+ continue;
74
+ }
75
+ if (Date.now() >= deadline) break;
76
+ await sleep(LOCK_RETRY_MS);
77
+ }
78
+ throw new Error(`Failed to acquire schedule lock: ${lockPath}`);
79
+ }
80
+
81
+ /** rename with a bounded retry: Windows reports EPERM/EBUSY while AV or an indexer holds the target. */
82
+ async function renameWithRetry(from: string, to: string): Promise<void> {
83
+ for (let attempt = 0; ; attempt++) {
84
+ try {
85
+ await rename(from, to);
86
+ return;
87
+ } catch (e) {
88
+ const code = errorCode(e);
89
+ const transient = code === "EPERM" || code === "EBUSY" || code === "EACCES";
90
+ if (!transient || attempt >= RENAME_RETRIES) {
91
+ // Best effort: the rename error below is the one that matters.
92
+ await unlink(from).catch(() => undefined);
93
+ throw e;
94
+ }
95
+ await sleep(RENAME_RETRY_MS * (attempt + 1));
96
+ }
97
+ }
98
+ }
99
+
100
+ async function releaseLock(lockPath: string): Promise<void> {
101
+ await unlink(lockPath).catch(() => undefined);
102
+ }
103
+
104
+ /** Resolve the storage path for a session-scoped store. */
105
+ export function resolveStorePath(cwd: string, sessionId: string): string {
106
+ return join(cwd, ".pi", "subagent-schedules", `${sessionId}.json`);
107
+ }
108
+
109
+ function parseStoreData(serialized: string): ScheduleStoreData | undefined {
110
+ try {
111
+ return JSON.parse(serialized) as ScheduleStoreData;
112
+ } catch {
113
+ return undefined;
114
+ }
115
+ }
116
+
117
+ export class ScheduleStore {
118
+ private filePath: string;
119
+ private lockPath: string;
120
+ private jobs = new Map<string, ScheduledSubagent>();
121
+
122
+ constructor(filePath: string) {
123
+ this.filePath = filePath;
124
+ this.lockPath = filePath + ".lock";
125
+ this.loadInitial();
126
+ }
127
+
128
+ /** Create the backing directory lazily — only when we're about to persist. */
129
+ private async ensureDir(): Promise<void> {
130
+ await mkdir(dirname(this.filePath), { recursive: true });
131
+ }
132
+
133
+ /**
134
+ * One cold synchronous read preserves the synchronous constructor and the
135
+ * list/get snapshot API. Every reload on a mutation path uses async I/O.
136
+ */
137
+ private loadInitial(): void {
138
+ let serialized: string;
139
+ try {
140
+ serialized = readFileSync(this.filePath, "utf-8");
141
+ } catch {
142
+ return;
143
+ }
144
+ const data = parseStoreData(serialized);
145
+ if (data) this.replaceJobs(data);
146
+ }
147
+
148
+ /** Reload from disk into the in-memory cache. Silent on parse errors. */
149
+ private async load(): Promise<void> {
150
+ let serialized: string;
151
+ try {
152
+ serialized = await readFile(this.filePath, "utf-8");
153
+ } catch (e) {
154
+ if (errorCode(e) === "ENOENT") return;
155
+ throw e;
156
+ }
157
+ const data = parseStoreData(serialized);
158
+ if (data) this.replaceJobs(data);
159
+ }
160
+
161
+ private replaceJobs(data: ScheduleStoreData): void {
162
+ this.jobs.clear();
163
+ for (const j of data.jobs ?? []) this.jobs.set(j.id, j);
164
+ }
165
+
166
+ /** Atomic write via temp file + rename (POSIX-atomic). */
167
+ private async save(): Promise<void> {
168
+ const data: ScheduleStoreData = { version: 1, jobs: [...this.jobs.values()] };
169
+ // Unique per write, so two writers can never clobber each other's temp file.
170
+ const tmp = `${this.filePath}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
171
+ await writeFile(tmp, JSON.stringify(data, null, 2));
172
+ await renameWithRetry(tmp, this.filePath);
173
+ }
174
+
175
+ /** Acquire lock → reload → mutate → save → release. */
176
+ private async withLock<T>(fn: () => T): Promise<T> {
177
+ await this.ensureDir();
178
+ await acquireLock(this.lockPath);
179
+ try {
180
+ await this.load();
181
+ const result = fn();
182
+ await this.save();
183
+ return result;
184
+ } finally {
185
+ await releaseLock(this.lockPath);
186
+ }
187
+ }
188
+
189
+ /** Read-only — returns a snapshot of the in-memory cache. */
190
+ list(): ScheduledSubagent[] {
191
+ return [...this.jobs.values()];
192
+ }
193
+
194
+ /** Read-only check — uses the cache. */
195
+ hasName(name: string, exceptId?: string): boolean {
196
+ for (const j of this.jobs.values()) {
197
+ if (j.id !== exceptId && j.name === name) return true;
198
+ }
199
+ return false;
200
+ }
201
+
202
+ get(id: string): ScheduledSubagent | undefined {
203
+ return this.jobs.get(id);
204
+ }
205
+
206
+ async add(job: ScheduledSubagent): Promise<void> {
207
+ await this.withLock(() => {
208
+ this.jobs.set(job.id, job);
209
+ });
210
+ }
211
+
212
+ /** Atomically re-check the latest committed names and insert only if unique. */
213
+ async addUnlessNameExists(job: ScheduledSubagent): Promise<boolean> {
214
+ return this.withLock(() => {
215
+ if (this.hasName(job.name)) return false;
216
+ this.jobs.set(job.id, job);
217
+ return true;
218
+ });
219
+ }
220
+
221
+ async update(id: string, patch: Partial<ScheduledSubagent>): Promise<ScheduledSubagent | undefined> {
222
+ // No-op fast path — an unknown id changes nothing, so don't lock or touch
223
+ // disk (which would otherwise lazily create the backing directory).
224
+ if (!this.jobs.has(id)) return undefined;
225
+ return this.withLock(() => {
226
+ const existing = this.jobs.get(id);
227
+ if (!existing) return undefined;
228
+ const updated = { ...existing, ...patch };
229
+ this.jobs.set(id, updated);
230
+ return updated;
231
+ });
232
+ }
233
+
234
+ async remove(id: string): Promise<boolean> {
235
+ // No-op fast path — see update().
236
+ if (!this.jobs.has(id)) return false;
237
+ return this.withLock(() => this.jobs.delete(id));
238
+ }
239
+
240
+ /** Delete the backing file (used when no jobs remain, optional cleanup). */
241
+ async deleteFileIfEmpty(): Promise<void> {
242
+ if (this.jobs.size === 0) await unlink(this.filePath).catch(() => undefined);
243
+ }
244
+ }