pinwright 0.0.0-stage → 0.1.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 (60) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +245 -2
  3. package/dist/agent.d.ts +16 -0
  4. package/dist/agent.js +292 -0
  5. package/dist/astro.d.ts +16 -0
  6. package/dist/astro.js +29 -0
  7. package/dist/bus.d.ts +16 -0
  8. package/dist/bus.js +13 -0
  9. package/dist/cli.d.ts +2 -0
  10. package/dist/cli.js +125 -0
  11. package/dist/cloudflared.d.ts +10 -0
  12. package/dist/cloudflared.js +98 -0
  13. package/dist/collab.d.ts +56 -0
  14. package/dist/collab.js +183 -0
  15. package/dist/config.d.ts +53 -0
  16. package/dist/config.js +59 -0
  17. package/dist/context.d.ts +18 -0
  18. package/dist/context.js +11 -0
  19. package/dist/db.d.ts +2 -0
  20. package/dist/db.js +74 -0
  21. package/dist/guard.d.ts +26 -0
  22. package/dist/guard.js +137 -0
  23. package/dist/index.d.ts +15 -0
  24. package/dist/index.js +70 -0
  25. package/dist/inject.d.ts +7 -0
  26. package/dist/inject.js +82 -0
  27. package/dist/locks.d.ts +14 -0
  28. package/dist/locks.js +51 -0
  29. package/dist/next-script.d.ts +6 -0
  30. package/dist/next-script.js +12 -0
  31. package/dist/next.d.ts +10 -0
  32. package/dist/next.js +28 -0
  33. package/dist/nuxt.d.ts +18 -0
  34. package/dist/nuxt.js +17 -0
  35. package/dist/ops.d.ts +39 -0
  36. package/dist/ops.js +146 -0
  37. package/dist/planner.d.ts +10 -0
  38. package/dist/planner.js +65 -0
  39. package/dist/plugin.d.ts +13 -0
  40. package/dist/plugin.js +58 -0
  41. package/dist/rebuild.d.ts +23 -0
  42. package/dist/rebuild.js +67 -0
  43. package/dist/scheduler.d.ts +26 -0
  44. package/dist/scheduler.js +150 -0
  45. package/dist/server.d.ts +7 -0
  46. package/dist/server.js +355 -0
  47. package/dist/shots.d.ts +25 -0
  48. package/dist/shots.js +86 -0
  49. package/dist/store.d.ts +76 -0
  50. package/dist/store.js +159 -0
  51. package/dist/tools.d.ts +11 -0
  52. package/dist/tools.js +27 -0
  53. package/dist/vite.d.ts +33 -0
  54. package/dist/vite.js +37 -0
  55. package/dist/webpack.d.ts +36 -0
  56. package/dist/webpack.js +58 -0
  57. package/dist/ws.d.ts +25 -0
  58. package/dist/ws.js +115 -0
  59. package/overlay/overlay.js +1379 -0
  60. package/package.json +59 -4
