@aarwitz/tapp 0.35.8 → 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.
@@ -231,7 +259,7 @@ function visibleToOwner(captureId, owner) {
231
259
 
232
260
  // Read-only website audits live in the captures directory like every other run; the Studio
233
261
  // lists the ones with a summary file. Newest first, bounded.
234
- function listAudits(limit = 50, owner = null) {
262
+ function listAudits(limit = 50, owner = null, hosted = false) {
235
263
  const root = captureRoot();
236
264
  let names;
237
265
  try { names = fs.readdirSync(root); } catch { return []; }
@@ -242,6 +270,7 @@ function listAudits(limit = 50, owner = null) {
242
270
  const summaryPath = path.join(root, name, "audit.json");
243
271
  let summary;
244
272
  try { summary = JSON.parse(fs.readFileSync(summaryPath, "utf8")); } catch { continue; }
273
+ if (hosted) summary = withAuditPageUrls(summary);
245
274
  const provenance = readCaptureProvenance(path.join(root, name));
246
275
  audits.push({
247
276
  id: name, createdAt: provenance?.createdAt || fs.statSync(summaryPath).mtime.toISOString(),
@@ -404,6 +433,99 @@ function studioLinkSummary() {
404
433
  return link ? { origin: link.origin, email: link.email || "", linkedAt: link.linkedAt || null } : null;
405
434
  }
406
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;
527
+ }
528
+
407
529
  function openBrowser(url) {
408
530
  const invocation = process.platform === "darwin" ? ["open", [url]]
409
531
  : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]]
@@ -526,6 +648,23 @@ function hostedRepository(repository) {
526
648
  return safe;
527
649
  }
528
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
+
529
668
  function hostedPayload(value) {
530
669
  if (Array.isArray(value)) return value.map(hostedPayload);
531
670
  if (!value || typeof value !== "object") {
@@ -603,7 +742,7 @@ function serveLoginPage(response, { failed = false, next = "" } = {}) {
603
742
  response.end(html);
604
743
  }
605
744
 
606
- 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 = "" } = {}) {
607
746
  const hosted = !!trustedProxyToken || !!directLogin || !!publicAccess;
608
747
  // publicOrigin accepts a comma-separated allowlist; the first entry is canonical.
609
748
  const publicOrigins = String(publicOrigin || "").split(",").map((value) => value.trim().replace(/\/$/, "")).filter(Boolean);
@@ -669,6 +808,26 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
669
808
  const sessionToken = crypto.randomBytes(32).toString("base64url");
670
809
  const csrfToken = crypto.randomBytes(24).toString("base64url");
671
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();
672
831
  // A public Studio serves strangers, and until now it recorded nothing about that — the journal
673
832
  // held only startup lines, so "is anyone using this?" had no answer at all. These lines go to
674
833
  // stdout, which systemd already captures, so there is no new storage to run:
@@ -806,13 +965,33 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
806
965
  // The application uses bounded runtime style properties for map layout and
807
966
  // operation progress. Keep scripts locked to first-party files while
808
967
  // allowing those styles to render in both local and relayed deployments.
809
- "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'`,
810
972
  "referrer-policy": "no-referrer", "x-content-type-options": "nosniff", "x-frame-options": "DENY",
811
973
  };
812
974
  for (const [key, value] of Object.entries(baseHeaders)) response.setHeader(key, value);
813
975
 
814
976
  try {
815
- 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")) {
816
995
  if (!sameSecret(url.searchParams.get("token"), sessionToken)) { response.writeHead(403); response.end("Invalid local session token"); return; }
817
996
  response.writeHead(303, { location: "/", "set-cookie": `${SESSION_COOKIE}=${encodeURIComponent(sessionToken)}; HttpOnly; SameSite=Strict; Path=/` });
818
997
  response.end();
@@ -823,7 +1002,12 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
823
1002
  return;
824
1003
  }
825
1004
  const proxyAuthenticated = !!trustedProxyToken && sameSecret(request.headers["x-tapp-proxy-token"], trustedProxyToken);
826
- 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));
827
1011
 
828
1012
  // A public Studio lets anyone in without an account, but an anonymous visitor gets a far
829
1013
  // smaller surface than the operator: audit a public website, and read back only the
@@ -846,7 +1030,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
846
1030
  // CSRF defends against a browser being made to act with its ambient cookie. A bearer token
847
1031
  // is never sent ambiently, so the check does not apply to it — and must not, or no agent
848
1032
  // could ever post anything.
849
- 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); };
850
1034
  if (account && !accountAllows(request.method, url.pathname)) {
851
1035
  json(response, 401, { error: "That part of the Studio runs on your own machine: npx -y @aarwitz/tapp@latest app" });
852
1036
  return;
@@ -954,10 +1138,10 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
954
1138
  : {});
