agenttwin 0.3.35 → 0.3.36

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/dist/gateway.js CHANGED
@@ -2314,7 +2314,7 @@ function parseWorld(value3) {
2314
2314
  const services = /* @__PURE__ */ new Map();
2315
2315
  const requestPathFaults = /* @__PURE__ */ new Set();
2316
2316
  for (const service of v.services) {
2317
- if (!object2(service) || typeof service.name !== "string" || !namePattern.test(service.name) || services.has(service.name)) invalid("service names must be unique lowercase identifiers");
2317
+ if (!object2(service) || typeof service.name !== "string" || !namePattern.test(service.name) || services.has(service.name)) invalid(`service names must be unique lowercase identifiers (${object2(service) && typeof service.name === "string" ? services.has(service.name) ? `${service.name} appears twice` : `${JSON.stringify(service.name)} is not one` : "a service has no name"})`);
2318
2318
  const item = service;
2319
2319
  if (!Array.isArray(item.collections) || !item.collections.length || item.collections.length > 20) invalid("each service needs 1\u201320 collections");
2320
2320
  if (item.adapter !== void 0 && !["json-collection", "slack", "stripe", "openai", "anthropic", "github", "linear", "notion", "hubspot", "shopify", "datadog", "gmail", "google-calendar", "gitlab", "jira", "discord", "twilio", "zendesk", "google-oauth", "composio", "upstash-redis", ...ENTERPRISE_ADAPTERS].includes(String(item.adapter)) && !isGeneratedAdapter(item.adapter) && !isPackAdapter(item.adapter)) invalid("unsupported service adapter");
@@ -18853,6 +18853,25 @@ var init_orm_schema = __esm({
18853
18853
  // src/flow/postgres-schema.ts
18854
18854
  import { lstat as lstat4, readFile as readFile25, readdir as readdir5, realpath as realpath9 } from "fs/promises";
18855
18855
  import { isAbsolute as isAbsolute5, join as join36, relative as relative8, resolve as resolve11 } from "path";
18856
+ function migrationOrder(a, b) {
18857
+ const x = a.split(/[\\/]/), y = b.split(/[\\/]/);
18858
+ for (let i = 0; i < Math.min(x.length, y.length); i++) {
18859
+ if (x[i] === y[i]) continue;
18860
+ const dx = /^\d+/.exec(x[i])?.[0], dy = /^\d+/.exec(y[i])?.[0];
18861
+ if (dx && dy && (dx.length < 8 || dy.length < 8)) return x[i].localeCompare(y[i], "en", { numeric: true });
18862
+ return x[i] < y[i] ? -1 : 1;
18863
+ }
18864
+ return x.length - y.length;
18865
+ }
18866
+ function withoutExtensions(sql, available) {
18867
+ const skipped = /* @__PURE__ */ new Set();
18868
+ const out = sql.replace(/CREATE\s+EXTENSION\s+(?:IF\s+NOT\s+EXISTS\s+)?"?([\w-]+)"?[^;]*;/gi, (stmt, name) => {
18869
+ if (available.includes(name.toLowerCase())) return stmt;
18870
+ skipped.add(name.toLowerCase());
18871
+ return `-- AgentTwin: extension ${name} is not in the embedded engine; left out.`;
18872
+ });
18873
+ return { sql: out, skipped: [...skipped] };
18874
+ }
18856
18875
  async function discoverAppPostgresSchema(root2, appDir) {
18857
18876
  try {
18858
18877
  return (await discoverPostgresSchema(join36(root2, appDir))).map((file) => appDir ? join36(appDir, file).split("\\").join("/") : file);
@@ -18891,7 +18910,7 @@ async function discoverPostgresSchema(root2) {
18891
18910
  else if (e.isFile() && e.name.endsWith(".sql") && !/^(?:down|.*\.down)\.sql$/i.test(e.name)) files.push(p);
18892
18911
  if (files.length > MAX_SCHEMA_FILES) throw new Error("Too many SQL migrations; select a schema snapshot using postgresSchemaFiles.");
18893
18912
  }
18894
- return files.sort((a, b) => a.localeCompare(b, "en", { numeric: true }));
18913
+ return files.sort(migrationOrder);
18895
18914
  };
18896
18915
  const configured = [];
18897
18916
  for (const file of ["drizzle.config.ts", "drizzle.config.js", "drizzle.config.mjs", "drizzle.config.json"]) {
@@ -18943,6 +18962,20 @@ async function discoverPostgresSchema(root2) {
18943
18962
  await named("", 0);
18944
18963
  groups2.sort((a, b) => Number(/postgres|pg/i.test(b[0])) - Number(/postgres|pg/i.test(a[0])));
18945
18964
  }
18965
+ for (const schema of ["prisma/schema.prisma", "schema.prisma"]) {
18966
+ let text3 = "";
18967
+ try {
18968
+ text3 = await readFile25(join36(root2, schema), "utf8");
18969
+ } catch {
18970
+ continue;
18971
+ }
18972
+ const provider = prismaProvider(text3);
18973
+ if (provider && !/^postgres/.test(provider)) {
18974
+ const dir = schema.replace(/schema\.prisma$/, "") + "migrations/";
18975
+ for (let i = groups2.length - 1; i >= 0; i--) if (groups2[i][0]?.startsWith(dir)) groups2.splice(i, 1);
18976
+ if (!groups2.length) return [];
18977
+ }
18978
+ }
18946
18979
  if (groups2.length > 1) {
18947
18980
  const applied = [];
18948
18981
  for (const [dir, config] of [["supabase/migrations", "supabase/config.toml"], ["prisma/migrations", "prisma/schema.prisma"]]) if (await exists2(config)) {
@@ -18986,17 +19019,19 @@ async function loadPostgresSchema(root2, files) {
18986
19019
  ${ddl}
18987
19020
  `);
18988
19021
  }
18989
- const sql = parts.join("\n");
19022
+ const sql = withoutExtensions(parts.join("\n"), POSTGRES_EXTENSIONS).sql;
18990
19023
  return needsSupabase(sql) ? SUPABASE_PLATFORM + "\n" + sql : sql;
18991
19024
  }
18992
- var MAX_SCHEMA_FILES, MAX_SCHEMA_BYTES, schemaExtensions, needsSupabase, SUPABASE_PLATFORM;
19025
+ var MAX_SCHEMA_FILES, MAX_SCHEMA_BYTES, schemaExtensions, prismaProvider, needsSupabase, SUPABASE_PLATFORM;
18993
19026
  var init_postgres_schema = __esm({
18994
19027
  "src/flow/postgres-schema.ts"() {
18995
19028
  "use strict";
18996
19029
  init_orm_schema();
19030
+ init_types();
18997
19031
  MAX_SCHEMA_FILES = 2e3;
18998
19032
  MAX_SCHEMA_BYTES = 16 * 1024 * 1024;
18999
19033
  schemaExtensions = (sql) => [...new Set([...sql.matchAll(/CREATE\s+EXTENSION\s+(?:IF\s+NOT\s+EXISTS\s+)?"?([\w-]+)"?/gi)].map((m) => m[1].toLowerCase()))];
19034
+ prismaProvider = (text3) => /datasource\s+\w+\s*\{[^}]*?\bprovider\s*=\s*["']([\w-]+)["']/.exec(text3)?.[1]?.toLowerCase();
19000
19035
  needsSupabase = (sql) => /\bauth\.(users|uid|jwt|role)\b|\bstorage\.(buckets|objects)\b|\bto (anon|authenticated|service_role)\b|\bsupabase_realtime\b/i.test(sql);
19001
19036
  SUPABASE_PLATFORM = `-- Schema source: Supabase platform (AgentTwin)
19002
19037
  DO $$ BEGIN
@@ -19007,12 +19042,16 @@ END $$;
19007
19042
  CREATE SCHEMA IF NOT EXISTS auth;
19008
19043
  CREATE SCHEMA IF NOT EXISTS storage;
19009
19044
  CREATE SCHEMA IF NOT EXISTS extensions;
19045
+ -- Supabase puts extensions in the extensions schema and keeps it on every role's search path.
19046
+ SET search_path TO "$user", public, extensions;
19047
+ CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA extensions;
19048
+ CREATE EXTENSION IF NOT EXISTS pgcrypto WITH SCHEMA extensions;
19010
19049
  CREATE TABLE IF NOT EXISTS auth.users (id uuid PRIMARY KEY DEFAULT gen_random_uuid(), aud text, role text, email text UNIQUE, encrypted_password text, email_confirmed_at timestamptz, phone text, raw_app_meta_data jsonb DEFAULT '{}'::jsonb, raw_user_meta_data jsonb DEFAULT '{}'::jsonb, is_anonymous boolean DEFAULT false, created_at timestamptz DEFAULT now(), updated_at timestamptz DEFAULT now(), last_sign_in_at timestamptz);
19011
19050
  CREATE OR REPLACE FUNCTION auth.uid() RETURNS uuid LANGUAGE sql STABLE AS $f$ SELECT nullif(current_setting('request.jwt.claim.sub', true), '')::uuid $f$;
19012
19051
  CREATE OR REPLACE FUNCTION auth.role() RETURNS text LANGUAGE sql STABLE AS $f$ SELECT nullif(current_setting('request.jwt.claim.role', true), '') $f$;
19013
19052
  CREATE OR REPLACE FUNCTION auth.jwt() RETURNS jsonb LANGUAGE sql STABLE AS $f$ SELECT coalesce(nullif(current_setting('request.jwt.claims', true), ''), '{}')::jsonb $f$;
19014
19053
  CREATE TABLE IF NOT EXISTS storage.buckets (id text PRIMARY KEY, name text UNIQUE NOT NULL, owner uuid, public boolean DEFAULT false, created_at timestamptz DEFAULT now(), updated_at timestamptz DEFAULT now());
19015
- CREATE TABLE IF NOT EXISTS storage.objects (id uuid PRIMARY KEY DEFAULT gen_random_uuid(), bucket_id text REFERENCES storage.buckets(id), name text, owner uuid, metadata jsonb, created_at timestamptz DEFAULT now(), updated_at timestamptz DEFAULT now());
19054
+ CREATE TABLE IF NOT EXISTS storage.objects (id uuid PRIMARY KEY DEFAULT gen_random_uuid(), bucket_id text REFERENCES storage.buckets(id), name text, owner uuid, owner_id text, metadata jsonb, created_at timestamptz DEFAULT now(), updated_at timestamptz DEFAULT now());
19016
19055
  DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_publication WHERE pubname='supabase_realtime') THEN CREATE PUBLICATION supabase_realtime; END IF; EXCEPTION WHEN OTHERS THEN NULL; END $$;
19017
19056
  `;
19018
19057
  }
@@ -20543,13 +20582,72 @@ var init_kafka = __esm({
20543
20582
  }
20544
20583
  });
20545
20584
 
20585
+ // src/flow/input-fields.ts
20586
+ function missingInputFields(stderr) {
20587
+ const found = /* @__PURE__ */ new Map();
20588
+ for (const m of stderr.matchAll(/HTTP 4\d\d from \S+ \S+?:\s*(\{.*)$/gm)) {
20589
+ let body2;
20590
+ try {
20591
+ body2 = JSON.parse(m[1]);
20592
+ } catch {
20593
+ continue;
20594
+ }
20595
+ const visit = (v) => {
20596
+ if (Array.isArray(v)) {
20597
+ v.forEach(visit);
20598
+ return;
20599
+ }
20600
+ if (!v || typeof v !== "object") return;
20601
+ const o = v;
20602
+ const path2 = Array.isArray(o.path) ? o.path[0] : typeof o.path === "string" ? o.path : typeof o.param === "string" ? o.param : void 0;
20603
+ const text3 = [o.message, o.msg, o.received, o.code].filter((x) => typeof x === "string").join(" ");
20604
+ if (typeof path2 === "string" && /^[A-Za-z_][\w-]{0,63}$/.test(path2) && /\bRequired\b|received(?:'| )?undefined|^undefined$|is required|missing/i.test(text3 + " " + String(o.received ?? "")))
20605
+ found.set(path2, { name: path2, ...typeof o.expected === "string" ? { expected: o.expected } : {} });
20606
+ if (o.fieldErrors && typeof o.fieldErrors === "object") {
20607
+ for (const [name, list4] of Object.entries(o.fieldErrors))
20608
+ if (Array.isArray(list4) && list4.some((x) => /Required|undefined/i.test(String(x)))) found.set(name, { name });
20609
+ }
20610
+ for (const x of Object.values(o)) if (x && typeof x === "object") visit(x);
20611
+ };
20612
+ visit(body2);
20613
+ }
20614
+ return [...found.values()];
20615
+ }
20616
+ function testValueFor(field2) {
20617
+ if (field2.expected === "number" || field2.expected === "integer") return 1;
20618
+ if (field2.expected === "boolean") return true;
20619
+ if (field2.expected === "array") return [];
20620
+ if (field2.expected === "object") return {};
20621
+ const n = field2.name.toLowerCase();
20622
+ if (/email/.test(n)) return "ada@example.com";
20623
+ if (/url|uri|redirect/.test(n)) return "https://example.com/";
20624
+ if (/(^|_)(amount|count|quantity|qty|limit|page)$/.test(n)) return 1;
20625
+ return `test-${field2.name}`;
20626
+ }
20627
+ function settleInput(input, stderr, tried) {
20628
+ if (!input || typeof input !== "object" || Array.isArray(input)) return [];
20629
+ const obj = input, added = [];
20630
+ for (const f of missingInputFields(stderr)) {
20631
+ if (f.name in obj || tried.has(f.name)) continue;
20632
+ tried.add(f.name);
20633
+ obj[f.name] = testValueFor(f);
20634
+ added.push(f.name);
20635
+ }
20636
+ return added;
20637
+ }
20638
+ var init_input_fields = __esm({
20639
+ "src/flow/input-fields.ts"() {
20640
+ "use strict";
20641
+ }
20642
+ });
20643
+
20546
20644
  // package.json
20547
20645
  var package_default;
20548
20646
  var init_package = __esm({
20549
20647
  "package.json"() {
20550
20648
  package_default = {
20551
20649
  name: "agenttwin",
20552
- version: "0.3.35",
20650
+ version: "0.3.36",
20553
20651
  description: "AgentTwin builds digital twins for testing AI agents. The current CLI prepares supported Node.js workflows with synthetic services, failures, and outcome checks.",
20554
20652
  mcpName: "io.github.AgentTwin/agenttwin",
20555
20653
  keywords: [
@@ -23260,7 +23358,19 @@ async function analyzeWorkflows(root2, opts = {}) {
23260
23358
  const fn = f.functions.get(route.name);
23261
23359
  const req = fn.params?.[0]?.type === "Identifier" ? fn.params[0].name : "req";
23262
23360
  const fields = /* @__PURE__ */ new Set();
23361
+ const aliases2 = /* @__PURE__ */ new Set();
23263
23362
  walk3(fn.body, (node) => {
23363
+ if (node.type === "VariableDeclarator" && node.id.type === "Identifier" && node.init) {
23364
+ const init = node.init.type === "TSAsExpression" || node.init.type === "TSSatisfiesExpression" ? node.init.expression : node.init;
23365
+ const names = chain(init);
23366
+ if (names && names[0] === req && names[1] === "body" && names.length === 2) aliases2.add(node.id.name);
23367
+ }
23368
+ });
23369
+ walk3(fn.body, (node) => {
23370
+ if (node.type === "MemberExpression" && !node.computed && node.object.type === "Identifier" && aliases2.has(node.object.name) && node.property.type === "Identifier") fields.add(node.property.name);
23371
+ if (node.type === "VariableDeclarator" && node.id.type === "ObjectPattern" && node.init?.type === "Identifier" && aliases2.has(node.init.name)) {
23372
+ for (const p of node.id.properties) if (p.type === "ObjectProperty" && !p.computed) fields.add(String(p.key.name ?? p.key.value));
23373
+ }
23264
23374
  if (node.type === "MemberExpression" && !node.computed) {
23265
23375
  const names = chain(node);
23266
23376
  if (names && names[0] === req && names[1] === "body" && names[2]) fields.add(names[2]);
@@ -23532,6 +23642,216 @@ export async function environment(file, module) {
23532
23642
  }
23533
23643
  });
23534
23644
 
23645
+ // src/flow/setup.ts
23646
+ import { spawn as spawn9, spawnSync as spawnSync2 } from "child_process";
23647
+ import { existsSync as existsSync8, mkdirSync, readFileSync as readFileSync9, readdirSync as readdirSync4 } from "fs";
23648
+ import { delimiter as delimiter2, join as join48, posix as posix5 } from "path";
23649
+ function packageManager(cwd) {
23650
+ const field2 = readJson2(join48(cwd, "package.json"))?.packageManager;
23651
+ if (typeof field2 === "string") {
23652
+ const [name, version] = field2.split("@");
23653
+ if (["npm", "pnpm", "yarn", "bun"].includes(name)) return { name, version: version?.split("+")[0] };
23654
+ }
23655
+ if (existsSync8(join48(cwd, "pnpm-lock.yaml"))) return { name: "pnpm" };
23656
+ if (existsSync8(join48(cwd, "yarn.lock"))) return { name: "yarn" };
23657
+ if (existsSync8(join48(cwd, "bun.lock")) || existsSync8(join48(cwd, "bun.lockb"))) return { name: "bun" };
23658
+ return { name: "npm" };
23659
+ }
23660
+ function nodeWanted(range, have = process.versions.node) {
23661
+ if (!range || !/\d/.test(range)) return void 0;
23662
+ const current2 = Number(have.split(".")[0]);
23663
+ const alternatives = range.split("||").map((alt) => [...alt.matchAll(/(>=|<=|>|<|\^|~|=)?\s*v?(\d+)/g)].map((m) => ({ op: m[1] ?? "", major: Number(m[2]) })));
23664
+ const satisfied = (cmp2) => cmp2.every(({ op: op2, major }) => op2 === ">=" || op2 === ">" ? current2 >= major : op2 === "<" ? current2 < major : op2 === "<=" ? current2 <= major : current2 === major);
23665
+ if (alternatives.some((a) => a.length && satisfied(a))) return void 0;
23666
+ const lows = alternatives.flatMap((a) => a.filter((c) => !c.op.startsWith("<")).map((c) => c.major));
23667
+ return lows.length ? String(Math.min(...lows.filter((m) => m > current2).concat(lows.every((m) => m <= current2) ? [Math.max(...lows)] : []))) : void 0;
23668
+ }
23669
+ function unbuiltWorkspacePackages(cwd, appDir) {
23670
+ const root2 = readJson2(join48(cwd, "package.json"));
23671
+ let patterns = Array.isArray(root2?.workspaces) ? root2.workspaces : Array.isArray(root2?.workspaces?.packages) ? root2.workspaces.packages : [];
23672
+ if (existsSync8(join48(cwd, "pnpm-workspace.yaml"))) {
23673
+ const text3 = readFileSync9(join48(cwd, "pnpm-workspace.yaml"), "utf8");
23674
+ patterns = [...patterns, ...[...text3.matchAll(/^\s*-\s*['"]?([^'"\n#]+)['"]?/gm)].map((m) => m[1].trim())];
23675
+ }
23676
+ const dirs = /* @__PURE__ */ new Set();
23677
+ for (const pattern of patterns) {
23678
+ if (pattern.startsWith("!")) continue;
23679
+ const base = pattern.replace(/\/\*\*?$/, "");
23680
+ if (pattern.endsWith("*")) {
23681
+ try {
23682
+ for (const e of readdirSync4(join48(cwd, base), { withFileTypes: true })) if (e.isDirectory()) dirs.add(posix5.join(base, e.name));
23683
+ } catch {
23684
+ }
23685
+ } else dirs.add(base);
23686
+ }
23687
+ let needed;
23688
+ if (appDir !== void 0) {
23689
+ const byName = /* @__PURE__ */ new Map();
23690
+ for (const dir of dirs) {
23691
+ const name = readJson2(join48(cwd, dir, "package.json"))?.name;
23692
+ if (typeof name === "string") byName.set(name, dir);
23693
+ }
23694
+ needed = /* @__PURE__ */ new Set();
23695
+ const queue = [appDir];
23696
+ while (queue.length) {
23697
+ const dir = queue.shift();
23698
+ const pkg = readJson2(join48(cwd, dir, "package.json"));
23699
+ for (const dep of Object.keys({ ...pkg?.dependencies, ...pkg?.devDependencies, ...pkg?.peerDependencies })) {
23700
+ const d2 = byName.get(dep);
23701
+ if (d2 && !needed.has(d2)) {
23702
+ needed.add(d2);
23703
+ queue.push(d2);
23704
+ }
23705
+ }
23706
+ }
23707
+ }
23708
+ const unbuilt = [];
23709
+ for (const dir of dirs) {
23710
+ if (needed && !needed.has(dir)) continue;
23711
+ const pkg = readJson2(join48(cwd, dir, "package.json"));
23712
+ if (!pkg) continue;
23713
+ const targets = [];
23714
+ const collect2 = (v) => {
23715
+ if (typeof v === "string") targets.push(v);
23716
+ else if (v && typeof v === "object") for (const x of Object.values(v)) collect2(x);
23717
+ };
23718
+ collect2(pkg.main);
23719
+ collect2(pkg.module);
23720
+ collect2(pkg.exports?.["."] ?? (typeof pkg.exports === "string" ? pkg.exports : void 0));
23721
+ const built = targets.filter((t) => /(^|\/)(dist|build|lib|out)\//.test(t) && !t.includes("*"));
23722
+ if (built.length && pkg.scripts?.build && built.every((t) => !existsSync8(join48(cwd, dir, t)))) unbuilt.push(dir);
23723
+ }
23724
+ return unbuilt.sort();
23725
+ }
23726
+ function planSetup(cwd, opts = {}) {
23727
+ const pm = packageManager(cwd);
23728
+ const root2 = readJson2(join48(cwd, "package.json")) ?? {};
23729
+ const steps = [];
23730
+ const runner = (args) => pm.name === "npm" || has(pm.name) && !(pm.name === "yarn" && pm.version && Number(pm.version.split(".")[0]) >= 2) ? { command: pm.name, args } : has("corepack") ? { command: "corepack", args: [`${pm.name}${pm.version ? "@" + pm.version : ""}`, ...args] } : { command: "npx", args: ["--yes", `${pm.name}${pm.version ? "@" + pm.version : ""}`, ...args] };
23731
+ const anyDeps = Object.keys({ ...root2.dependencies, ...root2.devDependencies }).length > 0 || root2.workspaces || existsSync8(join48(cwd, "pnpm-workspace.yaml"));
23732
+ if (opts.only !== "build" && anyDeps && !existsSync8(join48(cwd, "node_modules"))) {
23733
+ const r = runner(["install"]);
23734
+ steps.push({ id: "install", ...r, why: "dependencies are not installed", dir: cwd });
23735
+ }
23736
+ const unbuilt = steps.length || opts.only === "install" ? [] : unbuiltWorkspacePackages(cwd, opts.appDir);
23737
+ if (unbuilt.length) {
23738
+ const own = pm.name === "pnpm" ? runner(["-r", "--no-bail", "--workspace-concurrency=1", ...unbuilt.flatMap((d2) => ["--filter", `./${d2}`]), "run", "build"]) : pm.name === "yarn" ? runner(["workspaces", "foreach", "-R", "--from", `{${unbuilt.join(",")}}`, "run", "build"]) : pm.name === "bun" ? runner(["run", "--filter", "*", "build"]) : runner(["run", "build", ...unbuilt.flatMap((d2) => ["--workspace", d2]), "--if-present"]);
23739
+ const turbo = existsSync8(join48(cwd, "turbo.json")) && existsSync8(join48(cwd, "node_modules/.bin/turbo")) ? { command: join48(cwd, "node_modules/.bin/turbo"), args: ["run", "build", "--continue", "--concurrency=1", ...unbuilt.map((d2) => `--filter=./${d2}`)] } : void 0;
23740
+ const r = turbo ? { ...turbo, fallback: own } : own;
23741
+ steps.push({ id: "build", ...r, why: `${unbuilt.length} workspace package${unbuilt.length === 1 ? " is" : "s are"} not built yet (${unbuilt.slice(0, 3).join(", ")}${unbuilt.length > 3 ? "\u2026" : ""})`, dir: cwd });
23742
+ }
23743
+ const want = opts.only === "build" ? void 0 : nodeWanted(root2.engines?.node);
23744
+ return { packageManager: pm.name, steps, ...unbuilt.length ? { unbuilt: unbuilt.length } : {}, ...want ? { node: { want, have: process.versions.node, command: `nvm install ${want} && nvm use ${want}` } } : {} };
23745
+ }
23746
+ function installRetry(step, output) {
23747
+ const pm = step.command === "corepack" || step.command === "npx" ? step.args.find((a) => /^(npm|pnpm|yarn|bun)(@|$)/.test(a))?.split("@")[0] : step.command;
23748
+ const tail = step.command === "corepack" ? step.args.slice(1) : step.command === "npx" ? step.args.slice(2) : step.args;
23749
+ const pinned = step.command === "corepack" || step.command === "npx" ? step.args.find((a) => /^(npm|pnpm|yarn|bun)(@|$)/.test(a)) : pm;
23750
+ if (pm === "pnpm" && /ERR_PNPM_(OUTDATED_LOCKFILE|LOCKFILE_CONFIG_MISMATCH|LOCKFILE_MISSING_DEPENDENCY)|frozen.lockfile|specifiers in the lockfile/i.test(output))
23751
+ return { why: "The lockfile is behind package.json, so a frozen install stops", step: { ...step, args: [...step.args, "--no-frozen-lockfile"] } };
23752
+ const lockfile = pm === "pnpm" ? /lockfileVersion[\s│|]+of[\s│|]+(\d+)(?:\.(\d+))?[\s│|]+is[\s│|]+incompatible/i.exec(output) : null;
23753
+ if (lockfile) {
23754
+ const v = Number(lockfile[1]), minor = Number(lockfile[2] ?? 0), major = v >= 9 ? 9 : v === 6 ? 8 : v === 5 && minor >= 4 ? 7 : 6, want = `pnpm@${major}`;
23755
+ if (pinned !== want) return { why: `The lockfile was written by pnpm ${major}, which this pnpm cannot read`, step: { ...step, command: "corepack", args: [want, ...tail.filter((a) => a !== "--frozen-lockfile")] } };
23756
+ }
23757
+ if (pm === "yarn" && /YN0028|lockfile would have been modified|--frozen-lockfile/i.test(output))
23758
+ return { why: "The lockfile is behind package.json, so a frozen install stops", step: { ...step, args: [...step.args, "--no-immutable"] } };
23759
+ if (pm === "pnpm" && /ERR_PNPM_IGNORED_BUILDS/.test(output) && !step.args.some((a) => a.startsWith("--config.dangerously-allow-all-builds")))
23760
+ return { why: "pnpm skipped the dependencies' build scripts", step: { ...step, args: [...step.args, "--config.dangerously-allow-all-builds=true"] } };
23761
+ if (pm === "bun" && step.command === "corepack")
23762
+ return { why: "corepack cannot fetch bun", step: { ...step, command: "npx", args: ["--yes", pinned, ...tail] } };
23763
+ if (pm === "npm" && /EBADENGINE|notsup|Unsupported engine/i.test(output) && !step.args.includes("--engine-strict=false"))
23764
+ return { why: "The project's engines field does not allow this Node version", step: { ...step, args: [...step.args, "--engine-strict=false"] } };
23765
+ }
23766
+ async function corepackShims(cwd, steps) {
23767
+ const pm = packageManager(cwd).name;
23768
+ const managers = [.../* @__PURE__ */ new Set([...steps.filter((s) => s.command === "corepack").map((s) => s.args[0]?.split("@")[0]), pm])].filter((m) => (m === "pnpm" || m === "yarn") && !has(m));
23769
+ if (!managers.length || !steps.length || !has("corepack")) return;
23770
+ const dir = join48(cwd, ".agenttwin", "bin");
23771
+ try {
23772
+ mkdirSync(dir, { recursive: true });
23773
+ } catch {
23774
+ return;
23775
+ }
23776
+ const ok3 = await new Promise((resolve18) => {
23777
+ const c = spawn9("corepack", ["enable", "--install-directory", dir, ...managers], { stdio: "ignore" });
23778
+ c.once("error", () => resolve18(false));
23779
+ c.once("exit", (code) => resolve18(code === 0));
23780
+ });
23781
+ return ok3 ? dir : void 0;
23782
+ }
23783
+ async function runSetup(cwd, opts) {
23784
+ const plan = opts.plan ?? planSetup(cwd, { ...opts.appDir !== void 0 ? { appDir: opts.appDir } : {}, ...opts.only ? { only: opts.only } : {} });
23785
+ if (plan.node) opts.log(` ! This project asks for Node.js ${plan.node.want}; this machine runs ${plan.node.have}. If the app fails to start, run: ${plan.node.command}`);
23786
+ if (!plan.steps.length) return true;
23787
+ opts.log(` Before the app can start: ${plan.steps.map((s) => `${show(s)} (${s.why})`).join(", then ")}.`);
23788
+ const answer = (await opts.ask({ id: "setup", text: `Run ${plan.steps.length === 1 ? "it" : "them"} now? (Y/n)`, default: "y" })).trim().toLowerCase();
23789
+ if (answer.startsWith("n")) {
23790
+ opts.log(` Skipped. Run ${plan.steps.map(show).join(" && ")} yourself, then npx agenttwin again.`);
23791
+ return false;
23792
+ }
23793
+ const shims = await corepackShims(cwd, plan.steps);
23794
+ const exec11 = (step) => new Promise((resolve18) => {
23795
+ const child = spawn9(step.command, step.args, { cwd: step.dir, stdio: ["ignore", "pipe", "pipe"], env: { ...BUILD_PLACEHOLDERS, ...process.env, CI: "1", COREPACK_ENABLE_DOWNLOAD_PROMPT: "0", ...shims ? { PATH: `${shims}${delimiter2}${process.env.PATH ?? ""}` } : {} } });
23796
+ let tail = "";
23797
+ const keep = (c) => {
23798
+ tail = (tail + c.toString()).slice(-4e3);
23799
+ };
23800
+ child.stdout.on("data", keep);
23801
+ child.stderr.on("data", keep);
23802
+ child.once("error", (e) => {
23803
+ tail += String(e);
23804
+ resolve18({ code: 1, tail });
23805
+ });
23806
+ child.once("exit", (c) => resolve18({ code: c ?? 1, tail }));
23807
+ });
23808
+ for (const step of plan.steps) {
23809
+ opts.log(` Running ${show(step)}\u2026`);
23810
+ let { code, tail } = await exec11(step);
23811
+ for (let current2 = step, tries = 0; code !== 0 && step.id === "install" && tries < 3; tries++) {
23812
+ const retry = installRetry(current2, tail);
23813
+ if (!retry) break;
23814
+ opts.log(` ${retry.why}; running ${show(retry.step)}\u2026`);
23815
+ current2 = retry.step;
23816
+ ({ code, tail } = await exec11(retry.step));
23817
+ }
23818
+ const left = code !== 0 && step.id === "build" && plan.unbuilt ? unbuiltWorkspacePackages(cwd, opts.appDir) : void 0;
23819
+ if (left && left.length < plan.unbuilt) {
23820
+ opts.log(tail.split("\n").filter((l) => /error|failed|not found|cannot/i.test(l)).slice(-4).map((l) => " " + l.slice(0, 200)).join("\n"));
23821
+ opts.log(` ${plan.unbuilt - left.length} of ${plan.unbuilt} workspace packages built${left.length ? `; ${left.length} did not (${left.slice(0, 3).join(", ")}${left.length > 3 ? "\u2026" : ""})` : ""}. The run goes on.`);
23822
+ continue;
23823
+ }
23824
+ if (code !== 0 && step.fallback) {
23825
+ const next = { ...step, ...step.fallback, fallback: void 0 };
23826
+ opts.log(` ${show(step)} failed; running ${show(next)}\u2026`);
23827
+ ({ code, tail } = await exec11(next));
23828
+ }
23829
+ if (code !== 0) {
23830
+ opts.log(tail.split("\n").filter(Boolean).slice(-6).map((l) => " " + l.slice(0, 200)).join("\n"));
23831
+ opts.log(` ${show(step)} failed (exit ${code}). The run goes on; if the app cannot start, fix that first.`);
23832
+ return false;
23833
+ }
23834
+ }
23835
+ opts.log(" Setup done.");
23836
+ return true;
23837
+ }
23838
+ var readJson2, has, show, BUILD_PLACEHOLDERS;
23839
+ var init_setup = __esm({
23840
+ "src/flow/setup.ts"() {
23841
+ "use strict";
23842
+ readJson2 = (file) => {
23843
+ try {
23844
+ return JSON.parse(readFileSync9(file, "utf8"));
23845
+ } catch {
23846
+ return void 0;
23847
+ }
23848
+ };
23849
+ has = (cmd) => spawnSync2(process.platform === "win32" ? "where" : "which", [cmd], { stdio: "ignore" }).status === 0;
23850
+ show = (s) => [posix5.basename(s.command), ...s.args].join(" ");
23851
+ BUILD_PLACEHOLDERS = { DATABASE_URL: "postgresql://agenttwin:agenttwin@127.0.0.1:5432/agenttwin", DIRECT_URL: "postgresql://agenttwin:agenttwin@127.0.0.1:5432/agenttwin" };
23852
+ }
23853
+ });
23854
+
23535
23855
  // src/runtime/engines/mysql-sql.ts
23536
23856
  function tokenize(sql) {
23537
23857
  const tokens = [];
@@ -24265,15 +24585,15 @@ var init_providers = __esm({
24265
24585
  });
24266
24586
 
24267
24587
  // src/flow/env-values.ts
24268
- import { readFileSync as readFileSync9 } from "fs";
24269
- import { dirname as dirname11, join as join48, resolve as resolve14, sep as sep11 } from "path";
24588
+ import { readFileSync as readFileSync10 } from "fs";
24589
+ import { dirname as dirname11, join as join49, resolve as resolve14, sep as sep11 } from "path";
24270
24590
  function readCommentedExamples(root2, entryFile) {
24271
24591
  const top = resolve14(root2), values = {};
24272
24592
  for (let directory = dirname11(resolve14(top, entryFile)); directory === top || directory.startsWith(top + sep11); directory = dirname11(directory)) {
24273
24593
  for (const name of EXAMPLE_FILES) {
24274
24594
  let text3;
24275
24595
  try {
24276
- text3 = readFileSync9(join48(directory, name), "utf8");
24596
+ text3 = readFileSync10(join49(directory, name), "utf8");
24277
24597
  } catch {
24278
24598
  continue;
24279
24599
  }
@@ -24300,7 +24620,7 @@ function readEnvExamples(root2, entryFile) {
24300
24620
  for (const directory of folders) for (const name of EXAMPLE_FILES) {
24301
24621
  let text3;
24302
24622
  try {
24303
- text3 = readFileSync9(join48(directory, name), "utf8");
24623
+ text3 = readFileSync10(join49(directory, name), "utf8");
24304
24624
  } catch {
24305
24625
  continue;
24306
24626
  }
@@ -24357,12 +24677,14 @@ function envProblems(stderr) {
24357
24677
  if (/^[A-Z][A-Z0-9_]{2,79}$/.test(name) && !/^(NODE_ENV|PATH|HOME|ERR_[A-Z_]+|[A-Z]+_NOT_FOUND|ENOENT|ECONNREFUSED|ENOTFOUND|EACCES)$/.test(name)) found.set(name, (found.get(name) ?? false) || missing);
24358
24678
  };
24359
24679
  for (const block of stderr.split(/\n\s*\},?\s*\n/)) {
24360
- const path2 = /path:\s*\[\s*['"]([A-Z][A-Z0-9_]+)['"]\s*\]/.exec(block);
24680
+ const path2 = /path:\s*\[?\s*['"]([A-Z][A-Z0-9_]+)['"]\s*\]?/.exec(block);
24361
24681
  if (!path2) continue;
24362
24682
  add(path2[1], /received undefined|Required|invalid_type/.test(block) && !/received (?:string|number|boolean)/.test(block));
24363
24683
  }
24364
24684
  for (const m of stderr.matchAll(/(?:^|[\s{,])["']?([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+)["']?:\s*\[\s*((?:["'][^"'\n]*["']\s*,?\s*)+)\]/gm))
24365
24685
  add(m[1], /received undefined|\bRequired\b/.test(m[2]));
24686
+ for (const m of stderr.matchAll(/^\s*-\s+([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+):\s*(.+)$/gm))
24687
+ add(m[1], /received undefined|\bRequired\b/.test(m[2]));
24366
24688
  for (const m of stderr.matchAll(/\bbut ([A-Z][A-Z0-9_]+) returned a Promise/g)) add(m[1], false);
24367
24689
  for (const line of stderr.split("\n")) {
24368
24690
  if (!/env|environment|config|required|missing|not (?:set|defined)|must be|please (?:set|define|provide|add|configure)/i.test(line)) continue;
@@ -24371,6 +24693,23 @@ function envProblems(stderr) {
24371
24693
  }
24372
24694
  return [...found].map(([name, missing]) => ({ name, missing }));
24373
24695
  }
24696
+ function nextConfigProblems(stderr, root2, appDir = "") {
24697
+ if (!/Invalid (?:header|rewrite|redirect)s? found/i.test(stderr)) return [];
24698
+ const names = /* @__PURE__ */ new Set();
24699
+ for (const dir of [.../* @__PURE__ */ new Set([appDir, ""])]) for (const file of ["next.config.js", "next.config.mjs", "next.config.ts", "next.config.cjs"]) {
24700
+ let text3;
24701
+ try {
24702
+ text3 = readFileSync10(join49(root2, dir, file), "utf8");
24703
+ } catch {
24704
+ continue;
24705
+ }
24706
+ for (const m of text3.matchAll(/process\.env\.([A-Z][A-Z0-9_]+)|process\.env\[['"]([A-Z][A-Z0-9_]+)['"]\]/g)) {
24707
+ const n = m[1] ?? m[2];
24708
+ if (n !== "NODE_ENV") names.add(n);
24709
+ }
24710
+ }
24711
+ return [...names].map((name) => ({ name, missing: true }));
24712
+ }
24374
24713
  function settleEnvironment(environment, problems, examples, tried, blocked, commented = {}) {
24375
24714
  const set2 = [], cleared = [];
24376
24715
  for (const { name, missing } of problems) {
@@ -24401,7 +24740,7 @@ function declaredSettings(root2, appDir) {
24401
24740
  for (const file of [...EXAMPLE_FILES, "env.ts", "env.mjs", "env.js", "src/env.ts", "src/env.mjs", "src/env.js"]) {
24402
24741
  let text3;
24403
24742
  try {
24404
- text3 = readFileSync9(join48(root2, appDir, file), "utf8");
24743
+ text3 = readFileSync10(join49(root2, appDir, file), "utf8");
24405
24744
  } catch {
24406
24745
  continue;
24407
24746
  }
@@ -24555,11 +24894,11 @@ var init_account_presets = __esm({
24555
24894
 
24556
24895
  // src/flow/autoprep.ts
24557
24896
  import { mkdir as mkdir14, readFile as readFile31, writeFile as writeFile23 } from "fs/promises";
24558
- import { existsSync as existsSync8, readdirSync as readdirSync4, readFileSync as readFileSync10 } from "fs";
24897
+ import { existsSync as existsSync9, readdirSync as readdirSync5, readFileSync as readFileSync11 } from "fs";
24559
24898
  import { createHash as createHash26 } from "crypto";
24560
24899
  import { createRequire as createRequire5 } from "module";
24561
- import { spawnSync as spawnSync2 } from "child_process";
24562
- import { dirname as dirname12, join as join49, posix as posix5, relative as relative14 } from "path";
24900
+ import { spawnSync as spawnSync3 } from "child_process";
24901
+ import { delimiter as delimiter3, dirname as dirname12, join as join50, posix as posix6, relative as relative14 } from "path";
24563
24902
  import { pathToFileURL as pathToFileURL2 } from "url";
24564
24903
  function fieldValue(name, message, channel) {
24565
24904
  const n = name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
@@ -24680,7 +25019,26 @@ async function generateScenario(candidate, ask, discovered = discoverServices(ca
24680
25019
  const norm = resolvedAll[i].title.toLowerCase().replace(/[^a-z0-9]/g, "");
24681
25020
  return o.engine && norm.includes(o.engine.kind) || o.tier === "deep" && o.service?.adapter && norm.includes(o.service.adapter.replace(/-/g, ""));
24682
25021
  })));
24683
- const twins2 = discovered.map(resolveTwin);
25022
+ let twins2 = discovered.map(resolveTwin);
25023
+ {
25024
+ const byName = /* @__PURE__ */ new Map(), keep = [];
25025
+ twins2.forEach((t, i) => {
25026
+ const name = t.service?.name;
25027
+ const j = name === void 0 ? void 0 : byName.get(name);
25028
+ if (j === void 0) {
25029
+ if (name !== void 0) byName.set(name, i);
25030
+ keep.push(i);
25031
+ return;
25032
+ }
25033
+ const first = twins2[j] = { ...twins2[j], service: structuredClone(twins2[j].service) };
25034
+ for (const c of t.service.collections) if (!first.service.collections.some((x) => x.path === c.path)) first.service.collections.push(structuredClone(c));
25035
+ discovered[j] = { ...discovered[j], calls: [...discovered[j].calls, ...discovered[i].calls] };
25036
+ });
25037
+ if (keep.length < twins2.length) {
25038
+ twins2 = keep.map((i) => twins2[i]);
25039
+ discovered = keep.map((i) => discovered[i]);
25040
+ }
25041
+ }
24684
25042
  const plan = (key3) => twins2.find((t, i) => discovered[i].key === key3 && t.service);
24685
25043
  const calls = (p) => candidate.calls.filter((c) => c.provider === p || c.provider === `pack:${p}`);
24686
25044
  const refunds = calls("stripe").some((c) => /^refunds\.create$/.test(c.operation));
@@ -24706,7 +25064,7 @@ async function generateScenario(candidate, ask, discovered = discoverServices(ca
24706
25064
  let input;
24707
25065
  if (candidate.bolt) {
24708
25066
  if (!channel) channel = "C0AGENTTWIN";
24709
- const source = root2 ? await readFile31(join49(root2, candidate.file), "utf8").catch(() => "") : "";
25067
+ const source = root2 ? await readFile31(join50(root2, candidate.file), "utf8").catch(() => "") : "";
24710
25068
  const stateRefs = [...source.matchAll(/state\??\.values\??\.([A-Za-z_]\w*)\??\.([A-Za-z_]\w*)/g)].map((m) => [m[1], m[2]]);
24711
25069
  for (const d2 of source.matchAll(/\{([^{}]+)\}\s*=\s*[\w$.?]*state\??\.values\b/g)) for (const name of d2[1].split(",").map((x) => x.trim().split(/\s*:\s*/).pop()).filter((x) => /^[A-Za-z_]\w*$/.test(x)))
24712
25070
  for (const m of source.matchAll(new RegExp(`\\b${name}\\??\\.([A-Za-z_]\\w*)`, "g"))) if (!stateRefs.some(([b, a]) => b === name && a === m[1])) stateRefs.push([name, m[1]]);
@@ -24964,7 +25322,7 @@ async function generateScenario(candidate, ask, discovered = discoverServices(ca
24964
25322
  if (tables2.size) assumptions.push(`PostgreSQL synthetic rows (must satisfy the project schema), seeded with ${[...tables2].map(([t, r]) => `${t} ${JSON.stringify(r)}`).join("; ")}.`);
24965
25323
  } else if (adapter.startsWith("pack:")) {
24966
25324
  const own = discovered[twins2.indexOf(twin)]?.calls ?? [];
24967
- const manifest = candidate.boltApp && root2 ? await readFile31(join49(root2, "manifest.json"), "utf8").then((t) => {
25325
+ const manifest = candidate.boltApp && root2 ? await readFile31(join50(root2, "manifest.json"), "utf8").then((t) => {
24968
25326
  const m = JSON.parse(t);
24969
25327
  return m && typeof m === "object" && m.settings ? m : void 0;
24970
25328
  }).catch(() => void 0) : void 0;
@@ -25032,12 +25390,12 @@ async function generateScenario(candidate, ask, discovered = discoverServices(ca
25032
25390
  function upstashSettings(root2, appDir) {
25033
25391
  let text3 = "";
25034
25392
  try {
25035
- const pkg = JSON.parse(readFileSyncSafe(join49(root2, appDir, "package.json")) || "{}");
25393
+ const pkg = JSON.parse(readFileSyncSafe(join50(root2, appDir, "package.json")) || "{}");
25036
25394
  if (!pkg.dependencies?.["@upstash/redis"]) return void 0;
25037
25395
  } catch {
25038
25396
  return void 0;
25039
25397
  }
25040
- for (const file of [".env.example", "env.ts", "env.mjs", "src/env.ts", "src/env.mjs", "env.js"]) text3 += readFileSyncSafe(join49(root2, appDir, file));
25398
+ for (const file of [".env.example", "env.ts", "env.mjs", "src/env.ts", "src/env.mjs", "env.js"]) text3 += readFileSyncSafe(join50(root2, appDir, file));
25041
25399
  const url = ["UPSTASH_REDIS_REST_URL", "KV_REST_API_URL", "UPSTASH_REDIS_URL", "REDIS_HTTP_URL"].find((name) => new RegExp(`\\b${name}\\b`).test(text3)) ?? "UPSTASH_REDIS_REST_URL";
25042
25400
  const tokens = ["UPSTASH_REDIS_REST_TOKEN", "KV_REST_API_TOKEN", "UPSTASH_REDIS_TOKEN", "REDIS_HTTP_TOKEN"].filter((name) => new RegExp(`\\b${name}\\b`).test(text3));
25043
25401
  return { url, tokens: tokens.length ? tokens : ["UPSTASH_REDIS_REST_TOKEN"] };
@@ -25045,7 +25403,7 @@ function upstashSettings(root2, appDir) {
25045
25403
  async function settleConfiguration(cwd, prepared, stderr, tried) {
25046
25404
  const twins2 = prepared.scenario.twins, managed = new Set(twins2.flatMap((t) => [t.envUrl, ...Object.keys(t.env ?? {})]).filter((v) => !!v));
25047
25405
  const blocked = (name) => FORBIDDEN_ENV.test(name) || managed.has(name) || DATABASE_ENV.test(name) && twins2.some((t) => t.engine?.kind === "postgres");
25048
- const changed = settleEnvironment(prepared.scenario.environment, envProblems(stderr), readEnvExamples(cwd, prepared.candidate.file), tried, blocked, readCommentedExamples(cwd, prepared.candidate.file));
25406
+ const changed = settleEnvironment(prepared.scenario.environment, [...envProblems(stderr), ...nextConfigProblems(stderr, cwd, prepared.candidate.web?.appDir)], readEnvExamples(cwd, prepared.candidate.file), tried, blocked, readCommentedExamples(cwd, prepared.candidate.file));
25049
25407
  if (changed.set.length || changed.cleared.length) await writeFile23(prepared.scenarioPath, JSON.stringify(prepared.scenario, null, 2) + "\n", { mode: 384 });
25050
25408
  return changed;
25051
25409
  }
@@ -25067,8 +25425,8 @@ function typescriptLoader() {
25067
25425
  }
25068
25426
  async function prepareWorkflow(cwd, candidate, ask, log, discovered) {
25069
25427
  const slug4 = slugName(candidate.web ? candidate.title : candidate.exportName);
25070
- const directory = join49(cwd, ".agenttwin", "auto", slug4);
25071
- const scenarioPath = join49(directory, "scenario.json");
25428
+ const directory = join50(cwd, ".agenttwin", "auto", slug4);
25429
+ const scenarioPath = join50(directory, "scenario.json");
25072
25430
  await mkdir14(directory, { recursive: true });
25073
25431
  let scenario;
25074
25432
  try {
@@ -25150,7 +25508,7 @@ async function prepareWorkflow(cwd, candidate, ask, log, discovered) {
25150
25508
  const restDatabase = scenario.services.some((sv) => typeof sv.adapter === "string" && sv.adapter.startsWith("pack:") && (packRecord(sv.adapter.slice(5))?.hosts ?? []).some((h) => /rest/.test(h.pathPattern ?? "")));
25151
25509
  const servedPostgres = !!candidate.serve && usesPostgresDriver(cwd);
25152
25510
  if ((candidate.web?.appDir !== void 0 || restDatabase || servedPostgres) && !scenario.twins.some((t) => t.engine?.kind === "postgres") && scenario.postgresSchemaFiles === void 0) {
25153
- const appDir = candidate.web?.appDir ?? (candidate.serve ? posix5.dirname(candidate.serve.entry ?? candidate.file) : "");
25511
+ const appDir = candidate.web?.appDir ?? (candidate.serve ? posix6.dirname(candidate.serve.entry ?? candidate.file) : "");
25154
25512
  const found = await discoverAppPostgresSchema(cwd, candidate.web?.appDir ?? "");
25155
25513
  const files = found?.length ? found : servedPostgres ? await discoverWorkspaceSchema(cwd, appDir) : void 0;
25156
25514
  if (files?.length || servedPostgres) {
@@ -25167,11 +25525,11 @@ async function prepareWorkflow(cwd, candidate, ask, log, discovered) {
25167
25525
  if (mode !== "auto" && mode !== "explicit") throw new Error("postgresSchemaMode must be auto or explicit.");
25168
25526
  const nearest = async () => {
25169
25527
  const dirs = [];
25170
- let dir = posix5.dirname(candidate.file);
25528
+ let dir = posix6.dirname(candidate.file);
25171
25529
  while (true) {
25172
- if (existsSync8(join49(cwd, dir, "package.json")) || dir === ".") dirs.push(dir === "." ? "" : dir);
25530
+ if (existsSync9(join50(cwd, dir, "package.json")) || dir === ".") dirs.push(dir === "." ? "" : dir);
25173
25531
  if (dir === "." || dir === "") break;
25174
- dir = posix5.dirname(dir);
25532
+ dir = posix6.dirname(dir);
25175
25533
  }
25176
25534
  for (const d2 of dirs) {
25177
25535
  const found = d2 ? await discoverAppPostgresSchema(cwd, d2) : await discoverPostgresSchema(cwd);
@@ -25182,8 +25540,9 @@ async function prepareWorkflow(cwd, candidate, ask, log, discovered) {
25182
25540
  let files = mode === "auto" ? await nearest() : scenario.postgresSchemaFiles ?? [];
25183
25541
  scenario.postgresSchemaMode = mode;
25184
25542
  let unreadable = false;
25543
+ let skippedExtensions = [];
25185
25544
  try {
25186
- await loadPostgresSchema(cwd, files);
25545
+ skippedExtensions = [...(await loadPostgresSchema(cwd, files)).matchAll(/-- AgentTwin: extension ([\w-]+) is not in the embedded engine/g)].map((m) => m[1]);
25187
25546
  } catch (error) {
25188
25547
  const why = error instanceof Error ? error.message : String(error);
25189
25548
  if (!/Unsupported ORM schema|Unsupported SQL|not supported/i.test(why)) throw error;
@@ -25199,6 +25558,11 @@ async function prepareWorkflow(cwd, candidate, ask, log, discovered) {
25199
25558
  const note = "No PostgreSQL schema or migrations were found: the database starts empty and its writes are not checked.";
25200
25559
  if (!scenario.assumptions.includes(note)) scenario.assumptions.push(note);
25201
25560
  } else log(` PostgreSQL schema: ${files.length > 3 ? `${files.length} files from ${files[0].split("/").slice(0, -2).join("/") || "."}` : files.join(", ")} (SQL applied to a disposable database).`);
25561
+ if (skippedExtensions.length) {
25562
+ const note = `PostgreSQL extension${skippedExtensions.length > 1 ? "s" : ""} ${skippedExtensions.join(", ")} ${skippedExtensions.length > 1 ? "are" : "is"} not in the embedded database, so ${skippedExtensions.length > 1 ? "they were" : "it was"} left out; tables and functions that need ${skippedExtensions.length > 1 ? "them" : "it"} may not work.`;
25563
+ log(` ${note}`);
25564
+ if (!scenario.assumptions.includes(note)) scenario.assumptions.push(note);
25565
+ }
25202
25566
  if (files.length) {
25203
25567
  const note = "PostgreSQL uses project schema; generated synthetic rows must satisfy its constraints. Review the scenario seeds.";
25204
25568
  if (!scenario.assumptions.includes(note)) scenario.assumptions.push(note);
@@ -25224,7 +25588,7 @@ async function prepareWorkflow(cwd, candidate, ask, log, discovered) {
25224
25588
  services: noChecks ? [...seedTimes(scenario.services), sentinel] : seedTimes(scenario.services),
25225
25589
  assertions: noChecks ? [{ service: "none", path: "/none", count: 0 }] : scenario.assertions
25226
25590
  });
25227
- const sourceDigests = async () => Object.fromEntries(await Promise.all(sources.map(async (f) => [f, createHash26("sha256").update(await readFile31(join49(cwd, f))).digest("hex")])));
25591
+ const sourceDigests = async () => Object.fromEntries(await Promise.all(sources.map(async (f) => [f, createHash26("sha256").update(await readFile31(join50(cwd, f))).digest("hex")])));
25228
25592
  const build2 = async (repeat) => {
25229
25593
  ensurePrismaClient(cwd, candidate.web?.appDir ?? "");
25230
25594
  const driver = drivers(repeat);
@@ -25235,14 +25599,14 @@ import {pathToFileURL} from 'node:url';
25235
25599
  const environment=${JSON.stringify(scenario.environment)},calls=${JSON.stringify(calls)};
25236
25600
  for(const [key,value] of Object.entries(environment))if(process.env[key]===undefined)process.env[key]=value;
25237
25601
  try{
25238
- const module=await import(pathToFileURL(${JSON.stringify(join49(cwd, candidate.file))}).href);
25602
+ const module=await import(pathToFileURL(${JSON.stringify(join50(cwd, candidate.file))}).href);
25239
25603
  const fn=module[${JSON.stringify(candidate.exportName)}]??module.default?.[${JSON.stringify(candidate.exportName)}];
25240
25604
  if(typeof fn!=='function')throw new Error(${JSON.stringify(`${candidate.exportName} is not an exported function of ${candidate.file}`)});
25241
25605
  // {"$agenttwin:fn": name} in the scenario stands for a function the workflow calls on its argument (streamer.append):
25242
25606
  // it records each call and returns undefined.
25243
25607
  const invoked=[];let slackClient;
25244
25608
  // A Slack WebClient from the app's own dependencies (Bolt ships @slack/web-api); the twin routes slack.com calls.
25245
- const slack=async()=>{if(slackClient)return slackClient;const {createRequire}=await import('node:module');const req=createRequire(${JSON.stringify(join49(cwd, "package.json"))});let WebClient;try{({WebClient}=req('@slack/web-api'));}catch{({WebClient}=req('@slack/bolt').webApi);}return slackClient=new WebClient(process.env.SLACK_BOT_TOKEN??'xoxb-agenttwin');};
25609
+ const slack=async()=>{if(slackClient)return slackClient;const {createRequire}=await import('node:module');const req=createRequire(${JSON.stringify(join50(cwd, "package.json"))});let WebClient;try{({WebClient}=req('@slack/web-api'));}catch{({WebClient}=req('@slack/bolt').webApi);}return slackClient=new WebClient(process.env.SLACK_BOT_TOKEN??'xoxb-agenttwin');};
25246
25610
  const hydrate=async v=>Array.isArray(v)?Promise.all(v.map(hydrate)):v&&typeof v==='object'?(typeof v[${JSON.stringify(FN2)}]==='string'?(()=>{const name=v[${JSON.stringify(FN2)}];return async(...a)=>{invoked.push({fn:name,args:a.length});if(/^logger./.test(name))console.error('[app '+name+']',...a);};})()
25247
25611
  :v[${JSON.stringify(SLACK_CLIENT)}]?await slack()
25248
25612
  :typeof v[${JSON.stringify(SAY)}]==='string'?(()=>{const channel=v[${JSON.stringify(SAY)}];return async m=>(await slack()).chat.postMessage(typeof m==='string'?{channel,text:m}:{channel,...m});})()
@@ -25254,8 +25618,8 @@ setTimeout(()=>process.exit(),1000).unref();
25254
25618
  `;
25255
25619
  const serveEntry = serve?.entry ?? candidate.file;
25256
25620
  const workersConfig = (() => {
25257
- for (let dir = posix5.dirname(serveEntry); ; dir = posix5.dirname(dir)) {
25258
- for (const f of ["wrangler.jsonc", "wrangler.json", "wrangler.toml"]) if (existsSync8(join49(cwd, dir, f))) return join49(cwd, dir, f);
25621
+ for (let dir = posix6.dirname(serveEntry); ; dir = posix6.dirname(dir)) {
25622
+ for (const f of ["wrangler.jsonc", "wrangler.json", "wrangler.toml"]) if (existsSync9(join50(cwd, dir, f))) return join50(cwd, dir, f);
25259
25623
  if (dir === "." || dir === "/" || dir === "") return void 0;
25260
25624
  }
25261
25625
  })();
@@ -25263,7 +25627,7 @@ setTimeout(()=>process.exit(),1000).unref();
25263
25627
  import {pathToFileURL} from 'node:url';
25264
25628
  import {spawn} from 'node:child_process';
25265
25629
  import net from 'node:net';
25266
- const environment=${JSON.stringify(scenario.environment)},calls=${JSON.stringify(calls)},listenPort=${JSON.stringify(serve.listenPort ?? null)},script=${JSON.stringify(serve.script ? { ...serve.script, dir: join49(cwd, serve.script.dir) } : null)},root=${JSON.stringify(cwd)};
25630
+ const environment=${JSON.stringify(scenario.environment)},calls=${JSON.stringify(calls)},listenPort=${JSON.stringify(serve.listenPort ?? null)},script=${JSON.stringify(serve.script ? { ...serve.script, dir: join50(cwd, serve.script.dir) } : null)},root=${JSON.stringify(cwd)};
25267
25631
  for(const [key,value] of Object.entries(environment))if(process.env[key]===undefined)process.env[key]=value;
25268
25632
  const signature=${JSON.stringify(scenario.signature ?? null)};
25269
25633
  ${SIGNING_DRIVER}
@@ -25308,8 +25672,8 @@ try{
25308
25672
  const bound=[];const listen0=net.Server.prototype.listen;
25309
25673
  net.Server.prototype.listen=function(...a){this.once('listening',()=>{const ad=this.address();if(ad&&typeof ad==='object'&&!bound.includes(ad.port))bound.push(ad.port);});return listen0.apply(this,a);};
25310
25674
  const workersConfig=${JSON.stringify(workersConfig ?? null)};
25311
- let workers;if(workersConfig){const {writeFileSync}=await import('node:fs');const shim=${JSON.stringify(join49(cwd, ".agenttwin", "workers-env.mjs"))};writeFileSync(shim,${JSON.stringify(WORKERS_ENV)});workers=await import(pathToFileURL(shim).href);workers.install();}
25312
- const module=await import(pathToFileURL(${JSON.stringify(join49(cwd, serveEntry))}).href);
25675
+ let workers;if(workersConfig){const {writeFileSync}=await import('node:fs');const shim=${JSON.stringify(join50(cwd, ".agenttwin", "workers-env.mjs"))};writeFileSync(shim,${JSON.stringify(WORKERS_ENV)});workers=await import(pathToFileURL(shim).href);workers.install();}
25676
+ const module=await import(pathToFileURL(${JSON.stringify(join50(cwd, serveEntry))}).href);
25313
25677
  const workersEnv=workers?await workers.environment(workersConfig,module):undefined;
25314
25678
  const quick=async ports=>{const end=Date.now()+3000;while(Date.now()<end){for(const p of [...ports,...bound,...printed])if(p&&!taken.has(p)&&await open(p))return p;await new Promise(r=>setTimeout(r,100));}};
25315
25679
  port=await quick([free,listenPort]);
@@ -25352,10 +25716,12 @@ try{
25352
25716
  // A provider webhook arrives signed, as the provider sends it.
25353
25717
  const signed=signature?await signWebhook(signature.scheme,signingSecret(signature),JSON.stringify(args[0]??{})):{};
25354
25718
  // A redirect is the route's answer (to a hosted checkout page, a sign-in page); the browser would go there next.
25355
- const response=await fetch('http://127.0.0.1:'+port+${JSON.stringify(serve.path)},{redirect:'manual',method:${JSON.stringify(serve.method)},headers:{...signed,'content-type':'application/json','idempotency-key':'agenttwin-'+[...JSON.stringify(args[0]??{})].reduce((h,c)=>(h*31+c.charCodeAt(0))>>>0,7).toString(16)},...(${JSON.stringify(serve.method)}==='GET'?{}:{body:JSON.stringify(args[0]??{})})});
25719
+ // A GET carries its input as the query string (an OAuth callback's code and state).
25720
+ const query=${JSON.stringify(serve.method)}==='GET'&&args[0]&&typeof args[0]==='object'&&!Array.isArray(args[0])?new URLSearchParams(Object.entries(args[0]).map(([k,v])=>[k,typeof v==='string'?v:JSON.stringify(v)])).toString():'';
25721
+ const response=await fetch('http://127.0.0.1:'+port+${JSON.stringify(serve.path)}+(query?'?'+query:''),{redirect:'manual',method:${JSON.stringify(serve.method)},headers:{...signed,'content-type':'application/json','idempotency-key':'agenttwin-'+[...JSON.stringify(args[0]??{})].reduce((h,c)=>(h*31+c.charCodeAt(0))>>>0,7).toString(16)},...(${JSON.stringify(serve.method)}==='GET'?{}:{body:JSON.stringify(args[0]??{})})});
25356
25722
  const text=await response.text();
25357
25723
  console.log(JSON.stringify({schema:'agenttwin/call-result-v1',call:index+1,status:response.status,result:text.slice(0,2000)||response.headers.get('location')||''}));
25358
- if(response.status>=400){console.error('HTTP '+response.status+' from ${serve.method} ${serve.path}: '+text.slice(0,300));process.exitCode=1;}
25724
+ if(response.status>=400){console.error('HTTP '+response.status+' from ${serve.method} ${serve.path}: '+text.slice(0,800));process.exitCode=1;}
25359
25725
  }
25360
25726
  // Work the handler does after answering still runs: give it a moment.
25361
25727
  if(script)await new Promise(r=>setTimeout(r,1000));
@@ -25380,7 +25746,7 @@ const free=await new Promise(resolve=>{const s=net.createServer();s.listen(0,'12
25380
25746
  process.env.PORT=String(free);
25381
25747
  // Bolt's own start() settles once its Socket Mode connection is open: hold on to it.
25382
25748
  let started;
25383
- try{const {App}=createRequire(${JSON.stringify(join49(cwd, "package.json"))})('@slack/bolt');const start=App.prototype.start;App.prototype.start=function(...a){const p=start.apply(this,a);started=Promise.resolve(p).then(()=>this.receiver?.constructor?.name??'receiver');return p;};}catch(error){console.error('Could not load @slack/bolt: '+error.message);}
25749
+ try{const {App}=createRequire(${JSON.stringify(join50(cwd, "package.json"))})('@slack/bolt');const start=App.prototype.start;App.prototype.start=function(...a){const p=start.apply(this,a);started=Promise.resolve(p).then(()=>this.receiver?.constructor?.name??'receiver');return p;};}catch(error){console.error('Could not load @slack/bolt: '+error.message);}
25384
25750
  const route=(JSON.parse(process.env.AGENTTWIN_ROUTES||'{}').routes||[]).find(r=>r.host==='slack.com');
25385
25751
  // Calls made as the workspace, not the app: straight to the twin, with the run token beside the caller's own token.
25386
25752
  const slack=async(method,token,params,path='/api/'+method)=>{
@@ -25390,7 +25756,7 @@ const slack=async(method,token,params,path='/api/'+method)=>{
25390
25756
  };
25391
25757
  try{
25392
25758
  if(!route)throw new Error('No Slack twin serves slack.com in this run.');
25393
- await import(pathToFileURL(${JSON.stringify(join49(cwd, candidate.file))}).href);
25759
+ await import(pathToFileURL(${JSON.stringify(join50(cwd, candidate.file))}).href);
25394
25760
  const end=Date.now()+20000;while(!started&&Date.now()<end)await new Promise(r=>setTimeout(r,100));
25395
25761
  if(!started)throw new Error('The app did not call app.start() within 20 seconds.');
25396
25762
  const receiver=await Promise.race([started,new Promise((_,reject)=>setTimeout(()=>reject(new Error('The app did not connect to Slack within 20 seconds.')),20000))]);
@@ -25430,7 +25796,7 @@ import {pathToFileURL} from 'node:url';
25430
25796
  const environment=${JSON.stringify(scenario.environment)},calls=${JSON.stringify(calls)};
25431
25797
  for(const [key,value] of Object.entries(environment))if(process.env[key]===undefined)process.env[key]=value;
25432
25798
  try{
25433
- const module=await import(pathToFileURL(${JSON.stringify(join49(cwd, candidate.file))}).href);
25799
+ const module=await import(pathToFileURL(${JSON.stringify(join50(cwd, candidate.file))}).href);
25434
25800
  const fn=module[${JSON.stringify(candidate.exportName)}];
25435
25801
  if(typeof fn!=='function')throw new Error(${JSON.stringify(`${candidate.exportName} is not an exported function of ${candidate.file}`)});
25436
25802
  for(const [index,args] of calls.entries()){
@@ -25438,7 +25804,7 @@ try{
25438
25804
  const response=await fn(request,{params:Promise.resolve(${JSON.stringify(web.params)})});
25439
25805
  const status=response?.status??200,text=response&&typeof response.text==='function'?await response.text():JSON.stringify(response??null);
25440
25806
  console.log(JSON.stringify({schema:'agenttwin/call-result-v1',call:index+1,status,result:text.slice(0,2000)}));
25441
- if(status>=400){console.error('HTTP '+status+' from ${web.method} ${web.path}: '+text.slice(0,300));process.exitCode=1;}
25807
+ if(status>=400){console.error('HTTP '+status+' from ${web.method} ${web.path}: '+text.slice(0,800));process.exitCode=1;}
25442
25808
  }
25443
25809
  }catch(error){console.error(error);process.exitCode=1;}
25444
25810
  setTimeout(()=>process.exit(),1000).unref();
@@ -25447,7 +25813,7 @@ setTimeout(()=>process.exit(),1000).unref();
25447
25813
  import {spawn} from 'node:child_process';
25448
25814
  import {createRequire} from 'node:module';
25449
25815
  import net from 'node:net';
25450
- const environment=${JSON.stringify(scenario.environment)},calls=${JSON.stringify(calls)},appDir=${JSON.stringify(join49(cwd, web.appDir))};
25816
+ const environment=${JSON.stringify(scenario.environment)},calls=${JSON.stringify(calls)},appDir=${JSON.stringify(join50(cwd, web.appDir))};
25451
25817
  const env={...process.env,NEXT_TELEMETRY_DISABLED:'1'};for(const [key,value] of Object.entries(environment))if(env[key]===undefined)env[key]=value;
25452
25818
  const port=await new Promise(resolve=>{const s=net.createServer();s.listen(0,'127.0.0.1',()=>{const p=s.address().port;s.close(()=>resolve(p));});});
25453
25819
  env.PORT=String(port);
@@ -25505,7 +25871,7 @@ try{
25505
25871
  const response=await call(${JSON.stringify(web.path)}+${JSON.stringify(scenario.query ? "?" + scenario.query : "")},{method:${JSON.stringify(web.method)},headers:{'content-type':'application/json','idempotency-key':'agenttwin-'+[...payload].reduce((h,c)=>(h*31+c.charCodeAt(0))>>>0,7).toString(16),...signed},...(${JSON.stringify(web.method)}==='GET'?{}:{body:payload})});
25506
25872
  const text=await response.text();
25507
25873
  console.log(JSON.stringify({schema:'agenttwin/call-result-v1',call:index+1,status:response.status,result:text.slice(0,2000)}));
25508
- if(response.status>=400){console.error('HTTP '+response.status+' from ${web.method} ${web.path}: '+text.slice(0,300));process.exitCode=1;}
25874
+ if(response.status>=400){console.error('HTTP '+response.status+' from ${web.method} ${web.path}: '+text.slice(0,800));process.exitCode=1;}
25509
25875
  }
25510
25876
  // Work the handler scheduled after responding (after(), queued jobs) still runs: wait until the server goes quiet.
25511
25877
  const settleBy=Date.now()+30000;lastOutput=Date.now();
@@ -25519,15 +25885,15 @@ import {spawn} from 'node:child_process';
25519
25885
  const environment=${JSON.stringify(scenario.environment)},calls=${JSON.stringify(calls)};
25520
25886
  const env={...process.env};for(const [key,value] of Object.entries(environment))if(env[key]===undefined)env[key]=value;
25521
25887
  for(const [index] of calls.entries()){
25522
- const exitCode=await new Promise(resolve=>{const child=spawn(process.execPath,[...process.execArgv,${JSON.stringify(join49(cwd, candidate.file))}],{cwd:${JSON.stringify(cwd)},env,stdio:['ignore','inherit','inherit']});child.once('error',error=>{console.error(error);resolve(1);});child.once('exit',code=>resolve(code??1));});
25888
+ const exitCode=await new Promise(resolve=>{const child=spawn(process.execPath,[...process.execArgv,${JSON.stringify(join50(cwd, candidate.file))}],{cwd:${JSON.stringify(cwd)},env,stdio:['ignore','inherit','inherit']});child.once('error',error=>{console.error(error);resolve(1);});child.once('exit',code=>resolve(code??1));});
25523
25889
  console.log(JSON.stringify({schema:'agenttwin/call-result-v1',call:index+1,result:{exitCode}}));
25524
25890
  if(exitCode!==0){console.error(${JSON.stringify(candidate.file)}+' exited with code '+exitCode);process.exitCode=1;}
25525
25891
  }
25526
25892
  ` : void 0;
25527
25893
  if (candidate.python) {
25528
25894
  const pyDriver = driver.replace(/\.mjs$/, ".py");
25529
- const venv = [".venv/bin/python", "venv/bin/python", ".venv/Scripts/python.exe"].map((p) => join49(cwd, p)).find((p) => existsSync8(p));
25530
- await writeFile23(join49(cwd, pyDriver), `# Generated by AgentTwin: runs ${candidate.file} as a script on twins.
25895
+ const venv = [".venv/bin/python", "venv/bin/python", ".venv/Scripts/python.exe"].map((p) => join50(cwd, p)).find((p) => existsSync9(p));
25896
+ await writeFile23(join50(cwd, pyDriver), `# Generated by AgentTwin: runs ${candidate.file} as a script on twins.
25531
25897
  import json, os, subprocess, sys
25532
25898
  environment = json.loads(${JSON.stringify(JSON.stringify(scenario.environment))})
25533
25899
  env = dict(os.environ)
@@ -25535,7 +25901,7 @@ for key, value in environment.items():
25535
25901
  env.setdefault(key, value)
25536
25902
  status = 0
25537
25903
  for index in range(${calls.length}):
25538
- code = subprocess.call([sys.executable, ${JSON.stringify(join49(cwd, candidate.file))}], cwd=${JSON.stringify(cwd)}, env=env)
25904
+ code = subprocess.call([sys.executable, ${JSON.stringify(join50(cwd, candidate.file))}], cwd=${JSON.stringify(cwd)}, env=env)
25539
25905
  print(json.dumps({"schema": "agenttwin/call-result-v1", "call": index + 1, "result": {"exitCode": code}}), flush=True)
25540
25906
  if code != 0:
25541
25907
  print(${JSON.stringify(candidate.file)} + " exited with code " + str(code), file=sys.stderr, flush=True)
@@ -25545,7 +25911,7 @@ sys.exit(status)
25545
25911
  const spec2 = parseWorld({ ...world, files: [pyDriver, ...sources], command: [venv ?? "python3", pyDriver] });
25546
25912
  return { dir: cwd, spec: spec2, sourceDigests: await sourceDigests() };
25547
25913
  }
25548
- await writeFile23(join49(cwd, driver), boltDriver ?? scriptDriver ?? nextDriver ?? webDriver ?? serveDriver ?? functionDriver, { mode: 384 });
25914
+ await writeFile23(join50(cwd, driver), boltDriver ?? scriptDriver ?? nextDriver ?? webDriver ?? serveDriver ?? functionDriver, { mode: 384 });
25549
25915
  const spec = parseWorld({ ...world, files: [driver, ...sources], command: ["node", ...loader ? ["--import", loader] : [], driver] });
25550
25916
  return { dir: cwd, spec, sourceDigests: await sourceDigests() };
25551
25917
  };
@@ -25553,19 +25919,25 @@ sys.exit(status)
25553
25919
  }
25554
25920
  function ensurePrismaClient(cwd, appDir) {
25555
25921
  const schemas = /* @__PURE__ */ new Set();
25556
- for (const dir of [join49(cwd, appDir), cwd]) for (const s of [join49(dir, "prisma", "schema.prisma"), join49(dir, "schema.prisma")]) if (existsSync8(s)) schemas.add(s);
25922
+ for (const dir of [join50(cwd, appDir), cwd]) for (const s of [join50(dir, "prisma", "schema.prisma"), join50(dir, "schema.prisma")]) if (existsSync9(s)) schemas.add(s);
25557
25923
  for (const group of ["packages", "apps", "libs"]) try {
25558
- for (const name of readdirSync4(join49(cwd, group))) for (const s of [join49(cwd, group, name, "prisma", "schema.prisma"), join49(cwd, group, name, "schema.prisma")]) if (existsSync8(s)) schemas.add(s);
25924
+ for (const name of readdirSync5(join50(cwd, group))) for (const s of [join50(cwd, group, name, "prisma", "schema.prisma"), join50(cwd, group, name, "schema.prisma")]) if (existsSync9(s)) schemas.add(s);
25559
25925
  } catch {
25560
25926
  }
25561
25927
  for (const schema of schemas) {
25562
- const text3 = readFileSync10(schema, "utf8"), pkgDir = dirname12(dirname12(schema)).endsWith("prisma") ? dirname12(dirname12(schema)) : existsSync8(join49(dirname12(schema), "..", "package.json")) ? join49(dirname12(schema), "..") : dirname12(schema);
25928
+ const text3 = readFileSync11(schema, "utf8"), pkgDir = dirname12(dirname12(schema)).endsWith("prisma") ? dirname12(dirname12(schema)) : existsSync9(join50(dirname12(schema), "..", "package.json")) ? join50(dirname12(schema), "..") : dirname12(schema);
25563
25929
  const output = /generator\s+\w+\s*\{[^}]*\boutput\s*=\s*"([^"]+)"/.exec(text3)?.[1];
25564
- const req = createRequire5(join49(pkgDir, "package.json"));
25565
- const generated = output ? existsSync8(join49(dirname12(schema), output)) : (() => {
25930
+ const req = createRequire5(join50(pkgDir, "package.json"));
25931
+ const generated = output ? existsSync9(join50(dirname12(schema), output)) : (() => {
25566
25932
  try {
25567
- req.resolve(".prisma/client/default");
25568
- return true;
25933
+ const dir = dirname12(req.resolve(".prisma/client/default"));
25934
+ return !["default.js", "index.js"].some((f) => {
25935
+ try {
25936
+ return readFileSync11(join50(dir, f), "utf8").includes("did not initialize yet");
25937
+ } catch {
25938
+ return false;
25939
+ }
25940
+ });
25569
25941
  } catch {
25570
25942
  return false;
25571
25943
  }
@@ -25573,12 +25945,18 @@ function ensurePrismaClient(cwd, appDir) {
25573
25945
  if (generated) continue;
25574
25946
  let bin;
25575
25947
  for (let dir = pkgDir; dir.startsWith(cwd) && !bin; dir = dirname12(dir)) {
25576
- const b = join49(dir, "node_modules", ".bin", "prisma");
25577
- if (existsSync8(b)) bin = b;
25948
+ const b = join50(dir, "node_modules", ".bin", "prisma");
25949
+ if (existsSync9(b)) bin = b;
25578
25950
  if (dir === cwd) break;
25579
25951
  }
25580
25952
  if (!bin) continue;
25581
- const result2 = spawnSync2(bin, ["generate", "--schema", schema], { cwd: pkgDir, stdio: "pipe", timeout: 18e4, env: { ...process.env, PRISMA_HIDE_UPDATE_MESSAGE: "1" } });
25953
+ const bins = [];
25954
+ for (let dir = pkgDir; dir.startsWith(cwd); dir = dirname12(dir)) {
25955
+ const b = join50(dir, "node_modules", ".bin");
25956
+ if (existsSync9(b)) bins.push(b);
25957
+ if (dir === cwd) break;
25958
+ }
25959
+ const result2 = spawnSync3(bin, ["generate", "--schema", schema], { cwd: pkgDir, stdio: "pipe", timeout: 18e4, env: { ...BUILD_PLACEHOLDERS, ...process.env, PRISMA_HIDE_UPDATE_MESSAGE: "1", PATH: [...bins, process.env.PATH ?? ""].join(delimiter3) } });
25582
25960
  if (result2.status !== 0) process.stderr.write(` prisma generate failed for ${relative14(cwd, schema)}: ${String(result2.stderr ?? "").trim().split("\n").slice(-2).join(" ")}
25583
25961
  `);
25584
25962
  }
@@ -25586,7 +25964,7 @@ function ensurePrismaClient(cwd, appDir) {
25586
25964
  function usesPostgresDriver(cwd) {
25587
25965
  const deps = (dir) => {
25588
25966
  try {
25589
- const p = JSON.parse(readFileSync10(join49(cwd, dir, "package.json"), "utf8"));
25967
+ const p = JSON.parse(readFileSync11(join50(cwd, dir, "package.json"), "utf8"));
25590
25968
  return Object.keys({ ...p.dependencies, ...p.devDependencies });
25591
25969
  } catch {
25592
25970
  return [];
@@ -25594,14 +25972,14 @@ function usesPostgresDriver(cwd) {
25594
25972
  };
25595
25973
  const dirs = ["."];
25596
25974
  for (const base of ["packages", "apps", "services", "server", "backend"]) try {
25597
- for (const e of readdirSync4(join49(cwd, base), { withFileTypes: true })) if (e.isDirectory()) dirs.push(join49(base, e.name));
25975
+ for (const e of readdirSync5(join50(cwd, base), { withFileTypes: true })) if (e.isDirectory()) dirs.push(join50(base, e.name));
25598
25976
  dirs.push(base);
25599
25977
  } catch {
25600
25978
  }
25601
25979
  if (dirs.some((d2) => deps(d2).some((n) => POSTGRES_DRIVERS.includes(n)))) return true;
25602
25980
  return dirs.some((d2) => deps(d2).includes("@prisma/client") && ["prisma/schema.prisma", "schema.prisma"].some((f) => {
25603
25981
  try {
25604
- return /provider\s*=\s*"postgres(?:ql)?"/.test(readFileSync10(join49(cwd, d2, f), "utf8"));
25982
+ return /provider\s*=\s*"postgres(?:ql)?"/.test(readFileSync11(join50(cwd, d2, f), "utf8"));
25605
25983
  } catch {
25606
25984
  return false;
25607
25985
  }
@@ -25611,8 +25989,8 @@ async function discoverWorkspaceSchema(cwd, appDir) {
25611
25989
  const own = appDir && appDir !== "." ? await discoverAppPostgresSchema(cwd, appDir) : void 0;
25612
25990
  if (own?.length) return own;
25613
25991
  for (const base of ["packages", "apps", "services"]) try {
25614
- for (const e of readdirSync4(join49(cwd, base), { withFileTypes: true })) if (e.isDirectory()) {
25615
- const found = await discoverAppPostgresSchema(cwd, join49(base, e.name));
25992
+ for (const e of readdirSync5(join50(cwd, base), { withFileTypes: true })) if (e.isDirectory()) {
25993
+ const found = await discoverAppPostgresSchema(cwd, join50(base, e.name));
25616
25994
  if (found?.length) return found;
25617
25995
  }
25618
25996
  } catch {
@@ -25625,6 +26003,7 @@ var init_autoprep = __esm({
25625
26003
  "use strict";
25626
26004
  init_http_world();
25627
26005
  init_workers_env();
26006
+ init_setup();
25628
26007
  init_postgres_schema();
25629
26008
  init_rabbitmq_assertions();
25630
26009
  init_kafka_assertions();
@@ -25664,7 +26043,7 @@ var init_autoprep = __esm({
25664
26043
  };
25665
26044
  readFileSyncSafe = (path2) => {
25666
26045
  try {
25667
- return readFileSync10(path2, "utf8");
26046
+ return readFileSync11(path2, "utf8");
25668
26047
  } catch {
25669
26048
  return "";
25670
26049
  }
@@ -25815,8 +26194,8 @@ var init_first_run_help = __esm({
25815
26194
  });
25816
26195
 
25817
26196
  // src/flow/twin-gaps.ts
25818
- import { existsSync as existsSync9, mkdirSync, readFileSync as readFileSync11, writeFileSync as writeFileSync2 } from "fs";
25819
- import { join as join50 } from "path";
26197
+ import { existsSync as existsSync10, mkdirSync as mkdirSync2, readFileSync as readFileSync12, writeFileSync as writeFileSync2 } from "fs";
26198
+ import { join as join51 } from "path";
25820
26199
  function twinGap(entry) {
25821
26200
  const m = /^([\w.-]+):\s*(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+(\/[^\s:?]*)/.exec(entry);
25822
26201
  if (!m) return void 0;
@@ -25826,11 +26205,11 @@ function twinGap(entry) {
25826
26205
  function recordTwinGaps(cwd, entries, now = /* @__PURE__ */ new Date()) {
25827
26206
  const labels = [...new Set(entries.map(twinGap).filter((g) => !!g).map(gapLabel))];
25828
26207
  if (!labels.length) return [];
25829
- const dir = join50(cwd, ".agenttwin"), file = join50(dir, "twin-gaps.json");
26208
+ const dir = join51(cwd, ".agenttwin"), file = join51(dir, "twin-gaps.json");
25830
26209
  let data = { version: 1, gaps: {} };
25831
26210
  try {
25832
- if (existsSync9(file)) {
25833
- const read2 = JSON.parse(readFileSync11(file, "utf8"));
26211
+ if (existsSync10(file)) {
26212
+ const read2 = JSON.parse(readFileSync12(file, "utf8"));
25834
26213
  if (read2?.version === 1 && read2.gaps) data = read2;
25835
26214
  }
25836
26215
  } catch {
@@ -25842,7 +26221,7 @@ function recordTwinGaps(cwd, entries, now = /* @__PURE__ */ new Date()) {
25842
26221
  data.gaps[label2] = g;
25843
26222
  }
25844
26223
  try {
25845
- mkdirSync(dir, { recursive: true });
26224
+ mkdirSync2(dir, { recursive: true });
25846
26225
  writeFileSync2(file, JSON.stringify(data, null, 2) + "\n");
25847
26226
  } catch {
25848
26227
  }
@@ -25861,199 +26240,6 @@ var init_twin_gaps = __esm({
25861
26240
  }
25862
26241
  });
25863
26242
 
25864
- // src/flow/setup.ts
25865
- import { spawn as spawn9, spawnSync as spawnSync3 } from "child_process";
25866
- import { existsSync as existsSync10, readFileSync as readFileSync12, readdirSync as readdirSync5 } from "fs";
25867
- import { delimiter as delimiter2, join as join51, posix as posix6 } from "path";
25868
- function packageManager(cwd) {
25869
- const field2 = readJson2(join51(cwd, "package.json"))?.packageManager;
25870
- if (typeof field2 === "string") {
25871
- const [name, version] = field2.split("@");
25872
- if (["npm", "pnpm", "yarn", "bun"].includes(name)) return { name, version: version?.split("+")[0] };
25873
- }
25874
- if (existsSync10(join51(cwd, "pnpm-lock.yaml"))) return { name: "pnpm" };
25875
- if (existsSync10(join51(cwd, "yarn.lock"))) return { name: "yarn" };
25876
- if (existsSync10(join51(cwd, "bun.lock")) || existsSync10(join51(cwd, "bun.lockb"))) return { name: "bun" };
25877
- return { name: "npm" };
25878
- }
25879
- function nodeWanted(range, have = process.versions.node) {
25880
- if (!range || !/\d/.test(range)) return void 0;
25881
- const current2 = Number(have.split(".")[0]);
25882
- const alternatives = range.split("||").map((alt) => [...alt.matchAll(/(>=|<=|>|<|\^|~|=)?\s*v?(\d+)/g)].map((m) => ({ op: m[1] ?? "", major: Number(m[2]) })));
25883
- const satisfied = (cmp2) => cmp2.every(({ op: op2, major }) => op2 === ">=" || op2 === ">" ? current2 >= major : op2 === "<" ? current2 < major : op2 === "<=" ? current2 <= major : current2 === major);
25884
- if (alternatives.some((a) => a.length && satisfied(a))) return void 0;
25885
- const lows = alternatives.flatMap((a) => a.filter((c) => !c.op.startsWith("<")).map((c) => c.major));
25886
- return lows.length ? String(Math.min(...lows.filter((m) => m > current2).concat(lows.every((m) => m <= current2) ? [Math.max(...lows)] : []))) : void 0;
25887
- }
25888
- function unbuiltWorkspacePackages(cwd, appDir) {
25889
- const root2 = readJson2(join51(cwd, "package.json"));
25890
- let patterns = Array.isArray(root2?.workspaces) ? root2.workspaces : Array.isArray(root2?.workspaces?.packages) ? root2.workspaces.packages : [];
25891
- if (existsSync10(join51(cwd, "pnpm-workspace.yaml"))) {
25892
- const text3 = readFileSync12(join51(cwd, "pnpm-workspace.yaml"), "utf8");
25893
- patterns = [...patterns, ...[...text3.matchAll(/^\s*-\s*['"]?([^'"\n#]+)['"]?/gm)].map((m) => m[1].trim())];
25894
- }
25895
- const dirs = /* @__PURE__ */ new Set();
25896
- for (const pattern of patterns) {
25897
- if (pattern.startsWith("!")) continue;
25898
- const base = pattern.replace(/\/\*\*?$/, "");
25899
- if (pattern.endsWith("*")) {
25900
- try {
25901
- for (const e of readdirSync5(join51(cwd, base), { withFileTypes: true })) if (e.isDirectory()) dirs.add(posix6.join(base, e.name));
25902
- } catch {
25903
- }
25904
- } else dirs.add(base);
25905
- }
25906
- let needed;
25907
- if (appDir !== void 0) {
25908
- const byName = /* @__PURE__ */ new Map();
25909
- for (const dir of dirs) {
25910
- const name = readJson2(join51(cwd, dir, "package.json"))?.name;
25911
- if (typeof name === "string") byName.set(name, dir);
25912
- }
25913
- needed = /* @__PURE__ */ new Set();
25914
- const queue = [appDir];
25915
- while (queue.length) {
25916
- const dir = queue.shift();
25917
- const pkg = readJson2(join51(cwd, dir, "package.json"));
25918
- for (const dep of Object.keys({ ...pkg?.dependencies, ...pkg?.devDependencies, ...pkg?.peerDependencies })) {
25919
- const d2 = byName.get(dep);
25920
- if (d2 && !needed.has(d2)) {
25921
- needed.add(d2);
25922
- queue.push(d2);
25923
- }
25924
- }
25925
- }
25926
- }
25927
- const unbuilt = [];
25928
- for (const dir of dirs) {
25929
- if (needed && !needed.has(dir)) continue;
25930
- const pkg = readJson2(join51(cwd, dir, "package.json"));
25931
- if (!pkg) continue;
25932
- const targets = [];
25933
- const collect2 = (v) => {
25934
- if (typeof v === "string") targets.push(v);
25935
- else if (v && typeof v === "object") for (const x of Object.values(v)) collect2(x);
25936
- };
25937
- collect2(pkg.main);
25938
- collect2(pkg.module);
25939
- collect2(pkg.exports?.["."] ?? (typeof pkg.exports === "string" ? pkg.exports : void 0));
25940
- const built = targets.filter((t) => /(^|\/)(dist|build|lib|out)\//.test(t) && !t.includes("*"));
25941
- if (built.length && pkg.scripts?.build && built.every((t) => !existsSync10(join51(cwd, dir, t)))) unbuilt.push(dir);
25942
- }
25943
- return unbuilt.sort();
25944
- }
25945
- function planSetup(cwd, opts = {}) {
25946
- const pm = packageManager(cwd);
25947
- const root2 = readJson2(join51(cwd, "package.json")) ?? {};
25948
- const steps = [];
25949
- const runner = (args) => pm.name === "npm" || has(pm.name) && !(pm.name === "yarn" && pm.version && Number(pm.version.split(".")[0]) >= 2) ? { command: pm.name, args } : has("corepack") ? { command: "corepack", args: [`${pm.name}${pm.version ? "@" + pm.version : ""}`, ...args] } : { command: "npx", args: ["--yes", `${pm.name}${pm.version ? "@" + pm.version : ""}`, ...args] };
25950
- const anyDeps = Object.keys({ ...root2.dependencies, ...root2.devDependencies }).length > 0 || root2.workspaces || existsSync10(join51(cwd, "pnpm-workspace.yaml"));
25951
- if (opts.only !== "build" && anyDeps && !existsSync10(join51(cwd, "node_modules"))) {
25952
- const r = runner(["install"]);
25953
- steps.push({ id: "install", ...r, why: "dependencies are not installed", dir: cwd });
25954
- }
25955
- const unbuilt = steps.length || opts.only === "install" ? [] : unbuiltWorkspacePackages(cwd, opts.appDir);
25956
- if (unbuilt.length) {
25957
- const own = pm.name === "pnpm" ? runner(["-r", ...unbuilt.flatMap((d2) => ["--filter", `./${d2}`]), "run", "build"]) : pm.name === "yarn" ? runner(["workspaces", "foreach", "-R", "--from", `{${unbuilt.join(",")}}`, "run", "build"]) : pm.name === "bun" ? runner(["run", "--filter", "*", "build"]) : runner(["run", "build", ...unbuilt.flatMap((d2) => ["--workspace", d2]), "--if-present"]);
25958
- const turbo = existsSync10(join51(cwd, "turbo.json")) && existsSync10(join51(cwd, "node_modules/.bin/turbo")) ? { command: join51(cwd, "node_modules/.bin/turbo"), args: ["run", "build", ...unbuilt.map((d2) => `--filter=./${d2}`)] } : void 0;
25959
- const r = turbo ? { ...turbo, fallback: own } : own;
25960
- steps.push({ id: "build", ...r, why: `${unbuilt.length} workspace package${unbuilt.length === 1 ? " is" : "s are"} not built yet (${unbuilt.slice(0, 3).join(", ")}${unbuilt.length > 3 ? "\u2026" : ""})`, dir: cwd });
25961
- }
25962
- const want = opts.only === "build" ? void 0 : nodeWanted(root2.engines?.node);
25963
- return { packageManager: pm.name, steps, ...want ? { node: { want, have: process.versions.node, command: `nvm install ${want} && nvm use ${want}` } } : {} };
25964
- }
25965
- function installRetry(step, output) {
25966
- const pm = step.command === "corepack" || step.command === "npx" ? step.args.find((a) => /^(npm|pnpm|yarn|bun)(@|$)/.test(a))?.split("@")[0] : step.command;
25967
- const tail = step.command === "corepack" ? step.args.slice(1) : step.command === "npx" ? step.args.slice(2) : step.args;
25968
- const pinned = step.command === "corepack" || step.command === "npx" ? step.args.find((a) => /^(npm|pnpm|yarn|bun)(@|$)/.test(a)) : pm;
25969
- if (pm === "pnpm" && /ERR_PNPM_(OUTDATED_LOCKFILE|LOCKFILE_CONFIG_MISMATCH|LOCKFILE_MISSING_DEPENDENCY)|frozen.lockfile|specifiers in the lockfile/i.test(output))
25970
- return { why: "The lockfile is behind package.json, so a frozen install stops", step: { ...step, args: [...step.args, "--no-frozen-lockfile"] } };
25971
- if (pm === "yarn" && /YN0028|lockfile would have been modified|--frozen-lockfile/i.test(output))
25972
- return { why: "The lockfile is behind package.json, so a frozen install stops", step: { ...step, args: [...step.args, "--no-immutable"] } };
25973
- if (pm === "pnpm" && /ERR_PNPM_IGNORED_BUILDS/.test(output) && !step.args.some((a) => a.startsWith("--config.dangerously-allow-all-builds")))
25974
- return { why: "pnpm skipped the dependencies' build scripts", step: { ...step, args: [...step.args, "--config.dangerously-allow-all-builds=true"] } };
25975
- if (pm === "bun" && step.command === "corepack")
25976
- return { why: "corepack cannot fetch bun", step: { ...step, command: "npx", args: ["--yes", pinned, ...tail] } };
25977
- if (pm === "npm" && /EBADENGINE|notsup|Unsupported engine/i.test(output) && !step.args.includes("--engine-strict=false"))
25978
- return { why: "The project's engines field does not allow this Node version", step: { ...step, args: [...step.args, "--engine-strict=false"] } };
25979
- }
25980
- async function corepackShims(cwd, steps) {
25981
- const pm = packageManager(cwd).name;
25982
- const managers = [.../* @__PURE__ */ new Set([...steps.filter((s) => s.command === "corepack").map((s) => s.args[0]?.split("@")[0]), pm])].filter((m) => (m === "pnpm" || m === "yarn") && !has(m));
25983
- if (!managers.length || !steps.length || !has("corepack")) return;
25984
- const dir = join51(cwd, ".agenttwin", "bin");
25985
- const ok3 = await new Promise((resolve18) => {
25986
- const c = spawn9("corepack", ["enable", "--install-directory", dir, ...managers], { stdio: "ignore" });
25987
- c.once("error", () => resolve18(false));
25988
- c.once("exit", (code) => resolve18(code === 0));
25989
- });
25990
- return ok3 ? dir : void 0;
25991
- }
25992
- async function runSetup(cwd, opts) {
25993
- const plan = opts.plan ?? planSetup(cwd, { ...opts.appDir !== void 0 ? { appDir: opts.appDir } : {}, ...opts.only ? { only: opts.only } : {} });
25994
- if (plan.node) opts.log(` ! This project asks for Node.js ${plan.node.want}; this machine runs ${plan.node.have}. If the app fails to start, run: ${plan.node.command}`);
25995
- if (!plan.steps.length) return true;
25996
- opts.log(` Before the app can start: ${plan.steps.map((s) => `${show(s)} (${s.why})`).join(", then ")}.`);
25997
- const answer = (await opts.ask({ id: "setup", text: `Run ${plan.steps.length === 1 ? "it" : "them"} now? (Y/n)`, default: "y" })).trim().toLowerCase();
25998
- if (answer.startsWith("n")) {
25999
- opts.log(` Skipped. Run ${plan.steps.map(show).join(" && ")} yourself, then npx agenttwin again.`);
26000
- return false;
26001
- }
26002
- const shims = await corepackShims(cwd, plan.steps);
26003
- const exec11 = (step) => new Promise((resolve18) => {
26004
- const child = spawn9(step.command, step.args, { cwd: step.dir, stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, CI: "1", COREPACK_ENABLE_DOWNLOAD_PROMPT: "0", ...shims ? { PATH: `${shims}${delimiter2}${process.env.PATH ?? ""}` } : {} } });
26005
- let tail = "";
26006
- const keep = (c) => {
26007
- tail = (tail + c.toString()).slice(-4e3);
26008
- };
26009
- child.stdout.on("data", keep);
26010
- child.stderr.on("data", keep);
26011
- child.once("error", (e) => {
26012
- tail += String(e);
26013
- resolve18({ code: 1, tail });
26014
- });
26015
- child.once("exit", (c) => resolve18({ code: c ?? 1, tail }));
26016
- });
26017
- for (const step of plan.steps) {
26018
- opts.log(` Running ${show(step)}\u2026`);
26019
- let { code, tail } = await exec11(step);
26020
- for (let current2 = step, tries = 0; code !== 0 && step.id === "install" && tries < 3; tries++) {
26021
- const retry = installRetry(current2, tail);
26022
- if (!retry) break;
26023
- opts.log(` ${retry.why}; running ${show(retry.step)}\u2026`);
26024
- current2 = retry.step;
26025
- ({ code, tail } = await exec11(retry.step));
26026
- }
26027
- if (code !== 0 && step.fallback) {
26028
- const next = { ...step, ...step.fallback, fallback: void 0 };
26029
- opts.log(` ${show(step)} failed; running ${show(next)}\u2026`);
26030
- ({ code, tail } = await exec11(next));
26031
- }
26032
- if (code !== 0) {
26033
- opts.log(tail.split("\n").filter(Boolean).slice(-6).map((l) => " " + l.slice(0, 200)).join("\n"));
26034
- opts.log(` ${show(step)} failed (exit ${code}). The run goes on; if the app cannot start, fix that first.`);
26035
- return false;
26036
- }
26037
- }
26038
- opts.log(" Setup done.");
26039
- return true;
26040
- }
26041
- var readJson2, has, show;
26042
- var init_setup = __esm({
26043
- "src/flow/setup.ts"() {
26044
- "use strict";
26045
- readJson2 = (file) => {
26046
- try {
26047
- return JSON.parse(readFileSync12(file, "utf8"));
26048
- } catch {
26049
- return void 0;
26050
- }
26051
- };
26052
- has = (cmd) => spawnSync3(process.platform === "win32" ? "where" : "which", [cmd], { stdio: "ignore" }).status === 0;
26053
- show = (s) => [posix6.basename(s.command), ...s.args].join(" ");
26054
- }
26055
- });
26056
-
26057
26243
  // src/flow/gap-sink.ts
26058
26244
  import { createServer as createHttpServer } from "http";
26059
26245
  import { createServer as createTcpServer } from "net";
@@ -26238,15 +26424,15 @@ async function startS3Engine(options = {}) {
26238
26424
  const objects = ensureBucket(bucket) ?? store.get(bucket);
26239
26425
  if (!objects) return error(res, 404, "NoSuchBucket", "The specified bucket does not exist", bucket);
26240
26426
  if (method === "GET" && !url2.searchParams.has("uploads")) {
26241
- const prefix = url2.searchParams.get("prefix") ?? "", delimiter3 = url2.searchParams.get("delimiter");
26427
+ const prefix = url2.searchParams.get("prefix") ?? "", delimiter4 = url2.searchParams.get("delimiter");
26242
26428
  const max = Math.min(Number(url2.searchParams.get("max-keys") ?? 1e3) || 1e3, 1e3);
26243
26429
  const after = url2.searchParams.get("continuation-token") ? Buffer.from(url2.searchParams.get("continuation-token"), "base64").toString() : url2.searchParams.get("start-after") ?? url2.searchParams.get("marker") ?? "";
26244
26430
  let keys = [...objects.keys()].filter((k) => k.startsWith(prefix) && k > after).sort();
26245
26431
  const prefixes = /* @__PURE__ */ new Set();
26246
- if (delimiter3) keys = keys.filter((k) => {
26247
- const rest = k.slice(prefix.length), i = rest.indexOf(delimiter3);
26432
+ if (delimiter4) keys = keys.filter((k) => {
26433
+ const rest = k.slice(prefix.length), i = rest.indexOf(delimiter4);
26248
26434
  if (i < 0) return true;
26249
- prefixes.add(prefix + rest.slice(0, i + delimiter3.length));
26435
+ prefixes.add(prefix + rest.slice(0, i + delimiter4.length));
26250
26436
  return false;
26251
26437
  });
26252
26438
  const page2 = keys.slice(0, max), truncated = keys.length > max;
@@ -29200,6 +29386,14 @@ async function runOneCommand(opts) {
29200
29386
  log(dim(` The project's configuration check stopped the start; ${[changed.set.length ? `set test values for ${names(changed.set)}` : "", changed.cleared.length ? `left ${names(changed.cleared)} unset` : ""].filter(Boolean).join(" and ")}, rerunning.`));
29201
29387
  clean = await track(void 0);
29202
29388
  }
29389
+ const triedInput = /* @__PURE__ */ new Set();
29390
+ for (let round = 0; round < 2 && clean.status === "error" && !clean.blockedCalls.length; round++) {
29391
+ const added = settleInput(prepared.scenario.input, clean.stderr, triedInput);
29392
+ if (!added.length) break;
29393
+ await writeFile26(prepared.scenarioPath, JSON.stringify(prepared.scenario, null, 2) + "\n", { mode: 384 });
29394
+ log(dim(` The route asked for ${added.join(", ")}; added test values to the input, rerunning.`));
29395
+ clean = await track(void 0);
29396
+ }
29203
29397
  for (let round = 0; round < 3 && clean.blockedCalls.length; round++) {
29204
29398
  let learnedTcp = false;
29205
29399
  for (const b of clean.blockedCalls.filter((b2) => b2.kind === "socket" && b2.port)) {
@@ -29698,6 +29892,7 @@ var init_one_command = __esm({
29698
29892
  init_kafka_diagnostics();
29699
29893
  init_kafka();
29700
29894
  init_offline();
29895
+ init_input_fields();
29701
29896
  init_http_world();
29702
29897
  init_local();
29703
29898
  init_seed();