@aarwitz/tapp 0.35.8 → 0.35.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +2 -2
- package/bin/tapp.js +15 -2
- package/browser/app.css +40 -0
- package/browser/app.js +340 -27
- package/browser/index.html +39 -3
- package/browser/product-contract.js +1 -1
- package/browser/view-model.js +24 -0
- package/docs/BROWSER-PRODUCT.md +61 -1
- package/mcp-server/src/app-store-discovery.js +42 -0
- package/mcp-server/src/browser-product.js +351 -18
- package/mcp-server/src/engines.js +212 -0
- package/mcp-server/src/flow-runtime.js +9 -1
- package/mcp-server/src/platforms.js +18 -3
- package/mcp-server/src/web-explorer.js +24 -1
- package/mcp-server/src/web-flow.js +51 -2
- package/package.json +2 -2
|
@@ -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
|
-
|
|
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
|
-
|
|
87
|
-
|
|
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,35 @@ 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
|
-
|
|
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
|
-
|
|
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
|
+
// Chrome asked this as "private network" until 2025 and asks it as "local network"
|
|
990
|
+
// since; both answers are given, so either generation lets the page through.
|
|
991
|
+
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-allow-local-network": "true", "access-control-max-age": "600" });
|
|
992
|
+
} else response.writeHead(204);
|
|
993
|
+
response.end();
|
|
994
|
+
return;
|
|
995
|
+
}
|
|
996
|
+
if (request.method === "GET" && url.pathname === "/" && url.searchParams.has("token")) {
|
|
816
997
|
if (!sameSecret(url.searchParams.get("token"), sessionToken)) { response.writeHead(403); response.end("Invalid local session token"); return; }
|
|
817
998
|
response.writeHead(303, { location: "/", "set-cookie": `${SESSION_COOKIE}=${encodeURIComponent(sessionToken)}; HttpOnly; SameSite=Strict; Path=/` });
|
|
818
999
|
response.end();
|
|
@@ -823,7 +1004,12 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
823
1004
|
return;
|
|
824
1005
|
}
|
|
825
1006
|
const proxyAuthenticated = !!trustedProxyToken && sameSecret(request.headers["x-tapp-proxy-token"], trustedProxyToken);
|
|
826
|
-
|
|
1007
|
+
// The operator from a hosted page: the launch secret as a bearer (fetches), or on the query
|
|
1008
|
+
// for the images a page cannot send headers with. Both only when something is connected.
|
|
1009
|
+
const operatorBearer = connectOrigin ? (/^Bearer\s+(\S+)$/i.exec(String(request.headers.authorization || ""))?.[1] || "") : "";
|
|
1010
|
+
const operatorQuery = connectOrigin && request.method === "GET" ? String(url.searchParams.get("token") || "") : "";
|
|
1011
|
+
const authenticated = proxyAuthenticated || sameSecret(cookies(request)[SESSION_COOKIE], sessionToken)
|
|
1012
|
+
|| (!!operatorBearer && sameSecret(operatorBearer, sessionToken)) || (!!operatorQuery && sameSecret(operatorQuery, sessionToken));
|
|
827
1013
|
|
|
828
1014
|
// A public Studio lets anyone in without an account, but an anonymous visitor gets a far
|
|
829
1015
|
// smaller surface than the operator: audit a public website, and read back only the
|
|
@@ -846,7 +1032,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
846
1032
|
// CSRF defends against a browser being made to act with its ambient cookie. A bearer token
|
|
847
1033
|
// is never sent ambiently, so the check does not apply to it — and must not, or no agent
|
|
848
1034
|
// could ever post anything.
|
|
849
|
-
const guardMutation = (req) => { if (viaToken) return; requireMutationAuth(req, hosted ? publicOrigins : origin, csrfToken); };
|
|
1035
|
+
const guardMutation = (req) => { if (viaToken) return; requireMutationAuth(req, hosted ? publicOrigins : [origin, ...(connectOrigin ? [connectOrigin] : [])], csrfToken); };
|
|
850
1036
|
if (account && !accountAllows(request.method, url.pathname)) {
|
|
851
1037
|
json(response, 401, { error: "That part of the Studio runs on your own machine: npx -y @aarwitz/tapp@latest app" });
|
|
852
1038
|
return;
|
|
@@ -954,10 +1140,10 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
954
1140
|
: {});
|
|
955
1141
|
return;
|
|
956
1142
|
}
|
|
957
|
-
if (request.method
|
|
1143
|
+
if (["GET", "HEAD"].includes(request.method) && url.pathname.startsWith("/assets/")) {
|
|
958
1144
|
const file = assetPath(url.pathname);
|
|
959
1145
|
if (!file) { response.writeHead(404); response.end("Not found"); return; }
|
|
960
|
-
serveFile(response, file);
|
|
1146
|
+
serveFile(response, file, { request });
|
|
961
1147
|
return;
|
|
962
1148
|
}
|
|
963
1149
|
// Signing in: an email address gets a link; the link, used once, becomes a session cookie.
|
|
@@ -1145,6 +1331,96 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
1145
1331
|
return;
|
|
1146
1332
|
}
|
|
1147
1333
|
}
|
|
1334
|
+
// Setting this machine up (ADR-0012's journey): the runtime, the agent, what each target
|
|
1335
|
+
// needs with the exact fix, and the account. One answer, so the first screen can say
|
|
1336
|
+
// "3 of 4 ready" without four round trips. Operator only, local only.
|
|
1337
|
+
if (!hosted && authenticated && request.method === "GET" && url.pathname === "/api/setup") {
|
|
1338
|
+
const report = await doctorReport();
|
|
1339
|
+
const engines = withApiKey(detectEngines());
|
|
1340
|
+
json(response, 200, {
|
|
1341
|
+
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 || "" },
|
|
1342
|
+
engines, selected: selectedEngineId(engines), apiKey: apiKeySummary(),
|
|
1343
|
+
deviceAuth: deviceAuth ? { engine: "codex", url: deviceAuth.url, code: deviceAuth.code, startedAt: deviceAuth.startedAt } : null,
|
|
1344
|
+
targets: setupTargets(report), platforms: platformStates({ hosted: false }),
|
|
1345
|
+
link: studioLinkSummary(),
|
|
1346
|
+
});
|
|
1347
|
+
return;
|
|
1348
|
+
}
|
|
1349
|
+
if (!hosted && authenticated && url.pathname === "/api/engines/api-key") {
|
|
1350
|
+
guardMutation(request);
|
|
1351
|
+
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; }
|
|
1352
|
+
if (request.method === "POST") {
|
|
1353
|
+
const body = await readJsonBody(request);
|
|
1354
|
+
const key = String(body.key || "").trim();
|
|
1355
|
+
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; }
|
|
1356
|
+
let valid = false;
|
|
1357
|
+
try { valid = await (apiKeyVerifier || verifyAnthropicKey)(key); } catch (error) { json(response, 400, { error: `Could not check the key with Anthropic: ${error.message}` }); return; }
|
|
1358
|
+
if (!valid) { json(response, 400, { error: "Anthropic refused that key. Check it in the Console and paste it again." }); return; }
|
|
1359
|
+
fs.mkdirSync(agentRoot(), { recursive: true, mode: 0o700 });
|
|
1360
|
+
fs.writeFileSync(apiKeyPath(), `${key}\n`, { mode: 0o600 });
|
|
1361
|
+
process.env.ANTHROPIC_API_KEY = key;
|
|
1362
|
+
logUsage("apikey.set", {});
|
|
1363
|
+
json(response, 200, { ok: true, apiKey: apiKeySummary() });
|
|
1364
|
+
return;
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
if (!hosted && authenticated && url.pathname === "/api/engines/codex/sign-in") {
|
|
1368
|
+
guardMutation(request);
|
|
1369
|
+
if (request.method === "DELETE") {
|
|
1370
|
+
if (deviceAuth) { try { deviceAuth.child.kill("SIGINT"); } catch { /* gone */ } deviceAuth = null; }
|
|
1371
|
+
json(response, 200, { ok: true });
|
|
1372
|
+
return;
|
|
1373
|
+
}
|
|
1374
|
+
if (request.method === "POST") {
|
|
1375
|
+
const codex = detectEngines().find((e) => e.id === "codex");
|
|
1376
|
+
if (!codex || codex.state === "missing") { json(response, 400, { error: ENGINES[1].install }); return; }
|
|
1377
|
+
if (codex.billing === "plan") { json(response, 200, { ok: true, alreadySignedIn: true }); return; }
|
|
1378
|
+
if (deviceAuth) { json(response, 200, { ok: true, url: deviceAuth.url, code: deviceAuth.code }); return; }
|
|
1379
|
+
const child = spawn(codex.binary, ["login", "--device-auth"], { stdio: ["ignore", "pipe", "pipe"] });
|
|
1380
|
+
let text = "";
|
|
1381
|
+
const parsed = await new Promise((resolve) => {
|
|
1382
|
+
const onData = (chunk) => { text += chunk; const found = parseDeviceAuth(text); if (found) resolve(found); };
|
|
1383
|
+
child.stdout.on("data", onData); child.stderr.on("data", onData);
|
|
1384
|
+
child.on("close", () => resolve(null));
|
|
1385
|
+
setTimeout(() => resolve(null), 15_000);
|
|
1386
|
+
});
|
|
1387
|
+
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; }
|
|
1388
|
+
deviceAuth = { child, ...parsed, startedAt: new Date().toISOString() };
|
|
1389
|
+
child.on("close", () => { if (deviceAuth?.child === child) deviceAuth = null; });
|
|
1390
|
+
logUsage("codex.signin.started", {});
|
|
1391
|
+
json(response, 200, { ok: true, url: parsed.url, code: parsed.code });
|
|
1392
|
+
return;
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
1395
|
+
// Which coding agents are on this machine, signed in to whose plan, and which one drives
|
|
1396
|
+
// tapp from the chat (ADR-0012). Operator only, local only.
|
|
1397
|
+
if (!hosted && authenticated && url.pathname === "/api/engines") {
|
|
1398
|
+
const engines = withApiKey(detectEngines());
|
|
1399
|
+
if (request.method === "GET") { json(response, 200, { engines, selected: selectedEngineId(engines) }); return; }
|
|
1400
|
+
if (request.method === "POST") {
|
|
1401
|
+
guardMutation(request);
|
|
1402
|
+
const body = await readJsonBody(request);
|
|
1403
|
+
const engine = String(body.engine || "");
|
|
1404
|
+
if (!ENGINES.some((e) => e.id === engine)) { json(response, 400, { error: "Not an engine tapp knows" }); return; }
|
|
1405
|
+
writeJsonFile(path.join(agentRoot(), "engine.json"), { engine });
|
|
1406
|
+
json(response, 200, { ok: true, engines, selected: selectedEngineId(engines) });
|
|
1407
|
+
return;
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
// "Tell me when the cloud is ready": an address and the date, in a file the owner reads.
|
|
1411
|
+
// No name, no IP, nothing else (ADR-0011 §3; the cloud is coming soon, not sold).
|
|
1412
|
+
if (hosted && request.method === "POST" && url.pathname === "/api/cloud/interest") {
|
|
1413
|
+
guardMutation(request);
|
|
1414
|
+
const body = await readJsonBody(request);
|
|
1415
|
+
const email = String(body.email || "").trim().toLowerCase();
|
|
1416
|
+
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || email.length > 254) { json(response, 400, { error: "That does not look like an email address." }); return; }
|
|
1417
|
+
const file = path.join(process.env.TAPP_HOME || path.join(os.homedir(), ".tapp"), "cloud-interest.jsonl");
|
|
1418
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
1419
|
+
fs.appendFileSync(file, `${JSON.stringify({ at: new Date().toISOString(), email })}\n`, { mode: 0o600 });
|
|
1420
|
+
logUsage("cloud.interest", { visitor: (visitorId || "").slice(0, 8) });
|
|
1421
|
+
json(response, 200, { ok: true });
|
|
1422
|
+
return;
|
|
1423
|
+
}
|
|
1148
1424
|
if (!anonymous && request.method === "GET" && url.pathname === "/api/journeys") {
|
|
1149
1425
|
const store = journeyStore();
|
|
1150
1426
|
const root = !account ? registry.currentRoot() : null;
|
|
@@ -1438,11 +1714,11 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
1438
1714
|
});
|
|
1439
1715
|
return;
|
|
1440
1716
|
}
|
|
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() });
|
|
1717
|
+
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
1718
|
return;
|
|
1443
1719
|
}
|
|
1444
1720
|
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; }
|
|
1721
|
+
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
1722
|
const filesMatch = url.pathname.match(/^\/api\/captures\/([A-Za-z0-9._-]{1,128})\/files$/);
|
|
1447
1723
|
if (request.method === "GET" && filesMatch) {
|
|
1448
1724
|
if (!visibleToOwner(filesMatch[1], evidenceOwner)) { response.writeHead(404); response.end("Not found"); return; }
|
|
@@ -1572,7 +1848,12 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
1572
1848
|
return;
|
|
1573
1849
|
}
|
|
1574
1850
|
if (prompt.kind === "business") {
|
|
1575
|
-
|
|
1851
|
+
if (body.searchAppStore === true) {
|
|
1852
|
+
const discovery = await discoverApps(prompt.value);
|
|
1853
|
+
json(response, 200, { kind: "business", ...discovery });
|
|
1854
|
+
return;
|
|
1855
|
+
}
|
|
1856
|
+
json(response, 200, { kind: "business", message: "Search the name in the App Store, or enter the website to audit it read-only." });
|
|
1576
1857
|
return;
|
|
1577
1858
|
}
|
|
1578
1859
|
json(response, 200, { kind: prompt.kind, value: prompt.value });
|
|
@@ -1672,6 +1953,55 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
1672
1953
|
// Replay a committed journey from the open project's .tapp/flows/. Web journeys run here
|
|
1673
1954
|
// with a recording; an iOS or Android journey needs the simulator or device, so it is
|
|
1674
1955
|
// answered with the command to run it where that is.
|
|
1956
|
+
// A chat turn with the person's own agent (ADR-0012): Claude Code on this machine, on
|
|
1957
|
+
// their plan, with tapp's tools and no shell. One turn is one job on the operator's lane,
|
|
1958
|
+
// so it cannot run over a release check; a thread continues the same session.
|
|
1959
|
+
if (operation === "agent" || operation === "agent-stop") {
|
|
1960
|
+
if (hosted || anonymous || account) { json(response, 401, { error: "The chat drives the agent on your own machine: npx -y @aarwitz/tapp@latest app" }); return; }
|
|
1961
|
+
if (operation === "agent-stop") {
|
|
1962
|
+
const running = [...jobs.values()].find((j) => j.operation === "agent" && j.status === "running" && j.agent);
|
|
1963
|
+
if (!running) { json(response, 200, { ok: true, stopped: false }); return; }
|
|
1964
|
+
running.agent.stop();
|
|
1965
|
+
json(response, 200, { ok: true, stopped: true });
|
|
1966
|
+
return;
|
|
1967
|
+
}
|
|
1968
|
+
const prompt = String(body.prompt || "").trim();
|
|
1969
|
+
if (!prompt || prompt.length > 4000) throw Object.assign(new Error("Ask something, in under 4000 characters"), { statusCode: 400 });
|
|
1970
|
+
const thread = /^[a-z0-9-]{1,40}$/.test(String(body.thread || "")) ? String(body.thread) : "studio";
|
|
1971
|
+
const engines = withApiKey(detectEngines());
|
|
1972
|
+
const engine = engines.find((e) => e.id === selectedEngineId(engines));
|
|
1973
|
+
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 });
|
|
1974
|
+
if (!engine.usable) throw Object.assign(new Error(`${engine.label}: ${engine.detail} ${engine.fix}`.trim()), { statusCode: 400 });
|
|
1975
|
+
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 });
|
|
1976
|
+
const threadsFile = path.join(agentRoot(), "threads.json");
|
|
1977
|
+
const threads = readJsonFile(threadsFile, {});
|
|
1978
|
+
const resume = String(threads[thread] || "");
|
|
1979
|
+
const root = registry.currentRoot();
|
|
1980
|
+
const cwd = root || agentRoot();
|
|
1981
|
+
fs.mkdirSync(cwd, { recursive: true });
|
|
1982
|
+
const args = claudeArguments({ prompt, resume, mcpConfig: tappMcpConfig({ packageRoot }), systemPromptFile: agentSystemPromptFile() });
|
|
1983
|
+
const job = startJob(operation, async (progress) => {
|
|
1984
|
+
progress({ phase: "agent", text: resume ? "Continuing the thread." : "Starting a new thread." });
|
|
1985
|
+
// A plan is never overridden: the key goes into Claude Code's environment only when the
|
|
1986
|
+
// key is what this engine is running on.
|
|
1987
|
+
const childEnv = { ...process.env };
|
|
1988
|
+
if (engine.billing === "api-key" && readApiKey()) childEnv.ANTHROPIC_API_KEY = readApiKey(); else delete childEnv.ANTHROPIC_API_KEY;
|
|
1989
|
+
const run = runClaude({ binary: engine.binary, args, cwd, env: childEnv, onEvent: (event) => { for (const line of agentLines(event)) progress(line); } });
|
|
1990
|
+
job.agent = run;
|
|
1991
|
+
let outcome;
|
|
1992
|
+
try { outcome = await run.done; }
|
|
1993
|
+
catch (error) {
|
|
1994
|
+
// A thread that no longer exists on disk must not wedge the chat: start a fresh one.
|
|
1995
|
+
if (resume && /No conversation found|session/i.test(error.message)) { delete threads[thread]; writeJsonFile(threadsFile, threads); }
|
|
1996
|
+
throw error;
|
|
1997
|
+
}
|
|
1998
|
+
if (outcome.sessionId) { threads[thread] = outcome.sessionId; writeJsonFile(threadsFile, threads); }
|
|
1999
|
+
logUsage("agent.turn", { engine: engine.id, billing: engine.billing, turns: outcome.turns, stopped: outcome.stopped, isError: outcome.isError });
|
|
2000
|
+
return { kind: "agent", engine: engine.id, thread, ...outcome };
|
|
2001
|
+
}, null, { lane: OPERATOR_LANE });
|
|
2002
|
+
json(response, 202, { job: publicJob(job, { hosted }) });
|
|
2003
|
+
return;
|
|
2004
|
+
}
|
|
1675
2005
|
if (operation === "run-flow") {
|
|
1676
2006
|
if (anonymous) { json(response, 401, { error: "Sign in to replay a journey" }); return; }
|
|
1677
2007
|
const store = journeyStore();
|
|
@@ -1746,7 +2076,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
1746
2076
|
findings: summary?.issueCount ?? (summary?.issues || []).length,
|
|
1747
2077
|
seconds: Math.round((Date.now() - auditStartedMs) / 100) / 10,
|
|
1748
2078
|
});
|
|
1749
|
-
return hosted ? hostedPayload(summary) : summary;
|
|
2079
|
+
return hosted ? hostedPayload(withAuditPageUrls(summary)) : summary;
|
|
1750
2080
|
}, null, { lane: ownerKey || OPERATOR_LANE });
|
|
1751
2081
|
job.ownerKey = ownerKey;
|
|
1752
2082
|
json(response, 202, { job: publicJob(job, { hosted }) });
|
|
@@ -1879,9 +2209,12 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
1879
2209
|
const address = server.address();
|
|
1880
2210
|
origin = `http://127.0.0.1:${address.port}`;
|
|
1881
2211
|
const launchUrl = `${origin}/?token=${encodeURIComponent(sessionToken)}`;
|
|
2212
|
+
// The hosted page learns where this runtime is from the URL fragment, which a browser never
|
|
2213
|
+
// sends to the hosted server: the secret stays between the page and this machine.
|
|
2214
|
+
const connectUrl = connectOrigin ? `${connectOrigin}/#connect=${encodeURIComponent(origin)}&token=${encodeURIComponent(sessionToken)}` : "";
|
|
1882
2215
|
if (launch) openBrowser(launchUrl);
|
|
1883
2216
|
return {
|
|
1884
|
-
root: registry.currentRoot(), origin, launchUrl, server, registry,
|
|
2217
|
+
root: registry.currentRoot(), origin, launchUrl, connectUrl, openConnect: () => { if (connectUrl) openBrowser(connectUrl); }, server, registry,
|
|
1885
2218
|
close: async () => {
|
|
1886
2219
|
if (liveSession?.active) {
|
|
1887
2220
|
const engine = await import("./index.js");
|