955
1139
  return;
956
1140
  }
957
- if (request.method === "GET" && url.pathname.startsWith("/assets/")) {
1141
+ if (["GET", "HEAD"].includes(request.method) && url.pathname.startsWith("/assets/")) {
958
1142
  const file = assetPath(url.pathname);
959
1143
  if (!file) { response.writeHead(404); response.end("Not found"); return; }
960
- serveFile(response, file);
1144
+ serveFile(response, file, { request });
961
1145
  return;
962
1146
  }
963
1147
  // Signing in: an email address gets a link; the link, used once, becomes a session cookie.
@@ -1145,6 +1329,96 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1145
1329
  return;
1146
1330
  }
1147
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
+ }
1148
1422
  if (!anonymous && request.method === "GET" && url.pathname === "/api/journeys") {
1149
1423
  const store = journeyStore();
1150
1424
  const root = !account ? registry.currentRoot() : null;
@@ -1438,11 +1712,11 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1438
1712
  });
1439
1713
  return;
1440
1714
  }
1441
- 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() });
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 });
1442
1716
  return;
1443
1717
  }
1444
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; }
1445
- 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; }
1446
1720
  const filesMatch = url.pathname.match(/^\/api\/captures\/([A-Za-z0-9._-]{1,128})\/files$/);
1447
1721
  if (request.method === "GET" && filesMatch) {
1448
1722
  if (!visibleToOwner(filesMatch[1], evidenceOwner)) { response.writeHead(404); response.end("Not found"); return; }
@@ -1572,7 +1846,12 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1572
1846
  return;
1573
1847
  }
1574
1848
  if (prompt.kind === "business") {
1575
- 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." });
1576
1855
  return;
1577
1856
  }
1578
1857
  json(response, 200, { kind: prompt.kind, value: prompt.value });
@@ -1672,6 +1951,55 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1672
1951
  // Replay a committed journey from the open project's .tapp/flows/. Web journeys run here
1673
1952
  // with a recording; an iOS or Android journey needs the simulator or device, so it is
1674
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
+ }
1675
2003
  if (operation === "run-flow") {
1676
2004
  if (anonymous) { json(response, 401, { error: "Sign in to replay a journey" }); return; }
1677
2005
  const store = journeyStore();
@@ -1746,7 +2074,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1746
2074
  findings: summary?.issueCount ?? (summary?.issues || []).length,
1747
2075
  seconds: Math.round((Date.now() - auditStartedMs) / 100) / 10,
1748
2076
  });
1749
- return hosted ? hostedPayload(summary) : summary;
2077
+ return hosted ? hostedPayload(withAuditPageUrls(summary)) : summary;
1750
2078
  }, null, { lane: ownerKey || OPERATOR_LANE });
1751
2079
  job.ownerKey = ownerKey;
1752
2080
  json(response, 202, { job: publicJob(job, { hosted }) });
@@ -1879,9 +2207,12 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1879
2207
  const address = server.address();
1880
2208
  origin = `http://127.0.0.1:${address.port}`;
1881
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)}` : "";
1882
2213
  if (launch) openBrowser(launchUrl);
1883
2214
  return {
1884
- root: registry.currentRoot(), origin, launchUrl, server, registry,
2215
+ root: registry.currentRoot(), origin, launchUrl, connectUrl, openConnect: () => { if (connectUrl) openBrowser(connectUrl); }, server, registry,
1885
2216
  close: async () => {
1886
2217
  if (liveSession?.active) {
1887
2218
  const engine = await import("./index.js");