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/api.js +463 -268
- package/dist/dashboard/assets/next/static/chunks/{webpack-e75a66f5f98ea674.js → webpack-fb2ff67c26653fb6.js} +1 -1
- package/dist/dashboard/index.html +2 -2
- package/dist/engine.js +459 -264
- package/dist/gateway.js +463 -268
- package/dist/worker.js +1 -1
- package/dist/world-host.js +1 -1
- package/package.json +1 -1
- /package/dist/dashboard/assets/next/static/{KHyBySEGTsVqoDj5pH2e6 → Hohse_HEIQKL22XK1m9DZ}/_buildManifest.js +0 -0
- /package/dist/dashboard/assets/next/static/{KHyBySEGTsVqoDj5pH2e6 → Hohse_HEIQKL22XK1m9DZ}/_ssgManifest.js +0 -0
package/dist/engine.js
CHANGED
|
@@ -290,7 +290,7 @@ var init_package = __esm({
|
|
|
290
290
|
"package.json"() {
|
|
291
291
|
package_default = {
|
|
292
292
|
name: "agenttwin",
|
|
293
|
-
version: "0.3.
|
|
293
|
+
version: "0.3.36",
|
|
294
294
|
description: "AgentTwin builds digital twins for testing AI agents. The current CLI prepares supported Node.js workflows with synthetic services, failures, and outcome checks.",
|
|
295
295
|
mcpName: "io.github.AgentTwin/agenttwin",
|
|
296
296
|
keywords: [
|
|
@@ -2456,7 +2456,7 @@ function parseWorld(value3) {
|
|
|
2456
2456
|
const services = /* @__PURE__ */ new Map();
|
|
2457
2457
|
const requestPathFaults = /* @__PURE__ */ new Set();
|
|
2458
2458
|
for (const service of v.services) {
|
|
2459
|
-
if (!object(service) || typeof service.name !== "string" || !namePattern.test(service.name) || services.has(service.name)) invalid(
|
|
2459
|
+
if (!object(service) || typeof service.name !== "string" || !namePattern.test(service.name) || services.has(service.name)) invalid(`service names must be unique lowercase identifiers (${object(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"})`);
|
|
2460
2460
|
const item = service;
|
|
2461
2461
|
if (!Array.isArray(item.collections) || !item.collections.length || item.collections.length > 20) invalid("each service needs 1\u201320 collections");
|
|
2462
2462
|
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");
|
|
@@ -21877,6 +21877,25 @@ var init_orm_schema = __esm({
|
|
|
21877
21877
|
// src/flow/postgres-schema.ts
|
|
21878
21878
|
import { lstat as lstat7, readFile as readFile38, readdir as readdir7, realpath as realpath16 } from "fs/promises";
|
|
21879
21879
|
import { isAbsolute as isAbsolute10, join as join48, relative as relative14, resolve as resolve20 } from "path";
|
|
21880
|
+
function migrationOrder(a, b) {
|
|
21881
|
+
const x = a.split(/[\\/]/), y = b.split(/[\\/]/);
|
|
21882
|
+
for (let i = 0; i < Math.min(x.length, y.length); i++) {
|
|
21883
|
+
if (x[i] === y[i]) continue;
|
|
21884
|
+
const dx = /^\d+/.exec(x[i])?.[0], dy = /^\d+/.exec(y[i])?.[0];
|
|
21885
|
+
if (dx && dy && (dx.length < 8 || dy.length < 8)) return x[i].localeCompare(y[i], "en", { numeric: true });
|
|
21886
|
+
return x[i] < y[i] ? -1 : 1;
|
|
21887
|
+
}
|
|
21888
|
+
return x.length - y.length;
|
|
21889
|
+
}
|
|
21890
|
+
function withoutExtensions(sql, available) {
|
|
21891
|
+
const skipped = /* @__PURE__ */ new Set();
|
|
21892
|
+
const out = sql.replace(/CREATE\s+EXTENSION\s+(?:IF\s+NOT\s+EXISTS\s+)?"?([\w-]+)"?[^;]*;/gi, (stmt, name) => {
|
|
21893
|
+
if (available.includes(name.toLowerCase())) return stmt;
|
|
21894
|
+
skipped.add(name.toLowerCase());
|
|
21895
|
+
return `-- AgentTwin: extension ${name} is not in the embedded engine; left out.`;
|
|
21896
|
+
});
|
|
21897
|
+
return { sql: out, skipped: [...skipped] };
|
|
21898
|
+
}
|
|
21880
21899
|
async function discoverAppPostgresSchema(root2, appDir) {
|
|
21881
21900
|
try {
|
|
21882
21901
|
return (await discoverPostgresSchema(join48(root2, appDir))).map((file) => appDir ? join48(appDir, file).split("\\").join("/") : file);
|
|
@@ -21915,7 +21934,7 @@ async function discoverPostgresSchema(root2) {
|
|
|
21915
21934
|
else if (e.isFile() && e.name.endsWith(".sql") && !/^(?:down|.*\.down)\.sql$/i.test(e.name)) files.push(p);
|
|
21916
21935
|
if (files.length > MAX_SCHEMA_FILES) throw new Error("Too many SQL migrations; select a schema snapshot using postgresSchemaFiles.");
|
|
21917
21936
|
}
|
|
21918
|
-
return files.sort(
|
|
21937
|
+
return files.sort(migrationOrder);
|
|
21919
21938
|
};
|
|
21920
21939
|
const configured = [];
|
|
21921
21940
|
for (const file of ["drizzle.config.ts", "drizzle.config.js", "drizzle.config.mjs", "drizzle.config.json"]) {
|
|
@@ -21967,6 +21986,20 @@ async function discoverPostgresSchema(root2) {
|
|
|
21967
21986
|
await named("", 0);
|
|
21968
21987
|
groups2.sort((a, b) => Number(/postgres|pg/i.test(b[0])) - Number(/postgres|pg/i.test(a[0])));
|
|
21969
21988
|
}
|
|
21989
|
+
for (const schema of ["prisma/schema.prisma", "schema.prisma"]) {
|
|
21990
|
+
let text3 = "";
|
|
21991
|
+
try {
|
|
21992
|
+
text3 = await readFile38(join48(root2, schema), "utf8");
|
|
21993
|
+
} catch {
|
|
21994
|
+
continue;
|
|
21995
|
+
}
|
|
21996
|
+
const provider = prismaProvider(text3);
|
|
21997
|
+
if (provider && !/^postgres/.test(provider)) {
|
|
21998
|
+
const dir = schema.replace(/schema\.prisma$/, "") + "migrations/";
|
|
21999
|
+
for (let i = groups2.length - 1; i >= 0; i--) if (groups2[i][0]?.startsWith(dir)) groups2.splice(i, 1);
|
|
22000
|
+
if (!groups2.length) return [];
|
|
22001
|
+
}
|
|
22002
|
+
}
|
|
21970
22003
|
if (groups2.length > 1) {
|
|
21971
22004
|
const applied = [];
|
|
21972
22005
|
for (const [dir, config] of [["supabase/migrations", "supabase/config.toml"], ["prisma/migrations", "prisma/schema.prisma"]]) if (await exists3(config)) {
|
|
@@ -22010,17 +22043,19 @@ async function loadPostgresSchema(root2, files) {
|
|
|
22010
22043
|
${ddl}
|
|
22011
22044
|
`);
|
|
22012
22045
|
}
|
|
22013
|
-
const sql = parts.join("\n");
|
|
22046
|
+
const sql = withoutExtensions(parts.join("\n"), POSTGRES_EXTENSIONS).sql;
|
|
22014
22047
|
return needsSupabase(sql) ? SUPABASE_PLATFORM + "\n" + sql : sql;
|
|
22015
22048
|
}
|
|
22016
|
-
var MAX_SCHEMA_FILES, MAX_SCHEMA_BYTES, schemaExtensions, needsSupabase, SUPABASE_PLATFORM;
|
|
22049
|
+
var MAX_SCHEMA_FILES, MAX_SCHEMA_BYTES, schemaExtensions, prismaProvider, needsSupabase, SUPABASE_PLATFORM;
|
|
22017
22050
|
var init_postgres_schema = __esm({
|
|
22018
22051
|
"src/flow/postgres-schema.ts"() {
|
|
22019
22052
|
"use strict";
|
|
22020
22053
|
init_orm_schema();
|
|
22054
|
+
init_types();
|
|
22021
22055
|
MAX_SCHEMA_FILES = 2e3;
|
|
22022
22056
|
MAX_SCHEMA_BYTES = 16 * 1024 * 1024;
|
|
22023
22057
|
schemaExtensions = (sql) => [...new Set([...sql.matchAll(/CREATE\s+EXTENSION\s+(?:IF\s+NOT\s+EXISTS\s+)?"?([\w-]+)"?/gi)].map((m) => m[1].toLowerCase()))];
|
|
22058
|
+
prismaProvider = (text3) => /datasource\s+\w+\s*\{[^}]*?\bprovider\s*=\s*["']([\w-]+)["']/.exec(text3)?.[1]?.toLowerCase();
|
|
22024
22059
|
needsSupabase = (sql) => /\bauth\.(users|uid|jwt|role)\b|\bstorage\.(buckets|objects)\b|\bto (anon|authenticated|service_role)\b|\bsupabase_realtime\b/i.test(sql);
|
|
22025
22060
|
SUPABASE_PLATFORM = `-- Schema source: Supabase platform (AgentTwin)
|
|
22026
22061
|
DO $$ BEGIN
|
|
@@ -22031,12 +22066,16 @@ END $$;
|
|
|
22031
22066
|
CREATE SCHEMA IF NOT EXISTS auth;
|
|
22032
22067
|
CREATE SCHEMA IF NOT EXISTS storage;
|
|
22033
22068
|
CREATE SCHEMA IF NOT EXISTS extensions;
|
|
22069
|
+
-- Supabase puts extensions in the extensions schema and keeps it on every role's search path.
|
|
22070
|
+
SET search_path TO "$user", public, extensions;
|
|
22071
|
+
CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA extensions;
|
|
22072
|
+
CREATE EXTENSION IF NOT EXISTS pgcrypto WITH SCHEMA extensions;
|
|
22034
22073
|
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);
|
|
22035
22074
|
CREATE OR REPLACE FUNCTION auth.uid() RETURNS uuid LANGUAGE sql STABLE AS $f$ SELECT nullif(current_setting('request.jwt.claim.sub', true), '')::uuid $f$;
|
|
22036
22075
|
CREATE OR REPLACE FUNCTION auth.role() RETURNS text LANGUAGE sql STABLE AS $f$ SELECT nullif(current_setting('request.jwt.claim.role', true), '') $f$;
|
|
22037
22076
|
CREATE OR REPLACE FUNCTION auth.jwt() RETURNS jsonb LANGUAGE sql STABLE AS $f$ SELECT coalesce(nullif(current_setting('request.jwt.claims', true), ''), '{}')::jsonb $f$;
|
|
22038
22077
|
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());
|
|
22039
|
-
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());
|
|
22078
|
+
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());
|
|
22040
22079
|
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 $$;
|
|
22041
22080
|
`;
|
|
22042
22081
|
}
|
|
@@ -23567,6 +23606,65 @@ var init_kafka = __esm({
|
|
|
23567
23606
|
}
|
|
23568
23607
|
});
|
|
23569
23608
|
|
|
23609
|
+
// src/flow/input-fields.ts
|
|
23610
|
+
function missingInputFields(stderr) {
|
|
23611
|
+
const found = /* @__PURE__ */ new Map();
|
|
23612
|
+
for (const m of stderr.matchAll(/HTTP 4\d\d from \S+ \S+?:\s*(\{.*)$/gm)) {
|
|
23613
|
+
let body;
|
|
23614
|
+
try {
|
|
23615
|
+
body = JSON.parse(m[1]);
|
|
23616
|
+
} catch {
|
|
23617
|
+
continue;
|
|
23618
|
+
}
|
|
23619
|
+
const visit = (v) => {
|
|
23620
|
+
if (Array.isArray(v)) {
|
|
23621
|
+
v.forEach(visit);
|
|
23622
|
+
return;
|
|
23623
|
+
}
|
|
23624
|
+
if (!v || typeof v !== "object") return;
|
|
23625
|
+
const o = v;
|
|
23626
|
+
const path2 = Array.isArray(o.path) ? o.path[0] : typeof o.path === "string" ? o.path : typeof o.param === "string" ? o.param : void 0;
|
|
23627
|
+
const text3 = [o.message, o.msg, o.received, o.code].filter((x) => typeof x === "string").join(" ");
|
|
23628
|
+
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 ?? "")))
|
|
23629
|
+
found.set(path2, { name: path2, ...typeof o.expected === "string" ? { expected: o.expected } : {} });
|
|
23630
|
+
if (o.fieldErrors && typeof o.fieldErrors === "object") {
|
|
23631
|
+
for (const [name, list5] of Object.entries(o.fieldErrors))
|
|
23632
|
+
if (Array.isArray(list5) && list5.some((x) => /Required|undefined/i.test(String(x)))) found.set(name, { name });
|
|
23633
|
+
}
|
|
23634
|
+
for (const x of Object.values(o)) if (x && typeof x === "object") visit(x);
|
|
23635
|
+
};
|
|
23636
|
+
visit(body);
|
|
23637
|
+
}
|
|
23638
|
+
return [...found.values()];
|
|
23639
|
+
}
|
|
23640
|
+
function testValueFor(field2) {
|
|
23641
|
+
if (field2.expected === "number" || field2.expected === "integer") return 1;
|
|
23642
|
+
if (field2.expected === "boolean") return true;
|
|
23643
|
+
if (field2.expected === "array") return [];
|
|
23644
|
+
if (field2.expected === "object") return {};
|
|
23645
|
+
const n = field2.name.toLowerCase();
|
|
23646
|
+
if (/email/.test(n)) return "ada@example.com";
|
|
23647
|
+
if (/url|uri|redirect/.test(n)) return "https://example.com/";
|
|
23648
|
+
if (/(^|_)(amount|count|quantity|qty|limit|page)$/.test(n)) return 1;
|
|
23649
|
+
return `test-${field2.name}`;
|
|
23650
|
+
}
|
|
23651
|
+
function settleInput(input, stderr, tried) {
|
|
23652
|
+
if (!input || typeof input !== "object" || Array.isArray(input)) return [];
|
|
23653
|
+
const obj = input, added = [];
|
|
23654
|
+
for (const f of missingInputFields(stderr)) {
|
|
23655
|
+
if (f.name in obj || tried.has(f.name)) continue;
|
|
23656
|
+
tried.add(f.name);
|
|
23657
|
+
obj[f.name] = testValueFor(f);
|
|
23658
|
+
added.push(f.name);
|
|
23659
|
+
}
|
|
23660
|
+
return added;
|
|
23661
|
+
}
|
|
23662
|
+
var init_input_fields = __esm({
|
|
23663
|
+
"src/flow/input-fields.ts"() {
|
|
23664
|
+
"use strict";
|
|
23665
|
+
}
|
|
23666
|
+
});
|
|
23667
|
+
|
|
23570
23668
|
// src/lib/logger.ts
|
|
23571
23669
|
function setQuiet(value3) {
|
|
23572
23670
|
quiet = value3;
|
|
@@ -24971,7 +25069,19 @@ async function analyzeWorkflows(root2, opts = {}) {
|
|
|
24971
25069
|
const fn = f.functions.get(route.name);
|
|
24972
25070
|
const req = fn.params?.[0]?.type === "Identifier" ? fn.params[0].name : "req";
|
|
24973
25071
|
const fields = /* @__PURE__ */ new Set();
|
|
25072
|
+
const aliases2 = /* @__PURE__ */ new Set();
|
|
24974
25073
|
walk3(fn.body, (node) => {
|
|
25074
|
+
if (node.type === "VariableDeclarator" && node.id.type === "Identifier" && node.init) {
|
|
25075
|
+
const init = node.init.type === "TSAsExpression" || node.init.type === "TSSatisfiesExpression" ? node.init.expression : node.init;
|
|
25076
|
+
const names = chain(init);
|
|
25077
|
+
if (names && names[0] === req && names[1] === "body" && names.length === 2) aliases2.add(node.id.name);
|
|
25078
|
+
}
|
|
25079
|
+
});
|
|
25080
|
+
walk3(fn.body, (node) => {
|
|
25081
|
+
if (node.type === "MemberExpression" && !node.computed && node.object.type === "Identifier" && aliases2.has(node.object.name) && node.property.type === "Identifier") fields.add(node.property.name);
|
|
25082
|
+
if (node.type === "VariableDeclarator" && node.id.type === "ObjectPattern" && node.init?.type === "Identifier" && aliases2.has(node.init.name)) {
|
|
25083
|
+
for (const p of node.id.properties) if (p.type === "ObjectProperty" && !p.computed) fields.add(String(p.key.name ?? p.key.value));
|
|
25084
|
+
}
|
|
24975
25085
|
if (node.type === "MemberExpression" && !node.computed) {
|
|
24976
25086
|
const names = chain(node);
|
|
24977
25087
|
if (names && names[0] === req && names[1] === "body" && names[2]) fields.add(names[2]);
|
|
@@ -25243,6 +25353,216 @@ export async function environment(file, module) {
|
|
|
25243
25353
|
}
|
|
25244
25354
|
});
|
|
25245
25355
|
|
|
25356
|
+
// src/flow/setup.ts
|
|
25357
|
+
import { spawn as spawn11, spawnSync as spawnSync2 } from "child_process";
|
|
25358
|
+
import { existsSync as existsSync10, mkdirSync as mkdirSync2, readFileSync as readFileSync10, readdirSync as readdirSync4 } from "fs";
|
|
25359
|
+
import { delimiter as delimiter3, join as join57, posix as posix5 } from "path";
|
|
25360
|
+
function packageManager(cwd) {
|
|
25361
|
+
const field2 = readJson2(join57(cwd, "package.json"))?.packageManager;
|
|
25362
|
+
if (typeof field2 === "string") {
|
|
25363
|
+
const [name, version] = field2.split("@");
|
|
25364
|
+
if (["npm", "pnpm", "yarn", "bun"].includes(name)) return { name, version: version?.split("+")[0] };
|
|
25365
|
+
}
|
|
25366
|
+
if (existsSync10(join57(cwd, "pnpm-lock.yaml"))) return { name: "pnpm" };
|
|
25367
|
+
if (existsSync10(join57(cwd, "yarn.lock"))) return { name: "yarn" };
|
|
25368
|
+
if (existsSync10(join57(cwd, "bun.lock")) || existsSync10(join57(cwd, "bun.lockb"))) return { name: "bun" };
|
|
25369
|
+
return { name: "npm" };
|
|
25370
|
+
}
|
|
25371
|
+
function nodeWanted(range, have = process.versions.node) {
|
|
25372
|
+
if (!range || !/\d/.test(range)) return void 0;
|
|
25373
|
+
const current2 = Number(have.split(".")[0]);
|
|
25374
|
+
const alternatives = range.split("||").map((alt) => [...alt.matchAll(/(>=|<=|>|<|\^|~|=)?\s*v?(\d+)/g)].map((m) => ({ op: m[1] ?? "", major: Number(m[2]) })));
|
|
25375
|
+
const satisfied = (cmp2) => cmp2.every(({ op: op2, major }) => op2 === ">=" || op2 === ">" ? current2 >= major : op2 === "<" ? current2 < major : op2 === "<=" ? current2 <= major : current2 === major);
|
|
25376
|
+
if (alternatives.some((a) => a.length && satisfied(a))) return void 0;
|
|
25377
|
+
const lows = alternatives.flatMap((a) => a.filter((c) => !c.op.startsWith("<")).map((c) => c.major));
|
|
25378
|
+
return lows.length ? String(Math.min(...lows.filter((m) => m > current2).concat(lows.every((m) => m <= current2) ? [Math.max(...lows)] : []))) : void 0;
|
|
25379
|
+
}
|
|
25380
|
+
function unbuiltWorkspacePackages(cwd, appDir) {
|
|
25381
|
+
const root2 = readJson2(join57(cwd, "package.json"));
|
|
25382
|
+
let patterns = Array.isArray(root2?.workspaces) ? root2.workspaces : Array.isArray(root2?.workspaces?.packages) ? root2.workspaces.packages : [];
|
|
25383
|
+
if (existsSync10(join57(cwd, "pnpm-workspace.yaml"))) {
|
|
25384
|
+
const text3 = readFileSync10(join57(cwd, "pnpm-workspace.yaml"), "utf8");
|
|
25385
|
+
patterns = [...patterns, ...[...text3.matchAll(/^\s*-\s*['"]?([^'"\n#]+)['"]?/gm)].map((m) => m[1].trim())];
|
|
25386
|
+
}
|
|
25387
|
+
const dirs2 = /* @__PURE__ */ new Set();
|
|
25388
|
+
for (const pattern of patterns) {
|
|
25389
|
+
if (pattern.startsWith("!")) continue;
|
|
25390
|
+
const base = pattern.replace(/\/\*\*?$/, "");
|
|
25391
|
+
if (pattern.endsWith("*")) {
|
|
25392
|
+
try {
|
|
25393
|
+
for (const e of readdirSync4(join57(cwd, base), { withFileTypes: true })) if (e.isDirectory()) dirs2.add(posix5.join(base, e.name));
|
|
25394
|
+
} catch {
|
|
25395
|
+
}
|
|
25396
|
+
} else dirs2.add(base);
|
|
25397
|
+
}
|
|
25398
|
+
let needed;
|
|
25399
|
+
if (appDir !== void 0) {
|
|
25400
|
+
const byName = /* @__PURE__ */ new Map();
|
|
25401
|
+
for (const dir of dirs2) {
|
|
25402
|
+
const name = readJson2(join57(cwd, dir, "package.json"))?.name;
|
|
25403
|
+
if (typeof name === "string") byName.set(name, dir);
|
|
25404
|
+
}
|
|
25405
|
+
needed = /* @__PURE__ */ new Set();
|
|
25406
|
+
const queue = [appDir];
|
|
25407
|
+
while (queue.length) {
|
|
25408
|
+
const dir = queue.shift();
|
|
25409
|
+
const pkg = readJson2(join57(cwd, dir, "package.json"));
|
|
25410
|
+
for (const dep of Object.keys({ ...pkg?.dependencies, ...pkg?.devDependencies, ...pkg?.peerDependencies })) {
|
|
25411
|
+
const d2 = byName.get(dep);
|
|
25412
|
+
if (d2 && !needed.has(d2)) {
|
|
25413
|
+
needed.add(d2);
|
|
25414
|
+
queue.push(d2);
|
|
25415
|
+
}
|
|
25416
|
+
}
|
|
25417
|
+
}
|
|
25418
|
+
}
|
|
25419
|
+
const unbuilt = [];
|
|
25420
|
+
for (const dir of dirs2) {
|
|
25421
|
+
if (needed && !needed.has(dir)) continue;
|
|
25422
|
+
const pkg = readJson2(join57(cwd, dir, "package.json"));
|
|
25423
|
+
if (!pkg) continue;
|
|
25424
|
+
const targets = [];
|
|
25425
|
+
const collect2 = (v) => {
|
|
25426
|
+
if (typeof v === "string") targets.push(v);
|
|
25427
|
+
else if (v && typeof v === "object") for (const x of Object.values(v)) collect2(x);
|
|
25428
|
+
};
|
|
25429
|
+
collect2(pkg.main);
|
|
25430
|
+
collect2(pkg.module);
|
|
25431
|
+
collect2(pkg.exports?.["."] ?? (typeof pkg.exports === "string" ? pkg.exports : void 0));
|
|
25432
|
+
const built = targets.filter((t) => /(^|\/)(dist|build|lib|out)\//.test(t) && !t.includes("*"));
|
|
25433
|
+
if (built.length && pkg.scripts?.build && built.every((t) => !existsSync10(join57(cwd, dir, t)))) unbuilt.push(dir);
|
|
25434
|
+
}
|
|
25435
|
+
return unbuilt.sort();
|
|
25436
|
+
}
|
|
25437
|
+
function planSetup(cwd, opts = {}) {
|
|
25438
|
+
const pm = packageManager(cwd);
|
|
25439
|
+
const root2 = readJson2(join57(cwd, "package.json")) ?? {};
|
|
25440
|
+
const steps = [];
|
|
25441
|
+
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] };
|
|
25442
|
+
const anyDeps = Object.keys({ ...root2.dependencies, ...root2.devDependencies }).length > 0 || root2.workspaces || existsSync10(join57(cwd, "pnpm-workspace.yaml"));
|
|
25443
|
+
if (opts.only !== "build" && anyDeps && !existsSync10(join57(cwd, "node_modules"))) {
|
|
25444
|
+
const r = runner(["install"]);
|
|
25445
|
+
steps.push({ id: "install", ...r, why: "dependencies are not installed", dir: cwd });
|
|
25446
|
+
}
|
|
25447
|
+
const unbuilt = steps.length || opts.only === "install" ? [] : unbuiltWorkspacePackages(cwd, opts.appDir);
|
|
25448
|
+
if (unbuilt.length) {
|
|
25449
|
+
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"]);
|
|
25450
|
+
const turbo = existsSync10(join57(cwd, "turbo.json")) && existsSync10(join57(cwd, "node_modules/.bin/turbo")) ? { command: join57(cwd, "node_modules/.bin/turbo"), args: ["run", "build", "--continue", "--concurrency=1", ...unbuilt.map((d2) => `--filter=./${d2}`)] } : void 0;
|
|
25451
|
+
const r = turbo ? { ...turbo, fallback: own } : own;
|
|
25452
|
+
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 });
|
|
25453
|
+
}
|
|
25454
|
+
const want = opts.only === "build" ? void 0 : nodeWanted(root2.engines?.node);
|
|
25455
|
+
return { packageManager: pm.name, steps, ...unbuilt.length ? { unbuilt: unbuilt.length } : {}, ...want ? { node: { want, have: process.versions.node, command: `nvm install ${want} && nvm use ${want}` } } : {} };
|
|
25456
|
+
}
|
|
25457
|
+
function installRetry(step, output) {
|
|
25458
|
+
const pm = step.command === "corepack" || step.command === "npx" ? step.args.find((a) => /^(npm|pnpm|yarn|bun)(@|$)/.test(a))?.split("@")[0] : step.command;
|
|
25459
|
+
const tail2 = step.command === "corepack" ? step.args.slice(1) : step.command === "npx" ? step.args.slice(2) : step.args;
|
|
25460
|
+
const pinned = step.command === "corepack" || step.command === "npx" ? step.args.find((a) => /^(npm|pnpm|yarn|bun)(@|$)/.test(a)) : pm;
|
|
25461
|
+
if (pm === "pnpm" && /ERR_PNPM_(OUTDATED_LOCKFILE|LOCKFILE_CONFIG_MISMATCH|LOCKFILE_MISSING_DEPENDENCY)|frozen.lockfile|specifiers in the lockfile/i.test(output))
|
|
25462
|
+
return { why: "The lockfile is behind package.json, so a frozen install stops", step: { ...step, args: [...step.args, "--no-frozen-lockfile"] } };
|
|
25463
|
+
const lockfile = pm === "pnpm" ? /lockfileVersion[\s│|]+of[\s│|]+(\d+)(?:\.(\d+))?[\s│|]+is[\s│|]+incompatible/i.exec(output) : null;
|
|
25464
|
+
if (lockfile) {
|
|
25465
|
+
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}`;
|
|
25466
|
+
if (pinned !== want) return { why: `The lockfile was written by pnpm ${major}, which this pnpm cannot read`, step: { ...step, command: "corepack", args: [want, ...tail2.filter((a) => a !== "--frozen-lockfile")] } };
|
|
25467
|
+
}
|
|
25468
|
+
if (pm === "yarn" && /YN0028|lockfile would have been modified|--frozen-lockfile/i.test(output))
|
|
25469
|
+
return { why: "The lockfile is behind package.json, so a frozen install stops", step: { ...step, args: [...step.args, "--no-immutable"] } };
|
|
25470
|
+
if (pm === "pnpm" && /ERR_PNPM_IGNORED_BUILDS/.test(output) && !step.args.some((a) => a.startsWith("--config.dangerously-allow-all-builds")))
|
|
25471
|
+
return { why: "pnpm skipped the dependencies' build scripts", step: { ...step, args: [...step.args, "--config.dangerously-allow-all-builds=true"] } };
|
|
25472
|
+
if (pm === "bun" && step.command === "corepack")
|
|
25473
|
+
return { why: "corepack cannot fetch bun", step: { ...step, command: "npx", args: ["--yes", pinned, ...tail2] } };
|
|
25474
|
+
if (pm === "npm" && /EBADENGINE|notsup|Unsupported engine/i.test(output) && !step.args.includes("--engine-strict=false"))
|
|
25475
|
+
return { why: "The project's engines field does not allow this Node version", step: { ...step, args: [...step.args, "--engine-strict=false"] } };
|
|
25476
|
+
}
|
|
25477
|
+
async function corepackShims(cwd, steps) {
|
|
25478
|
+
const pm = packageManager(cwd).name;
|
|
25479
|
+
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));
|
|
25480
|
+
if (!managers.length || !steps.length || !has("corepack")) return;
|
|
25481
|
+
const dir = join57(cwd, ".agenttwin", "bin");
|
|
25482
|
+
try {
|
|
25483
|
+
mkdirSync2(dir, { recursive: true });
|
|
25484
|
+
} catch {
|
|
25485
|
+
return;
|
|
25486
|
+
}
|
|
25487
|
+
const ok4 = await new Promise((resolve35) => {
|
|
25488
|
+
const c = spawn11("corepack", ["enable", "--install-directory", dir, ...managers], { stdio: "ignore" });
|
|
25489
|
+
c.once("error", () => resolve35(false));
|
|
25490
|
+
c.once("exit", (code) => resolve35(code === 0));
|
|
25491
|
+
});
|
|
25492
|
+
return ok4 ? dir : void 0;
|
|
25493
|
+
}
|
|
25494
|
+
async function runSetup2(cwd, opts) {
|
|
25495
|
+
const plan = opts.plan ?? planSetup(cwd, { ...opts.appDir !== void 0 ? { appDir: opts.appDir } : {}, ...opts.only ? { only: opts.only } : {} });
|
|
25496
|
+
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}`);
|
|
25497
|
+
if (!plan.steps.length) return true;
|
|
25498
|
+
opts.log(` Before the app can start: ${plan.steps.map((s) => `${show(s)} (${s.why})`).join(", then ")}.`);
|
|
25499
|
+
const answer = (await opts.ask({ id: "setup", text: `Run ${plan.steps.length === 1 ? "it" : "them"} now? (Y/n)`, default: "y" })).trim().toLowerCase();
|
|
25500
|
+
if (answer.startsWith("n")) {
|
|
25501
|
+
opts.log(` Skipped. Run ${plan.steps.map(show).join(" && ")} yourself, then npx agenttwin again.`);
|
|
25502
|
+
return false;
|
|
25503
|
+
}
|
|
25504
|
+
const shims = await corepackShims(cwd, plan.steps);
|
|
25505
|
+
const exec11 = (step) => new Promise((resolve35) => {
|
|
25506
|
+
const child = spawn11(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}${delimiter3}${process.env.PATH ?? ""}` } : {} } });
|
|
25507
|
+
let tail2 = "";
|
|
25508
|
+
const keep = (c) => {
|
|
25509
|
+
tail2 = (tail2 + c.toString()).slice(-4e3);
|
|
25510
|
+
};
|
|
25511
|
+
child.stdout.on("data", keep);
|
|
25512
|
+
child.stderr.on("data", keep);
|
|
25513
|
+
child.once("error", (e) => {
|
|
25514
|
+
tail2 += String(e);
|
|
25515
|
+
resolve35({ code: 1, tail: tail2 });
|
|
25516
|
+
});
|
|
25517
|
+
child.once("exit", (c) => resolve35({ code: c ?? 1, tail: tail2 }));
|
|
25518
|
+
});
|
|
25519
|
+
for (const step of plan.steps) {
|
|
25520
|
+
opts.log(` Running ${show(step)}\u2026`);
|
|
25521
|
+
let { code, tail: tail2 } = await exec11(step);
|
|
25522
|
+
for (let current2 = step, tries = 0; code !== 0 && step.id === "install" && tries < 3; tries++) {
|
|
25523
|
+
const retry = installRetry(current2, tail2);
|
|
25524
|
+
if (!retry) break;
|
|
25525
|
+
opts.log(` ${retry.why}; running ${show(retry.step)}\u2026`);
|
|
25526
|
+
current2 = retry.step;
|
|
25527
|
+
({ code, tail: tail2 } = await exec11(retry.step));
|
|
25528
|
+
}
|
|
25529
|
+
const left = code !== 0 && step.id === "build" && plan.unbuilt ? unbuiltWorkspacePackages(cwd, opts.appDir) : void 0;
|
|
25530
|
+
if (left && left.length < plan.unbuilt) {
|
|
25531
|
+
opts.log(tail2.split("\n").filter((l) => /error|failed|not found|cannot/i.test(l)).slice(-4).map((l) => " " + l.slice(0, 200)).join("\n"));
|
|
25532
|
+
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.`);
|
|
25533
|
+
continue;
|
|
25534
|
+
}
|
|
25535
|
+
if (code !== 0 && step.fallback) {
|
|
25536
|
+
const next = { ...step, ...step.fallback, fallback: void 0 };
|
|
25537
|
+
opts.log(` ${show(step)} failed; running ${show(next)}\u2026`);
|
|
25538
|
+
({ code, tail: tail2 } = await exec11(next));
|
|
25539
|
+
}
|
|
25540
|
+
if (code !== 0) {
|
|
25541
|
+
opts.log(tail2.split("\n").filter(Boolean).slice(-6).map((l) => " " + l.slice(0, 200)).join("\n"));
|
|
25542
|
+
opts.log(` ${show(step)} failed (exit ${code}). The run goes on; if the app cannot start, fix that first.`);
|
|
25543
|
+
return false;
|
|
25544
|
+
}
|
|
25545
|
+
}
|
|
25546
|
+
opts.log(" Setup done.");
|
|
25547
|
+
return true;
|
|
25548
|
+
}
|
|
25549
|
+
var readJson2, has, show, BUILD_PLACEHOLDERS;
|
|
25550
|
+
var init_setup = __esm({
|
|
25551
|
+
"src/flow/setup.ts"() {
|
|
25552
|
+
"use strict";
|
|
25553
|
+
readJson2 = (file) => {
|
|
25554
|
+
try {
|
|
25555
|
+
return JSON.parse(readFileSync10(file, "utf8"));
|
|
25556
|
+
} catch {
|
|
25557
|
+
return void 0;
|
|
25558
|
+
}
|
|
25559
|
+
};
|
|
25560
|
+
has = (cmd) => spawnSync2(process.platform === "win32" ? "where" : "which", [cmd], { stdio: "ignore" }).status === 0;
|
|
25561
|
+
show = (s) => [posix5.basename(s.command), ...s.args].join(" ");
|
|
25562
|
+
BUILD_PLACEHOLDERS = { DATABASE_URL: "postgresql://agenttwin:agenttwin@127.0.0.1:5432/agenttwin", DIRECT_URL: "postgresql://agenttwin:agenttwin@127.0.0.1:5432/agenttwin" };
|
|
25563
|
+
}
|
|
25564
|
+
});
|
|
25565
|
+
|
|
25246
25566
|
// src/runtime/engines/mysql-sql.ts
|
|
25247
25567
|
function tokenize(sql) {
|
|
25248
25568
|
const tokens = [];
|
|
@@ -25976,15 +26296,15 @@ var init_providers = __esm({
|
|
|
25976
26296
|
});
|
|
25977
26297
|
|
|
25978
26298
|
// src/flow/env-values.ts
|
|
25979
|
-
import { readFileSync as
|
|
25980
|
-
import { dirname as dirname16, join as
|
|
26299
|
+
import { readFileSync as readFileSync11 } from "fs";
|
|
26300
|
+
import { dirname as dirname16, join as join58, resolve as resolve22, sep as sep16 } from "path";
|
|
25981
26301
|
function readCommentedExamples(root2, entryFile) {
|
|
25982
26302
|
const top = resolve22(root2), values = {};
|
|
25983
26303
|
for (let directory2 = dirname16(resolve22(top, entryFile)); directory2 === top || directory2.startsWith(top + sep16); directory2 = dirname16(directory2)) {
|
|
25984
26304
|
for (const name of EXAMPLE_FILES) {
|
|
25985
26305
|
let text3;
|
|
25986
26306
|
try {
|
|
25987
|
-
text3 =
|
|
26307
|
+
text3 = readFileSync11(join58(directory2, name), "utf8");
|
|
25988
26308
|
} catch {
|
|
25989
26309
|
continue;
|
|
25990
26310
|
}
|
|
@@ -26011,7 +26331,7 @@ function readEnvExamples(root2, entryFile) {
|
|
|
26011
26331
|
for (const directory2 of folders) for (const name of EXAMPLE_FILES) {
|
|
26012
26332
|
let text3;
|
|
26013
26333
|
try {
|
|
26014
|
-
text3 =
|
|
26334
|
+
text3 = readFileSync11(join58(directory2, name), "utf8");
|
|
26015
26335
|
} catch {
|
|
26016
26336
|
continue;
|
|
26017
26337
|
}
|
|
@@ -26068,12 +26388,14 @@ function envProblems(stderr) {
|
|
|
26068
26388
|
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);
|
|
26069
26389
|
};
|
|
26070
26390
|
for (const block of stderr.split(/\n\s*\},?\s*\n/)) {
|
|
26071
|
-
const path2 = /path:\s*\[
|
|
26391
|
+
const path2 = /path:\s*\[?\s*['"]([A-Z][A-Z0-9_]+)['"]\s*\]?/.exec(block);
|
|
26072
26392
|
if (!path2) continue;
|
|
26073
26393
|
add(path2[1], /received undefined|Required|invalid_type/.test(block) && !/received (?:string|number|boolean)/.test(block));
|
|
26074
26394
|
}
|
|
26075
26395
|
for (const m of stderr.matchAll(/(?:^|[\s{,])["']?([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+)["']?:\s*\[\s*((?:["'][^"'\n]*["']\s*,?\s*)+)\]/gm))
|
|
26076
26396
|
add(m[1], /received undefined|\bRequired\b/.test(m[2]));
|
|
26397
|
+
for (const m of stderr.matchAll(/^\s*-\s+([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+):\s*(.+)$/gm))
|
|
26398
|
+
add(m[1], /received undefined|\bRequired\b/.test(m[2]));
|
|
26077
26399
|
for (const m of stderr.matchAll(/\bbut ([A-Z][A-Z0-9_]+) returned a Promise/g)) add(m[1], false);
|
|
26078
26400
|
for (const line of stderr.split("\n")) {
|
|
26079
26401
|
if (!/env|environment|config|required|missing|not (?:set|defined)|must be|please (?:set|define|provide|add|configure)/i.test(line)) continue;
|
|
@@ -26082,6 +26404,23 @@ function envProblems(stderr) {
|
|
|
26082
26404
|
}
|
|
26083
26405
|
return [...found].map(([name, missing]) => ({ name, missing }));
|
|
26084
26406
|
}
|
|
26407
|
+
function nextConfigProblems(stderr, root2, appDir = "") {
|
|
26408
|
+
if (!/Invalid (?:header|rewrite|redirect)s? found/i.test(stderr)) return [];
|
|
26409
|
+
const names = /* @__PURE__ */ new Set();
|
|
26410
|
+
for (const dir of [.../* @__PURE__ */ new Set([appDir, ""])]) for (const file of ["next.config.js", "next.config.mjs", "next.config.ts", "next.config.cjs"]) {
|
|
26411
|
+
let text3;
|
|
26412
|
+
try {
|
|
26413
|
+
text3 = readFileSync11(join58(root2, dir, file), "utf8");
|
|
26414
|
+
} catch {
|
|
26415
|
+
continue;
|
|
26416
|
+
}
|
|
26417
|
+
for (const m of text3.matchAll(/process\.env\.([A-Z][A-Z0-9_]+)|process\.env\[['"]([A-Z][A-Z0-9_]+)['"]\]/g)) {
|
|
26418
|
+
const n = m[1] ?? m[2];
|
|
26419
|
+
if (n !== "NODE_ENV") names.add(n);
|
|
26420
|
+
}
|
|
26421
|
+
}
|
|
26422
|
+
return [...names].map((name) => ({ name, missing: true }));
|
|
26423
|
+
}
|
|
26085
26424
|
function settleEnvironment(environment, problems, examples, tried, blocked, commented = {}) {
|
|
26086
26425
|
const set2 = [], cleared = [];
|
|
26087
26426
|
for (const { name, missing } of problems) {
|
|
@@ -26112,7 +26451,7 @@ function declaredSettings(root2, appDir) {
|
|
|
26112
26451
|
for (const file of [...EXAMPLE_FILES, "env.ts", "env.mjs", "env.js", "src/env.ts", "src/env.mjs", "src/env.js"]) {
|
|
26113
26452
|
let text3;
|
|
26114
26453
|
try {
|
|
26115
|
-
text3 =
|
|
26454
|
+
text3 = readFileSync11(join58(root2, appDir, file), "utf8");
|
|
26116
26455
|
} catch {
|
|
26117
26456
|
continue;
|
|
26118
26457
|
}
|
|
@@ -26266,11 +26605,11 @@ var init_account_presets = __esm({
|
|
|
26266
26605
|
|
|
26267
26606
|
// src/flow/autoprep.ts
|
|
26268
26607
|
import { mkdir as mkdir22, readFile as readFile41, writeFile as writeFile33 } from "fs/promises";
|
|
26269
|
-
import { existsSync as
|
|
26608
|
+
import { existsSync as existsSync11, readdirSync as readdirSync5, readFileSync as readFileSync12 } from "fs";
|
|
26270
26609
|
import { createHash as createHash28 } from "crypto";
|
|
26271
26610
|
import { createRequire as createRequire6 } from "module";
|
|
26272
|
-
import { spawnSync as
|
|
26273
|
-
import { dirname as dirname17, join as
|
|
26611
|
+
import { spawnSync as spawnSync3 } from "child_process";
|
|
26612
|
+
import { delimiter as delimiter4, dirname as dirname17, join as join59, posix as posix6, relative as relative18 } from "path";
|
|
26274
26613
|
import { pathToFileURL as pathToFileURL2 } from "url";
|
|
26275
26614
|
function fieldValue(name, message, channel) {
|
|
26276
26615
|
const n = name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
|
|
@@ -26391,7 +26730,26 @@ async function generateScenario(candidate, ask, discovered = discoverServices(ca
|
|
|
26391
26730
|
const norm = resolvedAll[i].title.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
26392
26731
|
return o.engine && norm.includes(o.engine.kind) || o.tier === "deep" && o.service?.adapter && norm.includes(o.service.adapter.replace(/-/g, ""));
|
|
26393
26732
|
})));
|
|
26394
|
-
|
|
26733
|
+
let twins2 = discovered.map(resolveTwin);
|
|
26734
|
+
{
|
|
26735
|
+
const byName = /* @__PURE__ */ new Map(), keep = [];
|
|
26736
|
+
twins2.forEach((t, i) => {
|
|
26737
|
+
const name = t.service?.name;
|
|
26738
|
+
const j = name === void 0 ? void 0 : byName.get(name);
|
|
26739
|
+
if (j === void 0) {
|
|
26740
|
+
if (name !== void 0) byName.set(name, i);
|
|
26741
|
+
keep.push(i);
|
|
26742
|
+
return;
|
|
26743
|
+
}
|
|
26744
|
+
const first = twins2[j] = { ...twins2[j], service: structuredClone(twins2[j].service) };
|
|
26745
|
+
for (const c of t.service.collections) if (!first.service.collections.some((x) => x.path === c.path)) first.service.collections.push(structuredClone(c));
|
|
26746
|
+
discovered[j] = { ...discovered[j], calls: [...discovered[j].calls, ...discovered[i].calls] };
|
|
26747
|
+
});
|
|
26748
|
+
if (keep.length < twins2.length) {
|
|
26749
|
+
twins2 = keep.map((i) => twins2[i]);
|
|
26750
|
+
discovered = keep.map((i) => discovered[i]);
|
|
26751
|
+
}
|
|
26752
|
+
}
|
|
26395
26753
|
const plan = (key3) => twins2.find((t, i) => discovered[i].key === key3 && t.service);
|
|
26396
26754
|
const calls = (p) => candidate.calls.filter((c) => c.provider === p || c.provider === `pack:${p}`);
|
|
26397
26755
|
const refunds = calls("stripe").some((c) => /^refunds\.create$/.test(c.operation));
|
|
@@ -26417,7 +26775,7 @@ async function generateScenario(candidate, ask, discovered = discoverServices(ca
|
|
|
26417
26775
|
let input;
|
|
26418
26776
|
if (candidate.bolt) {
|
|
26419
26777
|
if (!channel) channel = "C0AGENTTWIN";
|
|
26420
|
-
const source = root2 ? await readFile41(
|
|
26778
|
+
const source = root2 ? await readFile41(join59(root2, candidate.file), "utf8").catch(() => "") : "";
|
|
26421
26779
|
const stateRefs = [...source.matchAll(/state\??\.values\??\.([A-Za-z_]\w*)\??\.([A-Za-z_]\w*)/g)].map((m) => [m[1], m[2]]);
|
|
26422
26780
|
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)))
|
|
26423
26781
|
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]]);
|
|
@@ -26675,7 +27033,7 @@ async function generateScenario(candidate, ask, discovered = discoverServices(ca
|
|
|
26675
27033
|
if (tables.size) assumptions.push(`PostgreSQL synthetic rows (must satisfy the project schema), seeded with ${[...tables].map(([t, r]) => `${t} ${JSON.stringify(r)}`).join("; ")}.`);
|
|
26676
27034
|
} else if (adapter.startsWith("pack:")) {
|
|
26677
27035
|
const own = discovered[twins2.indexOf(twin)]?.calls ?? [];
|
|
26678
|
-
const manifest = candidate.boltApp && root2 ? await readFile41(
|
|
27036
|
+
const manifest = candidate.boltApp && root2 ? await readFile41(join59(root2, "manifest.json"), "utf8").then((t) => {
|
|
26679
27037
|
const m = JSON.parse(t);
|
|
26680
27038
|
return m && typeof m === "object" && m.settings ? m : void 0;
|
|
26681
27039
|
}).catch(() => void 0) : void 0;
|
|
@@ -26743,12 +27101,12 @@ async function generateScenario(candidate, ask, discovered = discoverServices(ca
|
|
|
26743
27101
|
function upstashSettings(root2, appDir) {
|
|
26744
27102
|
let text3 = "";
|
|
26745
27103
|
try {
|
|
26746
|
-
const pkg = JSON.parse(readFileSyncSafe(
|
|
27104
|
+
const pkg = JSON.parse(readFileSyncSafe(join59(root2, appDir, "package.json")) || "{}");
|
|
26747
27105
|
if (!pkg.dependencies?.["@upstash/redis"]) return void 0;
|
|
26748
27106
|
} catch {
|
|
26749
27107
|
return void 0;
|
|
26750
27108
|
}
|
|
26751
|
-
for (const file of [".env.example", "env.ts", "env.mjs", "src/env.ts", "src/env.mjs", "env.js"]) text3 += readFileSyncSafe(
|
|
27109
|
+
for (const file of [".env.example", "env.ts", "env.mjs", "src/env.ts", "src/env.mjs", "env.js"]) text3 += readFileSyncSafe(join59(root2, appDir, file));
|
|
26752
27110
|
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";
|
|
26753
27111
|
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));
|
|
26754
27112
|
return { url, tokens: tokens.length ? tokens : ["UPSTASH_REDIS_REST_TOKEN"] };
|
|
@@ -26756,7 +27114,7 @@ function upstashSettings(root2, appDir) {
|
|
|
26756
27114
|
async function settleConfiguration(cwd, prepared, stderr, tried) {
|
|
26757
27115
|
const twins2 = prepared.scenario.twins, managed = new Set(twins2.flatMap((t) => [t.envUrl, ...Object.keys(t.env ?? {})]).filter((v) => !!v));
|
|
26758
27116
|
const blocked = (name) => FORBIDDEN_ENV.test(name) || managed.has(name) || DATABASE_ENV.test(name) && twins2.some((t) => t.engine?.kind === "postgres");
|
|
26759
|
-
const changed = settleEnvironment(prepared.scenario.environment, envProblems(stderr), readEnvExamples(cwd, prepared.candidate.file), tried, blocked, readCommentedExamples(cwd, prepared.candidate.file));
|
|
27117
|
+
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));
|
|
26760
27118
|
if (changed.set.length || changed.cleared.length) await writeFile33(prepared.scenarioPath, JSON.stringify(prepared.scenario, null, 2) + "\n", { mode: 384 });
|
|
26761
27119
|
return changed;
|
|
26762
27120
|
}
|
|
@@ -26778,8 +27136,8 @@ function typescriptLoader() {
|
|
|
26778
27136
|
}
|
|
26779
27137
|
async function prepareWorkflow(cwd, candidate, ask, log, discovered) {
|
|
26780
27138
|
const slug5 = slugName(candidate.web ? candidate.title : candidate.exportName);
|
|
26781
|
-
const directory2 =
|
|
26782
|
-
const scenarioPath =
|
|
27139
|
+
const directory2 = join59(cwd, ".agenttwin", "auto", slug5);
|
|
27140
|
+
const scenarioPath = join59(directory2, "scenario.json");
|
|
26783
27141
|
await mkdir22(directory2, { recursive: true });
|
|
26784
27142
|
let scenario2;
|
|
26785
27143
|
try {
|
|
@@ -26861,7 +27219,7 @@ async function prepareWorkflow(cwd, candidate, ask, log, discovered) {
|
|
|
26861
27219
|
const restDatabase = scenario2.services.some((sv) => typeof sv.adapter === "string" && sv.adapter.startsWith("pack:") && (packRecord(sv.adapter.slice(5))?.hosts ?? []).some((h2) => /rest/.test(h2.pathPattern ?? "")));
|
|
26862
27220
|
const servedPostgres = !!candidate.serve && usesPostgresDriver(cwd);
|
|
26863
27221
|
if ((candidate.web?.appDir !== void 0 || restDatabase || servedPostgres) && !scenario2.twins.some((t) => t.engine?.kind === "postgres") && scenario2.postgresSchemaFiles === void 0) {
|
|
26864
|
-
const appDir = candidate.web?.appDir ?? (candidate.serve ?
|
|
27222
|
+
const appDir = candidate.web?.appDir ?? (candidate.serve ? posix6.dirname(candidate.serve.entry ?? candidate.file) : "");
|
|
26865
27223
|
const found = await discoverAppPostgresSchema(cwd, candidate.web?.appDir ?? "");
|
|
26866
27224
|
const files = found?.length ? found : servedPostgres ? await discoverWorkspaceSchema(cwd, appDir) : void 0;
|
|
26867
27225
|
if (files?.length || servedPostgres) {
|
|
@@ -26878,11 +27236,11 @@ async function prepareWorkflow(cwd, candidate, ask, log, discovered) {
|
|
|
26878
27236
|
if (mode !== "auto" && mode !== "explicit") throw new Error("postgresSchemaMode must be auto or explicit.");
|
|
26879
27237
|
const nearest = async () => {
|
|
26880
27238
|
const dirs2 = [];
|
|
26881
|
-
let dir =
|
|
27239
|
+
let dir = posix6.dirname(candidate.file);
|
|
26882
27240
|
while (true) {
|
|
26883
|
-
if (
|
|
27241
|
+
if (existsSync11(join59(cwd, dir, "package.json")) || dir === ".") dirs2.push(dir === "." ? "" : dir);
|
|
26884
27242
|
if (dir === "." || dir === "") break;
|
|
26885
|
-
dir =
|
|
27243
|
+
dir = posix6.dirname(dir);
|
|
26886
27244
|
}
|
|
26887
27245
|
for (const d2 of dirs2) {
|
|
26888
27246
|
const found = d2 ? await discoverAppPostgresSchema(cwd, d2) : await discoverPostgresSchema(cwd);
|
|
@@ -26893,8 +27251,9 @@ async function prepareWorkflow(cwd, candidate, ask, log, discovered) {
|
|
|
26893
27251
|
let files = mode === "auto" ? await nearest() : scenario2.postgresSchemaFiles ?? [];
|
|
26894
27252
|
scenario2.postgresSchemaMode = mode;
|
|
26895
27253
|
let unreadable = false;
|
|
27254
|
+
let skippedExtensions = [];
|
|
26896
27255
|
try {
|
|
26897
|
-
await loadPostgresSchema(cwd, files);
|
|
27256
|
+
skippedExtensions = [...(await loadPostgresSchema(cwd, files)).matchAll(/-- AgentTwin: extension ([\w-]+) is not in the embedded engine/g)].map((m) => m[1]);
|
|
26898
27257
|
} catch (error) {
|
|
26899
27258
|
const why = error instanceof Error ? error.message : String(error);
|
|
26900
27259
|
if (!/Unsupported ORM schema|Unsupported SQL|not supported/i.test(why)) throw error;
|
|
@@ -26910,6 +27269,11 @@ async function prepareWorkflow(cwd, candidate, ask, log, discovered) {
|
|
|
26910
27269
|
const note = "No PostgreSQL schema or migrations were found: the database starts empty and its writes are not checked.";
|
|
26911
27270
|
if (!scenario2.assumptions.includes(note)) scenario2.assumptions.push(note);
|
|
26912
27271
|
} 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).`);
|
|
27272
|
+
if (skippedExtensions.length) {
|
|
27273
|
+
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.`;
|
|
27274
|
+
log(` ${note}`);
|
|
27275
|
+
if (!scenario2.assumptions.includes(note)) scenario2.assumptions.push(note);
|
|
27276
|
+
}
|
|
26913
27277
|
if (files.length) {
|
|
26914
27278
|
const note = "PostgreSQL uses project schema; generated synthetic rows must satisfy its constraints. Review the scenario seeds.";
|
|
26915
27279
|
if (!scenario2.assumptions.includes(note)) scenario2.assumptions.push(note);
|
|
@@ -26935,7 +27299,7 @@ async function prepareWorkflow(cwd, candidate, ask, log, discovered) {
|
|
|
26935
27299
|
services: noChecks ? [...seedTimes(scenario2.services), sentinel] : seedTimes(scenario2.services),
|
|
26936
27300
|
assertions: noChecks ? [{ service: "none", path: "/none", count: 0 }] : scenario2.assertions
|
|
26937
27301
|
});
|
|
26938
|
-
const sourceDigests = async () => Object.fromEntries(await Promise.all(sources.map(async (f) => [f, createHash28("sha256").update(await readFile41(
|
|
27302
|
+
const sourceDigests = async () => Object.fromEntries(await Promise.all(sources.map(async (f) => [f, createHash28("sha256").update(await readFile41(join59(cwd, f))).digest("hex")])));
|
|
26939
27303
|
const build2 = async (repeat) => {
|
|
26940
27304
|
ensurePrismaClient(cwd, candidate.web?.appDir ?? "");
|
|
26941
27305
|
const driver = drivers(repeat);
|
|
@@ -26946,14 +27310,14 @@ import {pathToFileURL} from 'node:url';
|
|
|
26946
27310
|
const environment=${JSON.stringify(scenario2.environment)},calls=${JSON.stringify(calls)};
|
|
26947
27311
|
for(const [key,value] of Object.entries(environment))if(process.env[key]===undefined)process.env[key]=value;
|
|
26948
27312
|
try{
|
|
26949
|
-
const module=await import(pathToFileURL(${JSON.stringify(
|
|
27313
|
+
const module=await import(pathToFileURL(${JSON.stringify(join59(cwd, candidate.file))}).href);
|
|
26950
27314
|
const fn=module[${JSON.stringify(candidate.exportName)}]??module.default?.[${JSON.stringify(candidate.exportName)}];
|
|
26951
27315
|
if(typeof fn!=='function')throw new Error(${JSON.stringify(`${candidate.exportName} is not an exported function of ${candidate.file}`)});
|
|
26952
27316
|
// {"$agenttwin:fn": name} in the scenario stands for a function the workflow calls on its argument (streamer.append):
|
|
26953
27317
|
// it records each call and returns undefined.
|
|
26954
27318
|
const invoked=[];let slackClient;
|
|
26955
27319
|
// A Slack WebClient from the app's own dependencies (Bolt ships @slack/web-api); the twin routes slack.com calls.
|
|
26956
|
-
const slack=async()=>{if(slackClient)return slackClient;const {createRequire}=await import('node:module');const req=createRequire(${JSON.stringify(
|
|
27320
|
+
const slack=async()=>{if(slackClient)return slackClient;const {createRequire}=await import('node:module');const req=createRequire(${JSON.stringify(join59(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');};
|
|
26957
27321
|
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);};})()
|
|
26958
27322
|
:v[${JSON.stringify(SLACK_CLIENT)}]?await slack()
|
|
26959
27323
|
: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});})()
|
|
@@ -26965,8 +27329,8 @@ setTimeout(()=>process.exit(),1000).unref();
|
|
|
26965
27329
|
`;
|
|
26966
27330
|
const serveEntry = serve?.entry ?? candidate.file;
|
|
26967
27331
|
const workersConfig = (() => {
|
|
26968
|
-
for (let dir =
|
|
26969
|
-
for (const f of ["wrangler.jsonc", "wrangler.json", "wrangler.toml"]) if (
|
|
27332
|
+
for (let dir = posix6.dirname(serveEntry); ; dir = posix6.dirname(dir)) {
|
|
27333
|
+
for (const f of ["wrangler.jsonc", "wrangler.json", "wrangler.toml"]) if (existsSync11(join59(cwd, dir, f))) return join59(cwd, dir, f);
|
|
26970
27334
|
if (dir === "." || dir === "/" || dir === "") return void 0;
|
|
26971
27335
|
}
|
|
26972
27336
|
})();
|
|
@@ -26974,7 +27338,7 @@ setTimeout(()=>process.exit(),1000).unref();
|
|
|
26974
27338
|
import {pathToFileURL} from 'node:url';
|
|
26975
27339
|
import {spawn} from 'node:child_process';
|
|
26976
27340
|
import net from 'node:net';
|
|
26977
|
-
const environment=${JSON.stringify(scenario2.environment)},calls=${JSON.stringify(calls)},listenPort=${JSON.stringify(serve.listenPort ?? null)},script=${JSON.stringify(serve.script ? { ...serve.script, dir:
|
|
27341
|
+
const environment=${JSON.stringify(scenario2.environment)},calls=${JSON.stringify(calls)},listenPort=${JSON.stringify(serve.listenPort ?? null)},script=${JSON.stringify(serve.script ? { ...serve.script, dir: join59(cwd, serve.script.dir) } : null)},root=${JSON.stringify(cwd)};
|
|
26978
27342
|
for(const [key,value] of Object.entries(environment))if(process.env[key]===undefined)process.env[key]=value;
|
|
26979
27343
|
const signature=${JSON.stringify(scenario2.signature ?? null)};
|
|
26980
27344
|
${SIGNING_DRIVER}
|
|
@@ -27019,8 +27383,8 @@ try{
|
|
|
27019
27383
|
const bound=[];const listen0=net.Server.prototype.listen;
|
|
27020
27384
|
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);};
|
|
27021
27385
|
const workersConfig=${JSON.stringify(workersConfig ?? null)};
|
|
27022
|
-
let workers;if(workersConfig){const {writeFileSync}=await import('node:fs');const shim=${JSON.stringify(
|
|
27023
|
-
const module=await import(pathToFileURL(${JSON.stringify(
|
|
27386
|
+
let workers;if(workersConfig){const {writeFileSync}=await import('node:fs');const shim=${JSON.stringify(join59(cwd, ".agenttwin", "workers-env.mjs"))};writeFileSync(shim,${JSON.stringify(WORKERS_ENV)});workers=await import(pathToFileURL(shim).href);workers.install();}
|
|
27387
|
+
const module=await import(pathToFileURL(${JSON.stringify(join59(cwd, serveEntry))}).href);
|
|
27024
27388
|
const workersEnv=workers?await workers.environment(workersConfig,module):undefined;
|
|
27025
27389
|
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));}};
|
|
27026
27390
|
port=await quick([free,listenPort]);
|
|
@@ -27063,10 +27427,12 @@ try{
|
|
|
27063
27427
|
// A provider webhook arrives signed, as the provider sends it.
|
|
27064
27428
|
const signed=signature?await signWebhook(signature.scheme,signingSecret(signature),JSON.stringify(args[0]??{})):{};
|
|
27065
27429
|
// A redirect is the route's answer (to a hosted checkout page, a sign-in page); the browser would go there next.
|
|
27066
|
-
|
|
27430
|
+
// A GET carries its input as the query string (an OAuth callback's code and state).
|
|
27431
|
+
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():'';
|
|
27432
|
+
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]??{})})});
|
|
27067
27433
|
const text=await response.text();
|
|
27068
27434
|
console.log(JSON.stringify({schema:'agenttwin/call-result-v1',call:index+1,status:response.status,result:text.slice(0,2000)||response.headers.get('location')||''}));
|
|
27069
|
-
if(response.status>=400){console.error('HTTP '+response.status+' from ${serve.method} ${serve.path}: '+text.slice(0,
|
|
27435
|
+
if(response.status>=400){console.error('HTTP '+response.status+' from ${serve.method} ${serve.path}: '+text.slice(0,800));process.exitCode=1;}
|
|
27070
27436
|
}
|
|
27071
27437
|
// Work the handler does after answering still runs: give it a moment.
|
|
27072
27438
|
if(script)await new Promise(r=>setTimeout(r,1000));
|
|
@@ -27091,7 +27457,7 @@ const free=await new Promise(resolve=>{const s=net.createServer();s.listen(0,'12
|
|
|
27091
27457
|
process.env.PORT=String(free);
|
|
27092
27458
|
// Bolt's own start() settles once its Socket Mode connection is open: hold on to it.
|
|
27093
27459
|
let started;
|
|
27094
|
-
try{const {App}=createRequire(${JSON.stringify(
|
|
27460
|
+
try{const {App}=createRequire(${JSON.stringify(join59(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);}
|
|
27095
27461
|
const route=(JSON.parse(process.env.AGENTTWIN_ROUTES||'{}').routes||[]).find(r=>r.host==='slack.com');
|
|
27096
27462
|
// Calls made as the workspace, not the app: straight to the twin, with the run token beside the caller's own token.
|
|
27097
27463
|
const slack=async(method,token,params,path='/api/'+method)=>{
|
|
@@ -27101,7 +27467,7 @@ const slack=async(method,token,params,path='/api/'+method)=>{
|
|
|
27101
27467
|
};
|
|
27102
27468
|
try{
|
|
27103
27469
|
if(!route)throw new Error('No Slack twin serves slack.com in this run.');
|
|
27104
|
-
await import(pathToFileURL(${JSON.stringify(
|
|
27470
|
+
await import(pathToFileURL(${JSON.stringify(join59(cwd, candidate.file))}).href);
|
|
27105
27471
|
const end=Date.now()+20000;while(!started&&Date.now()<end)await new Promise(r=>setTimeout(r,100));
|
|
27106
27472
|
if(!started)throw new Error('The app did not call app.start() within 20 seconds.');
|
|
27107
27473
|
const receiver=await Promise.race([started,new Promise((_,reject)=>setTimeout(()=>reject(new Error('The app did not connect to Slack within 20 seconds.')),20000))]);
|
|
@@ -27141,7 +27507,7 @@ import {pathToFileURL} from 'node:url';
|
|
|
27141
27507
|
const environment=${JSON.stringify(scenario2.environment)},calls=${JSON.stringify(calls)};
|
|
27142
27508
|
for(const [key,value] of Object.entries(environment))if(process.env[key]===undefined)process.env[key]=value;
|
|
27143
27509
|
try{
|
|
27144
|
-
const module=await import(pathToFileURL(${JSON.stringify(
|
|
27510
|
+
const module=await import(pathToFileURL(${JSON.stringify(join59(cwd, candidate.file))}).href);
|
|
27145
27511
|
const fn=module[${JSON.stringify(candidate.exportName)}];
|
|
27146
27512
|
if(typeof fn!=='function')throw new Error(${JSON.stringify(`${candidate.exportName} is not an exported function of ${candidate.file}`)});
|
|
27147
27513
|
for(const [index,args] of calls.entries()){
|
|
@@ -27149,7 +27515,7 @@ try{
|
|
|
27149
27515
|
const response=await fn(request,{params:Promise.resolve(${JSON.stringify(web.params)})});
|
|
27150
27516
|
const status=response?.status??200,text=response&&typeof response.text==='function'?await response.text():JSON.stringify(response??null);
|
|
27151
27517
|
console.log(JSON.stringify({schema:'agenttwin/call-result-v1',call:index+1,status,result:text.slice(0,2000)}));
|
|
27152
|
-
if(status>=400){console.error('HTTP '+status+' from ${web.method} ${web.path}: '+text.slice(0,
|
|
27518
|
+
if(status>=400){console.error('HTTP '+status+' from ${web.method} ${web.path}: '+text.slice(0,800));process.exitCode=1;}
|
|
27153
27519
|
}
|
|
27154
27520
|
}catch(error){console.error(error);process.exitCode=1;}
|
|
27155
27521
|
setTimeout(()=>process.exit(),1000).unref();
|
|
@@ -27158,7 +27524,7 @@ setTimeout(()=>process.exit(),1000).unref();
|
|
|
27158
27524
|
import {spawn} from 'node:child_process';
|
|
27159
27525
|
import {createRequire} from 'node:module';
|
|
27160
27526
|
import net from 'node:net';
|
|
27161
|
-
const environment=${JSON.stringify(scenario2.environment)},calls=${JSON.stringify(calls)},appDir=${JSON.stringify(
|
|
27527
|
+
const environment=${JSON.stringify(scenario2.environment)},calls=${JSON.stringify(calls)},appDir=${JSON.stringify(join59(cwd, web.appDir))};
|
|
27162
27528
|
const env={...process.env,NEXT_TELEMETRY_DISABLED:'1'};for(const [key,value] of Object.entries(environment))if(env[key]===undefined)env[key]=value;
|
|
27163
27529
|
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));});});
|
|
27164
27530
|
env.PORT=String(port);
|
|
@@ -27216,7 +27582,7 @@ try{
|
|
|
27216
27582
|
const response=await call(${JSON.stringify(web.path)}+${JSON.stringify(scenario2.query ? "?" + scenario2.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})});
|
|
27217
27583
|
const text=await response.text();
|
|
27218
27584
|
console.log(JSON.stringify({schema:'agenttwin/call-result-v1',call:index+1,status:response.status,result:text.slice(0,2000)}));
|
|
27219
|
-
if(response.status>=400){console.error('HTTP '+response.status+' from ${web.method} ${web.path}: '+text.slice(0,
|
|
27585
|
+
if(response.status>=400){console.error('HTTP '+response.status+' from ${web.method} ${web.path}: '+text.slice(0,800));process.exitCode=1;}
|
|
27220
27586
|
}
|
|
27221
27587
|
// Work the handler scheduled after responding (after(), queued jobs) still runs: wait until the server goes quiet.
|
|
27222
27588
|
const settleBy=Date.now()+30000;lastOutput=Date.now();
|
|
@@ -27230,15 +27596,15 @@ import {spawn} from 'node:child_process';
|
|
|
27230
27596
|
const environment=${JSON.stringify(scenario2.environment)},calls=${JSON.stringify(calls)};
|
|
27231
27597
|
const env={...process.env};for(const [key,value] of Object.entries(environment))if(env[key]===undefined)env[key]=value;
|
|
27232
27598
|
for(const [index] of calls.entries()){
|
|
27233
|
-
const exitCode=await new Promise(resolve=>{const child=spawn(process.execPath,[...process.execArgv,${JSON.stringify(
|
|
27599
|
+
const exitCode=await new Promise(resolve=>{const child=spawn(process.execPath,[...process.execArgv,${JSON.stringify(join59(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));});
|
|
27234
27600
|
console.log(JSON.stringify({schema:'agenttwin/call-result-v1',call:index+1,result:{exitCode}}));
|
|
27235
27601
|
if(exitCode!==0){console.error(${JSON.stringify(candidate.file)}+' exited with code '+exitCode);process.exitCode=1;}
|
|
27236
27602
|
}
|
|
27237
27603
|
` : void 0;
|
|
27238
27604
|
if (candidate.python) {
|
|
27239
27605
|
const pyDriver = driver.replace(/\.mjs$/, ".py");
|
|
27240
|
-
const venv = [".venv/bin/python", "venv/bin/python", ".venv/Scripts/python.exe"].map((p) =>
|
|
27241
|
-
await writeFile33(
|
|
27606
|
+
const venv = [".venv/bin/python", "venv/bin/python", ".venv/Scripts/python.exe"].map((p) => join59(cwd, p)).find((p) => existsSync11(p));
|
|
27607
|
+
await writeFile33(join59(cwd, pyDriver), `# Generated by AgentTwin: runs ${candidate.file} as a script on twins.
|
|
27242
27608
|
import json, os, subprocess, sys
|
|
27243
27609
|
environment = json.loads(${JSON.stringify(JSON.stringify(scenario2.environment))})
|
|
27244
27610
|
env = dict(os.environ)
|
|
@@ -27246,7 +27612,7 @@ for key, value in environment.items():
|
|
|
27246
27612
|
env.setdefault(key, value)
|
|
27247
27613
|
status = 0
|
|
27248
27614
|
for index in range(${calls.length}):
|
|
27249
|
-
code = subprocess.call([sys.executable, ${JSON.stringify(
|
|
27615
|
+
code = subprocess.call([sys.executable, ${JSON.stringify(join59(cwd, candidate.file))}], cwd=${JSON.stringify(cwd)}, env=env)
|
|
27250
27616
|
print(json.dumps({"schema": "agenttwin/call-result-v1", "call": index + 1, "result": {"exitCode": code}}), flush=True)
|
|
27251
27617
|
if code != 0:
|
|
27252
27618
|
print(${JSON.stringify(candidate.file)} + " exited with code " + str(code), file=sys.stderr, flush=True)
|
|
@@ -27256,7 +27622,7 @@ sys.exit(status)
|
|
|
27256
27622
|
const spec2 = parseWorld({ ...world, files: [pyDriver, ...sources], command: [venv ?? "python3", pyDriver] });
|
|
27257
27623
|
return { dir: cwd, spec: spec2, sourceDigests: await sourceDigests() };
|
|
27258
27624
|
}
|
|
27259
|
-
await writeFile33(
|
|
27625
|
+
await writeFile33(join59(cwd, driver), boltDriver ?? scriptDriver ?? nextDriver ?? webDriver ?? serveDriver ?? functionDriver, { mode: 384 });
|
|
27260
27626
|
const spec = parseWorld({ ...world, files: [driver, ...sources], command: ["node", ...loader ? ["--import", loader] : [], driver] });
|
|
27261
27627
|
return { dir: cwd, spec, sourceDigests: await sourceDigests() };
|
|
27262
27628
|
};
|
|
@@ -27264,19 +27630,25 @@ sys.exit(status)
|
|
|
27264
27630
|
}
|
|
27265
27631
|
function ensurePrismaClient(cwd, appDir) {
|
|
27266
27632
|
const schemas = /* @__PURE__ */ new Set();
|
|
27267
|
-
for (const dir of [
|
|
27633
|
+
for (const dir of [join59(cwd, appDir), cwd]) for (const s of [join59(dir, "prisma", "schema.prisma"), join59(dir, "schema.prisma")]) if (existsSync11(s)) schemas.add(s);
|
|
27268
27634
|
for (const group of ["packages", "apps", "libs"]) try {
|
|
27269
|
-
for (const name of
|
|
27635
|
+
for (const name of readdirSync5(join59(cwd, group))) for (const s of [join59(cwd, group, name, "prisma", "schema.prisma"), join59(cwd, group, name, "schema.prisma")]) if (existsSync11(s)) schemas.add(s);
|
|
27270
27636
|
} catch {
|
|
27271
27637
|
}
|
|
27272
27638
|
for (const schema of schemas) {
|
|
27273
|
-
const text3 =
|
|
27639
|
+
const text3 = readFileSync12(schema, "utf8"), pkgDir = dirname17(dirname17(schema)).endsWith("prisma") ? dirname17(dirname17(schema)) : existsSync11(join59(dirname17(schema), "..", "package.json")) ? join59(dirname17(schema), "..") : dirname17(schema);
|
|
27274
27640
|
const output = /generator\s+\w+\s*\{[^}]*\boutput\s*=\s*"([^"]+)"/.exec(text3)?.[1];
|
|
27275
|
-
const req = createRequire6(
|
|
27276
|
-
const generated = output ?
|
|
27641
|
+
const req = createRequire6(join59(pkgDir, "package.json"));
|
|
27642
|
+
const generated = output ? existsSync11(join59(dirname17(schema), output)) : (() => {
|
|
27277
27643
|
try {
|
|
27278
|
-
req.resolve(".prisma/client/default");
|
|
27279
|
-
return
|
|
27644
|
+
const dir = dirname17(req.resolve(".prisma/client/default"));
|
|
27645
|
+
return !["default.js", "index.js"].some((f) => {
|
|
27646
|
+
try {
|
|
27647
|
+
return readFileSync12(join59(dir, f), "utf8").includes("did not initialize yet");
|
|
27648
|
+
} catch {
|
|
27649
|
+
return false;
|
|
27650
|
+
}
|
|
27651
|
+
});
|
|
27280
27652
|
} catch {
|
|
27281
27653
|
return false;
|
|
27282
27654
|
}
|
|
@@ -27284,12 +27656,18 @@ function ensurePrismaClient(cwd, appDir) {
|
|
|
27284
27656
|
if (generated) continue;
|
|
27285
27657
|
let bin;
|
|
27286
27658
|
for (let dir = pkgDir; dir.startsWith(cwd) && !bin; dir = dirname17(dir)) {
|
|
27287
|
-
const b =
|
|
27288
|
-
if (
|
|
27659
|
+
const b = join59(dir, "node_modules", ".bin", "prisma");
|
|
27660
|
+
if (existsSync11(b)) bin = b;
|
|
27289
27661
|
if (dir === cwd) break;
|
|
27290
27662
|
}
|
|
27291
27663
|
if (!bin) continue;
|
|
27292
|
-
const
|
|
27664
|
+
const bins = [];
|
|
27665
|
+
for (let dir = pkgDir; dir.startsWith(cwd); dir = dirname17(dir)) {
|
|
27666
|
+
const b = join59(dir, "node_modules", ".bin");
|
|
27667
|
+
if (existsSync11(b)) bins.push(b);
|
|
27668
|
+
if (dir === cwd) break;
|
|
27669
|
+
}
|
|
27670
|
+
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(delimiter4) } });
|
|
27293
27671
|
if (result2.status !== 0) process.stderr.write(` prisma generate failed for ${relative18(cwd, schema)}: ${String(result2.stderr ?? "").trim().split("\n").slice(-2).join(" ")}
|
|
27294
27672
|
`);
|
|
27295
27673
|
}
|
|
@@ -27297,7 +27675,7 @@ function ensurePrismaClient(cwd, appDir) {
|
|
|
27297
27675
|
function usesPostgresDriver(cwd) {
|
|
27298
27676
|
const deps = (dir) => {
|
|
27299
27677
|
try {
|
|
27300
|
-
const p = JSON.parse(
|
|
27678
|
+
const p = JSON.parse(readFileSync12(join59(cwd, dir, "package.json"), "utf8"));
|
|
27301
27679
|
return Object.keys({ ...p.dependencies, ...p.devDependencies });
|
|
27302
27680
|
} catch {
|
|
27303
27681
|
return [];
|
|
@@ -27305,14 +27683,14 @@ function usesPostgresDriver(cwd) {
|
|
|
27305
27683
|
};
|
|
27306
27684
|
const dirs2 = ["."];
|
|
27307
27685
|
for (const base of ["packages", "apps", "services", "server", "backend"]) try {
|
|
27308
|
-
for (const e of
|
|
27686
|
+
for (const e of readdirSync5(join59(cwd, base), { withFileTypes: true })) if (e.isDirectory()) dirs2.push(join59(base, e.name));
|
|
27309
27687
|
dirs2.push(base);
|
|
27310
27688
|
} catch {
|
|
27311
27689
|
}
|
|
27312
27690
|
if (dirs2.some((d2) => deps(d2).some((n) => POSTGRES_DRIVERS.includes(n)))) return true;
|
|
27313
27691
|
return dirs2.some((d2) => deps(d2).includes("@prisma/client") && ["prisma/schema.prisma", "schema.prisma"].some((f) => {
|
|
27314
27692
|
try {
|
|
27315
|
-
return /provider\s*=\s*"postgres(?:ql)?"/.test(
|
|
27693
|
+
return /provider\s*=\s*"postgres(?:ql)?"/.test(readFileSync12(join59(cwd, d2, f), "utf8"));
|
|
27316
27694
|
} catch {
|
|
27317
27695
|
return false;
|
|
27318
27696
|
}
|
|
@@ -27322,8 +27700,8 @@ async function discoverWorkspaceSchema(cwd, appDir) {
|
|
|
27322
27700
|
const own = appDir && appDir !== "." ? await discoverAppPostgresSchema(cwd, appDir) : void 0;
|
|
27323
27701
|
if (own?.length) return own;
|
|
27324
27702
|
for (const base of ["packages", "apps", "services"]) try {
|
|
27325
|
-
for (const e of
|
|
27326
|
-
const found = await discoverAppPostgresSchema(cwd,
|
|
27703
|
+
for (const e of readdirSync5(join59(cwd, base), { withFileTypes: true })) if (e.isDirectory()) {
|
|
27704
|
+
const found = await discoverAppPostgresSchema(cwd, join59(base, e.name));
|
|
27327
27705
|
if (found?.length) return found;
|
|
27328
27706
|
}
|
|
27329
27707
|
} catch {
|
|
@@ -27336,6 +27714,7 @@ var init_autoprep = __esm({
|
|
|
27336
27714
|
"use strict";
|
|
27337
27715
|
init_http_world();
|
|
27338
27716
|
init_workers_env();
|
|
27717
|
+
init_setup();
|
|
27339
27718
|
init_postgres_schema();
|
|
27340
27719
|
init_rabbitmq_assertions();
|
|
27341
27720
|
init_kafka_assertions();
|
|
@@ -27375,7 +27754,7 @@ var init_autoprep = __esm({
|
|
|
27375
27754
|
};
|
|
27376
27755
|
readFileSyncSafe = (path2) => {
|
|
27377
27756
|
try {
|
|
27378
|
-
return
|
|
27757
|
+
return readFileSync12(path2, "utf8");
|
|
27379
27758
|
} catch {
|
|
27380
27759
|
return "";
|
|
27381
27760
|
}
|
|
@@ -27525,199 +27904,6 @@ var init_first_run_help = __esm({
|
|
|
27525
27904
|
}
|
|
27526
27905
|
});
|
|
27527
27906
|
|
|
27528
|
-
// src/flow/setup.ts
|
|
27529
|
-
import { spawn as spawn11, spawnSync as spawnSync3 } from "child_process";
|
|
27530
|
-
import { existsSync as existsSync11, readFileSync as readFileSync12, readdirSync as readdirSync5 } from "fs";
|
|
27531
|
-
import { delimiter as delimiter3, join as join59, posix as posix6 } from "path";
|
|
27532
|
-
function packageManager(cwd) {
|
|
27533
|
-
const field2 = readJson2(join59(cwd, "package.json"))?.packageManager;
|
|
27534
|
-
if (typeof field2 === "string") {
|
|
27535
|
-
const [name, version] = field2.split("@");
|
|
27536
|
-
if (["npm", "pnpm", "yarn", "bun"].includes(name)) return { name, version: version?.split("+")[0] };
|
|
27537
|
-
}
|
|
27538
|
-
if (existsSync11(join59(cwd, "pnpm-lock.yaml"))) return { name: "pnpm" };
|
|
27539
|
-
if (existsSync11(join59(cwd, "yarn.lock"))) return { name: "yarn" };
|
|
27540
|
-
if (existsSync11(join59(cwd, "bun.lock")) || existsSync11(join59(cwd, "bun.lockb"))) return { name: "bun" };
|
|
27541
|
-
return { name: "npm" };
|
|
27542
|
-
}
|
|
27543
|
-
function nodeWanted(range, have = process.versions.node) {
|
|
27544
|
-
if (!range || !/\d/.test(range)) return void 0;
|
|
27545
|
-
const current2 = Number(have.split(".")[0]);
|
|
27546
|
-
const alternatives = range.split("||").map((alt) => [...alt.matchAll(/(>=|<=|>|<|\^|~|=)?\s*v?(\d+)/g)].map((m) => ({ op: m[1] ?? "", major: Number(m[2]) })));
|
|
27547
|
-
const satisfied = (cmp2) => cmp2.every(({ op: op2, major }) => op2 === ">=" || op2 === ">" ? current2 >= major : op2 === "<" ? current2 < major : op2 === "<=" ? current2 <= major : current2 === major);
|
|
27548
|
-
if (alternatives.some((a) => a.length && satisfied(a))) return void 0;
|
|
27549
|
-
const lows = alternatives.flatMap((a) => a.filter((c) => !c.op.startsWith("<")).map((c) => c.major));
|
|
27550
|
-
return lows.length ? String(Math.min(...lows.filter((m) => m > current2).concat(lows.every((m) => m <= current2) ? [Math.max(...lows)] : []))) : void 0;
|
|
27551
|
-
}
|
|
27552
|
-
function unbuiltWorkspacePackages(cwd, appDir) {
|
|
27553
|
-
const root2 = readJson2(join59(cwd, "package.json"));
|
|
27554
|
-
let patterns = Array.isArray(root2?.workspaces) ? root2.workspaces : Array.isArray(root2?.workspaces?.packages) ? root2.workspaces.packages : [];
|
|
27555
|
-
if (existsSync11(join59(cwd, "pnpm-workspace.yaml"))) {
|
|
27556
|
-
const text3 = readFileSync12(join59(cwd, "pnpm-workspace.yaml"), "utf8");
|
|
27557
|
-
patterns = [...patterns, ...[...text3.matchAll(/^\s*-\s*['"]?([^'"\n#]+)['"]?/gm)].map((m) => m[1].trim())];
|
|
27558
|
-
}
|
|
27559
|
-
const dirs2 = /* @__PURE__ */ new Set();
|
|
27560
|
-
for (const pattern of patterns) {
|
|
27561
|
-
if (pattern.startsWith("!")) continue;
|
|
27562
|
-
const base = pattern.replace(/\/\*\*?$/, "");
|
|
27563
|
-
if (pattern.endsWith("*")) {
|
|
27564
|
-
try {
|
|
27565
|
-
for (const e of readdirSync5(join59(cwd, base), { withFileTypes: true })) if (e.isDirectory()) dirs2.add(posix6.join(base, e.name));
|
|
27566
|
-
} catch {
|
|
27567
|
-
}
|
|
27568
|
-
} else dirs2.add(base);
|
|
27569
|
-
}
|
|
27570
|
-
let needed;
|
|
27571
|
-
if (appDir !== void 0) {
|
|
27572
|
-
const byName = /* @__PURE__ */ new Map();
|
|
27573
|
-
for (const dir of dirs2) {
|
|
27574
|
-
const name = readJson2(join59(cwd, dir, "package.json"))?.name;
|
|
27575
|
-
if (typeof name === "string") byName.set(name, dir);
|
|
27576
|
-
}
|
|
27577
|
-
needed = /* @__PURE__ */ new Set();
|
|
27578
|
-
const queue = [appDir];
|
|
27579
|
-
while (queue.length) {
|
|
27580
|
-
const dir = queue.shift();
|
|
27581
|
-
const pkg = readJson2(join59(cwd, dir, "package.json"));
|
|
27582
|
-
for (const dep of Object.keys({ ...pkg?.dependencies, ...pkg?.devDependencies, ...pkg?.peerDependencies })) {
|
|
27583
|
-
const d2 = byName.get(dep);
|
|
27584
|
-
if (d2 && !needed.has(d2)) {
|
|
27585
|
-
needed.add(d2);
|
|
27586
|
-
queue.push(d2);
|
|
27587
|
-
}
|
|
27588
|
-
}
|
|
27589
|
-
}
|
|
27590
|
-
}
|
|
27591
|
-
const unbuilt = [];
|
|
27592
|
-
for (const dir of dirs2) {
|
|
27593
|
-
if (needed && !needed.has(dir)) continue;
|
|
27594
|
-
const pkg = readJson2(join59(cwd, dir, "package.json"));
|
|
27595
|
-
if (!pkg) continue;
|
|
27596
|
-
const targets = [];
|
|
27597
|
-
const collect2 = (v) => {
|
|
27598
|
-
if (typeof v === "string") targets.push(v);
|
|
27599
|
-
else if (v && typeof v === "object") for (const x of Object.values(v)) collect2(x);
|
|
27600
|
-
};
|
|
27601
|
-
collect2(pkg.main);
|
|
27602
|
-
collect2(pkg.module);
|
|
27603
|
-
collect2(pkg.exports?.["."] ?? (typeof pkg.exports === "string" ? pkg.exports : void 0));
|
|
27604
|
-
const built = targets.filter((t) => /(^|\/)(dist|build|lib|out)\//.test(t) && !t.includes("*"));
|
|
27605
|
-
if (built.length && pkg.scripts?.build && built.every((t) => !existsSync11(join59(cwd, dir, t)))) unbuilt.push(dir);
|
|
27606
|
-
}
|
|
27607
|
-
return unbuilt.sort();
|
|
27608
|
-
}
|
|
27609
|
-
function planSetup(cwd, opts = {}) {
|
|
27610
|
-
const pm = packageManager(cwd);
|
|
27611
|
-
const root2 = readJson2(join59(cwd, "package.json")) ?? {};
|
|
27612
|
-
const steps = [];
|
|
27613
|
-
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] };
|
|
27614
|
-
const anyDeps = Object.keys({ ...root2.dependencies, ...root2.devDependencies }).length > 0 || root2.workspaces || existsSync11(join59(cwd, "pnpm-workspace.yaml"));
|
|
27615
|
-
if (opts.only !== "build" && anyDeps && !existsSync11(join59(cwd, "node_modules"))) {
|
|
27616
|
-
const r = runner(["install"]);
|
|
27617
|
-
steps.push({ id: "install", ...r, why: "dependencies are not installed", dir: cwd });
|
|
27618
|
-
}
|
|
27619
|
-
const unbuilt = steps.length || opts.only === "install" ? [] : unbuiltWorkspacePackages(cwd, opts.appDir);
|
|
27620
|
-
if (unbuilt.length) {
|
|
27621
|
-
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"]);
|
|
27622
|
-
const turbo = existsSync11(join59(cwd, "turbo.json")) && existsSync11(join59(cwd, "node_modules/.bin/turbo")) ? { command: join59(cwd, "node_modules/.bin/turbo"), args: ["run", "build", ...unbuilt.map((d2) => `--filter=./${d2}`)] } : void 0;
|
|
27623
|
-
const r = turbo ? { ...turbo, fallback: own } : own;
|
|
27624
|
-
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 });
|
|
27625
|
-
}
|
|
27626
|
-
const want = opts.only === "build" ? void 0 : nodeWanted(root2.engines?.node);
|
|
27627
|
-
return { packageManager: pm.name, steps, ...want ? { node: { want, have: process.versions.node, command: `nvm install ${want} && nvm use ${want}` } } : {} };
|
|
27628
|
-
}
|
|
27629
|
-
function installRetry(step, output) {
|
|
27630
|
-
const pm = step.command === "corepack" || step.command === "npx" ? step.args.find((a) => /^(npm|pnpm|yarn|bun)(@|$)/.test(a))?.split("@")[0] : step.command;
|
|
27631
|
-
const tail2 = step.command === "corepack" ? step.args.slice(1) : step.command === "npx" ? step.args.slice(2) : step.args;
|
|
27632
|
-
const pinned = step.command === "corepack" || step.command === "npx" ? step.args.find((a) => /^(npm|pnpm|yarn|bun)(@|$)/.test(a)) : pm;
|
|
27633
|
-
if (pm === "pnpm" && /ERR_PNPM_(OUTDATED_LOCKFILE|LOCKFILE_CONFIG_MISMATCH|LOCKFILE_MISSING_DEPENDENCY)|frozen.lockfile|specifiers in the lockfile/i.test(output))
|
|
27634
|
-
return { why: "The lockfile is behind package.json, so a frozen install stops", step: { ...step, args: [...step.args, "--no-frozen-lockfile"] } };
|
|
27635
|
-
if (pm === "yarn" && /YN0028|lockfile would have been modified|--frozen-lockfile/i.test(output))
|
|
27636
|
-
return { why: "The lockfile is behind package.json, so a frozen install stops", step: { ...step, args: [...step.args, "--no-immutable"] } };
|
|
27637
|
-
if (pm === "pnpm" && /ERR_PNPM_IGNORED_BUILDS/.test(output) && !step.args.some((a) => a.startsWith("--config.dangerously-allow-all-builds")))
|
|
27638
|
-
return { why: "pnpm skipped the dependencies' build scripts", step: { ...step, args: [...step.args, "--config.dangerously-allow-all-builds=true"] } };
|
|
27639
|
-
if (pm === "bun" && step.command === "corepack")
|
|
27640
|
-
return { why: "corepack cannot fetch bun", step: { ...step, command: "npx", args: ["--yes", pinned, ...tail2] } };
|
|
27641
|
-
if (pm === "npm" && /EBADENGINE|notsup|Unsupported engine/i.test(output) && !step.args.includes("--engine-strict=false"))
|
|
27642
|
-
return { why: "The project's engines field does not allow this Node version", step: { ...step, args: [...step.args, "--engine-strict=false"] } };
|
|
27643
|
-
}
|
|
27644
|
-
async function corepackShims(cwd, steps) {
|
|
27645
|
-
const pm = packageManager(cwd).name;
|
|
27646
|
-
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));
|
|
27647
|
-
if (!managers.length || !steps.length || !has("corepack")) return;
|
|
27648
|
-
const dir = join59(cwd, ".agenttwin", "bin");
|
|
27649
|
-
const ok4 = await new Promise((resolve35) => {
|
|
27650
|
-
const c = spawn11("corepack", ["enable", "--install-directory", dir, ...managers], { stdio: "ignore" });
|
|
27651
|
-
c.once("error", () => resolve35(false));
|
|
27652
|
-
c.once("exit", (code) => resolve35(code === 0));
|
|
27653
|
-
});
|
|
27654
|
-
return ok4 ? dir : void 0;
|
|
27655
|
-
}
|
|
27656
|
-
async function runSetup2(cwd, opts) {
|
|
27657
|
-
const plan = opts.plan ?? planSetup(cwd, { ...opts.appDir !== void 0 ? { appDir: opts.appDir } : {}, ...opts.only ? { only: opts.only } : {} });
|
|
27658
|
-
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}`);
|
|
27659
|
-
if (!plan.steps.length) return true;
|
|
27660
|
-
opts.log(` Before the app can start: ${plan.steps.map((s) => `${show(s)} (${s.why})`).join(", then ")}.`);
|
|
27661
|
-
const answer = (await opts.ask({ id: "setup", text: `Run ${plan.steps.length === 1 ? "it" : "them"} now? (Y/n)`, default: "y" })).trim().toLowerCase();
|
|
27662
|
-
if (answer.startsWith("n")) {
|
|
27663
|
-
opts.log(` Skipped. Run ${plan.steps.map(show).join(" && ")} yourself, then npx agenttwin again.`);
|
|
27664
|
-
return false;
|
|
27665
|
-
}
|
|
27666
|
-
const shims = await corepackShims(cwd, plan.steps);
|
|
27667
|
-
const exec11 = (step) => new Promise((resolve35) => {
|
|
27668
|
-
const child = spawn11(step.command, step.args, { cwd: step.dir, stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, CI: "1", COREPACK_ENABLE_DOWNLOAD_PROMPT: "0", ...shims ? { PATH: `${shims}${delimiter3}${process.env.PATH ?? ""}` } : {} } });
|
|
27669
|
-
let tail2 = "";
|
|
27670
|
-
const keep = (c) => {
|
|
27671
|
-
tail2 = (tail2 + c.toString()).slice(-4e3);
|
|
27672
|
-
};
|
|
27673
|
-
child.stdout.on("data", keep);
|
|
27674
|
-
child.stderr.on("data", keep);
|
|
27675
|
-
child.once("error", (e) => {
|
|
27676
|
-
tail2 += String(e);
|
|
27677
|
-
resolve35({ code: 1, tail: tail2 });
|
|
27678
|
-
});
|
|
27679
|
-
child.once("exit", (c) => resolve35({ code: c ?? 1, tail: tail2 }));
|
|
27680
|
-
});
|
|
27681
|
-
for (const step of plan.steps) {
|
|
27682
|
-
opts.log(` Running ${show(step)}\u2026`);
|
|
27683
|
-
let { code, tail: tail2 } = await exec11(step);
|
|
27684
|
-
for (let current2 = step, tries = 0; code !== 0 && step.id === "install" && tries < 3; tries++) {
|
|
27685
|
-
const retry = installRetry(current2, tail2);
|
|
27686
|
-
if (!retry) break;
|
|
27687
|
-
opts.log(` ${retry.why}; running ${show(retry.step)}\u2026`);
|
|
27688
|
-
current2 = retry.step;
|
|
27689
|
-
({ code, tail: tail2 } = await exec11(retry.step));
|
|
27690
|
-
}
|
|
27691
|
-
if (code !== 0 && step.fallback) {
|
|
27692
|
-
const next = { ...step, ...step.fallback, fallback: void 0 };
|
|
27693
|
-
opts.log(` ${show(step)} failed; running ${show(next)}\u2026`);
|
|
27694
|
-
({ code, tail: tail2 } = await exec11(next));
|
|
27695
|
-
}
|
|
27696
|
-
if (code !== 0) {
|
|
27697
|
-
opts.log(tail2.split("\n").filter(Boolean).slice(-6).map((l) => " " + l.slice(0, 200)).join("\n"));
|
|
27698
|
-
opts.log(` ${show(step)} failed (exit ${code}). The run goes on; if the app cannot start, fix that first.`);
|
|
27699
|
-
return false;
|
|
27700
|
-
}
|
|
27701
|
-
}
|
|
27702
|
-
opts.log(" Setup done.");
|
|
27703
|
-
return true;
|
|
27704
|
-
}
|
|
27705
|
-
var readJson2, has, show;
|
|
27706
|
-
var init_setup = __esm({
|
|
27707
|
-
"src/flow/setup.ts"() {
|
|
27708
|
-
"use strict";
|
|
27709
|
-
readJson2 = (file) => {
|
|
27710
|
-
try {
|
|
27711
|
-
return JSON.parse(readFileSync12(file, "utf8"));
|
|
27712
|
-
} catch {
|
|
27713
|
-
return void 0;
|
|
27714
|
-
}
|
|
27715
|
-
};
|
|
27716
|
-
has = (cmd) => spawnSync3(process.platform === "win32" ? "where" : "which", [cmd], { stdio: "ignore" }).status === 0;
|
|
27717
|
-
show = (s) => [posix6.basename(s.command), ...s.args].join(" ");
|
|
27718
|
-
}
|
|
27719
|
-
});
|
|
27720
|
-
|
|
27721
27907
|
// src/flow/gap-sink.ts
|
|
27722
27908
|
import { createServer as createHttpServer } from "http";
|
|
27723
27909
|
import { createServer as createTcpServer } from "net";
|
|
@@ -27902,15 +28088,15 @@ async function startS3Engine(options = {}) {
|
|
|
27902
28088
|
const objects = ensureBucket(bucket) ?? store.get(bucket);
|
|
27903
28089
|
if (!objects) return error(res, 404, "NoSuchBucket", "The specified bucket does not exist", bucket);
|
|
27904
28090
|
if (method === "GET" && !url2.searchParams.has("uploads")) {
|
|
27905
|
-
const prefix = url2.searchParams.get("prefix") ?? "",
|
|
28091
|
+
const prefix = url2.searchParams.get("prefix") ?? "", delimiter5 = url2.searchParams.get("delimiter");
|
|
27906
28092
|
const max = Math.min(Number(url2.searchParams.get("max-keys") ?? 1e3) || 1e3, 1e3);
|
|
27907
28093
|
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") ?? "";
|
|
27908
28094
|
let keys = [...objects.keys()].filter((k) => k.startsWith(prefix) && k > after).sort();
|
|
27909
28095
|
const prefixes = /* @__PURE__ */ new Set();
|
|
27910
|
-
if (
|
|
27911
|
-
const rest = k.slice(prefix.length), i = rest.indexOf(
|
|
28096
|
+
if (delimiter5) keys = keys.filter((k) => {
|
|
28097
|
+
const rest = k.slice(prefix.length), i = rest.indexOf(delimiter5);
|
|
27912
28098
|
if (i < 0) return true;
|
|
27913
|
-
prefixes.add(prefix + rest.slice(0, i +
|
|
28099
|
+
prefixes.add(prefix + rest.slice(0, i + delimiter5.length));
|
|
27914
28100
|
return false;
|
|
27915
28101
|
});
|
|
27916
28102
|
const page2 = keys.slice(0, max), truncated = keys.length > max;
|
|
@@ -30679,6 +30865,14 @@ async function runOneCommand(opts) {
|
|
|
30679
30865
|
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.`));
|
|
30680
30866
|
clean = await track(void 0);
|
|
30681
30867
|
}
|
|
30868
|
+
const triedInput = /* @__PURE__ */ new Set();
|
|
30869
|
+
for (let round = 0; round < 2 && clean.status === "error" && !clean.blockedCalls.length; round++) {
|
|
30870
|
+
const added = settleInput(prepared.scenario.input, clean.stderr, triedInput);
|
|
30871
|
+
if (!added.length) break;
|
|
30872
|
+
await writeFile35(prepared.scenarioPath, JSON.stringify(prepared.scenario, null, 2) + "\n", { mode: 384 });
|
|
30873
|
+
log(dim(` The route asked for ${added.join(", ")}; added test values to the input, rerunning.`));
|
|
30874
|
+
clean = await track(void 0);
|
|
30875
|
+
}
|
|
30682
30876
|
for (let round = 0; round < 3 && clean.blockedCalls.length; round++) {
|
|
30683
30877
|
let learnedTcp = false;
|
|
30684
30878
|
for (const b of clean.blockedCalls.filter((b2) => b2.kind === "socket" && b2.port)) {
|
|
@@ -31177,6 +31371,7 @@ var init_one_command = __esm({
|
|
|
31177
31371
|
init_kafka_diagnostics();
|
|
31178
31372
|
init_kafka();
|
|
31179
31373
|
init_offline();
|
|
31374
|
+
init_input_fields();
|
|
31180
31375
|
init_http_world();
|
|
31181
31376
|
init_local();
|
|
31182
31377
|
init_seed();
|
|
@@ -33346,7 +33541,7 @@ __export(live_view_exports, {
|
|
|
33346
33541
|
scenario: () => scenario,
|
|
33347
33542
|
strip: () => strip
|
|
33348
33543
|
});
|
|
33349
|
-
import { writeFileSync as writeFileSync3, mkdirSync as
|
|
33544
|
+
import { writeFileSync as writeFileSync3, mkdirSync as mkdirSync3 } from "fs";
|
|
33350
33545
|
import { join as join81 } from "path";
|
|
33351
33546
|
function reduce(s, e, now) {
|
|
33352
33547
|
switch (e.type) {
|
|
@@ -33663,7 +33858,7 @@ ${ESC}J`);
|
|
|
33663
33858
|
restore();
|
|
33664
33859
|
if (cwd) {
|
|
33665
33860
|
try {
|
|
33666
|
-
|
|
33861
|
+
mkdirSync3(join81(cwd, ".agenttwin"), { recursive: true });
|
|
33667
33862
|
writeFileSync3(join81(cwd, ".agenttwin", "last-run.log"), lines2.map(strip).join("\n") + "\n");
|
|
33668
33863
|
} catch {
|
|
33669
33864
|
}
|