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/cli.js ADDED
@@ -0,0 +1,125 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from 'node:util';
3
+ import { loadConfig } from './config.js';
4
+ import { startPinwright } from './index.js';
5
+ const HELP = `pinwright: give Claude feedback right on your dev site; agents fix the code.
6
+
7
+ Usage:
8
+ pinwright [start] --target http://localhost:4330 proxy the site and run the daemon
9
+ pinwright list [--all] notes in the running daemon
10
+ pinwright take <id> take a note into this session (prints a prompt)
11
+ pinwright done <id> [summary] close a note you handled by hand
12
+ pinwright reply <id> <text> answer a question / follow up on a note
13
+
14
+ Options:
15
+ --target <url> site to proxy (proxy mode)
16
+ --port <n> daemon port (default 4340)
17
+ --root <dir> project root (default: cwd)
18
+ --rebuild <cmd> command to run after edits (proxy mode, no HMR)
19
+ --agents <n> max parallel agents (default 3)
20
+ --model <name> worker model (default sonnet)
21
+ --config <file> config file (default pinwright.config.{mjs,js,json})
22
+ --api-key let ANTHROPIC_API_KEY through (default: use \`claude login\`)
23
+ `;
24
+ const { values: v, positionals } = parseArgs({
25
+ allowPositionals: true,
26
+ options: {
27
+ target: { type: 'string' },
28
+ port: { type: 'string' },
29
+ root: { type: 'string' },
30
+ rebuild: { type: 'string' },
31
+ agents: { type: 'string' },
32
+ model: { type: 'string' },
33
+ config: { type: 'string' },
34
+ 'api-key': { type: 'boolean' },
35
+ all: { type: 'boolean' },
36
+ help: { type: 'boolean', short: 'h' },
37
+ },
38
+ });
39
+ const [cmd = 'start', ...rest] = positionals;
40
+ const num = (s) => (s === undefined ? undefined : Number(s));
41
+ async function main() {
42
+ if (v.help || cmd === 'help')
43
+ return void process.stdout.write(HELP);
44
+ if (cmd === 'start')
45
+ return start();
46
+ const cfg = await loadConfig({ root: v.root, port: num(v.port), config: v.config, log: () => { } });
47
+ const base = `http://127.0.0.1:${cfg.port}/__pw`;
48
+ const call = async (path, init) => {
49
+ let r;
50
+ try {
51
+ r = await fetch(base + path, { ...init, headers: { 'content-type': 'application/json' } });
52
+ }
53
+ catch {
54
+ throw new Error(`pinwright is not running on port ${cfg.port}. Start it with \`pinwright --target …\` or your dev server.`);
55
+ }
56
+ const body = await r.json();
57
+ if (!r.ok)
58
+ throw new Error(body.error ?? r.statusText);
59
+ return body;
60
+ };
61
+ const post = (path, body = {}) => call(path, { method: 'POST', body: JSON.stringify(body) });
62
+ const need = (what) => {
63
+ if (!rest[0])
64
+ throw new Error(`usage: pinwright ${cmd} <id>${what}`);
65
+ return rest[0];
66
+ };
67
+ switch (cmd) {
68
+ case 'list': {
69
+ const notes = (await call(`/notes${v.all ? '?all=1' : ''}`));
70
+ if (!notes.length)
71
+ return console.log('No notes.');
72
+ for (const n of notes)
73
+ console.log(`${n.id} ${n.status.padEnd(8)} ${n.page} ${n.text.split('\n')[0].slice(0, 70)}`);
74
+ return;
75
+ }
76
+ case 'take': {
77
+ const { prompt } = (await post(`/notes/${need('')}/take`));
78
+ return void process.stdout.write(`${prompt}\n`);
79
+ }
80
+ case 'done':
81
+ await post(`/notes/${need(' [summary]')}/done`, { summary: rest.slice(1).join(' ') });
82
+ return console.log('Done.');
83
+ case 'reply':
84
+ if (!rest[1])
85
+ throw new Error('usage: pinwright reply <id> <text>');
86
+ await post(`/notes/${rest[0]}/reply`, { text: rest.slice(1).join(' ') });
87
+ return console.log('Sent: the note is back in the queue.');
88
+ default:
89
+ throw new Error(`unknown command ${cmd}\n\n${HELP}`);
90
+ }
91
+ }
92
+ async function start() {
93
+ // Standalone: the daemon owns the process, so nothing may take it down.
94
+ process.on('uncaughtException', (e) => console.error('[pinwright] uncaught:', e));
95
+ process.on('unhandledRejection', (e) => console.error('[pinwright] unhandled rejection:', e));
96
+ const pw = await startPinwright({
97
+ mode: 'cli',
98
+ root: v.root,
99
+ target: v.target,
100
+ port: num(v.port),
101
+ rebuild: v.rebuild,
102
+ maxAgents: num(v.agents),
103
+ models: v.model ? { worker: v.model } : undefined,
104
+ config: v.config,
105
+ useApiKey: v['api-key'] || undefined,
106
+ });
107
+ if (pw.config.target)
108
+ console.log(`[pinwright] open ${pw.url}/ to review`);
109
+ else
110
+ console.log(`[pinwright] no target: add <script src="${pw.scriptUrl}" defer></script> to your pages, or use pinwright/vite or pinwright/astro`);
111
+ let quitting = false;
112
+ const quit = () => {
113
+ if (quitting)
114
+ process.exit(1);
115
+ quitting = true;
116
+ console.log('\n[pinwright] stopping…');
117
+ pw.stop().finally(() => process.exit(0));
118
+ };
119
+ process.on('SIGINT', quit);
120
+ process.on('SIGTERM', quit);
121
+ }
122
+ main().catch((e) => {
123
+ console.error(`pinwright: ${e.message}`);
124
+ process.exit(1);
125
+ });
@@ -0,0 +1,10 @@
1
+ export declare const defaultCacheDir: () => string;
2
+ /**
3
+ * Finds cloudflared: the configured path, then the PATH, then our cache. If none, downloads the official
4
+ * build from Cloudflare's GitHub releases into the cache, once per machine.
5
+ */
6
+ export declare function resolveCloudflared(opts: {
7
+ configured?: string;
8
+ cacheDir?: string;
9
+ log: (m: string) => void;
10
+ }): Promise<string>;
@@ -0,0 +1,98 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { accessSync, chmodSync, constants, existsSync, mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { delimiter, join } from 'node:path';
5
+ import { promisify } from 'node:util';
6
+ const run = promisify(execFile);
7
+ const RELEASES = 'https://github.com/cloudflare/cloudflared/releases/latest/download';
8
+ /** Cloudflare's Apple developer team: macOS builds must be signed by it. */
9
+ const CLOUDFLARE_TEAM = '68WVV388M8';
10
+ /** The release asset for this machine, and whether it comes as a .tgz (macOS) or as the bare binary. */
11
+ function asset() {
12
+ const arch = process.arch === 'arm64' ? 'arm64' : process.arch === 'x64' ? 'amd64' : null;
13
+ if (!arch)
14
+ throw new Error(`no cloudflared build for ${process.arch}: install it yourself`);
15
+ if (process.platform === 'darwin')
16
+ return { name: `cloudflared-darwin-${arch}.tgz`, tgz: true };
17
+ if (process.platform === 'linux')
18
+ return { name: `cloudflared-linux-${arch}`, tgz: false };
19
+ if (process.platform === 'win32' && arch === 'amd64')
20
+ return { name: 'cloudflared-windows-amd64.exe', tgz: false };
21
+ throw new Error(`no cloudflared build for ${process.platform}-${process.arch}: install it yourself`);
22
+ }
23
+ const exe = process.platform === 'win32' ? 'cloudflared.exe' : 'cloudflared';
24
+ function onPath() {
25
+ for (const dir of (process.env.PATH ?? '').split(delimiter)) {
26
+ if (!dir)
27
+ continue;
28
+ const p = join(dir, exe);
29
+ try {
30
+ accessSync(p, constants.X_OK);
31
+ return p;
32
+ }
33
+ catch { }
34
+ }
35
+ return null;
36
+ }
37
+ export const defaultCacheDir = () => join(process.env.XDG_CACHE_HOME || join(homedir(), '.cache'), 'pinwright');
38
+ let pending = null;
39
+ /**
40
+ * Finds cloudflared: the configured path, then the PATH, then our cache. If none, downloads the official
41
+ * build from Cloudflare's GitHub releases into the cache, once per machine.
42
+ */
43
+ export function resolveCloudflared(opts) {
44
+ if (opts.configured)
45
+ return Promise.resolve(opts.configured);
46
+ const found = onPath();
47
+ if (found)
48
+ return Promise.resolve(found);
49
+ const dir = opts.cacheDir ?? defaultCacheDir();
50
+ const bin = join(dir, exe);
51
+ if (existsSync(bin))
52
+ return Promise.resolve(bin);
53
+ pending ??= download(dir, bin, opts.log).finally(() => (pending = null));
54
+ return pending;
55
+ }
56
+ async function download(dir, bin, log) {
57
+ const { name, tgz } = asset();
58
+ log(`cloudflared not found: downloading ${name} from Cloudflare's GitHub releases (first share only)…`);
59
+ mkdirSync(dir, { recursive: true });
60
+ const r = await fetch(`${RELEASES}/${name}`, { redirect: 'follow' });
61
+ if (!r.ok)
62
+ throw new Error(`cloudflared download failed: HTTP ${r.status}`);
63
+ const data = Buffer.from(await r.arrayBuffer());
64
+ const tmp = join(dir, `.${name}.${process.pid}`);
65
+ writeFileSync(tmp, data);
66
+ try {
67
+ if (tgz) {
68
+ const out = join(dir, `.extract.${process.pid}`);
69
+ mkdirSync(out, { recursive: true });
70
+ await run('tar', ['-xzf', tmp, '-C', out]);
71
+ renameSync(join(out, exe), bin);
72
+ rmSync(out, { recursive: true, force: true });
73
+ }
74
+ else {
75
+ renameSync(tmp, bin);
76
+ }
77
+ }
78
+ finally {
79
+ rmSync(tmp, { force: true });
80
+ }
81
+ chmodSync(bin, 0o755);
82
+ // A broken or foreign download must not stay in the cache.
83
+ try {
84
+ if (process.platform === 'darwin') {
85
+ await run('codesign', ['--verify', bin]);
86
+ const { stderr } = await run('codesign', ['-dv', bin]);
87
+ if (!stderr.includes(`TeamIdentifier=${CLOUDFLARE_TEAM}`))
88
+ throw new Error('not signed by Cloudflare');
89
+ }
90
+ const { stdout } = await run(bin, ['--version']);
91
+ log(`cloudflared ready: ${stdout.trim().split('\n')[0]} (${bin})`);
92
+ }
93
+ catch (e) {
94
+ rmSync(bin, { force: true });
95
+ throw new Error(`downloaded cloudflared rejected: ${e.message}`);
96
+ }
97
+ return bin;
98
+ }
@@ -0,0 +1,56 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ import type { Config } from './config.js';
3
+ export declare const MAX_PEOPLE = 8;
4
+ /**
5
+ * Who is asking: the host (this machine), or a guest from one of the two shared links. Notes from the
6
+ * `auto` link go straight to the agents; notes and replies from the `review` link wait for the host.
7
+ */
8
+ export type Access = 'host' | 'auto' | 'review';
9
+ export declare const LINK_KINDS: readonly ['auto', 'review'];
10
+ export interface Peer {
11
+ id: string;
12
+ name: string;
13
+ color: string;
14
+ guest: boolean;
15
+ page: string | null;
16
+ }
17
+ /** Whether a request reached the daemon from outside this machine (through the tunnel, or another host). */
18
+ export declare function isRemote(req: IncomingMessage): boolean;
19
+ /**
20
+ * Live sessions: who is here (max 8, each with a made-up name and a colour), and the shared link,
21
+ * which is a cloudflared quick tunnel to the daemon plus a secret token.
22
+ */
23
+ export declare class Collab {
24
+ private cfg;
25
+ peers: Map<string, Peer>;
26
+ /** Names stay with a browser tab for the daemon's lifetime, across reloads. */
27
+ private known;
28
+ private leaving;
29
+ private tokens;
30
+ private tunnel;
31
+ url: string | null;
32
+ constructor(cfg: Config);
33
+ get sharing(): boolean;
34
+ /** Which link a token belongs to, if any. */
35
+ private kindOf;
36
+ /** A remote request may pass only with a share token (from the link, then from its cookie). */
37
+ authorized(req: IncomingMessage, query: URLSearchParams): 'ok' | 'set-cookie' | 'denied';
38
+ /** What the request may do: the host, or a guest of the link its cookie came from. Null: no valid token. */
39
+ access(req: IncomingMessage): Access | null;
40
+ /** The cookie for the token in the link (the request was just `authorized` as 'set-cookie'). */
41
+ cookie(req: IncomingMessage, token: string): string;
42
+ /** Joins (or rejoins after a reload). Null when the session is full. `name`: the one the person chose before. */
43
+ join(id: string, guest: boolean, page: string | null, name?: string | null): Peer | null;
44
+ /** Sets the name a person chose. False if it's empty or someone else here has it. */
45
+ rename(id: string, raw: string): boolean;
46
+ /** Leaves after a short grace, so a reload doesn't look like someone left and came back. */
47
+ leave(id: string, onGone: () => void): void;
48
+ list(): Peer[];
49
+ /** Opens the tunnel (once) and returns the public base URL; the caller adds the page and a token. */
50
+ share(): Promise<{
51
+ url: string;
52
+ tokens: Record<'auto' | 'review', string>;
53
+ }>;
54
+ /** Closes the tunnel and voids both links: the next share gets new tokens. */
55
+ unshare(): void;
56
+ }
package/dist/collab.js ADDED
@@ -0,0 +1,183 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { randomBytes, timingSafeEqual } from 'node:crypto';
3
+ import { resolveCloudflared } from './cloudflared.js';
4
+ export const MAX_PEOPLE = 8;
5
+ const COLORS = ['#2563eb', '#16a34a', '#f59e0b', '#db2777', '#7c3aed', '#0891b2', '#ea580c', '#65a30d'];
6
+ const ANIMALS = {
7
+ it: ['Volpe', 'Gufo', 'Lontra', 'Panda', 'Koala', 'Riccio', 'Lince', 'Polpo', 'Bradipo', 'Tucano', 'Delfino', 'Fenicottero', 'Procione', 'Capibara'],
8
+ en: ['Fox', 'Owl', 'Otter', 'Panda', 'Koala', 'Hedgehog', 'Lynx', 'Octopus', 'Sloth', 'Toucan', 'Dolphin', 'Flamingo', 'Raccoon', 'Capybara'],
9
+ };
10
+ const TRAITS = ['Ninja', 'Turbo', 'Pixel', 'Laser', 'Disco', 'Zen', 'Jazz', 'Neon', 'Cosmo', 'Razzo', 'Funky', 'Groove'];
11
+ const pick = (xs) => xs[Math.floor(Math.random() * xs.length)];
12
+ export const LINK_KINDS = ['auto', 'review'];
13
+ /** Whether a request reached the daemon from outside this machine (through the tunnel, or another host). */
14
+ export function isRemote(req) {
15
+ const a = req.socket.remoteAddress ?? '';
16
+ const loopback = a === '127.0.0.1' || a === '::1' || a === '::ffff:127.0.0.1';
17
+ // cloudflared connects from localhost but marks the real client.
18
+ return !loopback || Boolean(req.headers['cf-connecting-ip'] || req.headers['x-forwarded-for']);
19
+ }
20
+ const readCookie = (req, name) => (req.headers.cookie ?? '')
21
+ .split(';')
22
+ .map((c) => c.trim().split('='))
23
+ .find(([k]) => k === name)?.[1];
24
+ /**
25
+ * Live sessions: who is here (max 8, each with a made-up name and a colour), and the shared link,
26
+ * which is a cloudflared quick tunnel to the daemon plus a secret token.
27
+ */
28
+ export class Collab {
29
+ cfg;
30
+ peers = new Map();
31
+ /** Names stay with a browser tab for the daemon's lifetime, across reloads. */
32
+ known = new Map();
33
+ leaving = new Map();
34
+ tokens = null;
35
+ tunnel = null;
36
+ url = null;
37
+ constructor(cfg) {
38
+ this.cfg = cfg;
39
+ }
40
+ get sharing() {
41
+ return Boolean(this.tokens && this.url);
42
+ }
43
+ /** Which link a token belongs to, if any. */
44
+ kindOf(t) {
45
+ if (!t || !this.tokens)
46
+ return null;
47
+ const a = Buffer.from(t);
48
+ for (const k of LINK_KINDS) {
49
+ const b = Buffer.from(this.tokens[k]);
50
+ if (a.length === b.length && timingSafeEqual(a, b))
51
+ return k;
52
+ }
53
+ return null;
54
+ }
55
+ /** A remote request may pass only with a share token (from the link, then from its cookie). */
56
+ authorized(req, query) {
57
+ if (!isRemote(req))
58
+ return 'ok';
59
+ if (this.kindOf(query.get('pw')))
60
+ return 'set-cookie';
61
+ return this.kindOf(readCookie(req, 'pw_t')) ? 'ok' : 'denied';
62
+ }
63
+ /** What the request may do: the host, or a guest of the link its cookie came from. Null: no valid token. */
64
+ access(req) {
65
+ if (!isRemote(req))
66
+ return 'host';
67
+ return this.kindOf(readCookie(req, 'pw_t'));
68
+ }
69
+ /** The cookie for the token in the link (the request was just `authorized` as 'set-cookie'). */
70
+ cookie(req, token) {
71
+ const https = req.headers['x-forwarded-proto'] === 'https' || Boolean(req.headers['cf-connecting-ip']);
72
+ return `pw_t=${token}; Path=/; HttpOnly; SameSite=Lax${https ? '; Secure' : ''}`;
73
+ }
74
+ /** Joins (or rejoins after a reload). Null when the session is full. `name`: the one the person chose before. */
75
+ join(id, guest, page, name) {
76
+ const pending = this.leaving.get(id);
77
+ if (pending)
78
+ clearTimeout(pending);
79
+ this.leaving.delete(id);
80
+ const existing = this.peers.get(id);
81
+ if (existing)
82
+ return Object.assign(existing, { page });
83
+ if (this.peers.size >= MAX_PEOPLE)
84
+ return null;
85
+ let who = this.known.get(id);
86
+ if (!who) {
87
+ const taken = new Set([...this.peers.values()].map((p) => p.name));
88
+ const used = new Set([...this.peers.values()].map((p) => p.color));
89
+ const lang = this.cfg.lang.startsWith('it') ? 'it' : 'en';
90
+ let name = '';
91
+ for (let i = 0; i < 50 && (!name || taken.has(name)); i++) {
92
+ const a = pick(ANIMALS[lang]);
93
+ const t = pick(TRAITS);
94
+ name = lang === 'it' ? `${a} ${t}` : `${t} ${a}`;
95
+ }
96
+ who = { name, color: COLORS.find((c) => !used.has(c)) ?? pick(COLORS) };
97
+ this.known.set(id, who);
98
+ }
99
+ const peer = { id, ...who, guest, page };
100
+ this.peers.set(id, peer);
101
+ if (name)
102
+ this.rename(id, name);
103
+ return peer;
104
+ }
105
+ /** Sets the name a person chose. False if it's empty or someone else here has it. */
106
+ rename(id, raw) {
107
+ const peer = this.peers.get(id);
108
+ const name = raw.replace(/\s+/g, ' ').trim().slice(0, 30);
109
+ if (!peer || !name)
110
+ return false;
111
+ if ([...this.peers.values()].some((p) => p.id !== id && p.name.toLowerCase() === name.toLowerCase()))
112
+ return false;
113
+ peer.name = name;
114
+ this.known.set(id, { name, color: peer.color });
115
+ return true;
116
+ }
117
+ /** Leaves after a short grace, so a reload doesn't look like someone left and came back. */
118
+ leave(id, onGone) {
119
+ this.leaving.set(id, setTimeout(() => {
120
+ this.leaving.delete(id);
121
+ if (this.peers.delete(id))
122
+ onGone();
123
+ }, 4000));
124
+ }
125
+ list() {
126
+ return [...this.peers.values()];
127
+ }
128
+ /** Opens the tunnel (once) and returns the public base URL; the caller adds the page and a token. */
129
+ async share() {
130
+ const tok = () => randomBytes(18).toString('base64url');
131
+ this.tokens ??= { auto: tok(), review: tok() };
132
+ const tokens = this.tokens;
133
+ if (this.url && this.tunnel && this.tunnel.exitCode === null)
134
+ return { url: this.url, tokens };
135
+ const bin = await resolveCloudflared({ configured: this.cfg.cloudflared, log: this.cfg.log });
136
+ this.url = await new Promise((ok, fail) => {
137
+ let out = '';
138
+ let p;
139
+ try {
140
+ p = spawn(bin, ['tunnel', '--no-autoupdate', '--url', `http://127.0.0.1:${this.cfg.port}`], { stdio: ['ignore', 'pipe', 'pipe'] });
141
+ }
142
+ catch (e) {
143
+ return fail(e);
144
+ }
145
+ this.tunnel = p;
146
+ const timer = setTimeout(() => fail(new Error('cloudflared did not give a URL within 30 s')), 30_000);
147
+ const read = (b) => {
148
+ out = (out + b.toString()).slice(-4000);
149
+ const m = out.match(/https:\/\/[a-z0-9-]+\.trycloudflare\.com/);
150
+ if (m) {
151
+ clearTimeout(timer);
152
+ ok(m[0]);
153
+ }
154
+ };
155
+ p.stdout?.on('data', read);
156
+ p.stderr?.on('data', read);
157
+ p.on('error', (e) => {
158
+ clearTimeout(timer);
159
+ fail(e.code === 'ENOENT' ? new Error(`cloudflared not found at ${bin}`) : e);
160
+ });
161
+ p.on('exit', () => {
162
+ clearTimeout(timer);
163
+ if (this.tunnel === p) {
164
+ this.tunnel = null;
165
+ this.url = null;
166
+ }
167
+ fail(new Error(`cloudflared exited: ${out.split('\n').slice(-3).join(' ')}`));
168
+ });
169
+ });
170
+ this.cfg.log(`sharing at ${this.url}`);
171
+ return { url: this.url, tokens };
172
+ }
173
+ /** Closes the tunnel and voids both links: the next share gets new tokens. */
174
+ unshare() {
175
+ if (!this.tokens && !this.tunnel)
176
+ return;
177
+ this.tunnel?.kill('SIGTERM');
178
+ this.tunnel = null;
179
+ this.url = null;
180
+ this.tokens = null;
181
+ this.cfg.log('sharing stopped');
182
+ }
183
+ }
@@ -0,0 +1,53 @@
1
+ export interface Viewport {
2
+ name: string;
3
+ width: number;
4
+ height: number;
5
+ }
6
+ export interface Config {
7
+ /** Project root: the agents' working directory and the only place they may edit. */
8
+ root: string;
9
+ /** Proxy mode: the site to put the overlay in front of. */
10
+ target?: string;
11
+ /** Where the site itself is reachable, for screenshots. Defaults to `target`; plugins set it from the dev server. */
12
+ siteUrl?: string;
13
+ port: number;
14
+ host: string;
15
+ /** Shell command run in `root` after edits, when the target has no HMR (proxy mode). */
16
+ rebuild?: string;
17
+ /** Rebuild right after every edit, so the reviewer sees changes while the agent works. */
18
+ rebuildOnEdit: boolean;
19
+ /** Let the agent ask the reviewer when a note is ambiguous. Off: it picks the likeliest reading and says so. */
20
+ ask: boolean;
21
+ maxAgents: number;
22
+ models: {
23
+ planner: string;
24
+ worker: string;
25
+ };
26
+ viewports: Viewport[];
27
+ maxTurns: number;
28
+ timeoutMin: number;
29
+ lang: string;
30
+ /** Extra text appended to the worker's system prompt. */
31
+ instructions: string;
32
+ /** Let ANTHROPIC_API_KEY through to the agents. Off by default: they use the `claude login` session. */
33
+ useApiKey: boolean;
34
+ /** Before/after thumbnails in the panel (Playwright + Chrome). Off by default: the reviewer sees changes live. */
35
+ shots: boolean;
36
+ /**
37
+ * Notes from a shared link may only edit files under a directory with one of these names
38
+ * (anywhere in the path: `src`, `apps/web/src`…). Config files, scripts and secrets stay off limits for every note.
39
+ */
40
+ guestDirs: string[];
41
+ /** cloudflared binary for live-session links. Default: on PATH, else downloaded once to ~/.cache/pinwright. */
42
+ cloudflared?: string;
43
+ /** Who launched the daemon: the CLI installs process-wide handlers, plugins must not. */
44
+ mode: 'cli' | 'plugin';
45
+ /** Print what happens. */
46
+ log: (msg: string) => void;
47
+ }
48
+ export type Options = Partial<Omit<Config, 'models'>> & {
49
+ models?: Partial<Config['models']>;
50
+ config?: string | false;
51
+ };
52
+ /** Defaults, then the config file in root, then explicit options (CLI flags, plugin options). */
53
+ export declare function loadConfig(opts?: Options): Promise<Config>;
package/dist/config.js ADDED
@@ -0,0 +1,59 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join, resolve } from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ const DEFAULTS = {
5
+ port: 4340,
6
+ host: '127.0.0.1',
7
+ maxAgents: 3,
8
+ rebuildOnEdit: true,
9
+ ask: false,
10
+ models: { planner: 'haiku', worker: 'sonnet' },
11
+ viewports: [
12
+ { name: 'mobile', width: 390, height: 844 },
13
+ { name: 'desktop', width: 1440, height: 900 },
14
+ ],
15
+ maxTurns: 30,
16
+ timeoutMin: 20,
17
+ lang: 'en',
18
+ instructions: '',
19
+ useApiKey: false,
20
+ shots: false,
21
+ guestDirs: ['src', 'public', 'app', 'pages', 'components', 'layouts', 'styles', 'css', 'assets', 'content', 'static', 'images', 'img'],
22
+ mode: 'plugin',
23
+ };
24
+ const FILES = ['pinwright.config.mjs', 'pinwright.config.js', 'pinwright.config.json'];
25
+ async function readFileConfig(root, explicit) {
26
+ const candidates = explicit ? [resolve(root, explicit)] : FILES.map((f) => join(root, f));
27
+ for (const file of candidates) {
28
+ if (!existsSync(file))
29
+ continue;
30
+ if (file.endsWith('.json'))
31
+ return JSON.parse(readFileSync(file, 'utf8'));
32
+ const mod = await import(`${pathToFileURL(file).href}?t=${Date.now()}`);
33
+ return (mod.default ?? mod);
34
+ }
35
+ if (explicit)
36
+ throw new Error(`config not found: ${explicit}`);
37
+ return {};
38
+ }
39
+ /** Defaults, then the config file in root, then explicit options (CLI flags, plugin options). */
40
+ export async function loadConfig(opts = {}) {
41
+ const root = resolve(opts.root ?? process.cwd());
42
+ const file = opts.config === false ? {} : await readFileConfig(root, opts.config || undefined);
43
+ const merged = { ...DEFAULTS, ...strip(file), ...strip(opts) };
44
+ merged.models = { ...DEFAULTS.models, ...file.models, ...opts.models };
45
+ const cfg = { ...merged, root, log: opts.log ?? file.log ?? ((m) => console.log(`[pinwright] ${m}`)) };
46
+ cfg.siteUrl ??= cfg.target;
47
+ if (cfg.target)
48
+ cfg.target = cfg.target.replace(/\/$/, '');
49
+ if (cfg.siteUrl)
50
+ cfg.siteUrl = cfg.siteUrl.replace(/\/$/, '');
51
+ return cfg;
52
+ }
53
+ function strip(o) {
54
+ const out = {};
55
+ for (const [k, v] of Object.entries(o))
56
+ if (v !== undefined && k !== 'config')
57
+ out[k] = v;
58
+ return out;
59
+ }
@@ -0,0 +1,18 @@
1
+ import type { Bus } from './bus.js';
2
+ import type { Config } from './config.js';
3
+ import type { Locks } from './locks.js';
4
+ import type { Rebuilder } from './rebuild.js';
5
+ import type { Shooter } from './shots.js';
6
+ import type { Store } from './store.js';
7
+ /** Everything a worker needs, built once by startPinwright. */
8
+ export interface Ctx {
9
+ cfg: Config;
10
+ store: Store;
11
+ bus: Bus;
12
+ locks: Locks;
13
+ shooter: Shooter;
14
+ rebuilder: Rebuilder;
15
+ }
16
+ export declare const langName: (code: string) => string;
17
+ /** The env the agents run with: no API key unless the user lets it through, so `claude login` is used. */
18
+ export declare function agentEnv(cfg: Config): Record<string, string | undefined>;
@@ -0,0 +1,11 @@
1
+ const LANGS = { it: 'Italian', en: 'English', es: 'Spanish', fr: 'French', de: 'German', pt: 'Portuguese' };
2
+ export const langName = (code) => LANGS[code.slice(0, 2).toLowerCase()] ?? code;
3
+ /** The env the agents run with: no API key unless the user lets it through, so `claude login` is used. */
4
+ export function agentEnv(cfg) {
5
+ const env = { ...process.env };
6
+ if (!cfg.useApiKey)
7
+ delete env.ANTHROPIC_API_KEY;
8
+ // Launched from inside a Claude Code session: the child must not think it is nested.
9
+ delete env.CLAUDECODE;
10
+ return env;
11
+ }
package/dist/db.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import { DatabaseSync } from 'node:sqlite';
2
+ export declare function openDb(root: string): DatabaseSync;