@justjoshn/pi-pstack 0.15.36-pi.1 → 0.15.36-pi.12
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/CHANGELOG.md +94 -0
- package/README.md +29 -24
- package/agents/ci-watcher.md +28 -0
- package/agents/thermo-nuclear-code-quality-review.md +23 -0
- package/assets/logo.png +0 -0
- package/automations/benny/FOR_AGENTS.md +2 -1
- package/automations/benny/README.md +2 -2
- package/automations/benny/skills/setup-benny/SKILL.md +10 -9
- package/automations/benny/templates/reproduce-automation-prompt.md +1 -1
- package/automations/benny/templates/triage-automation-prompt.md +1 -1
- package/bin/pstack-routines-supervisor +9 -0
- package/docs/guide/01-setup.md +2 -2
- package/docs/guide/07-overnight.md +1 -1
- package/docs/guide/09-make-it-yours.md +1 -1
- package/docs/guide/10-recipes-and-pitfalls.md +1 -1
- package/docs/native-gaps.md +14 -8
- package/docs/parity-reverse-engineering.md +94 -0
- package/docs/parity-status.md +128 -0
- package/package.json +41 -6
- package/packaging/install-supervisor-unit.sh +164 -0
- package/packaging/launchd/com.pstack.routines-supervisor.plist.example +24 -0
- package/packaging/systemd/pstack-routines-supervisor.service.example +15 -0
- package/skills/architect/SKILL.md +1 -1
- package/skills/architect/references/runner-prompt.md +1 -1
- package/skills/arena/SKILL.md +4 -4
- package/skills/check-compiler-errors/SKILL.md +23 -0
- package/skills/create-skill/SKILL.md +515 -29
- package/skills/fix-ci/SKILL.md +29 -0
- package/skills/fix-merge-conflicts/SKILL.md +32 -0
- package/skills/get-pr-comments/SKILL.md +23 -0
- package/skills/how/SKILL.md +1 -1
- package/skills/ketchup/SKILL.md +2 -2
- package/skills/ketchup-video/SKILL.md +2 -2
- package/skills/loop-on-ci/SKILL.md +50 -0
- package/skills/make-bot-ui/SKILL.md +2 -2
- package/skills/make-pr-easy-to-review/SKILL.md +59 -0
- package/skills/new-branch-and-pr/SKILL.md +29 -0
- package/skills/no-inline-imports/SKILL.md +12 -0
- package/skills/poteto-help/SKILL.md +4 -4
- package/skills/poteto-mode/SKILL.md +2 -2
- package/skills/poteto-mode/playbooks/bug-fix.md +1 -1
- package/skills/poteto-mode/playbooks/feature.md +1 -1
- package/skills/poteto-mode/playbooks/hillclimb.md +1 -1
- package/skills/poteto-mode/playbooks/multi-phase-plan.md +2 -2
- package/skills/poteto-mode/playbooks/orchestrate.md +2 -2
- package/skills/poteto-mode/playbooks/perf-issue.md +1 -1
- package/skills/poteto-mode/playbooks/refactoring.md +1 -1
- package/skills/pr-review-canvas/SKILL.md +176 -0
- package/skills/pr-review-canvas/renderer.js +170 -0
- package/skills/pr-review-canvas/styles.css +96 -0
- package/skills/pr-review-canvas/template.html +18 -0
- package/skills/reflect/SKILL.md +2 -2
- package/skills/review-and-ship/SKILL.md +41 -0
- package/skills/run-smoke-tests/SKILL.md +42 -0
- package/skills/setup-pstack/SKILL.md +13 -13
- package/skills/statechart/scripts/test/cli.test.ts +1 -1
- package/skills/swarm/SKILL.md +2 -2
- package/skills/teach/SKILL.md +1 -1
- package/skills/thermo-nuclear-code-quality-review/SKILL.md +192 -0
- package/skills/typescript-exhaustive-switch/SKILL.md +10 -0
- package/skills/verify-this/SKILL.md +74 -0
- package/skills/weekly-review/SKILL.md +32 -0
- package/skills/what-did-i-get-done/SKILL.md +31 -0
- package/skills/why/SKILL.md +2 -2
- package/skills/workflow-from-chats/SKILL.md +50 -0
- package/src/ask.ts +24 -10
- package/src/child-env.ts +15 -2
- package/src/generate-image.ts +98 -0
- package/src/index.ts +28 -9
- package/src/loop.ts +74 -17
- package/src/mode.ts +89 -27
- package/src/paths.ts +18 -0
- package/src/pi-command.ts +12 -0
- package/src/plan.ts +285 -30
- package/src/rule.ts +4 -4
- package/src/sections.ts +27 -3
- package/src/subscriptions/durable-store.ts +531 -0
- package/src/subscriptions/durable-types.ts +69 -0
- package/src/subscriptions/ensure-supervisor.ts +67 -0
- package/src/subscriptions/index.ts +310 -282
- package/src/subscriptions/supervisor-main.ts +134 -0
- package/src/subscriptions/supervisor.ts +325 -0
- package/src/subscriptions/webhook.ts +82 -21
- package/src/task/agents.ts +39 -3
- package/src/task/card.ts +31 -0
- package/src/task/format.ts +17 -3
- package/src/task/models.ts +7 -0
- package/src/task/progress.ts +112 -0
- package/src/task/records.ts +7 -9
- package/src/task/registry.ts +9 -4
- package/src/task/runner.ts +116 -24
- package/src/task/stop.ts +3 -3
- package/src/task/tool.ts +158 -57
- package/src/task/worktree.ts +5 -3
- package/src/todo.ts +29 -4
- package/scripts/live-e2e.mjs +0 -257
- package/test/aliases.test.ts +0 -57
- package/test/ask.test.ts +0 -85
- package/test/autocomplete.test.ts +0 -39
- package/test/e2e/aliases.e2e.test.ts +0 -81
- package/test/e2e/ask.e2e.test.ts +0 -135
- package/test/e2e/harness.ts +0 -179
- package/test/e2e/host.e2e.test.ts +0 -193
- package/test/e2e/lifecycle.e2e.test.ts +0 -99
- package/test/e2e/mode.e2e.test.ts +0 -160
- package/test/e2e/package.e2e.test.ts +0 -67
- package/test/e2e/task.e2e.test.ts +0 -734
- package/test/e2e/todo.e2e.test.ts +0 -59
- package/test/fixtures/cursor-askquestion-calls.json +0 -806
- package/test/fixtures/fake-pi.mjs +0 -96
- package/test/fixtures/image-model.ts +0 -16
- package/test/fixtures/list-models.ts +0 -15
- package/test/fixtures/readonly-shell-exit.ts +0 -17
- package/test/fixtures/scripted-model.ts +0 -113
- package/test/loop.test.ts +0 -209
- package/test/mode.test.ts +0 -143
- package/test/plan.test.ts +0 -126
- package/test/readonly-shell-security.test.ts +0 -84
- package/test/readonly-shell.test.ts +0 -44
- package/test/records.test.ts +0 -143
- package/test/registry.test.ts +0 -18
- package/test/resources.test.ts +0 -162
- package/test/rule.test.ts +0 -92
- package/test/scripts.test.ts +0 -182
- package/test/sections.test.ts +0 -56
- package/test/subscriptions-cron.test.ts +0 -60
- package/test/subscriptions.test.ts +0 -598
- package/test/task-agents.test.ts +0 -49
- package/test/task-card.test.ts +0 -34
- package/test/task-fork.test.ts +0 -233
- package/test/task-format.test.ts +0 -65
- package/test/task-model.test.ts +0 -141
- package/test/task-runner.test.ts +0 -259
- package/test/task-schema.test.ts +0 -50
- package/test/task-status.test.ts +0 -155
- package/test/task-worktree.test.ts +0 -106
- package/test/todo.test.ts +0 -74
- package/test/visualize.test.ts +0 -152
- package/tsconfig.json +0 -5
- package/vitest.config.ts +0 -16
|
@@ -0,0 +1,531 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { dirname, join, resolve } from 'node:path';
|
|
4
|
+
import { performance } from 'node:perf_hooks';
|
|
5
|
+
|
|
6
|
+
import { durableRegistryPath, durableRuntimeDir } from '../paths.ts';
|
|
7
|
+
import { parseCron } from './cron.ts';
|
|
8
|
+
import type { ArmStatus, DurableRegistry, DurableSubscription, EventAdmission, PendingEvent, StoredSubscription, SupervisorLock } from './durable-types.ts';
|
|
9
|
+
import { routineSlug } from './webhook.ts';
|
|
10
|
+
|
|
11
|
+
export function canonicalPath(path: string): string {
|
|
12
|
+
try {
|
|
13
|
+
return realpathSync(path);
|
|
14
|
+
} catch (error) {
|
|
15
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
|
16
|
+
const absolute = resolve(path);
|
|
17
|
+
return absolute === dirname(absolute) ? absolute : join(canonicalPath(dirname(absolute)), absolute.slice(dirname(absolute).length + 1));
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function zombie(pid: number): boolean {
|
|
22
|
+
if (process.platform !== 'linux') return false;
|
|
23
|
+
try {
|
|
24
|
+
const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
|
|
25
|
+
const close = stat.lastIndexOf(')');
|
|
26
|
+
return close !== -1 && stat.slice(close + 2, close + 3) === 'Z';
|
|
27
|
+
} catch {
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function alive(pid: number): boolean {
|
|
33
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
34
|
+
try {
|
|
35
|
+
process.kill(pid, 0);
|
|
36
|
+
// A zombie still answers kill(pid, 0) until its parent reaps it, but it holds no lock and runs nothing.
|
|
37
|
+
return !zombie(pid);
|
|
38
|
+
} catch (error) {
|
|
39
|
+
return (error as NodeJS.ErrnoException).code === 'EPERM';
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function writeAtomic(path: string, value: unknown): void {
|
|
44
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
45
|
+
const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
46
|
+
try {
|
|
47
|
+
writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
|
|
48
|
+
renameSync(temporary, path);
|
|
49
|
+
} finally {
|
|
50
|
+
rmSync(temporary, { force: true });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const runtime = (cwd: string) => durableRuntimeDir(canonicalPath(cwd));
|
|
55
|
+
export const supervisorLockPath = (cwd: string) => join(runtime(cwd), 'supervisor.lock');
|
|
56
|
+
const registryLockPath = (cwd: string) => join(runtime(cwd), 'registry.lock');
|
|
57
|
+
export const ownerLockPath = (cwd: string, id: string) => join(runtime(cwd), `owner-${createHash('sha256').update(id).digest('hex')}.lock`);
|
|
58
|
+
const routinesPortPath = (cwd: string) => join(runtime(cwd), 'routines.port');
|
|
59
|
+
|
|
60
|
+
/** The port this workspace's listener last bound, so a restart does not invalidate sender URLs. */
|
|
61
|
+
export function readRoutinesPort(cwd: string): number | undefined {
|
|
62
|
+
try {
|
|
63
|
+
const port = Number(readFileSync(routinesPortPath(cwd), 'utf8').trim());
|
|
64
|
+
return Number.isInteger(port) && port > 0 && port < 65_536 ? port : undefined;
|
|
65
|
+
} catch {
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function writeRoutinesPort(cwd: string, port: number): void {
|
|
71
|
+
if (!(Number.isInteger(port) && port > 0 && port < 65_536)) return;
|
|
72
|
+
try {
|
|
73
|
+
mkdirSync(runtime(cwd), { recursive: true, mode: 0o700 });
|
|
74
|
+
writeFileSync(routinesPortPath(cwd), `${port}\n`, { mode: 0o600 });
|
|
75
|
+
} catch {
|
|
76
|
+
// A missing runtime dir only costs a new port after restart.
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export type Lease = { token: string; release: () => void };
|
|
81
|
+
|
|
82
|
+
/** Publish a nonempty directory atomically. Recovery removes only the dead holder's token. */
|
|
83
|
+
export function acquireLease(path: string): Lease | undefined {
|
|
84
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
85
|
+
const token = `${process.pid}-${randomUUID()}`;
|
|
86
|
+
const temporary = `${path}.${token}.tmp`;
|
|
87
|
+
mkdirSync(temporary, { mode: 0o700 });
|
|
88
|
+
try {
|
|
89
|
+
writeFileSync(join(temporary, token), '', { mode: 0o600 });
|
|
90
|
+
for (let attempt = 0; attempt < 4; attempt += 1) {
|
|
91
|
+
try {
|
|
92
|
+
renameSync(temporary, path);
|
|
93
|
+
return {
|
|
94
|
+
token,
|
|
95
|
+
release: () => {
|
|
96
|
+
rmSync(join(path, token), { force: true });
|
|
97
|
+
try {
|
|
98
|
+
rmdirSync(path);
|
|
99
|
+
} catch (error) {
|
|
100
|
+
if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes((error as NodeJS.ErrnoException).code ?? '')) throw error;
|
|
101
|
+
}
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
} catch (error) {
|
|
105
|
+
if (!['ENOTEMPTY', 'EEXIST'].includes((error as NodeJS.ErrnoException).code ?? '')) throw error;
|
|
106
|
+
}
|
|
107
|
+
let holders: string[];
|
|
108
|
+
try {
|
|
109
|
+
holders = readdirSync(path);
|
|
110
|
+
} catch (error) {
|
|
111
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;
|
|
112
|
+
throw error;
|
|
113
|
+
}
|
|
114
|
+
for (const holder of holders) {
|
|
115
|
+
const pid = Number(/^(\d+)-[a-f0-9-]+$/.exec(holder)?.[1]);
|
|
116
|
+
if (!Number.isInteger(pid)) throw new Error(`Invalid subscription lock ${path}. Retain it for diagnosis.`);
|
|
117
|
+
if (alive(pid)) return undefined;
|
|
118
|
+
rmSync(join(path, holder), { force: true });
|
|
119
|
+
}
|
|
120
|
+
try {
|
|
121
|
+
rmdirSync(path);
|
|
122
|
+
} catch (error) {
|
|
123
|
+
if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes((error as NodeJS.ErrnoException).code ?? '')) throw error;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return undefined;
|
|
127
|
+
} finally {
|
|
128
|
+
rmSync(temporary, { recursive: true, force: true });
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function ownerIsLive(cwd: string, sessionId: string): boolean {
|
|
133
|
+
const path = ownerLockPath(cwd, sessionId);
|
|
134
|
+
try {
|
|
135
|
+
const holders = readdirSync(path);
|
|
136
|
+
for (const holder of holders) {
|
|
137
|
+
const pid = Number(/^(\d+)-[a-f0-9-]+$/.exec(holder)?.[1]);
|
|
138
|
+
if (Number.isInteger(pid) && alive(pid)) return true;
|
|
139
|
+
}
|
|
140
|
+
return false;
|
|
141
|
+
} catch {
|
|
142
|
+
return false;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function withRegistryLock<T>(cwd: string, work: () => T): T {
|
|
147
|
+
const deadline = performance.now() + 5_000;
|
|
148
|
+
do {
|
|
149
|
+
const lease = acquireLease(registryLockPath(cwd));
|
|
150
|
+
if (lease !== undefined) {
|
|
151
|
+
try {
|
|
152
|
+
return work();
|
|
153
|
+
} finally {
|
|
154
|
+
lease.release();
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5);
|
|
158
|
+
} while (performance.now() < deadline);
|
|
159
|
+
throw new Error(`Subscription registry is busy in ${cwd}. Retry when the live writer finishes.`);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function validSubscription(value: unknown): value is DurableSubscription {
|
|
163
|
+
if (typeof value !== 'object' || value === null) return false;
|
|
164
|
+
const sub = value as DurableSubscription;
|
|
165
|
+
if (typeof sub.id !== 'string' || !/^sub-[a-zA-Z0-9-]+$/.test(sub.id) || typeof sub.name !== 'string' || !sub.name.trim() || !Number.isFinite(sub.createdAt) || !Number.isFinite(sub.expiresAt)) return false;
|
|
166
|
+
if ((sub.ownerSessionId !== undefined && (typeof sub.ownerSessionId !== 'string' || !sub.ownerSessionId)) || (sub.ownerSessionFile !== undefined && typeof sub.ownerSessionFile !== 'string')) return false;
|
|
167
|
+
const c = sub.config;
|
|
168
|
+
if (typeof c !== 'object' || c === null) return false;
|
|
169
|
+
if (c.kind === 'github') {
|
|
170
|
+
const t = c.target;
|
|
171
|
+
return (
|
|
172
|
+
typeof t === 'object' &&
|
|
173
|
+
t !== null &&
|
|
174
|
+
(t.scope === 'pr'
|
|
175
|
+
? typeof t.prUrl === 'string' && /^https:\/\/[^\s/]+\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/\d+\/?$/.test(t.prUrl)
|
|
176
|
+
: (t.scope === 'repo' || t.scope === 'author') &&
|
|
177
|
+
typeof t.repo === 'string' &&
|
|
178
|
+
/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(t.repo) &&
|
|
179
|
+
(t.scope !== 'author' || (typeof t.author === 'string' && /^(?:@me|[A-Za-z0-9](?:[A-Za-z0-9-]|\[bot\]|\/)*)$/.test(t.author))))
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
if (typeof c.prompt !== 'string') return false;
|
|
183
|
+
if (c.kind === 'webhook') {
|
|
184
|
+
const strategy = c.strategy;
|
|
185
|
+
const model = c.model;
|
|
186
|
+
return (
|
|
187
|
+
(strategy === undefined || strategy === 'wake_self' || strategy === 'new_session') &&
|
|
188
|
+
(model === undefined || (typeof model === 'object' && model !== null && typeof model.provider === 'string' && typeof model.id === 'string' && (model.thinking === undefined || typeof model.thinking === 'string'))) &&
|
|
189
|
+
(c.trusted === undefined || typeof c.trusted === 'boolean') &&
|
|
190
|
+
typeof c.slug === 'string' &&
|
|
191
|
+
routineSlug(sub.name) === c.slug
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
if (c.kind !== 'timer' || typeof c.once !== 'boolean' || !['wake_self', 'new_session'].includes(c.strategy)) return false;
|
|
195
|
+
if ((c.cron === undefined) === (c.delaySeconds === undefined)) return false;
|
|
196
|
+
if (c.cron !== undefined) {
|
|
197
|
+
try {
|
|
198
|
+
parseCron(c.cron);
|
|
199
|
+
} catch {
|
|
200
|
+
return false;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return c.delaySeconds === undefined || (Number.isInteger(c.delaySeconds) && c.delaySeconds >= 1);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function emptyRegistry(cwd: string): DurableRegistry {
|
|
207
|
+
return { version: 2, workspaceCwd: canonicalPath(cwd), revision: 0, subscriptions: [], pending: [] };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function migratedOwner(sub: DurableSubscription): string | undefined {
|
|
211
|
+
if (sub.ownerSessionId !== undefined) return sub.ownerSessionId;
|
|
212
|
+
if (sub.ownerSessionFile === undefined) return undefined;
|
|
213
|
+
try {
|
|
214
|
+
const header = JSON.parse(readFileSync(sub.ownerSessionFile, 'utf8').split('\n')[0] ?? '');
|
|
215
|
+
return header.type === 'session' && typeof header.id === 'string' && header.id ? header.id : undefined;
|
|
216
|
+
} catch {
|
|
217
|
+
return undefined;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function loadRegistry(cwd: string): DurableRegistry {
|
|
222
|
+
const path = durableRegistryPath(canonicalPath(cwd));
|
|
223
|
+
if (!existsSync(path)) return emptyRegistry(cwd);
|
|
224
|
+
try {
|
|
225
|
+
const raw = JSON.parse(readFileSync(path, 'utf8'));
|
|
226
|
+
if (typeof raw !== 'object' || raw === null || ![1, 2].includes(raw.version) || !Array.isArray(raw.subscriptions) || !raw.subscriptions.every(validSubscription)) throw new Error('invalid subscriptions');
|
|
227
|
+
if (typeof raw.workspaceCwd !== 'string' || canonicalPath(raw.workspaceCwd) !== canonicalPath(cwd)) throw new Error('Registry belongs to a different workspace.');
|
|
228
|
+
if (raw.version === 1) {
|
|
229
|
+
return {
|
|
230
|
+
...emptyRegistry(cwd),
|
|
231
|
+
revision: 1,
|
|
232
|
+
subscriptions: raw.subscriptions.map((sub: DurableSubscription) => {
|
|
233
|
+
const { detachedDelivery: _legacy, ...config } = sub;
|
|
234
|
+
const ownerSessionId = migratedOwner(sub);
|
|
235
|
+
return { ...config, ...(ownerSessionId === undefined ? { lastError: { at: Date.now(), text: 'Owner session ID unavailable. Recreate this subscription.' } } : { ownerSessionId }), revision: 1, lifecycle: 'active' };
|
|
236
|
+
}),
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
if (!Number.isInteger(raw.revision) || raw.revision < 0 || !Array.isArray(raw.pending)) throw new Error('invalid registry revision or pending events');
|
|
240
|
+
const ids = new Set<string>();
|
|
241
|
+
for (const sub of raw.subscriptions) {
|
|
242
|
+
if (ids.has(sub.id) || !Number.isInteger(sub.revision) || !['active', 'completed', 'cancelled', 'expired'].includes(sub.lifecycle)) throw new Error('invalid subscription lifecycle');
|
|
243
|
+
ids.add(sub.id);
|
|
244
|
+
if (sub.lastOccurrence !== undefined && typeof sub.lastOccurrence !== 'string') throw new Error('invalid occurrence');
|
|
245
|
+
for (const note of [sub.lastEvent, sub.lastError, sub.lastOutcome]) if (note !== undefined && (typeof note.text !== 'string' || !Number.isFinite(note.at))) throw new Error('invalid subscription status');
|
|
246
|
+
}
|
|
247
|
+
const eventIds = new Set<string>();
|
|
248
|
+
for (const event of raw.pending) {
|
|
249
|
+
if (
|
|
250
|
+
typeof event.id !== 'string' ||
|
|
251
|
+
eventIds.has(event.id) ||
|
|
252
|
+
!ids.has(event.subscriptionId) ||
|
|
253
|
+
!Number.isFinite(event.acceptedAt) ||
|
|
254
|
+
typeof event.content !== 'string' ||
|
|
255
|
+
(event.claim !== undefined && (!Number.isInteger(event.claim.pid) || event.claim.pid <= 0 || typeof event.claim.token !== 'string' || !['live', 'detached'].includes(event.claim.mode))) ||
|
|
256
|
+
(event.attempts !== undefined && (!Number.isInteger(event.attempts) || event.attempts < 0)) ||
|
|
257
|
+
(event.retryAt !== undefined && !Number.isFinite(event.retryAt))
|
|
258
|
+
)
|
|
259
|
+
throw new Error('invalid pending event');
|
|
260
|
+
eventIds.add(event.id);
|
|
261
|
+
}
|
|
262
|
+
return { version: 2, workspaceCwd: canonicalPath(cwd), revision: raw.revision, subscriptions: raw.subscriptions, pending: raw.pending };
|
|
263
|
+
} catch (error) {
|
|
264
|
+
throw new Error(`Cannot read authoritative subscription registry ${path}. Retain the file for diagnosis. ${error instanceof Error ? error.message : String(error)}`);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export function readRegistry(cwd: string): DurableRegistry {
|
|
269
|
+
const path = durableRegistryPath(canonicalPath(cwd));
|
|
270
|
+
const registry = loadRegistry(cwd);
|
|
271
|
+
if (existsSync(path) && JSON.parse(readFileSync(path, 'utf8')).version === 1) {
|
|
272
|
+
return withRegistryLock(cwd, () => {
|
|
273
|
+
const current = loadRegistry(cwd);
|
|
274
|
+
writeAtomic(path, current);
|
|
275
|
+
return current;
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
return registry;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function transaction<T>(cwd: string, change: (registry: DurableRegistry) => T): T {
|
|
282
|
+
return withRegistryLock(cwd, () => {
|
|
283
|
+
const registry = loadRegistry(cwd);
|
|
284
|
+
const before = JSON.stringify(registry);
|
|
285
|
+
const result = change(registry);
|
|
286
|
+
if (JSON.stringify(registry) !== before) {
|
|
287
|
+
registry.revision += 1;
|
|
288
|
+
writeAtomic(durableRegistryPath(canonicalPath(cwd)), registry);
|
|
289
|
+
}
|
|
290
|
+
return result;
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** `expiresAt` 0 means the subscription does not expire: Cursor Automations run until they are disabled. */
|
|
295
|
+
export const isDesired = (sub: StoredSubscription, now = Date.now()) => sub.lifecycle === 'active' && (sub.expiresAt === 0 || sub.expiresAt > now);
|
|
296
|
+
/** Whether a fire runs in its own session instead of waking the owner chat. */
|
|
297
|
+
export const runsDetached = (sub: Pick<StoredSubscription, 'config'>) => (sub.config.kind === 'timer' || sub.config.kind === 'webhook' ? sub.config.strategy === 'new_session' : false);
|
|
298
|
+
export function visibleSubscriptions(registry: DurableRegistry, now = Date.now()): StoredSubscription[] {
|
|
299
|
+
return registry.subscriptions.filter((sub) => sub.lifecycle !== 'cancelled' && (isDesired(sub, now) || registry.pending.some((event) => event.subscriptionId === sub.id) || sub.lastOutcome !== undefined));
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
export function createDesired(cwd: string, sub: DurableSubscription): { created: boolean; subscription: StoredSubscription } {
|
|
303
|
+
if (!validSubscription(sub)) throw new Error('Invalid subscription configuration.');
|
|
304
|
+
return transaction(cwd, (registry) => {
|
|
305
|
+
const existing = registry.subscriptions.find((entry) => isDesired(entry) && entry.name === sub.name);
|
|
306
|
+
if (existing !== undefined) return { created: false, subscription: existing };
|
|
307
|
+
if (registry.subscriptions.some((entry) => entry.id === sub.id)) throw new Error(`Subscription identity ${sub.id} already exists.`);
|
|
308
|
+
const config = sub.config;
|
|
309
|
+
if (config.kind === 'webhook') {
|
|
310
|
+
const clash = registry.subscriptions.find((entry) => isDesired(entry) && entry.config.kind === 'webhook' && entry.config.slug === config.slug);
|
|
311
|
+
if (clash !== undefined) throw new Error(`Routine "${clash.name}" already uses the slug ${config.slug}.`);
|
|
312
|
+
}
|
|
313
|
+
const { detachedDelivery: _legacy, ...input } = sub;
|
|
314
|
+
const stored: StoredSubscription = { ...input, revision: registry.revision + 1, lifecycle: 'active' };
|
|
315
|
+
registry.subscriptions.push(stored);
|
|
316
|
+
return { created: true, subscription: stored };
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
export function cancelDesired(cwd: string, key: string): StoredSubscription | undefined {
|
|
321
|
+
return transaction(cwd, (registry) => {
|
|
322
|
+
const candidates = visibleSubscriptions(registry);
|
|
323
|
+
const sub = candidates.find((entry) => entry.id === key) ?? candidates.find((entry) => entry.name === key && isDesired(entry)) ?? candidates.find((entry) => entry.name === key);
|
|
324
|
+
if (sub === undefined) return undefined;
|
|
325
|
+
sub.lifecycle = 'cancelled';
|
|
326
|
+
delete sub.lastOutcome;
|
|
327
|
+
registry.pending = registry.pending.filter((event) => event.subscriptionId !== sub.id);
|
|
328
|
+
return sub;
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
export function expireDesired(cwd: string, at = Date.now()): void {
|
|
333
|
+
transaction(cwd, (registry) => {
|
|
334
|
+
for (const sub of registry.subscriptions) if (sub.lifecycle === 'active' && sub.expiresAt !== 0 && sub.expiresAt <= at) sub.lifecycle = 'expired';
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
export const MAX_PENDING_PER_SUBSCRIPTION = 20;
|
|
339
|
+
|
|
340
|
+
export function acceptEvent(cwd: string, subscriptionId: string, occurrence: string, content: string, at = Date.now()): EventAdmission {
|
|
341
|
+
return transaction(cwd, (registry) => {
|
|
342
|
+
const sub = registry.subscriptions.find((entry) => entry.id === subscriptionId);
|
|
343
|
+
if (sub === undefined || !isDesired(sub, at)) return 'inactive';
|
|
344
|
+
if (sub.lastOccurrence === occurrence || registry.pending.some((event) => event.id === occurrence)) return 'duplicate';
|
|
345
|
+
const forSub = registry.pending.filter((event) => event.subscriptionId === subscriptionId);
|
|
346
|
+
if (forSub.length >= MAX_PENDING_PER_SUBSCRIPTION) return 'full';
|
|
347
|
+
registry.pending.push({ id: occurrence, subscriptionId, acceptedAt: at, content });
|
|
348
|
+
sub.lastOccurrence = occurrence;
|
|
349
|
+
sub.lastEvent = { at, text: 'accepted' };
|
|
350
|
+
delete sub.lastError;
|
|
351
|
+
if (sub.config.kind === 'timer' && sub.config.once) sub.lifecycle = 'completed';
|
|
352
|
+
return 'accepted';
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
export function deliverOwner(cwd: string, ownerSessionId: string, eligible: () => boolean, send: (sub: StoredSubscription, event: PendingEvent) => void): void {
|
|
357
|
+
transaction(cwd, (registry) => {
|
|
358
|
+
for (const event of [...registry.pending]) {
|
|
359
|
+
const sub = registry.subscriptions.find((entry) => entry.id === event.subscriptionId);
|
|
360
|
+
if (sub === undefined || sub.ownerSessionId !== ownerSessionId || sub.lifecycle === 'cancelled' || runsDetached(sub)) continue;
|
|
361
|
+
if (!eligible()) return;
|
|
362
|
+
// Pi enqueue and disk acknowledgement cannot commit atomically. A crash can replay this event.
|
|
363
|
+
send(sub, event);
|
|
364
|
+
registry.pending = registry.pending.filter((entry) => entry.id !== event.id);
|
|
365
|
+
}
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
export function startFresh(
|
|
370
|
+
cwd: string,
|
|
371
|
+
eventId: string,
|
|
372
|
+
ownerSessionId: string | undefined,
|
|
373
|
+
eligible: () => boolean,
|
|
374
|
+
run: (sub: StoredSubscription, event: PendingEvent) => Promise<string | undefined> | string | undefined,
|
|
375
|
+
): { token: string; result: Promise<string | undefined> } | undefined {
|
|
376
|
+
const claim = transaction(cwd, (registry) => {
|
|
377
|
+
const event = registry.pending.find((entry) => entry.id === eventId);
|
|
378
|
+
const sub = registry.subscriptions.find((entry) => entry.id === event?.subscriptionId);
|
|
379
|
+
if (
|
|
380
|
+
event === undefined ||
|
|
381
|
+
sub === undefined ||
|
|
382
|
+
sub.lifecycle === 'cancelled' ||
|
|
383
|
+
!runsDetached(sub) ||
|
|
384
|
+
sub.ownerSessionId === undefined ||
|
|
385
|
+
(event.claim !== undefined && alive(event.claim.pid)) ||
|
|
386
|
+
(event.retryAt !== undefined && Date.now() < event.retryAt) ||
|
|
387
|
+
!eligible()
|
|
388
|
+
)
|
|
389
|
+
return undefined;
|
|
390
|
+
if (ownerSessionId === undefined ? sub.ownerSessionId !== undefined && ownerIsLive(cwd, sub.ownerSessionId) : sub.ownerSessionId !== ownerSessionId) return undefined;
|
|
391
|
+
const token = randomUUID();
|
|
392
|
+
event.claim = { pid: process.pid, token, mode: ownerSessionId === undefined ? 'detached' : 'live' };
|
|
393
|
+
return { token, sub, event };
|
|
394
|
+
});
|
|
395
|
+
if (claim === undefined) return undefined;
|
|
396
|
+
let result: Promise<string | undefined>;
|
|
397
|
+
try {
|
|
398
|
+
result = Promise.resolve(run(claim.sub, claim.event));
|
|
399
|
+
} catch (error) {
|
|
400
|
+
result = Promise.reject(error);
|
|
401
|
+
}
|
|
402
|
+
return { token: claim.token, result };
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
export function finishFresh(cwd: string, eventId: string, token: string, error?: unknown, outcome?: string): void {
|
|
406
|
+
transaction(cwd, (registry) => {
|
|
407
|
+
const event = registry.pending.find((entry) => entry.id === eventId && entry.claim?.token === token);
|
|
408
|
+
if (event === undefined) return;
|
|
409
|
+
const sub = registry.subscriptions.find((entry) => entry.id === event.subscriptionId);
|
|
410
|
+
if (sub === undefined) return;
|
|
411
|
+
if (error !== undefined) {
|
|
412
|
+
const attempts = (event.attempts ?? 0) + 1;
|
|
413
|
+
const MAX_ATTEMPTS = 5;
|
|
414
|
+
sub.lastError = { at: Date.now(), text: error instanceof Error ? error.message : String(error) };
|
|
415
|
+
delete event.claim;
|
|
416
|
+
event.attempts = attempts;
|
|
417
|
+
if (attempts >= MAX_ATTEMPTS) {
|
|
418
|
+
registry.pending = registry.pending.filter((entry) => entry.id !== eventId);
|
|
419
|
+
} else {
|
|
420
|
+
const backoffMs = Math.min(60_000, 250 * 2 ** (attempts - 1));
|
|
421
|
+
event.retryAt = Date.now() + backoffMs;
|
|
422
|
+
}
|
|
423
|
+
} else {
|
|
424
|
+
// A detached run's own final message is its run output, which is where the automation records status.
|
|
425
|
+
sub.lastOutcome = { at: Date.now(), text: event.claim?.mode === 'live' ? 'live Task callback accepted' : outcome?.trim() || 'detached run completed' };
|
|
426
|
+
delete sub.lastError;
|
|
427
|
+
registry.pending = registry.pending.filter((entry) => entry.id !== eventId);
|
|
428
|
+
}
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
export function clearError(cwd: string, id: string): void {
|
|
433
|
+
transaction(cwd, (registry) => {
|
|
434
|
+
const sub = registry.subscriptions.find((entry) => entry.id === id);
|
|
435
|
+
if (sub !== undefined) delete sub.lastError;
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
export function recordError(cwd: string, id: string, error: unknown): void {
|
|
440
|
+
const text = error instanceof Error ? error.message : String(error);
|
|
441
|
+
transaction(cwd, (registry) => {
|
|
442
|
+
const sub = registry.subscriptions.find((entry) => entry.id === id);
|
|
443
|
+
if (sub !== undefined && sub.lastError?.text !== text) {
|
|
444
|
+
sub.lastError = { at: Date.now(), text };
|
|
445
|
+
}
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
export function readLock(cwd: string): SupervisorLock | undefined {
|
|
450
|
+
try {
|
|
451
|
+
const value = JSON.parse(readFileSync(supervisorLockPath(cwd), 'utf8'));
|
|
452
|
+
return Number.isInteger(value.pid) && value.pid > 0 && Number.isFinite(value.startedAt) && typeof value.epoch === 'string' && value.epoch !== '' ? { pid: value.pid, startedAt: value.startedAt, epoch: value.epoch } : undefined;
|
|
453
|
+
} catch (error) {
|
|
454
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;
|
|
455
|
+
throw new Error(`Cannot read supervisor lock ${supervisorLockPath(cwd)}. ${String(error)}`);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
export function isSupervisorLive(cwd: string): boolean {
|
|
459
|
+
const lock = readLock(cwd);
|
|
460
|
+
return lock !== undefined && alive(lock.pid);
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
function supervisorProcess(pid: number, cwd: string): boolean {
|
|
464
|
+
if (process.platform !== 'linux') return false;
|
|
465
|
+
try {
|
|
466
|
+
// The bin is a bash shim that execs bun or node on supervisor-main.ts, so either name can be the live argv.
|
|
467
|
+
const cmdline = readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0').join(' ');
|
|
468
|
+
return cmdline.includes(cwd) && (cmdline.includes('supervisor-main.ts') || cmdline.includes('pstack-routines-supervisor'));
|
|
469
|
+
} catch {
|
|
470
|
+
return false;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
export function acquireSupervisorLock(cwd: string, pid = process.pid, startedAt = Date.now()): { acquired: true } | { acquired: false; alreadyRunning: true; pid: number } {
|
|
475
|
+
return withRegistryLock(cwd, () => {
|
|
476
|
+
try {
|
|
477
|
+
const raw = JSON.parse(readFileSync(supervisorLockPath(cwd), 'utf8'));
|
|
478
|
+
if (Number.isInteger(raw.pid) && raw.pid > 0 && alive(raw.pid)) {
|
|
479
|
+
if (typeof raw.epoch === 'string' && raw.epoch !== '') {
|
|
480
|
+
return { acquired: false, alreadyRunning: true, pid: raw.pid };
|
|
481
|
+
}
|
|
482
|
+
// A pre-epoch lock names no verified owner. Signal it only when its command line is this supervisor, so a
|
|
483
|
+
// reused pid cannot make a stale lock terminate an unrelated process.
|
|
484
|
+
if (!supervisorProcess(raw.pid, cwd)) return { acquired: false, alreadyRunning: true, pid: raw.pid };
|
|
485
|
+
try {
|
|
486
|
+
process.kill(raw.pid, 'SIGTERM');
|
|
487
|
+
} catch {}
|
|
488
|
+
const deadline = Date.now() + 1_000;
|
|
489
|
+
while (Date.now() < deadline && alive(raw.pid)) {
|
|
490
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25);
|
|
491
|
+
}
|
|
492
|
+
if (alive(raw.pid)) {
|
|
493
|
+
return { acquired: false, alreadyRunning: true, pid: raw.pid };
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
} catch (error) {
|
|
497
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
|
|
498
|
+
// Corrupted lock file: overwrite with clean lock
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
writeAtomic(supervisorLockPath(cwd), { pid, startedAt, epoch: randomUUID() });
|
|
502
|
+
return { acquired: true };
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
export function releaseSupervisorLock(cwd: string, pid = process.pid, epoch?: string): void {
|
|
506
|
+
withRegistryLock(cwd, () => {
|
|
507
|
+
const lock = readLock(cwd);
|
|
508
|
+
if (lock?.pid === pid && (epoch === undefined || epoch === lock.epoch)) rmSync(supervisorLockPath(cwd), { force: true });
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
const armPath = (cwd: string, id: string) => join(runtime(cwd), 'arms', `${createHash('sha256').update(id).digest('hex')}.json`);
|
|
513
|
+
export function writeArm(cwd: string, status: ArmStatus): void {
|
|
514
|
+
writeAtomic(armPath(cwd, status.subscriptionId), status);
|
|
515
|
+
}
|
|
516
|
+
export function readArm(cwd: string, sub: StoredSubscription): ArmStatus | undefined {
|
|
517
|
+
const lock = readLock(cwd);
|
|
518
|
+
if (lock === undefined || !alive(lock.pid)) return undefined;
|
|
519
|
+
try {
|
|
520
|
+
const status = JSON.parse(readFileSync(armPath(cwd, sub.id), 'utf8')) as ArmStatus;
|
|
521
|
+
return status.subscriptionId === sub.id &&
|
|
522
|
+
status.revision === sub.revision &&
|
|
523
|
+
status.epoch === lock.epoch &&
|
|
524
|
+
((status.state === 'error' && typeof status.message === 'string') || (status.state === 'ready' && (status.url === undefined || typeof status.url === 'string')))
|
|
525
|
+
? status
|
|
526
|
+
: undefined;
|
|
527
|
+
} catch (error) {
|
|
528
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;
|
|
529
|
+
throw error;
|
|
530
|
+
}
|
|
531
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
export type Target = { scope: 'pr'; prUrl: string } | { scope: 'repo'; repo: string } | { scope: 'author'; author: string; repo: string };
|
|
2
|
+
export type RunModel = { provider: string; id: string; thinking?: string };
|
|
3
|
+
/** What the durable store did with an event. `full` leaves every accepted event untouched so the sender can retry. */
|
|
4
|
+
export type EventAdmission = 'accepted' | 'duplicate' | 'inactive' | 'full';
|
|
5
|
+
export type Config =
|
|
6
|
+
| { kind: 'github'; target: Target }
|
|
7
|
+
| {
|
|
8
|
+
kind: 'timer';
|
|
9
|
+
prompt: string;
|
|
10
|
+
cron?: string;
|
|
11
|
+
delaySeconds?: number;
|
|
12
|
+
once: boolean;
|
|
13
|
+
strategy: 'wake_self' | 'new_session';
|
|
14
|
+
/** The owner's model when it created the timer, reused by a live or detached new_session fire. */
|
|
15
|
+
model?: RunModel;
|
|
16
|
+
/** The owner's project-trust decision when it created the timer. */
|
|
17
|
+
trusted?: boolean;
|
|
18
|
+
}
|
|
19
|
+
| {
|
|
20
|
+
kind: 'webhook';
|
|
21
|
+
prompt: string;
|
|
22
|
+
slug: string;
|
|
23
|
+
/** Absent in records written before webhook routines could run detached, which means wake_self. */
|
|
24
|
+
strategy?: 'wake_self' | 'new_session';
|
|
25
|
+
/** The owner's model when it created a detached routine, reused by every fire. */
|
|
26
|
+
model?: RunModel;
|
|
27
|
+
/** The owner's project-trust decision when it created a detached routine. */
|
|
28
|
+
trusted?: boolean;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/** `expiresAt` of 0 means the subscription does not expire, as Cursor Automations do not. */
|
|
32
|
+
export type Subscription = { id: string; name: string; createdAt: number; expiresAt: number; config: Config };
|
|
33
|
+
export type DurableSubscription = Subscription & {
|
|
34
|
+
ownerSessionId?: string;
|
|
35
|
+
ownerSessionFile?: string;
|
|
36
|
+
/** Read only during v1 migration. Delivery is determined by config, never this flag. */
|
|
37
|
+
detachedDelivery?: 'spawn' | 'park';
|
|
38
|
+
};
|
|
39
|
+
export type Note = { at: number; text: string };
|
|
40
|
+
export type StoredSubscription = DurableSubscription & {
|
|
41
|
+
revision: number;
|
|
42
|
+
lifecycle: 'active' | 'completed' | 'cancelled' | 'expired';
|
|
43
|
+
lastOccurrence?: string;
|
|
44
|
+
lastEvent?: Note;
|
|
45
|
+
lastError?: Note;
|
|
46
|
+
lastOutcome?: Note;
|
|
47
|
+
};
|
|
48
|
+
export type PendingEvent = {
|
|
49
|
+
id: string;
|
|
50
|
+
subscriptionId: string;
|
|
51
|
+
acceptedAt: number;
|
|
52
|
+
content: string;
|
|
53
|
+
claim?: { pid: number; token: string; mode: 'live' | 'detached' };
|
|
54
|
+
attempts?: number;
|
|
55
|
+
retryAt?: number;
|
|
56
|
+
};
|
|
57
|
+
export type DurableRegistry = {
|
|
58
|
+
version: 2;
|
|
59
|
+
workspaceCwd: string;
|
|
60
|
+
revision: number;
|
|
61
|
+
subscriptions: StoredSubscription[];
|
|
62
|
+
pending: PendingEvent[];
|
|
63
|
+
};
|
|
64
|
+
export type SupervisorLock = { pid: number; startedAt: number; epoch: string };
|
|
65
|
+
export type ArmStatus = {
|
|
66
|
+
subscriptionId: string;
|
|
67
|
+
revision: number;
|
|
68
|
+
epoch: string;
|
|
69
|
+
} & ({ state: 'ready'; url?: string } | { state: 'error'; message: string });
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
|
|
5
|
+
import { piCommand } from '../pi-command.ts';
|
|
6
|
+
import { isSupervisorLive, readArm, readRegistry } from './durable-store.ts';
|
|
7
|
+
import type { ArmStatus, StoredSubscription } from './durable-types.ts';
|
|
8
|
+
|
|
9
|
+
const DEFAULT_READY_MS = 2_000;
|
|
10
|
+
const POLL_MS = 50;
|
|
11
|
+
|
|
12
|
+
export function supervisorBinPath(): string {
|
|
13
|
+
return join(dirname(fileURLToPath(import.meta.url)), '../../bin/pstack-routines-supervisor');
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export type EnsureSupervisorSpawnOptions = {
|
|
17
|
+
/** Concrete port override forwarded as PSTACK_ROUTINES_PORT, including ephemeral port zero. */
|
|
18
|
+
routinesPort?: number;
|
|
19
|
+
/** Bin path override; production leaves this unset. */
|
|
20
|
+
binPath?: string;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Spawns `pstack-routines-supervisor --workspace <cwd>` detached when no live lock exists.
|
|
25
|
+
* Idempotent when the supervisor is already running for that workspace.
|
|
26
|
+
* Spawn errors (missing bin) are swallowed so the interactive Pi process cannot crash.
|
|
27
|
+
*/
|
|
28
|
+
export function defaultEnsureSupervisor(cwd: string, options: EnsureSupervisorSpawnOptions = {}): void {
|
|
29
|
+
if (isSupervisorLive(cwd)) return;
|
|
30
|
+
const env: NodeJS.ProcessEnv = { ...process.env, PI_PSTACK_PI_COMMAND: JSON.stringify(piCommand()) };
|
|
31
|
+
if (options.routinesPort !== undefined) {
|
|
32
|
+
env['PSTACK_ROUTINES_PORT'] = String(options.routinesPort);
|
|
33
|
+
}
|
|
34
|
+
const child = spawn(options.binPath ?? supervisorBinPath(), ['--workspace', cwd], {
|
|
35
|
+
detached: true,
|
|
36
|
+
stdio: 'ignore',
|
|
37
|
+
env,
|
|
38
|
+
});
|
|
39
|
+
child.on('error', () => {
|
|
40
|
+
// Missing bin or other spawn failure: chat falls back to in-process arming.
|
|
41
|
+
});
|
|
42
|
+
child.unref();
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Polls until supervisor.lock names a live pid, or the deadline passes. */
|
|
46
|
+
export async function waitForSupervisor(cwd: string, readyMs = DEFAULT_READY_MS, now = Date.now, sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))): Promise<boolean> {
|
|
47
|
+
if (isSupervisorLive(cwd)) return true;
|
|
48
|
+
const deadline = now() + readyMs;
|
|
49
|
+
while (now() < deadline) {
|
|
50
|
+
await sleep(POLL_MS);
|
|
51
|
+
if (isSupervisorLive(cwd)) return true;
|
|
52
|
+
}
|
|
53
|
+
return isSupervisorLive(cwd);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export async function waitForArm(cwd: string, sub: StoredSubscription, readyMs = DEFAULT_READY_MS): Promise<Extract<ArmStatus, { state: 'ready' }>> {
|
|
57
|
+
const deadline = Date.now() + readyMs;
|
|
58
|
+
for (;;) {
|
|
59
|
+
const current = readRegistry(cwd).subscriptions.find((entry) => entry.id === sub.id);
|
|
60
|
+
if (current?.lifecycle === 'cancelled') throw new Error(`Subscription ${sub.id} was cancelled while arming.`);
|
|
61
|
+
const status = readArm(cwd, sub);
|
|
62
|
+
if (status?.state === 'ready') return status;
|
|
63
|
+
if (status?.state === 'error') throw new Error(`Subscription ${sub.id} could not arm. ${status.message}`);
|
|
64
|
+
if (Date.now() >= deadline) throw new Error(`Subscription ${sub.id} readiness timed out. No matching live supervisor arm.`);
|
|
65
|
+
await new Promise<void>((resolve) => setTimeout(resolve, POLL_MS));
|
|
66
|
+
}
|
|
67
|
+
}
|