@bastani/atomic 0.6.5 → 0.6.6-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 (125) hide show
  1. package/.agents/skills/ado-commit/SKILL.md +2 -0
  2. package/.agents/skills/ado-create-pr/SKILL.md +2 -0
  3. package/.agents/skills/advanced-evaluation/SKILL.md +2 -0
  4. package/.agents/skills/ast-grep/SKILL.md +2 -0
  5. package/.agents/skills/bdi-mental-states/SKILL.md +2 -0
  6. package/.agents/skills/bun/SKILL.md +156 -122
  7. package/.agents/skills/context-compression/SKILL.md +2 -0
  8. package/.agents/skills/context-degradation/SKILL.md +2 -0
  9. package/.agents/skills/context-fundamentals/SKILL.md +2 -0
  10. package/.agents/skills/context-optimization/SKILL.md +2 -0
  11. package/.agents/skills/create-spec/SKILL.md +2 -0
  12. package/.agents/skills/docx/SKILL.md +2 -0
  13. package/.agents/skills/evaluation/SKILL.md +2 -0
  14. package/.agents/skills/explain-code/SKILL.md +2 -0
  15. package/.agents/skills/filesystem-context/SKILL.md +2 -0
  16. package/.agents/skills/find-skills/SKILL.md +2 -0
  17. package/.agents/skills/gh-commit/SKILL.md +2 -0
  18. package/.agents/skills/gh-create-pr/SKILL.md +2 -0
  19. package/.agents/skills/hosted-agents/SKILL.md +2 -0
  20. package/.agents/skills/impeccable/SKILL.md +117 -304
  21. package/.agents/skills/impeccable/agents/openai.yaml +4 -0
  22. package/.agents/skills/{adapt/SKILL.md → impeccable/reference/adapt.md} +2 -11
  23. package/.agents/skills/{animate/SKILL.md → impeccable/reference/animate.md} +15 -15
  24. package/.agents/skills/{audit/SKILL.md → impeccable/reference/audit.md} +8 -22
  25. package/.agents/skills/{bolder/SKILL.md → impeccable/reference/bolder.md} +9 -13
  26. package/.agents/skills/impeccable/reference/brand.md +114 -0
  27. package/.agents/skills/{clarify/SKILL.md → impeccable/reference/clarify.md} +2 -11
  28. package/.agents/skills/{colorize/SKILL.md → impeccable/reference/colorize.md} +23 -12
  29. package/.agents/skills/impeccable/reference/craft.md +152 -29
  30. package/.agents/skills/{critique/SKILL.md → impeccable/reference/critique.md} +25 -37
  31. package/.agents/skills/{delight/SKILL.md → impeccable/reference/delight.md} +9 -11
  32. package/.agents/skills/{distill/SKILL.md → impeccable/reference/distill.md} +2 -13
  33. package/.agents/skills/impeccable/reference/document.md +427 -0
  34. package/.agents/skills/impeccable/reference/extract.md +1 -1
  35. package/.agents/skills/{harden/SKILL.md → impeccable/reference/harden.md} +1 -43
  36. package/.agents/skills/{layout/SKILL.md → impeccable/reference/layout.md} +27 -11
  37. package/.agents/skills/impeccable/reference/live.md +594 -0
  38. package/.agents/skills/impeccable/reference/motion-design.md +12 -2
  39. package/.agents/skills/impeccable/reference/onboard.md +234 -0
  40. package/.agents/skills/{optimize/SKILL.md → impeccable/reference/optimize.md} +4 -12
  41. package/.agents/skills/{overdrive/SKILL.md → impeccable/reference/overdrive.md} +9 -21
  42. package/.agents/skills/{critique → impeccable}/reference/personas.md +1 -1
  43. package/.agents/skills/{polish/SKILL.md → impeccable/reference/polish.md} +31 -23
  44. package/.agents/skills/impeccable/reference/product.md +62 -0
  45. package/.agents/skills/{quieter/SKILL.md → impeccable/reference/quieter.md} +7 -11
  46. package/.agents/skills/impeccable/reference/shape.md +151 -0
  47. package/.agents/skills/impeccable/reference/teach.md +156 -0
  48. package/.agents/skills/{typeset/SKILL.md → impeccable/reference/typeset.md} +19 -11
  49. package/.agents/skills/impeccable/reference/typography.md +31 -14
  50. package/.agents/skills/impeccable/scripts/cleanup-deprecated.mjs +87 -17
  51. package/.agents/skills/impeccable/scripts/command-metadata.json +94 -0
  52. package/.agents/skills/impeccable/scripts/design-parser.mjs +820 -0
  53. package/.agents/skills/impeccable/scripts/detect-csp.mjs +198 -0
  54. package/.agents/skills/impeccable/scripts/is-generated.mjs +69 -0
  55. package/.agents/skills/impeccable/scripts/live-accept.mjs +595 -0
  56. package/.agents/skills/impeccable/scripts/live-browser.js +4781 -0
  57. package/.agents/skills/impeccable/scripts/live-inject.mjs +445 -0
  58. package/.agents/skills/impeccable/scripts/live-poll.mjs +186 -0
  59. package/.agents/skills/impeccable/scripts/live-server.mjs +694 -0
  60. package/.agents/skills/impeccable/scripts/live-wrap.mjs +571 -0
  61. package/.agents/skills/impeccable/scripts/live.mjs +247 -0
  62. package/.agents/skills/impeccable/scripts/load-context.mjs +141 -0
  63. package/.agents/skills/impeccable/scripts/modern-screenshot.umd.js +14 -0
  64. package/.agents/skills/impeccable/scripts/pin.mjs +214 -0
  65. package/.agents/skills/init/SKILL.md +2 -0
  66. package/.agents/skills/liteparse/SKILL.md +1 -0
  67. package/.agents/skills/memory-systems/SKILL.md +2 -0
  68. package/.agents/skills/multi-agent-patterns/SKILL.md +2 -0
  69. package/.agents/skills/opentui/SKILL.md +1 -0
  70. package/.agents/skills/pdf/SKILL.md +2 -0
  71. package/.agents/skills/playwright-cli/SKILL.md +51 -5
  72. package/.agents/skills/playwright-cli/references/playwright-tests.md +1 -1
  73. package/.agents/skills/playwright-cli/references/running-code.md +10 -0
  74. package/.agents/skills/playwright-cli/references/session-management.md +56 -0
  75. package/.agents/skills/playwright-cli/references/spec-driven-testing.md +305 -0
  76. package/.agents/skills/playwright-cli/references/test-generation.md +49 -3
  77. package/.agents/skills/pptx/SKILL.md +2 -0
  78. package/.agents/skills/project-development/SKILL.md +2 -0
  79. package/.agents/skills/prompt-engineer/SKILL.md +2 -0
  80. package/.agents/skills/research-codebase/SKILL.md +2 -0
  81. package/.agents/skills/ripgrep/SKILL.md +2 -0
  82. package/.agents/skills/skill-creator/LICENSE.txt +1 -1
  83. package/.agents/skills/skill-creator/SKILL.md +2 -0
  84. package/.agents/skills/sl-commit/SKILL.md +2 -0
  85. package/.agents/skills/sl-submit-diff/SKILL.md +2 -0
  86. package/.agents/skills/tdd/SKILL.md +4 -0
  87. package/.agents/skills/tool-design/SKILL.md +2 -0
  88. package/.agents/skills/typescript-advanced-types/SKILL.md +2 -1
  89. package/.agents/skills/typescript-expert/SKILL.md +7 -1
  90. package/.agents/skills/typescript-react-reviewer/SKILL.md +2 -1
  91. package/.agents/skills/workflow-creator/SKILL.md +75 -72
  92. package/.agents/skills/workflow-creator/references/session-config.md +48 -1
  93. package/.agents/skills/xlsx/SKILL.md +2 -0
  94. package/.opencode/opencode.json +4 -2
  95. package/dist/sdk/runtime/executor.d.ts +8 -0
  96. package/dist/sdk/runtime/executor.d.ts.map +1 -1
  97. package/dist/sdk/runtime/port-discovery.d.ts +71 -0
  98. package/dist/sdk/runtime/port-discovery.d.ts.map +1 -0
  99. package/dist/sdk/runtime/tmux.d.ts +10 -0
  100. package/dist/sdk/runtime/tmux.d.ts.map +1 -1
  101. package/dist/sdk/types.d.ts +1 -0
  102. package/dist/sdk/types.d.ts.map +1 -1
  103. package/dist/sdk/workflows/builtin/deep-research-codebase/opencode/index.d.ts.map +1 -1
  104. package/dist/sdk/workflows/builtin/open-claude-design/opencode/index.d.ts.map +1 -1
  105. package/dist/sdk/workflows/builtin/ralph/claude/index.d.ts.map +1 -1
  106. package/dist/sdk/workflows/builtin/ralph/copilot/index.d.ts.map +1 -1
  107. package/dist/sdk/workflows/builtin/ralph/helpers/prompts.d.ts +15 -0
  108. package/dist/sdk/workflows/builtin/ralph/helpers/prompts.d.ts.map +1 -1
  109. package/dist/sdk/workflows/builtin/ralph/opencode/index.d.ts.map +1 -1
  110. package/package.json +1 -1
  111. package/src/sdk/runtime/executor.test.ts +254 -1
  112. package/src/sdk/runtime/executor.ts +135 -89
  113. package/src/sdk/runtime/port-discovery.test.ts +573 -0
  114. package/src/sdk/runtime/port-discovery.ts +496 -0
  115. package/src/sdk/runtime/tmux.ts +16 -0
  116. package/src/sdk/types.ts +1 -0
  117. package/src/sdk/workflows/builtin/deep-research-codebase/opencode/index.ts +24 -6
  118. package/src/sdk/workflows/builtin/open-claude-design/opencode/index.ts +52 -13
  119. package/src/sdk/workflows/builtin/ralph/claude/index.ts +31 -3
  120. package/src/sdk/workflows/builtin/ralph/copilot/index.ts +16 -0
  121. package/src/sdk/workflows/builtin/ralph/helpers/prompts.ts +70 -3
  122. package/src/sdk/workflows/builtin/ralph/opencode/index.ts +50 -6
  123. package/.agents/skills/shape/SKILL.md +0 -96
  124. /package/.agents/skills/{critique → impeccable}/reference/cognitive-load.md +0 -0
  125. /package/.agents/skills/{critique → impeccable}/reference/heuristics-scoring.md +0 -0
