@nredd/pi-subagents 0.0.0-stage → 0.22.0-nredd.5
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/LICENSE +21 -0
- package/README.md +1244 -2
- package/package.json +75 -4
- package/src/abortable.ts +43 -0
- package/src/agent-color.ts +161 -0
- package/src/agent-file-toggle.ts +297 -0
- package/src/agent-manager.ts +1874 -0
- package/src/agent-runner.ts +1552 -0
- package/src/agent-source-badge.ts +75 -0
- package/src/agent-types.ts +346 -0
- package/src/child-context.ts +15 -0
- package/src/clock.ts +25 -0
- package/src/completion-outbox.ts +125 -0
- package/src/context.ts +58 -0
- package/src/cross-extension-rpc.ts +221 -0
- package/src/custom-agents.ts +436 -0
- package/src/default-agents.ts +126 -0
- package/src/detached-results.ts +134 -0
- package/src/enabled-models.ts +180 -0
- package/src/enterprise-local.ts +66 -0
- package/src/env.ts +33 -0
- package/src/group-join.ts +148 -0
- package/src/index.ts +4423 -0
- package/src/invocation-config.ts +189 -0
- package/src/memory.ts +179 -0
- package/src/mention-clone.ts +195 -0
- package/src/mention.ts +141 -0
- package/src/model-call.ts +83 -0
- package/src/model-resolver.ts +266 -0
- package/src/model-scope.ts +70 -0
- package/src/nested-tools.ts +448 -0
- package/src/output-file.ts +164 -0
- package/src/package-resources.ts +624 -0
- package/src/prompts.ts +156 -0
- package/src/quota-admission.ts +99 -0
- package/src/schedule-store.ts +153 -0
- package/src/schedule.ts +446 -0
- package/src/settings.ts +728 -0
- package/src/skill-loader.ts +137 -0
- package/src/startup-error.ts +29 -0
- package/src/status-note.ts +90 -0
- package/src/structured-output.ts +130 -0
- package/src/types.ts +404 -0
- package/src/ui/agent-mention.ts +216 -0
- package/src/ui/agent-row.ts +235 -0
- package/src/ui/agent-widget.ts +692 -0
- package/src/ui/conversation-viewer.ts +832 -0
- package/src/ui/fleet-list.ts +675 -0
- package/src/ui/notification-view.ts +120 -0
- package/src/ui/schedule-menu.ts +105 -0
- package/src/ui/select-item.ts +45 -0
- package/src/ui/viewer-keys.ts +39 -0
- package/src/ui/workflow-card.ts +462 -0
- package/src/ui/workflow-dialog.ts +1115 -0
- package/src/ui/workflow-menu.ts +193 -0
- package/src/usage.ts +167 -0
- package/src/workflow/collisions.ts +123 -0
- package/src/workflow/entry.ts +47 -0
- package/src/workflow/host.ts +401 -0
- package/src/workflow/journal.ts +164 -0
- package/src/workflow/json-schema.ts +129 -0
- package/src/workflow/meta.ts +326 -0
- package/src/workflow/progress.ts +549 -0
- package/src/workflow/runtime.ts +1216 -0
- package/src/workflow/saved.ts +259 -0
- package/src/workflow/task.ts +302 -0
- package/src/workflow/tool-description.ts +200 -0
- package/src/workflow/worker-source.ts +781 -0
- package/src/worktree.ts +230 -0
- package/src/xml.ts +13 -0
package/src/prompts.ts
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* prompts.ts — System prompt builder for agents.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import type { AgentConfig, EnvInfo } from "./types.js";
|
|
6
|
+
|
|
7
|
+
/** Extra sections to inject into the system prompt (memory, skills, etc.). */
|
|
8
|
+
export interface PromptExtras {
|
|
9
|
+
/** Persistent memory content to inject (first 200 lines of MEMORY.md + instructions). */
|
|
10
|
+
memoryBlock?: string;
|
|
11
|
+
/** Preloaded skill contents to inject. */
|
|
12
|
+
skillBlocks?: { name: string; content: string }[];
|
|
13
|
+
/**
|
|
14
|
+
* Parent directory the worktree copy was created from. Set only for
|
|
15
|
+
* `isolation: "worktree"` spawns — triggers the block that tells the agent
|
|
16
|
+
* to stay in the copy.
|
|
17
|
+
*/
|
|
18
|
+
worktreeBase?: string;
|
|
19
|
+
/**
|
|
20
|
+
* Set only for a workflow's own children, and only when they have no
|
|
21
|
+
* `StructuredOutput` tool to answer through.
|
|
22
|
+
*
|
|
23
|
+
* A workflow child's final text is not read by a human — it is the value
|
|
24
|
+
* `agent()` resolves to, and the script interpolates it straight into the
|
|
25
|
+
* next stage's prompt. Without this, children answer the way every other
|
|
26
|
+
* subagent does (a report addressed to a reader), and the padding becomes
|
|
27
|
+
* input tokens for the stage downstream. Claude Code's `Workflow` tool
|
|
28
|
+
* documents this contract to the script-writing model; this is the end of it
|
|
29
|
+
* that makes the documentation true.
|
|
30
|
+
*
|
|
31
|
+
* Deliberately NOT applied to every subagent. In pi an ordinary agent's
|
|
32
|
+
* output IS read by a human — through FleetView, the conversation viewer and
|
|
33
|
+
* `get_subagent_result` — so terse raw data would be the wrong answer there.
|
|
34
|
+
*/
|
|
35
|
+
workflowChild?: boolean;
|
|
36
|
+
/**
|
|
37
|
+
* Set when the agent lists `allowed_subagents` but got no `Agent` tool (depth
|
|
38
|
+
* cap, isolation, `disallowed_tools`). Without the line it reads the missing tool as a fault and
|
|
39
|
+
* emulates one, e.g. by shelling out to `claude -p`, which escapes the depth
|
|
40
|
+
* cap, quota admission and usage reporting.
|
|
41
|
+
*/
|
|
42
|
+
nestingDisabled?: boolean;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Build the system prompt for an agent from its config.
|
|
47
|
+
*
|
|
48
|
+
* - "replace" mode: env header + config.systemPrompt (full control, no parent identity)
|
|
49
|
+
* - "append" mode: parent system prompt + sub-agent context + env header + config.systemPrompt
|
|
50
|
+
* - "append" with empty systemPrompt: pure parent clone
|
|
51
|
+
*
|
|
52
|
+
* Both modes include an `<active_agent name="${config.name}"/>` tag so downstream
|
|
53
|
+
* extensions (e.g. permission/policy systems) can resolve per-agent policy
|
|
54
|
+
* inside the child session by parsing the system prompt. In replace mode the tag
|
|
55
|
+
* is prepended; in append mode it follows the shared inherited content so the
|
|
56
|
+
* parent prompt forms an identical, cacheable byte prefix with the parent
|
|
57
|
+
* session (the LLM's KV cache can then reuse those tokens across every spawn).
|
|
58
|
+
*
|
|
59
|
+
* @param parentSystemPrompt The parent agent's effective system prompt (for append mode).
|
|
60
|
+
* @param extras Optional extra sections to inject (memory, preloaded skills).
|
|
61
|
+
*/
|
|
62
|
+
export function buildAgentPrompt(
|
|
63
|
+
config: AgentConfig,
|
|
64
|
+
cwd: string,
|
|
65
|
+
env: EnvInfo,
|
|
66
|
+
parentSystemPrompt?: string,
|
|
67
|
+
extras?: PromptExtras,
|
|
68
|
+
): string {
|
|
69
|
+
const activeAgentTag = `<active_agent name="${config.name}"/>\n\n`;
|
|
70
|
+
|
|
71
|
+
const envBlock = `# Environment
|
|
72
|
+
Working directory: ${cwd}
|
|
73
|
+
${env.isGitRepo ? `Git repository: yes\nBranch: ${env.branch}` : "Not a git repository"}
|
|
74
|
+
Platform: ${env.platform}`;
|
|
75
|
+
|
|
76
|
+
// A worktree agent is told its cwd twice: by the env block above (the copy)
|
|
77
|
+
// and by whatever names the main checkout — the inherited parent prompt in
|
|
78
|
+
// append mode, or the task prompt in either mode. It follows the latter and
|
|
79
|
+
// works in the shared tree (#187), so resolve the contradiction explicitly.
|
|
80
|
+
const worktreeBlock = extras?.worktreeBase
|
|
81
|
+
? `\n\n<worktree_isolation>
|
|
82
|
+
Your working directory is an isolated git worktree copy of ${extras.worktreeBase}.
|
|
83
|
+
Work only inside it — never in ${extras.worktreeBase}, even if other instructions name that path as your working directory.
|
|
84
|
+
</worktree_isolation>`
|
|
85
|
+
: "";
|
|
86
|
+
|
|
87
|
+
// The script, not a person, reads what this child returns — see
|
|
88
|
+
// `PromptExtras.workflowChild` for why only workflow children get this.
|
|
89
|
+
const workflowBlock = extras?.workflowChild
|
|
90
|
+
? `\n\n<workflow_child>
|
|
91
|
+
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.
|
|
92
|
+
Return only the answer, in exactly the shape the prompt asks for — no preamble, no summary of what you did, no offer to continue.
|
|
93
|
+
</workflow_child>`
|
|
94
|
+
: "";
|
|
95
|
+
|
|
96
|
+
const nestingBlock = extras?.nestingDisabled
|
|
97
|
+
? `\n\n<nesting_disabled>
|
|
98
|
+
Nested subagents are disabled for this session, so you have no Agent tool. Do the work yourself, inline.
|
|
99
|
+
Do not emulate subagents by running another agent CLI (e.g. \`claude -p\`) from bash.
|
|
100
|
+
</nesting_disabled>`
|
|
101
|
+
: "";
|
|
102
|
+
|
|
103
|
+
// Build optional extras suffix
|
|
104
|
+
const extraSections: string[] = [];
|
|
105
|
+
if (extras?.memoryBlock) {
|
|
106
|
+
extraSections.push(extras.memoryBlock);
|
|
107
|
+
}
|
|
108
|
+
if (extras?.skillBlocks?.length) {
|
|
109
|
+
for (const skill of extras.skillBlocks) {
|
|
110
|
+
extraSections.push(`\n# Preloaded Skill: ${skill.name}\n${skill.content}`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
const extrasSuffix = extraSections.length > 0 ? "\n\n" + extraSections.join("\n") : "";
|
|
114
|
+
|
|
115
|
+
if (config.promptMode === "append") {
|
|
116
|
+
const identity = parentSystemPrompt || genericBase;
|
|
117
|
+
|
|
118
|
+
const bridge = `<sub_agent_context>
|
|
119
|
+
You are operating as a sub-agent invoked to handle a specific task.
|
|
120
|
+
- Use the read tool instead of cat/head/tail
|
|
121
|
+
- Use the edit tool instead of sed/awk
|
|
122
|
+
- Use the write tool instead of echo/heredoc
|
|
123
|
+
- Use the find tool instead of bash find/ls for file search
|
|
124
|
+
- Use the grep tool instead of bash grep/rg for content search
|
|
125
|
+
- Make independent tool calls in parallel
|
|
126
|
+
- Use absolute file paths
|
|
127
|
+
- Do not use emojis
|
|
128
|
+
- Be concise but complete
|
|
129
|
+
</sub_agent_context>`;
|
|
130
|
+
|
|
131
|
+
const customSection = config.systemPrompt?.trim()
|
|
132
|
+
? `\n\n<agent_instructions>\n${config.systemPrompt}\n</agent_instructions>`
|
|
133
|
+
: "";
|
|
134
|
+
|
|
135
|
+
// Place shared/stable content first so the LLM's KV cache can reuse the
|
|
136
|
+
// inherited prefix across all subagent invocations. The parent prompt is
|
|
137
|
+
// placed verbatim (no wrapper tag) so it forms an identical byte prefix
|
|
138
|
+
// with the parent session, maximising KV cache hits. The <active_agent>
|
|
139
|
+
// tag and env block vary per call and are placed after the cached prefix.
|
|
140
|
+
return identity + "\n\n" + bridge + "\n\n" + activeAgentTag + envBlock + worktreeBlock + workflowBlock + nestingBlock + customSection + extrasSuffix;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// "replace" mode — env header + the config's full system prompt
|
|
144
|
+
const replaceHeader = `You are a pi coding agent sub-agent.
|
|
145
|
+
You have been invoked to handle a specific task autonomously.
|
|
146
|
+
|
|
147
|
+
${envBlock}`;
|
|
148
|
+
|
|
149
|
+
return activeAgentTag + replaceHeader + worktreeBlock + workflowBlock + nestingBlock + "\n\n" + config.systemPrompt + extrasSuffix;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Fallback base prompt when parent system prompt is unavailable in append mode. */
|
|
153
|
+
const genericBase = `# Role
|
|
154
|
+
You are a general-purpose coding agent for complex, multi-step tasks.
|
|
155
|
+
You have full access to read, write, edit files, and execute commands.
|
|
156
|
+
Do what has been asked; nothing more, nothing less.`;
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* quota-admission.ts — ask a subscription router whether a dispatch may start.
|
|
3
|
+
*
|
|
4
|
+
* Quota tracking lives in a separate extension (nredd/pi-subscription-router),
|
|
5
|
+
* reached over `pi.events` with the same envelope as `cross-extension-rpc.ts`:
|
|
6
|
+
* emit `router:rpc:admit` `{ requestId, model }`, reply on
|
|
7
|
+
* `router:rpc:admit:reply:<requestId>` as `{ success, data?: { ok, resolvedModel?, resetAt?, wait? } }` (`resolvedModel` is ignored).
|
|
8
|
+
*
|
|
9
|
+
* Admission fails open. No router installed, a slow router, a malformed reply
|
|
10
|
+
* or a router error all admit the dispatch: quota is advisory here, and the
|
|
11
|
+
* router still routes (or fails) each request inside the child.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { nanoid } from "nanoid";
|
|
15
|
+
import { type Clock, realClock } from "./clock.js";
|
|
16
|
+
|
|
17
|
+
export const ADMIT_CHANNEL = "router:rpc:admit";
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* How long to wait for a reply. The router answers from cached state within
|
|
21
|
+
* the same macrotask, so this only bounds the cost when no router is installed.
|
|
22
|
+
*/
|
|
23
|
+
const ADMIT_TIMEOUT_MS = 100;
|
|
24
|
+
|
|
25
|
+
/** Minimal `pi.events` surface. */
|
|
26
|
+
export interface AdmissionEvents {
|
|
27
|
+
emit(channel: string, data: unknown): void;
|
|
28
|
+
on(channel: string, handler: (data: unknown) => void): () => void;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** A dispatch the router refused, with the earliest known reset (epoch ms). */
|
|
32
|
+
export interface QuotaBlock {
|
|
33
|
+
model: string;
|
|
34
|
+
resetAt?: number;
|
|
35
|
+
/**
|
|
36
|
+
* False when the router's exhaustion policy says fail now instead of parking.
|
|
37
|
+
* Absent (an older router) means the dispatch may park until `resetAt`.
|
|
38
|
+
*/
|
|
39
|
+
wait?: boolean;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Whether a refused background dispatch may be parked until the block's reset. */
|
|
43
|
+
export function mayPark(block: QuotaBlock): block is QuotaBlock & { resetAt: number } {
|
|
44
|
+
return block.resetAt !== undefined && block.wait !== false;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** `provider/id` for a model, the key the router expects. */
|
|
48
|
+
export function modelRef(model: { provider: string; id: string }): string {
|
|
49
|
+
return `${model.provider}/${model.id}`;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Resolve to the block when the router refuses `model`, else undefined. */
|
|
53
|
+
export function checkAdmission(
|
|
54
|
+
events: AdmissionEvents,
|
|
55
|
+
model: string,
|
|
56
|
+
timeoutMs = ADMIT_TIMEOUT_MS,
|
|
57
|
+
clock: Clock = realClock,
|
|
58
|
+
): Promise<QuotaBlock | undefined> {
|
|
59
|
+
const requestId = nanoid();
|
|
60
|
+
return new Promise(resolve => {
|
|
61
|
+
let done = false;
|
|
62
|
+
const finish = (block: QuotaBlock | undefined) => {
|
|
63
|
+
if (done) return;
|
|
64
|
+
done = true;
|
|
65
|
+
timer.cancel();
|
|
66
|
+
unsubscribe();
|
|
67
|
+
resolve(block);
|
|
68
|
+
};
|
|
69
|
+
const unsubscribe = events.on(`${ADMIT_CHANNEL}:reply:${requestId}`, raw => {
|
|
70
|
+
const reply = raw as { success?: unknown; data?: { ok?: unknown; resetAt?: unknown; wait?: unknown } } | undefined;
|
|
71
|
+
if (reply?.success !== true || reply.data?.ok !== false) return finish(undefined);
|
|
72
|
+
const resetAt = reply.data.resetAt;
|
|
73
|
+
const wait = reply.data.wait;
|
|
74
|
+
finish({
|
|
75
|
+
model,
|
|
76
|
+
resetAt: typeof resetAt === "number" && Number.isFinite(resetAt) ? resetAt : undefined,
|
|
77
|
+
...(typeof wait === "boolean" ? { wait } : {}),
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
const timer = clock.setTimeout(() => finish(undefined), timeoutMs);
|
|
81
|
+
events.emit(ADMIT_CHANNEL, { requestId, model });
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** One-line reason for a refused dispatch. */
|
|
86
|
+
export function describeBlock(block: QuotaBlock): string {
|
|
87
|
+
const when = block.resetAt === undefined ? "an unknown time" : new Date(block.resetAt).toISOString();
|
|
88
|
+
return `Subscription quota for ${block.model} is exhausted; it resets at ${when}.`;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Delay past a reported reset before a parked dispatch starts, so usage has refilled. */
|
|
92
|
+
export const QUOTA_RESTART_GRACE_MS = 60_000;
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Delay before re-admitting a parked dispatch whose reset passed while pi was
|
|
96
|
+
* closed. The router warms its usage cache on session_start; asking before that
|
|
97
|
+
* finishes would always fail open.
|
|
98
|
+
*/
|
|
99
|
+
export const PARKED_RESUME_DELAY_MS = 10_000;
|
|
@@ -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
|
+
}
|