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/db.js ADDED
@@ -0,0 +1,74 @@
1
+ import { mkdirSync, writeFileSync, existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { DatabaseSync } from 'node:sqlite';
4
+ /** Each entry moves the schema one version up; never edit a shipped one, append a new one. */
5
+ const MIGRATIONS = [
6
+ `CREATE TABLE notes (
7
+ id TEXT PRIMARY KEY,
8
+ page TEXT NOT NULL,
9
+ url TEXT,
10
+ selector TEXT,
11
+ element TEXT,
12
+ html TEXT,
13
+ styles TEXT,
14
+ fx REAL, fy REAL, page_x REAL, page_y REAL,
15
+ viewport TEXT,
16
+ text TEXT NOT NULL,
17
+ author TEXT,
18
+ approved INTEGER NOT NULL DEFAULT 1,
19
+ status TEXT NOT NULL DEFAULT 'queued',
20
+ area TEXT,
21
+ session_id TEXT,
22
+ attempts INTEGER NOT NULL DEFAULT 0,
23
+ summary TEXT,
24
+ diff TEXT,
25
+ shots TEXT,
26
+ cost_usd REAL NOT NULL DEFAULT 0,
27
+ created_at TEXT NOT NULL,
28
+ updated_at TEXT NOT NULL,
29
+ started_at TEXT
30
+ );
31
+ CREATE INDEX notes_status ON notes(status);
32
+ CREATE INDEX notes_page ON notes(page);
33
+ CREATE TABLE messages (
34
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
35
+ note_id TEXT NOT NULL REFERENCES notes(id) ON DELETE CASCADE,
36
+ role TEXT NOT NULL,
37
+ text TEXT NOT NULL,
38
+ at TEXT NOT NULL
39
+ );
40
+ CREATE INDEX messages_note ON messages(note_id);
41
+ CREATE TABLE changes (
42
+ note_id TEXT NOT NULL REFERENCES notes(id) ON DELETE CASCADE,
43
+ file TEXT NOT NULL,
44
+ original TEXT,
45
+ final TEXT,
46
+ PRIMARY KEY (note_id, file)
47
+ );`,
48
+ `ALTER TABLE notes ADD COLUMN tokens INTEGER NOT NULL DEFAULT 0;`,
49
+ `ALTER TABLE messages ADD COLUMN author TEXT;`,
50
+ `ALTER TABLE notes ADD COLUMN guest INTEGER NOT NULL DEFAULT 0;`,
51
+ ];
52
+ export function openDb(root) {
53
+ const dir = join(root, '.pinwright');
54
+ mkdirSync(join(dir, 'shots'), { recursive: true });
55
+ // Ignored even when the project's own .gitignore doesn't mention it.
56
+ if (!existsSync(join(dir, '.gitignore')))
57
+ writeFileSync(join(dir, '.gitignore'), '*\n');
58
+ const db = new DatabaseSync(join(dir, 'db.sqlite'));
59
+ db.exec('PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000; PRAGMA foreign_keys = ON;');
60
+ const { user_version } = db.prepare('PRAGMA user_version').get();
61
+ for (let v = user_version; v < MIGRATIONS.length; v++) {
62
+ db.exec('BEGIN');
63
+ try {
64
+ db.exec(MIGRATIONS[v]);
65
+ db.exec(`PRAGMA user_version = ${v + 1}`);
66
+ db.exec('COMMIT');
67
+ }
68
+ catch (e) {
69
+ db.exec('ROLLBACK');
70
+ throw e;
71
+ }
72
+ }
73
+ return db;
74
+ }
@@ -0,0 +1,26 @@
1
+ import type { CanUseTool, HookCallback } from '@anthropic-ai/claude-agent-sdk';
2
+ import type { Ctx } from './context.js';
3
+ export declare const EDIT_TOOLS: Set<string>;
4
+ export declare const NETWORK_TOOLS: string[];
5
+ export declare const READ_TOOLS: Set<string>;
6
+ /** Why a note may not edit this file, if it may not. */
7
+ export declare function editVerdict(rel: string, guest: boolean, guestDirs: string[]): string | null;
8
+ /** Why a read tool may not look there, if it may not. Reads stay inside the project; guests' notes skip secrets. */
9
+ export declare function readVerdict(root: string, input: Record<string, unknown>, guest: boolean): string | null;
10
+ /** A PreToolUse hook that keeps read-only tools (the planner's) inside the same limits. */
11
+ export declare function readHook(root: string, isGuest: () => boolean): HookCallback;
12
+ export declare function bashVerdict(cmd: string): string | null;
13
+ /** Path relative to root with forward slashes, or an error message. */
14
+ export declare function checkPath(root: string, p: string): {
15
+ rel: string;
16
+ abs: string;
17
+ } | {
18
+ error: string;
19
+ };
20
+ /**
21
+ * PreToolUse runs for every tool call, even the ones a project's settings auto-allow,
22
+ * so the path checks, the file locks and the undo record live here rather than in canUseTool.
23
+ */
24
+ export declare function guardHook(ctx: Ctx, noteId: string, beforeEdit: () => Promise<unknown>): HookCallback;
25
+ /** Whatever reaches the permission prompt already went through the hook: let it run. */
26
+ export declare const canUseTool: CanUseTool;
package/dist/guard.js ADDED
@@ -0,0 +1,137 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { isAbsolute, relative, resolve, sep } from 'node:path';
3
+ export const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']);
4
+ export const NETWORK_TOOLS = ['WebFetch', 'WebSearch'];
5
+ const FORBIDDEN_DIRS = new Set(['.git', 'node_modules', '.pinwright']);
6
+ const LOCK_WAIT_MS = 3 * 60_000;
7
+ export const READ_TOOLS = new Set(['Read', 'Glob', 'Grep', 'NotebookRead', 'LS']);
8
+ /**
9
+ * Files no note may change: what runs code on the next install, build or dev start (manifests, lockfiles,
10
+ * tool configs, scripts, CI) and secrets. A note about the page never needs them; a malicious one would.
11
+ */
12
+ const PROTECTED = [
13
+ /(^|\/)package\.json$/,
14
+ /(^|\/)(pnpm-lock\.yaml|package-lock\.json|yarn\.lock|bun\.lockb?|npm-shrinkwrap\.json)$/,
15
+ /(^|\/)\.(npmrc|yarnrc(\.yml)?|pnpmfile\.c?js|nvmrc|tool-versions)$/,
16
+ /(^|\/)[^/]*\.config\.(js|cjs|mjs|ts|cts|mts|json)$/,
17
+ /(^|\/)\.env(\.[^/]*)?$/,
18
+ /\.(sh|bash|zsh|ps1|bat|cmd)$/,
19
+ /(^|\/)(Makefile|Dockerfile[^/]*|docker-compose[^/]*|compose\.ya?ml|Procfile)$/,
20
+ /(^|\/)\.(github|husky|gitlab|circleci|vscode)\//,
21
+ /(^|\/)\.git(attributes|ignore|modules)$/,
22
+ /(^|\/)pinwright\.config\.[^/]+$/,
23
+ ];
24
+ /** Files a guest's note may not even read: they could be copied into the page everyone sees. */
25
+ const SECRET = /(^|\/)(\.env(\.[^/]*)?|\.npmrc|id_[a-z0-9]+|[^/]*\.(pem|key|p12|pfx|crt|keystore|jks)|credentials[^/]*|secrets?[^/]*)$/i;
26
+ /** Why a note may not edit this file, if it may not. */
27
+ export function editVerdict(rel, guest, guestDirs) {
28
+ if (PROTECTED.some((re) => re.test(rel)))
29
+ return `${rel} is protected (configs, manifests, scripts and secrets can't be changed from a note)`;
30
+ if (guest && !rel.split('/').slice(0, -1).some((d) => guestDirs.includes(d))) {
31
+ return `this note comes from a shared link: it may only change files under ${guestDirs.map((d) => `${d}/`).join(', ')}`;
32
+ }
33
+ return null;
34
+ }
35
+ /** Why a read tool may not look there, if it may not. Reads stay inside the project; guests' notes skip secrets. */
36
+ export function readVerdict(root, input, guest) {
37
+ const p = (input.file_path ?? input.notebook_path ?? input.path);
38
+ if (p) {
39
+ const abs = isAbsolute(p) ? p : resolve(root, p);
40
+ const rel = relative(root, abs);
41
+ if (rel.startsWith('..') || isAbsolute(rel))
42
+ return `${p} is outside the project`;
43
+ if (guest && SECRET.test(rel.split(sep).join('/')))
44
+ return `${p} may hold secrets: not readable for a note from a shared link`;
45
+ }
46
+ if (guest && typeof input.glob === 'string' && /\.env|\.pem|\.key|id_/.test(input.glob))
47
+ return 'secrets are not readable for a note from a shared link';
48
+ return null;
49
+ }
50
+ /** A PreToolUse hook that keeps read-only tools (the planner's) inside the same limits. */
51
+ export function readHook(root, isGuest) {
52
+ return async (input) => {
53
+ const { tool_name: name, tool_input } = input;
54
+ if (!READ_TOOLS.has(name))
55
+ return {};
56
+ const why = readVerdict(root, (tool_input ?? {}), isGuest());
57
+ return why ? deny(why) : {};
58
+ };
59
+ }
60
+ /** Shell commands the agents may not run: history rewrites, network, installs, file edits that bypass undo. */
61
+ const BASH_DENY = [
62
+ [/\bgit\s+(commit|push|reset|checkout|restore|stash|clean|rebase|merge|switch|cherry-pick|revert|am|tag|branch\s+-[dDmM])\b/, 'git history and branch commands are off limits'],
63
+ [/\b(curl|wget|ssh|scp|sftp|rsync|nc|ncat|telnet|ftp)\b/, 'no network access'],
64
+ [/\b(npm|pnpm|yarn|bun)\s+(i|install|add|remove|rm|uninstall|up|update|upgrade|publish|link)\b/, 'no package installs'],
65
+ [/\bsudo\b/, 'no sudo'],
66
+ [/\b(sed|perl)\s+(-\S*\s+)*-[a-zA-Z]*i/, 'edit files with Edit/Write so the reviewer can undo'],
67
+ [/(^|[;&|]\s*)(rm|mv|cp|tee|touch|truncate)\s/, 'change files with Edit/Write so the reviewer can undo'],
68
+ [/(^|[^0-9&>=-])>>?\s*(?!&|\/dev\/)[\w./~$'"-]/, 'no shell redirects into files: use Edit/Write so the reviewer can undo'],
69
+ ];
70
+ export function bashVerdict(cmd) {
71
+ for (const [re, why] of BASH_DENY)
72
+ if (re.test(cmd))
73
+ return why;
74
+ return null;
75
+ }
76
+ /** Path relative to root with forward slashes, or an error message. */
77
+ export function checkPath(root, p) {
78
+ if (typeof p !== 'string' || !p)
79
+ return { error: 'missing file path' };
80
+ const abs = isAbsolute(p) ? p : resolve(root, p);
81
+ const rel = relative(root, abs);
82
+ if (!rel || rel.startsWith('..') || isAbsolute(rel))
83
+ return { error: `${p} is outside the project root (${root})` };
84
+ const parts = rel.split(sep);
85
+ if (parts.some((s) => FORBIDDEN_DIRS.has(s)))
86
+ return { error: `${p} is inside .git, node_modules or .pinwright` };
87
+ return { rel: parts.join('/'), abs };
88
+ }
89
+ const deny = (reason) => ({
90
+ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: reason },
91
+ });
92
+ const allow = () => ({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow' } });
93
+ /**
94
+ * PreToolUse runs for every tool call, even the ones a project's settings auto-allow,
95
+ * so the path checks, the file locks and the undo record live here rather than in canUseTool.
96
+ */
97
+ export function guardHook(ctx, noteId, beforeEdit) {
98
+ const { cfg, store, locks, bus } = ctx;
99
+ return async (input, _id, { signal }) => {
100
+ const { tool_name: name, tool_input } = input;
101
+ const ti = (tool_input ?? {});
102
+ // Read at every call: a guest's reply turns a host's note into a guest note.
103
+ const guest = Boolean(store.get(noteId)?.guest);
104
+ if (READ_TOOLS.has(name)) {
105
+ const why = readVerdict(cfg.root, ti, guest);
106
+ return why ? deny(why) : {};
107
+ }
108
+ if (EDIT_TOOLS.has(name)) {
109
+ const checked = checkPath(cfg.root, (ti.file_path ?? ti.notebook_path));
110
+ if ('error' in checked)
111
+ return deny(checked.error);
112
+ const { rel, abs } = checked;
113
+ const refused = editVerdict(rel, guest, cfg.guestDirs);
114
+ if (refused)
115
+ return deny(`Not allowed: ${refused}.`);
116
+ const other = locks.holder(rel, noteId);
117
+ if (other)
118
+ bus.setActivity(noteId, `Waiting for ${rel} (busy with note ${other})`);
119
+ if (!(await locks.acquireOne(noteId, rel, LOCK_WAIT_MS, signal))) {
120
+ return deny(`${rel} is busy for another note. Try again later, or edit something else.`);
121
+ }
122
+ await beforeEdit();
123
+ if (!store.change(noteId, rel))
124
+ store.recordOriginal(noteId, rel, existsSync(abs) ? readFileSync(abs, 'utf8') : null);
125
+ return allow();
126
+ }
127
+ if (name === 'Bash') {
128
+ const why = bashVerdict(String(ti.command ?? ''));
129
+ return why ? deny(`Not allowed in pinwright: ${why}.`) : allow();
130
+ }
131
+ if (NETWORK_TOOLS.includes(name))
132
+ return deny('no network access');
133
+ return {};
134
+ };
135
+ }
136
+ /** Whatever reaches the permission prompt already went through the hook: let it run. */
137
+ export const canUseTool = async (name, input) => NETWORK_TOOLS.includes(name) ? { behavior: 'deny', message: 'no network access' } : { behavior: 'allow', updatedInput: input };
@@ -0,0 +1,15 @@
1
+ import { type Config, type Options } from './config.js';
2
+ export type { Config, Options } from './config.js';
3
+ export type { Note, Status } from './store.js';
4
+ export interface Pinwright {
5
+ /** Base URL of the daemon, e.g. http://127.0.0.1:4340 */
6
+ url: string;
7
+ /** Where the overlay script is served. */
8
+ scriptUrl: string;
9
+ config: Config;
10
+ /** Where screenshots load the site from (plugins call it once the dev server listens). */
11
+ setSiteUrl(url: string): void;
12
+ stop(): Promise<void>;
13
+ }
14
+ /** Starts the daemon: store, scheduler, HTTP server (API, SSE, overlay, and the proxy when there is a target). */
15
+ export declare function startPinwright(opts?: Options): Promise<Pinwright>;
package/dist/index.js ADDED
@@ -0,0 +1,70 @@
1
+ import { Bus } from './bus.js';
2
+ import { Collab } from './collab.js';
3
+ import { loadConfig } from './config.js';
4
+ import { openDb } from './db.js';
5
+ import { Locks } from './locks.js';
6
+ import { Ops } from './ops.js';
7
+ import { Rebuilder } from './rebuild.js';
8
+ import { Scheduler } from './scheduler.js';
9
+ import { createServer, SCRIPT_PATH } from './server.js';
10
+ import { Shooter } from './shots.js';
11
+ import { Store } from './store.js';
12
+ /** Starts the daemon: store, scheduler, HTTP server (API, SSE, overlay, and the proxy when there is a target). */
13
+ export async function startPinwright(opts = {}) {
14
+ const cfg = await loadConfig(opts);
15
+ const db = openDb(cfg.root);
16
+ const bus = new Bus();
17
+ bus.setMaxListeners(50);
18
+ const store = new Store(db, bus);
19
+ const ctx = { cfg, store, bus, locks: new Locks(cfg.root), shooter: new Shooter(cfg), rebuilder: new Rebuilder(cfg, bus) };
20
+ const scheduler = new Scheduler(ctx);
21
+ const ops = new Ops(ctx, scheduler);
22
+ const collab = new Collab(cfg);
23
+ const server = createServer(ctx, ops, scheduler, collab);
24
+ try {
25
+ await listen(server, cfg.port, cfg.host);
26
+ }
27
+ catch (e) {
28
+ db.close();
29
+ throw e;
30
+ }
31
+ scheduler.start();
32
+ const url = `http://${cfg.host.includes(':') ? `[${cfg.host}]` : cfg.host}:${cfg.port}`;
33
+ cfg.log(`listening on ${url}${cfg.target ? ` → ${cfg.target}` : ''} (root ${cfg.root}, ${cfg.maxAgents} agents, ${cfg.models.worker})`);
34
+ let stopped = null;
35
+ return {
36
+ url,
37
+ scriptUrl: url + SCRIPT_PATH,
38
+ config: cfg,
39
+ setSiteUrl(u) {
40
+ cfg.siteUrl = u.replace(/\/$/, '');
41
+ },
42
+ stop() {
43
+ stopped ??= (async () => {
44
+ collab.unshare();
45
+ await scheduler.stop();
46
+ await new Promise((ok) => {
47
+ server.close(() => ok());
48
+ server.closeAllConnections();
49
+ });
50
+ await ctx.shooter.close();
51
+ db.close();
52
+ })();
53
+ return stopped;
54
+ },
55
+ };
56
+ }
57
+ function listen(server, port, host) {
58
+ return new Promise((ok, fail) => {
59
+ const onErr = (e) => {
60
+ fail(e.code === 'EADDRINUSE' ? new Error(`port ${port} is busy: is pinwright already running? Set another with --port or \`port\` in the config.`) : e);
61
+ };
62
+ server.once('error', onErr);
63
+ server.listen(port, host, () => {
64
+ server.off('error', onErr);
65
+ // Once listening, a server error must never take the process down.
66
+ server.on('error', (e) => console.error('[pinwright] server error:', e));
67
+ ok();
68
+ });
69
+ });
70
+ }
@@ -0,0 +1,7 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ /**
3
+ * Wraps a response so that, if it turns out to be an HTML page, `tag` is inserted before `</body>` (or appended
4
+ * when there is none). Works with any framework that renders through Node's response, streaming included:
5
+ * chunks pass through as they come, only the one holding `</body>` is touched.
6
+ */
7
+ export declare function injectIntoHtml(req: IncomingMessage, res: ServerResponse, tag: string): void;
package/dist/inject.js ADDED
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Wraps a response so that, if it turns out to be an HTML page, `tag` is inserted before `</body>` (or appended
3
+ * when there is none). Works with any framework that renders through Node's response, streaming included:
4
+ * chunks pass through as they come, only the one holding `</body>` is touched.
5
+ */
6
+ export function injectIntoHtml(req, res, tag) {
7
+ if (req.method !== 'GET' || (req.headers['sec-fetch-dest'] && req.headers['sec-fetch-dest'] !== 'document'))
8
+ return;
9
+ const orig = { writeHead: res.writeHead, write: res.write, end: res.end };
10
+ let html = null;
11
+ let done = false;
12
+ const isHtml = () => {
13
+ if (html !== null)
14
+ return html;
15
+ const type = String(res.getHeader('content-type') ?? '');
16
+ html = res.statusCode >= 200 && res.statusCode < 300 && type.includes('text/html') && !res.getHeader('content-encoding');
17
+ if (html)
18
+ res.removeHeader('content-length');
19
+ return html;
20
+ };
21
+ const patch = (chunk, last) => {
22
+ if (done || chunk == null || typeof chunk === 'function')
23
+ return chunk;
24
+ const text = typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf8');
25
+ if (text.includes('data-pinwright')) {
26
+ done = true;
27
+ return chunk;
28
+ }
29
+ const i = text.lastIndexOf('</body>');
30
+ if (i >= 0) {
31
+ done = true;
32
+ return text.slice(0, i) + tag + text.slice(i);
33
+ }
34
+ if (last) {
35
+ done = true;
36
+ return text + tag;
37
+ }
38
+ return chunk;
39
+ };
40
+ res.writeHead = function (status, ...rest) {
41
+ // Fold the headers into the response first, so the content type can be read and content-length dropped.
42
+ const headers = rest.find((r) => r && typeof r === 'object');
43
+ const message = rest.find((r) => typeof r === 'string');
44
+ if (Array.isArray(headers)) {
45
+ const pairs = headers.length && Array.isArray(headers[0]) ? headers : chunkPairs(headers);
46
+ const merged = new Map();
47
+ for (const [k, v] of pairs)
48
+ merged.set(k, [...(merged.get(k) ?? []), String(v)]);
49
+ for (const [k, v] of merged)
50
+ res.setHeader(k, v.length === 1 ? v[0] : v);
51
+ }
52
+ else if (headers) {
53
+ for (const [k, v] of Object.entries(headers))
54
+ if (v !== undefined)
55
+ res.setHeader(k, v);
56
+ }
57
+ res.statusCode = status;
58
+ isHtml();
59
+ return message ? orig.writeHead.call(this, status, message) : orig.writeHead.call(this, status);
60
+ };
61
+ res.write = function (chunk, ...rest) {
62
+ if (isHtml())
63
+ chunk = patch(chunk, false);
64
+ return orig.write.call(this, chunk, ...rest);
65
+ };
66
+ res.end = function (chunk, ...rest) {
67
+ if (isHtml() && !done) {
68
+ if (typeof chunk === 'function') {
69
+ rest.unshift(chunk);
70
+ chunk = undefined;
71
+ }
72
+ chunk = patch(chunk ?? '', true);
73
+ }
74
+ return orig.end.call(this, chunk, ...rest);
75
+ };
76
+ }
77
+ function chunkPairs(flat) {
78
+ const out = [];
79
+ for (let i = 0; i + 1 < flat.length; i += 2)
80
+ out.push([flat[i], flat[i + 1]]);
81
+ return out;
82
+ }
@@ -0,0 +1,14 @@
1
+ /** Which note holds which file (or directory). Paths are relative to root, with forward slashes. */
2
+ export declare class Locks {
3
+ private root;
4
+ private held;
5
+ constructor(root: string);
6
+ norm(p: string): string;
7
+ holder(file: string, except?: string): string | undefined;
8
+ /** All or nothing: takes every path, or none if any overlaps another note's. */
9
+ tryAcquire(noteId: string, files: string[]): boolean;
10
+ /** Waits for one path, polling, until the timeout or the signal. */
11
+ acquireOne(noteId: string, file: string, timeoutMs: number, signal?: AbortSignal): Promise<boolean>;
12
+ releaseAll(noteId: string): void;
13
+ snapshot(): Record<string, string>;
14
+ }
package/dist/locks.js ADDED
@@ -0,0 +1,51 @@
1
+ import { isAbsolute, relative, resolve, sep } from 'node:path';
2
+ /** Two paths overlap when equal or when one is a directory prefix of the other. */
3
+ const overlaps = (a, b) => a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`) || a === '' || b === '';
4
+ /** Which note holds which file (or directory). Paths are relative to root, with forward slashes. */
5
+ export class Locks {
6
+ root;
7
+ held = new Map();
8
+ constructor(root) {
9
+ this.root = root;
10
+ }
11
+ norm(p) {
12
+ const abs = isAbsolute(p) ? p : resolve(this.root, p);
13
+ return relative(this.root, abs).split(sep).join('/').replace(/\/$/, '');
14
+ }
15
+ holder(file, except) {
16
+ const f = this.norm(file);
17
+ for (const [k, owner] of this.held)
18
+ if (owner !== except && overlaps(k, f))
19
+ return owner;
20
+ return undefined;
21
+ }
22
+ /** All or nothing: takes every path, or none if any overlaps another note's. */
23
+ tryAcquire(noteId, files) {
24
+ const fs = files.map((f) => this.norm(f)).filter((f) => !f.startsWith('..'));
25
+ if (fs.some((f) => this.holder(f, noteId)))
26
+ return false;
27
+ for (const f of fs)
28
+ this.held.set(f, noteId);
29
+ return true;
30
+ }
31
+ /** Waits for one path, polling, until the timeout or the signal. */
32
+ async acquireOne(noteId, file, timeoutMs, signal) {
33
+ const end = Date.now() + timeoutMs;
34
+ while (!signal?.aborted) {
35
+ if (this.tryAcquire(noteId, [file]))
36
+ return true;
37
+ if (Date.now() > end)
38
+ return false;
39
+ await new Promise((r) => setTimeout(r, 500));
40
+ }
41
+ return false;
42
+ }
43
+ releaseAll(noteId) {
44
+ for (const [k, owner] of this.held)
45
+ if (owner === noteId)
46
+ this.held.delete(k);
47
+ }
48
+ snapshot() {
49
+ return Object.fromEntries(this.held);
50
+ }
51
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Loads the pinwright overlay in `next dev`; renders nothing anywhere else.
3
+ * Put it in the root layout's <body> (app router) or in pages/_document (pages router).
4
+ */
5
+ export declare function Pinwright(): any;
6
+ export default Pinwright;
@@ -0,0 +1,12 @@
1
+ import { createElement } from 'react';
2
+ /**
3
+ * Loads the pinwright overlay in `next dev`; renders nothing anywhere else.
4
+ * Put it in the root layout's <body> (app router) or in pages/_document (pages router).
5
+ */
6
+ export function Pinwright() {
7
+ const src = process.env.PINWRIGHT_SRC;
8
+ if (!src)
9
+ return null;
10
+ return createElement('script', { src, defer: true, 'data-pinwright': '' });
11
+ }
12
+ export default Pinwright;
package/dist/next.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ import type { Options } from './index.js';
2
+ type ConfigInput<C> = C | ((phase: string, ctx: any) => C | Promise<C>);
3
+ /**
4
+ * Next.js: wrap the config, then render `<Pinwright />` (from `pinwright/next/script`) in the root layout.
5
+ * In `next dev` this starts pinwright and tells the component where the overlay lives; in builds it does nothing.
6
+ *
7
+ * export default withPinwright(nextConfig)
8
+ */
9
+ export declare function withPinwright<C extends object>(config?: ConfigInput<C>, opts?: Options): (phase: string, ctx: any) => Promise<C>;
10
+ export default withPinwright;
package/dist/next.js ADDED
@@ -0,0 +1,28 @@
1
+ import { tryDaemon } from './plugin.js';
2
+ /**
3
+ * Next.js: wrap the config, then render `<Pinwright />` (from `pinwright/next/script`) in the root layout.
4
+ * In `next dev` this starts pinwright and tells the component where the overlay lives; in builds it does nothing.
5
+ *
6
+ * export default withPinwright(nextConfig)
7
+ */
8
+ export function withPinwright(config = {}, opts = {}) {
9
+ return async (phase, ctx) => {
10
+ const base = typeof config === 'function' ? await config(phase, ctx) : config;
11
+ if (phase !== 'phase-development-server')
12
+ return base;
13
+ // next dev also loads the config in a detached telemetry process that outlives the server: no daemon there.
14
+ if (process.argv.some((a) => a.includes('telemetry')))
15
+ return base;
16
+ // Next loads its config in more than one process; children inherit the env, so only the first starts the daemon.
17
+ let src = process.env.PINWRIGHT_SRC;
18
+ if (!src) {
19
+ const pw = await tryDaemon(opts);
20
+ if (!pw)
21
+ return base;
22
+ src = process.env.PINWRIGHT_SRC = pw.scriptUrl;
23
+ }
24
+ const env = base.env;
25
+ return { ...base, env: { ...env, PINWRIGHT_SRC: src } };
26
+ };
27
+ }
28
+ export default withPinwright;
package/dist/nuxt.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ import type { Options } from './index.js';
2
+ interface Nuxt {
3
+ options: {
4
+ dev: boolean;
5
+ app: {
6
+ head: {
7
+ script?: Record<string, unknown>[];
8
+ };
9
+ };
10
+ };
11
+ hook(name: 'close', fn: () => void): void;
12
+ }
13
+ /**
14
+ * Nuxt module: in `nuxt dev`, starts pinwright and adds the overlay to every page's head.
15
+ * `modules: [['pinwright/nuxt', { ...options }]]`
16
+ */
17
+ export default function pinwright(inline: Options | undefined, nuxt: Nuxt): Promise<void>;
18
+ export {};
package/dist/nuxt.js ADDED
@@ -0,0 +1,17 @@
1
+ import { releaseDaemon, tryDaemon } from './plugin.js';
2
+ /**
3
+ * Nuxt module: in `nuxt dev`, starts pinwright and adds the overlay to every page's head.
4
+ * `modules: [['pinwright/nuxt', { ...options }]]`
5
+ */
6
+ export default async function pinwright(inline = {}, nuxt) {
7
+ if (!nuxt.options.dev)
8
+ return;
9
+ const pw = await tryDaemon(inline ?? {});
10
+ if (!pw)
11
+ return;
12
+ const head = nuxt.options.app.head;
13
+ head.script = [...(head.script ?? []), { src: pw.scriptUrl, defer: true, 'data-pinwright': '', tagPosition: 'bodyClose' }];
14
+ nuxt.hook('close', releaseDaemon);
15
+ }
16
+ // Read by Nuxt to name the module and its config key.
17
+ Object.assign(pinwright, { getMeta: async () => ({ name: 'pinwright', configKey: 'pinwright' }), getOptions: async (inline) => inline ?? {} });
package/dist/ops.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ import type { Ctx } from './context.js';
2
+ import type { Scheduler } from './scheduler.js';
3
+ import type { Note } from './store.js';
4
+ export declare class OpError extends Error {
5
+ code: number;
6
+ data?: unknown;
7
+ constructor(message: string, code?: number, data?: unknown);
8
+ }
9
+ /** What reviewers (overlay) and the CLI can do to a note. */
10
+ export declare class Ops {
11
+ private ctx;
12
+ private scheduler;
13
+ constructor(ctx: Ctx, scheduler: Scheduler);
14
+ private must;
15
+ /**
16
+ * An answer to a question, or a follow-up on a finished note: either way the same session resumes.
17
+ * `approved: false` (a guest of the review link) holds it until the host approves.
18
+ */
19
+ reply(id: string, text: string, author?: string | null, approved?: boolean, guest?: boolean): Note;
20
+ /** Lets a note from the review link go to the agents. */
21
+ approve(id: string): Note;
22
+ archive(id: string): Note;
23
+ retry(id: string, approved?: boolean): Note;
24
+ handoff(id: string): Note;
25
+ delete(id: string): void;
26
+ /**
27
+ * Restores what the note changed. A file nobody touched since goes back to its original; a file
28
+ * another edit changed since gets the note's patch reversed on top, and if that doesn't apply
29
+ * cleanly the whole undo is refused, listing the files.
30
+ */
31
+ undo(id: string): Promise<Note>;
32
+ /** Pulls a note into an interactive Claude Code session: marks it taken and returns a ready prompt. */
33
+ take(id: string): {
34
+ note: Note;
35
+ prompt: string;
36
+ };
37
+ /** Closes a note handled by hand (after `take`). */
38
+ markDone(id: string, summary?: string): Note;
39
+ }