@@ -0,0 +1,445 @@
1
+ /**
2
+ * CLI helper: insert/remove the live variant mode script tag in the project's
3
+ * main HTML entry point.
4
+ *
5
+ * On first live run, the agent generates `config.json` in this script's
6
+ * directory with the project's insertion target (framework-specific). On
7
+ * every subsequent run, this script handles insert/remove deterministically
8
+ * with zero LLM involvement.
9
+ *
10
+ * Usage:
11
+ * node live-inject.mjs --port PORT # Insert the live script tag
12
+ * node live-inject.mjs --remove # Remove the live script tag
13
+ * node live-inject.mjs --check # Check whether config.json exists
14
+ */
15
+
16
+ import fs from 'node:fs';
17
+ import path from 'node:path';
18
+ import { fileURLToPath } from 'node:url';
19
+
20
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
21
+ const CONFIG_PATH = process.env.IMPECCABLE_LIVE_CONFIG || path.join(__dirname, 'config.json');
22
+ const MARKER_OPEN_TEXT = 'impeccable-live-start';
23
+ const MARKER_CLOSE_TEXT = 'impeccable-live-end';
24
+
25
+ /**
26
+ * Hard-excluded directory patterns. These are NEVER user-facing pages and
27
+ * matching them would silently inject tracking scripts into third-party
28
+ * code. The user cannot turn these off via config — they are the floor.
29
+ */
30
+ const HARD_EXCLUDES = [
31
+ '**/node_modules/**',
32
+ '**/.git/**',
33
+ ];
34
+
35
+ export async function injectCli() {
36
+ const args = process.argv.slice(2);
37
+
38
+ if (args.includes('--help') || args.includes('-h')) {
39
+ console.log(`Usage: node live-inject.mjs [options]
40
+
41
+ Insert or remove the live mode script tag in the project's HTML entry point.
42
+ Reads configuration from config.json (in this same directory).
43
+
44
+ Modes:
45
+ --port PORT Insert script tag pointing at http://localhost:PORT/live.js
46
+ --remove Remove the script tag (if present)
47
+ --check Print whether config.json exists and its content
48
+
49
+ Output (JSON):
50
+ { ok, file, inserted|removed, config? }`);
51
+ process.exit(0);
52
+ }
53
+
54
+ if (args.includes('--check')) {
55
+ if (!fs.existsSync(CONFIG_PATH)) {
56
+ console.log(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
57
+ process.exit(0);
58
+ }
59
+ let cfg;
60
+ try {
61
+ cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
62
+ } catch (err) {
63
+ console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
64
+ return;
65
+ }
66
+ try {
67
+ validateConfig(cfg);
68
+ } catch (err) {
69
+ console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
70
+ return;
71
+ }
72
+ console.log(JSON.stringify({ ok: true, config: cfg, path: CONFIG_PATH }));
73
+ return;
74
+ }
75
+
76
+ // Load config
77
+ if (!fs.existsSync(CONFIG_PATH)) {
78
+ console.error(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
79
+ process.exit(1);
80
+ }
81
+ const config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
82
+ validateConfig(config);
83
+
84
+ const resolvedFiles = resolveFiles(process.cwd(), config);
85
+
86
+ if (args.includes('--remove')) {
87
+ const results = resolvedFiles.map((relFile) => {
88
+ const absFile = path.resolve(process.cwd(), relFile);
89
+ if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
90
+ const content = fs.readFileSync(absFile, 'utf-8');
91
+ const detagged = removeTag(content, config.commentSyntax);
92
+ const updated = revertCspMeta(detagged);
93
+ if (updated === content) return { file: relFile, removed: false, note: 'no tag present' };
94
+ fs.writeFileSync(absFile, updated, 'utf-8');
95
+ return {
96
+ file: relFile,
97
+ removed: detagged !== content,
98
+ cspReverted: updated !== detagged,
99
+ };
100
+ });
101
+ console.log(JSON.stringify({ ok: true, results }));
102
+ return;
103
+ }
104
+
105
+ // Insert mode — need --port
106
+ const portIdx = args.indexOf('--port');
107
+ const port = portIdx !== -1 ? parseInt(args[portIdx + 1], 10) : NaN;
108
+ if (!Number.isFinite(port)) {
109
+ console.error(JSON.stringify({ ok: false, error: 'missing_port' }));
110
+ process.exit(1);
111
+ }
112
+
113
+ const results = resolvedFiles.map((relFile) => {
114
+ const absFile = path.resolve(process.cwd(), relFile);
115
+ if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
116
+ const content = fs.readFileSync(absFile, 'utf-8');
117
+ const withoutOld = revertCspMeta(removeTag(content, config.commentSyntax));
118
+ const withTag = insertTag(withoutOld, config, port);
119
+ if (withTag === withoutOld) {
120
+ return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
121
+ }
122
+ const updated = patchCspMeta(withTag, port);
123
+ fs.writeFileSync(absFile, updated, 'utf-8');
124
+ return {
125
+ file: relFile,
126
+ inserted: true,
127
+ cspPatched: updated !== withTag,
128
+ };
129
+ });
130
+ const anyInserted = results.some((r) => r.inserted);
131
+ console.log(JSON.stringify({ ok: anyInserted, port, results }));
132
+ if (!anyInserted) process.exit(1);
133
+ }
134
+
135
+ /**
136
+ * Expand config.files (which may contain glob patterns) into a literal list
137
+ * of existing file paths relative to rootDir. Literal entries pass through;
138
+ * glob patterns are expanded via fs.globSync. HARD_EXCLUDES and config.exclude
139
+ * are applied as filters. Duplicates are removed. Order is preserved by
140
+ * first appearance.
141
+ */
142
+ export function resolveFiles(rootDir, config) {
143
+ const patterns = config.files;
144
+ const userExcludes = Array.isArray(config.exclude) ? config.exclude : [];
145
+ const allExcludes = [...HARD_EXCLUDES, ...userExcludes];
146
+ const excludeRegexes = allExcludes.map(globToRegex);
147
+
148
+ const isExcluded = (relPath) => excludeRegexes.some((re) => re.test(relPath));
149
+ const isGlob = (s) => /[*?[]/.test(s);
150
+
151
+ const seen = new Set();
152
+ const out = [];
153
+ for (const pat of patterns) {
154
+ if (!isGlob(pat)) {
155
+ // Literal path — include even if it doesn't exist yet; the caller
156
+ // reports file_not_found per-entry. Exclude list doesn't apply to
157
+ // explicit literal entries (user named it on purpose).
158
+ if (!seen.has(pat)) {
159
+ seen.add(pat);
160
+ out.push(pat);
161
+ }
162
+ continue;
163
+ }
164
+ let matches;
165
+ try {
166
+ matches = fs.globSync(pat, { cwd: rootDir, withFileTypes: true });
167
+ } catch {
168
+ continue;
169
+ }
170
+ for (const ent of matches) {
171
+ if (!ent.isFile || !ent.isFile()) continue;
172
+ const abs = path.join(ent.parentPath || ent.path || rootDir, ent.name);
173
+ const rel = path.relative(rootDir, abs).split(path.sep).join('/');
174
+ if (isExcluded(rel)) continue;
175
+ if (seen.has(rel)) continue;
176
+ seen.add(rel);
177
+ out.push(rel);
178
+ }
179
+ }
180
+ return out;
181
+ }
182
+
183
+ /**
184
+ * Convert a glob pattern to a RegExp. Supports:
185
+ * ** → any number of path segments (including zero)
186
+ * * → any chars except `/`
187
+ * ? → any single char except `/`
188
+ * Paths are normalized to forward slashes before matching.
189
+ */
190
+ function globToRegex(pattern) {
191
+ let re = '';
192
+ let i = 0;
193
+ while (i < pattern.length) {
194
+ const c = pattern[i];
195
+ if (c === '*') {
196
+ if (pattern[i + 1] === '*') {
197
+ // ** — any number of segments, including zero. Handle the common
198
+ // **/ and /** forms so `a/**/b` matches `a/b` as well as `a/x/y/b`.
199
+ if (pattern[i + 2] === '/') {
200
+ re += '(?:.*/)?';
201
+ i += 3;
202
+ } else {
203
+ re += '.*';
204
+ i += 2;
205
+ }
206
+ } else {
207
+ re += '[^/]*';
208
+ i += 1;
209
+ }
210
+ } else if (c === '?') {
211
+ re += '[^/]';
212
+ i += 1;
213
+ } else if (/[.+^${}()|[\]\\]/.test(c)) {
214
+ re += '\\' + c;
215
+ i += 1;
216
+ } else {
217
+ re += c;
218
+ i += 1;
219
+ }
220
+ }
221
+ return new RegExp('^' + re + '$');
222
+ }
223
+
224
+ // ---------------------------------------------------------------------------
225
+ // Core operations
226
+ // ---------------------------------------------------------------------------
227
+
228
+ function validateConfig(cfg) {
229
+ if (!cfg || typeof cfg !== 'object') throw new Error('config.json must be an object');
230
+ if (!Array.isArray(cfg.files) || cfg.files.length === 0) {
231
+ throw new Error('config.files (non-empty string array) required');
232
+ }
233
+ if (!cfg.files.every((f) => typeof f === 'string' && f.length > 0)) {
234
+ throw new Error('config.files must contain only non-empty strings');
235
+ }
236
+ if (cfg.exclude !== undefined) {
237
+ if (!Array.isArray(cfg.exclude)) {
238
+ throw new Error('config.exclude, if present, must be a string array');
239
+ }
240
+ if (!cfg.exclude.every((f) => typeof f === 'string' && f.length > 0)) {
241
+ throw new Error('config.exclude must contain only non-empty strings');
242
+ }
243
+ }
244
+ if (typeof cfg.insertBefore !== 'string' && typeof cfg.insertAfter !== 'string') {
245
+ throw new Error('config.insertBefore or config.insertAfter (string) required');
246
+ }
247
+ if (cfg.commentSyntax !== 'html' && cfg.commentSyntax !== 'jsx') {
248
+ throw new Error("config.commentSyntax must be 'html' or 'jsx'");
249
+ }
250
+ if (cfg.cspChecked !== undefined && typeof cfg.cspChecked !== 'boolean') {
251
+ throw new Error("config.cspChecked, if present, must be a boolean");
252
+ }
253
+ }
254
+
255
+ function commentOpen(syntax) { return syntax === 'jsx' ? '{/*' : '<!--'; }
256
+ function commentClose(syntax) { return syntax === 'jsx' ? '*/}' : '-->'; }
257
+
258
+ function buildTagBlock(syntax, port) {
259
+ const open = commentOpen(syntax);
260
+ const close = commentClose(syntax);
261
+ return (
262
+ open + ' ' + MARKER_OPEN_TEXT + ' ' + close + '\n' +
263
+ '<script src="http://localhost:' + port + '/live.js"></script>\n' +
264
+ open + ' ' + MARKER_CLOSE_TEXT + ' ' + close + '\n'
265
+ );
266
+ }
267
+
268
+ function insertTag(content, config, port) {
269
+ const block = buildTagBlock(config.commentSyntax, port);
270
+ // insertBefore: match the LAST occurrence. Anchors like `</body>` naturally
271
+ // belong at the end, and the same literal can appear earlier in code blocks
272
+ // within rendered documentation pages.
273
+ if (config.insertBefore) {
274
+ const idx = content.lastIndexOf(config.insertBefore);
275
+ if (idx === -1) return content;
276
+ return content.slice(0, idx) + block + content.slice(idx);
277
+ }
278
+ // insertAfter: match the FIRST occurrence — typical anchors like `<head>` or
279
+ // `<body>` open near the top of the document.
280
+ const idx = content.indexOf(config.insertAfter);
281
+ if (idx === -1) return content;
282
+ const after = idx + config.insertAfter.length;
283
+ // Preserve a single trailing newline if the anchor didn't end with one
284
+ const prefix = content[after] === '\n' ? content.slice(0, after + 1) : content.slice(0, after) + '\n';
285
+ return prefix + block + content.slice(prefix.length);
286
+ }
287
+
288
+ /**
289
+ * Remove the live script block. Matches either HTML or JSX comment markers
290
+ * regardless of config (so stale tags from a wrong config can still be cleaned).
291
+ *
292
+ * Indent-preserving: captures any whitespace immediately preceding the opener
293
+ * marker and re-emits it in place of the removed block. `insertTag` inserted
294
+ * the block *after* the original line's indent and *before* the anchor (e.g.
295
+ * `</body>`), which moved the indent onto the opener line and left the anchor
296
+ * unindented. Replacing the whole block (plus its trailing newline) with just
297
+ * the captured indent hands the indent back to the anchor that follows.
298
+ */
299
+ function removeTag(content, _syntax) {
300
+ const patterns = [
301
+ /([ \t]*)<!--\s*impeccable-live-start\s*-->[\s\S]*?<!--\s*impeccable-live-end\s*-->[ \t]*\n/,
302
+ /([ \t]*)\{\/\*\s*impeccable-live-start\s*\*\/\}[\s\S]*?\{\/\*\s*impeccable-live-end\s*\*\/\}[ \t]*\n/,
303
+ ];
304
+ for (const pat of patterns) {
305
+ const next = content.replace(pat, '$1');
306
+ if (next !== content) return next;
307
+ }
308
+ return content;
309
+ }
310
+
311
+ // ---------------------------------------------------------------------------
312
+ // Content-Security-Policy meta-tag patcher
313
+ //
314
+ // When the user's HTML carries `<meta http-equiv="Content-Security-Policy">`,
315
+ // the cross-origin load of /live.js (and the SSE/POST connection back to
316
+ // localhost:PORT) is blocked unless the CSP explicitly allows that origin.
317
+ //
318
+ // On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
319
+ // and stash the original `content` value in a `data-impeccable-csp-original`
320
+ // attribute (base64) so revert is exact.
321
+ //
322
+ // On remove: detect the marker attribute, decode it, restore the original
323
+ // content value verbatim, drop the marker.
324
+ //
325
+ // Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
326
+ // shared helpers) is NOT patched here — those need framework-specific config
327
+ // edits and are handled via the existing detect-csp.mjs reference output.
328
+ // Only the in-source meta-tag form gets the auto-patch.
329
+ // ---------------------------------------------------------------------------
330
+
331
+ const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
332
+
333
+ function findCspMetaTags(content) {
334
+ const out = [];
335
+ const tagRe = /<meta\s+([^>]*?)\/?>/gis;
336
+ let m;
337
+ while ((m = tagRe.exec(content)) !== null) {
338
+ const attrs = m[1];
339
+ if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
340
+ out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
341
+ }
342
+ return out;
343
+ }
344
+
345
+ function getAttr(attrs, name) {
346
+ const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
347
+ const m = attrs.match(re);
348
+ return m ? { quote: m[1], value: m[2], full: m[0] } : null;
349
+ }
350
+
351
+ function appendOriginToDirective(csp, directive, origin) {
352
+ const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
353
+ const m = csp.match(re);
354
+ if (m) {
355
+ const tokens = m[4].trim().split(/\s+/);
356
+ if (tokens.includes(origin)) return csp;
357
+ return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
358
+ }
359
+ // Directive missing — add it. Use 'self' + origin so we don't inadvertently
360
+ // narrow the policy compared to the default-src fallback (most users with
361
+ // an explicit CSP have 'self' there).
362
+ return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
363
+ }
364
+
365
+ export function patchCspMeta(content, port) {
366
+ const tags = findCspMetaTags(content);
367
+ if (tags.length === 0) return content;
368
+ const origin = `http://localhost:${port}`;
369
+
370
+ // Walk last-to-first so prior splices don't invalidate later indices.
371
+ let result = content;
372
+ for (let i = tags.length - 1; i >= 0; i--) {
373
+ const tag = tags[i];
374
+ const attrs = tag.attrs;
375
+ if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
376
+ const contentAttr = getAttr(attrs, 'content');
377
+ if (!contentAttr) continue;
378
+
379
+ const original = contentAttr.value;
380
+ let patched = original;
381
+ patched = appendOriginToDirective(patched, 'script-src', origin);
382
+ patched = appendOriginToDirective(patched, 'connect-src', origin);
383
+ // The shader overlay during 'generating' creates a screenshot via
384
+ // URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
385
+ // those. Add `blob:` so the overlay doesn't throw a CSP violation.
386
+ patched = appendOriginToDirective(patched, 'img-src', 'blob:');
387
+ if (patched === original) continue;
388
+
389
+ const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
390
+ const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
391
+ // The tagRe captures any whitespace between the last attribute and the
392
+ // closing `/>` as part of `attrs`. Naively appending ` ${marker}` after
393
+ // a replace would land it BEFORE that trailing space, leaving a double
394
+ // space inside attrs and clobbering the space before `/>`. Split off
395
+ // the trailing whitespace, splice the marker into the attribute body,
396
+ // and re-append the original trailing whitespace so a self-closing
397
+ // `<meta … />` round-trips byte-for-byte.
398
+ const trailingWs = (attrs.match(/[ \t]*$/) || [''])[0];
399
+ const attrsBody = attrs.slice(0, attrs.length - trailingWs.length);
400
+ const newAttrs = attrsBody.replace(contentAttr.full, newContentAttr) + ' ' + marker + trailingWs;
401
+ const newTag = tag.full.replace(attrs, newAttrs);
402
+
403
+ result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
404
+ }
405
+ return result;
406
+ }
407
+
408
+ export function revertCspMeta(content) {
409
+ const tags = findCspMetaTags(content);
410
+ if (tags.length === 0) return content;
411
+
412
+ let result = content;
413
+ for (let i = tags.length - 1; i >= 0; i--) {
414
+ const tag = tags[i];
415
+ const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
416
+ if (!origAttr) continue;
417
+ const contentAttr = getAttr(tag.attrs, 'content');
418
+ if (!contentAttr) continue;
419
+
420
+ let originalValue;
421
+ try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
422
+ catch { continue; }
423
+
424
+ const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
425
+ let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
426
+ // Drop the marker attribute and any single space immediately preceding it.
427
+ newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
428
+ const newTag = tag.full.replace(tag.attrs, newAttrs);
429
+
430
+ result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
431
+ }
432
+ return result;
433
+ }
434
+
435
+ // ---------------------------------------------------------------------------
436
+ // Auto-execute
437
+ // ---------------------------------------------------------------------------
438
+
439
+ const _running = process.argv[1];
440
+ if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs/')) {
441
+ injectCli();
442
+ }
443
+
444
+ export { insertTag, removeTag, validateConfig, buildTagBlock };
445
+ // patchCspMeta + revertCspMeta are exported above where they're defined.
@@ -0,0 +1,186 @@
1
+ /**
2
+ * CLI client for the live variant mode poll/reply protocol.
3
+ *
4
+ * Usage:
5
+ * npx impeccable poll # Block until browser event, print JSON
6
+ * npx impeccable poll --timeout=600000 # Custom timeout (ms); default is long-poll friendly
7
+ * npx impeccable poll --reply <id> done # Reply "done" to event <id>
8
+ * npx impeccable poll --reply <id> error "msg" # Reply with error
9
+ */
10
+
11
+ import { execFileSync } from 'node:child_process';
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import os from 'node:os';
15
+ import { fileURLToPath } from 'node:url';
16
+
17
+ // Node's built-in fetch (undici under the hood) enforces a 300s headers
18
+ // timeout that can't be lowered per-request. We cap each request below
19
+ // that ceiling and loop in `pollOnce` to synthesize a long poll without
20
+ // depending on the standalone undici package.
21
+ const PER_REQUEST_TIMEOUT_MS = 270_000;
22
+
23
+ const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');
24
+
25
+ function readServerInfo() {
26
+ try {
27
+ return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
28
+ } catch {
29
+ console.error('No running live server found. Start one with: npx impeccable live');
30
+ process.exit(1);
31
+ }
32
+ }
33
+
34
+ export async function pollCli() {
35
+ const args = process.argv.slice(2);
36
+
37
+ if (args.includes('--help') || args.includes('-h')) {
38
+ console.log(`Usage: impeccable poll [options]
39
+
40
+ Wait for a browser event from the live variant server, or reply to one.
41
+
42
+ Modes:
43
+ poll Block until a browser event arrives, print JSON
44
+ poll --reply <id> done Reply "done" to event <id>
45
+ poll --reply <id> error "msg" Reply with an error message
46
+
47
+ Options:
48
+ --timeout=MS Long-poll timeout in ms (default: 600000). Use the default unless the user asked to pause live; never use a short timeout to end the chat turn
49
+ --help Show this help message`);
50
+ process.exit(0);
51
+ }
52
+
53
+ const info = readServerInfo();
54
+ const base = `http://localhost:${info.port}`;
55
+
56
+ // Reply mode: npx impeccable poll --reply <id> <status> [--file path] [message]
57
+ const replyIdx = args.indexOf('--reply');
58
+ if (replyIdx !== -1) {
59
+ const id = args[replyIdx + 1];
60
+ const status = args[replyIdx + 2] || 'done';
61
+ const fileIdx = args.indexOf('--file');
62
+ const filePath = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
63
+ // Message is any remaining positional arg that isn't a flag
64
+ const message = args.find((a, i) => i > replyIdx + 2 && !a.startsWith('--') && i !== fileIdx + 1) || undefined;
65
+
66
+ if (!id) {
67
+ console.error('Usage: npx impeccable poll --reply <id> <status> [--file path] [message]');
68
+ process.exit(1);
69
+ }
70
+
71
+ try {
72
+ const res = await fetch(`${base}/poll`, {
73
+ method: 'POST',
74
+ headers: { 'Content-Type': 'application/json' },
75
+ body: JSON.stringify({
76
+ token: info.token,
77
+ id,
78
+ type: status,
79
+ message,
80
+ file: filePath,
81
+ }),
82
+ });
83
+
84
+ if (!res.ok) {
85
+ const body = await res.json().catch(() => ({}));
86
+ console.error(`Reply failed (${res.status}):`, body.error || res.statusText);
87
+ process.exit(1);
88
+ }
89
+
90
+ // Success — silent exit (agent doesn't need output for replies)
91
+ } catch (err) {
92
+ if (err.cause?.code === 'ECONNREFUSED') {
93
+ console.error('Live server not running. Start one with: npx impeccable live');
94
+ } else {
95
+ console.error('Reply failed:', err.message);
96
+ }
97
+ process.exit(1);
98
+ }
99
+ return;
100
+ }
101
+
102
+ // Poll mode: block until browser event. Default 10 min. Node's built-in
103
+ // fetch enforces a 300s headers timeout, so we loop in slices under that
104
+ // ceiling and keep re-polling until we get a real event or the user's
105
+ // total timeout runs out.
106
+ const timeoutArg = args.find(a => a.startsWith('--timeout='));
107
+ const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600000;
108
+
109
+ const deadline = Date.now() + totalTimeout;
110
+ let event;
111
+ try {
112
+ while (true) {
113
+ const remaining = deadline - Date.now();
114
+ if (remaining <= 0) {
115
+ event = { type: 'timeout' };
116
+ break;
117
+ }
118
+ const slice = Math.min(remaining, PER_REQUEST_TIMEOUT_MS);
119
+ const res = await fetch(`${base}/poll?token=${info.token}&timeout=${slice}`);
120
+
121
+ if (res.status === 401) {
122
+ console.error('Authentication failed. The server token may have changed.');
123
+ console.error('Try restarting: npx impeccable live stop && npx impeccable live');
124
+ process.exit(1);
125
+ }
126
+
127
+ if (!res.ok) {
128
+ console.error(`Poll failed: ${res.status} ${res.statusText}`);
129
+ process.exit(1);
130
+ }
131
+
132
+ const next = await res.json();
133
+ // Server-side timeout means no browser event arrived in this slice.
134
+ // Loop and re-poll until we get a real event or we hit the user's
135
+ // total deadline.
136
+ if (next?.type === 'timeout' && Date.now() < deadline) continue;
137
+ event = next;
138
+ break;
139
+ }
140
+
141
+ // Auto-handle accept/discard via deterministic script
142
+ if (event.type === 'accept' || event.type === 'discard') {
143
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
144
+ const acceptScript = path.join(__dirname, 'live-accept.mjs');
145
+ const scriptArgs = event.type === 'discard'
146
+ ? ['--id', event.id, '--discard']
147
+ : ['--id', event.id, '--variant', event.variantId];
148
+ if (event.type === 'accept' && event.paramValues && Object.keys(event.paramValues).length > 0) {
149
+ scriptArgs.push('--param-values', JSON.stringify(event.paramValues));
150
+ }
151
+ try {
152
+ const out = execFileSync(
153
+ 'node',
154
+ [acceptScript, ...scriptArgs],
155
+ { encoding: 'utf-8', cwd: process.cwd(), timeout: 30_000 }
156
+ );
157
+ event._acceptResult = JSON.parse(out.trim());
158
+ } catch (err) {
159
+ event._acceptResult = { handled: false, error: err.message };
160
+ }
161
+ }
162
+
163
+ // Second signal path: stderr banner in case the agent parses stdout
164
+ // JSON but skips nested fields. One line is enough — the full checklist
165
+ // is in reference/live.md.
166
+ if (event._acceptResult?.carbonize === true) {
167
+ process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. See reference/live.md "Required after accept".\n\n');
168
+ }
169
+
170
+ // Print the event as JSON — the agent reads this from stdout
171
+ console.log(JSON.stringify(event));
172
+ } catch (err) {
173
+ if (err.cause?.code === 'ECONNREFUSED') {
174
+ console.error('Live server not running. Start one with: npx impeccable live');
175
+ } else {
176
+ console.error('Poll failed:', err.message);
177
+ }
178
+ process.exit(1);
179
+ }
180
+ }
181
+
182
+ // Auto-execute when run directly
183
+ const _running = process.argv[1];
184
+ if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {
185
+ pollCli();
186
+ }