@aarwitz/tapp 0.35.7 → 0.35.9

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.
@@ -24,8 +24,10 @@ import { accessConfig, createAccessVerifier } from "./access-jwt.js";
24
24
  import { oauthProviders, oauthAuthorizeUrl, oauthEmailFromCode, isOauthProvider } from "./oauth.js";
25
25
  import { journeyFromCapture, JourneyStore, slugify } from "./journeys.js";
26
26
  import { AlertStore, alertForChange, alertMessage, deliverAlert } from "./alerts.js";
27
+ import { ENGINES, detectEngines, claudeArguments, agentLines, runClaude, tappMcpConfig } from "./engines.js";
27
28
  import { platformStates, selfHostAnswer, PLATFORM_TARGETS, hostToolchain } from "./platforms.js";
28
29
  import { isMacosAppBundle } from "./macos-driver.js";
30
+ import { discoverApps } from "./app-store-discovery.js";
29
31
 
30
32
  const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
31
33
  const assetRoot = path.join(packageRoot, "browser");
@@ -36,7 +38,7 @@ const contentTypes = new Map([
36
38
  [".css", "text/css; charset=utf-8"], [".html", "text/html; charset=utf-8"],
37
39
  [".js", "text/javascript; charset=utf-8"], [".json", "application/json; charset=utf-8"],
38
40
  [".png", "image/png"], [".jpg", "image/jpeg"], [".jpeg", "image/jpeg"],
39
- [".webm", "video/webm"], [".mov", "video/quicktime"], [".svg", "image/svg+xml"],
41
+ [".webm", "video/webm"], [".mp4", "video/mp4"], [".mov", "video/quicktime"], [".svg", "image/svg+xml"],
40
42
  ]);
41
43
 
42
44
  function sameSecret(left, right) {
@@ -75,16 +77,39 @@ function readJsonBody(request) {
75
77
  });
76
78
  }
77
79
 
