@archangel70/cosmo 1.14.0 → 1.15.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,20 @@
2
2
 
3
3
  All notable Cosmo changes are recorded here.
4
4
 
5
+ ## 1.15.0 — Shared preview tunnels
6
+
7
+ - Added one-command temporary public previews through Cloudflare Quick Tunnels with no account, DNS change, API key, or deployment configuration.
8
+ - Kept Astro bound to loopback, supervised both processes, and made `Ctrl+C` invalidate the public link by stopping the preview and tunnel together.
9
+ - Added beginner-friendly `cloudflared` installation guidance, optional port selection, conversational launcher guidance, and regression coverage.
10
+ - Kept shared previews out of deployment history and production release decisions.
11
+
12
+ ## 1.14.1 — Wikimedia-safe EntityMap enrichment
13
+
14
+ - Throttled serial Wikidata searches to avoid request spikes on sites with many entities.
15
+ - Added a versioned, descriptive Wikimedia User-Agent with a public support URL and an optional operator-specific contact override.
16
+ - Added bounded HTTP 429 and 503 retries that honor `Retry-After` and otherwise use a Wikimedia-compatible exponential backoff.
17
+ - Added regression coverage for recovery after repeated rate limits and for the bounded failure path.
18
+
5
19
  ## 1.14.0 — Native EntityMap and resilient browser signals
6
20
 
7
21
  - Classified browser console messages explicitly marked as report-only CSP observations as visible, non-blocking warnings while keeping enforced CSP failures critical.
package/README.md CHANGED
@@ -4,7 +4,7 @@ Cosmo helps an AI coding assistant build a complete, original Astro website for
4
4
 
5
5
  You do **not** need to know how to code. Cosmo supports Claude Code, Codex, and Google Antigravity.
6
6
 
7
- Current version: **1.14.0**
7
+ Current version: **1.15.0**
8
8
 
9
9
  ## Quick install
10
10
 
@@ -82,7 +82,7 @@ This is the only part of the beginner setup that uses a terminal. It is one inst
82
82
  cosmo --version
83
83
  ```
84
84
 
85
- You should see `1.14.0` or a newer version. Cosmo automatically installs its Claude, Codex, and Antigravity launchers.
85
+ You should see `1.15.0` or a newer version. Cosmo automatically installs its Claude, Codex, and Antigravity launchers.
86
86
 
87
87
  ### On Windows
88
88
 
@@ -99,7 +99,7 @@ You should see `1.14.0` or a newer version. Cosmo automatically installs its Cla
99
99
  cosmo --version
100
100
  ```
101
101
 
102
- You should see `1.14.0` or a newer version. Cosmo automatically installs its Claude, Codex, and Antigravity launchers.
102
+ You should see `1.15.0` or a newer version. Cosmo automatically installs its Claude, Codex, and Antigravity launchers.
103
103
 
104
104
  ## Step 4: create your website folder
105
105
 
@@ -236,6 +236,7 @@ npm uninstall --global @archangel70/cosmo
236
236
  | Your assistant does not recognize Cosmo | Restart it, run `cosmo setup`, then use Claude's `/cosmo:cosmo`, Codex's `$cosmo`, or Antigravity's `/cosmo`. |
237
237
  | You opened the wrong folder | Stop before approving changes, create or select the intended website folder, and start again there. |
238
238
  | You do not know how to answer a question | Tell the assistant what you know and ask it to explain what information is missing. |
239
+ | `cloudflared` is required for a shared preview | Install the free Cloudflare helper shown in Cosmo's message, then repeat the preview request. A Cloudflare account is not required. |
239
240
 
