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/api.js
CHANGED
|
@@ -1851,7 +1851,7 @@ function parseWorld(value3) {
|
|
|
1851
1851
|
const services = /* @__PURE__ */ new Map();
|
|
1852
1852
|
const requestPathFaults = /* @__PURE__ */ new Set();
|
|
1853
1853
|
for (const service of v.services) {
|
|
1854
|
-
if (!object2(service) || typeof service.name !== "string" || !namePattern.test(service.name) || services.has(service.name)) invalid(
|
|
1854
|
+
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"})`);
|
|
1855
1855
|
const item = service;
|
|
1856
1856
|
if (!Array.isArray(item.collections) || !item.collections.length || item.collections.length > 20) invalid("each service needs 1\u201320 collections");
|
|
1857
1857
|
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");
|
|
@@ -18390,6 +18390,25 @@ var init_orm_schema = __esm({
|
|
|
18390
18390
|
// src/flow/postgres-schema.ts
|
|
18391
18391
|
import { lstat as lstat4, readFile as readFile25, readdir as readdir5, realpath as realpath9 } from "fs/promises";
|
|
18392
18392
|
import { isAbsolute as isAbsolute5, join as join36, relative as relative8, resolve as resolve11 } from "path";
|
|
18393
|
+
function migrationOrder(a, b) {
|
|
18394
|
+
const x = a.split(/[\\/]/), y = b.split(/[\\/]/);
|
|
18395
|
+
for (let i = 0; i < Math.min(x.length, y.length); i++) {
|
|
18396
|
+
if (x[i] === y[i]) continue;
|
|
18397
|
+
const dx = /^\d+/.exec(x[i])?.[0], dy = /^\d+/.exec(y[i])?.[0];
|
|
18398
|
+
if (dx && dy && (dx.length < 8 || dy.length < 8)) return x[i].localeCompare(y[i], "en", { numeric: true });
|
|
18399
|
+
return x[i] < y[i] ? -1 : 1;
|
|
18400
|
+
}
|
|
18401
|
+
return x.length - y.length;
|
|
18402
|
+
}
|
|
18403
|
+
function withoutExtensions(sql, available) {
|
|
18404
|
+
const skipped = /* @__PURE__ */ new Set();
|
|
18405
|
+
const out = sql.replace(/CREATE\s+EXTENSION\s+(?:IF\s+NOT\s+EXISTS\s+)?"?([\w-]+)"?[^;]*;/gi, (stmt, name) => {
|
|
18406
|
+
if (available.includes(name.toLowerCase())) return stmt;
|
|
18407
|
+
skipped.add(name.toLowerCase());
|
|
18408
|
+
return `-- AgentTwin: extension ${name} is not in the embedded engine; left out.`;
|
|
18409
|
+
});
|
|
18410
|
+
return { sql: out, skipped: [...skipped] };
|
|
18411
|
+
}
|
|
18393
18412
|
async function discoverAppPostgresSchema(root2, appDir) {
|
|
18394
18413
|
try {
|
|
18395
18414
|
return (await discoverPostgresSchema(join36(root2, appDir))).map((file) => appDir ? join36(appDir, file).split("\\").join("/") : file);
|
|
@@ -18428,7 +18447,7 @@ async function discoverPostgresSchema(root2) {
|
|
|
18428
18447
|
else if (e.isFile() && e.name.endsWith(".sql") && !/^(?:down|.*\.down)\.sql$/i.test(e.name)) files.push(p);
|
|
18429
18448
|
if (files.length > MAX_SCHEMA_FILES) throw new Error("Too many SQL migrations; select a schema snapshot using postgresSchemaFiles.");
|
|
18430
18449
|
}
|
|
18431
|
-
return files.sort(
|
|
18450
|
+
return files.sort(migrationOrder);
|
|
18432
18451
|
};
|
|
18433
18452
|
const configured = [];
|
|
18434
18453
|
for (const file of ["drizzle.config.ts", "drizzle.config.js", "drizzle.config.mjs", "drizzle.config.json"]) {
|
|
@@ -18480,6 +18499,20 @@ async function discoverPostgresSchema(root2) {
|
|
|
18480
18499
|
await named("", 0);
|
|
18481
18500
|
groups2.sort((a, b) => Number(/postgres|pg/i.test(b[0])) - Number(/postgres|pg/i.test(a[0])));
|
|
18482
18501
|
}
|
|
18502
|
+
for (const schema of ["prisma/schema.prisma", "schema.prisma"]) {
|
|
18503
|
+
let text3 = "";
|
|
18504
|
+
try {
|
|
18505
|
+
text3 = await readFile25(join36(root2, schema), "utf8");
|
|
18506
|
+
} catch {
|
|
18507
|
+
continue;
|
|
18508
|
+
}
|
|
18509
|
+
const provider = prismaProvider(text3);
|
|
18510
|
+
if (provider && !/^postgres/.test(provider)) {
|
|
18511
|
+
const dir = schema.replace(/schema\.prisma$/, "") + "migrations/";
|
|
18512
|
+
for (let i = groups2.length - 1; i >= 0; i--) if (groups2[i][0]?.startsWith(dir)) groups2.splice(i, 1);
|
|
18513
|
+
if (!groups2.length) return [];
|
|
18514
|
+
}
|
|
18515
|
+
}
|
|
18483
18516
|
if (groups2.length > 1) {
|
|
18484
18517
|
const applied = [];
|
|
18485
18518
|
for (const [dir, config] of [["supabase/migrations", "supabase/config.toml"], ["prisma/migrations", "prisma/schema.prisma"]]) if (await exists2(config)) {
|
|
@@ -18523,17 +18556,19 @@ async function loadPostgresSchema(root2, files) {
|
|
|
18523
18556
|
${ddl}
|
|
18524
18557
|
`);
|
|
18525
18558
|
}
|
|
18526
|
-
const sql = parts.join("\n");
|
|
18559
|
+
const sql = withoutExtensions(parts.join("\n"), POSTGRES_EXTENSIONS).sql;
|
|
18527
18560
|
return needsSupabase(sql) ? SUPABASE_PLATFORM + "\n" + sql : sql;
|
|
18528
18561
|
}
|
|
18529
|
-
var MAX_SCHEMA_FILES, MAX_SCHEMA_BYTES, schemaExtensions, needsSupabase, SUPABASE_PLATFORM;
|
|
18562
|
+
var MAX_SCHEMA_FILES, MAX_SCHEMA_BYTES, schemaExtensions, prismaProvider, needsSupabase, SUPABASE_PLATFORM;
|
|
18530
18563
|
var init_postgres_schema = __esm({
|
|
18531
18564
|
"src/flow/postgres-schema.ts"() {
|
|
18532
18565
|
"use strict";
|
|
18533
18566
|
init_orm_schema();
|
|
18567
|
+
init_types();
|
|
18534
18568
|
MAX_SCHEMA_FILES = 2e3;
|
|
18535
18569
|
MAX_SCHEMA_BYTES = 16 * 1024 * 1024;
|
|
18536
18570
|
schemaExtensions = (sql) => [...new Set([...sql.matchAll(/CREATE\s+EXTENSION\s+(?:IF\s+NOT\s+EXISTS\s+)?"?([\w-]+)"?/gi)].map((m) => m[1].toLowerCase()))];
|
|
18571
|
+
prismaProvider = (text3) => /datasource\s+\w+\s*\{[^}]*?\bprovider\s*=\s*["']([\w-]+)["']/.exec(text3)?.[1]?.toLowerCase();
|
|
18537
18572
|
needsSupabase = (sql) => /\bauth\.(users|uid|jwt|role)\b|\bstorage\.(buckets|objects)\b|\bto (anon|authenticated|service_role)\b|\bsupabase_realtime\b/i.test(sql);
|
|
18538
18573
|
SUPABASE_PLATFORM = `-- Schema source: Supabase platform (AgentTwin)
|
|
18539
18574
|
DO $$ BEGIN
|
|
@@ -18544,12 +18579,16 @@ END $$;
|
|
|
18544
18579
|
CREATE SCHEMA IF NOT EXISTS auth;
|
|
18545
18580
|
CREATE SCHEMA IF NOT EXISTS storage;
|
|
18546
18581
|
CREATE SCHEMA IF NOT EXISTS extensions;
|
|
18582
|
+
-- Supabase puts extensions in the extensions schema and keeps it on every role's search path.
|
|
18583
|
+
SET search_path TO "$user", public, extensions;
|
|
18584
|
+
CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA extensions;
|
|
18585
|
+
CREATE EXTENSION IF NOT EXISTS pgcrypto WITH SCHEMA extensions;
|
|
18547
18586
|
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);
|
|
18548
18587
|
CREATE OR REPLACE FUNCTION auth.uid() RETURNS uuid LANGUAGE sql STABLE AS $f$ SELECT nullif(current_setting('request.jwt.claim.sub', true), '')::uuid $f$;
|
|
18549
18588
|
CREATE OR REPLACE FUNCTION auth.role() RETURNS text LANGUAGE sql STABLE AS $f$ SELECT nullif(current_setting('request.jwt.claim.role', true), '') $f$;
|
|
18550
18589
|
CREATE OR REPLACE FUNCTION auth.jwt() RETURNS jsonb LANGUAGE sql STABLE AS $f$ SELECT coalesce(nullif(current_setting('request.jwt.claims', true), ''), '{}')::jsonb $f$;
|
|
18551
18590
|
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());
|
|
18552
|
-
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());
|
|
18591
|
+
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());
|
|
18553
18592
|
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 $$;
|
|
18554
18593
|
`;
|
|
18555
18594
|
}
|
|
@@ -20080,13 +20119,72 @@ var init_kafka = __esm({
|
|
|
20080
20119
|
}
|
|
20081
20120
|
});
|
|
20082
20121
|
|
|
20122
|
+
// src/flow/input-fields.ts
|
|
20123
|
+
function missingInputFields(stderr) {
|
|
20124
|
+
const found = /* @__PURE__ */ new Map();
|
|
20125
|
+
for (const m of stderr.matchAll(/HTTP 4\d\d from \S+ \S+?:\s*(\{.*)$/gm)) {
|
|
20126
|
+
let body2;
|
|
20127
|
+
try {
|
|
20128
|
+
body2 = JSON.parse(m[1]);
|
|
20129
|
+
} catch {
|
|
20130
|
+
continue;
|
|
20131
|
+
}
|
|
20132
|
+
const visit = (v) => {
|
|
20133
|
+
if (Array.isArray(v)) {
|
|
20134
|
+
v.forEach(visit);
|
|
20135
|
+
return;
|
|
20136
|
+
}
|
|
20137
|
+
if (!v || typeof v !== "object") return;
|
|
20138
|
+
const o = v;
|
|
20139
|
+
const path2 = Array.isArray(o.path) ? o.path[0] : typeof o.path === "string" ? o.path : typeof o.param === "string" ? o.param : void 0;
|
|
20140
|
+
const text3 = [o.message, o.msg, o.received, o.code].filter((x) => typeof x === "string").join(" ");
|
|
20141
|
+
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 ?? "")))
|
|
20142
|
+
found.set(path2, { name: path2, ...typeof o.expected === "string" ? { expected: o.expected } : {} });
|
|
20143
|
+
if (o.fieldErrors && typeof o.fieldErrors === "object") {
|
|
20144
|
+
for (const [name, list4] of Object.entries(o.fieldErrors))
|
|
20145
|
+
if (Array.isArray(list4) && list4.some((x) => /Required|undefined/i.test(String(x)))) found.set(name, { name });
|
|
20146
|
+
}
|
|
20147
|
+
for (const x of Object.values(o)) if (x && typeof x === "object") visit(x);
|
|
20148
|
+
};
|
|
20149
|
+
visit(body2);
|
|
20150
|
+
}
|
|
20151
|
+
return [...found.values()];
|
|
20152
|
+
}
|
|
20153
|
+
function testValueFor(field2) {
|
|
20154
|
+
if (field2.expected === "number" || field2.expected === "integer") return 1;
|
|
20155
|
+
if (field2.expected === "boolean") return true;
|
|
20156
|
+
if (field2.expected === "array") return [];
|
|
20157
|
+
if (field2.expected === "object") return {};
|
|
20158
|
+
const n = field2.name.toLowerCase();
|
|
20159
|
+
if (/email/.test(n)) return "ada@example.com";
|
|
20160
|
+
if (/url|uri|redirect/.test(n)) return "https://example.com/";
|
|
20161
|
+
if (/(^|_)(amount|count|quantity|qty|limit|page)$/.test(n)) return 1;
|
|
20162
|
+
return `test-${field2.name}`;
|
|
20163
|
+
}
|
|
20164
|
+
function settleInput(input, stderr, tried) {
|
|
20165
|
+
if (!input || typeof input !== "object" || Array.isArray(input)) return [];
|
|
20166
|
+
const obj = input, added = [];
|
|
20167
|
+
for (const f of missingInputFields(stderr)) {
|
|
20168
|
+
if (f.name in obj || tried.has(f.name)) continue;
|
|
20169
|
+
tried.add(f.name);
|
|
20170
|
+
obj[f.name] = testValueFor(f);
|
|
20171
|
+
added.push(f.name);
|
|
20172
|
+
}
|
|
20173
|
+
return added;
|
|
20174
|
+
}
|
|
20175
|
+
var init_input_fields = __esm({
|
|
20176
|
+
"src/flow/input-fields.ts"() {
|
|
20177
|
+
"use strict";
|
|
20178
|
+
}
|
|
20179
|
+
});
|
|
20180
|
+
|
|
20083
20181
|
// package.json
|
|
20084
20182
|
var package_default;
|
|
20085
20183
|
var init_package = __esm({
|
|
20086
20184
|
"package.json"() {
|
|
20087
20185
|
package_default = {
|
|
20088
20186
|
name: "agenttwin",
|
|
20089
|
-
version: "0.3.
|
|
20187
|
+
version: "0.3.36",
|
|
20090
20188
|
description: "AgentTwin builds digital twins for testing AI agents. The current CLI prepares supported Node.js workflows with synthetic services, failures, and outcome checks.",
|
|
20091
20189
|
mcpName: "io.github.AgentTwin/agenttwin",
|
|
20092
20190
|
keywords: [
|
|
@@ -22797,7 +22895,19 @@ async function analyzeWorkflows(root2, opts = {}) {
|
|
|
22797
22895
|
const fn = f.functions.get(route.name);
|
|
22798
22896
|
const req = fn.params?.[0]?.type === "Identifier" ? fn.params[0].name : "req";
|
|
22799
22897
|
const fields = /* @__PURE__ */ new Set();
|
|
22898
|
+
const aliases2 = /* @__PURE__ */ new Set();
|
|
22800
22899
|
walk3(fn.body, (node) => {
|
|
22900
|
+
if (node.type === "VariableDeclarator" && node.id.type === "Identifier" && node.init) {
|
|
22901
|
+
const init = node.init.type === "TSAsExpression" || node.init.type === "TSSatisfiesExpression" ? node.init.expression : node.init;
|
|
22902
|
+
const names = chain(init);
|
|
22903
|
+
if (names && names[0] === req && names[1] === "body" && names.length === 2) aliases2.add(node.id.name);
|
|
22904
|
+
}
|
|
22905
|
+
});
|
|
22906
|
+
walk3(fn.body, (node) => {
|
|
22907
|
+
if (node.type === "MemberExpression" && !node.computed && node.object.type === "Identifier" && aliases2.has(node.object.name) && node.property.type === "Identifier") fields.add(node.property.name);
|
|
22908
|
+
if (node.type === "VariableDeclarator" && node.id.type === "ObjectPattern" && node.init?.type === "Identifier" && aliases2.has(node.init.name)) {
|
|
22909
|
+
for (const p of node.id.properties) if (p.type === "ObjectProperty" && !p.computed) fields.add(String(p.key.name ?? p.key.value));
|
|
22910
|
+
}
|
|
22801
22911
|
if (node.type === "MemberExpression" && !node.computed) {
|
|
22802
22912
|
const names = chain(node);
|
|
22803
22913
|
if (names && names[0] === req && names[1] === "body" && names[2]) fields.add(names[2]);
|
|
@@ -23069,6 +23179,216 @@ export async function environment(file, module) {
|
|
|
23069
23179
|
}
|
|
23070
23180
|
});
|
|
23071
23181
|
|
|
23182
|
+
// src/flow/setup.ts
|
|
23183
|
+
import { spawn as spawn9, spawnSync as spawnSync2 } from "child_process";
|
|
23184
|
+
import { existsSync as existsSync8, mkdirSync, readFileSync as readFileSync9, readdirSync as readdirSync4 } from "fs";
|
|
23185
|
+
import { delimiter as delimiter2, join as join48, posix as posix5 } from "path";
|
|
23186
|
+
function packageManager(cwd) {
|
|
23187
|
+
const field2 = readJson2(join48(cwd, "package.json"))?.packageManager;
|
|
23188
|
+
if (typeof field2 === "string") {
|
|
23189
|
+
const [name, version] = field2.split("@");
|
|
23190
|
+
if (["npm", "pnpm", "yarn", "bun"].includes(name)) return { name, version: version?.split("+")[0] };
|
|
23191
|
+
}
|
|
23192
|
+
if (existsSync8(join48(cwd, "pnpm-lock.yaml"))) return { name: "pnpm" };
|
|
23193
|
+
if (existsSync8(join48(cwd, "yarn.lock"))) return { name: "yarn" };
|
|
23194
|
+
if (existsSync8(join48(cwd, "bun.lock")) || existsSync8(join48(cwd, "bun.lockb"))) return { name: "bun" };
|
|
23195
|
+
return { name: "npm" };
|
|
23196
|
+
}
|
|
23197
|
+
function nodeWanted(range, have = process.versions.node) {
|
|
23198
|
+
if (!range || !/\d/.test(range)) return void 0;
|
|
23199
|
+
const current2 = Number(have.split(".")[0]);
|
|
23200
|
+
const alternatives = range.split("||").map((alt) => [...alt.matchAll(/(>=|<=|>|<|\^|~|=)?\s*v?(\d+)/g)].map((m) => ({ op: m[1] ?? "", major: Number(m[2]) })));
|
|
23201
|
+
const satisfied = (cmp2) => cmp2.every(({ op: op2, major }) => op2 === ">=" || op2 === ">" ? current2 >= major : op2 === "<" ? current2 < major : op2 === "<=" ? current2 <= major : current2 === major);
|
|
23202
|
+
if (alternatives.some((a) => a.length && satisfied(a))) return void 0;
|
|
23203
|
+
const lows = alternatives.flatMap((a) => a.filter((c) => !c.op.startsWith("<")).map((c) => c.major));
|
|
23204
|
+
return lows.length ? String(Math.min(...lows.filter((m) => m > current2).concat(lows.every((m) => m <= current2) ? [Math.max(...lows)] : []))) : void 0;
|
|
23205
|
+
}
|
|
23206
|
+
function unbuiltWorkspacePackages(cwd, appDir) {
|
|
23207
|
+
const root2 = readJson2(join48(cwd, "package.json"));
|
|
23208
|
+
let patterns = Array.isArray(root2?.workspaces) ? root2.workspaces : Array.isArray(root2?.workspaces?.packages) ? root2.workspaces.packages : [];
|
|
23209
|
+
if (existsSync8(join48(cwd, "pnpm-workspace.yaml"))) {
|
|
23210
|
+
const text3 = readFileSync9(join48(cwd, "pnpm-workspace.yaml"), "utf8");
|
|
23211
|
+
patterns = [...patterns, ...[...text3.matchAll(/^\s*-\s*['"]?([^'"\n#]+)['"]?/gm)].map((m) => m[1].trim())];
|
|
23212
|
+
}
|
|
23213
|
+
const dirs = /* @__PURE__ */ new Set();
|
|
23214
|
+
for (const pattern of patterns) {
|
|
23215
|
+
if (pattern.startsWith("!")) continue;
|
|
23216
|
+
const base = pattern.replace(/\/\*\*?$/, "");
|
|
23217
|
+
if (pattern.endsWith("*")) {
|
|
23218
|
+
try {
|
|
23219
|
+
for (const e of readdirSync4(join48(cwd, base), { withFileTypes: true })) if (e.isDirectory()) dirs.add(posix5.join(base, e.name));
|
|
23220
|
+
} catch {
|
|
23221
|
+
}
|
|
23222
|
+
} else dirs.add(base);
|
|
23223
|
+
}
|
|
23224
|
+
let needed;
|
|
23225
|
+
if (appDir !== void 0) {
|
|
23226
|
+
const byName = /* @__PURE__ */ new Map();
|
|
23227
|
+
for (const dir of dirs) {
|
|
23228
|
+
const name = readJson2(join48(cwd, dir, "package.json"))?.name;
|
|
23229
|
+
if (typeof name === "string") byName.set(name, dir);
|
|
23230
|
+
}
|
|
23231
|
+
needed = /* @__PURE__ */ new Set();
|
|
23232
|
+
const queue = [appDir];
|
|
23233
|
+
while (queue.length) {
|
|
23234
|
+
const dir = queue.shift();
|
|
23235
|
+
const pkg = readJson2(join48(cwd, dir, "package.json"));
|
|
23236
|
+
for (const dep of Object.keys({ ...pkg?.dependencies, ...pkg?.devDependencies, ...pkg?.peerDependencies })) {
|
|
23237
|
+
const d2 = byName.get(dep);
|
|
23238
|
+
if (d2 && !needed.has(d2)) {
|
|
23239
|
+
needed.add(d2);
|
|
23240
|
+
queue.push(d2);
|
|
23241
|
+
}
|
|
23242
|
+
}
|
|
23243
|
+
}
|
|
23244
|
+
}
|
|
23245
|
+
const unbuilt = [];
|
|
23246
|
+
for (const dir of dirs) {
|
|
23247
|
+
if (needed && !needed.has(dir)) continue;
|
|
23248
|
+
const pkg = readJson2(join48(cwd, dir, "package.json"));
|
|
23249
|
+
if (!pkg) continue;
|
|
23250
|
+
const targets = [];
|
|
23251
|
+
const collect2 = (v) => {
|
|
23252
|
+
if (typeof v === "string") targets.push(v);
|
|
23253
|
+
else if (v && typeof v === "object") for (const x of Object.values(v)) collect2(x);
|
|
23254
|
+
};
|
|
23255
|
+
collect2(pkg.main);
|
|
23256
|
+
collect2(pkg.module);
|
|
23257
|
+
collect2(pkg.exports?.["."] ?? (typeof pkg.exports === "string" ? pkg.exports : void 0));
|
|
23258
|
+
const built = targets.filter((t) => /(^|\/)(dist|build|lib|out)\//.test(t) && !t.includes("*"));
|
|
23259
|
+
if (built.length && pkg.scripts?.build && built.every((t) => !existsSync8(join48(cwd, dir, t)))) unbuilt.push(dir);
|
|
23260
|
+
}
|
|
23261
|
+
return unbuilt.sort();
|
|
23262
|
+
}
|
|
23263
|
+
function planSetup(cwd, opts = {}) {
|
|
23264
|
+
const pm = packageManager(cwd);
|
|
23265
|
+
const root2 = readJson2(join48(cwd, "package.json")) ?? {};
|
|
23266
|
+
const steps = [];
|
|
23267
|
+
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] };
|
|
23268
|
+
const anyDeps = Object.keys({ ...root2.dependencies, ...root2.devDependencies }).length > 0 || root2.workspaces || existsSync8(join48(cwd, "pnpm-workspace.yaml"));
|
|
23269
|
+
if (opts.only !== "build" && anyDeps && !existsSync8(join48(cwd, "node_modules"))) {
|
|
23270
|
+
const r = runner(["install"]);
|
|
23271
|
+
steps.push({ id: "install", ...r, why: "dependencies are not installed", dir: cwd });
|
|
23272
|
+
}
|
|
23273
|
+
const unbuilt = steps.length || opts.only === "install" ? [] : unbuiltWorkspacePackages(cwd, opts.appDir);
|
|
23274
|
+
if (unbuilt.length) {
|
|
23275
|
+
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"]);
|
|
23276
|
+
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;
|
|
23277
|
+
const r = turbo ? { ...turbo, fallback: own } : own;
|
|
23278
|
+
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 });
|
|
23279
|
+
}
|
|
23280
|
+
const want = opts.only === "build" ? void 0 : nodeWanted(root2.engines?.node);
|
|
23281
|
+
return { packageManager: pm.name, steps, ...unbuilt.length ? { unbuilt: unbuilt.length } : {}, ...want ? { node: { want, have: process.versions.node, command: `nvm install ${want} && nvm use ${want}` } } : {} };
|
|
23282
|
+
}
|
|
23283
|
+
function installRetry(step, output) {
|
|
23284
|
+
const pm = step.command === "corepack" || step.command === "npx" ? step.args.find((a) => /^(npm|pnpm|yarn|bun)(@|$)/.test(a))?.split("@")[0] : step.command;
|
|
23285
|
+
const tail = step.command === "corepack" ? step.args.slice(1) : step.command === "npx" ? step.args.slice(2) : step.args;
|
|
23286
|
+
const pinned = step.command === "corepack" || step.command === "npx" ? step.args.find((a) => /^(npm|pnpm|yarn|bun)(@|$)/.test(a)) : pm;
|
|
23287
|
+
if (pm === "pnpm" && /ERR_PNPM_(OUTDATED_LOCKFILE|LOCKFILE_CONFIG_MISMATCH|LOCKFILE_MISSING_DEPENDENCY)|frozen.lockfile|specifiers in the lockfile/i.test(output))
|
|
23288
|
+
return { why: "The lockfile is behind package.json, so a frozen install stops", step: { ...step, args: [...step.args, "--no-frozen-lockfile"] } };
|
|
23289
|
+
const lockfile = pm === "pnpm" ? /lockfileVersion[\s│|]+of[\s│|]+(\d+)(?:\.(\d+))?[\s│|]+is[\s│|]+incompatible/i.exec(output) : null;
|
|
23290
|
+
if (lockfile) {
|
|
23291
|
+
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}`;
|
|
23292
|
+
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")] } };
|
|
23293
|
+
}
|
|
23294
|
+
if (pm === "yarn" && /YN0028|lockfile would have been modified|--frozen-lockfile/i.test(output))
|
|
23295
|
+
return { why: "The lockfile is behind package.json, so a frozen install stops", step: { ...step, args: [...step.args, "--no-immutable"] } };
|
|
23296
|
+
if (pm === "pnpm" && /ERR_PNPM_IGNORED_BUILDS/.test(output) && !step.args.some((a) => a.startsWith("--config.dangerously-allow-all-builds")))
|
|
23297
|
+
return { why: "pnpm skipped the dependencies' build scripts", step: { ...step, args: [...step.args, "--config.dangerously-allow-all-builds=true"] } };
|
|
23298
|
+
if (pm === "bun" && step.command === "corepack")
|
|
23299
|
+
return { why: "corepack cannot fetch bun", step: { ...step, command: "npx", args: ["--yes", pinned, ...tail] } };
|
|
23300
|
+
if (pm === "npm" && /EBADENGINE|notsup|Unsupported engine/i.test(output) && !step.args.includes("--engine-strict=false"))
|
|
23301
|
+
return { why: "The project's engines field does not allow this Node version", step: { ...step, args: [...step.args, "--engine-strict=false"] } };
|
|
23302
|
+
}
|
|
23303
|
+
async function corepackShims(cwd, steps) {
|
|
23304
|
+
const pm = packageManager(cwd).name;
|
|
23305
|
+
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));
|
|
23306
|
+
if (!managers.length || !steps.length || !has("corepack")) return;
|
|
23307
|
+
const dir = join48(cwd, ".agenttwin", "bin");
|
|
23308
|
+
try {
|
|
23309
|
+
mkdirSync(dir, { recursive: true });
|
|
23310
|
+
} catch {
|
|
23311
|
+
return;
|
|
23312
|
+
}
|
|
23313
|
+
const ok3 = await new Promise((resolve18) => {
|
|
23314
|
+
const c = spawn9("corepack", ["enable", "--install-directory", dir, ...managers], { stdio: "ignore" });
|
|
23315
|
+
c.once("error", () => resolve18(false));
|
|
23316
|
+
c.once("exit", (code) => resolve18(code === 0));
|
|
23317
|
+
});
|
|
23318
|
+
return ok3 ? dir : void 0;
|
|
23319
|
+
}
|
|
23320
|
+
async function runSetup(cwd, opts) {
|
|
23321
|
+
const plan = opts.plan ?? planSetup(cwd, { ...opts.appDir !== void 0 ? { appDir: opts.appDir } : {}, ...opts.only ? { only: opts.only } : {} });
|
|
23322
|
+
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}`);
|
|
23323
|
+
if (!plan.steps.length) return true;
|
|
23324
|
+
opts.log(` Before the app can start: ${plan.steps.map((s) => `${show(s)} (${s.why})`).join(", then ")}.`);
|
|
23325
|
+
const answer = (await opts.ask({ id: "setup", text: `Run ${plan.steps.length === 1 ? "it" : "them"} now? (Y/n)`, default: "y" })).trim().toLowerCase();
|
|
23326
|
+
if (answer.startsWith("n")) {
|
|
23327
|
+
opts.log(` Skipped. Run ${plan.steps.map(show).join(" && ")} yourself, then npx agenttwin again.`);
|
|
23328
|
+
return false;
|
|
23329
|
+
}
|
|
23330
|
+
const shims = await corepackShims(cwd, plan.steps);
|
|
23331
|
+
const exec11 = (step) => new Promise((resolve18) => {
|
|
23332
|
+
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 ?? ""}` } : {} } });
|
|
23333
|
+
let tail = "";
|
|
23334
|
+
const keep = (c) => {
|
|
23335
|
+
tail = (tail + c.toString()).slice(-4e3);
|
|
23336
|
+
};
|
|
23337
|
+
child.stdout.on("data", keep);
|
|
23338
|
+
child.stderr.on("data", keep);
|
|
23339
|
+
child.once("error", (e) => {
|
|
23340
|
+
tail += String(e);
|
|
23341
|
+
resolve18({ code: 1, tail });
|
|
23342
|
+
});
|
|
23343
|
+
child.once("exit", (c) => resolve18({ code: c ?? 1, tail }));
|
|
23344
|
+
});
|
|
23345
|
+
for (const step of plan.steps) {
|
|
23346
|
+
opts.log(` Running ${show(step)}\u2026`);
|
|
23347
|
+
let { code, tail } = await exec11(step);
|
|
23348
|
+
for (let current2 = step, tries = 0; code !== 0 && step.id === "install" && tries < 3; tries++) {
|
|
23349
|
+
const retry = installRetry(current2, tail);
|
|
23350
|
+
if (!retry) break;
|
|
23351
|
+
opts.log(` ${retry.why}; running ${show(retry.step)}\u2026`);
|
|
23352
|
+
current2 = retry.step;
|
|
23353
|
+
({ code, tail } = await exec11(retry.step));
|
|
23354
|
+
}
|
|
23355
|
+
const left = code !== 0 && step.id === "build" && plan.unbuilt ? unbuiltWorkspacePackages(cwd, opts.appDir) : void 0;
|
|
23356
|
+
if (left && left.length < plan.unbuilt) {
|
|
23357
|
+
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"));
|
|
23358
|
+
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.`);
|
|
23359
|
+
continue;
|
|
23360
|
+
}
|
|
23361
|
+
if (code !== 0 && step.fallback) {
|
|
23362
|
+
const next = { ...step, ...step.fallback, fallback: void 0 };
|
|
23363
|
+
opts.log(` ${show(step)} failed; running ${show(next)}\u2026`);
|
|
23364
|
+
({ code, tail } = await exec11(next));
|
|
23365
|
+
}
|
|
23366
|
+
if (code !== 0) {
|
|
23367
|
+
opts.log(tail.split("\n").filter(Boolean).slice(-6).map((l) => " " + l.slice(0, 200)).join("\n"));
|
|
23368
|
+
opts.log(` ${show(step)} failed (exit ${code}). The run goes on; if the app cannot start, fix that first.`);
|
|
23369
|
+
return false;
|
|
23370
|
+
}
|
|
23371
|
+
}
|
|
23372
|
+
opts.log(" Setup done.");
|
|
23373
|
+
return true;
|
|
23374
|
+
}
|
|
23375
|
+
var readJson2, has, show, BUILD_PLACEHOLDERS;
|
|
23376
|
+
var init_setup = __esm({
|
|
23377
|
+
"src/flow/setup.ts"() {
|
|
23378
|
+
"use strict";
|
|
23379
|
+
readJson2 = (file) => {
|
|
23380
|
+
try {
|
|
23381
|
+
return JSON.parse(readFileSync9(file, "utf8"));
|
|
23382
|
+
} catch {
|
|
23383
|
+
return void 0;
|
|
23384
|
+
}
|
|
23385
|
+
};
|
|
23386
|
+
has = (cmd) => spawnSync2(process.platform === "win32" ? "where" : "which", [cmd], { stdio: "ignore" }).status === 0;
|
|
23387
|
+
show = (s) => [posix5.basename(s.command), ...s.args].join(" ");
|
|
23388
|
+
BUILD_PLACEHOLDERS = { DATABASE_URL: "postgresql://agenttwin:agenttwin@127.0.0.1:5432/agenttwin", DIRECT_URL: "postgresql://agenttwin:agenttwin@127.0.0.1:5432/agenttwin" };
|
|
23389
|
+
}
|
|
23390
|
+
});
|
|
23391
|
+
|
|
23072
23392
|
// src/runtime/engines/mysql-sql.ts
|
|
23073
23393
|
function tokenize(sql) {
|
|
23074
23394
|
const tokens = [];
|
|
@@ -23802,15 +24122,15 @@ var init_providers = __esm({
|
|
|
23802
24122
|
});
|
|
23803
24123
|
|
|
23804
24124
|
// src/flow/env-values.ts
|
|
23805
|
-
import { readFileSync as
|
|
23806
|
-
import { dirname as dirname11, join as
|
|
24125
|
+
import { readFileSync as readFileSync10 } from "fs";
|
|
24126
|
+
import { dirname as dirname11, join as join49, resolve as resolve14, sep as sep11 } from "path";
|
|
23807
24127
|
function readCommentedExamples(root2, entryFile) {
|
|
23808
24128
|
const top = resolve14(root2), values = {};
|
|
23809
24129
|
for (let directory = dirname11(resolve14(top, entryFile)); directory === top || directory.startsWith(top + sep11); directory = dirname11(directory)) {
|
|
23810
24130
|
for (const name of EXAMPLE_FILES) {
|
|
23811
24131
|
let text3;
|
|
23812
24132
|
try {
|
|
23813
|
-
text3 =
|
|
24133
|
+
text3 = readFileSync10(join49(directory, name), "utf8");
|
|
23814
24134
|
} catch {
|
|
23815
24135
|
continue;
|
|
23816
24136
|
}
|
|
@@ -23837,7 +24157,7 @@ function readEnvExamples(root2, entryFile) {
|
|
|
23837
24157
|
for (const directory of folders) for (const name of EXAMPLE_FILES) {
|
|
23838
24158
|
let text3;
|
|
23839
24159
|
try {
|
|
23840
|
-
text3 =
|
|
24160
|
+
text3 = readFileSync10(join49(directory, name), "utf8");
|
|
23841
24161
|
} catch {
|
|
23842
24162
|
continue;
|
|
23843
24163
|
}
|
|
@@ -23894,12 +24214,14 @@ function envProblems(stderr) {
|
|
|
23894
24214
|
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);
|
|
23895
24215
|
};
|
|
23896
24216
|
for (const block of stderr.split(/\n\s*\},?\s*\n/)) {
|
|
23897
|
-
const path2 = /path:\s*\[
|
|
24217
|
+
const path2 = /path:\s*\[?\s*['"]([A-Z][A-Z0-9_]+)['"]\s*\]?/.exec(block);
|
|
23898
24218
|
if (!path2) continue;
|
|
23899
24219
|
add(path2[1], /received undefined|Required|invalid_type/.test(block) && !/received (?:string|number|boolean)/.test(block));
|
|
23900
24220
|
}
|
|
23901
24221
|
for (const m of stderr.matchAll(/(?:^|[\s{,])["']?([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+)["']?:\s*\[\s*((?:["'][^"'\n]*["']\s*,?\s*)+)\]/gm))
|
|
23902
24222
|
add(m[1], /received undefined|\bRequired\b/.test(m[2]));
|
|
24223
|
+
for (const m of stderr.matchAll(/^\s*-\s+([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+):\s*(.+)$/gm))
|
|
24224
|
+
add(m[1], /received undefined|\bRequired\b/.test(m[2]));
|
|
23903
24225
|
for (const m of stderr.matchAll(/\bbut ([A-Z][A-Z0-9_]+) returned a Promise/g)) add(m[1], false);
|
|
23904
24226
|
for (const line of stderr.split("\n")) {
|
|
23905
24227
|
if (!/env|environment|config|required|missing|not (?:set|defined)|must be|please (?:set|define|provide|add|configure)/i.test(line)) continue;
|
|
@@ -23908,6 +24230,23 @@ function envProblems(stderr) {
|
|
|
23908
24230
|
}
|
|
23909
24231
|
return [...found].map(([name, missing]) => ({ name, missing }));
|
|
23910
24232
|
}
|
|
24233
|
+
function nextConfigProblems(stderr, root2, appDir = "") {
|
|
24234
|
+
if (!/Invalid (?:header|rewrite|redirect)s? found/i.test(stderr)) return [];
|
|
24235
|
+
const names = /* @__PURE__ */ new Set();
|
|
24236
|
+
for (const dir of [.../* @__PURE__ */ new Set([appDir, ""])]) for (const file of ["next.config.js", "next.config.mjs", "next.config.ts", "next.config.cjs"]) {
|
|
24237
|
+
let text3;
|
|
24238
|
+
try {
|
|
24239
|
+
text3 = readFileSync10(join49(root2, dir, file), "utf8");
|
|
24240
|
+
} catch {
|
|
24241
|
+
continue;
|
|
24242
|
+
}
|
|
24243
|
+
for (const m of text3.matchAll(/process\.env\.([A-Z][A-Z0-9_]+)|process\.env\[['"]([A-Z][A-Z0-9_]+)['"]\]/g)) {
|
|
24244
|
+
const n = m[1] ?? m[2];
|
|
24245
|
+
if (n !== "NODE_ENV") names.add(n);
|
|
24246
|
+
}
|
|
24247
|
+
}
|
|
24248
|
+
return [...names].map((name) => ({ name, missing: true }));
|
|
24249
|
+
}
|
|
23911
24250
|
function settleEnvironment(environment, problems, examples, tried, blocked, commented = {}) {
|
|
23912
24251
|
const set2 = [], cleared = [];
|
|
23913
24252
|
for (const { name, missing } of problems) {
|
|
@@ -23938,7 +24277,7 @@ function declaredSettings(root2, appDir) {
|
|
|
23938
24277
|
for (const file of [...EXAMPLE_FILES, "env.ts", "env.mjs", "env.js", "src/env.ts", "src/env.mjs", "src/env.js"]) {
|
|
23939
24278
|
let text3;
|
|
23940
24279
|
try {
|
|
23941
|
-
text3 =
|
|
24280
|
+
text3 = readFileSync10(join49(root2, appDir, file), "utf8");
|
|
23942
24281
|
} catch {
|
|
23943
24282
|
continue;
|
|
23944
24283
|
}
|
|
@@ -24092,11 +24431,11 @@ var init_account_presets = __esm({
|
|
|
24092
24431
|
|
|
24093
24432
|
// src/flow/autoprep.ts
|
|
24094
24433
|
import { mkdir as mkdir14, readFile as readFile31, writeFile as writeFile23 } from "fs/promises";
|
|
24095
|
-
import { existsSync as
|
|
24434
|
+
import { existsSync as existsSync9, readdirSync as readdirSync5, readFileSync as readFileSync11 } from "fs";
|
|
24096
24435
|
import { createHash as createHash25 } from "crypto";
|
|
24097
24436
|
import { createRequire as createRequire5 } from "module";
|
|
24098
|
-
import { spawnSync as
|
|
24099
|
-
import { dirname as dirname12, join as
|
|
24437
|
+
import { spawnSync as spawnSync3 } from "child_process";
|
|
24438
|
+
import { delimiter as delimiter3, dirname as dirname12, join as join50, posix as posix6, relative as relative14 } from "path";
|
|
24100
24439
|
import { pathToFileURL as pathToFileURL2 } from "url";
|
|
24101
24440
|
function fieldValue(name, message, channel) {
|
|
24102
24441
|
const n = name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
|
|
@@ -24217,7 +24556,26 @@ async function generateScenario(candidate, ask, discovered = discoverServices(ca
|
|
|
24217
24556
|
const norm = resolvedAll[i].title.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
24218
24557
|
return o.engine && norm.includes(o.engine.kind) || o.tier === "deep" && o.service?.adapter && norm.includes(o.service.adapter.replace(/-/g, ""));
|
|
24219
24558
|
})));
|
|
24220
|
-
|
|
24559
|
+
let twins2 = discovered.map(resolveTwin);
|
|
24560
|
+
{
|
|
24561
|
+
const byName = /* @__PURE__ */ new Map(), keep = [];
|
|
24562
|
+
twins2.forEach((t, i) => {
|
|
24563
|
+
const name = t.service?.name;
|
|
24564
|
+
const j = name === void 0 ? void 0 : byName.get(name);
|
|
24565
|
+
if (j === void 0) {
|
|
24566
|
+
if (name !== void 0) byName.set(name, i);
|
|
24567
|
+
keep.push(i);
|
|
24568
|
+
return;
|
|
24569
|
+
}
|
|
24570
|
+
const first = twins2[j] = { ...twins2[j], service: structuredClone(twins2[j].service) };
|
|
24571
|
+
for (const c of t.service.collections) if (!first.service.collections.some((x) => x.path === c.path)) first.service.collections.push(structuredClone(c));
|
|
24572
|
+
discovered[j] = { ...discovered[j], calls: [...discovered[j].calls, ...discovered[i].calls] };
|
|
24573
|
+
});
|
|
24574
|
+
if (keep.length < twins2.length) {
|
|
24575
|
+
twins2 = keep.map((i) => twins2[i]);
|
|
24576
|
+
discovered = keep.map((i) => discovered[i]);
|
|
24577
|
+
}
|
|
24578
|
+
}
|
|
24221
24579
|
const plan = (key3) => twins2.find((t, i) => discovered[i].key === key3 && t.service);
|
|
24222
24580
|
const calls = (p) => candidate.calls.filter((c) => c.provider === p || c.provider === `pack:${p}`);
|
|
24223
24581
|
const refunds = calls("stripe").some((c) => /^refunds\.create$/.test(c.operation));
|
|
@@ -24243,7 +24601,7 @@ async function generateScenario(candidate, ask, discovered = discoverServices(ca
|
|
|
24243
24601
|
let input;
|
|
24244
24602
|
if (candidate.bolt) {
|
|
24245
24603
|
if (!channel) channel = "C0AGENTTWIN";
|
|
24246
|
-
const source = root2 ? await readFile31(
|
|
24604
|
+
const source = root2 ? await readFile31(join50(root2, candidate.file), "utf8").catch(() => "") : "";
|
|
24247
24605
|
const stateRefs = [...source.matchAll(/state\??\.values\??\.([A-Za-z_]\w*)\??\.([A-Za-z_]\w*)/g)].map((m) => [m[1], m[2]]);
|
|
24248
24606
|
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)))
|
|
24249
24607
|
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]]);
|
|
@@ -24501,7 +24859,7 @@ async function generateScenario(candidate, ask, discovered = discoverServices(ca
|
|
|
24501
24859
|
if (tables2.size) assumptions.push(`PostgreSQL synthetic rows (must satisfy the project schema), seeded with ${[...tables2].map(([t, r]) => `${t} ${JSON.stringify(r)}`).join("; ")}.`);
|
|
24502
24860
|
} else if (adapter.startsWith("pack:")) {
|
|
24503
24861
|
const own = discovered[twins2.indexOf(twin)]?.calls ?? [];
|
|
24504
|
-
const manifest = candidate.boltApp && root2 ? await readFile31(
|
|
24862
|
+
const manifest = candidate.boltApp && root2 ? await readFile31(join50(root2, "manifest.json"), "utf8").then((t) => {
|
|
24505
24863
|
const m = JSON.parse(t);
|
|
24506
24864
|
return m && typeof m === "object" && m.settings ? m : void 0;
|
|
24507
24865
|
}).catch(() => void 0) : void 0;
|
|
@@ -24569,12 +24927,12 @@ async function generateScenario(candidate, ask, discovered = discoverServices(ca
|
|
|
24569
24927
|
function upstashSettings(root2, appDir) {
|
|
24570
24928
|
let text3 = "";
|
|
24571
24929
|
try {
|
|
24572
|
-
const pkg = JSON.parse(readFileSyncSafe(
|
|
24930
|
+
const pkg = JSON.parse(readFileSyncSafe(join50(root2, appDir, "package.json")) || "{}");
|
|
24573
24931
|
if (!pkg.dependencies?.["@upstash/redis"]) return void 0;
|
|
24574
24932
|
} catch {
|
|
24575
24933
|
return void 0;
|
|
24576
24934
|
}
|
|
24577
|
-
for (const file of [".env.example", "env.ts", "env.mjs", "src/env.ts", "src/env.mjs", "env.js"]) text3 += readFileSyncSafe(
|
|
24935
|
+
for (const file of [".env.example", "env.ts", "env.mjs", "src/env.ts", "src/env.mjs", "env.js"]) text3 += readFileSyncSafe(join50(root2, appDir, file));
|
|
24578
24936
|
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";
|
|
24579
24937
|
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));
|
|
24580
24938
|
return { url, tokens: tokens.length ? tokens : ["UPSTASH_REDIS_REST_TOKEN"] };
|
|
@@ -24582,7 +24940,7 @@ function upstashSettings(root2, appDir) {
|
|
|
24582
24940
|
async function settleConfiguration(cwd, prepared, stderr, tried) {
|
|
24583
24941
|
const twins2 = prepared.scenario.twins, managed = new Set(twins2.flatMap((t) => [t.envUrl, ...Object.keys(t.env ?? {})]).filter((v) => !!v));
|
|
24584
24942
|
const blocked = (name) => FORBIDDEN_ENV.test(name) || managed.has(name) || DATABASE_ENV.test(name) && twins2.some((t) => t.engine?.kind === "postgres");
|
|
24585
|
-
const changed = settleEnvironment(prepared.scenario.environment, envProblems(stderr), readEnvExamples(cwd, prepared.candidate.file), tried, blocked, readCommentedExamples(cwd, prepared.candidate.file));
|
|
24943
|
+
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));
|
|
24586
24944
|
if (changed.set.length || changed.cleared.length) await writeFile23(prepared.scenarioPath, JSON.stringify(prepared.scenario, null, 2) + "\n", { mode: 384 });
|
|
24587
24945
|
return changed;
|
|
24588
24946
|
}
|
|
@@ -24604,8 +24962,8 @@ function typescriptLoader() {
|
|
|
24604
24962
|
}
|
|
24605
24963
|
async function prepareWorkflow(cwd, candidate, ask, log, discovered) {
|
|
24606
24964
|
const slug4 = slugName(candidate.web ? candidate.title : candidate.exportName);
|
|
24607
|
-
const directory =
|
|
24608
|
-
const scenarioPath =
|
|
24965
|
+
const directory = join50(cwd, ".agenttwin", "auto", slug4);
|
|
24966
|
+
const scenarioPath = join50(directory, "scenario.json");
|
|
24609
24967
|
await mkdir14(directory, { recursive: true });
|
|
24610
24968
|
let scenario;
|
|
24611
24969
|
try {
|
|
@@ -24687,7 +25045,7 @@ async function prepareWorkflow(cwd, candidate, ask, log, discovered) {
|
|
|
24687
25045
|
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 ?? "")));
|
|
24688
25046
|
const servedPostgres = !!candidate.serve && usesPostgresDriver(cwd);
|
|
24689
25047
|
if ((candidate.web?.appDir !== void 0 || restDatabase || servedPostgres) && !scenario.twins.some((t) => t.engine?.kind === "postgres") && scenario.postgresSchemaFiles === void 0) {
|
|
24690
|
-
const appDir = candidate.web?.appDir ?? (candidate.serve ?
|
|
25048
|
+
const appDir = candidate.web?.appDir ?? (candidate.serve ? posix6.dirname(candidate.serve.entry ?? candidate.file) : "");
|
|
24691
25049
|
const found = await discoverAppPostgresSchema(cwd, candidate.web?.appDir ?? "");
|
|
24692
25050
|
const files = found?.length ? found : servedPostgres ? await discoverWorkspaceSchema(cwd, appDir) : void 0;
|
|
24693
25051
|
if (files?.length || servedPostgres) {
|
|
@@ -24704,11 +25062,11 @@ async function prepareWorkflow(cwd, candidate, ask, log, discovered) {
|
|
|
24704
25062
|
if (mode !== "auto" && mode !== "explicit") throw new Error("postgresSchemaMode must be auto or explicit.");
|
|
24705
25063
|
const nearest = async () => {
|
|
24706
25064
|
const dirs = [];
|
|
24707
|
-
let dir =
|
|
25065
|
+
let dir = posix6.dirname(candidate.file);
|
|
24708
25066
|
while (true) {
|
|
24709
|
-
if (
|
|
25067
|
+
if (existsSync9(join50(cwd, dir, "package.json")) || dir === ".") dirs.push(dir === "." ? "" : dir);
|
|
24710
25068
|
if (dir === "." || dir === "") break;
|
|
24711
|
-
dir =
|
|
25069
|
+
dir = posix6.dirname(dir);
|
|
24712
25070
|
}
|
|
24713
25071
|
for (const d2 of dirs) {
|
|
24714
25072
|
const found = d2 ? await discoverAppPostgresSchema(cwd, d2) : await discoverPostgresSchema(cwd);
|
|
@@ -24719,8 +25077,9 @@ async function prepareWorkflow(cwd, candidate, ask, log, discovered) {
|
|
|
24719
25077
|
let files = mode === "auto" ? await nearest() : scenario.postgresSchemaFiles ?? [];
|
|
24720
25078
|
scenario.postgresSchemaMode = mode;
|
|
24721
25079
|
let unreadable = false;
|
|
25080
|
+
let skippedExtensions = [];
|
|
24722
25081
|
try {
|
|
24723
|
-
await loadPostgresSchema(cwd, files);
|
|
25082
|
+
skippedExtensions = [...(await loadPostgresSchema(cwd, files)).matchAll(/-- AgentTwin: extension ([\w-]+) is not in the embedded engine/g)].map((m) => m[1]);
|
|
24724
25083
|
} catch (error) {
|
|
24725
25084
|
const why = error instanceof Error ? error.message : String(error);
|
|
24726
25085
|
if (!/Unsupported ORM schema|Unsupported SQL|not supported/i.test(why)) throw error;
|
|
@@ -24736,6 +25095,11 @@ async function prepareWorkflow(cwd, candidate, ask, log, discovered) {
|
|
|
24736
25095
|
const note = "No PostgreSQL schema or migrations were found: the database starts empty and its writes are not checked.";
|
|
24737
25096
|
if (!scenario.assumptions.includes(note)) scenario.assumptions.push(note);
|
|
24738
25097
|
} 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).`);
|
|
25098
|
+
if (skippedExtensions.length) {
|
|
25099
|
+
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.`;
|
|
25100
|
+
log(` ${note}`);
|
|
25101
|
+
if (!scenario.assumptions.includes(note)) scenario.assumptions.push(note);
|
|
25102
|
+
}
|
|
24739
25103
|
if (files.length) {
|
|
24740
25104
|
const note = "PostgreSQL uses project schema; generated synthetic rows must satisfy its constraints. Review the scenario seeds.";
|
|
24741
25105
|
if (!scenario.assumptions.includes(note)) scenario.assumptions.push(note);
|
|
@@ -24761,7 +25125,7 @@ async function prepareWorkflow(cwd, candidate, ask, log, discovered) {
|
|
|
24761
25125
|
services: noChecks ? [...seedTimes(scenario.services), sentinel] : seedTimes(scenario.services),
|
|
24762
25126
|
assertions: noChecks ? [{ service: "none", path: "/none", count: 0 }] : scenario.assertions
|
|
24763
25127
|
});
|
|
24764
|
-
const sourceDigests = async () => Object.fromEntries(await Promise.all(sources.map(async (f) => [f, createHash25("sha256").update(await readFile31(
|
|
25128
|
+
const sourceDigests = async () => Object.fromEntries(await Promise.all(sources.map(async (f) => [f, createHash25("sha256").update(await readFile31(join50(cwd, f))).digest("hex")])));
|
|
24765
25129
|
const build2 = async (repeat) => {
|
|
24766
25130
|
ensurePrismaClient(cwd, candidate.web?.appDir ?? "");
|
|
24767
25131
|
const driver = drivers(repeat);
|
|
@@ -24772,14 +25136,14 @@ import {pathToFileURL} from 'node:url';
|
|
|
24772
25136
|
const environment=${JSON.stringify(scenario.environment)},calls=${JSON.stringify(calls)};
|
|
24773
25137
|
for(const [key,value] of Object.entries(environment))if(process.env[key]===undefined)process.env[key]=value;
|
|
24774
25138
|
try{
|
|
24775
|
-
const module=await import(pathToFileURL(${JSON.stringify(
|
|
25139
|
+
const module=await import(pathToFileURL(${JSON.stringify(join50(cwd, candidate.file))}).href);
|
|
24776
25140
|
const fn=module[${JSON.stringify(candidate.exportName)}]??module.default?.[${JSON.stringify(candidate.exportName)}];
|
|
24777
25141
|
if(typeof fn!=='function')throw new Error(${JSON.stringify(`${candidate.exportName} is not an exported function of ${candidate.file}`)});
|
|
24778
25142
|
// {"$agenttwin:fn": name} in the scenario stands for a function the workflow calls on its argument (streamer.append):
|
|
24779
25143
|
// it records each call and returns undefined.
|
|
24780
25144
|
const invoked=[];let slackClient;
|
|
24781
25145
|
// A Slack WebClient from the app's own dependencies (Bolt ships @slack/web-api); the twin routes slack.com calls.
|
|
24782
|
-
const slack=async()=>{if(slackClient)return slackClient;const {createRequire}=await import('node:module');const req=createRequire(${JSON.stringify(
|
|
25146
|
+
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');};
|
|
24783
25147
|
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);};})()
|
|
24784
25148
|
:v[${JSON.stringify(SLACK_CLIENT)}]?await slack()
|
|
24785
25149
|
: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});})()
|
|
@@ -24791,8 +25155,8 @@ setTimeout(()=>process.exit(),1000).unref();
|
|
|
24791
25155
|
`;
|
|
24792
25156
|
const serveEntry = serve?.entry ?? candidate.file;
|
|
24793
25157
|
const workersConfig = (() => {
|
|
24794
|
-
for (let dir =
|
|
24795
|
-
for (const f of ["wrangler.jsonc", "wrangler.json", "wrangler.toml"]) if (
|
|
25158
|
+
for (let dir = posix6.dirname(serveEntry); ; dir = posix6.dirname(dir)) {
|
|
25159
|
+
for (const f of ["wrangler.jsonc", "wrangler.json", "wrangler.toml"]) if (existsSync9(join50(cwd, dir, f))) return join50(cwd, dir, f);
|
|
24796
25160
|
if (dir === "." || dir === "/" || dir === "") return void 0;
|
|
24797
25161
|
}
|
|
24798
25162
|
})();
|
|
@@ -24800,7 +25164,7 @@ setTimeout(()=>process.exit(),1000).unref();
|
|
|
24800
25164
|
import {pathToFileURL} from 'node:url';
|
|
24801
25165
|
import {spawn} from 'node:child_process';
|
|
24802
25166
|
import net from 'node:net';
|
|
24803
|
-
const environment=${JSON.stringify(scenario.environment)},calls=${JSON.stringify(calls)},listenPort=${JSON.stringify(serve.listenPort ?? null)},script=${JSON.stringify(serve.script ? { ...serve.script, dir:
|
|
25167
|
+
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)};
|
|
24804
25168
|
for(const [key,value] of Object.entries(environment))if(process.env[key]===undefined)process.env[key]=value;
|
|
24805
25169
|
const signature=${JSON.stringify(scenario.signature ?? null)};
|
|
24806
25170
|
${SIGNING_DRIVER}
|
|
@@ -24845,8 +25209,8 @@ try{
|
|
|
24845
25209
|
const bound=[];const listen0=net.Server.prototype.listen;
|
|
24846
25210
|
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);};
|
|
24847
25211
|
const workersConfig=${JSON.stringify(workersConfig ?? null)};
|
|
24848
|
-
let workers;if(workersConfig){const {writeFileSync}=await import('node:fs');const shim=${JSON.stringify(
|
|
24849
|
-
const module=await import(pathToFileURL(${JSON.stringify(
|
|
25212
|
+
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();}
|
|
25213
|
+
const module=await import(pathToFileURL(${JSON.stringify(join50(cwd, serveEntry))}).href);
|
|
24850
25214
|
const workersEnv=workers?await workers.environment(workersConfig,module):undefined;
|
|
24851
25215
|
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));}};
|
|
24852
25216
|
port=await quick([free,listenPort]);
|
|
@@ -24889,10 +25253,12 @@ try{
|
|
|
24889
25253
|
// A provider webhook arrives signed, as the provider sends it.
|
|
24890
25254
|
const signed=signature?await signWebhook(signature.scheme,signingSecret(signature),JSON.stringify(args[0]??{})):{};
|
|
24891
25255
|
// A redirect is the route's answer (to a hosted checkout page, a sign-in page); the browser would go there next.
|
|
24892
|
-
|
|
25256
|
+
// A GET carries its input as the query string (an OAuth callback's code and state).
|
|
25257
|
+
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():'';
|
|
25258
|
+
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]??{})})});
|
|
24893
25259
|
const text=await response.text();
|
|
24894
25260
|
console.log(JSON.stringify({schema:'agenttwin/call-result-v1',call:index+1,status:response.status,result:text.slice(0,2000)||response.headers.get('location')||''}));
|
|
24895
|
-
if(response.status>=400){console.error('HTTP '+response.status+' from ${serve.method} ${serve.path}: '+text.slice(0,
|
|
25261
|
+
if(response.status>=400){console.error('HTTP '+response.status+' from ${serve.method} ${serve.path}: '+text.slice(0,800));process.exitCode=1;}
|
|
24896
25262
|
}
|
|
24897
25263
|
// Work the handler does after answering still runs: give it a moment.
|
|
24898
25264
|
if(script)await new Promise(r=>setTimeout(r,1000));
|
|
@@ -24917,7 +25283,7 @@ const free=await new Promise(resolve=>{const s=net.createServer();s.listen(0,'12
|
|
|
24917
25283
|
process.env.PORT=String(free);
|
|
24918
25284
|
// Bolt's own start() settles once its Socket Mode connection is open: hold on to it.
|
|
24919
25285
|
let started;
|
|
24920
|
-
try{const {App}=createRequire(${JSON.stringify(
|
|
25286
|
+
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);}
|
|
24921
25287
|
const route=(JSON.parse(process.env.AGENTTWIN_ROUTES||'{}').routes||[]).find(r=>r.host==='slack.com');
|
|
24922
25288
|
// Calls made as the workspace, not the app: straight to the twin, with the run token beside the caller's own token.
|
|
24923
25289
|
const slack=async(method,token,params,path='/api/'+method)=>{
|
|
@@ -24927,7 +25293,7 @@ const slack=async(method,token,params,path='/api/'+method)=>{
|
|
|
24927
25293
|
};
|
|
24928
25294
|
try{
|
|
24929
25295
|
if(!route)throw new Error('No Slack twin serves slack.com in this run.');
|
|
24930
|
-
await import(pathToFileURL(${JSON.stringify(
|
|
25296
|
+
await import(pathToFileURL(${JSON.stringify(join50(cwd, candidate.file))}).href);
|
|
24931
25297
|
const end=Date.now()+20000;while(!started&&Date.now()<end)await new Promise(r=>setTimeout(r,100));
|
|
24932
25298
|
if(!started)throw new Error('The app did not call app.start() within 20 seconds.');
|
|
24933
25299
|
const receiver=await Promise.race([started,new Promise((_,reject)=>setTimeout(()=>reject(new Error('The app did not connect to Slack within 20 seconds.')),20000))]);
|
|
@@ -24967,7 +25333,7 @@ import {pathToFileURL} from 'node:url';
|
|
|
24967
25333
|
const environment=${JSON.stringify(scenario.environment)},calls=${JSON.stringify(calls)};
|
|
24968
25334
|
for(const [key,value] of Object.entries(environment))if(process.env[key]===undefined)process.env[key]=value;
|
|
24969
25335
|
try{
|
|
24970
|
-
const module=await import(pathToFileURL(${JSON.stringify(
|
|
25336
|
+
const module=await import(pathToFileURL(${JSON.stringify(join50(cwd, candidate.file))}).href);
|
|
24971
25337
|
const fn=module[${JSON.stringify(candidate.exportName)}];
|
|
24972
25338
|
if(typeof fn!=='function')throw new Error(${JSON.stringify(`${candidate.exportName} is not an exported function of ${candidate.file}`)});
|
|
24973
25339
|
for(const [index,args] of calls.entries()){
|
|
@@ -24975,7 +25341,7 @@ try{
|
|
|
24975
25341
|
const response=await fn(request,{params:Promise.resolve(${JSON.stringify(web.params)})});
|
|
24976
25342
|
const status=response?.status??200,text=response&&typeof response.text==='function'?await response.text():JSON.stringify(response??null);
|
|
24977
25343
|
console.log(JSON.stringify({schema:'agenttwin/call-result-v1',call:index+1,status,result:text.slice(0,2000)}));
|
|
24978
|
-
if(status>=400){console.error('HTTP '+status+' from ${web.method} ${web.path}: '+text.slice(0,
|
|
25344
|
+
if(status>=400){console.error('HTTP '+status+' from ${web.method} ${web.path}: '+text.slice(0,800));process.exitCode=1;}
|
|
24979
25345
|
}
|
|
24980
25346
|
}catch(error){console.error(error);process.exitCode=1;}
|
|
24981
25347
|
setTimeout(()=>process.exit(),1000).unref();
|
|
@@ -24984,7 +25350,7 @@ setTimeout(()=>process.exit(),1000).unref();
|
|
|
24984
25350
|
import {spawn} from 'node:child_process';
|
|
24985
25351
|
import {createRequire} from 'node:module';
|
|
24986
25352
|
import net from 'node:net';
|
|
24987
|
-
const environment=${JSON.stringify(scenario.environment)},calls=${JSON.stringify(calls)},appDir=${JSON.stringify(
|
|
25353
|
+
const environment=${JSON.stringify(scenario.environment)},calls=${JSON.stringify(calls)},appDir=${JSON.stringify(join50(cwd, web.appDir))};
|
|
24988
25354
|
const env={...process.env,NEXT_TELEMETRY_DISABLED:'1'};for(const [key,value] of Object.entries(environment))if(env[key]===undefined)env[key]=value;
|
|
24989
25355
|
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));});});
|
|
24990
25356
|
env.PORT=String(port);
|
|
@@ -25042,7 +25408,7 @@ try{
|
|
|
25042
25408
|
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})});
|
|
25043
25409
|
const text=await response.text();
|
|
25044
25410
|
console.log(JSON.stringify({schema:'agenttwin/call-result-v1',call:index+1,status:response.status,result:text.slice(0,2000)}));
|
|
25045
|
-
if(response.status>=400){console.error('HTTP '+response.status+' from ${web.method} ${web.path}: '+text.slice(0,
|
|
25411
|
+
if(response.status>=400){console.error('HTTP '+response.status+' from ${web.method} ${web.path}: '+text.slice(0,800));process.exitCode=1;}
|
|
25046
25412
|
}
|
|
25047
25413
|
// Work the handler scheduled after responding (after(), queued jobs) still runs: wait until the server goes quiet.
|
|
25048
25414
|
const settleBy=Date.now()+30000;lastOutput=Date.now();
|
|
@@ -25056,15 +25422,15 @@ import {spawn} from 'node:child_process';
|
|
|
25056
25422
|
const environment=${JSON.stringify(scenario.environment)},calls=${JSON.stringify(calls)};
|
|
25057
25423
|
const env={...process.env};for(const [key,value] of Object.entries(environment))if(env[key]===undefined)env[key]=value;
|
|
25058
25424
|
for(const [index] of calls.entries()){
|
|
25059
|
-
const exitCode=await new Promise(resolve=>{const child=spawn(process.execPath,[...process.execArgv,${JSON.stringify(
|
|
25425
|
+
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));});
|
|
25060
25426
|
console.log(JSON.stringify({schema:'agenttwin/call-result-v1',call:index+1,result:{exitCode}}));
|
|
25061
25427
|
if(exitCode!==0){console.error(${JSON.stringify(candidate.file)}+' exited with code '+exitCode);process.exitCode=1;}
|
|
25062
25428
|
}
|
|
25063
25429
|
` : void 0;
|
|
25064
25430
|
if (candidate.python) {
|
|
25065
25431
|
const pyDriver = driver.replace(/\.mjs$/, ".py");
|
|
25066
|
-
const venv = [".venv/bin/python", "venv/bin/python", ".venv/Scripts/python.exe"].map((p) =>
|
|
25067
|
-
await writeFile23(
|
|
25432
|
+
const venv = [".venv/bin/python", "venv/bin/python", ".venv/Scripts/python.exe"].map((p) => join50(cwd, p)).find((p) => existsSync9(p));
|
|
25433
|
+
await writeFile23(join50(cwd, pyDriver), `# Generated by AgentTwin: runs ${candidate.file} as a script on twins.
|
|
25068
25434
|
import json, os, subprocess, sys
|
|
25069
25435
|
environment = json.loads(${JSON.stringify(JSON.stringify(scenario.environment))})
|
|
25070
25436
|
env = dict(os.environ)
|
|
@@ -25072,7 +25438,7 @@ for key, value in environment.items():
|
|
|
25072
25438
|
env.setdefault(key, value)
|
|
25073
25439
|
status = 0
|
|
25074
25440
|
for index in range(${calls.length}):
|
|
25075
|
-
code = subprocess.call([sys.executable, ${JSON.stringify(
|
|
25441
|
+
code = subprocess.call([sys.executable, ${JSON.stringify(join50(cwd, candidate.file))}], cwd=${JSON.stringify(cwd)}, env=env)
|
|
25076
25442
|
print(json.dumps({"schema": "agenttwin/call-result-v1", "call": index + 1, "result": {"exitCode": code}}), flush=True)
|
|
25077
25443
|
if code != 0:
|
|
25078
25444
|
print(${JSON.stringify(candidate.file)} + " exited with code " + str(code), file=sys.stderr, flush=True)
|
|
@@ -25082,7 +25448,7 @@ sys.exit(status)
|
|
|
25082
25448
|
const spec2 = parseWorld({ ...world, files: [pyDriver, ...sources], command: [venv ?? "python3", pyDriver] });
|
|
25083
25449
|
return { dir: cwd, spec: spec2, sourceDigests: await sourceDigests() };
|
|
25084
25450
|
}
|
|
25085
|
-
await writeFile23(
|
|
25451
|
+
await writeFile23(join50(cwd, driver), boltDriver ?? scriptDriver ?? nextDriver ?? webDriver ?? serveDriver ?? functionDriver, { mode: 384 });
|
|
25086
25452
|
const spec = parseWorld({ ...world, files: [driver, ...sources], command: ["node", ...loader ? ["--import", loader] : [], driver] });
|
|
25087
25453
|
return { dir: cwd, spec, sourceDigests: await sourceDigests() };
|
|
25088
25454
|
};
|
|
@@ -25090,19 +25456,25 @@ sys.exit(status)
|
|
|
25090
25456
|
}
|
|
25091
25457
|
function ensurePrismaClient(cwd, appDir) {
|
|
25092
25458
|
const schemas = /* @__PURE__ */ new Set();
|
|
25093
|
-
for (const dir of [
|
|
25459
|
+
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);
|
|
25094
25460
|
for (const group of ["packages", "apps", "libs"]) try {
|
|
25095
|
-
for (const name of
|
|
25461
|
+
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);
|
|
25096
25462
|
} catch {
|
|
25097
25463
|
}
|
|
25098
25464
|
for (const schema of schemas) {
|
|
25099
|
-
const text3 =
|
|
25465
|
+
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);
|
|
25100
25466
|
const output = /generator\s+\w+\s*\{[^}]*\boutput\s*=\s*"([^"]+)"/.exec(text3)?.[1];
|
|
25101
|
-
const req = createRequire5(
|
|
25102
|
-
const generated = output ?
|
|
25467
|
+
const req = createRequire5(join50(pkgDir, "package.json"));
|
|
25468
|
+
const generated = output ? existsSync9(join50(dirname12(schema), output)) : (() => {
|
|
25103
25469
|
try {
|
|
25104
|
-
req.resolve(".prisma/client/default");
|
|
25105
|
-
return
|
|
25470
|
+
const dir = dirname12(req.resolve(".prisma/client/default"));
|
|
25471
|
+
return !["default.js", "index.js"].some((f) => {
|
|
25472
|
+
try {
|
|
25473
|
+
return readFileSync11(join50(dir, f), "utf8").includes("did not initialize yet");
|
|
25474
|
+
} catch {
|
|
25475
|
+
return false;
|
|
25476
|
+
}
|
|
25477
|
+
});
|
|
25106
25478
|
} catch {
|
|
25107
25479
|
return false;
|
|
25108
25480
|
}
|
|
@@ -25110,12 +25482,18 @@ function ensurePrismaClient(cwd, appDir) {
|
|
|
25110
25482
|
if (generated) continue;
|
|
25111
25483
|
let bin;
|
|
25112
25484
|
for (let dir = pkgDir; dir.startsWith(cwd) && !bin; dir = dirname12(dir)) {
|
|
25113
|
-
const b =
|
|
25114
|
-
if (
|
|
25485
|
+
const b = join50(dir, "node_modules", ".bin", "prisma");
|
|
25486
|
+
if (existsSync9(b)) bin = b;
|
|
25115
25487
|
if (dir === cwd) break;
|
|
25116
25488
|
}
|
|
25117
25489
|
if (!bin) continue;
|
|
25118
|
-
const
|
|
25490
|
+
const bins = [];
|
|
25491
|
+
for (let dir = pkgDir; dir.startsWith(cwd); dir = dirname12(dir)) {
|
|
25492
|
+
const b = join50(dir, "node_modules", ".bin");
|
|
25493
|
+
if (existsSync9(b)) bins.push(b);
|
|
25494
|
+
if (dir === cwd) break;
|
|
25495
|
+
}
|
|
25496
|
+
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) } });
|
|
25119
25497
|
if (result2.status !== 0) process.stderr.write(` prisma generate failed for ${relative14(cwd, schema)}: ${String(result2.stderr ?? "").trim().split("\n").slice(-2).join(" ")}
|
|
25120
25498
|
`);
|
|
25121
25499
|
}
|
|
@@ -25123,7 +25501,7 @@ function ensurePrismaClient(cwd, appDir) {
|
|
|
25123
25501
|
function usesPostgresDriver(cwd) {
|
|
25124
25502
|
const deps = (dir) => {
|
|
25125
25503
|
try {
|
|
25126
|
-
const p = JSON.parse(
|
|
25504
|
+
const p = JSON.parse(readFileSync11(join50(cwd, dir, "package.json"), "utf8"));
|
|
25127
25505
|
return Object.keys({ ...p.dependencies, ...p.devDependencies });
|
|
25128
25506
|
} catch {
|
|
25129
25507
|
return [];
|
|
@@ -25131,14 +25509,14 @@ function usesPostgresDriver(cwd) {
|
|
|
25131
25509
|
};
|
|
25132
25510
|
const dirs = ["."];
|
|
25133
25511
|
for (const base of ["packages", "apps", "services", "server", "backend"]) try {
|
|
25134
|
-
for (const e of
|
|
25512
|
+
for (const e of readdirSync5(join50(cwd, base), { withFileTypes: true })) if (e.isDirectory()) dirs.push(join50(base, e.name));
|
|
25135
25513
|
dirs.push(base);
|
|
25136
25514
|
} catch {
|
|
25137
25515
|
}
|
|
25138
25516
|
if (dirs.some((d2) => deps(d2).some((n) => POSTGRES_DRIVERS.includes(n)))) return true;
|
|
25139
25517
|
return dirs.some((d2) => deps(d2).includes("@prisma/client") && ["prisma/schema.prisma", "schema.prisma"].some((f) => {
|
|
25140
25518
|
try {
|
|
25141
|
-
return /provider\s*=\s*"postgres(?:ql)?"/.test(
|
|
25519
|
+
return /provider\s*=\s*"postgres(?:ql)?"/.test(readFileSync11(join50(cwd, d2, f), "utf8"));
|
|
25142
25520
|
} catch {
|
|
25143
25521
|
return false;
|
|
25144
25522
|
}
|
|
@@ -25148,8 +25526,8 @@ async function discoverWorkspaceSchema(cwd, appDir) {
|
|
|
25148
25526
|
const own = appDir && appDir !== "." ? await discoverAppPostgresSchema(cwd, appDir) : void 0;
|
|
25149
25527
|
if (own?.length) return own;
|
|
25150
25528
|
for (const base of ["packages", "apps", "services"]) try {
|
|
25151
|
-
for (const e of
|
|
25152
|
-
const found = await discoverAppPostgresSchema(cwd,
|
|
25529
|
+
for (const e of readdirSync5(join50(cwd, base), { withFileTypes: true })) if (e.isDirectory()) {
|
|
25530
|
+
const found = await discoverAppPostgresSchema(cwd, join50(base, e.name));
|
|
25153
25531
|
if (found?.length) return found;
|
|
25154
25532
|
}
|
|
25155
25533
|
} catch {
|
|
@@ -25162,6 +25540,7 @@ var init_autoprep = __esm({
|
|
|
25162
25540
|
"use strict";
|
|
25163
25541
|
init_http_world();
|
|
25164
25542
|
init_workers_env();
|
|
25543
|
+
init_setup();
|
|
25165
25544
|
init_postgres_schema();
|
|
25166
25545
|
init_rabbitmq_assertions();
|
|
25167
25546
|
init_kafka_assertions();
|
|
@@ -25201,7 +25580,7 @@ var init_autoprep = __esm({
|
|
|
25201
25580
|
};
|
|
25202
25581
|
readFileSyncSafe = (path2) => {
|
|
25203
25582
|
try {
|
|
25204
|
-
return
|
|
25583
|
+
return readFileSync11(path2, "utf8");
|
|
25205
25584
|
} catch {
|
|
25206
25585
|
return "";
|
|
25207
25586
|
}
|
|
@@ -25352,8 +25731,8 @@ var init_first_run_help = __esm({
|
|
|
25352
25731
|
});
|
|
25353
25732
|
|
|
25354
25733
|
// src/flow/twin-gaps.ts
|
|
25355
|
-
import { existsSync as
|
|
25356
|
-
import { join as
|
|
25734
|
+
import { existsSync as existsSync10, mkdirSync as mkdirSync2, readFileSync as readFileSync12, writeFileSync as writeFileSync2 } from "fs";
|
|
25735
|
+
import { join as join51 } from "path";
|
|
25357
25736
|
function twinGap(entry) {
|
|
25358
25737
|
const m = /^([\w.-]+):\s*(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+(\/[^\s:?]*)/.exec(entry);
|
|
25359
25738
|
if (!m) return void 0;
|
|
@@ -25363,11 +25742,11 @@ function twinGap(entry) {
|
|
|
25363
25742
|
function recordTwinGaps(cwd, entries, now = /* @__PURE__ */ new Date()) {
|
|
25364
25743
|
const labels = [...new Set(entries.map(twinGap).filter((g) => !!g).map(gapLabel))];
|
|
25365
25744
|
if (!labels.length) return [];
|
|
25366
|
-
const dir =
|
|
25745
|
+
const dir = join51(cwd, ".agenttwin"), file = join51(dir, "twin-gaps.json");
|
|
25367
25746
|
let data = { version: 1, gaps: {} };
|
|
25368
25747
|
try {
|
|
25369
|
-
if (
|
|
25370
|
-
const read2 = JSON.parse(
|
|
25748
|
+
if (existsSync10(file)) {
|
|
25749
|
+
const read2 = JSON.parse(readFileSync12(file, "utf8"));
|
|
25371
25750
|
if (read2?.version === 1 && read2.gaps) data = read2;
|
|
25372
25751
|
}
|
|
25373
25752
|
} catch {
|
|
@@ -25379,7 +25758,7 @@ function recordTwinGaps(cwd, entries, now = /* @__PURE__ */ new Date()) {
|
|
|
25379
25758
|
data.gaps[label2] = g;
|
|
25380
25759
|
}
|
|
25381
25760
|
try {
|
|
25382
|
-
|
|
25761
|
+
mkdirSync2(dir, { recursive: true });
|
|
25383
25762
|
writeFileSync2(file, JSON.stringify(data, null, 2) + "\n");
|
|
25384
25763
|
} catch {
|
|
25385
25764
|
}
|
|
@@ -25398,199 +25777,6 @@ var init_twin_gaps = __esm({
|
|
|
25398
25777
|
}
|
|
25399
25778
|
});
|
|
25400
25779
|
|
|
25401
|
-
// src/flow/setup.ts
|
|
25402
|
-
import { spawn as spawn9, spawnSync as spawnSync3 } from "child_process";
|
|
25403
|
-
import { existsSync as existsSync10, readFileSync as readFileSync12, readdirSync as readdirSync5 } from "fs";
|
|
25404
|
-
import { delimiter as delimiter2, join as join51, posix as posix6 } from "path";
|
|
25405
|
-
function packageManager(cwd) {
|
|
25406
|
-
const field2 = readJson2(join51(cwd, "package.json"))?.packageManager;
|
|
25407
|
-
if (typeof field2 === "string") {
|
|
25408
|
-
const [name, version] = field2.split("@");
|
|
25409
|
-
if (["npm", "pnpm", "yarn", "bun"].includes(name)) return { name, version: version?.split("+")[0] };
|
|
25410
|
-
}
|
|
25411
|
-
if (existsSync10(join51(cwd, "pnpm-lock.yaml"))) return { name: "pnpm" };
|
|
25412
|
-
if (existsSync10(join51(cwd, "yarn.lock"))) return { name: "yarn" };
|
|
25413
|
-
if (existsSync10(join51(cwd, "bun.lock")) || existsSync10(join51(cwd, "bun.lockb"))) return { name: "bun" };
|
|
25414
|
-
return { name: "npm" };
|
|
25415
|
-
}
|
|
25416
|
-
function nodeWanted(range, have = process.versions.node) {
|
|
25417
|
-
if (!range || !/\d/.test(range)) return void 0;
|
|
25418
|
-
const current2 = Number(have.split(".")[0]);
|
|
25419
|
-
const alternatives = range.split("||").map((alt) => [...alt.matchAll(/(>=|<=|>|<|\^|~|=)?\s*v?(\d+)/g)].map((m) => ({ op: m[1] ?? "", major: Number(m[2]) })));
|
|
25420
|
-
const satisfied = (cmp2) => cmp2.every(({ op: op2, major }) => op2 === ">=" || op2 === ">" ? current2 >= major : op2 === "<" ? current2 < major : op2 === "<=" ? current2 <= major : current2 === major);
|
|
25421
|
-
if (alternatives.some((a) => a.length && satisfied(a))) return void 0;
|
|
25422
|
-
const lows = alternatives.flatMap((a) => a.filter((c) => !c.op.startsWith("<")).map((c) => c.major));
|
|
25423
|
-
return lows.length ? String(Math.min(...lows.filter((m) => m > current2).concat(lows.every((m) => m <= current2) ? [Math.max(...lows)] : []))) : void 0;
|
|
25424
|
-
}
|
|
25425
|
-
function unbuiltWorkspacePackages(cwd, appDir) {
|
|
25426
|
-
const root2 = readJson2(join51(cwd, "package.json"));
|
|
25427
|
-
let patterns = Array.isArray(root2?.workspaces) ? root2.workspaces : Array.isArray(root2?.workspaces?.packages) ? root2.workspaces.packages : [];
|
|
25428
|
-
if (existsSync10(join51(cwd, "pnpm-workspace.yaml"))) {
|
|
25429
|
-
const text3 = readFileSync12(join51(cwd, "pnpm-workspace.yaml"), "utf8");
|
|
25430
|
-
patterns = [...patterns, ...[...text3.matchAll(/^\s*-\s*['"]?([^'"\n#]+)['"]?/gm)].map((m) => m[1].trim())];
|
|
25431
|
-
}
|
|
25432
|
-
const dirs = /* @__PURE__ */ new Set();
|
|
25433
|
-
for (const pattern of patterns) {
|
|
25434
|
-
if (pattern.startsWith("!")) continue;
|
|
25435
|
-
const base = pattern.replace(/\/\*\*?$/, "");
|
|
25436
|
-
if (pattern.endsWith("*")) {
|
|
25437
|
-
try {
|
|
25438
|
-
for (const e of readdirSync5(join51(cwd, base), { withFileTypes: true })) if (e.isDirectory()) dirs.add(posix6.join(base, e.name));
|
|
25439
|
-
} catch {
|
|
25440
|
-
}
|
|
25441
|
-
} else dirs.add(base);
|
|
25442
|
-
}
|
|
25443
|
-
let needed;
|
|
25444
|
-
if (appDir !== void 0) {
|
|
25445
|
-
const byName = /* @__PURE__ */ new Map();
|
|
25446
|
-
for (const dir of dirs) {
|
|
25447
|
-
const name = readJson2(join51(cwd, dir, "package.json"))?.name;
|
|
25448
|
-
if (typeof name === "string") byName.set(name, dir);
|
|
25449
|
-
}
|
|
25450
|
-
needed = /* @__PURE__ */ new Set();
|
|
25451
|
-
const queue = [appDir];
|
|
25452
|
-
while (queue.length) {
|
|
25453
|
-
const dir = queue.shift();
|
|
25454
|
-
const pkg = readJson2(join51(cwd, dir, "package.json"));
|
|
25455
|
-
for (const dep of Object.keys({ ...pkg?.dependencies, ...pkg?.devDependencies, ...pkg?.peerDependencies })) {
|
|
25456
|
-
const d2 = byName.get(dep);
|
|
25457
|
-
if (d2 && !needed.has(d2)) {
|
|
25458
|
-
needed.add(d2);
|
|
25459
|
-
queue.push(d2);
|
|
25460
|
-
}
|
|
25461
|
-
}
|
|
25462
|
-
}
|
|
25463
|
-
}
|
|
25464
|
-
const unbuilt = [];
|
|
25465
|
-
for (const dir of dirs) {
|
|
25466
|
-
if (needed && !needed.has(dir)) continue;
|
|
25467
|
-
const pkg = readJson2(join51(cwd, dir, "package.json"));
|
|
25468
|
-
if (!pkg) continue;
|
|
25469
|
-
const targets = [];
|
|
25470
|
-
const collect2 = (v) => {
|
|
25471
|
-
if (typeof v === "string") targets.push(v);
|
|
25472
|
-
else if (v && typeof v === "object") for (const x of Object.values(v)) collect2(x);
|
|
25473
|
-
};
|
|
25474
|
-
collect2(pkg.main);
|
|
25475
|
-
collect2(pkg.module);
|
|
25476
|
-
collect2(pkg.exports?.["."] ?? (typeof pkg.exports === "string" ? pkg.exports : void 0));
|
|
25477
|
-
const built = targets.filter((t) => /(^|\/)(dist|build|lib|out)\//.test(t) && !t.includes("*"));
|
|
25478
|
-
if (built.length && pkg.scripts?.build && built.every((t) => !existsSync10(join51(cwd, dir, t)))) unbuilt.push(dir);
|
|
25479
|
-
}
|
|
25480
|
-
return unbuilt.sort();
|
|
25481
|
-
}
|
|
25482
|
-
function planSetup(cwd, opts = {}) {
|
|
25483
|
-
const pm = packageManager(cwd);
|
|
25484
|
-
const root2 = readJson2(join51(cwd, "package.json")) ?? {};
|
|
25485
|
-
const steps = [];
|
|
25486
|
-
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] };
|
|
25487
|
-
const anyDeps = Object.keys({ ...root2.dependencies, ...root2.devDependencies }).length > 0 || root2.workspaces || existsSync10(join51(cwd, "pnpm-workspace.yaml"));
|
|
25488
|
-
if (opts.only !== "build" && anyDeps && !existsSync10(join51(cwd, "node_modules"))) {
|
|
25489
|
-
const r = runner(["install"]);
|
|
25490
|
-
steps.push({ id: "install", ...r, why: "dependencies are not installed", dir: cwd });
|
|
25491
|
-
}
|
|
25492
|
-
const unbuilt = steps.length || opts.only === "install" ? [] : unbuiltWorkspacePackages(cwd, opts.appDir);
|
|
25493
|
-
if (unbuilt.length) {
|
|
25494
|
-
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"]);
|
|
25495
|
-
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;
|
|
25496
|
-
const r = turbo ? { ...turbo, fallback: own } : own;
|
|
25497
|
-
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 });
|
|
25498
|
-
}
|
|
25499
|
-
const want = opts.only === "build" ? void 0 : nodeWanted(root2.engines?.node);
|
|
25500
|
-
return { packageManager: pm.name, steps, ...want ? { node: { want, have: process.versions.node, command: `nvm install ${want} && nvm use ${want}` } } : {} };
|
|
25501
|
-
}
|
|
25502
|
-
function installRetry(step, output) {
|
|
25503
|
-
const pm = step.command === "corepack" || step.command === "npx" ? step.args.find((a) => /^(npm|pnpm|yarn|bun)(@|$)/.test(a))?.split("@")[0] : step.command;
|
|
25504
|
-
const tail = step.command === "corepack" ? step.args.slice(1) : step.command === "npx" ? step.args.slice(2) : step.args;
|
|
25505
|
-
const pinned = step.command === "corepack" || step.command === "npx" ? step.args.find((a) => /^(npm|pnpm|yarn|bun)(@|$)/.test(a)) : pm;
|
|
25506
|
-
if (pm === "pnpm" && /ERR_PNPM_(OUTDATED_LOCKFILE|LOCKFILE_CONFIG_MISMATCH|LOCKFILE_MISSING_DEPENDENCY)|frozen.lockfile|specifiers in the lockfile/i.test(output))
|
|
25507
|
-
return { why: "The lockfile is behind package.json, so a frozen install stops", step: { ...step, args: [...step.args, "--no-frozen-lockfile"] } };
|
|
25508
|
-
if (pm === "yarn" && /YN0028|lockfile would have been modified|--frozen-lockfile/i.test(output))
|
|
25509
|
-
return { why: "The lockfile is behind package.json, so a frozen install stops", step: { ...step, args: [...step.args, "--no-immutable"] } };
|
|
25510
|
-
if (pm === "pnpm" && /ERR_PNPM_IGNORED_BUILDS/.test(output) && !step.args.some((a) => a.startsWith("--config.dangerously-allow-all-builds")))
|
|
25511
|
-
return { why: "pnpm skipped the dependencies' build scripts", step: { ...step, args: [...step.args, "--config.dangerously-allow-all-builds=true"] } };
|
|
25512
|
-
if (pm === "bun" && step.command === "corepack")
|
|
25513
|
-
return { why: "corepack cannot fetch bun", step: { ...step, command: "npx", args: ["--yes", pinned, ...tail] } };
|
|
25514
|
-
if (pm === "npm" && /EBADENGINE|notsup|Unsupported engine/i.test(output) && !step.args.includes("--engine-strict=false"))
|
|
25515
|
-
return { why: "The project's engines field does not allow this Node version", step: { ...step, args: [...step.args, "--engine-strict=false"] } };
|
|
25516
|
-
}
|
|
25517
|
-
async function corepackShims(cwd, steps) {
|
|
25518
|
-
const pm = packageManager(cwd).name;
|
|
25519
|
-
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));
|
|
25520
|
-
if (!managers.length || !steps.length || !has("corepack")) return;
|
|
25521
|
-
const dir = join51(cwd, ".agenttwin", "bin");
|
|
25522
|
-
const ok3 = await new Promise((resolve18) => {
|
|
25523
|
-
const c = spawn9("corepack", ["enable", "--install-directory", dir, ...managers], { stdio: "ignore" });
|
|
25524
|
-
c.once("error", () => resolve18(false));
|
|
25525
|
-
c.once("exit", (code) => resolve18(code === 0));
|
|
25526
|
-
});
|
|
25527
|
-
return ok3 ? dir : void 0;
|
|
25528
|
-
}
|
|
25529
|
-
async function runSetup(cwd, opts) {
|
|
25530
|
-
const plan = opts.plan ?? planSetup(cwd, { ...opts.appDir !== void 0 ? { appDir: opts.appDir } : {}, ...opts.only ? { only: opts.only } : {} });
|
|
25531
|
-
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}`);
|
|
25532
|
-
if (!plan.steps.length) return true;
|
|
25533
|
-
opts.log(` Before the app can start: ${plan.steps.map((s) => `${show(s)} (${s.why})`).join(", then ")}.`);
|
|
25534
|
-
const answer = (await opts.ask({ id: "setup", text: `Run ${plan.steps.length === 1 ? "it" : "them"} now? (Y/n)`, default: "y" })).trim().toLowerCase();
|
|
25535
|
-
if (answer.startsWith("n")) {
|
|
25536
|
-
opts.log(` Skipped. Run ${plan.steps.map(show).join(" && ")} yourself, then npx agenttwin again.`);
|
|
25537
|
-
return false;
|
|
25538
|
-
}
|
|
25539
|
-
const shims = await corepackShims(cwd, plan.steps);
|
|
25540
|
-
const exec11 = (step) => new Promise((resolve18) => {
|
|
25541
|
-
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 ?? ""}` } : {} } });
|
|
25542
|
-
let tail = "";
|
|
25543
|
-
const keep = (c) => {
|
|
25544
|
-
tail = (tail + c.toString()).slice(-4e3);
|
|
25545
|
-
};
|
|
25546
|
-
child.stdout.on("data", keep);
|
|
25547
|
-
child.stderr.on("data", keep);
|
|
25548
|
-
child.once("error", (e) => {
|
|
25549
|
-
tail += String(e);
|
|
25550
|
-
resolve18({ code: 1, tail });
|
|
25551
|
-
});
|
|
25552
|
-
child.once("exit", (c) => resolve18({ code: c ?? 1, tail }));
|
|
25553
|
-
});
|
|
25554
|
-
for (const step of plan.steps) {
|
|
25555
|
-
opts.log(` Running ${show(step)}\u2026`);
|
|
25556
|
-
let { code, tail } = await exec11(step);
|
|
25557
|
-
for (let current2 = step, tries = 0; code !== 0 && step.id === "install" && tries < 3; tries++) {
|
|
25558
|
-
const retry = installRetry(current2, tail);
|
|
25559
|
-
if (!retry) break;
|
|
25560
|
-
opts.log(` ${retry.why}; running ${show(retry.step)}\u2026`);
|
|
25561
|
-
current2 = retry.step;
|
|
25562
|
-
({ code, tail } = await exec11(retry.step));
|
|
25563
|
-
}
|
|
25564
|
-
if (code !== 0 && step.fallback) {
|
|
25565
|
-
const next = { ...step, ...step.fallback, fallback: void 0 };
|
|
25566
|
-
opts.log(` ${show(step)} failed; running ${show(next)}\u2026`);
|
|
25567
|
-
({ code, tail } = await exec11(next));
|
|
25568
|
-
}
|
|
25569
|
-
if (code !== 0) {
|
|
25570
|
-
opts.log(tail.split("\n").filter(Boolean).slice(-6).map((l) => " " + l.slice(0, 200)).join("\n"));
|
|
25571
|
-
opts.log(` ${show(step)} failed (exit ${code}). The run goes on; if the app cannot start, fix that first.`);
|
|
25572
|
-
return false;
|
|
25573
|
-
}
|
|
25574
|
-
}
|
|
25575
|
-
opts.log(" Setup done.");
|
|
25576
|
-
return true;
|
|
25577
|
-
}
|
|
25578
|
-
var readJson2, has, show;
|
|
25579
|
-
var init_setup = __esm({
|
|
25580
|
-
"src/flow/setup.ts"() {
|
|
25581
|
-
"use strict";
|
|
25582
|
-
readJson2 = (file) => {
|
|
25583
|
-
try {
|
|
25584
|
-
return JSON.parse(readFileSync12(file, "utf8"));
|
|
25585
|
-
} catch {
|
|
25586
|
-
return void 0;
|
|
25587
|
-
}
|
|
25588
|
-
};
|
|
25589
|
-
has = (cmd) => spawnSync3(process.platform === "win32" ? "where" : "which", [cmd], { stdio: "ignore" }).status === 0;
|
|
25590
|
-
show = (s) => [posix6.basename(s.command), ...s.args].join(" ");
|
|
25591
|
-
}
|
|
25592
|
-
});
|
|
25593
|
-
|
|
25594
25780
|
// src/flow/gap-sink.ts
|
|
25595
25781
|
import { createServer as createHttpServer } from "http";
|
|
25596
25782
|
import { createServer as createTcpServer } from "net";
|
|
@@ -25775,15 +25961,15 @@ async function startS3Engine(options = {}) {
|
|
|
25775
25961
|
const objects = ensureBucket(bucket) ?? store.get(bucket);
|
|
25776
25962
|
if (!objects) return error(res, 404, "NoSuchBucket", "The specified bucket does not exist", bucket);
|
|
25777
25963
|
if (method === "GET" && !url2.searchParams.has("uploads")) {
|
|
25778
|
-
const prefix = url2.searchParams.get("prefix") ?? "",
|
|
25964
|
+
const prefix = url2.searchParams.get("prefix") ?? "", delimiter4 = url2.searchParams.get("delimiter");
|
|
25779
25965
|
const max = Math.min(Number(url2.searchParams.get("max-keys") ?? 1e3) || 1e3, 1e3);
|
|
25780
25966
|
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") ?? "";
|
|
25781
25967
|
let keys = [...objects.keys()].filter((k) => k.startsWith(prefix) && k > after).sort();
|
|
25782
25968
|
const prefixes = /* @__PURE__ */ new Set();
|
|
25783
|
-
if (
|
|
25784
|
-
const rest = k.slice(prefix.length), i = rest.indexOf(
|
|
25969
|
+
if (delimiter4) keys = keys.filter((k) => {
|
|
25970
|
+
const rest = k.slice(prefix.length), i = rest.indexOf(delimiter4);
|
|
25785
25971
|
if (i < 0) return true;
|
|
25786
|
-
prefixes.add(prefix + rest.slice(0, i +
|
|
25972
|
+
prefixes.add(prefix + rest.slice(0, i + delimiter4.length));
|
|
25787
25973
|
return false;
|
|
25788
25974
|
});
|
|
25789
25975
|
const page2 = keys.slice(0, max), truncated = keys.length > max;
|
|
@@ -28737,6 +28923,14 @@ async function runOneCommand(opts) {
|
|
|
28737
28923
|
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.`));
|
|
28738
28924
|
clean = await track(void 0);
|
|
28739
28925
|
}
|
|
28926
|
+
const triedInput = /* @__PURE__ */ new Set();
|
|
28927
|
+
for (let round = 0; round < 2 && clean.status === "error" && !clean.blockedCalls.length; round++) {
|
|
28928
|
+
const added = settleInput(prepared.scenario.input, clean.stderr, triedInput);
|
|
28929
|
+
if (!added.length) break;
|
|
28930
|
+
await writeFile26(prepared.scenarioPath, JSON.stringify(prepared.scenario, null, 2) + "\n", { mode: 384 });
|
|
28931
|
+
log(dim(` The route asked for ${added.join(", ")}; added test values to the input, rerunning.`));
|
|
28932
|
+
clean = await track(void 0);
|
|
28933
|
+
}
|
|
28740
28934
|
for (let round = 0; round < 3 && clean.blockedCalls.length; round++) {
|
|
28741
28935
|
let learnedTcp = false;
|
|
28742
28936
|
for (const b of clean.blockedCalls.filter((b2) => b2.kind === "socket" && b2.port)) {
|
|
@@ -29235,6 +29429,7 @@ var init_one_command = __esm({
|
|
|
29235
29429
|
init_kafka_diagnostics();
|
|
29236
29430
|
init_kafka();
|
|
29237
29431
|
init_offline();
|
|
29432
|
+
init_input_fields();
|
|
29238
29433
|
init_http_world();
|
|
29239
29434
|
init_local();
|
|
29240
29435
|
init_seed();
|