78
- function serveFile(response, file, { inline = true } = {}) {
79
- if (!fs.existsSync(file) || !fs.statSync(file).isFile()) { response.writeHead(404); response.end("Not found"); return; }
80
+ export function serveFile(response, file, { inline = true, request } = {}) {
81
+ const stat = fs.statSync(file, { throwIfNoEntry: false });
82
+ if (!stat?.isFile()) { response.writeHead(404); response.end("Not found"); return; }
83
+ const size = stat.size;
80
84
  const headers = {
81
85
  "content-type": contentTypes.get(path.extname(file).toLowerCase()) || "application/octet-stream",
82
86
  "cache-control": "no-store",
83
87
  "x-content-type-options": "nosniff",
88
+ "content-length": size,
84
89
  };
85
90
  if (!inline) headers["content-disposition"] = `attachment; filename="${path.basename(file).replaceAll('"', "")}"`;
86
- response.writeHead(200, headers);
87
- fs.createReadStream(file).pipe(response);
91
+ let range;
92
+ if (request && headers["content-type"].startsWith("video/")) {
93
+ headers["accept-ranges"] = "bytes";
94
+ const match = /^bytes=(\d*)-(\d*)$/.exec(request.headers.range || "");
95
+ if (request.method === "GET" && match && (match[1] || match[2])) {
96
+ const start = match[1] ? Number(match[1]) : Math.max(0, size - Number(match[2]));
97
+ const end = match[1] && match[2] ? Math.min(Number(match[2]), size - 1) : size - 1;
98
+ if (start > end || !Number.isSafeInteger(start)) {
99
+ response.writeHead(416, { ...headers, "content-range": `bytes */${size}`, "content-length": 0 });
100
+ response.end();
101
+ return;
102
+ }
103
+ range = { start, end };
104
+ headers["content-range"] = `bytes ${start}-${end}/${size}`;
105
+ headers["content-length"] = end - start + 1;
106
+ }
107
+ }
108
+ response.writeHead(range ? 206 : 200, headers);
109
+ if (request?.method === "HEAD") { response.end(); return; }
110
+ const stream = fs.createReadStream(file, range);
111
+ response.on("close", () => stream.destroy());
112
+ stream.on("error", error => response.destroy(error)).pipe(response);
88
113
  }
89
114
 
90
115
  function serveBrowserIndex(response, { apiBase = "", loginUrl = "" } = {}) {
@@ -134,6 +159,7 @@ const OAUTH_STATE_COOKIE = "tapp_oauth_state";
134
159
  // What a signed-out visitor on a public Studio may reach. Everything absent from this list is
135
160
  // refused, so a new route is private until someone deliberately opens it.
136
161
  function anonymousAllows(method, pathname) {
162
+ if (method === "HEAD" && pathname.startsWith("/assets/")) return true;
137
163
  if (method === "GET") {
138
164
  if (pathname === "/" || pathname === "/admin" || pathname === "/api/version" || pathname === "/api/session" || pathname === "/api/audits") return true;
139
165
  if (pathname === "/api/platforms") return true;
@@ -148,6 +174,8 @@ function anonymousAllows(method, pathname) {
148
174
  }
149
175
  // Asking for a sign-in link is the one thing a stranger may post besides a run.
150
176
  if (method === "POST" && pathname === "/api/auth/link") return true;
177
+ // The cloud is "coming soon": an address to tell when it is, nothing more (ADR-0011 §3).
178
+ if (method === "POST" && pathname === "/api/cloud/interest") return true;
151
179
  // A visitor may start a read-only audit, and may *ask* about the other kinds of target so the
152
180
  // Studio can say where they actually run. A bare 401 reads as "broken" to someone who typed a
153
181
  // repo into the landing page, which is how five of its six examples used to dead-end.
@@ -170,14 +198,32 @@ function accountAllows(method, pathname) {
170
198
  if (method === "POST" && (pathname === "/api/alerts" || pathname === "/api/alerts/test")) return true;
171
199
  // Personal access tokens: the owner's coding agent acting as them (ADR-0009 slice 4).
172
200
  if (method === "POST" && pathname === "/api/tokens") return true;
201
+ // The deployment's owner marks an account paid or extends its trial; the handler checks who.
202
+ if (method === "POST" && pathname === "/api/admin/plan") return true;
173
203
  if (method === "DELETE" && /^\/api\/tokens\/[a-f0-9]{12}$/.test(pathname)) return true;
174
204
  if (method === "DELETE" && /^\/api\/actors\/[A-Za-z0-9.:-]{1,253}\/[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(pathname)) return true;
175
205
  // Journeys: keep a proven run, replay it, forget it (ADR-0009 slice 3).
176
206
  if (method === "POST" && (/^\/api\/captures\/[A-Za-z0-9._-]{1,128}\/keep$/.test(pathname) || pathname === "/api/operations/run-flow" || pathname === "/api/journeys")) return true;
207
+ // A journey run on the owner's own machine reports how it went (ADR-0011 §4).
208
+ if (method === "POST" && pathname === "/api/journeys/report") return true;
177
209
  if (method === "DELETE" && /^\/api\/journeys\/[a-z0-9-]{1,60}$/.test(pathname)) return true;
178
210
  return false;
179
211
  }
180
212
 
213
+ // Starting a cloud run — going inside a site, keeping or replaying a journey, importing one —
214
+ // is what a plan or a free trial buys (ADR-0011 §3). Reading what you own is not gated, so a
215
+ // lapsed trial can still see its journeys, test accounts and tokens, and forget them.
216
+ function cloudRunRoute(method, pathname) {
217
+ if (method !== "POST") return false;
218
+ return pathname === "/api/operations/explore" || pathname === "/api/operations/run-flow" || pathname === "/api/journeys"
219
+ || /^\/api\/captures\/[A-Za-z0-9._-]{1,128}\/keep$/.test(pathname);
220
+ }
221
+
222
+ function trialEndedMessage(plan) {
223
+ const when = plan?.endsAt ? ` on ${String(plan.endsAt).slice(0, 10)}` : "";
224
+ return `Your free trial ended${when}. Cloud runs — going inside a site, kept journeys and daily checks — are for accounts on a plan. Write to hello@runtapp.com, or run everything on your own machine, where nothing is gated: npx -y @aarwitz/tapp@latest app`;
225
+ }
226
+
181
227
  // One visitor may start a bounded number of audits per hour. Each audit drives a real browser
182
228
  // over as many as 20 pages, so this is about the machine, not about abuse alone.
183
229
  const AUDIT_LIMIT_PER_HOUR = 10;
@@ -213,7 +259,7 @@ function visibleToOwner(captureId, owner) {
213
259
 
214
260
  // Read-only website audits live in the captures directory like every other run; the Studio
215
261
  // lists the ones with a summary file. Newest first, bounded.
216
- function listAudits(limit = 50, owner = null) {
262
+ function listAudits(limit = 50, owner = null, hosted = false) {
217
263
  const root = captureRoot();
218
264
  let names;
219
265
  try { names = fs.readdirSync(root); } catch { return []; }
@@ -224,6 +270,7 @@ function listAudits(limit = 50, owner = null) {
224
270
  const summaryPath = path.join(root, name, "audit.json");
225
271
  let summary;
226
272
  try { summary = JSON.parse(fs.readFileSync(summaryPath, "utf8")); } catch { continue; }
273
+ if (hosted) summary = withAuditPageUrls(summary);
227
274
  const provenance = readCaptureProvenance(path.join(root, name));
228
275
  audits.push({
229
276
  id: name, createdAt: provenance?.createdAt || fs.statSync(summaryPath).mtime.toISOString(),
@@ -358,7 +405,125 @@ async function replayJourney({ store, slug, flow, actorRoot = "", ownerKey = nul
358
405
  // due when its last result is older than the interval (TAPP_JOURNEY_CHECK_HOURS, default 24);
359
406
  // a restart therefore does not re-run everything, and a busy lane simply waits for the next tick.
360
407
  export function dueJourneys(journeys, { intervalMs, now = Date.now() }) {
361
- return journeys.filter((j) => (j.platform || "web") === "web" && (!j.status || now - Date.parse(j.status.at || 0) >= intervalMs));
408
+ // A reported journey runs on somebody's own machine; the cloud has no flow to replay.
409
+ return journeys.filter((j) => j.source !== "reported" && (j.platform || "web") === "web" && (!j.status || now - Date.parse(j.status.at || 0) >= intervalMs));
410
+ }
411
+
412
+ // ADR-0011 §4: results flow up, the browser never reaches down. A self-hosted Studio can be
413
+ // linked to an account on a hosted one with a token the owner created there; from then on a
414
+ // journey run here reports its name and result to that account. The link lives beside the
415
+ // machine's other state, readable by this user only. Never on a hosted Studio: its account IS
416
+ // the account.
417
+ function studioLinkPath() {
418
+ return path.join(process.env.TAPP_HOME || path.join(os.homedir(), ".tapp"), "studio-link.json");
419
+ }
420
+ function readStudioLink() {
421
+ try {
422
+ const link = JSON.parse(fs.readFileSync(studioLinkPath(), "utf8"));
423
+ return link && typeof link.origin === "string" && typeof link.token === "string" ? link : null;
424
+ } catch { return null; }
425
+ }
426
+ function writeStudioLink(link) {
427
+ const file = studioLinkPath();
428
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
429
+ fs.writeFileSync(file, JSON.stringify(link), { mode: 0o600 });
430
+ }
431
+ function studioLinkSummary() {
432
+ const link = readStudioLink();
433
+ return link ? { origin: link.origin, email: link.email || "", linkedAt: link.linkedAt || null } : null;
434
+ }
435
+
436
+ // The person's own agent drives tapp from the chat (ADR-0012). Which one, and the session each
437
+ // chat thread continues, live beside the machine's other state.
438
+ function agentRoot() {
439
+ return path.join(process.env.TAPP_HOME || path.join(os.homedir(), ".tapp"), "agent");
440
+ }
441
+ function readJsonFile(file, fallback) {
442
+ try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch { return fallback; }
443
+ }
444
+ function writeJsonFile(file, value) {
445
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
446
+ fs.writeFileSync(file, JSON.stringify(value), { mode: 0o600 });
447
+ }
448
+ function selectedEngineId(engines) {
449
+ const chosen = String(readJsonFile(path.join(agentRoot(), "engine.json"), {}).engine || "");
450
+ if (chosen && engines.some((e) => e.id === chosen)) return chosen;
451
+ return engines.find((e) => e.usable && e.drives)?.id || engines.find((e) => e.usable)?.id || "";
452
+ }
453
+ // What the agent is told beyond its own defaults: the tapp skill (how to use the tools), and
454
+ // that it is in the Studio for the owner of this machine, with no shell.
455
+ function agentSystemPromptFile() {
456
+ const file = path.join(agentRoot(), "system.md");
457
+ const skill = (() => { try { return fs.readFileSync(path.join(packageRoot, "skills", "tapp", "SKILL.md"), "utf8"); } catch { return ""; } })();
458
+ const studio = [
459
+ "# You are in the tapp Studio",
460
+ "You are driving tapp from its Studio on this machine, for the person who owns it, through the `tapp_*` MCP tools. You have no shell and cannot edit files; tapp's tools are how you act, and reading the project is how you orient. Keep replies short — the Studio shows screenshots and evidence beside the chat — and say plainly what you observed, what you could not, and what you did not try. Never claim a screen or journey works from source alone.",
461
+ ].join("\n\n");
462
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
463
+ fs.writeFileSync(file, `${skill}\n\n${studio}\n`, { mode: 0o600 });
464
+ return file;
465
+ }
466
+
467
+ // An Anthropic API key the person pasted in the Studio: the fallback brain when no agent is
468
+ // signed in with a plan (ADR-0012 §4). Kept 0600 beside the machine's other state; shown only
469
+ // by its last four characters; handed to Claude Code only when it is NOT signed in with a plan,
470
+ // because an ANTHROPIC_API_KEY in the environment would override the plan and bill per use.
471
+ function apiKeyPath() { return path.join(agentRoot(), "anthropic-api-key"); }
472
+ function readApiKey() { try { return fs.readFileSync(apiKeyPath(), "utf8").trim(); } catch { return ""; } }
473
+ function apiKeySummary() { const key = readApiKey(); return { set: !!key, hint: key ? `…${key.slice(-4)}` : "" }; }
474
+ async function verifyAnthropicKey(key) {
475
+ // The models list costs nothing and answers 401 for a bad key.
476
+ const response = await fetch("https://api.anthropic.com/v1/models?limit=1", { headers: { "x-api-key": key, "anthropic-version": "2023-06-01" } });
477
+ return response.ok;
478
+ }
479
+ // With a key on file, Claude Code works without a plan (billing per use); say so in its row.
480
+ function withApiKey(engines) {
481
+ const key = readApiKey();
482
+ if (!key) return engines;
483
+ return engines.map((engine) => {
484
+ if (engine.id !== "claude" || engine.state === "missing" || engine.billing === "plan") return engine;
485
+ return { ...engine, state: "warning", usable: true, billing: "api-key", detail: "API key on file, which bills per use.", fix: "Sign in with your Claude account instead to use your plan: run `claude`, then /login." };
486
+ });
487
+ }
488
+
489
+ // What a person needs on THIS machine for each thing tapp drives, from `tapp doctor` — the one
490
+ // place that already knows whether Xcode is installed, a simulator is booted, adb exists, the
491
+ // Accessibility permission is granted. The setup card shows these with the exact fix.
492
+ function setupTargets(report, platform = process.platform) {
493
+ const p = report?.platforms || {};
494
+ const mac = platform === "darwin";
495
+ const item = (ok, text, fix = "") => ({ ok: !!ok, text, fix: ok ? "" : fix });
496
+ const targets = [
497
+ { id: "web", label: "Web", items: [
498
+ item(p.web?.available, p.web?.available ? "Chromium for Playwright is installed" : "Chromium for Playwright is not installed yet", "tapp downloads it on the first web run; nothing to do."),
499
+ ] },
500
+ { id: "ios", label: "iOS", items: mac ? [
501
+ item(p.ios?.xcode, p.ios?.xcode ? `${p.ios.xcode}` : "Xcode is not installed", "Install Xcode from the App Store and open it once to finish its setup."),
502
+ item(p.ios?.bootedSimulator, p.ios?.bootedSimulator ? `${p.ios.bootedSimulator} is booted` : "No simulator is booted", "tapp boots one when a run needs it; or open Simulator.app."),
503
+ ] : [item(false, "iOS runs on a Mac", "A Mac with Xcode runs iOS; this machine cannot.")] },
504
+ { id: "android", label: "Android", items: [
505
+ item(p.android?.adb, p.android?.adb ? "The Android SDK (adb) is installed" : "The Android SDK (adb) is not installed", "Install Android Studio or the command-line tools; set ANDROID_HOME if tapp still cannot find adb."),
506
+ item((p.android?.devicesConnected || 0) > 0, (p.android?.devicesConnected || 0) > 0 ? `${p.android.devicesConnected} device(s) connected` : "No device or emulator is connected", "Plug in a phone with USB debugging allowed, or start an emulator from Android Studio."),
507
+ ] },
508
+ { id: "macos", label: "macOS app", items: mac ? [
509
+ item(p.macos?.accessibility, p.macos?.accessibility ? "Accessibility permission granted" : "Accessibility permission not granted", "System Settings → Privacy & Security → Accessibility: allow the app that runs tapp (your terminal, or Node)."),
510
+ ] : [item(false, "macOS apps run on a Mac", "A Mac runs macOS apps; this machine cannot.")] },
511
+ { id: "windows", label: "Windows app", items: [item(false, "No Windows driver yet", "It is being built; early Windows runs are set up with us — hello@runtapp.com.")] },
512
+ ];
513
+ // A target is ready when nothing on its list is missing — web counts as ready because the one
514
+ // thing it needs arrives by itself.
515
+ return targets.map((target) => ({ ...target, ready: target.id === "web" ? true : target.items.every((i) => i.ok) }));
516
+ }
517
+
518
+ // The Codex device sign-in (ADR-0012): `codex login --device-auth` prints a link and a one-time
519
+ // code and waits for the person to finish on any device. tapp shows those two things and polls.
520
+ // Started only when Codex is not signed in — starting the flow discards an existing sign-in.
521
+ const ANSI = /\u001b\[[0-9;]*m/g;
522
+ function parseDeviceAuth(text) {
523
+ const plain = String(text).replace(ANSI, "");
524
+ const url = plain.match(/https:\/\/\S+/)?.[0] || "";
525
+ const code = plain.match(/\b[A-Z0-9]{4,6}-[A-Z0-9]{4,6}\b/)?.[0] || "";
526
+ return url && code ? { url, code } : null;
362
527
  }
363
528
 
364
529
  function openBrowser(url) {
@@ -483,6 +648,23 @@ function hostedRepository(repository) {
483
648
  return safe;
484
649
  }
485
650
 
651
+ // Website paths like /services.html look like files to hostedPayload. Resolve only
652
+ // page identifiers corroborated by the audit's own visited URLs; keep file redaction intact.
653
+ export function withAuditPageUrls(audit) {
654
+ const urls = new Map();
655
+ for (const page of audit.pages || []) {
656
+ try {
657
+ const url = new URL(page.url);
658
+ if (url.protocol === "http:" || url.protocol === "https:") urls.set(url.pathname + url.search, url.href);
659
+ } catch { /* Older or incomplete captures may have no page URL. */ }
660
+ }
661
+ const label = value => urls.get(value) || value;
662
+ const located = item => ({ ...item, ...(item.pages ? { pages: item.pages.map(label) } : {}), ...(item.screen ? { screen: label(item.screen) } : {}) });
663
+ return { ...audit, issues: (audit.issues || []).map(located), observations: (audit.observations || []).map(located),
664
+ pages: (audit.pages || []).map(page => ({ ...page, findings: (page.findings || []).map(located), observations: (page.observations || []).map(located) })),
665
+ };
666
+ }
667
+
486
668
  function hostedPayload(value) {
487
669
  if (Array.isArray(value)) return value.map(hostedPayload);
488
670
  if (!value || typeof value !== "object") {
@@ -560,7 +742,7 @@ function serveLoginPage(response, { failed = false, next = "" } = {}) {
560
742
  response.end(html);
561
743
  }
562
744
 
563
- export async function startBrowserProduct({ projectDir, port = 0, launch = false, workspaceRoot, githubProvider, publicOrigin = "", trustedProxyToken = "", directLogin = null, publicEgressOnly = null, publicAccess = false, accessVerifier = undefined, oauthExchange = null } = {}) {
745
+ export async function startBrowserProduct({ projectDir, port = 0, launch = false, workspaceRoot, githubProvider, publicOrigin = "", trustedProxyToken = "", directLogin = null, publicEgressOnly = null, publicAccess = false, accessVerifier = undefined, oauthExchange = null, doctor = null, apiKeyVerifier = null, connectOrigin = "" } = {}) {
564
746
  const hosted = !!trustedProxyToken || !!directLogin || !!publicAccess;
565
747
  // publicOrigin accepts a comma-separated allowlist; the first entry is canonical.
566
748
  const publicOrigins = String(publicOrigin || "").split(",").map((value) => value.trim().replace(/\/$/, "")).filter(Boolean);
@@ -626,6 +808,26 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
626
808
  const sessionToken = crypto.randomBytes(32).toString("base64url");
627
809
  const csrfToken = crypto.randomBytes(24).toString("base64url");
628
810
  const jobs = new Map();
811
+ // `tapp doctor --json` is the one place that knows what this machine has; it takes a few
812
+ // seconds (xcodebuild, adb), so the setup card reuses an answer for half a minute.
813
+ let doctorCache = { at: 0, report: null };
814
+ const runDoctor = doctor || (async () => {
815
+ const run = spawn(process.execPath, [path.join(packageRoot, "bin", "tapp.js"), "doctor", "--json"], { env: { ...process.env }, stdio: ["ignore", "pipe", "pipe"] });
816
+ let out = "";
817
+ run.stdout.on("data", (chunk) => { out += chunk; });
818
+ await new Promise((resolve) => { run.on("close", resolve); run.on("error", resolve); setTimeout(() => { try { run.kill(); } catch { /* done */ } resolve(); }, 60_000); });
819
+ try { return JSON.parse(out); } catch { return null; }
820
+ });
821
+ const doctorReport = async () => {
822
+ if (doctorCache.report && Date.now() - doctorCache.at < 30_000) return doctorCache.report;
823
+ const report = await runDoctor();
824
+ doctorCache = { at: Date.now(), report };
825
+ return report;
826
+ };
827
+ let deviceAuth = null; // { child, url, code, startedAt }
828
+ // A key pasted in an earlier run of this Studio serves tapp's own model features again after a
829
+ // restart; a key already in the environment is the operator's and is left alone.
830
+ if (!hosted && !process.env.ANTHROPIC_API_KEY && readApiKey()) process.env.ANTHROPIC_API_KEY = readApiKey();
629
831
  // A public Studio serves strangers, and until now it recorded nothing about that — the journal
630
832
  // held only startup lines, so "is anyone using this?" had no answer at all. These lines go to
631
833
  // stdout, which systemd already captures, so there is no new storage to run:
@@ -733,6 +935,10 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
733
935
  for (const accountId of owners) {
734
936
  const store = JourneyStore.forAccount(accountId);
735
937
  const ownerKey = `acct:${accountId}`;
938
+ // A daily check is a cloud run: a lapsed trial's journeys keep their last result and are
939
+ // not re-run until the account is on a plan again (ADR-0011 §3).
940
+ const record = accounts.getAccount(accountId);
941
+ if (record && !isAdmin(record) && !accounts.entitlement(record).allowed) continue;
736
942
  for (const journey of dueJourneys(store.list(), { intervalMs: checkIntervalMs })) {
737
943
  const flowPath = store.flowPath(journey.slug);
738
944
  let flow;
@@ -759,13 +965,33 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
759
965
  // The application uses bounded runtime style properties for map layout and
760
966
  // operation progress. Keep scripts locked to first-party files while
761
967
  // allowing those styles to render in both local and relayed deployments.
762
- "content-security-policy": "default-src 'self'; img-src 'self' data: blob:; media-src 'self' blob:; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
968
+ // A hosted page drives the runtime on the viewer's own machine (ADR-0011 §4): its fetches
969
+ // and the evidence images it shows come from that machine's loopback address, and nothing
970
+ // else. A local Studio talks only to itself.
971
+ "content-security-policy": `default-src 'self'; img-src 'self' data: blob:${hosted ? " http://127.0.0.1:* http://localhost:*" : ""}; media-src 'self' blob:${hosted ? " http://127.0.0.1:* http://localhost:*" : ""}; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self'${hosted ? " http://127.0.0.1:* http://localhost:*" : ""}; frame-ancestors 'none'; base-uri 'none'; form-action 'self'`,
763
972
  "referrer-policy": "no-referrer", "x-content-type-options": "nosniff", "x-frame-options": "DENY",
764
973
  };
765
974
  for (const [key, value] of Object.entries(baseHeaders)) response.setHeader(key, value);
766
975
 
767
976
  try {
768
- if (request.method === "GET" && url.searchParams.has("token")) {
977
+ // Driven from a hosted Studio (ADR-0011 §4, join B): exactly one foreign origin may call
978
+ // this runtime from a browser, with the launch secret as a bearer token instead of the
979
+ // cookie, and the browser's own local-network check is answered. Every other origin gets
980
+ // no CORS headers and so no answer the browser will show it.
981
+ const foreignOrigin = String(request.headers.origin || "");
982
+ const connectedCaller = !!connectOrigin && foreignOrigin === connectOrigin;
983
+ if (connectedCaller) {
984
+ response.setHeader("access-control-allow-origin", connectOrigin);
985
+ response.setHeader("vary", "Origin");
986
+ }
987
+ if (request.method === "OPTIONS") {
988
+ if (connectedCaller) {
989
+ response.writeHead(204, { "access-control-allow-methods": "GET,POST,DELETE,OPTIONS", "access-control-allow-headers": "authorization,content-type,x-tapp-csrf", "access-control-allow-private-network": "true", "access-control-max-age": "600" });
990
+ } else response.writeHead(204);
991
+ response.end();
992
+ return;
993
+ }
994
+ if (request.method === "GET" && url.pathname === "/" && url.searchParams.has("token")) {
769
995
  if (!sameSecret(url.searchParams.get("token"), sessionToken)) { response.writeHead(403); response.end("Invalid local session token"); return; }
770
996
  response.writeHead(303, { location: "/", "set-cookie": `${SESSION_COOKIE}=${encodeURIComponent(sessionToken)}; HttpOnly; SameSite=Strict; Path=/` });
771
997
  response.end();
@@ -776,7 +1002,12 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
776
1002
  return;
777
1003
  }
778
1004
  const proxyAuthenticated = !!trustedProxyToken && sameSecret(request.headers["x-tapp-proxy-token"], trustedProxyToken);
779
- const authenticated = proxyAuthenticated || sameSecret(cookies(request)[SESSION_COOKIE], sessionToken);
1005
+ // The operator from a hosted page: the launch secret as a bearer (fetches), or on the query
1006
+ // for the images a page cannot send headers with. Both only when something is connected.
1007
+ const operatorBearer = connectOrigin ? (/^Bearer\s+(\S+)$/i.exec(String(request.headers.authorization || ""))?.[1] || "") : "";
1008
+ const operatorQuery = connectOrigin && request.method === "GET" ? String(url.searchParams.get("token") || "") : "";
1009
+ const authenticated = proxyAuthenticated || sameSecret(cookies(request)[SESSION_COOKIE], sessionToken)
1010
+ || (!!operatorBearer && sameSecret(operatorBearer, sessionToken)) || (!!operatorQuery && sameSecret(operatorQuery, sessionToken));
780
1011
 
781
1012
  // A public Studio lets anyone in without an account, but an anonymous visitor gets a far
782
1013
  // smaller surface than the operator: audit a public website, and read back only the
@@ -799,11 +1030,21 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
799
1030
  // CSRF defends against a browser being made to act with its ambient cookie. A bearer token
800
1031
  // is never sent ambiently, so the check does not apply to it — and must not, or no agent
801
1032
  // could ever post anything.
802
- const guardMutation = (req) => { if (viaToken) return; requireMutationAuth(req, hosted ? publicOrigins : origin, csrfToken); };
1033
+ const guardMutation = (req) => { if (viaToken) return; requireMutationAuth(req, hosted ? publicOrigins : [origin, ...(connectOrigin ? [connectOrigin] : [])], csrfToken); };
803
1034
  if (account && !accountAllows(request.method, url.pathname)) {
804
1035
  json(response, 401, { error: "That part of the Studio runs on your own machine: npx -y @aarwitz/tapp@latest app" });
805
1036
  return;
806
1037
  }
1038
+ // The cloud beyond the visitor audit is for an account on a plan or in its free trial
1039
+ // (ADR-0011 §3). The deployment's owner is never gated on their own machine.
1040
+ if (account && !isAdmin(account) && cloudRunRoute(request.method, url.pathname)) {
1041
+ const plan = accounts.entitlement(account);
1042
+ if (!plan.allowed) {
1043
+ logUsage("refused", { account: account.id.slice(0, 8), reason: "trial-ended", method: request.method, path: url.pathname, status: 402 });
1044
+ json(response, 402, { error: trialEndedMessage(plan), plan });
1045
+ return;
1046
+ }
1047
+ }
807
1048
  if (publicAccess && !authenticated && !account) {
808
1049
  anonymous = true;
809
1050
  visitorId = String(cookies(request)[VISITOR_COOKIE] || "");
@@ -897,10 +1138,10 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
897
1138
  : {});
898
1139
  return;
899
1140
  }
900
- if (request.method === "GET" && url.pathname.startsWith("/assets/")) {
1141
+ if (["GET", "HEAD"].includes(request.method) && url.pathname.startsWith("/assets/")) {
901
1142
  const file = assetPath(url.pathname);
902
1143
  if (!file) { response.writeHead(404); response.end("Not found"); return; }
903
- serveFile(response, file);
1144
+ serveFile(response, file, { request });
904
1145
  return;
905
1146
  }
906
1147
  // Signing in: an email address gets a link; the link, used once, becomes a session cookie.
@@ -1037,6 +1278,147 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1037
1278
  json(response, 200, { name: journey.flow.name, slug: kept.slug, steps: journey.steps, screens: journey.screens, signedIn: journey.signedIn, path: registry.currentRoot() && !account ? path.relative(registry.currentRoot(), kept.path) : null });
1038
1279
  return;
1039
1280
  }
1281
+ // A journey that ran on the owner's own machine says how it went (ADR-0011 §4). The name
1282
+ // and the result are kept under the account; nothing else is accepted, and a change
1283
+ // between runs is announced the way a cloud check's would be.
1284
+ if (account && request.method === "POST" && url.pathname === "/api/journeys/report") {
1285
+ guardMutation(request);
1286
+ const body = await readJsonBody(request);
1287
+ const name = String(body.name || "").replace(/[\u0000-\u001f]/g, "").trim().slice(0, 120);
1288
+ if (!name) throw Object.assign(new Error("A report names the journey"), { statusCode: 400 });
1289
+ const platform = ["web", "ios", "android", "macos"].includes(body.platform) ? body.platform : "web";
1290
+ const machine = String(body.machine || "").replace(/[\u0000-\u001f]/g, "").trim().slice(0, 64);
1291
+ const count = (value) => Math.max(0, Math.min(10_000, Number.isFinite(Number(value)) ? Math.trunc(Number(value)) : 0));
1292
+ const at = Number.isFinite(Date.parse(body.at)) ? new Date(Date.parse(body.at)).toISOString() : null;
1293
+ const store = JourneyStore.forAccount(account.id);
1294
+ const previous = store.reported(slugify(name))?.status || null;
1295
+ const record = store.report({ name, platform, url: String(body.url || "").slice(0, 2048), steps: count(body.steps), machine, passed: body.passed === true, executed: count(body.executed), total: count(body.total), failed: count(body.failed), at });
1296
+ const change = alertForChange({ previous, current: record.status });
1297
+ if (change) {
1298
+ const alerts = AlertStore.forAccount(accounts.root, account.id);
1299
+ const settings = alerts.read();
1300
+ if (settings.webhook) {
1301
+ const alert = await deliverAlert({ webhook: settings.webhook, message: alertMessage({ kind: change, journey: `${name}${machine ? ` (on ${machine})` : ""}`, status: record.status, origin: publicOrigins[0] || "" }) });
1302
+ alerts.write({ lastDelivery: { at: new Date().toISOString(), journey: name, change, ...alert } });
1303
+ }
1304
+ }
1305
+ logUsage("journey.reported", { account: account.id.slice(0, 8), passed: record.status.passed, platform, change: change || null });
1306
+ json(response, 200, { ok: true, slug: record.slug, status: record.status, change: change || null });
1307
+ return;
1308
+ }
1309
+ // Linking this machine to an account on a hosted Studio (ADR-0011 §4). Operator only, and
1310
+ // only on a self-hosted Studio: a hosted one has nothing to link to but itself.
1311
+ if (!hosted && authenticated && url.pathname === "/api/studio-link") {
1312
+ if (request.method === "GET") { json(response, 200, { link: studioLinkSummary() }); return; }
1313
+ guardMutation(request);
1314
+ if (request.method === "DELETE") { try { fs.rmSync(studioLinkPath(), { force: true }); } catch { /* gone */ } json(response, 200, { ok: true, link: null }); return; }
1315
+ if (request.method === "POST") {
1316
+ const body = await readJsonBody(request);
1317
+ const { studioConfig, verifyStudioToken } = await import("./studio-client.js");
1318
+ let config;
1319
+ try { config = studioConfig({ studio: String(body.origin || "https://app.runtapp.com"), token: String(body.token || "") }, {}); }
1320
+ catch (error) { json(response, 400, { error: error.message }); return; }
1321
+ if (!config) { json(response, 400, { error: "A Studio URL is needed" }); return; }
1322
+ let who;
1323
+ try { who = await verifyStudioToken(config); }
1324
+ catch (error) { json(response, 400, { error: error.message }); return; }
1325
+ const link = { origin: config.origin, token: config.token, email: who.email, linkedAt: new Date().toISOString() };
1326
+ writeStudioLink(link);
1327
+ logUsage("studio.linked", { origin: config.origin });
1328
+ json(response, 200, { ok: true, link: studioLinkSummary() });
1329
+ return;
1330
+ }
1331
+ }
1332
+ // Setting this machine up (ADR-0012's journey): the runtime, the agent, what each target
1333
+ // needs with the exact fix, and the account. One answer, so the first screen can say
1334
+ // "3 of 4 ready" without four round trips. Operator only, local only.
1335
+ if (!hosted && authenticated && request.method === "GET" && url.pathname === "/api/setup") {
1336
+ const report = await doctorReport();
1337
+ const engines = withApiKey(detectEngines());
1338
+ json(response, 200, {
1339
+ runtime: { version: report?.version || "", node: report?.node?.version || process.versions.node, python: report?.python3?.ok ? (report.python3.version || "python3") : "", pyyaml: report?.pyyaml?.ok ?? null, disk: report?.disk || null, home: report?.home || "" },
1340
+ engines, selected: selectedEngineId(engines), apiKey: apiKeySummary(),
1341
+ deviceAuth: deviceAuth ? { engine: "codex", url: deviceAuth.url, code: deviceAuth.code, startedAt: deviceAuth.startedAt } : null,
1342
+ targets: setupTargets(report), platforms: platformStates({ hosted: false }),
1343
+ link: studioLinkSummary(),
1344
+ });
1345
+ return;
1346
+ }
1347
+ if (!hosted && authenticated && url.pathname === "/api/engines/api-key") {
1348
+ guardMutation(request);
1349
+ if (request.method === "DELETE") { try { fs.rmSync(apiKeyPath(), { force: true }); } catch { /* gone */ } delete process.env.ANTHROPIC_API_KEY; json(response, 200, { ok: true, apiKey: apiKeySummary() }); return; }
1350
+ if (request.method === "POST") {
1351
+ const body = await readJsonBody(request);
1352
+ const key = String(body.key || "").trim();
1353
+ if (!/^sk-ant-[A-Za-z0-9_-]{20,}$/.test(key)) { json(response, 400, { error: "That does not look like an Anthropic API key (they start with sk-ant-)." }); return; }
1354
+ let valid = false;
1355
+ try { valid = await (apiKeyVerifier || verifyAnthropicKey)(key); } catch (error) { json(response, 400, { error: `Could not check the key with Anthropic: ${error.message}` }); return; }
1356
+ if (!valid) { json(response, 400, { error: "Anthropic refused that key. Check it in the Console and paste it again." }); return; }
1357
+ fs.mkdirSync(agentRoot(), { recursive: true, mode: 0o700 });
1358
+ fs.writeFileSync(apiKeyPath(), `${key}\n`, { mode: 0o600 });
1359
+ process.env.ANTHROPIC_API_KEY = key;
1360
+ logUsage("apikey.set", {});
1361
+ json(response, 200, { ok: true, apiKey: apiKeySummary() });
1362
+ return;
1363
+ }
1364
+ }
1365
+ if (!hosted && authenticated && url.pathname === "/api/engines/codex/sign-in") {
1366
+ guardMutation(request);
1367
+ if (request.method === "DELETE") {
1368
+ if (deviceAuth) { try { deviceAuth.child.kill("SIGINT"); } catch { /* gone */ } deviceAuth = null; }
1369
+ json(response, 200, { ok: true });
1370
+ return;
1371
+ }
1372
+ if (request.method === "POST") {
1373
+ const codex = detectEngines().find((e) => e.id === "codex");
1374
+ if (!codex || codex.state === "missing") { json(response, 400, { error: ENGINES[1].install }); return; }
1375
+ if (codex.billing === "plan") { json(response, 200, { ok: true, alreadySignedIn: true }); return; }
1376
+ if (deviceAuth) { json(response, 200, { ok: true, url: deviceAuth.url, code: deviceAuth.code }); return; }
1377
+ const child = spawn(codex.binary, ["login", "--device-auth"], { stdio: ["ignore", "pipe", "pipe"] });
1378
+ let text = "";
1379
+ const parsed = await new Promise((resolve) => {
1380
+ const onData = (chunk) => { text += chunk; const found = parseDeviceAuth(text); if (found) resolve(found); };
1381
+ child.stdout.on("data", onData); child.stderr.on("data", onData);
1382
+ child.on("close", () => resolve(null));
1383
+ setTimeout(() => resolve(null), 15_000);
1384
+ });
1385
+ if (!parsed) { try { child.kill("SIGINT"); } catch { /* gone */ } json(response, 502, { error: "Codex did not offer a sign-in link. Run `codex login` in a terminal instead." }); return; }
1386
+ deviceAuth = { child, ...parsed, startedAt: new Date().toISOString() };
1387
+ child.on("close", () => { if (deviceAuth?.child === child) deviceAuth = null; });
1388
+ logUsage("codex.signin.started", {});
1389
+ json(response, 200, { ok: true, url: parsed.url, code: parsed.code });
1390
+ return;
1391
+ }
1392
+ }
1393
+ // Which coding agents are on this machine, signed in to whose plan, and which one drives
1394
+ // tapp from the chat (ADR-0012). Operator only, local only.
1395
+ if (!hosted && authenticated && url.pathname === "/api/engines") {
1396
+ const engines = withApiKey(detectEngines());
1397
+ if (request.method === "GET") { json(response, 200, { engines, selected: selectedEngineId(engines) }); return; }
1398
+ if (request.method === "POST") {
1399
+ guardMutation(request);
1400
+ const body = await readJsonBody(request);
1401
+ const engine = String(body.engine || "");
1402
+ if (!ENGINES.some((e) => e.id === engine)) { json(response, 400, { error: "Not an engine tapp knows" }); return; }
1403
+ writeJsonFile(path.join(agentRoot(), "engine.json"), { engine });
1404
+ json(response, 200, { ok: true, engines, selected: selectedEngineId(engines) });
1405
+ return;
1406
+ }
1407
+ }
1408
+ // "Tell me when the cloud is ready": an address and the date, in a file the owner reads.
1409
+ // No name, no IP, nothing else (ADR-0011 §3; the cloud is coming soon, not sold).
1410
+ if (hosted && request.method === "POST" && url.pathname === "/api/cloud/interest") {
1411
+ guardMutation(request);
1412
+ const body = await readJsonBody(request);
1413
+ const email = String(body.email || "").trim().toLowerCase();
1414
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || email.length > 254) { json(response, 400, { error: "That does not look like an email address." }); return; }
1415
+ const file = path.join(process.env.TAPP_HOME || path.join(os.homedir(), ".tapp"), "cloud-interest.jsonl");
1416
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
1417
+ fs.appendFileSync(file, `${JSON.stringify({ at: new Date().toISOString(), email })}\n`, { mode: 0o600 });
1418
+ logUsage("cloud.interest", { visitor: (visitorId || "").slice(0, 8) });
1419
+ json(response, 200, { ok: true });
1420
+ return;
1421
+ }
1040
1422
  if (!anonymous && request.method === "GET" && url.pathname === "/api/journeys") {
1041
1423
  const store = journeyStore();
1042
1424
  const root = !account ? registry.currentRoot() : null;
@@ -1109,6 +1491,17 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1109
1491
  // What the owner of this deployment can see: how it is being used, who has an account, and
1110
1492
  // which journeys are failing. Never a credential — they are encrypted and never decrypted
1111
1493
  // for display — and never anyone's evidence.
1494
+ // The owner decides who is on a plan: mark an account paid, or give it a trial of so many
1495
+ // days from today. Anyone else asking gets 403, not a hint of who has an account.
1496
+ if (account && request.method === "POST" && url.pathname === "/api/admin/plan") {
1497
+ if (!isAdmin(account)) { json(response, 403, { error: "Only the owner of this deployment can do that" }); return; }
1498
+ guardMutation(request);
1499
+ const body = await readJsonBody(request);
1500
+ const plan = accounts.setPlan(String(body.accountId || ""), { kind: String(body.kind || ""), days: body.days });
1501
+ logUsage("plan.set", { account: String(body.accountId || "").slice(0, 8), kind: plan.kind, by: account.id.slice(0, 8) });
1502
+ json(response, 200, { ok: true, plan });
1503
+ return;
1504
+ }
1112
1505
  if (account && isAdmin(account) && request.method === "GET" && url.pathname === "/api/admin/overview") {
1113
1506
  const accountsRoot = accounts.root;
1114
1507
  const listAccounts = () => {
@@ -1127,7 +1520,8 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1127
1520
  }
1128
1521
  } catch { /* none yet */ }
1129
1522
  return {
1130
- email: record.email, createdAt: record.createdAt, lastSeenAt: record.lastSeenAt || null,
1523
+ id: record.id, email: record.email, createdAt: record.createdAt, lastSeenAt: record.lastSeenAt || null,
1524
+ plan: isAdmin(record) ? { kind: "owner", allowed: true, endsAt: null, daysLeft: null } : accounts.entitlement(record),
1131
1525
  journeys: journeys.length,
1132
1526
  failing: journeys.filter((j) => j.status && !j.status.passed).length,
1133
1527
  neverRun: journeys.filter((j) => !j.status).length,
@@ -1291,6 +1685,8 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1291
1685
  csrfToken, mode: "public", product: "Tapp", root: null, repository: null, repositories: [],
1292
1686
  contract: customerProductContract, supportedPlatforms: ["web"], runners: [],
1293
1687
  access: "account", email: account.email, signInProvider, signInOptions, viaToken, admin: isAdmin(account),
1688
+ // What the cloud will do for this account, and until when (ADR-0011 §3).
1689
+ plan: isAdmin(account) ? { kind: "owner", allowed: true, endsAt: null, daysLeft: null } : accounts.entitlement(account),
1294
1690
  accepts: ["url"],
1295
1691
  selfHostOnly: ["path", "github", "bundle", "app", "apk"],
1296
1692
  // What tapp drives, and what THIS machine can start. The Studio shows all of it:
@@ -1316,11 +1712,11 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1316
1712
  });
1317
1713
  return;
1318
1714
  }
1319
- json(response, 200, { csrfToken, mode: hosted ? "managed" : "local", product: "Tapp", root: hosted ? null : registry.currentRoot(), repository: hosted ? hostedRepository(registry.current()) : registry.current(), repositories: hosted ? registry.list().map(hostedRepository) : registry.list(), contract: customerProductContract, supportedPlatforms: customerProductContract.targetPlatforms, runners: runnerSummary({ hosted }), platforms: platformStates({ hosted }) });
1715
+ json(response, 200, { csrfToken, mode: hosted ? "managed" : "local", product: "Tapp", root: hosted ? null : registry.currentRoot(), repository: hosted ? hostedRepository(registry.current()) : registry.current(), repositories: hosted ? registry.list().map(hostedRepository) : registry.list(), contract: customerProductContract, supportedPlatforms: customerProductContract.targetPlatforms, runners: runnerSummary({ hosted }), platforms: platformStates({ hosted }), studioLink: hosted ? null : studioLinkSummary(), connectOrigin: hosted ? "" : connectOrigin });
1320
1716
  return;
1321
1717
  }
1322
1718
  if (request.method === "GET" && url.pathname === "/api/repositories") { json(response, 200, hosted ? { current:hostedRepository(registry.current()), repositories:registry.list().map(hostedRepository) } : { current: registry.current(), repositories: registry.list() }); return; }
1323
- if (request.method === "GET" && url.pathname === "/api/audits") { const audits = listAudits(50, evidenceOwner); const explores = anonymous ? [] : listBuildExplores(50, evidenceOwner); json(response, 200, { audits: hosted ? hostedPayload(audits) : audits, explores: hosted ? hostedPayload(explores) : explores }); return; }
1719
+ if (request.method === "GET" && url.pathname === "/api/audits") { const audits = listAudits(50, evidenceOwner, hosted); const explores = anonymous ? [] : listBuildExplores(50, evidenceOwner); json(response, 200, { audits: hosted ? hostedPayload(audits) : audits, explores: hosted ? hostedPayload(explores) : explores }); return; }
1324
1720
  const filesMatch = url.pathname.match(/^\/api\/captures\/([A-Za-z0-9._-]{1,128})\/files$/);
1325
1721
  if (request.method === "GET" && filesMatch) {
1326
1722
  if (!visibleToOwner(filesMatch[1], evidenceOwner)) { response.writeHead(404); response.end("Not found"); return; }
@@ -1450,7 +1846,12 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1450
1846
  return;
1451
1847
  }
1452
1848
  if (prompt.kind === "business") {
1453
- json(response, 200, { kind: "business", message: `I can't find a business's website or app from a name yet — paste its URL and I'll audit it read-only, or open its repository.` });
1849
+ if (body.searchAppStore === true) {
1850
+ const discovery = await discoverApps(prompt.value);
1851
+ json(response, 200, { kind: "business", ...discovery });
1852
+ return;
1853
+ }
1854
+ json(response, 200, { kind: "business", message: "Search the name in the App Store, or enter the website to audit it read-only." });
1454
1855
  return;
1455
1856
  }
1456
1857
  json(response, 200, { kind: prompt.kind, value: prompt.value });
@@ -1550,6 +1951,55 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1550
1951
  // Replay a committed journey from the open project's .tapp/flows/. Web journeys run here
1551
1952
  // with a recording; an iOS or Android journey needs the simulator or device, so it is
1552
1953
  // answered with the command to run it where that is.
1954
+ // A chat turn with the person's own agent (ADR-0012): Claude Code on this machine, on
1955
+ // their plan, with tapp's tools and no shell. One turn is one job on the operator's lane,
1956
+ // so it cannot run over a release check; a thread continues the same session.
1957
+ if (operation === "agent" || operation === "agent-stop") {
1958
+ if (hosted || anonymous || account) { json(response, 401, { error: "The chat drives the agent on your own machine: npx -y @aarwitz/tapp@latest app" }); return; }
1959
+ if (operation === "agent-stop") {
1960
+ const running = [...jobs.values()].find((j) => j.operation === "agent" && j.status === "running" && j.agent);
1961
+ if (!running) { json(response, 200, { ok: true, stopped: false }); return; }
1962
+ running.agent.stop();
1963
+ json(response, 200, { ok: true, stopped: true });
1964
+ return;
1965
+ }
1966
+ const prompt = String(body.prompt || "").trim();
1967
+ if (!prompt || prompt.length > 4000) throw Object.assign(new Error("Ask something, in under 4000 characters"), { statusCode: 400 });
1968
+ const thread = /^[a-z0-9-]{1,40}$/.test(String(body.thread || "")) ? String(body.thread) : "studio";
1969
+ const engines = withApiKey(detectEngines());
1970
+ const engine = engines.find((e) => e.id === selectedEngineId(engines));
1971
+ if (!engine) throw Object.assign(new Error("No coding agent is signed in on this machine. Install Claude Code and sign in with your Claude account, then try again."), { statusCode: 400 });
1972
+ if (!engine.usable) throw Object.assign(new Error(`${engine.label}: ${engine.detail} ${engine.fix}`.trim()), { statusCode: 400 });
1973
+ if (!engine.drives) throw Object.assign(new Error(`${engine.label} is found and signed in, but driving tapp from the chat runs on Claude Code for now. Choose Claude Code under “Your agent”.`), { statusCode: 400 });
1974
+ const threadsFile = path.join(agentRoot(), "threads.json");
1975
+ const threads = readJsonFile(threadsFile, {});
1976
+ const resume = String(threads[thread] || "");
1977
+ const root = registry.currentRoot();
1978
+ const cwd = root || agentRoot();
1979
+ fs.mkdirSync(cwd, { recursive: true });
1980
+ const args = claudeArguments({ prompt, resume, mcpConfig: tappMcpConfig({ packageRoot }), systemPromptFile: agentSystemPromptFile() });
1981
+ const job = startJob(operation, async (progress) => {
1982
+ progress({ phase: "agent", text: resume ? "Continuing the thread." : "Starting a new thread." });
1983
+ // A plan is never overridden: the key goes into Claude Code's environment only when the
1984
+ // key is what this engine is running on.
1985
+ const childEnv = { ...process.env };
1986
+ if (engine.billing === "api-key" && readApiKey()) childEnv.ANTHROPIC_API_KEY = readApiKey(); else delete childEnv.ANTHROPIC_API_KEY;
1987
+ const run = runClaude({ binary: engine.binary, args, cwd, env: childEnv, onEvent: (event) => { for (const line of agentLines(event)) progress(line); } });
1988
+ job.agent = run;
1989
+ let outcome;
1990
+ try { outcome = await run.done; }
1991
+ catch (error) {
1992
+ // A thread that no longer exists on disk must not wedge the chat: start a fresh one.
1993
+ if (resume && /No conversation found|session/i.test(error.message)) { delete threads[thread]; writeJsonFile(threadsFile, threads); }
1994
+ throw error;
1995
+ }
1996
+ if (outcome.sessionId) { threads[thread] = outcome.sessionId; writeJsonFile(threadsFile, threads); }
1997
+ logUsage("agent.turn", { engine: engine.id, billing: engine.billing, turns: outcome.turns, stopped: outcome.stopped, isError: outcome.isError });
1998
+ return { kind: "agent", engine: engine.id, thread, ...outcome };
1999
+ }, null, { lane: OPERATOR_LANE });
2000
+ json(response, 202, { job: publicJob(job, { hosted }) });
2001
+ return;
2002
+ }
1553
2003
  if (operation === "run-flow") {
1554
2004
  if (anonymous) { json(response, 401, { error: "Sign in to replay a journey" }); return; }
1555
2005
  const store = journeyStore();
@@ -1572,6 +2022,17 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1572
2022
  const job = startJob(operation, async (progress) => {
1573
2023
  const result = await replayJourney({ store, slug, flow, actorRoot: actorRootFor() || "", ownerKey, progress, alerts: account ? AlertStore.forAccount(accounts.root, account.id) : null, origin: publicOrigins[0] || "" });
1574
2024
  logUsage("journey.run", { owner: (ownerKey || "operator").slice(0, 13), passed: result.passed });
2025
+ // A run on this machine reports to the linked account: the name and how it went,
2026
+ // never the journey, a credential or a screenshot (ADR-0011 §4). Best effort — a
2027
+ // Studio that cannot be reached is said in the chat and never fails the run.
2028
+ const link = !hosted && !account ? readStudioLink() : null;
2029
+ if (link) {
2030
+ try {
2031
+ const { reportStudioJourney } = await import("./studio-client.js");
2032
+ await reportStudioJourney({ origin: link.origin, token: link.token }, { name: flow.name || slug, platform, url: flow.url || "", steps: (flow.steps || []).length, machine: os.hostname(), passed: result.passed, executed: result.executed, total: result.total, failed: result.failed, at: result.status?.at || null });
2033
+ progress({ phase: "replay", text: `Reported to ${link.origin} as ${link.email || "your account"}` });
2034
+ } catch (error) { progress({ phase: "replay", text: `Could not report to ${link.origin}: ${error.message}` }); }
2035
+ }
1575
2036
  return result;
1576
2037
  }, null, { lane: ownerKey || OPERATOR_LANE });
1577
2038
  job.ownerKey = ownerKey;
@@ -1613,7 +2074,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1613
2074
  findings: summary?.issueCount ?? (summary?.issues || []).length,
1614
2075
  seconds: Math.round((Date.now() - auditStartedMs) / 100) / 10,
1615
2076
  });
1616
- return hosted ? hostedPayload(summary) : summary;
2077
+ return hosted ? hostedPayload(withAuditPageUrls(summary)) : summary;
1617
2078
  }, null, { lane: ownerKey || OPERATOR_LANE });
1618
2079
  job.ownerKey = ownerKey;
1619
2080
  json(response, 202, { job: publicJob(job, { hosted }) });
@@ -1746,9 +2207,12 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1746
2207
  const address = server.address();
1747
2208
  origin = `http://127.0.0.1:${address.port}`;
1748
2209
  const launchUrl = `${origin}/?token=${encodeURIComponent(sessionToken)}`;
2210
+ // The hosted page learns where this runtime is from the URL fragment, which a browser never
2211
+ // sends to the hosted server: the secret stays between the page and this machine.
2212
+ const connectUrl = connectOrigin ? `${connectOrigin}/#connect=${encodeURIComponent(origin)}&token=${encodeURIComponent(sessionToken)}` : "";
1749
2213
  if (launch) openBrowser(launchUrl);
1750
2214
  return {
1751
- root: registry.currentRoot(), origin, launchUrl, server, registry,
2215
+ root: registry.currentRoot(), origin, launchUrl, connectUrl, openConnect: () => { if (connectUrl) openBrowser(connectUrl); }, server, registry,
1752
2216
  close: async () => {
1753
2217
  if (liveSession?.active) {
1754
2218
  const engine = await import("./index.js");