240
241
  For additional problems, see [Troubleshooting](#troubleshooting).
241
242
 
@@ -249,7 +250,7 @@ For additional problems, see [Troubleshooting](#troubleshooting).
249
250
  - Built-in research, authority, local-business, editorial, regulated-topic, audience, search, conversion, writing, brand-language, image-direction, and Claude Design capabilities.
250
251
  - Checks for business facts, claims, proof, page purpose, links, accessibility, mobile layouts, and build quality.
251
252
  - Saved project state so any supported agent can continue without relying on the old chat.
252
- - Local previews plus Cloudflare Pages, SFTP, FTPS, and explicitly acknowledged FTP deployment.
253
+ - Local previews, temporary public Cloudflare preview links, plus Cloudflare Pages, SFTP, FTPS, and explicitly acknowledged FTP deployment.
253
254
  - No license key, WordPress installation, hosted Cosmo account, or Cosmo cloud service.
254
255
 
255
256
  ## Contents for advanced users
@@ -436,6 +437,8 @@ During setup, Cosmo can ask whether you want an EntityMap. If you say yes, it cr
436
437
 
437
438
  No paid service is required. Wikidata can suggest public identifiers; Google Knowledge Graph, Google Places, and TextRazor can be enabled later with your own keys. Suggestions stay private and never change or publish business information until a named person accepts them.
438
439
 
440
+ Wikidata requests are automatically serialized and throttled. Cosmo identifies itself with a public support URL, honors Wikimedia's `Retry-After` response, and retries temporary rate limits twice. You can optionally set `COSMO_WIKIMEDIA_CONTACT` in your ignored environment file to identify the site's operator with a current email address or full URL.
441
+
439
442
  Cosmo publishes `/entitymap.json` and `/entitymap.html`, adds the discovery links, and checks the files during release QA. Automated output remains clearly marked as a draft until you review it. EntityMap complements the site's Schema.org JSON-LD and does not promise higher rankings.
440
443
 
441
444
  On an adopted Astro site, EntityMap uses the approved native route inventory and the site's built HTML. It does not require `src/content/pages`, replace hand-authored `.astro` pages, or change the existing design. Home and about represent the Organization, service and service-area routes become Services and Places, and other routes become Concepts unless a reviewed route override supplies a different name or core type.
@@ -562,6 +565,22 @@ Start a production-style local preview:
562
565
  cosmo deploy local .
563
566
  ```
564
567
 
568
+ ### Share a temporary preview
569
+
570
+ To let a client, friend, phone, or another assistant see the site before it is deployed, ask your assistant:
571
+
572
+ > Share this site with a temporary preview link.
573
+
574
+ Or run:
575
+
576
+ ```bash
577
+ cosmo preview share .
578
+ ```
579
+
580
+ Cosmo builds the site, starts a private local preview, and uses Cloudflare Quick Tunnels to print one temporary public HTTPS address. No Cloudflare account, DNS change, deployment setup, or API key is required. The free `cloudflared` application must be installed; when it is missing, Cosmo prints the appropriate installation step.
581
+
582
+ Anyone who has the address can view the preview. The random address stops working as soon as you press `Ctrl+C`. It is for review only: Cosmo does not record it as a deployment, treat it as production, or use it to bypass QA and release approval. Use `--no-build` only when the current `dist` is already correct, and use `--port 4173` only when you need a specific local port.
583
+
565
584
  ### Cloudflare Pages
566
585
 
567
586
  Configure a Direct Upload project:
@@ -736,6 +755,7 @@ Additional intake options include `--location`, `--pages`, `--language`, `--desi
736
755
  | `cosmo handoff show [directory]` | Display the current handoff. |
737
756
  | `cosmo deploy configure <provider> [directory] [options]` | Configure Cloudflare Pages, SFTP, FTPS, or FTP. |
738
757
  | `cosmo deploy local [directory] [--no-build]` | Run the production build locally. |
758
+ | `cosmo preview share [directory] [--no-build] [--port n]` | Create a temporary public review link that ends when Cosmo stops. |
739
759
  | `cosmo deploy preview|production [directory] [options]` | Deploy review or READY production output. |
740
760
  | `cosmo deploy status|history [directory]` | Inspect deployment configuration and durable history. |
741
761
 
@@ -10,6 +10,18 @@ cosmo deploy local .
10
10
 
11
11
  This builds the project and starts Astro's production preview server on `127.0.0.1`. Pass `--no-build` only when `dist` is already current.
12
12
 
13
+ ## Temporary shared preview
14
+
15
+ ```bash
16
+ cosmo preview share .
17
+ ```
18
+
19
+ This builds the project, binds Astro only to `127.0.0.1`, starts a Cloudflare Quick Tunnel, and prints the generated `trycloudflare.com` address. It requires the free `cloudflared` application but does not require a Cloudflare account, DNS changes, credentials, inbound ports, or deployment configuration. Cosmo detects a missing executable and prints a platform-appropriate installation instruction.
20
+
21
+ The address is public to anyone who has it, random, and available only while the command is running. Press `Ctrl+C` to stop both the local Astro process and the tunnel. Cosmo does not write the address to deployment history, call the session a release, or relax any production gate. Optional flags are `--no-build` for a current build and `--port <number>` for a specific loopback port.
22
+
23
+ Quick Tunnels are for review and testing only. Cloudflare documents a 200-concurrent-request limit and no Server-Sent Events support. Use a durable preview provider or a production deployment for persistent hosting.
24
+
13
25
  ## Cloudflare Pages
14
26
 
15
27
  The first remote adapter uses Cloudflare Pages Direct Upload. Static Astro projects require no Cloudflare Astro adapter: Cosmo builds `dist` and invokes Wrangler's `pages deploy` command.
@@ -110,6 +122,8 @@ Cloudflare Direct Upload projects cannot later be converted to Git integration.
110
122
 
111
123
  Official references:
112
124
 
125
+ - [Cloudflare Quick Tunnels](https://try.cloudflare.com/)
126
+ - [Cloudflare Tunnel development documentation](https://developers.cloudflare.com/tunnel/get-started/#quick-tunnels-development)
113
127
  - [Cloudflare Pages Direct Upload](https://developers.cloudflare.com/pages/get-started/direct-upload/)
114
128
  - [Wrangler Pages commands](https://developers.cloudflare.com/workers/wrangler/commands/pages/)
115
129
  - [Astro deployment to Cloudflare](https://docs.astro.build/en/guides/deploy/cloudflare/)
@@ -61,12 +61,15 @@ Approval records the reviewer and time, then changes the public status to `self-
61
61
 
62
62
  Wikidata is enabled by default and does not require a key. Google Knowledge Graph, Google Places, and TextRazor are available but disabled until the user chooses them.
63
63
 
64
+ Cosmo sends Wikidata searches serially with a short delay and identifies the client with its version and public support URL. If Wikidata responds with HTTP 429 or 503, Cosmo honors `Retry-After` and retries twice with exponential backoff when no delay is supplied. For installations that need an operator-specific contact, set `COSMO_WIKIMEDIA_CONTACT` to a current email address or full URL in the local environment; the public Cosmo issue tracker is the safe default.
65
+
64
66
  Provider settings live in `.cosmo/entities/config.json`. Keys belong in a local ignored environment file:
65
67
 
66
68
  ```dotenv
67
69
  COSMO_GOOGLE_KG_API_KEY=
68
70
  COSMO_GOOGLE_PLACES_API_KEY=
69
71
  COSMO_TEXTRAZOR_API_KEY=
72
+ COSMO_WIKIMEDIA_CONTACT=
70
73
  ```
71
74
 
72
75
  Run one provider at a time:
package/docs/ROADMAP.md CHANGED
@@ -194,6 +194,14 @@ The acceptance pilot completed five generation entries, static and browser QA wi
194
194
  - Private candidate review that prevents external services from overwriting the Entity Canon.
195
195
  - EntityMap conformance, attribution, relationship, source, and freshness checks integrated into release readiness.
196
196
 
197
+ ## Milestone 21 — shared preview tunnels (complete)
198
+
199
+ - One-command temporary public HTTPS previews through Cloudflare Quick Tunnels.
200
+ - No Cloudflare account, DNS change, API key, or durable deployment configuration.
201
+ - Loopback-only Astro binding with supervised preview and tunnel processes.
202
+ - Clean link extraction from structured cloudflared output and beginner-friendly installation guidance.
203
+ - Explicit testing-only boundaries with no deployment history or production-release effect.
204
+
197
205
  ## Later, only when justified
198
206
 
199
207
  - Additional deployment adapters, including Cloudflare Workers.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@archangel70/cosmo",
3
- "version": "1.14.0",
3
+ "version": "1.15.0",
4
4
  "description": "Local-first, multi-agent Astro website builder for Claude, Codex, Antigravity, and the command line.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -41,6 +41,7 @@ import {
41
41
  writeJson,
42
42
  } from '../lib/project.mjs';
43
43
  import { run } from '../lib/process.mjs';
44
+ import { assertCloudflared, sharePreview } from '../lib/shared-preview.mjs';
44
45
  import { updateCosmo } from '../lib/self-update.mjs';
45
46
  import { captureResearchSource, checkResearchWorkbench, scaffoldResearchWorkbench } from '../lib/research.mjs';
46
47
  import { collectProjectStatus } from '../lib/status.mjs';
@@ -65,7 +66,7 @@ import {
65
66
  workflowSummary,
66
67
  } from '../lib/workflow.mjs';
67
68
 
68
- const VERSION = '1.14.0';
69
+ const VERSION = '1.15.0';
69
70
  const cliDirectory = path.dirname(fileURLToPath(import.meta.url));
70
71
  const templateDirectory = path.resolve(cliDirectory, '../../../templates/astro-site');
71
72
  const [command = 'start', ...rawArgs] = process.argv.slice(2);
@@ -158,6 +159,7 @@ Commands
158
159
  cosmo deploy configure cloudflare-pages [directory] --project name [--production-branch main]
159
160
  cosmo deploy configure sftp|ftps|ftp [directory] --host name --remote-dir path [--preview-remote-dir path]
160
161
  cosmo deploy local [directory] [--no-build]
162
+ cosmo preview share [directory] [--no-build] [--port number]
161
163
  cosmo deploy preview [directory] [--no-build] [--env-file path]
162
164
  cosmo deploy production [directory] [--no-build] [--env-file path]
163
165
  cosmo deploy status [directory]
@@ -1099,6 +1101,22 @@ async function deployCommand(args) {
1099
1101
  throw new Error(`Unknown deploy command: ${subcommand}`);
1100
1102
  }
1101
1103
 
1104
+ async function previewCommand(args) {
1105
+ const subcommand = args[0] ?? 'share';
1106
+ const { options, positional } = parseOptions(args.slice(1));
1107
+ const target = projectDirectory(positional[0] ?? '.');
1108
+ if (subcommand === 'share') {
1109
+ readProject(target);
1110
+ await assertCloudflared();
1111
+ await prepareAndBuild(target, !options['no-build']);
1112
+ console.log('Starting a temporary public preview through Cloudflare...');
1113
+ console.log('No Cloudflare account, DNS changes, or deployment configuration are required.');
1114
+ await sharePreview(target, { port: options.port, cloudflaredCheck: async () => {} });
1115
+ return;
1116
+ }
1117
+ throw new Error(`Unknown preview command: ${subcommand}. Use cosmo preview share.`);
1118
+ }
1119
+
1102
1120
  async function main() {
1103
1121
  if (command === 'help' || command === '--help' || command === '-h') return help();
1104
1122
  if (command === 'start') return start(rawArgs);
@@ -1132,6 +1150,7 @@ async function main() {
1132
1150
  if (command === 'handoff') return handoffCommand(rawArgs);
1133
1151
  if (command === 'release') return releaseCommand(rawArgs);
1134
1152
  if (command === 'deploy') return deployCommand(rawArgs);
1153
+ if (command === 'preview') return previewCommand(rawArgs);
1135
1154
  throw new Error(`Unknown command: ${[command, ...rawArgs].join(' ')}`);
1136
1155
  }
1137
1156
 
@@ -9,6 +9,13 @@ const SPEC = 'https://entitymap.org/spec/v1.0';
9
9
  const TYPES = new Set(['Concept', 'ProprietaryTerm', 'Methodology', 'Metric', 'Taxonomy', 'Person', 'Organization', 'SoftwareProduct', 'PhysicalProduct', 'Service', 'Platform', 'Place', 'Event', 'Standard', 'Regulation']);
10
10
  const PREDICATES = new Set(['INSTANCE_OF', 'PART_OF', 'INCLUDES', 'DEPENDS_ON', 'REQUIRES', 'MEASURES', 'PRODUCED_BY', 'REGULATED_BY', 'AUTHORED_BY', 'AFFILIATED_WITH', 'COVERS', 'RELATES_TO', 'PRECEDES', 'ENABLES', 'PREVENTS', 'CONFLICTS_WITH', 'DESCRIBED_BY', 'OFFERS', 'IMPROVES', 'DEGRADES', 'LEADS_TO', 'SUITED_FOR', 'TARGETS', 'ACHIEVES']);
11
11
  const TIER_THREE = new Set(['IMPROVES', 'DEGRADES', 'LEADS_TO', 'SUITED_FOR', 'TARGETS', 'ACHIEVES']);
12
+ const WIKIDATA_REQUEST_INTERVAL_MS = 500;
13
+ const WIKIDATA_MAX_RETRIES = 2;
14
+ const WIKIDATA_CONTACT = 'https://github.com/ArchAngel70/cosmo/issues';
15
+ const COSMO_VERSION = (() => {
16
+ try { return JSON.parse(fs.readFileSync(new URL('../../../package.json', import.meta.url), 'utf8')).version; }
17
+ catch { return 'unknown'; }
18
+ })();
12
19
 
13
20
  export const DEFAULT_ENTITY_MAP_CONFIG = {
14
21
  version: 1,
@@ -411,6 +418,26 @@ function candidateId(value) {
411
418
  return `candidate-${crypto.createHash('sha256').update([value.provider, value.entityId, value.externalId, value.uri].join('|')).digest('hex').slice(0, 16)}`;
412
419
  }
413
420
 
421
+ function sleep(milliseconds) {
422
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
423
+ }
424
+
425
+ function wikidataUserAgent() {
426
+ const configured = process.env.COSMO_WIKIMEDIA_CONTACT?.trim();
427
+ const contact = configured && !/[\r\n]/.test(configured) ? configured.slice(0, 500) : WIKIDATA_CONTACT;
428
+ return `Cosmo-EntityMap/${COSMO_VERSION} (${contact})`;
429
+ }
430
+
431
+ function retryAfterMilliseconds(response, attempt) {
432
+ const value = response.headers.get('retry-after')?.trim();
433
+ if (value && /^\d+$/.test(value)) return Number(value) * 1000;
434
+ if (value) {
435
+ const date = Date.parse(value);
436
+ if (Number.isFinite(date)) return Math.max(0, date - Date.now());
437
+ }
438
+ return 5000 * (2 ** attempt);
439
+ }
440
+
414
441
  function entitySubjects(projectDir) {
415
442
  const project = readProject(projectDir).data;
416
443
  const publisher = readJson(path.join(projectDir, '.cosmo', 'brand', 'entity-canon.json'), 'Entity Canon');
@@ -424,12 +451,23 @@ function entitySubjects(projectDir) {
424
451
  return { subjects: [...subjects.values()], pages, config };
425
452
  }
426
453
 
427
- async function enrichWikidata(subjects, fetchImpl) {
454
+ async function enrichWikidata(subjects, fetchImpl, {
455
+ sleepImpl = sleep,
456
+ requestIntervalMs = WIKIDATA_REQUEST_INTERVAL_MS,
457
+ maxRetries = WIKIDATA_MAX_RETRIES,
458
+ } = {}) {
428
459
  const values = [];
429
- for (const subject of subjects) {
460
+ for (const [index, subject] of subjects.entries()) {
461
+ if (index > 0 && requestIntervalMs > 0) await sleepImpl(requestIntervalMs);
430
462
  const url = new URL('https://www.wikidata.org/w/api.php');
431
463
  for (const [key, value] of Object.entries({ action: 'wbsearchentities', search: subject.name, language: 'en', uselang: 'en', format: 'json', limit: '5', origin: '*' })) url.searchParams.set(key, value);
432
- const response = await fetchImpl(url, { headers: { 'user-agent': 'Cosmo EntityMap Builder/1.0' } });
464
+ let response;
465
+ for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
466
+ response = await fetchImpl(url, { headers: { 'user-agent': wikidataUserAgent() } });
467
+ if (![429, 503].includes(response.status)) break;
468
+ if (attempt === maxRetries) throw new Error(`Wikidata returned HTTP ${response.status} after ${maxRetries + 1} attempts. Wait before running enrichment again.`);
469
+ await sleepImpl(retryAfterMilliseconds(response, attempt));
470
+ }
433
471
  if (!response.ok) throw new Error(`Wikidata returned HTTP ${response.status}.`);
434
472
  const body = await response.json();
435
473
  for (const item of body.search ?? []) values.push({ provider: 'wikidata', entityId: subject.entityId, matchedName: item.label, externalId: item.id, uri: item.concepturi ?? `https://www.wikidata.org/wiki/${item.id}`, description: item.description ?? '', score: null });
@@ -480,7 +518,12 @@ async function enrichTextRazor(subjects, pages, key, fetchImpl) {
480
518
  return values;
481
519
  }
482
520
 
483
- export async function enrichEntityMap(projectDir, provider, { fetchImpl = fetch } = {}) {
521
+ export async function enrichEntityMap(projectDir, provider, {
522
+ fetchImpl = fetch,
523
+ sleepImpl = sleep,
524
+ wikidataRequestIntervalMs = WIKIDATA_REQUEST_INTERVAL_MS,
525
+ wikidataMaxRetries = WIKIDATA_MAX_RETRIES,
526
+ } = {}) {
484
527
  const { subjects, pages, config } = entitySubjects(projectDir);
485
528
  const providerConfig = config.providers?.[provider];
486
529
  if (!providerConfig) throw new Error(`Unknown EntityMap provider: ${provider}`);
@@ -488,7 +531,7 @@ export async function enrichEntityMap(projectDir, provider, { fetchImpl = fetch
488
531
  const key = providerConfig.apiKeyEnv ? process.env[providerConfig.apiKeyEnv] : null;
489
532
  if (providerConfig.apiKeyEnv && !key) throw new Error(`Missing ${providerConfig.apiKeyEnv}. Put it in a local environment file; never commit it.`);
490
533
  let raw = [];
491
- if (provider === 'wikidata') raw = await enrichWikidata(subjects, fetchImpl);
534
+ if (provider === 'wikidata') raw = await enrichWikidata(subjects, fetchImpl, { sleepImpl, requestIntervalMs: wikidataRequestIntervalMs, maxRetries: wikidataMaxRetries });
492
535
  if (provider === 'googleKnowledgeGraph') raw = await enrichGoogleKnowledgeGraph(subjects, key, fetchImpl);
493
536
  if (provider === 'googlePlaces') raw = await enrichGooglePlaces(subjects, key, fetchImpl);
494
537
  if (provider === 'textRazor') raw = await enrichTextRazor(subjects, pages, key, fetchImpl);
@@ -0,0 +1,212 @@
1
+ import http from 'node:http';
2
+ import net from 'node:net';
3
+ import { spawn } from 'node:child_process';
4
+
5
+ const QUICK_TUNNEL_PATTERN = /https:\/\/[a-z0-9-]+\.trycloudflare\.com\b/i;
6
+
7
+ export class SharedPreviewError extends Error {}
8
+
9
+ export function extractQuickTunnelUrl(value) {
10
+ return String(value ?? '').match(QUICK_TUNNEL_PATTERN)?.[0] ?? null;
11
+ }
12
+
13
+ export function quickTunnelArgs(port) {
14
+ return ['tunnel', '--url', `http://127.0.0.1:${port}`, '--output', 'json'];
15
+ }
16
+
17
+ export function cloudflaredInstallHelp(platform = process.platform) {
18
+ const instruction = platform === 'darwin'
19
+ ? 'Install it with Homebrew: brew install cloudflared'
20
+ : platform === 'win32'
21
+ ? 'Install it with Windows Package Manager: winget install --id Cloudflare.cloudflared'
22
+ : 'Install cloudflared from https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/';
23
+ return `Cloudflare shared previews require the free cloudflared application.\n${instruction}\nThen run this command again.`;
24
+ }
25
+
26
+ function executable(command) {
27
+ return process.platform === 'win32' && command === 'npm' ? 'npm.cmd' : command;
28
+ }
29
+
30
+ function waitForExit(child) {
31
+ return new Promise((resolve, reject) => {
32
+ child.once('error', reject);
33
+ child.once('exit', (code, signal) => resolve({ code, signal }));
34
+ });
35
+ }
36
+
37
+ export async function assertCloudflared({ spawnProcess = spawn, platform = process.platform } = {}) {
38
+ let child;
39
+ try {
40
+ child = spawnProcess('cloudflared', ['--version'], { stdio: 'ignore', shell: false });
41
+ const result = await waitForExit(child);
42
+ if (result.code !== 0) throw new Error(`cloudflared exited with code ${result.code}`);
43
+ } catch (error) {
44
+ throw new SharedPreviewError(cloudflaredInstallHelp(platform), { cause: error });
45
+ }
46
+ }
47
+
48
+ export function findAvailablePort(host = '127.0.0.1') {
49
+ return new Promise((resolve, reject) => {
50
+ const server = net.createServer();
51
+ server.unref();
52
+ server.once('error', reject);
53
+ server.listen(0, host, () => {
54
+ const address = server.address();
55
+ const port = typeof address === 'object' && address ? address.port : null;
56
+ server.close((error) => error ? reject(error) : resolve(port));
57
+ });
58
+ });
59
+ }
60
+
61
+ function previewResponds(port) {
62
+ return new Promise((resolve) => {
63
+ const request = http.get({ hostname: '127.0.0.1', port, path: '/', timeout: 1_000 }, (response) => {
64
+ response.resume();
65
+ resolve(true);
66
+ });
67
+ request.once('timeout', () => request.destroy());
68
+ request.once('error', () => resolve(false));
69
+ });
70
+ }
71
+
72
+ export async function waitForPreview(port, { timeoutMs = 30_000, intervalMs = 150 } = {}) {
73
+ const deadline = Date.now() + timeoutMs;
74
+ while (Date.now() < deadline) {
75
+ if (await previewResponds(port)) return;
76
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
77
+ }
78
+ throw new SharedPreviewError(`The local Astro preview did not start on port ${port} within ${Math.round(timeoutMs / 1_000)} seconds.`);
79
+ }
80
+
81
+ function waitForPreviewProcess(child, port, readyCheck) {
82
+ return new Promise((resolve, reject) => {
83
+ const cleanup = () => {
84
+ child.removeListener('error', onError);
85
+ child.removeListener('exit', onExit);
86
+ };
87
+ const onError = (error) => {
88
+ cleanup();
89
+ reject(new SharedPreviewError(`The local Astro preview could not start: ${error.message}`, { cause: error }));
90
+ };
91
+ const onExit = (code) => {
92
+ cleanup();
93
+ reject(new SharedPreviewError(`The local Astro preview stopped before it was ready${code === null ? '' : ` with code ${code}`}.`));
94
+ };
95
+ child.once('error', onError);
96
+ child.once('exit', onExit);
97
+ Promise.resolve(readyCheck(port)).then(() => {
98
+ cleanup();
99
+ resolve();
100
+ }, (error) => {
101
+ cleanup();
102
+ reject(error);
103
+ });
104
+ });
105
+ }
106
+
107
+ function stopChild(child) {
108
+ if (!child || child.exitCode !== null || child.killed) return;
109
+ child.kill('SIGTERM');
110
+ const timer = setTimeout(() => {
111
+ if (child.exitCode === null) child.kill('SIGKILL');
112
+ }, 3_000);
113
+ timer.unref();
114
+ }
115
+
116
+ function mirror(stream, destination) {
117
+ stream?.on('data', (chunk) => destination.write(chunk));
118
+ }
119
+
120
+ export async function sharePreview(projectDir, {
121
+ port,
122
+ spawnProcess = spawn,
123
+ signalSource = process,
124
+ output = process.stdout,
125
+ errorOutput = process.stderr,
126
+ readyCheck = waitForPreview,
127
+ cloudflaredCheck = assertCloudflared,
128
+ urlTimeoutMs = 30_000,
129
+ } = {}) {
130
+ await cloudflaredCheck({ spawnProcess });
131
+ const requestedPort = port ?? await findAvailablePort();
132
+ const previewPort = typeof requestedPort === 'number'
133
+ ? requestedPort
134
+ : /^\d+$/.test(String(requestedPort)) ? Number(requestedPort) : Number.NaN;
135
+ if (!Number.isInteger(previewPort) || previewPort < 1 || previewPort > 65535) {
136
+ throw new SharedPreviewError('Preview port must be a whole number between 1 and 65535.');
137
+ }
138
+
139
+ const preview = spawnProcess(executable('npm'), ['run', 'preview', '--', '--host', '127.0.0.1', '--port', String(previewPort)], {
140
+ cwd: projectDir,
141
+ env: process.env,
142
+ stdio: ['inherit', 'pipe', 'pipe'],
143
+ shell: false,
144
+ });
145
+ mirror(preview.stdout, output);
146
+ mirror(preview.stderr, errorOutput);
147
+
148
+ try {
149
+ await waitForPreviewProcess(preview, previewPort, readyCheck);
150
+ } catch (error) {
151
+ stopChild(preview);
152
+ throw error;
153
+ }
154
+
155
+ const tunnel = spawnProcess('cloudflared', quickTunnelArgs(previewPort), {
156
+ cwd: projectDir,
157
+ env: process.env,
158
+ stdio: ['ignore', 'pipe', 'pipe'],
159
+ shell: false,
160
+ });
161
+
162
+ return new Promise((resolve, reject) => {
163
+ let buffer = '';
164
+ let url = null;
165
+ let stopping = false;
166
+ let settled = false;
167
+
168
+ const finish = (error) => {
169
+ if (settled) return;
170
+ settled = true;
171
+ clearTimeout(urlTimer);
172
+ signalSource.removeListener('SIGINT', shutdown);
173
+ signalSource.removeListener('SIGTERM', shutdown);
174
+ stopChild(preview);
175
+ stopChild(tunnel);
176
+ if (error) reject(error);
177
+ else resolve({ url, port: previewPort });
178
+ };
179
+
180
+ const shutdown = () => {
181
+ stopping = true;
182
+ output.write('\nShared preview stopped. The temporary link no longer works.\n');
183
+ finish();
184
+ };
185
+
186
+ const inspect = (chunk) => {
187
+ buffer = `${buffer}${chunk}`.slice(-16_000);
188
+ const found = extractQuickTunnelUrl(buffer);
189
+ if (!found || url) return;
190
+ url = found;
191
+ output.write(`\nYour temporary preview is ready:\n\n${url}\n\n`);
192
+ output.write('Anyone with this address can view the site. Press Ctrl+C when you are finished sharing.\n');
193
+ output.write('This is a temporary review link, not a production deployment.\n');
194
+ };
195
+
196
+ tunnel.stdout?.on('data', inspect);
197
+ tunnel.stderr?.on('data', inspect);
198
+ const urlTimer = setTimeout(() => finish(new SharedPreviewError('Cloudflare did not provide a temporary preview address within 30 seconds.')), urlTimeoutMs);
199
+ urlTimer.unref();
200
+
201
+ preview.once('error', (error) => finish(new SharedPreviewError(`The local Astro preview could not start: ${error.message}`, { cause: error })));
202
+ tunnel.once('error', (error) => finish(new SharedPreviewError(`${cloudflaredInstallHelp()}\nDetails: ${error.message}`, { cause: error })));
203
+ preview.once('exit', (code) => {
204
+ if (!stopping) finish(new SharedPreviewError(`The local Astro preview stopped unexpectedly${code === null ? '' : ` with code ${code}`}.`));
205
+ });
206
+ tunnel.once('exit', (code) => {
207
+ if (!stopping) finish(new SharedPreviewError(`The Cloudflare shared preview stopped unexpectedly${code === null ? '' : ` with code ${code}`}.`));
208
+ });
209
+ signalSource.once('SIGINT', shutdown);
210
+ signalSource.once('SIGTERM', shutdown);
211
+ });
212
+ }
@@ -1,4 +1,4 @@
1
1
  {
2
2
  "name": "cosmo",
3
- "version": "1.14.0"
3
+ "version": "1.15.0"
4
4
  }
@@ -70,6 +70,8 @@ Before page writing in a generated-content project, run `cosmo copy guide <page-
70
70
 
71
71
  Advance generation one state at a time. After two failed repair cycles, leave the page for human review. For release, run the build plus Copy Studio, content, intelligence, integrity, EntityMap when enabled, static, browser, and release checks. Deploy production only when the exact current release reports READY.
72
72
 
73
+ When the user asks to share a temporary preview, run `cosmo preview share .`. Explain that the generated address is public to anyone who has it, works only while the command remains running, and is not a production deployment. A missing `cloudflared` application is an optional-preview setup issue, not a project or release failure; follow Cosmo's displayed installation guidance and never request a Cloudflare API key for a Quick Tunnel.
74
+
73
75
  ## Switching agents
74
76
 
75
77
  Any supported agent may continue the project. Before switching, run appropriate checks and create `cosmo handoff create . --from <current-agent> --to <next-agent> --note "<completed work and open decisions>"`. The receiving agent must recover intent from the repository rather than prior chat history.
@@ -1,4 +1,4 @@
1
- <!-- cosmo-agent-version: 1.14.0 -->
1
+ <!-- cosmo-agent-version: 1.15.0 -->
2
2
  # Cosmo
3
3
 
4
4
  Use the Cosmo website-building workflow in the current workspace.
@@ -19,5 +19,6 @@ First, look for `.agents/skills/cosmo/SKILL.md` and follow it completely when pr
19
19
  - Use `cosmo doctor .` and `cosmo status . --json` to identify the next safe action.
20
20
  - Explain decisions conversationally so the user does not need to know Cosmo commands.
21
21
  - Ask whether a new or adopted project should include the optional AI-readable EntityMap. Never accept enrichment matches or approve it without explicit human review.
22
+ - If the user asks for a temporary public preview, run `cosmo preview share .`; explain that the address is public, works only while the command is running, and is not a deployment.
22
23
 
23
24
  If this is not yet a Cosmo project, guide the user through the smallest set of questions needed to start or adopt it. If it is already managed by Cosmo, continue the active stage and preserve every approved contract and handoff.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cosmo",
3
- "version": "1.14.0",
3
+ "version": "1.15.0",
4
4
  "description": "Conversational launcher for starting, adopting, and resuming local-first Cosmo Astro website builds.",
5
5
  "author": {
6
6
  "name": "Cosmo"
@@ -130,6 +130,8 @@ At every stage:
130
130
 
131
131
  For design, explore at least three genuinely distinct directions and preserve the selected direction in repository artifacts. After the page plan is approved, run `cosmo copy brief --all . --replace`, complete each flexible annotated section contract, and obtain approval. Before drafting a page, run `cosmo copy guide <page-id> .` and follow its separate grounding, drafting, evidence, editorial, reader, and final passes. Never imitate a living writer, import private Lyra files, reproduce copyrighted source wording, fabricate reader psychology, or use unsupported attacks on an alternative. For generation, advance one page gate at a time and respect repair limits. For QA, run `cosmo copy check .` with integrity, content, intelligence, EntityMap when enabled, static, and browser checks. For production, require the exact current release to be READY.
132
132
 
133
+ When the user asks to share a temporary preview, run `cosmo preview share .`. Explain that the generated address is public to anyone who has it, works only while the command remains running, and is not a production deployment. A missing `cloudflared` application is an optional-preview setup issue, not a project or release failure; follow Cosmo's displayed installation guidance and never request a Cloudflare API key for a Quick Tunnel.
134
+
133
135
  ## Help mode
134
136
 
135
137
  If the user asks what Cosmo can do, lead with four choices: build a new website, continue a Cosmo website, improve an existing Astro website without converting it, or review/publish a website. Show the simple journey `Discover → Brand → Design → Copy and page plan → Build → Quality checks → Preview and launch`. Mention advanced capabilities only if relevant or requested, and end with one clear question.
@@ -7,6 +7,7 @@ COSMO_DEPLOY_PASSWORD=
7
7
  # COSMO_DEPLOY_HOST_FINGERPRINT=SHA256:replace-with-server-fingerprint
8
8
 
9
9
  # Optional EntityMap enrichment. Wikidata works without a key.
10
+ COSMO_WIKIMEDIA_CONTACT=
10
11
  # Enable a provider in .cosmo/entities/config.json before using it.
11
12
  # COSMO_GOOGLE_KG_API_KEY=
12
13
  # COSMO_GOOGLE_PLACES_API_KEY=
@@ -30,4 +30,4 @@ cosmo browser check . --no-build
30
30
  cosmo release check .
31
31
  ```
32
32
 
33
- For deployment work, inspect `cosmo deploy status .` and `.cosmo/deploy/history.jsonl`. Review builds may use `cosmo deploy preview .`; production must use `cosmo deploy production .` after the exact current release reports READY. Keep provider credentials in process environment or a gitignored runtime env file. Never accept an EntityMap enrichment candidate or mark the map reviewed without explicit human approval. Never delete remote files implicitly.
33
+ For deployment work, inspect `cosmo deploy status .` and `.cosmo/deploy/history.jsonl`. A user asking for a temporary public link may use `cosmo preview share .`; make clear that it is public, process-bound, and not a deployment. Durable review builds may use `cosmo deploy preview .`; production must use `cosmo deploy production .` after the exact current release reports READY. Keep provider credentials in process environment or a gitignored runtime env file. Never accept an EntityMap enrichment candidate or mark the map reviewed without explicit human approval. Never delete remote files implicitly.
@@ -27,4 +27,4 @@ cosmo release check .
27
27
  cosmo handoff create . --from claude --to codex --note "Summary of the completed work and any open judgment calls"
28
28
  ```
29
29
 
30
- Use `cosmo deploy preview .` for review. Run `cosmo deploy production .` only after `cosmo release check .` reports READY. Provider credentials may come from process environment or a runtime `--env-file`; never write values into Cosmo config, history, handoffs, or tracked files. Never accept an EntityMap enrichment candidate or mark the map reviewed without explicit human approval.
30
+ Use `cosmo preview share .` when the user wants a temporary public link, and explain that it is public, process-bound, and not a deployment. Use `cosmo deploy preview .` for durable review. Run `cosmo deploy production .` only after `cosmo release check .` reports READY. Provider credentials may come from process environment or a runtime `--env-file`; never write values into Cosmo config, history, handoffs, or tracked files. Never accept an EntityMap enrichment candidate or mark the map reviewed without explicit human approval.
@@ -14,4 +14,4 @@ The initial home and about routes are neutral, `noindex` scaffolds. The build pl
14
14
 
15
15
  The starter uses the `lean` intelligence profile. Run `cosmo intelligence list` to inspect optional profiles and packs, then `cosmo intelligence apply <profile> .` and `cosmo intelligence scaffold .` before starting the workflow when the project needs additional authority, local, editorial, regulated, research, image-direction, or Claude Design gates.
16
16
 
17
- Optional deployment supports Cloudflare Pages, SFTP, FTPS, and acknowledged plain FTP. Copy `.env.example` to `.env.deploy` for local credentials; `.env` variants are ignored and their values must never be committed.
17
+ Run `cosmo preview share .` for an optional temporary public review link; it requires the free `cloudflared` application but no Cloudflare account or API key. Optional durable deployment supports Cloudflare Pages, SFTP, FTPS, and acknowledged plain FTP. Copy `.env.example` to `.env.deploy` for local credentials; `.env` variants are ignored and their values must never be committed.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cosmo/astro-starter",
3
- "version": "1.14.0",
3
+ "version": "1.15.0",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "scripts": {