package/dist/ops.js ADDED
@@ -0,0 +1,146 @@
1
+ import { existsSync, readFileSync, unlinkSync, writeFileSync, mkdirSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { applyPatch, structuredPatch } from 'diff';
4
+ import { notePrompt } from './agent.js';
5
+ export class OpError extends Error {
6
+ code;
7
+ data;
8
+ constructor(message, code = 400, data) {
9
+ super(message);
10
+ this.code = code;
11
+ this.data = data;
12
+ }
13
+ }
14
+ /** What reviewers (overlay) and the CLI can do to a note. */
15
+ export class Ops {
16
+ ctx;
17
+ scheduler;
18
+ constructor(ctx, scheduler) {
19
+ this.ctx = ctx;
20
+ this.scheduler = scheduler;
21
+ }
22
+ must(id) {
23
+ const n = this.ctx.store.get(id);
24
+ if (!n || n.status === 'deleted')
25
+ throw new OpError('note not found', 404);
26
+ return n;
27
+ }
28
+ /**
29
+ * An answer to a question, or a follow-up on a finished note: either way the same session resumes.
30
+ * `approved: false` (a guest of the review link) holds it until the host approves.
31
+ */
32
+ reply(id, text, author = null, approved = true, guest = false) {
33
+ const n = this.must(id);
34
+ const t = text.trim();
35
+ if (!t)
36
+ throw new OpError('empty reply');
37
+ if (['working', 'planning'].includes(n.status))
38
+ throw new OpError('the agent is still working on this note', 409);
39
+ this.ctx.store.message(id, 'user', t, author);
40
+ // Once a guest has written in the thread, the whole note runs under the guest rules.
41
+ return this.ctx.store.update(id, { status: 'queued', attempts: 0, approved, ...(guest ? { guest: true } : {}) });
42
+ }
43
+ /** Lets a note from the review link go to the agents. */
44
+ approve(id) {
45
+ const n = this.must(id);
46
+ if (n.approved)
47
+ return n;
48
+ this.ctx.store.message(id, 'system', 'Approved by the host.');
49
+ this.ctx.cfg.log(`${id}: approved`);
50
+ return this.ctx.store.update(id, { approved: true });
51
+ }
52
+ archive(id) {
53
+ this.must(id);
54
+ return this.ctx.store.update(id, { status: 'archived' });
55
+ }
56
+ retry(id, approved = true) {
57
+ const n = this.must(id);
58
+ if (['working', 'planning', 'queued'].includes(n.status))
59
+ return n;
60
+ return this.ctx.store.update(id, { status: 'queued', attempts: 0, approved });
61
+ }
62
+ handoff(id) {
63
+ this.must(id);
64
+ this.scheduler.abort(id, 'handed off');
65
+ this.ctx.store.message(id, 'system', 'Handed off by the reviewer.');
66
+ return this.ctx.store.update(id, { status: 'handoff' });
67
+ }
68
+ delete(id) {
69
+ this.must(id);
70
+ this.scheduler.abort(id);
71
+ this.ctx.store.update(id, { status: 'deleted' });
72
+ }
73
+ /**
74
+ * Restores what the note changed. A file nobody touched since goes back to its original; a file
75
+ * another edit changed since gets the note's patch reversed on top, and if that doesn't apply
76
+ * cleanly the whole undo is refused, listing the files.
77
+ */
78
+ async undo(id) {
79
+ const { store, cfg, rebuilder, locks } = this.ctx;
80
+ const n = this.must(id);
81
+ if (['working', 'planning'].includes(n.status))
82
+ throw new OpError('the agent is still working on this note', 409);
83
+ if (n.status === 'undone')
84
+ throw new OpError('already undone');
85
+ const changes = store.changes(id);
86
+ if (!changes.length)
87
+ throw new OpError('nothing to undo');
88
+ const busy = changes.filter((c) => locks.holder(c.file, id));
89
+ if (busy.length)
90
+ throw new OpError(`files in use by another note: ${busy.map((c) => c.file).join(', ')}`, 409, { files: busy.map((c) => c.file) });
91
+ const read = (f) => (existsSync(join(cfg.root, f)) ? readFileSync(join(cfg.root, f), 'utf8') : null);
92
+ const plan = [];
93
+ const conflicts = [];
94
+ for (const c of changes) {
95
+ const now = read(c.file);
96
+ if (now === c.final)
97
+ plan.push({ file: c.file, content: c.original });
98
+ else if (now !== null && c.final !== null && c.original !== null) {
99
+ const reverted = applyPatch(now, structuredPatch(c.file, c.file, c.final, c.original, "", "", { context: 0 }));
100
+ if (reverted === false)
101
+ conflicts.push(c.file);
102
+ else
103
+ plan.push({ file: c.file, content: reverted });
104
+ }
105
+ else
106
+ conflicts.push(c.file);
107
+ }
108
+ if (conflicts.length) {
109
+ throw new OpError(`changed since in a conflicting way, undo refused: ${conflicts.join(', ')}`, 409, { files: conflicts });
110
+ }
111
+ for (const { file, content } of plan) {
112
+ const abs = join(cfg.root, file);
113
+ if (content === null)
114
+ unlinkSync(abs);
115
+ else {
116
+ mkdirSync(dirname(abs), { recursive: true });
117
+ writeFileSync(abs, content);
118
+ }
119
+ }
120
+ store.message(id, 'system', `Undone: ${changes.map((c) => c.file).join(', ')}`);
121
+ cfg.log(`${id}: undone`);
122
+ const note = store.update(id, { status: 'undone' });
123
+ void rebuilder.request();
124
+ return note;
125
+ }
126
+ /** Pulls a note into an interactive Claude Code session: marks it taken and returns a ready prompt. */
127
+ take(id) {
128
+ const { store, cfg } = this.ctx;
129
+ const n = this.must(id);
130
+ this.scheduler.abort(id, 'taken');
131
+ const msgs = store.messages(id).slice(1);
132
+ const thread = msgs.length ? `\n\nThread so far:\n${msgs.map((m) => `- ${m.role}: ${m.text}`).join('\n')}` : '';
133
+ const prompt = `${notePrompt(n)}${thread}\n\nThis note was handed over from pinwright. Work on it here with me. When it's done, run \`pinwright done ${id} "<one-line summary>"\`.`;
134
+ store.message(id, 'system', 'Taken into an interactive session.');
135
+ const note = store.update(id, { status: 'taken' });
136
+ cfg.log(`${id}: taken`);
137
+ return { note, prompt };
138
+ }
139
+ /** Closes a note handled by hand (after `take`). */
140
+ markDone(id, summary) {
141
+ const n = this.must(id);
142
+ const s = summary?.trim() || 'Done by hand.';
143
+ this.ctx.store.message(id, 'agent', s);
144
+ return this.ctx.store.update(id, { status: 'done', summary: s, attempts: 0, shots: n.shots });
145
+ }
146
+ }
@@ -0,0 +1,10 @@
1
+ import { type Ctx } from './context.js';
2
+ import type { Note } from './store.js';
3
+ /**
4
+ * Predicts which files a note touches, so non-overlapping notes can run side by side.
5
+ * Never throws: on any failure the answer is [] and the edit-time locks take over.
6
+ */
7
+ export declare function plan(ctx: Ctx, note: Note, signal: AbortSignal): Promise<{
8
+ files: string[];
9
+ cost: number;
10
+ }>;
@@ -0,0 +1,65 @@
1
+ import { query } from '@anthropic-ai/claude-agent-sdk';
2
+ import { agentEnv } from './context.js';
3
+ import { notePrompt } from './agent.js';
4
+ import { readHook } from './guard.js';
5
+ const SYSTEM = `You plan work for a code agent. Given a review note pinned on a web page, find which source files the fix will most likely edit.
6
+ Use Glob and Grep (Read only if needed) to locate the element: search for its distinctive text, classes or ids. Be quick: a few searches.
7
+ Answer with ONLY a JSON object, no prose: {"files": ["relative/path", ...]}.
8
+ List at most 5 files, relative to the project root. Use a directory path only if you truly cannot narrow it down. If unsure, {"files": []}.`;
9
+ /**
10
+ * Predicts which files a note touches, so non-overlapping notes can run side by side.
11
+ * Never throws: on any failure the answer is [] and the edit-time locks take over.
12
+ */
13
+ export async function plan(ctx, note, signal) {
14
+ const abort = new AbortController();
15
+ const onAbort = () => abort.abort();
16
+ signal.addEventListener('abort', onAbort);
17
+ const timer = setTimeout(() => abort.abort(), 90_000);
18
+ let text = '';
19
+ let cost = 0;
20
+ try {
21
+ for await (const m of query({
22
+ prompt: `${notePrompt(note)}\n\nWhich files will the fix edit? JSON only.`,
23
+ options: {
24
+ cwd: ctx.cfg.root,
25
+ model: ctx.cfg.models.planner,
26
+ tools: ['Read', 'Glob', 'Grep'],
27
+ settingSources: [],
28
+ systemPrompt: SYSTEM,
29
+ maxTurns: 8,
30
+ persistSession: false,
31
+ abortController: abort,
32
+ env: agentEnv(ctx.cfg),
33
+ // Auto-allowed reads skip canUseTool: the hook keeps them inside the project (and off secrets for guests).
34
+ hooks: { PreToolUse: [{ hooks: [readHook(ctx.cfg.root, () => note.guest)] }] },
35
+ canUseTool: async (name, input) => ['Read', 'Glob', 'Grep'].includes(name) ? { behavior: 'allow', updatedInput: input } : { behavior: 'deny', message: 'read-only' },
36
+ },
37
+ })) {
38
+ if (m.type === 'assistant')
39
+ for (const b of m.message.content)
40
+ if (b.type === 'text')
41
+ text = b.text;
42
+ if (m.type === 'result') {
43
+ cost = m.total_cost_usd;
44
+ if (m.subtype === 'success')
45
+ text = m.result || text;
46
+ }
47
+ }
48
+ }
49
+ catch (e) {
50
+ ctx.cfg.log(`${note.id}: planner failed: ${e.message.split('\n')[0]}`);
51
+ }
52
+ finally {
53
+ clearTimeout(timer);
54
+ signal.removeEventListener('abort', onAbort);
55
+ }
56
+ const json = text.match(/\{[\s\S]*\}/)?.[0];
57
+ try {
58
+ const files = JSON.parse(json ?? '{}').files;
59
+ if (Array.isArray(files)) {
60
+ return { files: files.filter((f) => typeof f === 'string' && f.length > 0).slice(0, 8), cost };
61
+ }
62
+ }
63
+ catch { }
64
+ return { files: [], cost };
65
+ }
@@ -0,0 +1,13 @@
1
+ import { type Options, type Pinwright } from './index.js';
2
+ export declare function ensureDaemon(opts: Options): Promise<Pinwright>;
3
+ export declare function currentDaemon(): Promise<Pinwright | null>;
4
+ export declare function releaseDaemon(): void;
5
+ /** Starts the daemon for a plugin, logging instead of throwing: a dev server must come up without pinwright. */
6
+ export declare function tryDaemon(opts: Options): Promise<Pinwright | null>;
7
+ /**
8
+ * Browser code that loads the overlay once. A classic script, so the overlay can find its own origin through
9
+ * document.currentScript. Automated browsers are skipped (the overlay skips them too).
10
+ */
11
+ export declare function loaderCode(scriptUrl: string): string;
12
+ /** The tag to put in served HTML. */
13
+ export declare function scriptTag(scriptUrl: string): string;
package/dist/plugin.js ADDED
@@ -0,0 +1,58 @@
1
+ import { startPinwright } from './index.js';
2
+ /*
3
+ * Shared by every framework plugin: one daemon per process. Dev servers restart by opening the new
4
+ * server before closing the old one, so the daemon stops only when the last user has let it go for a moment.
5
+ */
6
+ let current = null;
7
+ let users = 0;
8
+ let stopTimer = null;
9
+ export function ensureDaemon(opts) {
10
+ users++;
11
+ if (stopTimer)
12
+ clearTimeout(stopTimer);
13
+ stopTimer = null;
14
+ current ??= startPinwright({ ...opts, mode: 'plugin' }).catch((e) => {
15
+ current = null;
16
+ throw e;
17
+ });
18
+ return current;
19
+ }
20
+ export function currentDaemon() {
21
+ return current?.catch(() => null) ?? Promise.resolve(null);
22
+ }
23
+ export function releaseDaemon() {
24
+ users = Math.max(0, users - 1);
25
+ if (users || stopTimer)
26
+ return;
27
+ stopTimer = setTimeout(() => {
28
+ stopTimer = null;
29
+ if (users)
30
+ return;
31
+ const c = current;
32
+ current = null;
33
+ void c?.then((pw) => pw.stop()).catch(() => { });
34
+ }, 1500);
35
+ stopTimer.unref();
36
+ }
37
+ /** Starts the daemon for a plugin, logging instead of throwing: a dev server must come up without pinwright. */
38
+ export async function tryDaemon(opts) {
39
+ try {
40
+ return await ensureDaemon(opts);
41
+ }
42
+ catch (e) {
43
+ releaseDaemon();
44
+ console.error(`[pinwright] not started: ${e.message}`);
45
+ return null;
46
+ }
47
+ }
48
+ /**
49
+ * Browser code that loads the overlay once. A classic script, so the overlay can find its own origin through
50
+ * document.currentScript. Automated browsers are skipped (the overlay skips them too).
51
+ */
52
+ export function loaderCode(scriptUrl) {
53
+ return `if(typeof window!=='undefined'&&!navigator.webdriver&&!document.querySelector('script[data-pinwright]')){const s=document.createElement('script');s.src=${JSON.stringify(scriptUrl)};s.dataset.pinwright='';(document.body||document.documentElement).append(s)}`;
54
+ }
55
+ /** The tag to put in served HTML. */
56
+ export function scriptTag(scriptUrl) {
57
+ return `<script src="${scriptUrl}" data-pinwright defer></script>`;
58
+ }
@@ -0,0 +1,23 @@
1
+ import type { Bus } from './bus.js';
2
+ import type { Config } from './config.js';
3
+ export interface RebuildResult {
4
+ ok: boolean;
5
+ output: string;
6
+ skipped?: boolean;
7
+ }
8
+ /** Runs a shell command in root; resolves with the exit status and the tail of its output. */
9
+ export declare function sh(cmd: string, cwd: string, timeoutMs?: number): Promise<RebuildResult>;
10
+ /**
11
+ * The configured rebuild, serialized and coalesced: while one runs, every new request
12
+ * shares a single follow-up run, which picks up all the edits made in the meantime.
13
+ */
14
+ export declare class Rebuilder {
15
+ private cfg;
16
+ private bus;
17
+ private running;
18
+ private next;
19
+ constructor(cfg: Config, bus: Bus);
20
+ get enabled(): boolean;
21
+ request(): Promise<RebuildResult>;
22
+ private run;
23
+ }
@@ -0,0 +1,67 @@
1
+ import { spawn } from 'node:child_process';
2
+ /** Runs a shell command in root; resolves with the exit status and the tail of its output. */
3
+ export function sh(cmd, cwd, timeoutMs = 10 * 60_000) {
4
+ return new Promise((done) => {
5
+ const p = spawn(cmd, { cwd, shell: true, stdio: ['ignore', 'pipe', 'pipe'] });
6
+ let out = '';
7
+ const add = (b) => {
8
+ out = (out + b.toString()).slice(-8000);
9
+ };
10
+ p.stdout.on('data', add);
11
+ p.stderr.on('data', add);
12
+ const timer = setTimeout(() => p.kill('SIGTERM'), timeoutMs);
13
+ p.on('error', (e) => {
14
+ clearTimeout(timer);
15
+ done({ ok: false, output: String(e) });
16
+ });
17
+ p.on('close', (code) => {
18
+ clearTimeout(timer);
19
+ done({ ok: code === 0, output: out.slice(-4000) });
20
+ });
21
+ });
22
+ }
23
+ /**
24
+ * The configured rebuild, serialized and coalesced: while one runs, every new request
25
+ * shares a single follow-up run, which picks up all the edits made in the meantime.
26
+ */
27
+ export class Rebuilder {
28
+ cfg;
29
+ bus;
30
+ running = null;
31
+ next = null;
32
+ constructor(cfg, bus) {
33
+ this.cfg = cfg;
34
+ this.bus = bus;
35
+ }
36
+ get enabled() {
37
+ return Boolean(this.cfg.rebuild);
38
+ }
39
+ request() {
40
+ if (!this.cfg.rebuild)
41
+ return Promise.resolve({ ok: true, output: 'No rebuild configured: the dev server reloads on its own (HMR).', skipped: true });
42
+ if (!this.running)
43
+ return (this.running = this.run());
44
+ if (!this.next) {
45
+ this.next = this.running.then(() => {
46
+ this.next = null;
47
+ return (this.running = this.run());
48
+ });
49
+ }
50
+ return this.next;
51
+ }
52
+ async run() {
53
+ const t = Date.now();
54
+ this.cfg.log(`rebuild: ${this.cfg.rebuild}`);
55
+ try {
56
+ const r = await sh(this.cfg.rebuild, this.cfg.root);
57
+ this.cfg.log(`rebuild ${r.ok ? 'ok' : 'FAILED'} in ${((Date.now() - t) / 1000).toFixed(1)}s`);
58
+ if (r.ok)
59
+ this.bus.emit('reload');
60
+ return r;
61
+ }
62
+ finally {
63
+ if (!this.next)
64
+ this.running = null;
65
+ }
66
+ }
67
+ }
@@ -0,0 +1,26 @@
1
+ import type { Ctx } from './context.js';
2
+ /**
3
+ * Queue → planner → locks → workers. Ticks every second and whenever a note changes.
4
+ * Every step is caught: the scheduler must outlive any agent.
5
+ */
6
+ export declare class Scheduler {
7
+ private ctx;
8
+ private running;
9
+ private jobs;
10
+ private planning;
11
+ private timer;
12
+ private ticking;
13
+ private again;
14
+ private onNote;
15
+ constructor(ctx: Ctx);
16
+ start(): void;
17
+ stop(): Promise<void>;
18
+ get busy(): string[];
19
+ /** Stops a note's agent or planner (the note was deleted or taken). */
20
+ abort(id: string, why?: string): void;
21
+ wake(): void;
22
+ private tick;
23
+ private schedule;
24
+ private startPlan;
25
+ private startWork;
26
+ }
@@ -0,0 +1,150 @@
1
+ import { MAX_ATTEMPTS, runNote } from './agent.js';
2
+ import { plan } from './planner.js';
3
+ const MAX_PLANNERS = 2;
4
+ /**
5
+ * Queue → planner → locks → workers. Ticks every second and whenever a note changes.
6
+ * Every step is caught: the scheduler must outlive any agent.
7
+ */
8
+ export class Scheduler {
9
+ ctx;
10
+ running = new Map();
11
+ jobs = new Set();
12
+ planning = new Map();
13
+ timer = null;
14
+ ticking = false;
15
+ again = false;
16
+ onNote = () => this.wake();
17
+ constructor(ctx) {
18
+ this.ctx = ctx;
19
+ }
20
+ start() {
21
+ const { store, cfg } = this.ctx;
22
+ // Whatever was mid-flight when the daemon stopped goes back in the queue.
23
+ for (const n of store.list(['working', 'planning'])) {
24
+ store.update(n.id, { status: 'queued', attempts: n.status === 'working' ? n.attempts + 1 : n.attempts });
25
+ cfg.log(`${n.id}: recovered, back in the queue`);
26
+ }
27
+ this.timer = setInterval(() => this.tick(), 1000);
28
+ this.ctx.bus.on('note', this.onNote);
29
+ this.wake();
30
+ }
31
+ async stop() {
32
+ if (this.timer)
33
+ clearInterval(this.timer);
34
+ this.timer = null;
35
+ this.ctx.bus.off('note', this.onNote);
36
+ for (const a of [...this.running.values(), ...this.planning.values()])
37
+ a.abort(new Error('shutdown'));
38
+ // Let the aborted agents write their status back before the database closes.
39
+ await Promise.race([Promise.allSettled([...this.jobs]), new Promise((ok) => setTimeout(ok, 5000))]);
40
+ }
41
+ get busy() {
42
+ return [...this.running.keys()];
43
+ }
44
+ /** Stops a note's agent or planner (the note was deleted or taken). */
45
+ abort(id, why = 'deleted') {
46
+ this.running.get(id)?.abort(new Error(why));
47
+ this.planning.get(id)?.abort(new Error(why));
48
+ }
49
+ wake() {
50
+ setImmediate(() => this.tick());
51
+ }
52
+ tick() {
53
+ if (!this.timer)
54
+ return;
55
+ if (this.ticking) {
56
+ this.again = true;
57
+ return;
58
+ }
59
+ this.ticking = true;
60
+ try {
61
+ this.schedule();
62
+ }
63
+ catch (e) {
64
+ this.ctx.cfg.log(`scheduler: ${e.message}`);
65
+ }
66
+ finally {
67
+ this.ticking = false;
68
+ if (this.again) {
69
+ this.again = false;
70
+ this.wake();
71
+ }
72
+ }
73
+ }
74
+ schedule() {
75
+ const { store, cfg, locks } = this.ctx;
76
+ if (cfg.maxAgents < 1)
77
+ return;
78
+ const queued = store.list(['queued']).filter((n) => n.approved && !this.running.has(n.id) && !this.planning.has(n.id));
79
+ for (const note of queued) {
80
+ if (note.attempts >= MAX_ATTEMPTS) {
81
+ store.message(note.id, 'system', 'Failed too many times.');
82
+ store.update(note.id, { status: 'failed' });
83
+ continue;
84
+ }
85
+ if (note.area === null) {
86
+ // Nothing to run alongside: planning would only add latency.
87
+ const alone = this.running.size === 0 && this.planning.size === 0 && queued.length === 1;
88
+ if (!cfg.models.planner || alone)
89
+ store.update(note.id, { area: [] });
90
+ else if (this.planning.size < MAX_PLANNERS)
91
+ this.startPlan(note);
92
+ if (store.get(note.id)?.area === null)
93
+ continue;
94
+ note.area = [];
95
+ }
96
+ if (this.running.size >= cfg.maxAgents)
97
+ continue;
98
+ if (!locks.tryAcquire(note.id, note.area))
99
+ continue;
100
+ this.startWork(note);
101
+ }
102
+ }
103
+ startPlan(note) {
104
+ const { store, cfg } = this.ctx;
105
+ const abort = new AbortController();
106
+ this.planning.set(note.id, abort);
107
+ store.update(note.id, { status: 'planning' });
108
+ this.ctx.bus.setActivity(note.id, 'Planning');
109
+ plan(this.ctx, note, abort.signal)
110
+ .then(({ files, cost }) => {
111
+ const cur = store.get(note.id);
112
+ if (!cur || cur.status !== 'planning')
113
+ return;
114
+ cfg.log(`${note.id}: area ${files.length ? files.join(', ') : '(unknown)'} ($${cost.toFixed(3)})`);
115
+ store.update(note.id, { status: 'queued', area: files });
116
+ })
117
+ .catch((e) => {
118
+ cfg.log(`${note.id}: planning failed: ${e.message}`);
119
+ if (store.get(note.id)?.status === 'planning')
120
+ store.update(note.id, { status: 'queued', area: [] });
121
+ })
122
+ .finally(() => {
123
+ this.planning.delete(note.id);
124
+ this.ctx.bus.setActivity(note.id, null);
125
+ this.wake();
126
+ });
127
+ }
128
+ startWork(note) {
129
+ const { store, cfg, locks } = this.ctx;
130
+ const abort = new AbortController();
131
+ this.running.set(note.id, abort);
132
+ const started = store.update(note.id, { status: 'working', startedAt: new Date().toISOString() }) ?? note;
133
+ cfg.log(`${note.id}: working on “${note.text.split('\n')[0].slice(0, 70)}”${note.area?.length ? ` [${note.area.join(', ')}]` : ''}`);
134
+ const job = runNote(this.ctx, started, abort)
135
+ .catch((e) => {
136
+ // runNote is not supposed to throw; if it does, the note goes back in the queue.
137
+ cfg.log(`${note.id}: worker crashed: ${e.stack ?? e}`);
138
+ const cur = store.get(note.id);
139
+ if (cur?.status === 'working')
140
+ store.update(note.id, { status: 'queued', attempts: cur.attempts + 1 });
141
+ })
142
+ .finally(() => {
143
+ this.running.delete(note.id);
144
+ this.jobs.delete(job);
145
+ locks.releaseAll(note.id);
146
+ this.wake();
147
+ });
148
+ this.jobs.add(job);
149
+ }
150
+ }
@@ -0,0 +1,7 @@
1
+ import http from 'node:http';
2
+ import { type Collab } from './collab.js';
3
+ import type { Ctx } from './context.js';
4
+ import { type Ops } from './ops.js';
5
+ import type { Scheduler } from './scheduler.js';
6
+ export declare const SCRIPT_PATH = "/__pw/overlay.js";
7
+ export declare function createServer(ctx: Ctx, ops: Ops, scheduler: Scheduler, collab: Collab): http.Server;